How do I search for the selected text?

:set hls
:vmap * y:let @/ = @"<CR>
  • set hls (hight light search)
  • v => hjkl (select something)
  • press *, copy selected text to reg "
  • set content of reg / as "
  • press n/N to navigate

In insert mode you can use CTRL-R to insert the contents of Vim registers. By default, copied text gets put in the unnamed register ", so to insert that text you would type <C-R>" in insert mode. The search prompt uses Command-line mode which has its own CTRL-R that works almost identically to the one in Insert mode.

So if I just yanked the text foo, typing /<C-R>" would search for the text foo once I press enter.


I have this mapping defined in my vimrc, it maps * to defining the search pattern as what is currently highlighted (escaping all potential dangerous characters, and converting a space in what is highlighted to any sequence of spaces)

xnoremap * :<C-U>let old_reg=getreg('"')|let old_regtype=getregtype('"')<CR>gvy/<C-R><C-R>=substitute(substitute(escape(@", '/\.*$^~['), '\s\+', '\\s\\+', 'g'), '\_s\+', '\\_s*', 'g')<CR><CR>gV:call setreg('"', old_reg, old_regtype)<CR>:let v:searchforward=1<CR>

In order to use it, start visual mode with v, and then highlight what you want to search and press * not y.

Of course you can map # to search backwards (exactly the same except that v:searchforward should be set to 0.

Tags:

Vim