Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Conditionally use fugitive#statusline function in vimrc

Tags:

git

vim

I use the same vimrc across many machines, some of which have fugitive.vim installed and some of which don't. I like including fugitive#statusline() in my statusline, but on machines that don't have the plugin installed this raises an error.

Is there a way to check for this function's existence before calling set statusline? I've tried using existsy, but it doesn't work for some reason (load order?)

if exists("*fugitive#statusline")
  set statusline=%<\ %f\ %{fugitive#statusline()} ... (other stuff)
endif

I've also tried silencing the error by prefixing the command with silent! but that doesn't seem to work either.

like image 866
jerodsanto Avatar asked May 12 '11 20:05

jerodsanto


2 Answers

This one would be a shortcut:

set statusline+=%{exists('g:loaded_fugitive')?fugitive#statusline():''}
like image 177
tungd Avatar answered Oct 17 '22 07:10

tungd


As fugitive does not define fugitive#statusline in an autoload directory it sadly can not be sniffed use silent! call / exists technique (Thank you @Christopher). There are however some alternatives:

  • Put a ternary branch in your 'statusline' option as @tungd suggested.
  • Set 'statusline' in an after/plugin file like @Christopher suggests. This solves the problem but means your statusline is defined in an rather unlikely place so it would probably be best to put in a nice comment in your ~/.vimrc file.
  • Simply define the function in your ~/.vimrc file.

Example:

if !exists('*fugitive#statusline')
  function! fugitive#statusline()
      return ''
  endfunction
endif
  • Another option is to use a Fugitive autocmd event that Fugitive defines. Note that this will only fire when Fugitive detects a git directory.

Put something like this in your ~/.vimrc file:

augroup fugitive_status
  autocmd!
  autocmd user Fugitive set statusline=%<\ %f\ %{fugitive#statusline()} ...
augroup END

Personally I think @tungd solution is the simplest. However just define a dummy function would be my next choice. Fugitive will override it if Fugitive is installed. The best part is this keeps your 'statusline' option neat and clean.

like image 38
Peter Rincker Avatar answered Oct 17 '22 07:10

Peter Rincker