Zsh – Set Autocompletion Rules for Second Argument

autocompletegitzsh

I have a custom Zsh function g:

function g() {
  # Handle arguments [...]
}

Within it, I handle short arguments that execute Git commands. For example:

g ls # Executes git ls-files ...
g g  # Executes git grep ...

I need to be able to set the autocompletion rules to Git's rules for the short arguments but I am unsure of how to do this.

For example, I need g ls <TAB> to tab-complete the rules for git ls-files <TAB> which would give me the arguments for git ls-files:

$ g ls --<TAB>
--abbrev                 -- set minimum SHA1 display-length
--cached                 -- show cached files in output
--deleted                -- show deleted files in output
# Etc...

This is not simply setting g to autocomplete for git since I'm mapping my custom short commands to the Git commands.

Best Answer

I found /usr/share/zsh/functions/Completion/Unix/_git which had some tips for aliases like this and ended up defining these functions for the aliases:

_git-ls () {
  # Just return the _git-ls-files autocomplete function
  _git-ls-files
}

Then, I did a straight compdef g=git. The autocomplete system will see that you are running, for example, g ls and use the _git-ls autocomplete function.

Thanks to user67060 for steering me in the right direction.

Related Question