#compdef odd
#
# zsh completion for odd.
#
# Install: put this file's directory on $fpath before compinit. After
# `opam install` it lives under the package's share dir; add to ~/.zshrc:
#
#     fpath=("$(opam var odd:share)/zsh" $fpath)
#     autoload -U compinit && compinit
#
# (or point $fpath at completions/zsh in a source checkout.)
#
# Reference arguments (to `doc` and `complete`) are completed by calling
# `odd complete`, which resolves the partial reference against the whole
# switch and returns the candidates — so completion is always in sync with the
# command's own resolver (Stdlib open, package-qualified `/pkg/...` paths, kind
# tags like `type-`, section labels, …).

local -a cmds
cmds=(
  'doc:print an item'\''s documentation as Markdown'
  'complete:list the completions of a partial reference'
  'search:search the switch documentation'
  'sync:bring the switch documentation up to date'
  'rebuild:mark packages stale and rebuild their docs'
  'order:print the dependency order sync would use'
  'setup:configure the opam hooks'
)

# Word 1 is "odd"; word 2 is the subcommand.
if (( CURRENT == 2 )); then
  _describe -t commands 'odd command' cmds
  return
fi

case ${words[2]} in
  (doc|complete)
    local cur=${words[CURRENT]} prev=${words[CURRENT-1]}
    if [[ $cur == -* ]]; then
      compadd -- --prefix --help
    elif [[ $prev == (--prefix|-p) ]]; then
      _files -/
    else
      # Hand the current word to `odd complete`; it returns full
      # reference strings. Empty suffix so dotted/slashed references can be
      # drilled into (type `.` and complete again).
      local -a refs
      refs=(${(f)"$(odd complete -- "$cur" 2>/dev/null)"})
      compadd -S '' -- $refs
    fi
    ;;
esac
