Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim keep window position when switching buffers

Tags:

A problem I've been having with Vim in general is that when I switch buffers in a window (either :[n]b or MiniBufExpl) the cursor position stays the same, but the window always positions itself so the row the cursor on is in the middle.

This is really annoying me since I visually remember where the top/bottom parts of the window are, not where they would be should the cursor be positioned in the middle of the window.

Is there a setting I can change to preserve a window's position over a buffer?

like image 950
andrew Avatar asked Nov 23 '10 00:11

andrew


2 Answers

It's interesting to note that it didn't bother me until I've read your question, lol.

Try this:

if v:version >= 700   au BufLeave * let b:winview = winsaveview()   au BufEnter * if(exists('b:winview')) | call winrestview(b:winview) | endif endif 
like image 153
dnets Avatar answered Sep 20 '22 15:09

dnets


That script posted by @dnets always sets the cursor at the top of the screen for me, albeit at the same position in the file.

I changed it to this (copied from http://vim.wikia.com/wiki/Avoid_scrolling_when_switch_buffers)

" 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 

And it now works as I want, screen and cursor position saved.

like image 45
Adamski Avatar answered Sep 17 '22 15:09

Adamski