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?

2 Answers 2

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.

1
  • 6
    It is sufficient to just give the widget name, if it is the same as the function name: zle -N name.
    – Adaephon
    Commented Jun 15, 2016 at 23:43
1

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'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .