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

How do I apply a macro to every line in a visual selection?

Answer

:'<,'>normal @q

Explanation

The :'<,'>normal @q command runs macro q on every line of the visual selection. This combines the power of macros with visual mode ranges.

How it works

  1. Select lines with V and motions
  2. Press : (auto-fills '<,'>)
  3. Type normal @q (where q is your macro register)
  4. Press Enter — the macro runs on each selected line

Example

Record a macro q that wraps a line in <li> tags: qa0i<li><Esc>A</li><Esc>q

Select 5 lines, then :'<,'>normal @q wraps all of them.

Tips

  • Use normal! to ignore user mappings
  • This is safer than recursive macros for bounded operations
  • Works with any macro register (a-z)
  • :g/pattern/normal @q runs the macro on all matching lines
  • The macro should ideally work on a single line without jumping

Next

How do you yank a single word into a named register?