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

How do I make a macro run repeatedly until it reaches the end of the file or encounters an error?

Answer

qaqqa{actions}@aq@a

Explanation

A recursive macro is a macro that calls itself at the end of its recording. When executed, it repeats indefinitely until a motion fails (like j at the last line or n with no more matches), which causes the entire macro chain to stop. This is a powerful technique for applying repetitive edits across an unknown number of lines or matches without counting them first.

How it works

  • qaq — clears register a first (important to avoid leftover content from a previous recording)
  • qa — starts recording into register a
  • {actions} — the editing operations you want to repeat (e.g., transform a line, then move to the next)
  • @a — the recursive call: the macro invokes itself
  • q — stops recording
  • @a — runs the macro, which will repeat until a motion error breaks the chain

Example

Surround every line in the file with quotes. Start on line 1:

qaqqa0i"<Esc>A"<Esc>j@aq@a
Before:         After:
hello            "hello"
world            "world"
foo              "foo"

The macro inserts " at the beginning and end of each line, moves down with j, then calls itself. When j fails on the last line, the recursion stops.

Tips

  • Always clear the register first with qaq — if register a already contains a macro, the self-reference during recording would execute the old content
  • The macro stops on any failed motion: j, n, w past end of file, f{char} with no match, etc.
  • For large files, this is faster than :%norm because it lets you use complex multi-step operations that norm cannot express easily
  • You can also use a count: 1000@a as a simpler alternative, but recursive macros are more elegant and stop precisely when needed

Next

How do I return to normal mode from absolutely any mode in Vim?