Publicado em: 19/Nov/2018
Atualizado em: 16/Dec/2019

Fast Search in Vim

Projects can be searched for specific text within Vim:

:grep sometext

Can we grep faster?

Override to use The Silver Searcher

grep is a built-in command of Vim. By default, it will use the system’s grep command. We can overwrite it to use The Silver Searcher’s ag command by putting this in our ~/.vimrc:

 1" The Silver Searcher
 2if executable('ag')
 3  " Use ag over grep
 4  set grepprg=ag\ --nogroup\ --nocolor
 6  " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
 7  let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
 9  " ag is fast enough that CtrlP doesn't need to cache
10  let g:ctrlp_use_caching = 0

Search for the word under the cursor

This searches for the text under the cursor and shows the results in a “quickfix” window:

1" bind K to grep word under cursor
2nnoremap K :grep! "\b<C-R><C-W>\b"<CR>:cw<CR>

It looks like this when K is typed with the cursor over SubscriptionMailer:


Cursor over each search result, hit Enter, and the file will be opened.

Using ag arguments

This defines a new command Ag to search for the provided text and open a “quickfix” window:

1" bind \ (backward slash) to grep shortcut
2command -nargs=+ -complete=file -bar Ag silent! grep! <args>|cwindow|redraw!

Map it to any character, such as \:

1nnoremap \ :Ag<SPACE>

When \ is pressed, Vim waits for input:


Standard ag arguments may be passed in at this point:

1:Ag -i Stripe app/models

Hitting Enter results in:

comments powered by Disqus