Skip to content

Commit d8963a2

Browse files
committed
feat: add folding module with custom foldexpr function
1 parent 706439a commit d8963a2

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

lua/astroui/folding.lua

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
-- AstroNvim Folding Utilities
2+
--
3+
-- Helper functions for configuring folding in Neovim
4+
--
5+
-- This module can be loaded with `local astro = require "astroui.folding"`
6+
--
7+
-- copyright 2024
8+
-- license GNU General Public License v3.0
9+
10+
local M = {}
11+
12+
local lsp_bufs = {}
13+
14+
--- A fold expression for doing LSP and Treesitter based folding
15+
---@param lnum? integer the current line number
16+
---@return string the calculated fold level
17+
function M.foldexpr(lnum)
18+
local buf = vim.api.nvim_get_current_buf()
19+
if not require("astrocore.buffer").is_valid(buf) then return "0" end
20+
if lsp_bufs[buf] then return vim.lsp.foldexpr(lnum) end
21+
local filetype = vim.bo[buf].filetype
22+
if filetype == "" or filetype:find "dashboard" then return "0" end
23+
return vim.treesitter.get_parser(buf, nil, { error = false }) and vim.treesitter.foldexpr(lnum) or "0"
24+
end
25+
26+
function M.setup()
27+
local augroup = vim.api.nvim_create_augroup("astroui_foldexpr", { clear = true })
28+
vim.api.nvim_create_autocmd("LspAttach", {
29+
desc = "Monitor attached LSP clients with fold providers",
30+
group = augroup,
31+
callback = function(args)
32+
local client = assert(vim.lsp.get_client_by_id(args.data.client_id))
33+
if client.supports_method "textDocument/foldingRange" then lsp_bufs[args.buf] = true end
34+
end,
35+
})
36+
vim.api.nvim_create_autocmd("LspDetach", {
37+
group = augroup,
38+
desc = "Safely remove LSP folding providers when language servers detach",
39+
callback = function(args)
40+
if not vim.api.nvim_buf_is_valid(args.buf) then return end
41+
for _, client in pairs(vim.lsp.get_clients { bufnr = args.buf }) do
42+
if client.id ~= args.data.client_id and client.supports_method "textDocument/foldingRange" then return end
43+
end
44+
lsp_bufs[args.buf] = nil
45+
end,
46+
})
47+
end
48+
49+
return M

lua/astroui/init.lua

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ function M.setup(opts)
3434
})
3535

3636
require("astroui.lazygit").setup()
37+
38+
-- TODO: remove check when dropping support for Neovim v0.10
39+
if vim.fn.has "nvim-0.11" == 1 then require("astroui.folding").setup() end
3740
end
3841

3942
--- Get highlight properties for a given highlight name

0 commit comments

Comments
 (0)