logoalt Hacker News

alkhlast Thursday at 10:05 PM0 repliesview on HN

This snippet for zsh still has some rough edges but works for the majority of cases. Automatically extends any global alias when space is pressed in zsh. For ex. I have `alias -G G='rg -s'`, so if I type `command | G` it will autoexpand it to `command | rg -s` and so on.

  globalias() {
    local raw word
    # raw last blank-separated token, exactly as typed
    raw=${LBUFFER##\* }
    # shell-parsed last word
    word=${${(z)LBUFFER}[-1]}
    # if user typed \alias, don't expand
    if [[ $raw == \\* ]]; then
        zle self-insert
        return
    fi
    if alias -- ${(q)word} &>/dev/null; then
        zle _expand_alias
        zle expand-word
    fi
    zle self-insert
}

zle -N globalias bindkey ' ' globalias