reflow.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. local core = require "core"
  2. local config = require "core.config"
  3. local command = require "core.command"
  4. local keymap = require "core.keymap"
  5. local function wordwrap_text(text, limit)
  6. local t = {}
  7. local n = 0
  8. for word in text:gmatch("%S+") do
  9. if n + #word > limit then
  10. table.insert(t, "\n")
  11. n = 0
  12. elseif #t > 0 then
  13. table.insert(t, " ")
  14. end
  15. table.insert(t, word)
  16. n = n + #word + 1
  17. end
  18. return table.concat(t)
  19. end
  20. command.add("core.docview", {
  21. ["reflow:reflow"] = function()
  22. local doc = core.active_view.doc
  23. doc:replace(function(text)
  24. local prefix_set = "[^%w\n%[%](){}`'\"]*"
  25. -- get line prefix and trailing whitespace
  26. local prefix1 = text:match("^\n*" .. prefix_set)
  27. local prefix2 = text:match("\n(" .. prefix_set .. ")", #prefix1+1)
  28. local trailing = text:match("%s*$")
  29. if not prefix2 or prefix2 == "" then
  30. prefix2 = prefix1
  31. end
  32. -- strip all line prefixes and trailing whitespace
  33. text = text:sub(#prefix1+1, -#trailing - 1):gsub("\n" .. prefix_set, "\n")
  34. -- split into blocks, wordwrap and join
  35. local line_limit = config.line_limit - #prefix1
  36. local blocks = {}
  37. text = text:gsub("\n\n", "\0")
  38. for block in text:gmatch("%Z+") do
  39. table.insert(blocks, wordwrap_text(block, line_limit))
  40. end
  41. text = table.concat(blocks, "\n\n")
  42. -- add prefix to start of lines
  43. text = prefix1 .. text:gsub("\n", "\n" .. prefix2) .. trailing
  44. return text
  45. end)
  46. end,
  47. })
  48. keymap.add {
  49. ["ctrl+shift+q"] = "reflow:reflow"
  50. }