Zsh completion of arbitrary commands

I spent a good few hours over the weekend trying to figure out how do something with zsh completion that I figured would probably be quite simple but I just couldn’t find an example of anywhere.

I wanted to do tab completion based on the output of an arbitrary command.

This was so that I could make full use of AndyA‘s very useful directory shortcut pind script.

Essentially I was porting the _cdpin function from bash to zsh.


function _cdpin() {
local cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=(
$( hasle ~/.pind -cx $cur )
)
}

complete -F _cdpin cdpin

It looked like it should be simple but after reading sections of the zsh manual, searching online, looking at the various completion scripts in my zsh installation and trawling Stack Overflow’s zsh content I couldn’t find a succinct example.

Eventually I found the answer in a book called From Bash to Z Shell which I was able to read on my Safari Books Online subscription.

The solution turned out to be ludicrously simple:


function _cdpin() {
compadd $(hasle ~/.pind -cx)
}

compdef _cdpin cdpin

I could make it even simpler if I stuck if in a file called _cdpin but I wanted to keep it in the same place as the functions.

Now when I type cdpin and hit tab I get a list of my existing entries and I can complete from there.

Annoying that something so simple was so hard to find so I’m posting it here in the hope it helps others.

And as AndyA was smart enough to share his scripts on github I’ve forked it and will add zsh support (via a conditional) and see if I can get him to pull in my changes (I’m sure he’ll do it if I buy him a beer).

As an aside, gotta say I’m loving github – I joined a few months back but have only just started uploading some code to it.

You can see my stuff at github.com/boncey.

Leave a Reply

Your email address will not be published. Required fields are marked *