How do I run a macro on only the lines I've visually selected?
Answer
:'<,'>norm @q
Explanation
When you visually select lines and then type a : command, Vim automatically inserts '<,'> (the visual range marks) into the command line. Combining this with :norm @q lets you apply a recorded macro (q) to only the selected lines, rather than repeating it a fixed number of times with N@q. This is perfect when you need to transform a specific, non-contiguous or irregular set of lines.
How it works
- Record a macro into register
q:qq ... q - Visually select the lines you want to transform:
Vthenj/k - Press
:— the command line shows:'<,'> - Type
norm @qand press<CR> - Vim runs
@q(execute macro from registerq) on each line in the selection
Example
Macro in q: ^Isprintf("<Esc>A");<Esc> (wraps a word with sprintf("..."))
Before (lines 3–7 selected):
error_message
warning_text
info_log
After :'<,'>norm @q:
sprintf("error_message");
sprintf("warning_text");
sprintf("info_log");
Tips
- You can use any register:
:'<,'>norm @afor macro ina - To run the last used macro, use
@@::'<,'>norm @@ - This technique also works with a line range:
:5,12norm @q - Compare with
N@q(count-based repeat) — range-based is more precise when you can't easily count the lines