#! /usr/bin/zsh -f

# copied from space_separated
function autoload_widget()
{
    autoload $1
    zle -N $1
}
autoload_widget forward-word-match


edit-alias() {
    # Function to populate next command-line with this template:
    local expanded_alias
    expanded_alias="$(alias $1)"  ||  return 1
    # populate BUFFER:
    print -z alias $expanded_alias
}


# expand the 1st word as an alias:
# not previous
my-expand-alias() {
    # get the 1st sequence of non space:
    zle beginning-of-line;
    zle forward-word-match

    # forward
    # bug!
    # If we are  *really* after the end of the word, then this is ok
    # otherwise   "cff" will expand to "cf" + "f" !
    # zle  backward-char;

    if [ ' ' = ${LBUFFER[$CURSOR]} ];
    then
        zle backward-char;
    fi

    # for safety, in case there's an = which will mess things up...
    local alias=${LBUFFER#*=}
    # echo ">$alias<"
    if [ -z $alias ]
    then
        zle beep
        WORDCHARS=old
        return 1
    fi

    if  ! alias=$(alias $LBUFFER) ; then
        zle beep
        WORDCHARS=old
        return 1
    fi
    LBUFFER=${(Q)${alias#*=}}
    # subtract & add string lenghts
    # position=$CURSOR+ ${alias#*=}

    WORDCHARS=old
}


zle -N my-expand-alias

# [05 lug 06] mmc:   So I go back to my function:
bindkey '^[^e' my-expand-alias

# in 4.2.5, if i try to expand an alias which starts with "- " (e.g. alias ds='- du -x -s *(/) |sort -n| human 1024')
# bindkey '^[^e' _expand-alias  fails!
# 2020: I cannot reproduce it, so reinstate:
bindkey '^[^e' _expand_alias

output_region (){
    region=${LBUFFER[0,$CURSOR]}
    echo $CURSOR $MARK $region
}

zle -N output_region
