Scite Delete Blank Lines

lua-users home
wiki

Delete all blank lines in a document

The following script uses Scintilla line and position functions to get all empty lines removed. Since the caret moves during processing, the display position will shift at the end of processing. The empty line test includes lines with whitespace.

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 explicitly blank lines with no whitespace are to be deleted only, the line test can be replaced with:

    if text == "\r\n" or text == "\n" then

A shorter version that processes the entire document text as a single Lua string is as follows:

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

The caret is set to the top left of the document after processing, for simplicity.


RecentChanges · preferences
edit · history
Last edited March 26, 2008 3:11 am GMT (diff)