Introduction
Have you ever found yourself in a situation where you accidentally deleted a row or changed your mind about a change and want to undo the changes?
In this article we will show you how to undo and redo changes in Vim/Vi.
Vi is a lightweight editor that has been around since the dawn of Unix, while Vim is an improved version of Vi that includes many additional features and options.
Vi or Vim is pre-installed by default on macOS and almost all Linux distributions. Knowing the basics of Vim can be especially helpful when you find yourself in a situation where your favorite editor isn't available.
Undo changes in Vim/Vi
Vim keeps track of all changes made in the current session. The Undo command reverses one or more changes in the order they were made.
To undo changes in Vim and Vi use the u
, :u
or :undo
commands:
- If you are in insert mode or any other mode, press the
Esc
key to return to normal mode, also known as command mode. - Type
u
to undo the last change. In Vim, theu
command also accepts quantifiers. For example, if you wanted to undo the last four changes, you would use4u
.
Make sure you type u
the lowercase command and not uppercase U
, which undoes all the latest changes on a single line. If you accidentally type U
you can undo the change with u
.
Use the Undo command to undo changes made by any other command, such as delete, paste, find and replace, and so on.
When working in insert mode, all text changes are treated as an entry in the undo tree. For example, if you switch to insert mode and enter five lines, then return to normal mode and press u
to cancel the change, all five lines will be removed.
Repeat changes in Vim/Vi
The redo function is the opposite of Undo; allows you to reverse the previous action.
To redo a change in Vim and Vi use the Ctrl-R
or :redo
command:
- Press the
Esc
key to return to normal mode. - Use
Ctrl-R
(hold downCtrl
and pressr
) to redo the last change. In Vim you can also use quantifiers. For example, if you want to repeat the last four changes, you would type4Ctrl-R
.
Each undo command can be undone by a redo command.
Conclusion
When working with text files, it's common to make mistakes while editing, such as accidentally deleting a line or making an unintentional change. To undo a change in Vim/Vi u
type and to redo a canceled change use the Ctrl-R
key sequence.
Vim also supports undo branches.
Additionally, you can also use the :earlier
and :later
commands to move back and forth in time through the changes you make. For example, typing :earlier 10m
will undo changes made in the last ten minutes, while typing :later 5s
will revert the change made five seconds ago.
Feel free to leave a comment if you have any questions.