Let me guess.
You made some mistakes while editing a file in Vim and now looking for a way to undo the previous action. Right?
Well, it is pretty easy to undo and redo in Vim and can be done by following the given keybindings:
||Undo the last action.|
||Redo the previous action.|
Make sure you use these shortcuts in the normal mode (activated by pressing the
Want a detailed explanation? I got you!
How to undo in Vim
To undo in Vim, all you have to do is follow the given steps:
- Press the
Esckey to switch to the normal mode
- Press the
ukey to undo the last action (press it multiple times to undo earlier actions).
For example, here, I removed lines 3, 5, and 7 and now want to undo them so I will press the
u key 3 times:
As you can see when I pressed the
u key multiple times, it brought back all the deleted lines and when I pressed it again, it said
Already at oldest change.
It simply means you brought the file to the previously saved position and if that's the new file and you keep pressing the
u key, it will remove all the lines.
But if you don't want to keep pressing the
u key, then you can specify how many times you want to perform undo at once by appending the number.
For example, if I want to undo the last 3 actions, then I will have to enter
3u (first, enter 3 and then u):
How to redo in Vim
For those who don't know, redo is used to revert the action done by undo. I mean you may have pressed the
u key accidentally or you just changed your mind about the undo action itself.
In that case, simply follow these two steps:
- Switch to normal mode (if you haven't already)
Ctrl + Rto redo the action
For example, I used undo to get back lines that I deleted accidentally so now, I will use
Ctrl + r 3 times to remove them again:
As you can see when I pressed
Ctrl + r, it reverts the action done by undo and when I pressed it more than the required times, it said
Already at newest change.
Which simply means there is nothing left to redo.
Similar to undo, you can also specify how many times you want to perform the redo action at once.
For that, you have to first enter the number of how many times you want to perform redo and then press
Ctrl + r which will look like this:
number + Ctrl + r.
Let's say I want to perform redo 3 times, so I will use
3 + Ctrl + r:
Pretty convenient. Right?
Here's how to master Vim
If you want to master Vim and want to flaunt your skills, you have to start from scratch and learn all the basics first and for that, you can refer to our detailed guide on Vim commands:
Once you are done with the basics, here are some tips to get to the next level:
And if you want to take it even further, here's an excellent Vim course for you.
Mastering Vim Quickly
Master Vim like a true professional with this highly rated, premium Vim book and training course.
I hope you will find this guide helpful.