OnSwipe redirect code

Thursday, June 25, 2009

Vim -- Restoring cursor from previous session

I am sure every Vim user needs this. Its just so frustrating to open a source file to see the #includes (the first few lines) in the file when we actually will be editing many hundred lines later. Today specially I was juggling with several source files, adding something to the .h file and then come back, do something in the .cpp file and then again go to some .c file and so on. Every time I opened a file the cursor was at the first line and every time invariably I had to search for the function I was editing and cycle through the matches to reach it. So I set on a "Search Mission" - A mission to search for the appropriate .vimrc settings to make Vim remember the cursor position from the previous session.

I got a lot of links. In fact there is a separate Vim Tip - Vim Tip #80 for this. But it has so many code lines and I was a little wary to put all that in my .vimrc file. Continued search revealed me a simpler way. Just two lines solution and it is here : Some Mr.Gopinath's .vimrc file. Its very big, but the lines concerning me are:

" VimTip 80: Restore cursor to file position in previous editing session
" for unix/linux/solaris
set viminfo='10,\"100,:20,%,n~/.viminfo

" only for windows [give some path to store the line number info]
"set viminfo='10,\"100,:20,%,nc:\\Winnt\\_viminfo
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif

Looks like he also picked this up from the same Vim Tip #80 but was smart enough to take out only the necessary part. Nevertheless, this works for me. Thank you Mr. Gopinath.

Happy Vimming :-)

Edit:

I read the Vim Tip #80 again and it made more sense this time. I picked up the last line for a user comment. Now the cursor is put back on the same column too.

2 comments:

  1. Why are you opening and closing the files if you intend to open them again? Won't tabs or vertical splits make your life easier? Then you can use the cursor history (^PO and ^PI) or marks (m<letter> to mark and '<letter> to restore mark) to navigate around easily.

    ReplyDelete
  2. First, I have not used marks and as such it appears to be some effort every to mark a line and then return to that mark manually. If vim can do it automatically, good for me. :)

    And about closing and opening the files, there are many files I edit but not all of them simultaneously. Splits work for me when I need two files together to copy something from one to another. Otherwise I generally prefer one file in full screen. So I tend to close and open files.

    This and other bunch of "practices of mine" made me hunt for this cursor restoration solution.

    ReplyDelete