Building uppon Lie Ryan's answer and the code provided above (it is described here)
.
Change your function parsing the git branch as follows:
let g:gitparsedbranchname = ' '
function! UpdateGitBranch()
let l:string = system("git rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
let g:gitparsedbranchname = strlen(l:string) > 0?'['.l:string.']':''
endfunction
And change the display of the result in your status line:
set statusline+=%{g:gitparsedbranchname}
To update the vim variable g:gitparsedbranchname
hook a function call to UpdateGitBranch()
in a auto command group (see vim help: autocmd-groups as you do not want to have multiple listeners on one event (see vim help: autocommand-events).
E.g. if you want to update your git branch variable g:gitparsedbranchname
on buffer writes, after buffer reads and buffer changes you can set it up like that (it depends on when you want to update the branch variable):
augroup UPDATE_GITBRANCH
" clear old commands
autocmd!
" update git branch
autocmd BufWritePre * :call UpdateGitBranch()
autocmd BufReadPost * :call UpdateGitBranch()
autocmd BufEnter * :call UpdateGitBranch()
augroup END
You can change the g:
as you see fit to limit the scope of that variable (see: vim :help internal-variables).
Those changes fixed the issue with mouse escape codes being printed while using the function to get the git branch.
I for my part settled with the following (and the code snippet for the augroup
):
let b:gitparsedbranchname = ' '
function! UpdateGitBranch()
let l:string = system("git -C ".expand("%:p:h")." rev-parse --abbrev-ref HEAD 2>/dev/null | tr -d '\n'")
let b:gitparsedbranchname = strlen(l:string) > 0?''.l:string.'':' '
endfunction
set laststatus=2
set statusline=
set statusline+=[%{b:gitparsedbranchname}]
This
- sets the current git branch in my status line,
- updates it after each write and
- considers different git-directories of open files.
For git versions of 2.22 and above it might be easier to get the branch name and the system call can be changed for them (see: here).
$TERM
variable set to?