在使用 Neovim 打开某个文件时,我希望 Neovim 自动把当前目录切换到该文件所在的项目根目录。 其实,能实现这一功能的有不少的插件,我最早使用的是 vim-rooter,但是后来因为切换到了 Neovim, 因此使用 Lua 重写了该功能,这个功能早期是 SpaceVim 的内置的, 在 SpaceVim 项目停止维护后独立成单独的插件:rooter.nvim。
安装 rooter.nvim
可以使用任意插件管理器进行安装,比如 nvim-plug
require('plug').add({
{
'wsdjeg/rooter.nvim',
config = function()
require('rooter').setup({})
end,
},
})
插件配置
以下是默认的配置:
require('rooter').setup({
root_patterns = { '.git/' },
outermost = true,
enable_cache = true,
project_non_root = '', -- this can be '', 'home' or 'current'
enable_logger = true, -- enable runtime log via logger.nvim
})
project_non_root
: 配置打开非项目文件时的行为outermost
: 若设为true
,那么通过root_patterns
检索到的多个目录时,取最外层目录。
Telescope 拓展
rooter.nvim 自带 telescope.nvim 拓展,可以使用 :Telescope project
列出过往打开过的项目。
插件运行日志
在插件运行过程中产生的日志信息,可以使用 logger.nvim 进行查看。 如果有这一需求,那么在安装 rooter.nvim 时,需要添加相应的依赖插件。
require('plug').add({
{
'wsdjeg/rooter.nvim',
config = function()
require('rooter').setup({})
end,
depends = {
{
'wsdjeg/logger.nvim',
},
},
},
})
设置 callback 函数
通过 reg_callback
可以设置 callback 函数,该函数会在项目切换时被调用。
local function update_ctags_option()
local project_root = vim.fn.getcwd()
local dir = require('util').unify_path(require('tags').cache_dir)
.. require('util').path_to_fname(project_root)
table.insert(tags, dir .. '/tags')
vim.o.tags = table.concat(tags, ',')
end
require('rooter').reg_callback(update_gtags_option)