Mastodon hachyterm.io

Today I learned about Vim undo and redo.

Undo changes:

  • in normal mode: u to undo latest change, U to undo all changes
  • in Ex mode (command mode): :u to undo latest change

Use :u {N} to undo a number of changes. For example, :undo 5 reverts the latest 5 changes.

Redo changes:

  • in normal mode: Ctrl+r
  • in Ex mode: :re or :redo

In Vim, undo is a tree:

		one ~
		 |
	      change 1
		 |
	      one too ~
	      /     \
	 change 2  change 3
	    |	      |
	 one two    me too ~
	    |
	 change 4
	    |
	 not two ~

You can see the number of branches with :undolist:

:undolist
number changes  time ~
3       2  16 seconds ago
4       3  5 seconds ago

See :h undolist and :h usr_32.txt.

The undolist is not obvious, and I’m not sure if I’m able to navigate the list without a visualization plugin.

Luckily, there are other commands that can help out.

:earlier or :ea allow you to undo changes regardless of where you are in the tree. For example, :ea 10m undos the changes fromThe last 10 minutes.

:earlier {count}	Go to older text state {count} times.
:earlier {N}s		Go to older text state about {N} seconds before.
:earlier {N}m		Go to older text state about {N} minutes before.
:earlier {N}h		Go to older text state about {N} hours before.
:earlier {N}d		Go to older text state about {N} days before.

:earlier {N}f		Go to older text state {N} file writes before.
			When changes were made since the last write
			":earlier 1f" will revert the text to the state when
			it was written.  Otherwise it will go to the write
			before that.
			When at the state of the first file write, or when
			the file was not written, ":earlier 1f" will go to
			before the first change.

You can also redo changes.

The :later command mirrors :earlier:

:later {count}		Go to newer text state {count} times.
:later {N}s		Go to newer text state about {N} seconds later.
:later {N}m		Go to newer text state about {N} minutes later.
:later {N}h		Go to newer text state about {N} hours later.
:later {N}d		Go to newer text state about {N} days later.

:later {N}f		Go to newer text state {N} file writes later.
			When at the state of the last file write, ":later 1f"
			will go to the newest text state.

The commands g- and g+ do the changes regardless of the tree. You could map these to F9 and F10 (in your ~/.vimrc or similar):

nnoremap <F9> g-
nnoremap <F10> g+

The undo tree only works as long as you don’t close your editor.

But you can also create a persistent undo. The option saves your changes across sessions.
Set this option in your configuration file (~/.vimrc or similar):

set undodir=$HOME."/.undodir" "stores undo in a central location
set undofile "creates persistent undo tree

Further Reading