Extending Vim with ripgrep
In this post I want to talk about how I use ripgrep in Vim.
This is a crucial part of my daily workflow. It’s fast because of ripgrep and
extensible because of how nicely vim is integrated with the command line.
Here’s the configuration needed:
if executable("rg")
set grepprg=rg\ --vimgrep\ --smart-case\ --hidden
set grepformat=%f:%l:%c:%m
endif At first, it was not obvious to me how I could use it beyond :grep foo, so I
want to share how I do.
Common use cases
- Search for
fooin current working directory::grep foo. - Search for
fooin files undersrc/::grep foo src. - Search for
fooin current file directory::grep foo %:h1. - Search for
fooin current file directory’s parent directory::grep foo %:h:h(and so on).
Less common use cases
- Search for the exact word
foo(notfoobar)::grep -w foo(equivalent to:grep '\bfoo\b'). - Search for
fooin JavaScript files::grep foo -t js - Search for
fooin files matching a glob::grep foo -g '*.js'
Extensibility
This is nice but here is where it truly shines. I can give any command line output as an argument.
Say I want to search in files modified between git revisions:
:grep foo `git diff --name-only master..` Or only modified files:
:grep foo `git ls-files --modified` I don’t use this everyday but I enjoy it when I do.
Usage with Vim
This will populate the quickfix list with the search results, so I can navigate them with commands I’m already familiar with.
For example, to replace foo with bar across files (asking me to confirm
before): :cdo s/foo/bar/gc. And then :cfdo update. Sometimes I narrow the
search down with :Cfilter too.
Downsides
A downside is that you can’t use backreferences or look-around in regex. In
the rare case I need them, I use I just find out, thanks to
ripgrep’s
author,
that you can use backreferences/look-around in regex with the :vimgrep.-P/--pcre2 flag
or --engine auto and I can’t wait to use it!!
Another one is that it’s synchronous, so if the directory is huge it may block vim
for a few seconds. But I don’t usually experience this because of how fast
ripgrep is.
Conclusion
This might be one of the few sane reasons why I insist on using nvim for
development (vim-fugitive and LSP as well). It’s just one of those things I
enjoy using and makes development more fun (to me).
Footnotes
-
%:his expanded byvimto get the header of the current file. See:h expand. ↩