配置 NeoVim 的代码折叠

配置 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({ ... }) 内部)中,添加以下代码块:

lua 复制代码
-- ... (其他插件,例如 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 复制代码
-- 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 折叠命令来操作代码块了:

  • <math xmlns="http://www.w3.org/1998/Math/MathML"> z a \mathbf{za} </math>za:切换(打开/关闭)光标下的折叠。
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> z M \mathbf{zM} </math>zM:关闭文件中所有折叠。
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> z R \mathbf{zR} </math>zR:打开文件中所有折叠。
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> z i \mathbf{zi} </math>zi:切换折叠功能 ('foldenable') 的启用/禁用状态。
相关推荐
千寻技术帮6 小时前
10399_基于SpringBoot的智慧养老院管理系统
java·spring boot·后端·源码·安装·代码
飞升不如收破烂~7 小时前
# Spring Boot 跨域请求未到达后端问题排查记录
java·spring boot·后端
短剑重铸之日7 小时前
《RocketMQ研读》面试篇
java·后端·面试·职场和发展·rocketmq
changzehai7 小时前
Rust + VSCode + probe-rs搭建stm32-rs嵌入式开发调试环境
vscode·后端·stm32·rust·嵌入式·probe-rs
终端域名7 小时前
如何选择有利于品牌宣传的网站域名
java·后端·struts·数字货币域名·网站域名
拽着尾巴的鱼儿7 小时前
Spring:定时任务@Scheduled cron 的实现原理
java·后端·spring
郑州光合科技余经理8 小时前
源码部署同城O2O系统:中台架构开发指南
java·开发语言·后端·架构·系统架构·uni-app·php
Marktowin8 小时前
访问控制权限模型分析梳理
后端
Object~8 小时前
7.Go语言中的slice
开发语言·后端·golang
逍遥德8 小时前
函数式编程 Java Lambda Stream及其实现类常用函数
java·后端·spring