Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shyam-habarakada/f95b88fef76193417bb93fba851708f9 to your computer and use it in GitHub Desktop.
Save shyam-habarakada/f95b88fef76193417bb93fba851708f9 to your computer and use it in GitHub Desktop.
git-blame.vim while scrolling
" -----------------------------------------------------------------------------
" Extended behavior on top of https://github.com/zivyangll/git-blame.vim
" An attempt to see if re-mapping j/k to invoke :GitBlame is a useful feature
function! IsGitControlled()
let l:filepath = expand('%:p')
let l:git_root = system('git rev-parse --show-toplevel 2>/dev/null')
" If the file is under git control
if v:shell_error == 0 && !empty(l:git_root)
return 1
else
return 0
endif
endfunction
function! ResetDefaultMotions()
" Reset `j` and `k` to their default behavior
silent! nunmap <buffer> j
silent! nunmap <buffer> k
endfunction
function! ToggleBlaming()
if exists("b:blaming") && b:blaming == 1
let b:blaming = 0
call ResetDefaultMotions()
else
let b:under_git = IsGitControlled()
if b:under_git == 1
let b:blaming = 1
execute "GitBlame"
" Map `j` and `k` to ConditionalGitBlame in the current buffer
nnoremap <buffer> j :call ShowGitBlame('j')<CR>
nnoremap <buffer> k :call ShowGitBlame('k')<CR>
else
let b:blaming = 0
echo "Blaming disabled for current buffer (not under git control)"
call ResetDefaultMotions()
endif
endif
endfunction
function! ShowGitBlame(direction)
execute "normal!" a:direction
execute "GitBlame"
endfunction
" Automatically reset blaming and restore default behavior when entering a new buffer
autocmd BufEnter * let b:blaming = 0 | silent! nunmap <buffer> j | silent! nunmap <buffer> k
" Map <leader>b to toggle blaming for the current buffer
nnoremap <silent> <leader>b :call ToggleBlaming()<CR>
" -----------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment