#autoload

# This is intended to be used as a completer function after the normal
# completer as in: `compstyle "*" completer _complete _match'.
# It temporarily switches on pattern matching, allowing you to try 
# completion on patterns without having to setopt glob_complete.
#
# Note, however, that this is only really useful if you don't use the
# expand-or-complete function because otherwise the pattern will
# be expanded using globbing.

local tmp opm="$compstate[pattern_match]" ret=0 orig ins
local curcontext="${curcontext}:match"

# Do nothing if we don't have a pattern or there are still global
# match specifications to try.

tmp="${${:-$PREFIX$SUFFIX}#[~=]}"
[[ "$tmp:q" = "$tmp" ||
   compstate[matcher] -ne compstate[total_matchers] ]] && return 1

_style -s '' original orig
_style -b '' insert-unambiguous ins

# Try completion without inserting a `*'?

if [[ -n "$orig" ]]; then
  compstate[matcher]=-1
  compstate[pattern_match]='-'
  _complete && ret=1
  compstate[pattern_match]="$opm"
  compstate[matcher]="$compstate[total_matchers]"

  if (( ret )); then
    [[ "$ins" = yes &&
       $#compstate[unambiguous] -ge ${#:-${PREFIX}${SUFFIX}} ]] && 
        compstate[pattern_insert]=unambiguous
    return 0
  fi
fi

# No completion with inserting `*'?

[[ "$orig" = only ]] && return 1

compstate[matcher]=-1
compstate[pattern_match]='*'
_complete && ret=1
compstate[pattern_match]="$opm"
compstate[matcher]="$compstate[total_matchers]"

[[ ret -eq 1 && "$ins" = yes &&
   $#compstate[unambiguous] -ge ${#:-${PREFIX}${SUFFIX}} ]] && 
    compstate[pattern_insert]=unambiguous

return 1-ret
