Step 3 of 5

7. Undo And Redo

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!

The first part of the checklist below walks you through this exact workflow — follow it, 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.

The final checklist items have you try g- and g+ for yourself. 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.

  1. Start writing at the Type here --> marker Move to the last line, then press A to append at its end.
  2. Write the first sentence, then return to normal mode Something like Hello, this is my first sentence! — then hit Escape.
  3. Append a second sentence Press A to pick up where you left off.
  4. Write the second sentence, then return to normal mode Add another sentence, then hit Escape — leaving insert mode is what seals it into its own undo step.
  5. Undo the second sentence The second sentence disappears — press u.
  6. Start writing something else This is where your undo history branches — press A again.
  7. Write a different ending, then return to normal mode The second sentence becomes unreachable with u and Ctrl-r alone — type something new, then hit Escape.
  8. Walk back through text states with g- The lost second sentence only comes back after a few repeats — press g then -.
  9. Walk forward again with g+ Press g then + to move toward newer text states.
Start writing at the Type here --> marker Move to the last line, then press A to append at its end.

Next: Write the first sentence, then return to normal mode

Loading editor…