You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Neovim配置自定义LSP时vim.fs.root()调用报错,如何正确使用?

问题

尝试为lspconfig未收录的Cue语言配置语言服务器,仅略懂Lua。参考Neovim文档想用vim.fs.root()查找Git仓库根目录,但在vim.lsp.start()里调用vim.fs.root(ev.buf, '.git')时报错:attempt to call field 'root' (a nil value)。

配置代码:

local augroup_foo = vim.api.nvim_create_augroup('foo', { clear = true })
vim.api.nvim_create_autocmd({ 'FileType' }, {
    group = augroup_foo,
    pattern = { "cue" },
    callback = function(ev)
        vim.lsp.start({
            name = "cuepls",
            cmd = { "cuepls" },
            root_dir = vim.fs.root(ev.buf, '.git'), <--- 此处调用报错
        })
    end,
})

完整错误信息:

Error detected while processing BufNewFile Autocommands for "": Error executing lua callback: ...brew/Cellar/neovim/0.9.1/share/nvim/runtime/filetype.lua:21: Error executing lua: ...brew/Cellar/neovim/0.9.1/share/nvim/runtime/filetype.lua:22: BufNewFile Autocommands for ""..FileType Autocommands for "cue": Vim(append):Error executing lua callback: /Users/me/.config/nvim/lua/me/lsp.lua:98: attempt to call field 'root' (a nil value)

解决方法
  • 报错原因:你使用的Neovim版本是0.9.1,vim.fs.root()是Neovim 0.10及以上版本才新增的API,0.9.x版本没有这个函数,所以会提示字段为nil。
  • 0.9.x版本替代方案:用vim.fs.find()实现相同的根目录查找逻辑,从当前文件目录向上搜索.git目录,取找到的第一个结果的父目录作为根目录。
  • 修正后的配置代码:
local augroup_foo = vim.api.nvim_create_augroup('foo', { clear = true })
vim.api.nvim_create_autocmd({ 'FileType' }, {
    group = augroup_foo,
    pattern = { "cue" },
    callback = function(ev)
        -- 获取当前缓冲区对应的文件路径
        local buf_path = vim.api.nvim_buf_get_name(ev.buf)
        -- 向上查找.git目录,找到第一个就停止搜索
        local git_root = vim.fs.find('.git', { upward = true, path = vim.fs.dirname(buf_path) })[1]
        -- 确定根目录:找到.git就取其父目录,否则用当前文件所在目录
        local root_dir = git_root and vim.fs.dirname(git_root) or vim.fs.dirname(buf_path)

        vim.lsp.start({
            name = "cuepls",
            cmd = { "cuepls" },
            root_dir = root_dir,
        })
    end,
})
  • 版本升级后的用法:如果之后升级到Neovim 0.10+,可以直接用vim.fs.root(),但注意它的第一个参数是文件路径而非缓冲区编号,需要先把ev.buf转换为路径:
root_dir = vim.fs.root(vim.api.nvim_buf_get_name(ev.buf), '.git'),

内容的提问来源于stack exchange,提问作者meh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:37:26