Unlock your productivity with Vim For Developers book!

Vim Macros

November 16, 2021

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.

  1. Start recording a macro with pressing q followed by any letter (register), for example qa. You can have as many recorded macros as you have registers.
  2. Type your commands, for example $xj (go to the end of line, remove the last character, go to the next line)
  3. Stop recording by pressing q again
  4. 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 or 100@@).


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!
  1. Start recording with qq (recording into the register q)
  2. /function will get us at the beginning of the next function keyword. Then ciw will delete the whole word and put us into the INSERT mode, type const, then Esc, then f( to put the cursor into the next parenthesis, then i and <Space>=<Space>, Esc again. Then we can jump to the closing parenthesis with f) and then a and <Space>=><Space> and Esc.

The whole sequence would look something like this:

  1. Stop recording with q. Now let's repeat with @q. And again with @@. Then we can repeat 100 times with 100@q.

Using Vim Macros
Using Vim Macros

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.

  1. :help recording (Vim help is always a great resource)
Vim For Developers

Vim For Developers

Learn Vim and upgrade your productivity to the next level by building the IDE of your dreams.