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

How do I create a macro that runs itself repeatedly until it fails?

Answer

qaqqa...@aq

Explanation

A recursive macro calls itself at the end of its recording, creating a loop that repeats until a motion or command fails (like reaching the end of the file or finding no more matches). This eliminates the need to guess a repeat count — the macro simply runs until it can't anymore.

How it works

  • qaq clears register a first (this is critical — without it, a previous recording in a would execute during the recursive call while recording)
  • qa starts recording into register a
  • ... is the sequence of commands you want to repeat
  • @a calls the macro recursively — it replays register a from within itself
  • q stops recording
  • Run the macro with @a and it loops until a command in the sequence fails

The macro terminates automatically when any command in the sequence encounters an error, such as n finding no more search matches, j hitting the last line, or f{char} finding no match on the current line.

Example

Add quotes around the first word on every line from the current line to the end of the file:

qaqqa0ei"<Esc>bi"<Esc>j@aq

Breaking it down:

  • qaq — clear register a
  • qa — start recording
  • 0 — go to beginning of line
  • ei"<Esc> — go to end of first word, insert a closing quote
  • bi"<Esc> — go to beginning of word, insert an opening quote
  • j — move to next line (fails on the last line, stopping the recursion)
  • @a — call self recursively
  • q — stop recording

Given:

hello world
foo bar
baz qux

After running @a:

"hello" world
"foo" bar
"baz" qux

Tips

  • Always clear the register first with qaq — skipping this step is the most common mistake and causes unpredictable behavior
  • The macro is "self-terminating" — you don't need to count lines or matches
  • Use u to undo the entire recursive run if the result isn't what you expected
  • Recursive macros are ideal for processing every line in a file, every search match, or every occurrence of a pattern
  • For extra safety, set a high but bounded count: 1000@a limits execution to 1000 iterations

Next

How do I edit multiple lines at once using multiple cursors in Vim?