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

How do I restrict a search or substitution to exactly the characters I visually selected?

Answer

\%V (in search/substitute pattern)

Explanation

The \%V atom in a Vim pattern matches only inside the last visual selection. Unlike a line-range like '<,'>, which operates on entire lines, \%V is character-precise — perfect for column-wise or character-wise selections where you only want to touch specific columns or partial lines.

How it works

  • Make a visual selection (any mode: v, V, or <C-v>)
  • Exit visual mode with <Esc> — Vim remembers the selection as '< and '>
  • In a search or substitute command, include \%V in the pattern to constrain matching to that exact region
  • \%V acts as a zero-width assertion: it does not consume characters, it just enforces that the match starts inside the selection

Example

Given these two lines where you block-selected only the middle columns:

foo BAR baz
foo BAR baz

After selecting BAR on both lines with <C-v> and running:

:'<,'>s/\%VBAR/QUX/g

Result:

foo QUX baz
foo QUX baz

Without \%V, the substitute range '<,'> would still operate on whole lines. \%V ensures only the selected columns are matched.

Tips

  • Works in plain search too: /\%Vword highlights the pattern only within the last visual selection
  • Combine with \%l and \%c for even finer column or line constraints
  • In Neovim, this behaviour is identical — \%V is part of the Vim regex engine shared by both

Next

How do I rename a variable across all its case variants (camelCase, snake_case, SCREAMING_CASE) in one command?