Using the Ag.vim plugin you can easily search for the word under the cursor by calling :Ag
without any arguments, but how can I include the word under the cursor as part of a search pattern? I'm trying to add a bit to my vimrc to search for method definitions in Ruby files. Something like:
autocmd FileType ruby noremap K :Ag! "\bdef <C-R><C-W>\b"<CR>
It doesn't recognize the <C-R><C-W>
. Also, I've tried both \b
and \<
, \>
as word boundaries. Ag uses \b
outside the context of Vim, but I know it translates \<
and \>
to \b
in some contexts (not sure about this context though).
I usually use one trick, just press *
on you current word and then use :AgFromSearch
, you could specify concrete path e.g :AgFromSearch /any/path/
If you really want to do word as part of your search pattern, you can use <cword>
(current word)
nmap <silent> <D-f> :Ag "def <cword>" /any/path/<CR>
augroup Ruby
" clear this augroup's autocmds
autocmd!
" use this version:
autocmd FileType ruby nnoremap <buffer> K :<C-u>execute 'Ag! "\bdef ' . expand('<cword>') . '\b"'<CR>
" or this one, ^R^W is obtained by pressing <C-v><C-r> then <C-v><C-w>:
autocmd FileType ruby nnoremap <buffer> K :Ag! "\bdef ^R^W\b"<CR>
augroup END
Use augroup
and autocmd!
as above for a cleaner ~/.vimrc
.
nnoremap
is better than noremap
unless you really want a single mapping for normal, visual and operator-pending mode (which doesn't really make any sense).
<buffer>
is needed to ensure that your mapping is limited to the current buffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With