vimack

Using Ack.vim on visual selection


Currently I have this mapping in my ~/.vimrc

noremap <Leader>a :Ack <cword><cr>

which enables me to search for a word under the cursor.

I would like to search for a current visual selection instead, because sometimes words are not enough.

Is there a way I can send visual selection to ack.vim?


Solution

  • You can write a visual-mode map that yanks the highlighted text and then pastes it verbatim (properly escaped) onto the vim command-line:

    vnoremap <Leader>a y:Ack <C-r>=fnameescape(@")<CR><CR>
    

    This solution uses the <C-r>= trick that allows you to enter a kind of second-level command-line, which allows you to enter any vimscript expression, which is then evaluated, and the result is stringified and pasted onto the (original, first-level) command-line where the cursor is.

    A slight disadvantage of this approach is that it commandeers the unnamed register, which you may not want.