add treesitter plugin to visibly divide sections
authorLukas Hägele <lukas.haegele93@web.de>
Sun, 11 Oct 2026 12:27:09 +0000 (14:27 +0200)
committerLukas Hägele <lukas.haegele93@web.de>
Sun, 11 Oct 2026 12:27:09 +0000 (14:27 +0200)
plugin/treesitter/section-divider.lua [new file with mode: 0644]

diff --git a/plugin/treesitter/section-divider.lua b/plugin/treesitter/section-divider.lua
new file mode 100644 (file)
index 0000000..c73be79
--- /dev/null
@@ -0,0 +1,51 @@
+-- namespace
+local ns_id = vim.api.nvim_create_namespace("section_divider")
+
+local function update_extmarks()
+  local winid = vim.api.nvim_get_current_win()
+  local bufnr = vim.api.nvim_get_current_buf()
+
+  local parser = vim.treesitter.get_parser(bufnr, "c")
+  if not parser then
+    vim.notify("currently only 'C' is supported", vim.log.levels.INFO)
+    return
+  end
+
+  -- delete old extmarks
+  vim.api.nvim_buf_clear_namespace(bufnr, ns_id, 0, -1)
+
+  -- parse tree
+  local tree = parser:parse()[1]
+  local root = tree:root()
+
+  local query = vim.treesitter.query.parse("c", "(comment) @comment")
+
+  -- get currently visible window area
+  local top_line = vim.fn.line("w0", winid) - 1
+  local bot_line = vim.fn.line("w$", winid)
+
+  -- iterate query within visible area
+  for id, node in query:iter_captures(root, bufnr, top_line, bot_line) do
+    local start_row, _, end_row, end_col = node:range()
+    local lines = vim.api.nvim_buf_get_lines(bufnr, start_row, start_row + 1, false)
+    local text = lines[1] and vim.trim(lines[1]) or ""
+
+    if vim.startswith(text, "///") then
+      local win_width = vim.api.nvim_win_get_width(winid)
+      local fill_count = math.max(0, win_width - end_col - 4)
+      vim.print("win_width: " ..win_width ..", end_col: " ..end_col ..", fill_count: " ..fill_count)
+      local divider = string.rep("-", fill_count)
+      pcall(vim.api.nvim_buf_set_extmark, bufnr, ns_id, end_row, 0, {
+        virt_text = {{divider, "Comment"}},
+        virt_text_pos = "eol",
+        hl_mode = "combine",
+      })
+    end
+  end
+end
+
+-- update extmarks after cursor movement
+vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI", "BufEnter" }, {
+  pattern = {"*.c", "*.h"},
+  callback = update_extmarks,
+})