Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vim, how do I get a file to open at the same line number I closed it at last time?

Tags:

vim

People also ask

How do I go to a specific line number in vim?

The Vim goto line number command One can use the G letter. For example, press [ESC] key and type 10G (Shift-g) goto line number 10.

How do I go to a specific line number in Linux?

To do this, press Esc , type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file.


From Ubuntu's /etc/vim/vimrc file, this example is commented out:

" Uncomment the following to have Vim jump to the last position when                                                       
" reopening a file
if has("autocmd")
  au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$")
    \| exe "normal! g'\"" | endif
endif

If this doesn't work, a common problem is not having ownership of your ~/.viminfo file. If this is the case, then run:

sudo chown user:group ~/.viminfo

where user is your username and group is often the same as your username.


If you don't mind trading automation for simplicity, just press the keystroke '" (apostrophe, followed by double quotes) on opening a file, you'll jump to where you were. This is essentially what @marcog's answer is doing.


  :h views-sessions

You can place this in your .vimrc :

  autocmd BufWinLeave *.* mkview
  autocmd BufWinEnter *.* silent loadview 

the views will be placed in .vim/view. You probably need to create these directories.


You can start vim without specifying a file name using

vim 

Next press CTRL+O twice to move to the last location in any file you worked on.


There is a plugin called vim-lastplace (I am the author) that will open your files where you left off. It improves on the above suggestions by ignoring commit messages because you're typically editing a new message and want to start at the top of the commit message file.


If you have viminfo enabled, it is as simple as `0 to go to the last edited file position. You'll notice that this is just a 'go to mark' command;

Indeed, you can later do '3 to go to the third previous edited location (perhaps in another file), and then return to the last one with `0 again

Have a look at

 :marks

to see remembered locations. Note also that viminfo stores all kinds of other stuff (like the contents of registers, marks per file, command and search history). Most people have this enabled for obvious reasons


Sometimes ~/.viminfo becomes read-only or your user don't have access to the file. That could also be a reason that vim does not store your cursor position when you close your file.