Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 it takes me to:

~/Clients/Client here/Projects/Project here

Nothing special going on here. But how do I implement autocomplete for this function? I managed to get autocompletion work for the first argument (clients):

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

But how do I autocomplete the second argument (projects)? It needs to be autocompleted from the folder based on the client:

~/Clients/$1/Projects

Hope somebody can help! :-)

like image 735
agronemann Avatar asked May 22 '12 10:05

agronemann


1 Answers

A clever person (Mikachu) on IRC helped out:

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]} to make it work 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
like image 114
agronemann Avatar answered Nov 14 '22 14:11

agronemann