Working with Grep and Vim
19 Apr 2018 • Ian Emnace

The demo: asciinema

This workflow is in thanks to a Reddit post by romainl.

Opening grep results directly in Vim

Sometimes, you just want to know where a string is found. In these cases, a simple

$ grep -nr foo .
suffices.

But sometimes, you actually want to jump to the string and start editing. It makes sense to open grep results directly in Vim in this case. Try this:

$ vim -q <(grep -nr foo .) +copen

Grepping from a running Vim

Vim already has a feature to support running grep from a Vim instance! Try this:

:set grepprg=grep\ -nr
  :grep foo . | copen

Making use of better greps

In the demo, I use ripgrep as my grep. Making use of it is easy:

:set grepprg=rg\ --vimgrep

I have that in my vimrc. If you want to be robust across different machines and grep programs, try this Reddit post by robertmeta.

Making use of AsyncRun

In the demo, I also use AsyncRun to run my greps in the background, in case I’m working on something else and the grep takes more than a couple of seconds.

I have

command! -bang -nargs=+ Grep AsyncRun -program=grep @ <args>
in my vimrc, which provides me with an async :Grep alternative to :grep.

Wrapping up with a shell function

Now that I have a comfortable way to list grep results, I simply make a shell function for convenience:

vg() {
      vim +"Grep ${*:?No pattern provided.}" +copen
  }