# -*- shell-script -*-

################################################################################

bashrun_completion=''

function §completion.init {
    §completion.set $(§mode.get_completion)
}

function §completion.set {

    local ctype="$1"
    local atype="$2"
    local threshold="${3:-0}"

    if [[ $# -eq 3 && $threshold -gt 0 ]]; then
	§completion.apply_threshold "$ctype" "$atype" "$threshold"
	return $?
    fi

    if [[ "$bashrun_completion" == "$ctype" ]]; then
	return 0
    fi

    if [[ "$bashrun_completion" == "quiet-complete" ]]; then
	
        # if we're changing from quiet-complete, reset readline
        # settings to user's initial settings
	§readline.reset "page-completions"
	§readline.reset "print-completions-horizontally"
	§readline.reset "completion-query-items"
    fi

    # set completion type
    case "$ctype" in
	"complete")
	    bind '"\t":complete'
	    ;;
	menu-complete)
	    bind '"\t":menu-complete'
	    ;;
	quiet-complete)
	    bind '"\t":complete'
	    bind 'set page-completions off'
	    bind 'set print-completions-horizontally on'
	    bind 'set completion-query-items -1'
	    ;;
	*)
	    §debug "unknown completion type:" -v "$ctype"
	    ;;
    esac
    bashrun_completion="$ctype"
    §debug -v "$ctype"
}

function §completion.apply_threshold {

    local ctype="$1"
    local atype="$2"
    local threshold="$3"

    declare -i t=$threshold

    if [[ $bashrun_window_height -ge $t ]]; then
	§completion.set "$atype"
    else
	§completion.set "$ctype"
    fi

    if [[ bashrun_window_height -gt 1 ]]; then
	bind 'set horizontal-scroll-mode off'
    else
	bind 'set horizontal-scroll-mode on'
    fi
}

