Search for the selected text
* command searches for the word under the cursor. That makes sense in Normal mode, but from Visual mode it would be more useful if the star command searched for the current selection, rather than the current word. We can add this feature to Vim using the visual star search plugin.
I’ll be running my Core Vim Class online on Monday, January 27th. Tickets cost £160, but you can get the earlybird discount of £145 if you buy yours before January 24th. The price includes an exclusive screencast that summarises the material from the class.
: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
*) 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
# 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 /<C-r>//g **
Naturally, the patterns generated by these
# mappings can also be used with any Ex command that accepts a pattern, including