Use last-position-jump to recover context after reopening a file with Vim

A simple and official Vimscript that synergize well with Persistent Undo.

Lately, I am watching screencasts from Destroy All Software. There are a lot of great learning materials, but what’s even more important it is really entertaining to watch these Vim centric coding sessions.

In one of the videos Gary mentions an interesting Vim feature, that is very similar to Persistent Undo. Persistent Undo enhances Vim experience by saving the history for each file, making the undo/redo continue to work after you close and reopen the editor.

The feature I’d like to highlight today is a simple script found in the official help pages:

   This autocommand jumps to the last known position in a file
   just after opening it, if the '" mark is set:

   :au BufReadPost *
   \ if line("'\"") > 1 && line("'\"") <= line("$") && &ft !~# 'commit'
   \ |   exe "normal! g`\""
   \ | endif

If you paste the snippet to your .vimrc, Vim will save the last cursor position when you close a file, and if you later reopen it, the cursor automatically jumps there.

It’s inevitable that you have to interact with multiple files. Usually, there are files that you might want to edit only a few times, and you don’t want to keep them open in a buffer.

Both of these features are beneficial if you use Vim for longer coding sessions, and I highly recommend them.

When you close a buffer you don’t lose all the context and if you reopen a file later, you can continue exactly where you left off. For me, it means that I don’t have to think about which buffers to keep open, so I usually close every tab and panel that I don’t use at the given moment. I even close Vim if I have some work to do in the terminal, rather than keeping multiple terminals open all the time just for the sake of history.

08 May 2018

Interesting article?

Get hand-crafted emails on new content!