Intro
This post follows up on my previous post Using keyboard-shortcuts with zsh. As promised I will show how we can pass an argument / string to a zsh keyboard-shortcut.
We could for example use this option to create git feature branches by doing:
[typing the name of the branch] --> [keyboard-shortcut] --> [done]
Show me the code!
# create a feature branch with <name> and then ctrl-g+f
function featbranch() {
branch_name=$BUFFER
zle backward-kill-line
echo "git checkout -b feat/$branch_name"
git checkout -b "feat/${branch_name}"
zle reset-prompt
zle redisplay
}
zle -N featbranch
bindkey '^gf' featbranch
A bit longer than our previous widget. Let's break it down line by line:
- Another awesome comment
- The function which will be executed by our keystroke:
- Save the current terminal-line into a variable
- Clear the current line
- Display the full command we like to execute
- Execute the command
- Reset the prompt. (Useful if we display branch-information in our promt)
- Redisplay our prompt.
- Again we define a widget that points to the function
- And bind our key-combination to the widget
So there we have it. Let me know if it works for you!
❤️ Let's connect!
I would love to grow my network with other tech enthusiasts. Let's connect here or over on twitter! 👋 @langhard
Top comments (5)
Nice! I've been using and loving simple
bindkey
for a few shortcuts in my zsh/tmux/vim setup.I didn't know about the
$BUFFER
variable! It will come in handy for a problem i didn't know how to solve: Often times halfway through typing a command I think "this would be better ran in its own tmux pane", but then I would have to go to the beginning of the command and add thetmux split-window
etc. Too much to bother. Having a shortcut I can press after finishing typing the command is much more ergonomic. Thanks for sharing!Thats a really nice usecase! Thank you too for sharing it.
btw, the code in your example doesn't display any output for me. The branch gets created but I can't see the output from
echo
orgit checkout
. After some googling I suspect it might have to do with using a multiline prompt.for some reason that I don't fully understand, adding a newline after
git checkout
makes it display for me:Thanks for the follow up!
🤷♂️😂
You may need override KEYTIMEOUT to 20 or large number to use the multi-key keybinding. The default is 1.