14

In zsh, how do I bind a keyboard shortcut to a function?

In other words, how do I translate:

bash:

hw(){ echo "hello world"; }
bind -x '"\C-h": hw;'

to zsh?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Petr Skocik
  • 28,176
  • 14
  • 81
  • 141

2 Answers2

16

It won't take the functions raw. They need to be wrapped in a "widget" by doing

zle -N widgetname funcname

The two can have the same name:

 zle -N hw{,}

Then it's possible to do:

bindkey ^h hw

, causing Ctrl+h to run the hw widget which runs the hw function.

Petr Skocik
  • 28,176
  • 14
  • 81
  • 141
  • 6
    It is sufficient to just give the widget name, if it is the same as the function name: `zle -N name`. – Adaephon Jun 15 '16 at 23:43
0

This is working for me on zsh 5.8.1 on xterm terminal. I have the following defined inside my zshrc to quickly create templates for scripting languages/tests. For instance, a template (of a template) for a shell script:

# Function and keybind defined in .zshrc:
create-template (){
cat << EOF > template.sh
#!/usr/bin/bash
# Your template goes here ...
EOF
echo "template.sh created"
}

bindkey -s "^E" 'create-template^M'