LoginSignup
0
0

zshで環境変数RBENV_VERSION, NODENV_VERSIONの値を補完する

Last updated at Posted at 2023-12-14

やりたいこと

$ 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>

のように環境変数名を補完できるようになるので便利。

0
0
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
0
0