From 8157a6d3fc531d73abda72e6bea97dfb8aceb247 Mon Sep 17 00:00:00 2001 From: Alexander Karle Date: Mon, 29 Oct 2018 22:27:02 -0400 Subject: [PATCH] vim: Add function to git grep word under cursor Errors if not in a repo! --- vim/vimrc | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/vim/vimrc b/vim/vimrc index 5f3caa1..aa64998 100644 --- a/vim/vimrc +++ b/vim/vimrc @@ -140,6 +140,52 @@ function! ToggleColorColumn() abort set colorcolumn="" endif endfunction + +" Searches all of project for word under cursor +function! GitGrepWordUnderCursor() abort + let word = substitute(expand(''), '#', '\\#', 'g') + if s:InGitRepo() + let raw = system('git grep -n ' . word) + let matches = split(raw, '\n') + let qfitems = [] + for m in matches + let items = split(m, ':') + let d = { + \'filename': items[0], + \'lnum': items[1], + \'text': join(items[2:], '') + \} + + let qfitems += [d] + endfor + call setqflist(qfitems, 'r') + else + call s:warn("called GitGrepWordUnderCursor outside of git repo") + endif +endfunction + +function! s:InGitRepo() abort + if has('win64') || has('win32') + let fsep = '\' + else + let fsep = '/' + endif + let dir_list = split(getcwd(), fsep) + let running_path = '' + for dir in dir_list + let running_path = join([running_path, dir], fsep) + if isdirectory(running_path . fsep . '.git') + return 1 + endif + endfor + return 0 +endfunction + +function! s:warn(msg) abort + echohl WarningMsg + echo 'vimrc: ' . a:msg + echohl None +endfunction " }}} " KEY MAPPINGS {{{ @@ -198,6 +244,7 @@ nnoremap :nohlsearch " Get greppin quick! --> search word under cursor (escape # for VimL autoload) nnoremap g :exe "grep " . substitute(expand(''), '#', '\\#', 'g') +nnoremap G :call GitGrepWordUnderCursor():copen " Toggle whitespace nnoremap w :set list! -- libgit2 0.28.4