---
title: Faster Grepping in Vim
teaser:
tags: vim
author: Dan Croak
published_on: 2013-11-27
---

We often search our projects for specific text within Vim like so:

    :grep sometext

However, we have a need for speed. How can we grep faster?

## Override to use The Silver Searcher

`grep` is a built-in command of Vim. By default, it will use our system's
`grep` command. We can overwrite it to use [The Silver
Searcher](https://github.com/ggreer/the_silver_searcher)'s `ag` command instead
by putting this in [our
`~/.vimrc`](https://github.com/thoughtbot/dotfiles/blob/master/vimrc):

    " The Silver Searcher
    if executable('ag')
      " Use ag over grep
      set grepprg=ag\ --nogroup\ --nocolor

      " Use ag in CtrlP for listing files. Lightning fast and respects .gitignore
      let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'

      " ag is fast enough that CtrlP doesn't need to cache
      let g:ctrlp_use_caching = 0
    endif

## Search for the word under the cursor

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

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

It looks like this when we hit `K` with our cursor over `SubscriptionMailer`
in the [Upcase](https://thoughtbot.com/upcase/join) repo:

![''](https://images.thoughtbot.com/faster-grepping-in-vim/quickfix-under-cursor.png)

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:

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

We can map it to any character, such as `\`:

    nnoremap \ :Ag<SPACE>

When `\` is pressed, Vim waits for our input:

    :Ag

Standard `ag` arguments may be passed in at this point:

    :Ag -i Stripe app/models

Hitting `Enter` results in:

![''](https://images.thoughtbot.com/faster-grepping-in-vim/quickfix-custom-command.png)

## What's next

If you found this useful, you might also enjoy:

* [How Grep Got its Name][how]
* [Running Specs from Vim][specs]
* [Navigating Ruby Files with Vim][nav]

[how]: https://thoughtbot.com/blog/how-grep-got-its-name
[specs]: https://thoughtbot.com/blog/running-specs-from-vim/
[nav]: https://thoughtbot.com/upcase/navigating-ruby-files-with-vim?utm_source=giantrobots&utm_medium=blog
