Vim Search Visual Selection
You can search within a visual selection in Vim by using a special escape sequence in your pattern. Vim calls these “atoms” and for more info you can check the help docs: :help atom
and :help ordinary-atom
.
When might this be useful? Sometimes I want to search for a string only in the current method. Using this feature I can be sure I’m searching only in the area of the code I’m intending to and won’t be bounced all around the file.
To utilize, first visually select some region of text. I can do that manually with shift-V
and then j
and k
to choose lines. But in my most common case I will use a command like vap
to visually select around the current paragraph. (And make sure you know how to edit a visual selection — one of our most popular tips.)
Once you’ve selected something, press Esc
to exit selection mode. Then search using /
and use \%V
to indicate to Vim that you want to only search the last visual selection.
For example: /\%Vfoobar
will search the last visual selection for foobar
.
There’s a brief demo of searching in a visual selection below. First, I select around the current method with vap
. Then I search for request
in that method by using /\%Vrequest
.
(For this demo, I set my highlight color to yellow so it would stand out using the following: :hi Search ctermbg=Yellow ctermfg=Black
.)
How do I search within a visual selection in Vim?
You can search within the last visual selection in Vim by using the \%V
escape sequence inside your pattern. Just search for a word or phrase but prepend that sequence like so:
/\%Vfoobar
and Vim will restrict its search only to the last visually selected area of text.
When is Vim visual selection search useful?
Because a visual selection can extend to any area of text, there are many cases when you might be searching only in a visual selection. But one common use case is searching inside a method, which you can often select with vap
(visually select around paragraph).
Can't I just visually select in Vim and then use / to search?
No, when you are in visual selection mode in Vim, using /
will extend your search area to the next match, meaning you can't just select and highlight text and then search within it. You first have to stop visually selecting with Esc
and then search and use \%V
to match within the last visual selection.
What are the %V Vim docs?
Match inside the Visual area. When Visual mode has already been stopped match in the area that gv
would reselect. This is a /zero-width
match. To make sure the whole pattern is inside the Visual area put it at the start and just before the end of
the pattern, e.g.:
/\%Vfoo.*ba\%Vr
This also works if only "foo bar" was Visually selected. This:
/\%Vfoo.*bar\%V
would match "foo bar" if the Visual selection continues after the "r". Only works for the current buffer.