# elm(1) completion.  See Debian package "elm-me+".
# Written by Joe Nahmias <joe@nahmias.net> and Matej Vela <vela@debian.org>.

have elm &&
_elm()
{
	local cur prev maildir

	COMPREPLY=()
	cur=${COMP_WORDS[COMP_CWORD]}
	prev=${COMP_WORDS[COMP_CWORD-1]}

	case $prev in
	-*[As])
		_filedir
		;;
	-*f)
		# Mail folder completion.
		if [[ $cur == =* ]]; then
			# Determine Elm's mail folder directory (maildir).
			eval "maildir=$( sed \
			 's/^[[:space:]]*maildir[[:space:]]*=[[:space:]]*//I
			  th; bg; :h; h; :g; $!d; g
			  # Allow tilde and environment variable expansion...
			  s/[[:space:]"&'\''();<>`|\]/\\&/g
			  # ... but only at path component boundaries.
			  s,\([^/]\)\$,\1\\$,g' \
			 /etc/elm-me+/elm.rc ~/.elm/elmrc 2>/dev/null )"
			: ${maildir:=~/Mail}

			# Match any file in $maildir beginning with $cur
			# (minus the leading equals).
			COMPREPLY=( $( compgen -f -- "$maildir/${cur:1}" ) )
			COMPREPLY=( ${COMPREPLY[@]#$maildir/} )
		else
			_filedir
		fi
		;;
	*)
		# E-mail address completion.  Can't use _user_at_host because
		# it requires `-o nospace', which doesn't mesh well with
		# filename completion above.
		if [[ $cur == *@* ]]; then
			_known_hosts
		else
			COMPREPLY=( $( compgen -u -- "$cur" ) )
		fi

		# Elm alias completion.
		COMPREPLY=( $( compgen -W '$( elmalias -f %a )' -- "$cur" )
			    ${COMPREPLY[@]} )
		;;
	esac

	return 0
}
[ "$have" ] && complete -F _elm $filenames elm
