Vim - visual search

by Gregor Uhlenheuer on May 20, 2010

For all of you who want to search for a visually selected string in vim this small function might come in handy:

function! VSetSearch()
    let tmp = @@
    normal! gvy
    let @/ = '\V' . substitute(escape(@@, '\'), '\n', '\\n', 'g')
    call histadd('/', substitute(@/, '[?/]',
                \ '\="\\%d".char2nr(submatch(0))', 'g'))
    let @@ = tmp

vnoremap * :<C-u>call VSetSearch()<CR>//<CR>
vnoremap # :<C-u>call VSetSearch()<CR>??<CR>

Now you can search as usual with * and # for the next and previous search match of the currently highlighted text.

This post is tagged with vim and programming