Note: this is an educational exercise. For those wanting a ready-made solution, use vim-gitbranch.
I am learning vimscript, and the code below is part of my .vimrc
used to display the current git branch in the statusline. I am aware that there are ready-made options out there, but this is more of an educational exercise. The purpose of this question is to solicit advice on improving the code.
The only arbitrary requirement of this exercise is that the git branch has to be obtained using a system
call (instead of directly through the .git
directory).
function! StatuslineGitBranch()
if exists("g:git_branch")
return g:git_branch
else
return ''
endif
endfunction
function! GetGitBranch()
let l:is_git_dir = system('echo -n $(git rev-parse --is-inside-work-tree)')
let g:git_branch = l:is_git_dir == 'true' ?
\ system('bash -c "echo -n $(git rev-parse --abbrev-ref HEAD)"') : ''
endfunction
autocmd BufEnter * call GetGitBranch()
set laststatus=2
set statusline=
set statusline+=%{StatuslineGitBranch()}
Reason for the existence of g:git_branch
, and the slightly convoluted execution: so that statusline does not involve a system
call (reference).
How can the above be improved? I'm new to this, so comments will be very helpful.
b:git_branch
) instead of a global one? Technically, you could.have buffers opening files from different repos, with different branches checked out... – filbranden♦ Jul 8 '19 at 7:45