2

I run zsh on my machine. I was wondering if I can do text-replace in shell. For example fn[SPACE/TAB]should be replaced with function. On OSX there is the option of keyboard-shortcuts but they don't run on chrome or shell. Is there a way to tweak the OS so that it interprets fn as function?

It'd be amazing if this could be achieved.

3

zsh provides plenty of rope a portion of which is the _user_expand feature to provide so-called "user expansions" of random inputs to random outputs. For example.

# turn on completion system
autoload -U compinit
compinit
# how to mangle inputs; this is a hash or "associative array" of terms
declare -A manglements
manglements=( fn function )
# register mangler and enable _user_expand
zstyle ':completion:*:user-expand:*' user-expand '$manglements'
zstyle ':completion:*' completer _user_expand _complete _ignored

With this set in .zshrc or the like, typing fntabspace should replace that text with function (or at least it does for me inputting the above lines into zsh 5.3.1 run as zsh -f to avoid conflicting with any extant configuration). To reduce the input to just fntab set the add-space setting

zstyle ':completion:*:user-expand:*' add-space 1

though if you really want a magical space instead of tab completion, this requires that the space bar have a widget bound to it, which is a slightly more significant (and dangerous) change.

declare -A manglements
manglements=( fn function )

function magic-space-bar {
   local -a le_vlapoi

   # split on words, see zshexpn(1)
   le_vlapoi=(${(z)BUFFER})

   # only mangle the first word, not surprisingly in middle of some
   # "echo blah fn ..." sequence (this is the same as the `alias -g`
   # rake problem waiting to whap you in the face)
   if [[ $#le_vlapoi -eq 1 ]]; then
      local romoi
      romoi=$manglements[$le_vlapoi[-1]]
      if [[ -n $romoi ]]; then
         le_vlapoi[-1]=$romoi
         BUFFER="$le_vlapoi"
      fi
   fi

   # ensure the typed space happens regardless
   BUFFER="$BUFFER ";
   CURSOR=$#BUFFER
}

zle -N magic-space-bar
autoload -U compinit
compinit
bindkey ' ' magic-space-bar
bindkey -M isearch ' ' self-insert
  • fn TAB gives two options to choose from namely fn and function. Although it aproximately solves the problem, not completely. I've to TAB through the selection different from just typing fn and then proceeding to type and on next char to have already replaced it with function. This additionally wouldn't work say if you run ocaml interpreter. I was thinking of a way to trick the OS into thinking that when fn is inserted that function instead was inserted. Ideally one would have text-replace as one types in all programs. – CupOfCoffee Aug 8 '17 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.