Vim Macros
When people tell me that Vim can do nothing that a modern IDE wouldn't do, I force a grin and reply "Oh really?" and then entrance every single person in the room by exquisitely executing a commonly-known mundane task in several seconds.
By the time I finish, the whole office is ecstatic in a standing ovation, while my boss immediately promotes me to his place, deciding to devote the rest of his life to farming.
OK, usually that only happens in my head, but seriously, there is no lack of impressive ways of using macros.
In this article, we will see how easy it is to use Vim macros and what a great power it gives us.
What is a macro?
Macro (don't confuse with Macross) is a sequence of actions that you can record and then replay to automate a repetetive task.
How to use macros?
Using a macro is remarkably easy. Record by pressing qa
. When you're done stop recording with q
. Replay it with @a
.
Now let's have a deeper look.
- Start recording a macro with pressing
q
followed by any letter (register), for exampleqa
. You can have as many recorded macros as you have registers. - Type your commands, for example
$xj
(go to the end of line, remove the last character, go to the next line) - Stop recording by pressing
q
again - Replay macro with
@a
. Then you can repeat it with@@
(replay the last used macros), and then you can repeat it multiple time by prefixing with a number (100@a
or100@@
).
Example
Imaging that we have a JavaScript file with function declarations that we want to convert to "arrow function expressions".
function myFunc() {
// doesn't matter
}
function nextOne() {
// nope, nothing here
}
function anotherOne() {
// Dj Khaled!
}
- Start recording with
qq
(recording into the registerq
) /function
will get us at the beginning of the next function keyword. Thenciw
will delete the whole word and put us into the INSERT mode, typeconst
, thenEsc
, thenf(
to put the cursor into the next parenthesis, theni
and<Space>=<Space>
,Esc
again. Then we can jump to the closing parenthesis withf)
and thena
and<Space>=><Space>
andEsc
.
The whole sequence would look something like this:
/functionciwconst<Esc>f(i<Space>=<Space><Esc>f)a<Space>=><Space><Esc>
- Stop recording with
q
. Now let's repeat with@q
. And again with@@
. Then we can repeat 100 times with100@q
.
Here's a fun little trick
Since macros are stored in the same registers that are used for yanking text, we can paste a macro as text, change it as we want (fix a mistake), and then yank back into the register.
That's basically it.
You have a great power now, don't forget about the great responsibility!
What's next?
Here's where to learn more.
:help recording
(Vim help is always a great resource)