nowox
nowox

Reputation: 29166

Vim search with ag the word under cursor

I would like to map <Leader>a to search with ag the word under the cursor

I wrote this:

noremap <Leader>a  :Ag!<C-u><C-r>=Escape(expand('<cword>'))<CR>

function! Escape(stuff)
    return substitute(escape(a:stuff, '\/.*$^~[]'), "\n", '\\n', "g")
endfunction

Unfortunately when I hit <Leader>a on the word foo I get this:

:foo

The Ag! vanished and the trailing <CR> was not executed.

Where is my mistake?

Upvotes: 9

Views: 1996

Answers (3)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

Add answer I found in GitHub answered by junegunn in case someone needs it

nnoremap <silent> <Leader>ag :Ag <C-R><C-W><CR>

Original link

Upvotes: 2

Pegasus
Pegasus

Reputation: 1593

noremap <leader>a :Ag! "<cword>"<cr>

Upvotes: 3

Kent
Kent

Reputation: 195229

you added <c-u> in your mapping, it will remove :Ag!

You may want to use -Q for ag to do a literal search.

For the <CR> problem, your <CR> is for the <c-r>= expression, you need one extra <CR> to launch the command.

Upvotes: 9

Related Questions