Automatically Expanding zsh Global Aliases - Simplified

| Comments

Last year I set up a key binding to automatically expand zsh global aliases as you type. I am definitely not the first person to do this, but I recently discovered a much cleaner way to accomplish the same thing.

globalias demo animation

zsh already ships with a function called expand-alias. I was able to replace the majority of my own code with a call to this existing function. I probably could have almost gotten away with just binding expand-alias to the space bar. For my uses, though, I think this would have been an ugly solution.

I don’t often want to see regular aliases expanded. That would just clutter up my command line too often. I also use the pretty standard practice of using only capital letters in the names of my global aliases. This made it easy to construct a regex as a filter for my globalias function:

globalias code
1
2
3
4
5
6
7
8
9
10
11
12
13
globalias() {
   if [[ $LBUFFER =~ ' [A-Z0-9]+$' ]]; then
     zle _expand_alias
     zle expand-word
   fi
   zle self-insert
}

zle -N globalias

bindkey " " globalias
bindkey "^ " magic-space           # control-space to bypass completion
bindkey -M isearch " " magic-space # normal space during searches

If you’d like to try it out you can just add the above code to your zsh config file, or you can download and source oh-my-zsh plugin.

It should be no problem to loosen up or completely remove the filtering regex if expanding only all-caps aliases isn’t to your liking.

Update: I added zle expand-word to the globalias function. I have one or two global aliases that end in a file glob. This makes them immediately appear expanded.

Comments