LoginSignup
16
14

More than 5 years have passed since last update.

vimのコマンドライン補完を自作する。

Posted at

vimのコマンドライン補完関数の基本的な作り方まとめ。

書式

コマンドに独自の補完関数を指定するときは、コマンド定義時に引数に-complete=customlist,{func}を指定する。

command! -nargs=1 -complete=customlist,{func} {cmd} {rep}

補完関数は補完候補のリストを返せばいい。

function {func}(lead, line, pos)
  return ['abc', 'efg']
endfunction

引数の意味

仮引数名 説明
lead カーソル下の引数文字列
line コマンド名を含めたコマンドライン全体の文字列
pos lineの先頭文字を0とした時のカーソル位置

サンプル

:editをラップしただけの:Editコマンドと補完候補を3つ返すだけの補完関数。

" コマンドを定義
command! -nargs=1 -complete=customlist,CompSamp Edit :edit <args>

" 補完関数を定義
function! CompSamp(lead, line, pos)
  return ['~/.bashrc', '~/.zshrc', '~/vimrc']
endfunction

デバッグ

補完関数中では出力ができないようなので、:echomsg {str}でメッセージ領域に出力して、:messageコマンドで確認する。

デバッグ (vimconsole)

毎回:messageを呼ぶのが面倒ならrbtnn/vimconsoleを使う手もある。
プラグインを導入したら以下の設定をするといい。

let g:vimconsole#auto_redraw = 1

最低限の使い方説明(詳細はdocを参照)。

:VimConsoleOpen              # 出力用ウィンドを開く。
:VimConsoleLog 'message'     # メッセージを出力する。

参考資料

:h :command-completion-customlist

複雑な補完を書きやすくするためのプラグインもあるらしい(使ったこと無い)。
LeafCage/lim.vim

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14