vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. qqq — record an empty macro to register q, clearing any previous content
  2. qq — start recording a new macro into register q
  3. {commands} — the operations you want to repeat
  4. @q — call register q recursively before stopping
  5. q — 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 qqq to 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 lazyredraw before running for a significant speed boost on large files
  • Works identically with any letter register, not just q

Next

How do I navigate quickfix entries, buffers, and conflicts with consistent bracket mappings?