Scite 删除空行 |
|
以下脚本使用 Scintilla 行和位置函数来删除所有空行。由于光标在处理过程中移动,因此处理结束时显示位置将发生偏移。空行测试包括包含空格的行。
function del_empty_lines() editor:BeginUndoAction() -- remember last caret line position local pre_l = editor:LineFromPosition(editor.CurrentPos) local ln = 0 while ln < editor.LineCount do local text = editor:GetLine(ln) if not text then break end -- empty last line without EOL if string.match(text, "^%s*\r?\n$") then local p = editor:PositionFromLine(ln) editor:GotoPos(p) editor:LineDelete() -- adjust caret position if necessary if ln < pre_l then pre_l = pre_l - 1 end else -- move on if no more empty lines at this line number ln = ln + 1 end end -- restore last caret line position local pre_p = editor:PositionFromLine(pre_l) editor:GotoPos(pre_p) editor:EndUndoAction() end
如果要删除的只是没有空格的显式空行,则可以将行测试替换为
if text == "\r\n" or text == "\n" then
以下是一个更短的版本,它将整个文档文本作为单个 Lua 字符串进行处理
function del_empty_lines() local txt = editor:GetText() if #txt == 0 then return end local chg, n = false while true do txt, n = string.gsub(txt, "(\r?\n)%s*\r?\n", "%1") if n == 0 then break end chg = true end if chg then editor:SetText(txt) editor:GotoPos(0) end end
为简单起见,处理后光标将设置到文档的左上角。