【问题标题】:zsh: use completions for command X when I type command Yzsh:当我输入命令 Y 时,对命令 X 使用补全
【发布时间】:2011-05-12 09:32:07
【问题描述】:

在 zsh 中,我有一个名为 g 的函数,其作用如下:

  • 没有参数,调用git status
  • 带有一个或多个参数,将所有给定参数委托给 git - 即调用 git $@

我希望g 的制表符完成与git 完全相同。我可以使用alias g=git 来实现这一点,但这不允许我默认调用status(上面的第一点)。

我如何委托git 完成?

在 bash 中,我只是做了complete -F _git g,它重用了 git 的完成功能。使用 zsh,git 的补全看起来要复杂得多,我也找不到类似的解决方案。

我猜 zsh 中有一些功能可以说“假装我输入了命令 [x],你会完成它来做什么?”。如果我知道那是什么,那么使用函数委托给它应该很简单。但是我在手册中没有找到这样的功能。

【问题讨论】:

  • 感谢您提供有关如何使其在 bash 中工作的提示!

标签: zsh tab-completion programmable-completion


【解决方案1】:

compdef 的文档是这样说的:

函数compdef 可用于将现有完成函数与新命令相关联。例如,

compdef _pids foo

但调整它(_git 是 git 的常用完成功能)并没有为我产生工作结果(即使在 _git 已自动加载之后):

compdef _git g

我可以通过_dispatch 让它工作:

compdef '_dispatch git git' g

【讨论】:

  • 这很奇怪。我也发生了同样的事情,但其他完成功能在第一个命令中工作得很好。
  • 太好了,非常感谢!至于为什么第一个不起作用,也许 _git 的完成是足够自定义的,仅仅重定向它不足以让它响应任何有用的东西? (即它可能会检查命令是否以“git”开头)
  • 知道如何调整 compdef '_dispatch git git' g 以使 g 像 git-status 一样自动完成,而不仅仅是 git?
  • 当我直接在 zsh shell 中运行它时,这对我有用,但由于某种原因,当我把它放在我的 .zshrc 时它不起作用。
【解决方案2】:

在更改配置后,相同的功能已停止为我工作。

# in ~/.zsh/functions/g.zsh

# # No arguments: `git status`
# # With arguments: acts like `git`
g() {
  if [[ $# > 0 ]]; then
    git "$@"
  else
    git status
  fi
}

实际上很重要的是将函数放在~/.zsh/functions/g.zsh 中并在~/.zsh/completions/_g 中创建一个compdef:

#compdef g
compdef g=git

然后,在.zshrc:

fpath=($HOME/.zsh/completions $fpath)

# load custom executable functions
for function in ~/.zsh/functions/*.zsh; do
  source $function
done

# completion
autoload -U compinit
compinit

不确定订单是否重要。我认为当 compdef 位于单独的文件夹中时,它适用于任何顺序。

从这里获得g 函数:

https://github.com/thoughtbot/dotfiles/blob/master/zsh/functions/g

https://github.com/thoughtbot/dotfiles/blob/master/zsh/completion/_g

感谢 Thoughtbot!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多