#!/bin/zsh
zmodload zsh/complist
typeset -ga _autocomplete__suggest_ignore_widgets=()
typeset -g ZSH_AUTOSUGGEST_MANUAL_REBIND=1
typeset -g ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX=.autosuggest-orig-

${0}:c() {
  _autocomplete__suggest_ignore_widgets+=( $1 )
  builtin zle -C "$1" "$2" .autocomplete__${3}__completion-widget
}

${0}:z() {
  builtin zle -N "$1" .autocomplete__${2}__zle-widget
}

${0}:z   up-line-or-search{,}
${0}:z down-line-or-select{,}
${0}:z history-search{-backward,}

${0}:precmd() {
  emulate -L zsh \
      # -x
  setopt $_autocomplete__func_opts[@]

  0=${0%:*}

  # Create all completion widgets here, to avoid getting them wrapped by
  # Autosuggest or Syntax Highlighting.

  local -P tab_style=
  for tab_style in complete-word menu-complete menu-select; do
    ${0}:c "$tab_style" "$tab_style" complete-word
  done
  ${0}:c {,}reverse-menu-complete            complete-word
  ${0}:c insert-unambiguous-or-complete   {,}complete-word
  ${0}:c menu-search             menu-select complete-word
  ${0}:c history-search-backward menu-select history-search

  # Autosuggestions otherwise makes $WIDGETSTYLE disappear
  [[ -v ZSH_AUTOSUGGEST_IGNORE_WIDGETS ]] &&
      ZSH_AUTOSUGGEST_IGNORE_WIDGETS+=(
          $_autocomplete__suggest_ignore_widgets
      )

  unset _autocomplete__suggest_ignore_widgets
  unfunction ${0}:{c,z}
}
