How do I search for text only within a visual selection?
Answer
/\%Vpattern
Explanation
The \%V atom restricts a search pattern to only match inside the most recent visual selection. This lets you perform targeted searches and substitutions within a highlighted block of text, ignoring everything else in the file.
How it works
- First, make a visual selection and press
<Esc>to leave visual mode (the selection boundaries are remembered as'<and'>) - Start a search with
/and include\%Vin your pattern \%Vtells Vim to only match text that falls within the previous visual selection- Matches outside the selection are completely ignored
Example
Given the text:
foo bar baz
foo bar baz
foo bar baz
foo bar baz
Visually select lines 2 and 3 with 2GVj<Esc>. Now search with /\%Vfoo — only the foo on lines 2 and 3 are highlighted and matched. The foo on lines 1 and 4 are ignored.
This is especially powerful with substitution:
:'<,'>s/\%Vfoo/FOO/g
This replaces foo with FOO only within the previously selected area — critical for visual block selections where you don't want to affect the entire line.
Tips
- Without
\%V, a substitute on'<,'>still operates on the full lines that overlap the selection —\%Vrestricts it to the exact visual area, which matters in block selections - Place
\%Vat both ends for strictest matching:/\%Vpattern\%Vensures the entire match is within the selection - Works with all visual modes: characterwise (
v), linewise (V), and blockwise (<C-v>) - Combine with other search atoms:
/\%V\<word\>for whole-word search within the selection - You can use
\%Vinside:gcommands too::g/\%Vpattern/ddeletes only lines with matches inside the visual area