Vim tips: Visual Search

You may be ware of super star [one of the best rated vim tips].

With a little effort you can have a visual super star by adding this to your vimrc:

function! CmdLine(str)
    exe "menu Foo.Bar :" . a:str
    emenu Foo.Bar
    unmenu Foo
endfunction 

" From an idea by Michael Naumann
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 . "^M"
    elseif a:direction == 'gv'
        call CmdLine("vimgrep " . '/'. l:pattern . '/' . ' **/*.')
    elseif a:direction == 'f'
        execute "normal /" . l:pattern . "^M"
    endif

    let @/ = l:pattern
    let @" = l:saved_reg
endfunction

"Basically you press * or # to search for the current selection
vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>
vnoremap <silent> gv :call VisualSearch('gv')<CR>

How to use these maps:

  • Using the "*" key while in visual mode searches for the current selection (forwards)
  • Using the "#" key while in visual mode searches for the current selection (backwards)
  • Pressing "gv" will vimgrep the current selection

The selection will be escaped, so you can search after "getUser(" or "#headline".

6. Aug 2008 Tips · VIM Editor
© Amir Salihefendic