Lines of Code is the Best Software Productivity Metric
Why The Post Scarcity Society Will Not Be Star Trek

Vim's undo list isn't a list. It's a tree.

Vim's undo list isn't a list. It's a tree...meaning that it keeps track of all the edits you make after having "undone/redone" something. Putting this power to use can be a bit daunting, unless you keep a couple of simple vim commands handy.

First, let's create an example to work with. Make a new buffer and type three things (switching back to normal mode after each line to produce three separate changes). You should wind up with something like this:


Now let's say I undo the change that created "third", and then change "second" to "2nd". Now I have this:


You can undo and redo to remove and re-add "second" and "first", but there's no way to bring "third" back, right? In most editors, it would be lost.

Actually, in Vim, there's at least three ways to get it back.

The :earlier and :later commands will move you back and forward in time across the undo tree. It's basically a time machine built into vim. At this point, to bring back "third" we just need to use the 'earlier' command, like so:

:earlier 1

That will bring us back one edit in time (rather than in the undo/redo path) leaving a buffer that looks like this:


If you prefer using 'g' rather than command mode, g+ and g- from normal mode will move you across the edit tree one step forward or backward, respectively.

And of course, no self-respecting time machine would be complete without time, so :earlier and :later both take time as an argument as well. To jump back to the state of your code 30 seconds ago, just type this

:earlier 30s

It works with [m]inutes, [h]ours, and [d]ays too. Being able to jump back and forth between changes I was making days ago, in just a few keystrokes, is just one of the many reasons I love Vim.

Ben Rady is the author of "Continuous Testing with Ruby, Rails, and JavaScript". If you've enjoyed this post and would like to read more, you should follow him on Twitter.


Feed You can follow this conversation by subscribing to the comment feed for this post.

The comments to this entry are closed.