Using *
works great when I'm just searching for a word, but often I want to search for a phrase or a filename that appears in code, and it would be nice to just visually select the string and be able to hit *
or #
to search for it. This turns out to be more complicated than I hoped. I started with this:
vnoremap * y/\<<c-r>"<cr>\>
But this breaks if my string has a forward slash in it. I tried getting it to automatically replace forward slashes with the \/
combo, as follows:
vnoremap * yo<esc>pV:s-/-\\/-ge<cr>0D"_dd/\<<c-r>"<cr>\>
" y - yank the text
" o<esc> - open a new line
" p - paste the string
" V:s-/-\\/-ge<cr> - replace / with \/
" 0D"_dd - Grab the string and get rid of the line I just created
" /\<<c-r>"<cr>\> - Do the search
The there are (at least) two problems with this: It won't work if I can't edit the current file, and it blows up if I'm trying to grab text in a comment. When I use o
on a commented line, the new line starts with a comment which means it won't scoop up the right text when I run 0D
. Is there a way to make this work the way I want?