trimwhitespace.lua 669 B

123456789101112131415161718192021222324252627282930
  1. local core = require "core"
  2. local command = require "core.command"
  3. local Doc = require "core.doc"
  4. local function trim_trailing_whitespace(doc)
  5. for i = 1, #doc.lines do
  6. local old_text = doc:get_text(i, 1, i, math.huge)
  7. local new_text = old_text:gsub("%s*$", "")
  8. if old_text ~= new_text then
  9. doc:insert(i, 1, new_text)
  10. doc:remove(i, #new_text + 1, i, math.huge)
  11. end
  12. end
  13. end
  14. command.add("core.docview", {
  15. ["trim-whitespace:trim-trailing-whitespace"] = function()
  16. trim_trailing_whitespace(self.active_view.doc)
  17. end,
  18. })
  19. local save = Doc.save
  20. Doc.save = function(self, ...)
  21. trim_trailing_whitespace(self)
  22. save(self, ...)
  23. end