Look up :help visual-search in Vim’s documentation, and you’ll find a suggestion for this simple mapping:
:vmap X y/<C-R>"<CR>
This comes with a warning: Note that special characters (like . and *) will cause problems. It’s not too hard to avoid these problems. This snippet of code takes care of them:
function! s:VSetSearch(cmdtype) let temp = @s norm! gv"sy let @/ = '\V' . substitute(escape(@s, a:cmdtype.'\'), '\n', '\\n', 'g') let @s = temp endfunction xnoremap * :<C-u>call <SID>VSetSearch('/')<CR>/<C-R>=@/<CR><CR> xnoremap # :<C-u>call <SID>VSetSearch('?')<CR>?<C-R>=@/<CR><CR>
You install the visual-star-search plugin from github, which wraps up this functionality.
Note that these visual mode * and # mappings create a new record in Vim’s search history. You can always paste the last search pattern by pressing <C-r>/, so you can easily search through multiple files using :vimgrep:
:vimgrep /<C-r>//g **
Naturally, the patterns generated by these * and # mappings can also be used with any Ex command that accepts a pattern, including :substitute, :global, and :vimgrep.
Further reading
- visual-star-search plugin
:help visual-search:help quote/:help c_CTRL-R- Practical Vim tip 86 - Search for the current visual selection
- Practical Vim tip 78 - Escape Problem Characters
- Vim pr0n: Visual search mappings