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
\%Vis 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,\%Vkeeps working in subsequent commands - Combine it with
:%sto 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
\%Vin a plain search:/\%Vpattern— only matches inside the selection will be highlighted - Pair with
n/Nto cycle through matches confined to the selected region - The trick works with character-wise, line-wise, and block-wise selections