Restoring the Last Known Cursor Position in Vim
In unconfigured Vim, the cursor is placed at the beginning of each file that I open. When I close a file in Vim and open it again later, it’d be really nice if the cursor would automatically move to where I left off editing. And it can, with this handy autocommand:
" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event handler
" (happens when dropping a file on gvim).
autocmd BufReadPost *
\ if line("'\"") > 0 && line("'\"") <= line("$") |
\ execute "normal g'\"" |
\ endif
Autocommands let you write callbacks for certain events that occur in certain files. Here, we are defining some code that we want to execute after we open (BufReadPost) a file of any type (*). The code itself reads the last known cursor position, which Vim kindly stored for us in a special register named ” (that’s a double-quote). (Information like this is stored in ~/.viminfo, but this doesn’t concern us.) Then we
- Determine if the line number where the cursor was at still exists in the file. 1 is the first valid line and line(“$”) is the last valid line, so line(“‘\””) must be within this range. We need this check because some other editor may have altered the file and invalidated our bookmark.
- If we’re in range, issue a keyboard command: g'”, which means go to the line number stored in register “.
This autocommand was pulled directly from Vim’s help pages.