【发布时间】:2016-12-05 23:07:07
【问题描述】:
如何在切换缓冲区时将光标位置保留在一行中,例如:bn?
Vim 记得我的光标在哪一行,但当我在缓冲区之间切换时,总是将光标移动到行首。
【问题讨论】:
标签: vim line text-cursor
如何在切换缓冲区时将光标位置保留在一行中,例如:bn?
Vim 记得我的光标在哪一行,但当我在缓冲区之间切换时,总是将光标移动到行首。
【问题讨论】:
标签: vim line text-cursor
我不确定为什么 Vim 会这样,但幸运的是,确切的位置存储在 '" 标记中(cp.:help 'quote)。
以下:autocmd 将尝试使用g` 命令将光标恢复到该位置:
:autocmd BufEnter * silent! normal! g`"
注意:您可以在g` 之后附加定位命令,如zz(将当前行定位在窗口中心)或zv(打开任何折叠)。
【讨论】:
zz 像这样autocmd BufEnter * silent! normal! g`"zz
怎么样
Vim cursor jumps to beginning of the line after buffer switch
TL;DR
:set nostartofline
对我来说 g`" 搞乱了我的快速修复位置。
【讨论】:
我的 ~/.vimrc 中有一个函数,可以在保存时将日期时间保存在文件顶部附近(如果文件顶部附近有“最后修改”字符串):
function! LastModified()
if &modified
let save_cursor = getpos(".")
let n = min([250, line("$")])
:silent keepjumps exe '1,' . n . 's/^\(.*L\)ast.modified.*:.*/\1ast modified: ' . strftime('%Y-%m-%d %H:%M:%S %z (PST)') . '/e'
call histdel('search', -1)
call setpos('.', save_cursor)
endif
endfun
autocmd BufWritePre * call LastModified()
## Ref [1], [2]
效果很好;但是,在垂直拆分中切换缓冲区时,我的光标正在跳线(未能保留行位置/光标位置)。
autocmd BufEnter * silent! normal! g`"
(建议在此线程的另一个答案中)没有效果,但是这个(参考 [3])解决了这个问题:
" Save current view settings on a per-window, per-buffer basis.
function! AutoSaveWinView()
if !exists("w:SavedBufView")
let w:SavedBufView = {}
endif
let w:SavedBufView[bufnr("%")] = winsaveview()
endfunction
" Restore current view settings.
function! AutoRestoreWinView()
let buf = bufnr("%")
if exists("w:SavedBufView") && has_key(w:SavedBufView, buf)
let v = winsaveview()
let atStartOfFile = v.lnum == 1 && v.col == 0
if atStartOfFile && !&diff
call winrestview(w:SavedBufView[buf])
endif
unlet w:SavedBufView[buf]
endif
endfunction
" When switching buffers, preserve window view.
if v:version >= 700
autocmd BufLeave * call AutoSaveWinView()
autocmd BufEnter * call AutoRestoreWinView()
endif
另外:为了更容易在任一拆分中跟踪编辑,在普通模式下按 zz 将当前行垂直居中(参考 [4])。
[1]https://docwhat.org/vim-preserve-your-cursor-and-window-state
[2]http://vim.wikia.com/wiki/Insert_current_date_or_time
[3]https://vim.fandom.com/wiki/Avoid_scrolling_when_switch_buffers
[4]https://vim.fandom.com/wiki/Make_search_results_appear_in_the_middle_of_the_screen
【讨论】: