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
为了简单起见,处理完成后插入符被设置到文档的左上角。