The demo: asciinema
This workflow is in thanks to a Reddit post by romainl.
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
Vim already has a feature to support running grep from a Vim instance! Try this:
:set grepprg=grep\ -nr
:grep foo . | copen
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.
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
.
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
}