When editing with Vim on Linux, it's easy to make mistakes. Fortunately, it's also easy to undo them. Here's how to quickly undo your edits in the popular Linux text-editor Vim.
How to Undo a Vim Edit
Simple Vim undo operations are similar to the undo function you might have used in a modern word processor such as Microsoft Word, LibreOffice Writer, or Google Docs. Vim keeps track of changes that you make to a file and can roll back if you need to.
Vim considers anything you do in insert mode or any commands in command mode as changes. For example:
- If you type several lines in insert mode, then perform an undo immediately, those lines will be deleted.
- If you type a line, switch to command mode, then switch back to insert mode and type some more text, you’ll create two changes. Undo will remove each one separately.
You can also repeat Vim commands like "3dd" to delete three lines. If you issue one of these compound commands, this will also be redone as the latest change. You can keep undoing until you get back to where you started, when you opened or created the file.
If you realize you've made an edit in Vim that you didn't want to make, undoing it is a simple two-step process:
- Press Esc to make sure you're in command mode.
- Press u to undo the previous change.
That's it. You'll see a message about what changes are made, such as "n fewer lines."
If you want to undo more than one change, you can do that too. Just prefix the undo command with the number of changes you want to undo, as you can with most other Vim commands. For example, if you wanted to undo two changes, you would press:
2u
How to Redo in Vim
You may find that your undo command does something undesirable, or you just change your mind about it. In this case, you can issue redo commands to get your file back to its previous state.
As Vim keeps track of your changes, it also keeps track of your undos. So you can undo your undos if you need to through redo operations. Remember, Vim treats multiple lines entered in input mode as one change, so if you redo an operation, you'll get several lines back in one command.
The command to do this is Ctrl + r, for "redo." Make sure you're in command mode by pressing Esc. Redo works on the same principle as undo; for example, you can repeat the redo by prefixing it with the number of redos you want to make.
As with undo, you'll see a brief message about the changes that were redone, such as the number of lines added to the file. You can redo any number of times, until you get back to the current state of the file.