Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve last editing position in VIM

Tags:

vim

When I quit VIM and open the same file again, I am positioned at the start of the file. How can I preserve the last cursor position?

like image 544
Dmitry Negoda Avatar asked Oct 25 '11 18:10

Dmitry Negoda


4 Answers

Taken from http://amix.dk/vim/vimrc.html

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif
like image 121
Mariano Avatar answered Oct 23 '22 14:10

Mariano


The "out of the box" .vimrc enables this with the statement:

source $VIMRUNTIME/vimrc_example.vim

You may just need to restore this statement in your .vimrc. In any case, see vimrc_example.vim and also see the line() function in the Vim manual for a discussion of how it works.

like image 31
MetaEd Avatar answered Oct 23 '22 14:10

MetaEd


The last edit position is automatically preserved by Vim, and is available as "special" jump mark .. Other special marks include " (position you saved from) and ' (position you jumped from).

You can jump to a mark by typing '<mark>, so '. will take you to the place of the last edit, '' will take you back to where you were, and '" takes you to the position you saved the file at.

That and more about Vim marks at Vim.Wikia.

like image 29
DevSolar Avatar answered Oct 23 '22 14:10

DevSolar


There is a plugin (I am the author) called vim-lastplace that will intelligently return you to the last edit that you made.

It also has a configuration option to ignore certain file types. By default it will ignore commit messages for git, svn, and mercurial. For these file types it will start your cursor at the first line. The code snippets above will jump into the middle of your commit message file (where you left off in your previous commit) even though that's probably not what you want. vim-lastplace fixes this problem.

like image 16
Greg Dietsche Avatar answered Oct 23 '22 14:10

Greg Dietsche