brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Vim's :%norm runs the same normal-mode keys on every line

Vim
~/tips/tip-vim-normal-range-every-line

:%norm A;

Repeats a set of normal-mode keystrokes on every line in a range.

Say you want a semicolon at the end of forty lines. You could record a macro, but my advice is to skip that and type one Ex command. :normal runs normal-mode keys as if you typed them, and with a range in front it does that once per line.

:%norm A;

% means the whole file, norm is short for :normal, and A; is what you would type by hand: append at the end of the line, then a semicolon. You don’t need to press Escape. When the keys leave a command unfinished, Vim ends it as if you had pressed Escape, so the insert simply stops.

Before each line Vim puts the cursor in the first column, which makes I and 0 predictable. Any range works. To comment out lines 10 to 20 of a shell script:

:10,20norm I# 

Select some lines in visual mode and type :, and Vim fills in '<,'> for you, so :'<,'>norm A, works on just the selection. It pairs nicely with a recorded macro too: :%norm @q plays register q on every line.

A few things to know. Use :norm! if you have mappings that might get in the way, because the ! makes Vim ignore them. You can’t put | and a second command after it, since Vim treats the bar as part of the keys. The keys can’t start with a space either; the help suggests a count of 1 in front if you really need one. The screen doesn’t redraw while it runs, so on a big file it can look frozen for a moment.

Further reading: Vim help: :normal

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link