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 the cursor in the beginning of the line 'bark': 'dog':

Let's record the macro into register b. First, we'll need to flush it and enter macro recording mode: qbqqb (qbq empties register b, and qb enters macro recording mode).

Now, as we want to swap bark and dog, we could yank one of these words into some temporary register (say c), and then move dog over using the default register.

Let's go ahead: "cdi' (delete inside single quotes into buffer c):

Move over 'dog' (W) and run di' to yank dog into the default register:

Move one character to the left (either with h or b) and insert the word bark from register c ("cp):

Now, move back to the beginning of the line (_) and paste dog from the default register (p):

Almost there! Go down one line (j), and move your cursor to the beginning of the line (_):

Now, replay macro b: @b. Nothing will happen, since register b is still empty. Finish recording the macro (q).

Now replay the macro using @b once, and it will iterate through every line in your file:

That's it! You can make any macro recursive by appending to the register. To append to a register, you use the uppercase version of the register identifier. For example, if you wanted to make a macro in a register b recursive, run qB@bq to append @b to the end of the macro.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.142.146