Neovim:根据 Tree-sitter 使用 `foldmethod=syntax` 或 `foldmethod=expr` 折叠代码

问题描述 投票:0回答:1

我刚刚全新安装了LazyVim,但在根据我的喜好配置代码折叠时遇到了麻烦。

  • 对于我没有安装 nvim-treesitter 解析器的语言,我想使用

    :set foldmethod=syntax
    (想必 Neovim 已经知道如何在基础级别上解析这些语言)。

  • 另一方面,对于我安装并配置了 nvim-treesitter 解析器的语言,我想使用

    :set foldmethod=expr foldexpr=nvim_treesitter#foldexpr()

这样做的原因是,在这两种情况下,如果我使用相反的配置,那么代码折叠将根本不起作用。

我的想法是默认为

:set foldmethod=syntax
并使用 autocommand 在使用
nvim-treesitter
支持打开缓冲区时将其切换为 expr,但是我不知道如何实现这一点(我不知道什么)要侦听的事件以及如何检测是否为当前缓冲区加载了 nvim-treesitter 解析器)。也许还有其他方法可以实现这一点,通过直接配置 nvim-treesitter 来进行切换;我不知道。

有人有解决办法吗?

neovim code-folding treesitter
1个回答
0
投票

在 LazyVim 配置中的

lua/config/autocmds.lua
下,您可以添加:

vim.api.nvim_create_autocmd({ "FileType" }, {
  callback = function()
    if require("nvim-treesitter.parsers").has_parser() then
      vim.opt.foldmethod = "expr"
      vim.opt.foldexpr = "nvim_treesitter#foldexpr()"
    else
      vim.opt.foldmethod = "syntax"
    end
  end,
})

这遵循 LazyVim 的提示部分推荐的一般格式。

请注意,根据 nvim-treesitter 自述文件中的建议,您可能还想在其他地方设置:

set nofoldenable   " Disable folding at startup.

...虽然我发现没有必要,因为在我的 LazyVim 配置中文件打开时不会折叠。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.