anon anon - 2 months ago 14
Git Question

techniques in git grep and vim

Note: marked as community wiki

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?

Readers: please upvote answers involving vim + git grep; please downvote answers involving non-vim editors, and editors referring to external tools besides git grep.

Answer

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
  let &grepprg = save
endfun
command -nargs=? G call GitGrep(<f-args>)

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>
Comments