5

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?

3

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)}#??}"
}
  • I tried your first approach with having zsh 5.1.1 installed. It fails with the error gpDo (eval):1: command not found: __git_branch_names. Please note that I am also using oh-my-zsh if this allows for another solution. – JJD Mar 15 '16 at 11:15
  • 1
    @JJD Had you already performed a completion with git? That loads the function. Alternatively you can run _git once, which loads and executes the function (there's no way to load an autoloaded function without executing it, unfortunately). – Gilles Mar 15 '16 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.