0

Suppose I have selected a word in visual mode. Now I want to search that word in the document.

How can I do that?

Thanks in advance.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
prime
  • 435
  • 2
  • 4
  • 6

4 Answers4

7

If it's just a single word, you don't even have to select it. Just place the cursor on the word and press * (or # to search backwards). Note that this search will only match the whole word. To allow a search for foo to match foobar, use g* or g#.

hammar
  • 138,522
  • 17
  • 304
  • 385
3

Press y (you'll exit from visual mode after that) then press / Ctrl+r then " end hit enter.

You can use it to bind // for this action:

:vmap // y/<C-R>"<CR>

If you select special chars you better use this

:vmap <silent> // y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>
Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
hadvig
  • 1,096
  • 10
  • 20
  • This is a quick and dirty fix, but you'll only be able to depend on it for the simplest cases, because Vim's search field treats many characters as special (For example: the `.` character stands for anything, and `<`, `(` and `[` brackets all have special meanings). Handling the special cases requires a little bit of Vimscript, so you're better off installing a plugin as [lucapette](http://stackoverflow.com/questions/6870902/vim-editor-how-can-i-search-a-word-after-selecting-it-in-visual-mode-in-vim/6871062#6871062) suggested. – nelstrom Jul 29 '11 at 12:49
  • :vmap // y/=escape(@", '\\/.*$^~[]') – hadvig Jul 29 '11 at 13:20
2

I recommend https://github.com/thinca/vim-visualstar because you can use * for searching but with some selections you can run into problems.

lucapette
  • 20,564
  • 6
  • 65
  • 59
  • 1
    I use [visual-star-search](https://github.com/bronson/vim-visual-star-search), which is similar, but seems to achieve the same result with a much simpler implementation. – nelstrom Jul 29 '11 at 12:53
  • Oh @nelstrom nice to see you here! Thank you for pointing me that I'll give it a try. – lucapette Jul 29 '11 at 12:59
0

I have this in my ~/.vimrc:

" Search for visually-selected text, forwards or backwards.
vnoremap <silent> * :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy/<C-R><C-R>=substitute(
  \escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>
vnoremap <silent> # :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy?<C-R><C-R>=substitute(
  \escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>
Jeet
  • 38,594
  • 7
  • 49
  • 56