Undo & Redo in Vim / Vi
Understanding How Vim Tracks Changes Conceptually
Vim tracks changes by entries. An entry in Vim is defined as anything you can do within a session in insert mode before returning to normal mode, or a command you use in normal mode.
Each of the following examples below can be considered 1 entry:
- Pressing i to move into insert mode
- Writing 4 new lines in insert mode
- Editing 4 different lines in insert mode
To clarify, here is what is not considered an entry:
- Typing one character, then continuing to type in insert mode. Vim will not work like your normal text editor (Google Docs or Notion) where you can undo typing character by character unless you switch to normal mode then back to insert mode (thus ending and starting a new entry) per character.
Undo Changes in Vim / Vi
- Press esc to return to normal mode. Any character typed in normal mode will be interpreted as a vim command.
- Press u, :u, or :undo to undo the last change (entry). The reason why it is important to be in normal mode is because pressing u in another mode may trigger different results, like turning the selected characters lowercase.
Redo Changes in Vim / Vi
- Press esc to return to normal mode. Any character typed in normal mode will be interpreted as a vim command.
- Press CTRL+r to redo the last change (entry).
Advanced Usage of Vim Undo/Redo Shortcuts
Undo
- U: Undo latest changes to one line. This command is unique because it will create a new entry instead of reverting back to an old entry. This means you can actually press u to undo the changes done with U.
- 4u: Undo last 4 changes (You can change 4 to any number to undo that number of changes)
Redo
- 4CTRL+R: Redo last 4 changes (You can change 4 to any number to undo that number of changes)
Conclusion
This should be everything you need to undo and redo in Vim / Vi, which is a fundamental skill that every Vim user should know. If you didn’t find what you were looking for, it may be worth checking out the official vim docs.
Related articles
Go To End of File in Vim / Vi
Select and delete to the end of a file in Vim
Select all in Vim / Vi
Select all and copy, paste, or delete the contents
Copy & Paste in Vim / Vi
Copy (Yank), Paste (Put) and Cut (Delete) in Vim
Searching in Vim
Search forward, backward, case insensitive, and more
Show & Hide Line Numbers in Vim / Vi
Toggle absolute and relative line numbers
Vim Go To End/Start of Line
Go to the end or beginning of a line in Vim
Go To Line In Vim
Variety of approaches to go to lines
Go To Top of File in Vim
Learn how to jump the top of the file in Vim, then navigate, search, highlight, and delete.
Vim / Vi Page Up and Down Controls
Quick reference for Vim's page up and down controls
How to delete lines in Vim / Vi
The best answer depends on which mode you use
Vim Find And Replace
You can use either the substitute command or the slash and dot method to search for patterns and replace with different values.