How do I restrict a search to only match within a previously selected visual area?
Answer
/%Vpattern
Explanation
The \%V atom in a Vim search pattern restricts matches to text that falls inside the last visual selection. Unlike :'<,'>s/ which operates on whole lines, \%V is character-precise — it only matches within the exact columns that were selected.
How it works
- Make a visual selection (character, line, or block mode)
- Press
<Esc>to leave visual mode - Search with:
/\%Vpattern - Only occurrences within the previously selected area will match
Example
Select a paragraph with vip, then <Esc>:
/\%Verror
Highlights only error occurrences inside that paragraph — not elsewhere in the file.
Combine with substitution for precise replacements:
:%s/\%Vold/new/g
Replaces old with new only within the visual area (character-precise, not just the line range).
Visual block precision
\%V is especially powerful with <C-v> block selections:
- Select a column of text with
<C-v> <Esc>, then:%s/\%Vfoo/bar/g- Only
foowithin that rectangular block is replaced
Tips
\%Vcan appear anywhere in the pattern:/\%V.*errormatches lines starting inside the selection that containerror- Without
\%V,:'<,'>s/old/new/goperates on entire lines — if your block selection covers columns 10–20, the substitution still affects the whole line.\%Vfixes this. - Combine with
\vfor readability:/\v\%Vpattern :help /\%Vhas the full specification