How do I run the same normal mode command on every line in a range?
Answer
:'<,'>norm {commands}
Explanation
The :normal (or :norm) command lets you execute normal mode keystrokes from the command line. When combined with a range, it runs those keystrokes on every line in the range, making it a powerful tool for repetitive edits without recording a macro.
How it works
- Select lines in visual mode, then type
:which prefills:'<,'> - Append
normfollowed by the normal mode commands you want to run - Vim executes those commands on each line in the range independently, as if you pressed them with the cursor at the beginning of each line
Example
Given the text:
alpha
beta
gamma
delta
Select all four lines in visual mode and run :'<,'>norm A; to append a semicolon to every line:
alpha;
beta;
gamma;
delta;
Or prepend // to comment out each line: :'<,'>norm I//
// alpha;
// beta;
// gamma;
// delta;
Tips
- Use
:%normto apply the command to every line in the file normdoes not recognize special keys like<Esc>as literal text — usenorm!withexecuteif you need special keys, or use<C-v><Esc>to insert a literal escape characternorm!(with the bang) ignores user-defined mappings, using only default Vim behavior — this is safer in scripts- Combine with
:gfor even more power::g/TODO/norm ^dwA (done)modifies only lines matching a pattern - You can run complex sequences:
:'<,'>norm 0f=lC0deletes from after=to the end on each line - This is often faster than recording a macro for simple repetitive edits