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

How do I run a macro as many times as needed until it hits an error and stops automatically in Vim?

Answer

1000@q

Explanation

Vim macros stop executing the moment any step in the macro causes an error — a failed search, a motion that cannot proceed, or a substitution with no matches. By running a macro with a large count like 1000@q, you can let this error-based stopping do the work: the macro repeats until it genuinely can't continue, without you having to predict the right number of iterations in advance.

How it works

  • 1000 — a count large enough to cover any realistic file (adjust upward for very large files)
  • @q — execute the macro stored in register q
  • Vim automatically aborts the entire count when the macro encounters its first error, such as when /pattern finds no more matches or n wraps and returns to the start

Example

Suppose register q contains n"_dd (find next match, delete the line). Running:

1000@q

Deletes every line containing the search pattern, stopping automatically when there are no more matches — no recursive macro required.

Tips

  • Prefer this technique over recursive macros (qq{cmds}@qq) when the macro is already recorded and you want a simple re-run strategy
  • Set set nowrapscan to prevent the search from cycling back to the top — otherwise the macro will loop forever through the file
  • Use @@ to re-run the same macro with the same count if you need to repeat the operation later
  • If the macro stops earlier than expected, check whether an intermediate step is failing silently — prefix uncertain motions with :silent! in complex macros

Next

How do I define custom fold marker strings instead of the default {{{ }}} in Vim?