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

How do I limit a search or substitution to only the text I visually selected?

Answer

\%V

Explanation

The \%V atom in a Vim pattern matches only inside the last visual selection. By embedding \%V in a search or substitute command, you can restrict matches to exactly what you highlighted — even after you've left Visual mode.

How it works

  • \%V is a zero-width match atom that succeeds only at positions inside the most-recently-made visual selection (the area between '< and '>)
  • Because the visual marks '< and '> persist after leaving Visual mode, \%V keeps working in subsequent commands
  • Combine it with :%s to replace only within the selection, or with / to highlight only selected occurrences

Example

Suppose you have the buffer:

error: file not found
warning: file permissions denied
info: file opened successfully

Visually select the first two lines with Vj, then return to Normal mode. Now run:

:%s/\%Vfile/FILE/g

Result:

error: FILE not found
warning: FILE permissions denied
info: file opened successfully

The word file on the third line is untouched because it is outside the visual selection.

Tips

  • You can also use \%V in a plain search: /\%Vpattern — only matches inside the selection will be highlighted
  • Pair with n / N to cycle through matches confined to the selected region
  • The trick works with character-wise, line-wise, and block-wise selections

Next

How do I complete identifiers using ctags from within insert mode?