Skip to content

Instantly share code, notes, and snippets.

@igemnace
Created April 19, 2018 06:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igemnace/bf617fa7f84b379feedb39dcf27c0719 to your computer and use it in GitHub Desktop.
Save igemnace/bf617fa7f84b379feedb39dcf27c0719 to your computer and use it in GitHub Desktop.
Working with Grep and Vim

Working with Grep and Vim

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment