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

How do I repeatedly run a macro while a pattern is still found in the buffer?

Answer

:while search('TODO') | normal! @q | endwhile

Explanation

A fixed count like 100@q is brittle: sometimes your macro needs 12 passes, sometimes 300, and over-running can corrupt already-processed text. A :while loop tied to search() lets Vim stop naturally when there are no more targets. This is a safer pattern for large cleanup passes where macro termination should be data-driven, not count-driven.

How it works

  • search('TODO') moves to the next match and returns non-zero when found
  • :while ... | ... | endwhile repeats as long as the condition stays true
  • normal! @q replays macro register q without user mappings interfering
  • Once search() returns 0, the loop exits automatically

This workflow is ideal when your macro edits each matching line similarly, such as expanding placeholders, normalizing comments, or changing marker prefixes.

Example

TODO alpha
TODO beta
DONE gamma
TODO delta

Suppose macro q transforms TODO into DONE . Running:

:while search('TODO') | normal! @q | endwhile

produces:

DONE alpha
DONE beta
DONE gamma
DONE delta

Tips

  • Start from the top with gg if you need full-buffer coverage
  • Use a stricter pattern (for example '^TODO\s') to avoid accidental matches
  • Add :keepjumps before normal! if you want to minimize jumplist noise during bulk replay

Next

How do I restrict keyword completion to current buffer, windows, buffers, and tags for predictable results?