#autoload
local -a match=() mbegin=() mend=()  # `zstyle` for some reason assigns these.

unset MENUMODE MENUSELECT

local -i nmatches
if [[ $compstate[old_list] == keep ]]; then
  (( nmatches = _lastcomp[nmatches] ))
else
  (( nmatches = compstate[nmatches] ))
fi

[[ $WIDGETSTYLE == (|*-)menu(|-*) ]]
local -i is_menu=$(( ! ? ))

if (( is_menu )); then
  compstate[list]='list force'
else
  compstate[list]=
  zle -Rc
fi

if  [[ $compstate[old_list] == keep && $_lastcomp[completer] == prefix ]] ||
    [[ $_completer == prefix ]]; then
  compstate[to_end]=
else
  compstate[to_end]='match'
fi

{
  compstate[insert]=

  if [[ $compstate[unambiguous] != (|$PREFIX$SUFFIX) ]] && _autocomplete__should_insert_unambiguous
  then
    (( is_menu )) &&
      compstate[insert]='automenu-'
    compstate[insert]+='unambiguous'
    return
  fi

  if (( is_menu )); then
    if [[ $WIDGETSTYLE == (|*-)select(|-*) ]]; then
      typeset -gi MENUSELECT=0

      if [[ $WIDGET == (|*-)search(|-*) ]]; then
        typeset -g MENUMODE=search-forward
      fi
    fi

    compstate[insert]='menu:'
  fi

  if [[ $WIDGET == (|.)reverse-* || $WIDGETSTYLE == (|.)reverse-menu-complete ]]; then
    compstate[insert]+='0'
  else
    compstate[insert]+='1'
  fi

  if (( ! is_menu )) && _autocomplete__should_add_space; then
    compstate[insert]+=' '
  fi
  return 0
} always {
  if [[ -n $compstate[insert] ]]; then
    typeset -g _autocomplete__inserted
  else
    unset _autocomplete__inserted
  fi
}
