# Coop Bash completion.
# Candidate lookup is best-effort; a failed lookup must not block the shell.
# Generate: coop completion bash > ~/.config/coop/completion.bash
# Source this file from ~/.bashrc.
_coop() {
  local candidate word prefix='' i last
  local -a words=()
  # Bash 4+ splits a target's colon into its own word; Bash 3.2 keeps it joined.
  for ((i=1; i<=COMP_CWORD; i++)); do
    word=${COMP_WORDS[i]}
    last=$((${#words[@]}-1))
    if ((last >= 0)) && [[ $word == : || ${COMP_WORDS[i-1]} == : ]]; then
      words[last]+=$word
    else
      words+=("$word")
    fi
  done
  word=${words[${#words[@]}-1]:-}
  if [[ ${COMP_WORDBREAKS:-} == *:* && $word == *:* ]]; then
    prefix=${word%:*}:
  fi
  COMPREPLY=()
  while IFS= read -r candidate; do
    # Readline replaces only the suffix after the last word-breaking colon.
    COMPREPLY+=("${candidate#"$prefix"}")
  done < <(coop __complete "${words[@]}" 2>/dev/null)
}
complete -o default -F _coop coop
