Vim:在vimrc中有条件地使用逃犯#statusline函数

jer*_*nto 7 git vim

我在许多机器上使用相同的vimrc,其中一些机器安装了fugitive.vim,而其中一些机器没有.我喜欢fugitive#statusline()在我的状态行中包含,但是在没有安装插件的机器上,这会引发错误.

有没有办法在调用之前检查此函数的存在set statusline?我尝试过使用existsy,但由于某种原因它不起作用(加载顺序?)

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

我也尝试通过为命令添加前缀来解决错误,silent!但这似乎也不起作用.

tun*_*ngd 10

这个将是一个捷径:

set statusline+=%{exists('g:loaded_fugitive')?fugitive#statusline():''}
Run Code Online (Sandbox Code Playgroud)

  • @ZyX:实际上插件总是在`vimrc`之后加载,这在`:help initialization`中有明确记载.但是,这仍然可以正常工作,因为`%{}`表示每当状态行更新时都会计算表达式. (2认同)

Pet*_*ker 8

由于逃犯没有fugitive#statuslineautoload目录中定义,所以很遗憾不能使用silent! call/ exists技术(谢谢@Christopher).但是有一些替代方案:

  • 'statusline'@tungd建议的情况下,在您的选项中添加三元分支.
  • 设置'statusline'after/plugin@Christopher建议的文件中.这解决了问题,但意味着您的状态行是在一个相当不可能的地方定义的,因此最好在~/.vimrc文件中添加一个好的注释.
  • 只需在~/.vimrc文件中定义该功能即可.

例:

if !exists('*fugitive#statusline')
  function! fugitive#statusline()
      return ''
  endfunction
endif
Run Code Online (Sandbox Code Playgroud)
  • 另一种选择是使用Fugitive autocmdFugitive定义的事件.请注意,这只会在Fugitive检测到git目录时触发.

把这样的东西放在你的~/.vimrc文件中:

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

我个人认为@tungd解决方案是最简单的.然而,定义一个虚拟函数将是我的下一个选择.如果安装了Fugitive,则Fugitive将覆盖它.最好的部分是保持您的'statusline'选择整洁干净.


act*_*imp 1

您可以尝试检查逃逸插件的加载变量?

if exists('g:loaded_fugitive')
   set statusline=%<\ %f\ %{fugitive#statusline()} ... (other stuff)
endif
Run Code Online (Sandbox Code Playgroud)

尽管如果逃亡#statusline 的存在不起作用,这可能不会那么有效!