Zsh autocomplete function based on 2 arguments

I have a function like this:

p() { cd ~/Clients/$1/Projects/$2; }

Then I can type:

p "Client here" "Project here"

and he accepts me:

~/Clients/Client here/Projects/Project here

Nothing special happens here. But how can I implement autocomplete for this function? I managed to get autocomplete for the first argument (clients):

_p() { _files -W ~/Clients -/; }
compdef _p p

But how do I autofill the second argument (projects)? It should be autocompleted from a client-based folder:

~/Clients/$1/Projects

Hope someone can help! :-)

+5
source share
1 answer

The smart person (Mikachu) at IRC helped:

p() { cd ~/Clients/$1/Projects/$2; }
_p() {
  _arguments '1: :->client' '2: :->project'
  case $state in
    client)
      _files -W ~/Clients
    ;;
    project)
      _files -W ~/Clients/$words[CURRENT-1]/Projects
    ;;
  esac 
}
compdef _p p

UPDATE: Change $ words [CURRENT-1] to $ {(Q) words [CURRENT-1]} so that it works with directories containing spaces:

p() { cd ~/Clients/$1/Projects/$2; }
_p() {
  _arguments '1: :->client' '2: :->project'
  case $state in
    client)
      _files -W ~/Clients
    ;;
    project)
      _files -W ~/Clients/${(Q)words[CURRENT-1]}/Projects
    ;;
  esac 
}
compdef _p p
+6
source

All Articles