###-begin-pnpm-completion-###
if type complete &>/dev/null; then
  _pnpm_completion () {
    local words cword
    if type _get_comp_words_by_ref &>/dev/null; then
      _get_comp_words_by_ref -n = -n @ -n : -w words -i cword
    else
      cword="$COMP_CWORD"
      words=("${COMP_WORDS[@]}")
    fi

    local si="$IFS"
    local completions completion
    IFS=$'\n' completions=$(COMP_CWORD="$cword" \
                           COMP_LINE="$COMP_LINE" \
                           COMP_POINT="$COMP_POINT" \
                           SHELL=bash \
                           pnpm completion-server -- "${words[@]}" \
                           2>/dev/null) || return $?
    COMPREPLY=()
    if [ -n "$completions" ]; then
      local word="${COMP_LINE:0:COMP_POINT}" replaced_prefix="" i
      word="${word##*[[:space:]]}"
      for ((i = ${#word} - 1; i >= 0; i--)); do
        if [[ "$COMP_WORDBREAKS" == *"${word:i:1}"* ]]; then
          replaced_prefix="${word:0:i+1}"
          break
        fi
      done
      while IFS= read -r completion; do
        printf -v completion '%q' "${completion#"$replaced_prefix"}"
        COMPREPLY+=("$completion")
      done <<< "$completions"
    fi
    IFS="$si"

    if [ "$COMPREPLY" = "__tabtab_complete_files__" ]; then
      COMPREPLY=($(compgen -f -- "$cword"))
    fi
  }
  complete -o default -F _pnpm_completion pnpm pn
fi
###-end-pnpm-completion-###

