How do I create a self-referential recursive macro that repeats until it fails?
Answer
qqq then qq{commands}@qq
Explanation
A recursive macro in Vim calls itself at the end of its body, repeating automatically until one of its commands fails. This lets you process an unbounded number of items without knowing the count in advance — the macro stops naturally when it hits a dead end, such as no more search matches or the cursor reaching end of file.
How it works
qqq— clears registerqso the initial@qat the end of the recording is a no-op (not a leftover macro)qq— starts recording into registerq{your commands}— the operations to perform on each iteration@q— the recursive call; Vim invokes the macro again, which will halt automatically when any command in the body failsq— stops recording
Once recorded, trigger the loop with @q. It runs until failure, then stops silently.
Example
Delete the first word from every line until end of file:
qqq " clear register q
qqdw0j@qq " record: delete word, go to col 0, move down, recurse
@q " start the loop
The macro runs until j fails on the last line, at which point the chain halts.
Tips
- The stop condition is implicit — any failed command (motion, search, substitution) breaks the chain
- Use
nnoremapin a wrapper to run it safely, or prefix with:silentto suppress error messages::silent! normal @q - If the macro is getting stuck in an infinite loop, press
<C-c>to interrupt - For a known repeat count,
{N}@qis simpler — but the recursive pattern shines when the count is unknown