8

When I close a file in vim and reopen it, the file opens at the start of the file. Is there anyway to make the file open at the last place the I viewed?

3 Answers 3

10

Put this in your .vimrc :

if has("autocmd")
  " When editing a file, always jump to the last cursor position
  autocmd BufReadPost *
  \ if line("'\"") > 0 && line ("'\"") X= line("$") |
  \   exe "normal g'\"" |
  \ endif
endif

Just change the big X with <.

If I put < the code fails to print correctly.

4
  • 3
    +1. As a BTW, you can read more on this from :help last-position-jump. Feb 19, 2010 at 23:46
  • Also, this command ('") is not available in vi, which might be why sixtyfootersdude's vi is not behaving like this by default. It's the default behavior in vim. Feb 19, 2010 at 23:48
  • +1: Thanks for the response but I think that I found a simpler solution (by mistake) Feb 24, 2010 at 15:02
  • this is the same answer as given here: unix.stackexchange.com/questions/23335/…
    – LEo
    May 6, 2020 at 12:40
8

I just noticed that my cursor has started to have this behavior. I went through my vimrc (commenting out line by line) and found that this code will also work:

"make vim save and load the folding of the document each time it loads"
"also places the cursor in the last place that it was left."
au BufWinLeave * mkview
au BufWinEnter * silent loadview

(Quotes finished to make it easier to read)

The main purpose of this block is to make any folds created appear again when a file is opened but apparently it also saves/loads the cursor position.

1
  • Hint: In neovim one needs to end silent! with an exclamation mark as :help loadview suggests. Oct 14, 2022 at 1:04
2

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.

3
  • Hi Greg, regarding your last answers, please take a look here.
    – bummi
    Jan 17, 2016 at 7:08
  • I think its Greg is doing okay so far. Still he must go through the link you shared
    – clhy
    Jan 17, 2016 at 19:21
  • 2
    I think my answer is both good and relevant. I disclosed that I am the author. Is there something I've missed? From the policy: "Post good, relevant answers, and if some (but not all) happen to be about your product or website, that’s okay. However, you must disclose your affiliation in your answers." Jan 18, 2016 at 15:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .