Skip to content

Instantly share code, notes, and snippets.

@casssoft
Last active August 13, 2018 23:47
Show Gist options
  • Save casssoft/ca9dc37d9183e9924880f2ec05e9dfae to your computer and use it in GitHub Desktop.
Save casssoft/ca9dc37d9183e9924880f2ec05e9dfae to your computer and use it in GitHub Desktop.
vim-grep-with-git
" This is the grep command I've always wanted.
" This plugin opens the results of 'grep -r' in a bottom window
" and uses 'git grep' when in a git repo and regular grep otherwise.
" <C-x><C-x> runs grep for the word under the cursor
" also this:
"map <C-j> :cn<CR>
"map <C-k> :cp<CR>
"map <leader>c :cclose<CR>
function! Grep(args, ignorecase)
let grepprg_bak=&grepprg
let g:gitroot=system('git rev-parse --show-cdup')
if v:shell_error
if a:ignorecase
let g:mygrepprg="grep\\ -nir"
else
let g:mygrepprg="grep\\ -nr"
endif
let g:grepcmd="silent! grep \"\\b" . a:args . "\\b\" ."
else
if a:ignorecase
let g:mygrepprg="git\\ grep\\ -ni"
else
let g:mygrepprg="git\\ grep\\ -n"
endif
let g:grepcmd="silent! grep \"\\b" . a:args . "\\b\" ."
"to always start from the root use this:
"let g:grepcmd="silent! grep \"\\b" . a:args . "\\b\" " . g:gitroot
endif
exec "set grepprg=" . g:mygrepprg
execute g:grepcmd
botright copen
let &grepprg=grepprg_bak
wincmd p
exec "redraw!"
endfunction
func GrepWord()
normal! "zyiw
call Grep(getreg('z'), 0)
endf
nmap <C-x><C-x> :call GrepWord()<CR>
map <C-j> :cn<CR>
map <C-k> :cp<CR>
map <leader>c :cclose<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment