How do I create a macro that repeats itself automatically until there is nothing left to process?
Answer
qq{commands}@qq
Explanation
A recursive macro calls itself at the end of its own definition, causing it to run repeatedly until Vim hits an error — such as reaching the end of the file or a failed motion — which silently terminates execution. This eliminates the need to prefix @q with a count and makes macros self-limiting by nature.
How it works
qqq— record an empty macro to registerq, clearing any previous contentqq— start recording a new macro into registerq{commands}— the operations you want to repeat@q— call registerqrecursively before stoppingq— stop recording
On playback, @q runs the macro, which reaches @q again at the end and reruns itself. When a command fails (e.g., j at the last line), Vim aborts the recursion silently.
Example
To prepend - to every line in a file:
apple
banana
cherry
Record: qqqqqI- <Esc>j@qq then execute with @q.
Result:
- apple
- banana
- cherry
The macro fails on the j after the last line and stops cleanly.
Tips
- Always start with
qqqto empty the register before recording — otherwise leftover content from a previous recording may corrupt the recursion - The termination condition must naturally produce an error; if your commands never fail, the macro loops forever
- Use
:set lazyredrawbefore running for a significant speed boost on large files - Works identically with any letter register, not just
q