Issue
I code in vim.
I use git; and love git grep.
Does anyone have a particularly nice set of techniques / scripts for using git grep inside of vim?
Solution
You do have this VIM extension (created by Timo Hirvonen back in 2006!)
git grep <pattern>
searches for a pattern in a currently selected git branch.
This adds:G <pattern>
command to run the command from within Vim.func GitGrep(...) let save = &grepprg set grepprg=git\ grep\ -n\ $* let s = 'grep!' for i in a:000 let s = s . ' ' . i endfor exe s copen let &grepprg = save endfun command -nargs=? G call GitGrep(<f-args>)
As noted by dafnahaktana in the comments:
let s = 'grep'
is replaced withlet s = '!grep'
, to avoid automatically jumping to the first match (why would I want to?).
And also add the commandcopen
after the commandexe s
, so that the matching list automatically opens.
Then:
You can also limit searching to files matching a pattern (Git will do the pattern matching):
:G <pattern> -- '*.c'
Additions:
The following addition will run
git grep
on the word under the cursor when Ctrl+X G is pressed.func GitGrepWord() normal! "zyiw" call GitGrep('-w -e ', getreg('z')) endf nmap <C-x>G :call GitGrepWord()<CR>
Answered By - VonC Answer Checked By - Pedro (WPSolving Volunteer)