nvim-treesitter
Neovim 0.5 版本引入了 Tree-sitter 这个现代化语法解析框架。。
Parsers
tree-sitter 的核心是 Parsers,即解析器。 Nvim 内置了 C、Lua、Markdown、VImscript 和 Vimdoc 这几个解析器,而其他需要自己手动安装。Nvim 会查找 $VIMRUNTIME/parser/{lang}.*
作为对应语言的解析器,也可以使用以下方式来加载:
同样我们可以将一个 Parser 注册到对应的文件类型:
一旦注册就可以使用提供查询等模块来使用了。
nvim-treesitter
Neovim 仅仅内置了 tree-sitter 解析框架,他需要手动安装解析器手动执行查询等,于是开源社区就有人编写了nvim-treesitter来作为 Nvim 中内置的tree-sitter 管理器。
他提供了自动安装语法解析器、自动实现语法高亮、折叠、缩进控制、文本对象等功能,以及更好用的 API 来让社区添加更多功能。
安装
推荐使用lazy插件管理工具:
Lua
{
"nvim-treesitter/nvim-treesitter",
build = ":TSUpdate",
config = function ()
local configs = require("nvim-treesitter.configs")
configs.setup({
ensure_installed = { "c", "lua", "vim", "vimdoc", "query", "elixir", "heex", "javascript", "html" },
sync_install = false,
highlight = { enable = true },
indent = { enable = true },
})
end
}
Note
可以在 ensure_installed 中控制要安装解析器的编程语言,nvim-treesitter 会自动帮助我们安装,当然也可以使用 :TSInstall <code>
来安装。注意这需要 tar、curl 和 libstdc++ 的支持。
功能模块
nvim-treesitter 内置了几个功能模块,并且他提供了 API 来允许引入第三方模块。
highlight(高亮)
Lua
-- 启用语法高亮
require'nvim-treesitter.configs'.setup {
highlight = {
enable = true,
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = false,
},
}
indent(缩进)
fold(折叠)
折叠比较特殊,首先需要启用:
或者在