Made a mistake while editing a file with Vim? Don't worry, you can undo the changes in Vim and if you want, you can redo the changes as well.
And it's pretty simple, too.
- Go to command mode by pressing Esc key.
- Press the u key to undo the changes.
- Press the Ctrl+R keys to redo the changes.
It cannot be simpler than this, can it? To remember,
u stands for undo and
r stands for redo.
Let's go a bit in detail.
Undo changes in Vim
Vim maintains the record of changes in a stack in LIFO (last in first out) format. Whenever you make any change, it gets added in the stack. When you undo it, the last change gets undone first.
Let's take an example. I have this file where I have deleted lines 3 and 6 in the same order.
It's easy to see which lines have been deleted even if I am not showing line numbers in Vim.
To undo the changes, I go to the command mode by pressing Esc key and then press the
u key. As you can see, it brings back the line number 6 first. Vim even shows the information about the undone change at the bottom.
If I press the
u key once more, it will undo the next change, which was deleting line 3.
You get the point. To undo multiple changes, you can keep on pressing
If you want to undo multiple changes at once, you can specify the number with the
For example, if you want to undo the last 3 changes, type
3u i.e. 3 and u one after another in quick succession.
Redo changes in Vim
No undo is complete without a redo. You can change your mind about the undo after all.
The redo process is the same as undo. You go to command mode by pressing the Esc key. While in the command mode, press Ctrl+r. Which means Press and hold the ctrl key and press r at the same time.
This will redo the last undone change. You can press
Ctrl+r multiple times to redo the changes one by one.
As you can see in the screenshot below, press Ctrl+r two times removes the line 3 and line 6 again.
You may also specify a number to do multiple redo at once. For example, to redo the last 3 undone changes, use
3Ctrl+r. Which means press 3 first and the in quick succession press and hold Ctrl and press r key.
That's how you undo and redo changes in Vim. It's not that hard, is it?
Questions or suggestions? Please leave a comment.