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 inprint(...). - 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#Dstrips trailing comments and leaves comment-free lines untouched. It also leaves the space before the#, so follow up with:%s/\s\+$//if that matters. :normaluses your mappings. If you have remappedIorA, the replay uses your version. Write:norm!to run vim’s built-in keys and ignore mappings.- Everything after
normis 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 singleurestores 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.