mdtree.lua 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. VERSION = "1.0.0"
  2. local micro = import("micro")
  3. local buffer = import("micro/buffer")
  4. local config = import("micro/config")
  5. local action = import("micro/action")
  6. function init()
  7. config.MakeCommand("mdtree", mdtree, config.OptionComplete)
  8. config.AddRuntimeFile("mdtree", config.RTPlugin, "mdtree.lua")
  9. config.AddRuntimeFile("mdtree", config.RTPlugin, "bar.lua")
  10. config.AddRuntimeFile("mdtree", config.RTSyntax, "syntax.yaml")
  11. end
  12. headings = {}
  13. function mdtree(buffer_pane)
  14. local buf = buffer_pane.Buf
  15. -- Make sure that you don't create new sidebar when one exists
  16. if SideBar:IsOpen()
  17. then
  18. SideBar:Close()
  19. else
  20. -- Prevent opening bar for non-markdown files
  21. -- NOTE: must be here after check for bar existence
  22. -- because otherwise bar will be checked if it is md file
  23. if buf:FileType() ~= "markdown"
  24. then
  25. micro.InfoBar():Error("File isn't markdown")
  26. return
  27. end
  28. SideBar:Create(buffer_pane)
  29. SideBar.callbacks:Update()
  30. end
  31. end
  32. -------------------------
  33. -- SideBar callbacks
  34. -------------------------
  35. function SideBar.callbacks:Update()
  36. SideBar:Clear()
  37. parse_headings(SideBar.owner.Buf)
  38. ident_headings()
  39. print_headings()
  40. end
  41. function SideBar.callbacks:Jump(y)
  42. SideBar.owner.Cursor:GotoLoc({
  43. X = 0,
  44. Y = headings[y + 1].position
  45. })
  46. SideBar.owner:Center()
  47. -- TODO: Make main file active
  48. -- SideBar.buffer_pane:SetActive(false)
  49. -- SideBar.owner:SetActive(true)
  50. end
  51. -------------------------
  52. -- Parsing functions
  53. -------------------------
  54. function is_heading(line)
  55. local head, tail = string.find(line, "#+ .*")
  56. if head ~= nil and tail ~= nil
  57. then
  58. return true
  59. else
  60. return false
  61. end
  62. end
  63. function parse_headings(buf)
  64. headings = {}
  65. for i = 0, buf:LinesNum()
  66. do
  67. local line = buf:Line(i)
  68. if is_heading(line)
  69. then
  70. local heading = {text=line, position=i }
  71. table.insert(headings, heading)
  72. end
  73. end
  74. end
  75. function ident_headings()
  76. for i, heading in ipairs(headings) do
  77. local head, tail = string.find(heading.text, "^#+")
  78. local header_level = tail - head
  79. heading.text = string.rep(" ", header_level) .. heading.text
  80. end
  81. end
  82. function print_headings()
  83. for i, heading in ipairs(headings) do
  84. --Don't add \n in the end of the tree
  85. if i == #headings
  86. then
  87. SideBar:Append(heading.text)
  88. else
  89. SideBar:Append(heading.text .. "\n")
  90. end
  91. end
  92. end