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
- Select lines with
Vand motions - Press
:(auto-fills'<,'>) - Type
normal @q(whereqis your macro register) - 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 @qruns the macro on all matching lines- The macro should ideally work on a single line without jumping