Cloning vim's abbreviation feature

I saw this idea in strcat's config for the first time.

This way you can get a similar featureset as with global aliases, but without its dangers and with additional flexiblity.

The idea is, to enter unique strings that get replaced with something useful as soon as the space-key gets hit:

zsh% ls -l /dev Im<space>
# gets replaced by
zsh% ls -l /dev | more

This is really useful, because you are able to get really long commands by only typing a few characters, plus you may change the inserted command, if needed in the current situation.

To get this feature, add the following code to your .zshrc:

typeset -Ag abbreviations
  "Im"    "| more"
  "Ia"    "| awk"
  "Ig"    "| grep"
  "Ieg"   "| egrep"
  "Iag"   "| agrep"
  "Igr"   "| groff -s -p -t -e -Tlatin1 -mandoc"
  "Ip"    "| $PAGER"
  "Ih"    "| head"
  "Ik"    "| keep"
  "It"    "| tail"
  "Is"    "| sort"
  "Iv"    "| ${VISUAL:-${EDITOR}}"
  "Iw"    "| wc"
  "Ix"    "| xargs"

magic-abbrev-expand() {
    local MATCH
    zle self-insert

no-magic-abbrev-expand() {
  LBUFFER+=' '

zle -N magic-abbrev-expand
zle -N no-magic-abbrev-expand
bindkey " " magic-abbrev-expand
bindkey "^x " no-magic-abbrev-expand
bindkey -M isearch " " self-insert

This also adds the possibility to _not_ replace abbreviations by hitting CTRL-x<SPACE>. That way, you may enter 'Iag' without replacing it by 'agrep' if you need to.

But this could also be accomplished using ^V<space> [i.e. "quoted-insert"], without adding the "no-magic-abbrev-expand" stuff, could it not? – At least it works for me, but I have re-bound ^V to "vi-quoted-insert". /zrajm

When I rebind space in this manner ^R/^S (incremental search backwards/forwards) is interrupted if I press space. Is there another, better, way of rebinding it so that I won't exit the incremental search, yet work at the ordinary prompt? /zrajm 9 october 2008

  • Yes, you can do "bindkey -M isearch ' ' self-insert" and it should work as normal — Mikachu 2011/04/22 13:15

Of course, this idea is not limited to expanding pipelines. You could, for example, add a replacement for 'emacs' that expands to 'emacs -nw'.

Note, that you need to set the extendedglob option before calling these lines. If don't do this already, this is the needed line:

setopt extendedglob
examples/zleiab.txt · Last modified: 2015/12/08 07:45 by spamkiller