Jean-Rene David wrote:
* Lev Lvovsky [2006.10.17 17:15]:

Is it possible to search for a string by
selecting that string in  visual mode?  Meaning,
if I highlight something, and then want to
search for that thing which is highlighted in
the rest of the doc?


You already got lots of good answers. Here's
another one.

I've had this in my vimrc for years, and use it
when the string I'm searching for is not a
keyword. It works both forward and backward, puts
the searched pattern in the search history and
doesn't screw up any register.

"--------------< cut here >---------------------------
" Search for visually selected text {{{
" From an idea by Michael Naumann, Jürgen Krämer.
function! VisualSearch(direction) range
   let l:saved_reg = @"
   execute "normal! vgvy"
   let l:pattern = escape(@", '\\/.*$^~[]')
   let l:pattern = substitute(l:pattern, "\n$", "", "")
   if a:direction == 'b'
      execute "normal ?" . l:pattern . "
"
   else
      execute "normal /" . l:pattern . "
"
   endif
   let @/ = l:pattern
   let @" = l:saved_reg
endfunction

vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>
"--------------< cut here >---------------------------

HTH,


This sounds brilliant Jean-Rene, I put it into my .vimrc, but it doesn't seem to work, I did notice that between the if and else there are " which just act as comments as they are on newlines, didn't know if this was just my text wrapping, so I tried putting them on the line above, both with a space between or not, didn't know if that might be cause but that didn't seem to help either. Sorry I may be missing something obvious, but I'd like to get this to work as it seems very useful. I was selecting text in visual mode, then pressing / or ? and I just get the normal action of pressing / or ?

Thanks,
Rob.


Reply via email to