ZSH – Tab Completion for Function with Git Commands

autocompletefunctiongitzsh

In zsh I am using the following function to delete a local and a remote branch with one command:

gpDo () {
    git branch -d "$1" && git push --delete origin "$1"
}

Currently, auto-completion for the Git branch does not work. I have to manually type the whole branch name. How can I get tab completion working for such as function?

Best Answer

I assume you're using the β€œnew” completion system enabled by compinit. If you're using oh-my-zsh, you are.

You need to tell zsh to use git branch names for gpDo. Git already comes with a way to complete branch names. As of zsh 5.0.7 this is the function __git_branch_names but this isn't a stable interface so it could change in other versions. To use this function, put this line in your .zshrc:

compdef __git_branch_names gpDo

With this declaration, completion after gpDo will only work after you've completed something on a git command line at least once. This is due to a quirk of function autoloading in zsh. Alternatively, run _git 2>/dev/null in your .zshrc; this causes an error because the completion function is called in an invalid context, but the error is harmless, and the side effect of loading _git and associated functions including __git_branch_names` remains.

Alternatively, define your own function for git branch completion. Quick-and-dirty way:

_JJD_git_branch_names () {
  compadd "${(@)${(f)$(git branch -a)}#??}"
}
Related Question