# -*- shell-script -*-

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

bashrun_readline_bindings=()
bashrun_readline_settings=()

function §readline.get_settings {
    # retrieve the original user's settings that are in effect
    # before bashrun alters any of them

    local restore=$IFS
    IFS=$'\n' 
    bashrun_readline_settings=($(bind -v))
    IFS=$restore    
}

function §readline.get_bindings {

    # retrieve the original user's keybindings that are in effect
    # before bashrun binds any keys of it's own

    local restore=$IFS
    IFS=$'\n' 
    bashrun_readline_bindings=($(bind -p; bind -s))
    IFS=$restore
}

function §readline.get_setting {

    local wanted="$1"
    local name=""
    local value=""

    local i=0
    for (( i=0; i<${#bashrun_readline_settings[@]}; i+=1 )); do

	[[ "${bashrun_readline_settings[$i]}" =~ ^set\ ([^\ ]+)\ (.+) ]]
	name="${BASH_REMATCH[1]}"
	value="${BASH_REMATCH[2]}"
	[[ "$name" == "$wanted" ]] && break
    done
    printf '%s' "$value"
}

function §readline.get_binding {

    local keyseq=$1
    local line='';
    local i=0

    for (( i=0; i<${#bashrun_readline_bindings[@]}; i+=1 )); do
	line=${bashrun_readline_bindings[$i]}
	[[ "$line" =~ ^# ]] && continue

	if [[ "$line" =~ .?${keyseq}\" ]]; then # FIXME: regexp ^ ?!
	    printf '%s' "$line"
	    return 0
	fi
    done    
}

function §readline.reset {
    local varname="$1"
    bind "set $varname $(§readline.get_setting $varname)"
}

function §readline.restore {
    local keyseq=$1
    local keymap=${2:-emacs}
    local readline=$(§readline.get_binding $keyseq)
    readline=${readline//\'/\\x27}
    
    local binding="-m $keymap '$readline'"    

    if [[ -n "$readline" ]]; then 
	§debug -v "bind $binding"
	eval "bind $binding"
    fi
}
