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

How do I run a substitution only within the exact characters of my visual selection?

Answer

:%s/\%Vpattern/replacement/g

Explanation

The \%V atom restricts a regex match to the last visual selection — more precisely than :'<,'>s/..., which operates on whole lines. With \%V, the substitution only affects characters that were inside the visual selection, letting you replace in the middle of lines without touching surrounding text.

How it works

  1. Make a visual selection (characterwise v, linewise V, or blockwise <C-v>)
  2. Press <Esc> to exit visual mode (the selection is preserved as '< and '>)
  3. Run the substitution with \%V in the pattern:
:%s/\%Vpattern/replacement/g

The % range covers the whole file, but \%V inside the regex causes matches to be skipped if they fall outside the visual selection boundaries.

Example

Given this line, with only the middle word visually selected:

foo bar baz
    ^^^

Running :%s/\%Va/X/g changes only the a inside the selection:

foo bXr baz

Without \%V, all three a characters across the file would be affected.

Tips

  • You can also scope with :'<,'>s/\%Vpattern/replacement/g to limit both by line range and visual boundaries
  • Works with all visual selection types: characterwise, linewise, and blockwise
  • The \%V atom matches zero-width, so it can be placed at the start of the pattern or between atoms
  • Use \%>'< and \%<'> as lower-level alternatives to bracket the selection manually

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?