自定义 zsh 自动完成

mik*_*ike 5 zsh autocomplete oh-my-zsh

我想为 pytest 编写一个 zsh 完成。

我从哪里开始?我正在使用 oh-my-zsh。

在 .zshrc 中:

fpath=($HOME/.mycompletions $fpath)
autoload -U compinit && compinit -u
Run Code Online (Sandbox Code Playgroud)

在 $HOME/.mycompletions/_pytest 中:

#compdef pytest

_pytest()
{
    cur="${COMP_WORDS[COMP_CWORD]}"
    COMPREPLY=(`pytestcomplete ${cur} 2>/dev/null`)
}
complete -o nospace -F _pytest py.test
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是正确的吗?

现在我“只”需要编写pytestcomplete脚本。

返回值应该是什么样的?如何将已完成的部分交给脚本?

即如果用户这样py.test<TAB>做应该首先完成文件。如果这样做,py.test tests/my.test.py<TAB>它应该完成类名。如果这样做,py.test tests/my.test.py::TestClass<TAB>它应该完成方法名称。

要从 pytest 中获取信息,可以使用--collect-only. 目前唯一的问题是 zsh 和完成脚本之间的来回。

这可以像这样完成还是我需要编写一个 oh-my-zsh 插件?

Mar*_*ert 0

您不需要为此编写自己的完成函数。您可以简单地重复使用pytest的 Bash 补全:

  1. 安装argcomplete
    pip install argcomplete
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将以下内容添加到您的.zshrc
    autoload -Uz bashcompinit && bashcompinit
    eval "$(register-python-argcomplete pytest)"
    
    Run Code Online (Sandbox Code Playgroud)
  3. 重新启动你的外壳。
  4. 完毕!