O'Reilly logo

Mastering Vim by Ruslan Osipov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Recursive macros

Earlier we ran macros multiple times by prefixing @ with a number. That's not very computer science-like, and we can do better.

Vim supports recursive macros, but there are a few quirks to be aware of.

First, you'll need to make sure the register you will be recording to is empty. You can do this by entering macro recording mode, and immediately exiting it. For instance, if you wanted to empty register b, you'll run qbq to clear it.

Then, record your macro as usual, and insert that same register into itself (for example, by using @b).

Let's say we wanted to swap keys with values in a Python dictionary:

animal_noises = {    'bark': 'dog',    'meow': 'cat',    'silence': 'dogfish',}

We could record a macro as follows, starting with ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required