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

Neovim多文件打开时光标位置恢复问题求助

Neovim多文件打开时光标位置全恢复方案

我从Vim迁移至Neovim,此前在Vim中通过以下autocmd实现打开文件时恢复上次编辑的光标位置:

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
    \ if line("'\&quot;&quot;") > 0 && line("'\&quot;&quot;") <= line("$") |
    \   exe "normal! g`\&quot;" |
    \ endif

搭配配置:

set viminfo^=%

单文件打开时Neovim能正常恢复光标,但**多文件同时打开(nvim <file> <file>)**时,只有第一个文件能恢复光标位置,其他文件无法生效。我试过以下方法都没解决问题:

  • Stack Overflow上的同类autocmd
  • persisted.nvim插件
  • vim-lastplace插件

通过调试autocmd发现,Neovim会为所有打开的文件触发BufReadPost事件,且能正确获取每个文件的光标位置:

vim.api.nvim_create_autocmd("BufReadPost", {
  callback = function(args)
    local mark = vim.api.nvim_buf_get_mark(args.buf, '&quot;')
    local line = mark[1]
    local col = mark[2]
    local line_count = vim.api.nvim_buf_line_count(args.buf)
    vim.print("Line: " .. line .. " / Column: " .. col .. " / Lines: " .. line_count)
  end
})

打开两个文件(nvim foo bar)时输出如下:

[foo] Line: 23 / Column: 2 / Lines: 100
[bar] Line: 2 / Column: 0 / Lines: 12

问题原因

原来的BufReadPost事件触发时,后续打开的文件处于后台缓冲区状态,并未激活为当前窗口,normal! g"`这类命令只会作用于当前活动窗口,导致后台缓冲区的光标恢复操作无效。

解决方法

改用BufWinEnter事件(窗口激活对应缓冲区时触发),并使用Neovim API直接设置光标位置,确保每个文件在显示到窗口时都能恢复光标:

vim.api.nvim_create_autocmd("BufWinEnter", {
  pattern = "*",
  callback = function(args)
    local mark = vim.api.nvim_buf_get_mark(args.buf, '"')
    local line = mark[1]
    local col = mark[2]
    local line_count = vim.api.nvim_buf_line_count(args.buf)
    if line > 0 and line <= line_count then
      vim.api.nvim_win_set_cursor(0, {line, col})
    end
  end,
})

同时确保Neovim的viminfo配置正确,用来保存文件的光标标记:

vim.opt.viminfo:append("%")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:05:14