Vim Tip: Restore cursor’s last position

Here’s a useful vi trick that turned out to be a real time saver. It’s a set of commands you add to your vimrc file (on windows) that will recover the cursor’s last position when the file was last closed. The original tip was found on the vim wikia, which is full of those very useful vim tricks. Give it a try!

" Tell vim to remember certain things when we exit
"  '10 : marks will be remembered for up to 10 previously edited files
"  "100 : will save up to 100 lines for each register
"  :20 : up to 20 lines of command-line history will be remembered
"  % : saves and restores the buffer list
"  n... : where to save the viminfo files
set viminfo='10,"100,:20,%,n~/.viminfo

" when we reload, tell vim to restore the cursor to the saved position
augroup JumpCursorOnEdit
 autocmd BufReadPost *
  if expand(":p:h") !=? $TEMP |
  if line("'"") > 1 && line("'"")  foldlevel(JumpCursorOnEdit_foo - 1)) |
  let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
  let b:doopenfold = 2 |
  endif |
  exe JumpCursorOnEdit_foo |
  endif |
 " Need to postpone using "zv" until after reading the modelines.
 autocmd BufWinEnter *
  if exists("b:doopenfold") |
  exe "normal zv" |
  if(b:doopenfold > 1) |
  exe "+".1 |
  endif |
  unlet b:doopenfold |
augroup END

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s