Wednesday, June 2, 2010

VIM: go to last position when re-open a file

Each time I re-open a file with vi (vim actually), the very beginning of the file is shown. If I just want to add something at the end of the file, I could quickly go to the end by pressing Shift-g. But most of the time, I need to go to where I was working on in the middle of the file. Then I have to remember some strings or phrases to search, or go down page by page. That would be a headache to a lazy people like me.

Fortunately, VIM can memorize the last position for me. In its configuration file ~/.vimrc, add these lines at the end:
   " Only do this part when compiled with support for autocommands
   if has("autocmd")
     " When editing a file, always jump to the last cursor position
     autocmd BufReadPost *
     \ if line("'\"") > 0 && line ("'\"") <= line("$") |
     \   exe "normal g'\"" |
     \ endif
The secret is that '" records the place where the cursor was before the file was closed last time.

No comments:

Get This <