How do I apply a normal mode command to every line in a range at once?
Answer
:norm
Explanation
:normal (abbreviated :norm) executes a sequence of normal-mode keystrokes on each line of an address range. It's one of Vim's most powerful batch-editing tools, letting you drive arbitrary normal-mode operations — including motions, operators, and macros — across a selection of lines without recording a dedicated macro.
How it works
:norm takes the form :[range]norm[al] {commands}, where {commands} is the same sequence of keys you'd type in normal mode:
:%norm A; " append a semicolon to every line in the file
:5,15norm >> " indent lines 5–15 two levels
:'<,'>norm 0dt: " on each selected line, go to col 1 and delete to first ':'
:%norm @q " replay macro q on every line (like :g but simpler)
- Ranges work just like any other Ex command:
%for all lines,'<,'>for visual,1,10for a line span - To include literal
<Esc>,<CR>, or other special keys, type them with<C-v>{key}when entering the command - Each line starts with the cursor at the beginning of that line
Example
Given a list of bare CSS properties:
color: red
font-size: 14px
margin: 0
Running :%norm A; appends a semicolon to every line:
color: red;
font-size: 14px;
margin: 0;
Tips
:norm!uses the default key mappings, bypassing any remaps — useful in plugins or scripts- Combining
:g/pattern/norm {cmd}lets you target specific lines::g/TODO/norm A // FIXME - The command is idempotent when paired with idempotent normal-mode actions