繁体   English   中英

Vim:在 vimrc 中有条件地使用 fugitive#statusline function

[英]Vim: Conditionally use fugitive#statusline function in vimrc

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

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

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

我还尝试通过在命令前加上silent来消除错误,但这似乎也不起作用。

这将是一条捷径:

set statusline+=%{exists('g:loaded_fugitive')?fugitive#statusline():''}

由于 fugitive 没有在autoload目录中定义fugitive#statusline ,因此遗憾的是无法使用silent call / exists技术嗅探它(谢谢@Christopher)。 然而,有一些替代方案:

  • 按照@tungd 的建议,在您'statusline'选项中放置一个三元分支。
  • 在@Christopher 建议的after/plugin文件中设置'statusline' 这解决了问题,但意味着您的状态行被定义在一个不太可能的地方,因此最好在您的~/.vimrc文件中添加一个很好的注释。
  • 只需在~/.vimrc文件中定义 function 即可。

例子:

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

在你的~/.vimrc文件中加入这样的内容:

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

我个人认为@tungd 解决方案是最简单的。 但是,只需定义一个虚拟 function 将是我的下一个选择。 如果安装了 Fugitive,Fugitive 将覆盖它。 最好的部分是这使您'statusline'选项保持整洁。

我想我已经想出了如何实现这一目标。 插件加载需要检查是否存在fugitive#statusline() 在此之前,不会加载逃犯相关的变量或函数。

将此代码文件添加到$VIMRUNTIME/after/plugin路径中:

" $VIMRUNTIME/after/plugin/fugitive-statusline.vim
if has("statusline") && exists('*fugitive#statusline')
    " git fugitive statusline
    set statusline=%<%f\ %h%m%r%{fugitive#statusline()}%=%-14.(%l,%c%V%)\ %P

    " show statusline always
    set laststatus=2

    " turn off ruler
    set noruler
endif

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

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

虽然如果逃犯#statusline 的存在不起作用,这可能不是那么有效

在你的 vimrc 或 init.vim 文件中

set statusline=%F%r%h%w%=(%{&ff}/%Y)\ (line\ %l\/%L,\ col\ %c)\

if exists("*fugitive#statusline")
  set statusline+=%{fugitive#statusline()}
endif

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM