I've read a few guides on zsh completion, but I am still confused. In our development environment we have a custom Git command called git new-branch
. I'd like zsh to auto-complete it for me after typing just git ne
and a Tab. How can I do that?
There are two different _git
completion files distributed - one by written and maintained directly by ZSH, and another written by Git contributors.
Using _whence -v _git
You can find the path to the file of the completion your $fpath
is using by default. The ZSH distributed _git
function is much better and includes the feature you need (and more) quoted below:
Say you got your own git sub-commands (git will run a program `git-foo' when you run "git foo") and you want "git f" to complete that sub commands name for you. You can make that sub-command known to the completion via the user-command style:
% zstyle ':completion:*:*:git:*' user-commands foo:'description for foo'
`user-commands' is a list style, so you can add any number of programs there. The :description part is optional, so you could add all git-* programs from your $path like this:
% zstyle ':completion:*:*:git:*' user-commands ${${(M)${(k)commands}:#git-*}/git-/}
That is, it suffices to add
zstyle ':completion:*:*:git:*' user-commands new-branch:'custom new branch function'
to your zshrc
.
If you would like to handle parameters to your custom command as well, then it is a better solution to use a custom compdef file. The file referenced above has some details on that as well:
Find a directory in your $fpath
to put a file with the following contents:
#compded git-new-branch
#description create a new branch (custom script)
# Use and execute here any builtin completion functions
You will also have available in that context any function defined in ZSH's _git
file - functions such as _git-log
and _git-add
. You can read the source code of ZSH's _git
.