How do I create a macro that runs itself repeatedly until it fails?
Answer
qaqqa...@aq
Explanation
A recursive macro calls itself at the end of its recording, creating a loop that repeats until a motion or command fails (like reaching the end of the file or finding no more matches). This eliminates the need to guess a repeat count — the macro simply runs until it can't anymore.
How it works
qaqclears registerafirst (this is critical — without it, a previous recording inawould execute during the recursive call while recording)qastarts recording into registera...is the sequence of commands you want to repeat@acalls the macro recursively — it replays registerafrom within itselfqstops recording- Run the macro with
@aand it loops until a command in the sequence fails
The macro terminates automatically when any command in the sequence encounters an error, such as n finding no more search matches, j hitting the last line, or f{char} finding no match on the current line.
Example
Add quotes around the first word on every line from the current line to the end of the file:
qaqqa0ei"<Esc>bi"<Esc>j@aq
Breaking it down:
qaq— clear registeraqa— start recording0— go to beginning of lineei"<Esc>— go to end of first word, insert a closing quotebi"<Esc>— go to beginning of word, insert an opening quotej— move to next line (fails on the last line, stopping the recursion)@a— call self recursivelyq— stop recording
Given:
hello world
foo bar
baz qux
After running @a:
"hello" world
"foo" bar
"baz" qux
Tips
- Always clear the register first with
qaq— skipping this step is the most common mistake and causes unpredictable behavior - The macro is "self-terminating" — you don't need to count lines or matches
- Use
uto undo the entire recursive run if the result isn't what you expected - Recursive macros are ideal for processing every line in a file, every search match, or every occurrence of a pattern
- For extra safety, set a high but bounded count:
1000@alimits execution to 1000 iterations