#-*- mode: shell-script;-*-

# darcs command line completion.
# Copyright 2002 "David Roundy" <droundy@abridgegame.org>
# This archive should be copied in the directory /etc/bash_completion.d/

_darcs()
{
    local cur
    cur=${COMP_WORDS[COMP_CWORD]}

    COMPREPLY=()

    if (($COMP_CWORD == 1)); then
        COMPREPLY=( $( darcs --commands | command grep "^$cur" ) )
        return 0
    fi

    # Store the whole command line substituting the (possibly empty)
    # to-be-completed word with '--list-options'.
    local -a words=("${COMP_WORDS[@]}")
    words[$COMP_CWORD]="--list-options"

    # Options are processed from left to right, so avoid to display the help
    # page when trying to complete a command line that includes '--help'. It
    # could be tricked by things like '--repodir --hell', but, come on... you
    # don't deserve a working completion if you name a directory '--hell'.
    for w in "${words[@]}"; do
        case "$w" in
            (--he*) return 0;;
        esac
    done

    # So that the following "command-output to array" operation splits only at
    # newlines, not at each space, tab or newline.
    local IFS=$'\n'
    COMPREPLY=( $( "${words[@]}" 2>/dev/null |\
        command grep "^${cur//./\\.}" | cut -d ';' -f 1) )

	# Then, we adapt the resulting strings to be reusable by bash. If we don't
	# do this, in the case where we have two repositories named
	# ~/space in there-0.1 and ~/space in there-0.2, the first completion will
	# give us:
	# bash> darcs push ~/space in there-0.
	# ~/space in there-0.1 ~/space in there-0.2
	# and we have introduced two spaces in the command line (if we try to
	# recomplete that, it won't find anything, as it doesn't know anything
	# starting with "there-0.").
	# printf %q will gracefully add the necessary backslashes.
	#
	# Bash also interprets colon as a separator. If we didn't handle it
	# specially, completing http://example.org/repo from http://e would 
	# give us:
	# bash> darcs pull http:http://example.org/repo
	# An option would be to require the user to escape : as \: and we
	# would do the same here. Instead, we return only the part after
	# the last colon that is already there, and thus fool bash. The
	# downside is that bash only shows this part to the user.
    local i=${#COMPREPLY[*]}
    local colonprefixes=${cur%"${cur##*:}"}
    while [ $((--i)) -ge 0 ]; do
      COMPREPLY[$i]=`printf %q "${COMPREPLY[$i]}"`
      COMPREPLY[$i]=${COMPREPLY[$i]#"$colonprefixes"} 
    done
    return 0
}
complete -F _darcs -o default darcs