How do I search for a pattern only within a visual selection?
Answer
/\%V
Explanation
The \%V pattern atom restricts a search to the region spanned by the last visual selection. After visually selecting text and pressing <Esc>, Vim remembers the selection boundaries via the '< and '> marks — \%V uses those marks to filter matches.
How it works
- Select text with
v,V, or<C-v>, then press<Esc>to preserve the selection boundaries. - Start a search with
/\%Vfollowed by your pattern. \%Vis a zero-width assertion that matches only at positions inside the last visual area.- The
'<and'>marks persist until a new selection is made, so you can search multiple times.
Example
Given three lines:
function foo(): alpha beta
function bar(): alpha delta
function baz(): alpha omega
Visually select lines 1–2 with V, press <Esc>, then type:
/\%Valpha
Vim cycles through alpha on lines 1 and 2, skipping line 3 entirely.
Tips
- Use with substitution:
:%s/\%Vold/new/greplaces only inside the visual area. Unlike:'<,'>swhich operates on full lines, this respects column boundaries — useful for block (<C-v>) selections. - Combine with
n/Nto navigate all matches inside the selection. - Works with complex patterns:
/\%V\<word\>restricts whole-word matching to the visual region.