How do I make a macro run repeatedly until it reaches the end of the file or encounters an error?
Answer
qaqqa{actions}@aq@a
Explanation
A recursive macro is a macro that calls itself at the end of its recording. When executed, it repeats indefinitely until a motion fails (like j at the last line or n with no more matches), which causes the entire macro chain to stop. This is a powerful technique for applying repetitive edits across an unknown number of lines or matches without counting them first.
How it works
qaq— clears registerafirst (important to avoid leftover content from a previous recording)qa— starts recording into registera{actions}— the editing operations you want to repeat (e.g., transform a line, then move to the next)@a— the recursive call: the macro invokes itselfq— stops recording@a— runs the macro, which will repeat until a motion error breaks the chain
Example
Surround every line in the file with quotes. Start on line 1:
qaqqa0i"<Esc>A"<Esc>j@aq@a
Before: After:
hello "hello"
world "world"
foo "foo"
The macro inserts " at the beginning and end of each line, moves down with j, then calls itself. When j fails on the last line, the recursion stops.
Tips
- Always clear the register first with
qaq— if registeraalready contains a macro, the self-reference during recording would execute the old content - The macro stops on any failed motion:
j,n,wpast end of file,f{char}with no match, etc. - For large files, this is faster than
:%normbecause it lets you use complex multi-step operations thatnormcannot express easily - You can also use a count:
1000@aas a simpler alternative, but recursive macros are more elegant and stop precisely when needed