Load Grep Results Into Vim
28 Jun 2025 Tools vimgittipsWhen coding, I often need to search for the references of a variable or a function across multiple files.
Usually I enter command mode of vim and do a grep command,
memorize the search results and open the files having hits.
This common pattern could be dramatically accelerated by a user-defined vim command:
:command Gitgrep :lex system("git grep -n " . shellescape(getreg('/'))).
How it works is it takes the content in the current register ‘/’
(the register holding the pattern we search in vim),
then do the command git grep with this pattern,
with results written into a location list.
The basic way to iterate through the location list would be using the vim command
:lnext (or :ln) and :lprev (or :lp).
Of course, we could add shortcuts to them,
such as :nnoremap <C-n> :lnext<CR> makes Ctrl+n jump to the next location on the location list.
To view the entire list
(could be useful to identify a specific occurance such as the function definition)
use vim command :lopen (or :lop).
If we are not coding under a git repo,
then the git grep command would not work,
but we could just make a general version, for example:
:command Grep :lex system("grep -Inr " . shellescape(getreg('/'))).
With this, I do not need to type the pattern to grep (it is usually available in current file, and might even has been searched within current file already), and there is no more challange to my short-term memory (first memorize the file path and type it right to open it is painful).
Credits
- Thanks to my colleague, Ned, who shares the wonderful tip.
- How to suppress binary file matching results in grep - Thanks for the grep command option
-I - Vim documentation: quickfix - Where vim commands for location list is documented
