I am writing zsh completion functions for a couple of commands from the same toolkit.

The commands are different enough that I want to write different completions for them in different files. (i.e. the completion for do_thingA is in a file _do_thingA with a #compdef do_thingA header, and the completion for do_thingB is in _do_thingB with #compdef do_thingB).

As different as they are, the commands all have one argument in common. So with all the things that differ between the commands, at some point all _do_thing files contain something along the lines

_arguments \
  '-c[common option]:common option:_helper_function' \

I would like to avoid having the same _helper_function defined in all _do_thing files. And on top I would like to allow users to provide their own (better personalised _helper_function).

What's the best way to achieve this?

things considered:

definition guard

I already know that I can prevent myself from overwriting the _helper_function if it is already defined with

(( $+functions[_helper_function] )) ||
_helper_function() {

which I could put into every of the _do_thing files. But I would prefer outsourcing the _helper_function into a separate _helper_function file.

putting function body in separate file

If I create a file _helper_function (and have it somewhere in the fpath) its content will become the function body of a _helper_function function. In this scenario I don't see how to put the definition guard around the _helper_function() header (since I don't write it myself anymore).


One method would be to place _helper_function somewhere in fpath and then in .zshrc

autoload -U _helper_function

Then if the user wants to customize it they merely place a new _helper_function file into fpath such that their version is found before yours, e.g. into a firstfuncdir:

% cd
% mkdir firstfuncdir
% fpath=(~/firstfuncdir $fpath)
% print -l $fpath

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.