Subscribe for free with iTunes, Twitter, or RSS (Ogg or Quicktime).

Vimcasts

Search for the selected text

#46

The * 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.

Download

OGG 5.3 MB

Quicktime 9.4 MB

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