Scite 排序选择

lua-users home
wiki

下面的函数可以将选中的文本按字母顺序或字母逆序排序。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

来自 StringRecipes、适用于 SciTE 1.74 之前的版本(Lua 5.0.x)的旧 lines() 函数如下

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

WalterCruz, KeinHongMan


RecentChanges · preferences
编辑 · 历史
最后编辑于 2007年11月18日 上午3:42 GMT (差异)