配置 NeoVim 的代码折叠

13 阅读2分钟

配置 NeoVim 的代码折叠,最现代化且推荐的方式是使用 Tree-sitter 驱动的 表达式折叠 (foldmethod='expr')。这能提供最准确的语言感知型折叠(例如,根据函数体、类或代码块自动折叠)。

两步配置:

  1. 添加 nvim-treesitter 插件:它是实现准确折叠的基础。
  2. 设置折叠选项:在 options.lua 中开启并指定折叠方法。

步骤一:在 lua/plugins/init.lua 中添加 Tree-sitter

要将 nvim-treesitter 插件添加到你的 lazy.nvim 列表中,并配置它启用折叠功能。

请在 lua/plugins/init.lua 文件的插件列表(require("lazy").setup({ ... }) 内部)中,添加以下代码块:

-- ... (其他插件,例如 plenary.nvim 和 catppuccin 插件之间)

-- Tree-sitter:提供先进的语法解析,是实现精确折叠的基础
{
    "git@github.com:nvim-treesitter/nvim-treesitter.git",
    build = ":TSUpdate", -- 首次安装后运行此命令来下载解析器
    name = "treesitter",
    event = "BufReadPost",
    config = function()
        require("nvim-treesitter.configs").setup({
            -- 确保安装常用语言的解析器
            ensure_installed = { 
                "c", "lua", "vim", "vimdoc", "javascript", "typescript", 
                "html", "css", "json", "bash", "python" 
            }, 
            
            highlight = { enable = true }, -- 启用高亮(推荐)
            indent = { enable = true },    -- 启用智能缩进(推荐)
            folding = { enable = true },   -- **启用折叠**
        })
    end,
},

-- ...

步骤二:在 lua/core/options.lua 中配置折叠选项

在你的 lua/core/options.lua 文件中,添加以下配置来启用并指定使用 Tree-sitter 提供的折叠表达式。

在文件末尾或专门的配置区域添加以下几行:

-- lua/core/options.lua

-- ... (其他配置,如 opt.timeoutlen = 300)

-- == 折叠配置 (Folding) ==
opt.foldenable = true                  -- 启用折叠功能
opt.foldmethod = "expr"                -- 使用表达式进行折叠
opt.foldexpr = "nvim_treesitter#foldexpr()" -- 指定折叠表达式为 Tree-sitter 函数
opt.foldlevel = 99                     -- 默认打开所有折叠(推荐:文件打开时全部展开)
opt.foldcolumn = "1"                   -- 在左侧显示一列来表示折叠(可选,设为"0"则不显示)

步骤三:完成与使用

完成上述配置后,重新启动 NeoVim。你就可以使用标准的 Vim 折叠命令来操作代码块了:

  • za\mathbf{za}:切换(打开/关闭)光标下的折叠。
  • zM\mathbf{zM}:关闭文件中所有折叠。
  • zR\mathbf{zR}:打开文件中所有折叠。
  • zi\mathbf{zi}:切换折叠功能 ('foldenable') 的启用/禁用状态。