← All lessons

7. Undo And Redo

Step 3 of 5

Undo branches

The u and <C-r> keys are useful if you consider your undo history to be linear. But in actual fact, it’s not always that simple. Sometimes, you undo a few steps, then start writing again. In other editors, this would destroy your redo history, making the text you had before the undo completely irrecoverable.

Vim keeps track of undo branches, so you’ll never find yourself in this situation.

This is best illustrated with an example. Let’s say you have an empty document, and you start writing a sentence:

Hello, this is my first sentence!

Then, you decide to write another sentence:

Hello, this is my first sentence! This is my second sentence!

You then decide you don’t want the second sentence, so you undo your change:

Hello, this is my first sentence!

You then write something else:

Hello, this is my first sentence! Now there's something else!

If you then decide you want to recover the “And this is my second sentence” text, we’re in a bit of a sticky situation. No amount of u and <C-r> can recover it!

Try this workflow for yourself in the editor, and verify that I’m telling the truth.

Now, luckily, Vim provides us with another way to undo and redo. Vim keeps track of the way that changes branch in the undo history, and we can use the g- and g+ commands to go to older and newer text states respectively.

Try using the g- and g+ commands yourself in the editor. You should see that it’s actually possible to recover the lost text!

The details of how g- and g+ work under the hood are quite complex, but you should know that you’ve never really lost your text in Vim. If you keep hitting g-, you’ll find it eventually.

Loading editor…