#compdef mailctl
#
# zsh completion for mailctl.
#
# There is deliberately no command tree in here.  "mailctl __complete" is
# handed the words typed so far and answers with what may follow the last of
# them: one candidate per line, name and description separated by a tab, or
# the single line ":files" when the argument is a path.  The tree lives in the
# tool itself (complete.go), so this function stays as it is when a command is
# added - and it can never describe a grammar the tool no longer has.
#
# Narrowing the answer down to what has been typed is left to the shell, so
# that the usual matcher-list styles keep working.

# zsh writes "--" between a value and its description; a single hyphen is
# quieter.  Only mailctl's own completion is affected, and only when nothing
# has been set for it already - an explicit setting of your own stays.
zstyle -m ':completion:*:*:mailctl:*' list-separator '*' ||
    zstyle ':completion:*:*:mailctl:*' list-separator '-'

local bin=mailctl
whence -p mailctl >/dev/null 2>&1 || bin=/usr/local/sbin/mailctl

local -a lines
lines=( ${(f)"$($bin __complete "${(@)words[2,CURRENT]}" 2>/dev/null)"} )

if [[ $lines[1] == ':files' ]]; then
    _files
    return
fi

local -a values
local line name desc
for line in $lines; do
    if [[ $line == *$'\t'* ]]; then
        name=${line%%$'\t'*}
        desc=${line#*$'\t'}
    else
        name=$line
        desc=''
    fi
    # a colon inside a value would otherwise read as the separator
    values+=( "${name//:/\\:}${desc:+:$desc}" )
done

_describe -V -t mailctl 'mailctl' values
