Reputation: 687
In normal mode I want K
to search for the word under the cursor with ag.vim. In visual mode I want K
to search for the visual selection. This is what I have so far:
nnoremap <silent> K :Ag <C-R><C-W><CR>:copen<CR>
vnoremap <silent> K y:Ag <C-R>"<CR>:copen<CR>
However, it does not work with characters that needs to be escaped. (As far as I understand that is characters like %
, #
, /
, etc)
If I select the following text <C-R>"<CR>:copen<CR>
in visual mode and hit K
an error occurs:
Error detected while processing function ag#Ag
From ag.vim's homepage:
Some characters have special meaning, and need to be escaped your search pattern. For instance, '#'. You have to escape it like this :Ag '\\\#define foo' to search for #define foo.
So basically I need to escape the output + escape #
with \\\#
(the gotcha above) before it is passed to Ag
.
I hope someone can help me. Thanks.
Upvotes: 2
Views: 1132
Reputation: 8248
You need to escape those chars. Something like this should work (this is untested):
:xnoremap K y:<c-u>Ag <C-R>=shellescape(expand(@"),1)<CR>:copen<CR>
:nnoremap K :<c-u>Ag <c-r>=shellescape(expand("<cword>"),1)<cr>:copen<cr>
Note, I used xnoremap
instead of vnoremap, so that the mapping does not interfere with select mode.
Note also, depending on what you want, you might want to use <cWORD>
instead of <cword>
(see the help at :h <cword>
)
Upvotes: 1