Vim scripting: Preserve cursor position and screen view in function call

let l:winview = winsaveview()
" do stuff
call winrestview(l:winview)

This should pretty much do exactly what you want it to do, possibly excepting the line count changing above the cursor (I suspect that deleted lines above the cursor would have the effect of moving the cursor down).


You can save a mark for the first on-screen line that is displayed in the window and restore that as well. An example that executes a g? command on the whole buffer and restores both positions:

:noremap <F11> mkHmlggg?G`lzt`k

Walking through the command:

  • mk: set mark k for the current position
  • H: go to the first on-screen line
  • ml: set mark l for the this position
  • ggg?G: execute the command
  • ``l: jump to markl`
  • zt: set this line the first on-screen line
  • ``k: jump to markk`

Tags:

Vim