6

If I edit a file with vim that I have previously edited, I'd like vim to jump to the position I was in when I last closed the file.

How can I accomplish this?

4

What I use (adapted from :help restore-cursor):

" Go to the last cursor location when a file is opened, unless this is a
" git commit (in which case it's annoying)
au BufReadPost *
    \ if line("'\"") > 0 && line("'\"") <= line("$") && &filetype != "gitcommit" |
        \ execute("normal `\"") |
    \ endif

BufReadPost gets run when starting to edit a bufffer. The " mark is the cursor position when last exited the file (as remembered by viminfo). We first check if this is set higher than 0, and lower than the number of lines in the file, before jumping to it.

We don't do this if the filetype is gitcommit, since I find this annoying (I always want it to start at the first line).

You need to keep viminfo file for all of this, which is enabled by default.

  • Thank you but my commit message file without extension - on the path .git/COMMIT_EDITMSG – Vitaly Zdanevich Nov 20 '17 at 9:28
5

The vim-lastplace plugin does exactly what you want (I am the author). It improves on the above code snippet by handling commit messages intelligently. If you have debian-testing you can apt-get install vim-lastplace to quickly try it out.

  • Curious: What do you mean by "handling commit messages intelligently"? Also, I would strongly discourage anyone from installing a vim plugin through the main package manager. When people do this, they often tend to forget which plugins are installed and active. This is a rather common reason for plugin conflicts (at least as far as I have experienced while developing vimtex). – Karl Yngve Lervåg Sep 7 '16 at 6:06
  • 1
    Commit messages for git/svn/etc typically re-use the same file name for editing. Most commit messages are new messages (and not a re-edit of the previous message) the vim-lastplace plugin knows this and won't jump. The snippet marked as the answer currently (and many of the others posted around the net) will try to jump to the last edit position which is usually not what folks want to have happen. – Greg Dietsche Sep 8 '16 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.