#compdef man apropos whatis

_man() {
  local dirs expl mrd awk

  if [[ $service == man ]] && (( $words[(I)-l] + $words[(I)--local-file] )); then
    _files || return 0
  fi

  if (( ! $#manpath )); then
    local mp
    mp=($(manpath 2>/dev/null))
    [[ "$mp" == *:* ]] && mp=( ${(s.:.)mp} )
    manpath=( $mp )
  fi

  (( $#manpath )) || manpath=( ${(s.:.)$(manpath 2>/dev/null)} ) ||
      manpath=( /usr/man(-/) /(opt|usr)/(dt|share|X11R6|local)/(cat|)man(-/) )

  # `sman' is the SGML manual directory for Solaris 7.
  # 1M is system administrator commands on SVR4

  mrd=(${^manpath/\%L/${LANG:-En_US.ASCII}}/mandb(N))

  local sect
  if [[ $OSTYPE = solaris* ]]; then
    sect=$words[$words[(i)-s]+1]
  elif [[ -n ${sect:=$words[$words[(i)-S]+1]} || -n ${sect:=$MANSECT} ]]; then
    if [[ $sect != ${sect::="${sect//:/|}"} ]]; then
      sect="($sect)"
    fi
  elif (( CURRENT > 2 )); then
    sect=$words[2]
  fi

  if [[ $sect = (<->*|1M|l|n) || $sect = \(*\|*\) ]]; then
    dirs=( $^manpath/(sman|man|cat)${~sect}/ )
    awk="\$2 == \"$sect\" {print \$1}"
  else
    dirs=( $^manpath/(sman|man|cat)*/ )
    awk='{print $1}'
  fi
  if zstyle -t ":completion:${curcontext}:manuals" separate-sections; then
    typeset -U sects
    local ret=1

    sects=( ${(o)${dirs##*(man|cat)}%/} )

    (( $#sects )) || return 1

    _tags manuals.${^sects}
    while _tags; do
      for sect in $sects; do
        _requested manuals.$sect expl "manual page, section $sect" _man_pages &&
            ret=0
      done
      (( ret )) || return 0
    done

    return 1
  else
    sect=
    _wanted manuals expl 'manual page' _man_pages
  fi
}

_man_pages() {
  local matcher pages dummy

  zparseopts -E M+:=matcher

  if (( $#matcher )); then
    matcher=( ${matcher:#-M} )
    matcher="$matcher"
  else
    matcher=
  fi

  pages=( ${(M)dirs:#*$sect/} )
  compfiles -p pages '' '' "$matcher" '' dummy '*'
  pages=( ${^~pages}(N:t:r) )

  (($#mrd)) && pages[$#pages+1]=($(awk $awk $mrd))

  # Remove any compression suffix, then remove the minimum possible string
  # beginning with .<->: that handles problem cases like files called
  # `POSIX.1.5'.

  compadd "$@" - ${pages%.(?|<->*)}
}

_man "$@"
