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
\%Vin the pattern to constrain matching to that exact region \%Vacts 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:
/\%Vwordhighlights the pattern only within the last visual selection - Combine with
\%land\%cfor even finer column or line constraints - In Neovim, this behaviour is identical —
\%Vis part of the Vim regex engine shared by both