#
# Figure out where to get the best help, and get it.
#
# This version adapted for Debian GNU/Linux by Robert Leslie <rob@mars.org>
# from source written by Bart Schaefer <schaefer@brasslantern.com>.
#

emulate -R zsh
setopt localoptions

: ${HELPDIR:=/usr/lib/zsh/help}

[[ $1 == "." ]] && 1="dot"
[[ $1 == ":" ]] && 1="colon"

if [[ $# == 0 || $1 == "-l" ]]
then
    if [[ -n "${HELPDIR:-}" && -d $HELPDIR ]]
    then
	echo "Here is a list of topics for which special help is available:"
	echo ""
	print -rc $HELPDIR/*(:t)
    else
	echo "There is no list of special help topics available at this time."
    fi
    return 0
elif [[ -n "${HELPDIR:-}" && -r $HELPDIR/$1 && $1 != compctl ]]
then
    ${=PAGER:-more} $HELPDIR/$1
    return $?
fi

# No zsh help; use "whence" to figure out where else we might look
local what places newline='
'
integer i=0 didman=0

places=( "${(@f)$(builtin whence -va $1)}" )

while ((i++ < $#places))
do
    what=$places[$i]
    builtin print -r $what
    case $what in
    (*( is an alias)*)
	[[ ${what[(w)6]:t} != ${what[(w)1]} ]] && run-help ${what[(w)6]:t}
	;;
    (*( is a * function))
	builtin functions ${what[(w)1]} | ${=PAGER:-more}
	;;
    (*( is a * builtin))
	case ${what[(w)1]} in
	(compctl) man zshcompctl;;
	(bindkey) man zshzle;;
	(*setopt) man zshoptions;;
	(*) man zshbuiltins;;
	esac
	;;
    (*( is hashed to *))
	man ${what[(w)-1]:t}
	;;
    (*)
	((! didman++)) && man $1
	;;
    esac
    if ((i < $#places && ! didman))
    then
	builtin print -nP "%S Press any key for more help or Q to quit %s"
	builtin read -k what
	[[ $what != $newline ]] && echo
	[[ $what == [qQ] ]] && break
    fi
done
