Search for the selected text


Run time:

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.


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

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


Level-up your Vim


Boost your productivity with a Vim training class. Join a public class, or book a private session for your team.

Drew hosted a private Vim session for the shopify team that was one of the best workshops I have ever attended.

John Duff, Director of Engineering at Shopify


Make yourself a faster and more efficient developer with the help of these publications, including Practical Vim (Pragmatic Bookshelf 2012), which has over 50 five-star reviews on Amazon.

After reading it, I've switched to vim as my default editor on a daily basis with no regrets. ★★★★★

Javier Collado

Learn to use Vim efficiently in your Ruby projects

In association with thoughtbot, one of the most well respected Rails consultancies in the world, I've produced a series of screencasts on how to make navigating your Ruby projects with Vim ultra-efficient. Along the way, you’ll also learn how to make Ruby blocks a first-class text object in Vim. This lets you edit Ruby code at a higher level of abstraction. Available to buy from thoughtbot..