How to search for selected text in Vim?

I'm aware that I can use / followed by a regex to search something. And I can use ? to search backwards. And I can use n and N to repeat the search forward and backward.

There are also two nice shortcuts: * or # will search for the word under the cursor (forward/backward). That's very useful! (there are also g* and g# variants)

But... Once I've selected text using visual mode (v), how can I ask Vim to search for exactly that text? A quick look at :help did not... huh... help me.


The following sequence will do what you want, given an already selected block of text:

  • y (yank the selected text, into the " register by default)
  • / (enter search mode)
  • (\ V) (optional, enter "very no magic" mode*)
  • Ctrl+r " (insert text from " register)
  • Enter (Engage!)

(*) "very no magic" mode interprets the following text as plain text instead of as a regex. note however that \ and / are still special and will have to be handled in other ways. If the text does not have any characters considered special, you can skip this step.

Source: Vim Tips Wiki


You can yank the hightlighted text first. Then

  • /

  • Ctrlr

  • "

Which will paste what you have yanked after the /.


I never felt the need for such a feature but, considering you can find a need for any feature on Vim, I think this from the Vim Wiki should help:

vnoremap // y/\V<C-R>=escape(@",'/\')<CR><CR>

I didn't test it but, looking at the code, it seems to be exactly what you're searching for.


You can find a method to create this behavior here at the vim wiki.