Scite 排序選取 |
|
lines()
函式已更新,可以在 Lua 5.1 或 SciTE 1.74+ 運作。新的 lines()
函式允許在選取區塊結尾不存在換行符號。排序常式如果存在也會在排序後復原最後一個換行符號。如果使用 \n
換行符號,那麼在執行腳本後檔案大小不應該會變更。盡情享用!
-- Sort a selected text function lines(str) local t = {} local i, lstr = 1, #str while i <= lstr do local x, y = string.find(str, "\r?\n", i) if x then t[#t + 1] = string.sub(str, i, x - 1) else break end i = y + 1 end if i <= lstr then t[#t + 1] = string.sub(str, i) end return t end function sort_text() local sel = editor:GetSelText() if #sel == 0 then return end local eol = string.match(sel, "\n$") local buf = lines(sel) --table.foreach(buf, print) --used for debugging table.sort(buf) local out = table.concat(buf, "\n") if eol then out = out.."\n" end editor:ReplaceSel(out) end function sort_text_reverse() local sel = editor:GetSelText() if #sel == 0 then return end local eol = string.match(sel, "\n$") local buf = lines(sel) --table.foreach(buf, print) --used for debugging table.sort(buf, function(a, b) return a > b end) local out = table.concat(buf, "\n") if eol then out = out.."\n" end editor:ReplaceSel(out) end
如果要忽略空行,或者要排序的選取範圍中從來沒有空行,那麼以下的 lines()
函式會更簡單。
function lines(str) local t = {} for ln in string.gmatch(str, "[^\r\n]+") do t[#t + 1] = ln end return t end
舊版的 lines()
函式,從 StringRecipes,適合先前的 SciTE 1.74 (Lua 5.0.x) 版本,如下。
function lines(str) local t = {n = 0} local function helper(line) table.insert(t, line) end helper((string.gsub(str, "(.-)\r?\n", helper))) return t end