vimtricks.wiki Concise Vim tricks, one at a time.

How do I run a normal-mode append on only matching lines inside a visual selection?

Answer

:'<,'>g/let /normal! A;<CR>

Explanation

When you need a structural edit in part of a file, Visual mode ranges combine well with :global and :normal!. :'<,'>g/let /normal! A;<CR> appends a semicolon only on selected lines that contain let .

This is a strong workflow for refactors where a whole-file command would be risky. You constrain the scope first (Visual selection), then filter lines by pattern, then execute a precise Normal-mode action on each match.

How it works

  • :'<,'> targets the current Visual selection as an Ex range
  • g/let / keeps only lines in that range matching let
  • normal! A; runs A; on each matching line (A moves to end of line and inserts ;)

Using normal! is important: it ignores custom mappings, so behavior is predictable in scripts and ad-hoc bulk edits.

Example

Selected region:

let port = 8080
const host = "localhost"
let retries = 3

Run:

:'<,'>g/let /normal! A;<CR>

Result:

let port = 8080;
const host = "localhost"
let retries = 3;

Tips

  • Replace let with language-specific patterns like ^\s*if or \.spec
  • Swap A; for any Normal command sequence, e.g. I// to prefix comments
  • Add j to the pattern (/let /j) if you want to skip the current line

Next

How do I run one substitution in nomagic mode so most regex characters are literal?