Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ag.vim: Use word under the cursor as *part* of a search pattern?

Tags:

vim

search

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).

like image 649
ivan Avatar asked Dec 19 '22 13:12

ivan


2 Answers

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>   
like image 173
shemerey Avatar answered Mar 17 '23 19:03

shemerey


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.

like image 20
romainl Avatar answered Mar 17 '23 19:03

romainl