koturnの日記

普通の人です.ブログ上のコードはコピペ自由です.

NeoBundleの使い方

他人の.vimrcを見ていると,NeoBundleを用いてプラグインの管理をしている人が多い. かくいう僕もその一人である. しかし,NeoBundleの事情に詳しくない人は,どうも古い情報を参照しているため,以下のような古い仕様のNeoBundleに沿った記述や,そもそもイケてない記述をしていることがある.

if has('vim_starting')
  " ~/.vimrcの読み込みならば,自動的にnocompatibleになっているはず
  set nocompatible
  " 最近のNeoBundleでは必要ない
  filetype off
  set runtimepath+=~/.vim/bundle/neobundle.vim
endif
" neobundle#rc() より,neobundle#begin() を用いるべき
call neobundle#rc(expand('~/.vim/bundle/'))
" neobunde.vim自体は読み込みを行わないNeoBundleFetchで管理すべき
NeoBundle 'Shougo/neobundle.vim'

NeoBundle 'foo/bar'
NeoBundleLazy 'hoge/piyo', {
      \ 'autoload': {
      \   'commands': ['Piyo'],
      \ }
      \}

" ...

filetype plugin indent on

set nocompatibleは副作用の多いオプション設定で,他のオプション設定も変更することになる. 例えば,オプションhistoryの値がデフォルトの50に書き換えられたりする. デフォルトでvimが使用する.vimrc,例えば,~/.vimrcであれば,自動的にset nocompatibleになっているので,わざわざ.vimrc中で設定することは無い. また,

$ vim -u ~/other.vimrc

等としてvimを起動する場合であっても,オプション-Nを付加して起動すればよい. どうしても,set nocompatibleと書いて安心したいのであれば,

if !&compatible
  set nocompatible
endif

のように,互換モードか否かを判断してからにするべきだろう.

filetype offは,最近のNeoBundleでは内部で行っているため,わざわざ.vimrcに記述する必要が無いそうだ.

neobundle#rc()を用いていた場合,警告が出るので,言わずともneobundle#begin()neobundle#end()を用いる設定に書き換えることだろう.

以上のことを踏まえると,最近のNeoBundleでは以下のように記述するのが良い.

if has('vim_starting')
  set rtp+=~/.vim/bundle/neobundle.vim
endif
call neobundle#begin()
NeoBundleFetch 'Shougo/neobundle.vim'

NeoBundle 'foo/bar'
NeoBundleLazy 'hoge/piyo', {
      \ 'autoload': {
      \   'commands': ['Piyo'],
      \ }
      \}
call neobundle#end()
filetype plugin indent on

if !has('vim_starting')
  call neobundle#call_hook('on_source')
endif

また,NeoBundleのキャッシュ機能を利用するならば,以下のように記述する. (キャッシュ機能は実装当初と現在を比較すると,大きく仕様変更されているが,古い方の仕様は紹介しない)

if has('vim_starting')
  set rtp+=~/.vim/bundle/neobundle.vim
endif
call neobundle#begin()

" neobundle#load_cache() はキャッシュが最新ならば,0を返却する関数
if neobundle#load_cache()
  NeoBundleFetch 'Shougo/neobundle.vim'
  NeoBundle 'foo/bar'
  " Lazyの設定等はキャッシュされる
  NeoBundleLazy 'hoge/piyo', {
        \ 'autoload': {
        \   'commands': ['Piyo'],
        \ }
        \}
  NeoBundleSaveCache
endif
call neobundle#end()
filetype plugin indent on

" キャッシュされないプラグインのグローバル変数等の設定をここに
" neobundle#tap() は引数のプラグインがロードされているならば,1を返却する
if neobundle#tap('bar')
  let g:bar#var01 = 10
  let g:bar#var02 = ['a', 'b', 'c']
  call neobundle#untap()
endif

if neobundle#tap('piyo')
  " hooks.on_source() でプラグイン読み込み時の処理を指定できる
  " この程度(グローバル変数を設定するだけ)の処理ならば,無理に利用する必要はない
  " 時間のかかる処理などを記述すると吉
  function! neobundle#tapped.hooks.on_source(bundle) abort
    let g:piyo#var01 = 1
    let g:piyo#var02 = 'abc'
  endfunction
  call neobundle#untap()
endif

if !has('vim_starting')
  call neobundle#call_hook('on_source')
endif