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

如何使用Neovim Lua API获取当前缓冲区的文件完整路径

Neovim Lua获取当前缓冲区文件路径及telescope自定义函数实现

核心API说明

你可以使用vim.api.nvim_buf_get_name(bufnr)获取指定缓冲区对应的文件完整绝对路径,传入你已经拿到的当前缓冲区编号即可。
基础用法示例:

-- 获取当前缓冲区编号
local current_buf = vim.api.nvim_get_current_buf()
-- 获取缓冲区对应文件的完整绝对路径
local current_file_path = vim.api.nvim_buf_get_name(current_buf)

如果需要转换为其他格式的路径,可以配合vim.fn.fnamemodify使用:

  • 获取相对于当前工作目录的相对路径:vim.fn.fnamemodify(current_file_path, ":.")
  • 获取纯文件名(不带路径):vim.fn.fnamemodify(current_file_path, ":t")
  • 获取文件所在的目录路径:vim.fn.fnamemodify(current_file_path, ":h")

注意:如果当前是未保存的无名缓冲区,vim.api.nvim_buf_get_name会返回空字符串,使用前建议做非空判断避免逻辑报错。

配合telescope.nvim的自定义函数示例

以下是可直接使用的示例函数,实现调用telescope搜索当前文件所在目录下的所有文件的功能:

-- 自定义telescope功能:搜索当前文件所在目录下的文件
local function telescope_find_current_dir()
  local current_buf = vim.api.nvim_get_current_buf()
  local current_file = vim.api.nvim_buf_get_name(current_buf)
  -- 处理无名缓冲区的情况
  if current_file == "" then
    vim.notify("当前缓冲区无关联文件", vim.log.levels.WARN)
    return
  end
  local current_dir = vim.fn.fnamemodify(current_file, ":h")
  -- 调用telescope内置接口
  require("telescope.builtin").find_files({
    prompt_title = "当前目录文件搜索",
    cwd = current_dir,
  })
end
-- 绑定快捷键(可自行修改触发按键)
vim.keymap.set("n", "<leader>fcd", telescope_find_current_dir, { desc = "Telescope搜索当前文件目录" })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:09:02