How do I create a self-repeating macro that runs until there is nothing left to process?
Answer
@q (inside macro recording)
Explanation
A recursive macro calls itself as its last action, causing it to repeat indefinitely until it hits an error (like reaching end of file or failing a search). This is a powerful technique for processing every line, match, or occurrence in a file without needing to know the count in advance.
How it works
The trick relies on two properties:
- When you start recording into register
qwithqq, the register is cleared at the start. Any existing@qinside the macro body will call the empty register (a no-op) the first time — which is why you must populateqviaqqthen include@qat the end. - When the macro encounters an error (e.g., search fails, motion hits buffer boundary), Vim aborts the macro chain — cleanly stopping recursion.
Recording sequence:
qq " start recording into register q (clears q first)
{your commands} " the action to repeat
@q " recurse: call q from inside q
q " stop recording
@q " trigger the macro — it will run until an error stops it
Example
Delete every blank line in the file:
qq " start recording
/^$<CR> " find next blank line
dd " delete it
@q " recurse
q " stop recording
@q " run — stops automatically when no blank lines remain
Tips
- The macro must make forward progress on each iteration, or it will loop forever (no error to stop it)
- Use
jor a search to advance the cursor between iterations - For a fixed count,
10@qis simpler — use recursion only when the count is unknown :[range]normal @qapplies the macro to a range without recursion (often cleaner for line-by-line work)