如何用Vim的可靠命令行选项

116 阅读2分钟

我不知道为什么RVM仍然是我默认的Ruby版本管理器,但目前的问题在Rbenv上也应该是可以重现的。

让我们来补充一下背景:我们有一个用Ruby编写的API,在JRuby上运行,即通过JVM,这意味着与CRuby相比,启动时间很慢(是的,即使有export JRUBY_OPTS='--dev' )。我使用Vim 8.0.502,当然,它默认捆绑了Tim Pope的vim-ruby 。

问题是:自从我改用JRuby后,我开始注意到在Vim中处理.rb文件时速度变慢。起初我并没有太注意它(几乎读了一个月),但今天它真的开始困扰我。我不知道是什么原因导致了速度变慢,所以我试着用Vim的可靠的命令行选项:

vim --startuptime profile-data app/controllers/application_controller.rb

结果发现(为简洁起见编辑了一下):

104.316  002.877  002.877: sourcing /usr/local/share/vim/vim80/syntax/ruby.vim
1228.691  1123.486  1123.486: sourcing /usr/local/share/vim/vim80/ftplugin/ruby.vim
1229.935  000.686  000.686: sourcing /usr/local/share/vim/vim80/indent/ruby.vim
{ edited }
1273.618  043.838: opening buffers
1274.471  000.853: BufEnter autocommands
1274.475  000.004: editing files in windows
1274.924  000.449: VimEnter autocommands
1274.932  000.008: before starting main loop
1299.500  024.568: first screen update
1299.501  000.001: --- VIM STARTED ---

打开一个简单的Ruby文件需要超过一秒钟?

该文件中的相关行是:

1228.691  1123.486  1123.486: sourcing /usr/local/share/vim/vim80/ftplugin/ruby.vim

为什么我们要在ruby.vim 中花费一秒钟?答案就在这个函数中,它在打开一个.rb文件之前被执行。

function! s:query_path(root) abort
  let code = "print $:.join %q{,}"
  if &shell =~# 'sh' && empty(&shellxquote)
    let prefix = 'env PATH='.shellescape($PATH).' '
  else
    let prefix = ''
  endif
  if &shellxquote == "'"
    let path_check = prefix.'ruby --disable-gems -e "' . code . '"'
  else
    let path_check = prefix."ruby --disable-gems -e '" . code . "'"
  endif

注意:ftplugin 代表文件类型,而不是FTP - 所以是的,这个逻辑是需要的。

在所有这些之后,我又做了一个测试:在另一个tmux窗口中使用top ,我实际上可以看到在Vim之后运行的Java进程,因此问题是微不足道的:vim-ruby 是使用JRuby。

合理的下一步是:如果检测到使用JRuby的RVM,则指示Vim使用CRuby。经过一些 googling,解决方案是.vimrc 的一个附录。

if !empty(matchstr($MY_RUBY_HOME, 'jruby'))
  let g:ruby_path = '/usr/bin/ruby'
endif

基本上,如果RVM已经设置了JRuby,通过其有用的ruby_path 配置指示vim-ruby ,使用系统默认的Ruby(在macOS上是--CRuby版本2.0.0p648)

修复后的结果:

104.643  002.876  002.876: sourcing /usr/local/share/vim/vim80/syntax/ruby.vim
106.938  001.369  001.369: sourcing /usr/local/share/vim/vim80/ftplugin/ruby.vim
108.062  000.622  000.622: sourcing /usr/local/share/vim/vim80/indent/ruby.vim
{ edited }
152.700  044.957: opening buffers
153.389  000.689: BufEnter autocommands
153.394  000.005: editing files in windows
154.086  000.692: VimEnter autocommands
154.092  000.006: before starting main loop
178.172  024.080: first screen update
178.174  000.002: --- VIM STARTED ---

~200ms => 好多了。