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

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:

  1. Select a column of text with <C-v>
  2. <Esc>, then :%s/\%Vfoo/bar/g
  3. Only foo within that rectangular block is replaced

Tips

  • \%V can appear anywhere in the pattern: /\%V.*error matches lines starting inside the selection that contain error
  • Without \%V, :'<,'>s/old/new/g operates on entire lines — if your block selection covers columns 10–20, the substitution still affects the whole line. \%V fixes this.
  • Combine with \v for readability: /\v\%Vpattern
  • :help /\%V has the full specification

Next

How do I run a search and replace only within a visually selected region?