Last Updated: February 25, 2016
·
1.449K
· vitorbal

Search for visually selected text on vim

This is a neat little mapping that I discovered that searches the file for visually selected text.

I think this is quite useful when you're searching for something which is a little bigger than a few words. This way you just go into visual mode, select a bunch of stuff, and then press ***** to search the file for that selection ( or # to search backwards).

All you need is the following mapping on your .vimrc file:

" Search for 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>

Formatting seems a little weird here on coderwall, but just copy-paste it and it should work fine.

Enjoy!