The Power of Recursive Macros in Vim

If for some crazy reason you’re not already a user of Vim, shutdown your computer and go think about your life choices.

Joking aside, Vim is really a great editor. And if you didn’t know – Vim supports macros.

Basics of macros in Vim

Macros represent a simple concept which can be described as “record the sequence of my actions, save them, and anytime I need them again, execute them.”

This is probably the most underused Vim feature which can improve your productivity dramatically. You can do all sorts of amazing stuff with your code using macros.

Incredibly powerful. Here’s a simple example:

What’s happening here:

  • qa – start recording macro in register a
  • i<Tab>' – enter Insert mode, insert Tab and 
  • Esc – get back to Normal mode (so I can run next command)
  • AAppend command, which places cursor at the end of the current line, in Insert mode
  • ', – Insert ',
  • Esc – get back to Normal mode again
  • j – Go down one line
  • ^ – Go to the start of the current line
  • q – Stop recording the macro

Then, using command @a I run the macro on the current line. After that, I can just hit @@ to run the macro I previously run.

Recursive macros

Using macros can be even more effective with recursion. Recursive macros are especially useful when you need to act on many lines in a file.

In order to record a recursive macro, you need to start with an empty register. You can make the register a empty by hitting qaq.

Now, let’s see recursive macro in action, with a slightly different example:

 

Let’s see what’s going on here:

  • qa followed by Tab and ' followed by Esc – same as in first example
  • f: – find the first occurrence of : and place cursor on it
  • C – command to delete everything from cursor to the end of the line, and enter Insert mode
  • ', followed by Escj and ^ – same as in the first example: insert ', get to Normal mode, move one line below and jump to beginning
  • @a – this is the key step: while recording a macro in register a, we call it inside itself!
  • q – stop recording the macro
  • @a – now we run the recursive macro – and there you go – magic! :)

 

There’s so much more you can do with macros in Vim!

My colleagues sometimes stare at my screen and wonder wtf is going on, when my hands are even not on the keyboard – and my code is being edited by a macro :D

You can master this magic too!

Get Macros chapter (plus three other!) from my book Mastering Vim Quickly for free.

Get 4 chapters for Free!


If you liked the post, we should get connected - follow me on Twitter