Preserve cursor position when switching between buffers with :bn
Asked Answered
C

3

9

How do I preserve my cursor position within a line when switching buffers, with :bn for example?

Vim remembers which line my cursor was on, but always moves my cursor to the beginning of the line when I switch between buffers.

Catalogue answered 5/12, 2016 at 23:7 Comment(0)
K
7

I'm not sure why Vim behaves this way, but fortunately, the exact position is stored in the '" mark (cp. :help 'quote).

The following :autocmd will attempt to restore the cursor to that position, using the g` command:

:autocmd BufEnter * silent! normal! g`"

Note: You can append positioning commands like zz (which positions the current line in the center of the window) or zv (which opens any folds) after the g`.

Kelci answered 6/12, 2016 at 10:11 Comment(2)
Awesome. I added this autocmd to my vimrc and it works exactly as I expected.Catalogue
@LondonRob, append zz like so autocmd BufEnter * silent! normal! g`"zzHalliday
J
9

How about

Vim cursor jumps to beginning of the line after buffer switch

TL;DR

:set nostartofline

For me g`" messes with my quickfix position.

Juvenal answered 9/7, 2020 at 17:22 Comment(1)
This is the actual best solution as this behavior is documented in :h startofline : "In case of buffer changing commands the cursor is placed at the column where it was the last time the buffer was edited". Other solutions seem to be dirty hacks.Calciferous
K
7

I'm not sure why Vim behaves this way, but fortunately, the exact position is stored in the '" mark (cp. :help 'quote).

The following :autocmd will attempt to restore the cursor to that position, using the g` command:

:autocmd BufEnter * silent! normal! g`"

Note: You can append positioning commands like zz (which positions the current line in the center of the window) or zv (which opens any folds) after the g`.

Kelci answered 6/12, 2016 at 10:11 Comment(2)
Awesome. I added this autocmd to my vimrc and it works exactly as I expected.Catalogue
@LondonRob, append zz like so autocmd BufEnter * silent! normal! g`"zzHalliday
H
0

I have a function in my ~/.vimrc that saves the datetime near the top of the file upon saves (if there is a "last modified" string near the top of the file):

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]

That works fine; however, my cursor was jumping lines (failing to retain the line position / cursor position) when switching buffers in a vertical split.

autocmd BufEnter * silent! normal! g`"

(suggested in another answer in this thread) had no effect, but this (Ref [3]) solved that problem:

" 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

Aside: to make it somewhat easier to follow edits in either split, in Normal mode press zz to vertically center the current line (Ref [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

Harden answered 22/12, 2020 at 18:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.