Undoing Undos

Beyond the convenience of undoing an arbitrary number of edits, Vim offers an interesting twist called branching undos.

To use this feature, first decide how much control you want over undoing edits. Use the undolevels option to define the number of undoable changes you can make in an edit session. The default is 1,000, which is probably more than enough for most users. If you want vi compatibility, set undolevels to zero:

:set undolevels=0

In vi, the undo command u is basically a toggle between the file’s current state and its most recent change. The first undo reverts to the state before the last change. The next undo redoes the undone change. Vim behaves quite differently, and therefore the commands are implemented differently.

Instead of toggling the most recent change, repeated invocations of Vim’s undo rolls back the state of the file through the most recent changes, in order, for as many changes as defined by the undolevels option. Because the undo command u only moves backward, we need a command to roll forward and “redo” changes. Vim does this with the redo command, :redo, or the CTRL-R key. The CTRL-R key accepts a numeric prefix to redo several changes at once.

When rolling forward and backward through changes with the redo (CTRL-R) and undo (u) commands, Vim maintains a map of the file’s state and knows when the last possible undo has been performed. When all possible undos are done, Vim resets the file’s modified status, which allows quitting without the

Get Learning the vi and Vim Editors, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.