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
This autocommand was pulled directly from Vim’s help pages.