atevm atevm - 1 month ago 21
Bash Question

zsh bindkey does not work in a function

I wrote a small function for .zshrc to load plugins and set their keybindings

function loadPlugin() {
# Function to load external zsh plugins and set keybindings.
pluginName=$1
pluginPath=$2
if [ -r $pluginPath ];then
source $pluginPath
else
echo "$pluginName plugin can not be found at: $pluginPath"
fi

# set keybindings
shift
shift

while [[ $# > 0 ]]; do
bindkey -M emacs '$1' '$2'
shift
shift
done
}


The loading part works, but it does not set the keybindings:

loadPlugin "History search" \
"$HOME/zsh.d/plugins/zsh-history-substring-search/zsh-history-substring-search.zsh" \
'^p' "history-substring-search-up" \
'^n' "history-substring-search-down"


There is no error output, and if I called the binding commands outside the function after calling it with the same arguments they would work.

bindkey -M emacs '^p' "history-substring-search-up"
bindkey -M emacs '^n' "history-substring-search-down"

Answer

Your single quotes prevent $1 and $2 from being expanded. Use double-quotes instead.

bindkey -M emacs "$1" "$2"