_mail_complete_available_addresses ()
{
    local prefix="$1"
    if [ -z "$_mail_available_addresses" ]
    then
	# Cache the complete list because it rarely changes and makes
	# completion much faster.
	_mail_available_addresses="$(${COMP_WORDS[0]} neomutt -A 2> /dev/null \
                                    | cut -f1)"
    fi
    COMPREPLY=($(compgen -W "$_mail_available_addresses" -- "$prefix"))
}

_mail_is_command ()
{
    local word
    local result="false"
    for word in ${COMP_WORDS[*]}
    do
	if [ "$word" = "$1" ]
	then
	    result=true
	    break
	fi
    done
    $result
}

_mail_complete()
{
    local word_count=${#COMP_WORDS[*]}
    local word_at_point="${COMP_WORDS[$COMP_CWORD]}"
    case $COMP_CWORD in
        1)
	    if [ -z "$_mail_subcommands" ]
	    then
		# Cache the list of subcommands to speed things up.
		_mail_subcommands="$(mail --help 2> /dev/null \
                                     | grep '^  ' | cut -c 2-)"
	    fi
            COMPREPLY=($(compgen -W "$_mail_subcommands" -- "$word_at_point"))
            ;;
        *)
            if _mail_is_command "neomutt" || _mail_is_command "inbox"
            then
                _mail_complete_available_addresses "$word_at_point"
            fi
            ;;
    esac
}

complete -F _mail_complete mail
