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

How do I run a macro only between two marks without entering Visual mode?

Answer

:'a,'bnormal! @q<CR>

Explanation

When you need to replay a macro on a precise region, selecting lines manually can be slow and error-prone. A mark range lets you target exactly the lines you want, then apply the macro in one Ex command. This is particularly useful in long files where the region is far apart or when you want a repeatable, script-like workflow.

How it works

  • 'a,'b is an Ex range from mark a through mark b
  • normal! executes raw Normal-mode keys (ignoring mappings)
  • @q replays macro register q once per addressed line

Set marks first (for example with ma and mb), then run the command. Because it is range-based, you can repeat it later without reselecting text.

Example

Assume your macro in q appends ; to the end of a line.

alpha
beta
gamma
delta

Set marks on beta (ma) and gamma (mb), then run:

:'a,'bnormal! @q

Result:

alpha
beta;
gamma;
delta

Only the marked range is affected.

Tips

  • Use :marks to confirm mark positions before running bulk edits
  • Prefer normal! over normal so custom mappings cannot alter macro playback
  • Combine with :undojoin in scripts when multiple range operations should undo atomically

Next

How do I add another project-wide pattern search without replacing my current quickfix results?