Question

I am using lightline.vim and I would like to show the current git branch. At the moment, I am doing so using vim-fugitive, however, I do not use this plugin at all, except for showing the git branch in the status line.

My question is:

Is there a way to show the git branch in the status line without using fugitive?

I tried to create a custom function that I hooked to lightline. The function fetched the current git branch using the system vimscript function. It (didn't) work well, except that the status line was refreshed on every keystroke, which broke everything else and made vim unusable. Essentially, the git branch was being fetched using the system function on every keystroke...

So that's not a viable solution. What I "could" do, is create a global variable which says whether or not the git branch was fetched, and prevent the custom function from fetching the branch name again if it was already fetched. Then I could fetch the branch name again every time MacVim loses focus (not sure how to do that using terminal vim). That is not ideal though...

Any ideas on how to solve this problem please?

Was it helpful?

Solution

Yes, using a global variable is the way to go.

The non-obvious part is how/when to update the value of that variable. An autocmd seems to be the most obvious choice but hooked to what event? BufEnter seems to be a good start.

Now, since you don't use fugitive, how do you switch branches? Outside of Vim? On Vim's command-line?

If you do it on Vim's command-line, :!git checkout foo, you could write a command that takes a branch name as argument to execute the proper shell command and change the value of g:git_branch in one go, without even using an autocmd.

If you do it outside of Vim (<C-z>, :sh, another terminal window or tmux pane, a GUI app…) you will need to find a solid way to notify Vim of that change or use your system() call with an autocmd.

OTHER TIPS

I have created a plugin which focuses on the function you want.

https://github.com/itchyny/vim-gitbranch

You can get the branch name by gitbranch#name() function.

The code is so small that you can read in a minute.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top