forked from dail8859/LuaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomizeLines.lua
More file actions
Latest commit
97 lines (80 loc) · 2.56 KB
/
Copy pathRandomizeLines.lua
File metadata and controls
97 lines (80 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
---------------------------------------------------------------
-- randomizelines.lua for Notepad++ LuaScript plugin
--
-- This script will randomize the lines within a document.
--
-- Activate it on all text in the editor by running without a
-- selection, or select a group of lines to randomize only
-- the selected lines.
---------------------------------------------------------------
-- helper function to split lines
localfunctionsplit(str, sep)
localresult= {}
localregex= ("([^%s]+)"):format(sep)
foreachinstr:gmatch(regex) do
table.insert(result, each)
end
returnresult
end
-- helper function to shuffle a table
localfunctionshuffle(t)
math.randomseed( os.time() )
localrand=math.random
localiterations=#t
localj
fori=iterations, 2, -1do
j=rand(i)
t[i], t[j] =t[j], t[i]
end
returnt
end
--------------------------------------------------------------------
npp.AddShortcut("Randomize Lines", "", function()
localresult--placeholder to store the processed text for return to editor
localSelectionStart, SelectionEnd--placeholder to store selection points
-- Preserve Undo Capability
editor:BeginUndoAction()
-- Get any selected text
localseltext=editor:GetSelText()
localseltextlen=#seltext
-- read selected text or entire document
localrawtext
ifseltextlen>=1then
rawtext=seltext
--read the selection points for restore after operation
SelectionStart=editor.SelectionStart
SelectionEnd=editor.SelectionEnd
else
rawtext=editor:GetText()
end
-- Preserve EOL Mode when we send back the reordered lines
localEOLchar
ifeditor.EOLMode==0then
EOLchar="\r\n"
elseifeditor.EOLMode==1then
EOLchar="\r"
elseifeditor.EOLMode==2then
EOLchar="\n"
end
--------------------
-- process the text
--------------------
-- split the text into an array of lines
localrawtextlines=split(rawtext,EOLchar);
-- randomize the lines
rawtextlines=shuffle(rawtextlines)
-- output to result var
result=table.concat(rawtextlines, EOLchar)
--------------------
-- end processing
--------------------
-- replace selected text or entire document
ifseltextlen>=1then
editor:ReplaceSel(result)
-- restore selection
editor:SetSel(SelectionStart, SelectionEnd)
else
editor:SetText(result)
end
editor:EndUndoAction()
end)