← back to latest

Run the same edit on every selected line, wherever each line starts

VISUAL:'<,'>norm I# Run the same edit on every selected line, wherever each line starts

anatomy

:
From visual mode, opens the command line with the range already filled in. You type only what comes after it.
'<,'>
The range vim inserts for you: from the first line of the selection to the last. Every selected line gets the command, one at a time.
norm
Short for :normal. Runs the rest of the line as normal-mode keystrokes, as if you typed them, once for each line in the range with the cursor placed at the start of that line.
I
Insert before the first non-blank character. Because it runs separately on each line, it finds each line's own indentation.
#
The text to insert, including the trailing space. Insert mode ends automatically when the keystrokes run out, so no Escape is needed.

In the buffer

Before:

def retry(fn, attempts=3):
    for i in range(attempts):
    ^
        try:
            return fn()
        except TimeoutError:
            log.warning("retry %d", i)
    raise RuntimeError("gave up")

After typing V4j to select the loop, then :norm I# and Enter (vim fills in '<,'> when you press :):

def retry(fn, attempts=3):
    # for i in range(attempts):
        # try:
            # return fn()
        # except TimeoutError:
            # log.warning("retry %d", i)
             ^
    raise RuntimeError("gave up")

Each line gets its # at its own indentation level. The cursor ends on the last line of the range, where the final insert left it.

When you would reach for it

You need to make the same small edit on a handful of lines, but the lines do not line up. Block-visual I inserts at one fixed column, so on code with mixed indentation the comment markers land in the wrong place or in the middle of whitespace. A macro would work, but recording one for a single pass is overkill. :norm takes whatever keystrokes you would have typed on one line and replays them on each selected line, starting fresh from the beginning of every line, so motions like I, A, f, and w adapt to each line’s contents.

Gotchas

  • Insert mode ends on its own when the keystrokes run out, but you cannot type a literal Escape in the middle. To leave insert mode partway through, press <C-v><Esc> on the command line, which inserts a raw ^[ character. :%norm Iprint(<C-v><Esc>A) wraps every line in print(...).
  • If a keystroke fails on a line, such as f# on a line with no #, vim abandons the rest of the keystrokes for that line and moves on to the next one. :%norm f#D strips trailing comments and leaves comment-free lines untouched. It also leaves the space before the #, so follow up with :%s/\s\+$// if that matters.
  • :normal uses your mappings. If you have remapped I or A, the replay uses your version. Write :norm! to run vim’s built-in keys and ignore mappings.
  • Everything after norm is keystrokes, including | and trailing spaces. You cannot chain another Ex command after it with |, and a trailing space you meant to type disappears without a trace when someone copies the command. The whole run is still one undo step: a single u restores every line.

Variants

let width = 80;
let height = 24
let depth = 3
let width = 80;
let height = 24;
let depth = 3;

A; on the first line, then Vj on the other two and :'<,'>norm .: the dot command repeats your last change once per selected line. Make the edit once by hand, then broadcast it.

        except TimeoutError:
            log.warning("retry %d", i)
    raise RuntimeError("gave up")
        except TimeoutError:
            # log.warning("retry %d", i)
    raise RuntimeError("gave up")

:g/log\./norm I# : the global command supplies the lines instead of a selection. Only lines matching the pattern get commented, wherever they are in the file.

total
count
total / count
print(total)
print(count)
print(total / count)

:%norm Iprint(<C-v><Esc>A): with % as the range there is no selection at all. The <C-v><Esc> leaves insert mode midway so A can append the closing parenthesis.

lineage

Vi had no way to replay normal-mode keystrokes from the command line; its Ex commands and its visual commands lived in separate worlds. Vim added :normal to bridge them, which is also why scripts and mappings can drive normal-mode commands. Visual mode supplies the range, :normal supplies the edit, and the pairing turns any keystroke sequence you already know into a batch operation.

-- INSERT --vim-hacks.com035-035-run-a-normal-command-on-every-selected-line.html
utf-81,1All