tags:

views:

551

answers:

3

I have some Vim functions that make changes to the document format. When I call this function, I currently use something like the following to save and restore my cursor position:

func! Foo()
  :norm mz
  ...
  :norm `z
endf

This properly saves the cursor position, but it sometimes changes the window position, so that the current line moves from being near the top of the screen to being near the bottom or vice versa. Is there a way to preserve both cursor position and the on-screen position of the line?

+2  A: 
JD
+3  A: 

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 mark l
  • zt: set this line the first on-screen line
  • `k: jump to mark k
hcs42
+1  A: 

Just :h getpos()

let save_cursor = getpos(".")
" MoveTheCursorAround
call setpos('.', save_cursor)
Maxim Kim
That will not work. As JS Bangs stated that he needs to restore the window position as well.
JD