Skip to content

Instantly share code, notes, and snippets.

@mberkowski
Last active December 14, 2015 03:39
Show Gist options
  • Save mberkowski/5022495 to your computer and use it in GitHub Desktop.
Save mberkowski/5022495 to your computer and use it in GitHub Desktop.
A simple Vimscript function `GitCurrentBranch()` which returns the git branch of the current buffer. It is really nothing fancy - it just loads the branch into the buffer variable `b:gitbranch` upon reading a buffer via `autocmd`. Ideally, it can be used in the statusline with `:set statusline+=%{b:gitbranch}`
" Retrieves git branch of the current file
" Perfect for feeding the branch into the statusline
" Depends on autocmd
"
" USAGE:--------------------------------------------
"
" Call in statusline as %{b:gitbranch}
" :set statusline+={%b:gitbranch}
function! GitCurrentBranch()
" Stores current working directory
let lastdir = getcwd()
" Changes temporarily to the directory containing the buffer
let bufdir = expand('%:p:h')
if bufdir != lastdir
lcd `=bufdir`
endif
" Retrieves git branch after changing directory
let branch = system("git branch --no-color 2> /dev/null | cut -d' ' -f2")
" Then changes back
if bufdir != lastdir
lcd `=lastdir`
endif
if branch != ''
return '[GIT-BRANCH=' . substitute(branch, '\n', '', 'g') . ']'
en
return ''
endfunction
autocmd BufRead,BufNewFile * let b:gitbranch=GitCurrentBranch()
" Inspired By http://amix.dk/blog/post/19571
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment