Scite 刪除空白列

lua-users home
wiki

刪除文件中的所有空白列

下列腳本使用 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

為簡化,游標在處理後設定在文件左上角。


RecentChanges · 偏好設定
編輯 · 歷程
最後編輯於 2008 年 3 月 26 日上午 3:11 GMT (差異)