How do I make a macro repeat itself until it fails?
Answer
qaq qa...@aq @a
Explanation
A recursive macro calls itself at the end of its recording, causing it to repeat indefinitely until a command inside it fails (like a search hitting the end of the file). This is one of the most powerful macro techniques in Vim — it lets you apply a complex editing sequence to every match in a buffer without counting repetitions.
How it works
qaqclears registerato prevent a stale recursive call during recordingqastarts recording into registera...is your editing sequence — it must include a command that can fail (like/pattern<CR>,n, orj)@acalls registera(itself) recursivelyqstops recording@aexecutes the macro — it runs, then calls itself, runs again, and so on until one of the commands inside fails
Example
Delete every line containing "DEBUG" by searching and deleting:
qaq
qa/DEBUG<CR>dd@aq
@a
The macro searches for the next "DEBUG" line, deletes it, then calls itself. When no more matches exist, the search fails and the macro stops.
Tips
- Always clear the register first with
qaq— otherwise the old macro content executes during recording - The "failure" that stops recursion is any command that produces an error (failed search, movement past end of file, etc.)
- For line-by-line processing, use
jas the failing command — the macro stops at the last line - Prefer
:g/DEBUG/dfor simple cases — recursive macros shine when the editing logic is too complex for:global