|
| 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 |
0 commit comments