How do I get VIM to remember the line I was on when I reopen a file?

vim
34,997

Solution 1

Add the following lines to your ~/.vimrc or global /etc/vim/vimrc

if has("autocmd")
  au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe "normal! g`\"" | endif
endif

This will jump to the last known cursor position unless:

  • the position is invalid
  • the position is inside an event handler

Solution 2

Your system probably already contains the necessary feature. You just need to uncomment it in the default configuration /etc/vim/vimrc or add it to your ~/.vimrc file. vim is not remembering last position

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

This is an auto command that looks for line numbers of the evaluated expressions. The g command jumps to the last position if it was recorded. Using :help on commands BufReadPost, line() and g` will explain the details of how this works.

Share:
34,997

Related videos on Youtube

Ibrahim S. Gerbiqi
Author by

Ibrahim S. Gerbiqi

Just trying to muddle my way through.

Updated on September 18, 2022

Comments

  • Ibrahim S. Gerbiqi
    Ibrahim S. Gerbiqi about 1 year

    I just moved from RH/Fedora to Ubuntu 12.04. In RedHat, when I reopen a file with VIM, it opens with the cursor on the line it was on when I closed the file. However, what I am seeing now is that when I reopen a file, the cursor is always at the top, every time. As some of the files I am working with are 20k lines long, this gets a bit old quickly.

    I installed the full version of VIM via apt-get on my new Ubuntu so that I could use the arrow keys in insert mode. The version that is printed out is VIM - Vi IMproved 7.3.

    Any help at all would be gratefully welcomed.

    • Admin
      Admin about 11 years
      If you want to open more file with the lines these files was opened earlier use :mksession . For further details see the help of :mksession and Managing Sessions
    • Admin
      Admin over 5 years
      For those who voted this down as already been answered, I believe mine was asked first.
  • seth10
    seth10 over 6 years
    Thank! At times (such as :help) I'm getting E32: No file name, any advice?
  • Nagev
    Nagev about 6 years
    I've done this for both ~/.vimrc and /etc/vim/vimrc and even restarted, still always opens at the first line!
  • Chan Kim
    Chan Kim over 4 years
    @Nagev check the permission of ~/.viminfo. I changed the owner and group to mine, and it works.
  • koushik naskar
    koushik naskar over 2 years
    I did this, but vi always open in a fixed line, this doesn't update the viminfo file
  • alchemy
    alchemy almost 2 years
    one-liner: echo -e 'if has("autocmd")\n au BufReadPost * if line("'\''\"") > 0 && line("'\''\"") <= line("$") | exe "normal! g`\"" | endif\nendif' >> ~/.vimrc