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

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 /\%V followed by your pattern.
  • \%V is 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/g replaces only inside the visual area. Unlike :'<,'>s which operates on full lines, this respects column boundaries — useful for block (<C-v>) selections.
  • Combine with n/N to navigate all matches inside the selection.
  • Works with complex patterns: /\%V\<word\> restricts whole-word matching to the visual region.

Next

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