Undo, redo and the dot command

Vim · Essentials · 8 min

The dot command turns one careful edit into many, and undo makes experimenting safe.

u undoes the last change and Ctrl-r redoes it. A change is one Normal-mode command, or everything you typed in one visit to Insert mode, so ihello world<Esc> undoes in one step.

The dot command . repeats the last change. This is the single most useful key in Vim once you learn to make your changes repeatable:

  • A;<Esc> then j. j. adds semicolons to the next lines.
  • cwfoo<Esc> then n. changes the next search match to foo too.
  • dd then ... deletes three more lines.

The trick is to compose a change so it does not depend on where the cursor happens to be. A works anywhere on the line, $a is two commands and only the a part repeats. Using ciw (change inner word, from the text objects lesson) instead of cw repeats correctly even when the cursor is mid-word.

Vim also keeps a full undo tree, not just a stack: if you undo and then make a new change, the old branch is not lost. g- and g+ move back and forward through all states by time, and :earlier 5m rewinds the buffer to how it was five minutes ago. With set undofile in your config, undo history even survives closing the file.

Example

A;<Esc>      " append ';' to this line
j.           " move down, repeat: ';' added again
j.           " and again
u            " undo the last ';'
Ctrl-r       " redo it
:earlier 2m  " restore the buffer as it was 2 minutes ago
:later 1m    " move forward in time again

Remember

  • u = undo, Ctrl-r = redo, . = repeat last change
  • Design edits so they repeat well: A over $a, ciw over cw
  • :earlier / :later travel the undo tree by time

Watch out for

  • Moving the cursor inside Insert mode with arrow keys splits the change, so . only repeats the last part.

Check yourself

  1. You ran `cwbar<Esc>` on a word. Which sequence changes the next occurrence of the search match to `bar`?
  2. What counts as a single change for undo?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/undo.txt.html