やりたいこと
$ RBENV_VERSION=<Tab>
でインストールされているrubyのバージョン(2.5.7, 3.0.5, ...)を補完したい。nodeでも同様。
実装
下記ファイルを$fpath
のいずれかのディレクトリに配置する。$fpathはprint -l $fpath
で調べられる。
_rbenv_versions
#compdef -value-,RBENV_VERSION,-default-
local -a _versions
_versions=( ${(@f)"$(rbenv versions | sed -e 's@^..@@' -e 's@ .*@@')"} )
_describe -V -t versions Versions _versions
_nodenv_versions
#compdef -value-,NODENV_VERSION,-default-
local -a _versions
_versions=( ${(@f)"$(nodenv versions | sed -e 's@^..@@' -e 's@ .*@@')"} )
_describe -V -t versions Versions _versions
~/.zcompdumpを削除してzsh再起動する。
#compdefの説明
For the -value- context, the form is ‘-value-,name,command’, where name is the name of the parameter on the left hand side of the assignment. In the case of elements of an associative array, for example ‘assoc=(key ’, name is expanded to ‘name-key’. In certain special contexts, such as completing after ‘make CFLAGS=’, the command part gives the name of the command, here make; otherwise it is empty.
It is not necessary to define fully specific completions as the functions provided will try to generate completions by progressively replacing the elements with ‘-default-’. For example, when completing after ‘foo=’, _value will try the names ‘-value-,foo,’ (note the empty command part), ‘-value-,foo,-default-’ and‘-value-,-default-,-default-’, in that order, until it finds a function to handle the context.
https://zsh.sourceforge.io/Doc/Release/Completion-System.html
実装2
~/.zshrcに1行で
compdef -e '_versions=(${(f)"$(nodenv versions | sed -e "s@^..@@" -e "s@ .*@@")"}); _describe -V -t versions Versions _versions' '-value-,NODENV_VERSION,-default-'
と書いても同じ。
環境変数名も補完
なお~/.zshrcに
zstyle ':completion:*' fake-parameters {NODENV_VERSION,RBENV_VERSION}:string
と書いておくと、環境変数NODENV_VERSION, RBENV_VERSIONが定義されていないときでも
$ RBENV_V<Tab>
のように環境変数名を補完できるようになるので便利。