Expanding aliases in zsh

2014-06-25

I wanted to make some of my zsh aliases behave like vim abbreviations: Namely, as soon as you press space, the alias is expanded and you see the expanded command before executing it. Since I have a large number of clunky aliases, I didn’t want all aliases to be expanded by default.

Consequently, I came up with the following (based on something I first saw here).

typeset -a ealiases
ealiases=()

function ealias()
{
    alias $1
    ealiases+=(${1%%\=*})
}

function expand-ealias()
{
    if [[ $LBUFFER =~ "\<(${(j:|:)ealiases})\$" ]]; then
        zle _expand_alias
        zle expand-word
    fi
    zle magic-space
}

zle -N expand-ealias

bindkey -M viins ' '        expand-ealias
bindkey -M viins '^ '       magic-space     # control-space to bypass completion
bindkey -M isearch " "      magic-space     # normal space during searches

The last three bindkey commands are assuming you are primarily using VI mode. If you’re not, you might need to either remove the -M viins above, or replace it with -M emacs, etc.

Finally, to define an expandable alias use ealias. The syntax of ealias is the same as that of alias For example, I use

ealias gc='git commit'
ealias gp='git push'

Now typing gc in a position where zsh expands a command will appear like you typed git commit.

🗫 Comments

  • Anonymous
    A little question

    Anonymous (2019-12-22 06:26:53 EST)

    How to understand this statement "\<(${(j:|:)ealiases})\$"?

  • Gautam Iyer
    Re: A little question

    Gautam Iyer (2019-12-24 05:25:40 EST)

    How to understand this statement "\<(${(j:|:)ealiases})\$"?

    It’s described in the zshexpn man page. It joins all elements of the ealiases array with |, and so the above gives a regular expression matching any existing expandable alias.

📮 Leave a comment (Spammers beware: All comments are moderated)

Sorry. There was an error submitting your comment. Please try again, or contact me if the problem persists.
Sending comment; please wait.
Thanks. Your comment was successfully submitted. It will appear here shortly if it isn't spam.