Search code examples
zshtab-completionprogrammable-completion

zsh: use completions for command X when I type command Y


In zsh, I have a function called g which acts like this:

  • with no arguments, call git status
  • with one or more arguments, delegate to git with all given arguments - i.e. call git $@

I would like the tab completions for g to be exactly the same as for git. I can achieve this with alias g=git, but that doesn't allow me to call status by default (the first point above).

How can I delegate to the completion for git?

In bash, I simply did complete -F _git g which re-uses git's completion function. With zsh, git's completion looks much more complex, and I wan't able to find a similar solution.

I'd guess there's some function in zsh to say "pretend I typed command [x], what would you complete it to?". If I knew what that was, it should be simple enough to use a function to delegate to it. But I've found no such function in the manuals.


Solution

  • The documentation for compdef says this:

    The function compdef can be used to associate existing completion functions with new commands. For example,

    compdef _pids foo
    

    But adapting it (_git is the usual completion function for git) did not produce a working result for me (even after _git had been autoloaded):

    compdef _git g
    

    I was able to get it to work via _dispatch though:

    compdef '_dispatch git git' g