How to open vim at previous location

Vi (or Vim) editor can remember location at the time of exiting a file. This can be fairly convenient while editing files during development.

.vimrc autocmd code for opening vi at previous location

Add the following code to ~/.vimrc file.

au BufWinLeave ?* mkview
au BufWinEnter ?* silent loadview


autocmd BufWinLeave ?* mkview
auautocmd BufWinEnter ?* silent loadview

Note that ?* tells vi to run autocmd only if it was opend with a filename.

Testing above code

Open vi and create a file (say foo.txt) and enter few lines to it. Save the file and exit vi. Now when you reopen foo.txt in vi, it should open with cursor at the previous location as shown below:

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments