Vim open file at location that was last viewed

7,465

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
7,465

Related videos on Youtube

PATIL DADA
Author by

PATIL DADA

Updated on September 17, 2022

Comments

  • PATIL DADA
    PATIL DADA over 1 year

    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?

  • DaveParillo
    DaveParillo about 14 years
    +1. As a BTW, you can read more on this from :help last-position-jump.
  • DaveParillo
    DaveParillo about 14 years
    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.
  • PATIL DADA
    PATIL DADA about 14 years
    +1: Thanks for the response but I think that I found a simpler solution (by mistake)
  • bummi
    bummi over 8 years
    Hi Greg, regarding your last answers, please take a look here.
  • clhy
    clhy over 8 years
    I think its Greg is doing okay so far. Still he must go through the link you shared
  • Greg Dietsche
    Greg Dietsche over 8 years
    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."
  • LEo
    LEo about 4 years
    this is the same answer as given here: unix.stackexchange.com/questions/23335/…