Create function for readline command
The problem
Clearing the screen on the terminal is quite finicky. The behaviour on some emulators (Ghostty, Kitty & co.) is massively different than say on iTerm2 or the macOS built-in Terminal.app.
You see, I tend to use the command clear
, which is aliased to c
in my case. Now, I like to keep the scrollback buffer
intact.
Using clear
, the scrollback is only preserved so far by iTerm2 and the Terminal.app. In all the other emulators that I’ve tried so far, the scrollback gets cut off – from the bottom ¯\_(ツ)_/¯.
But listen… when I use Ctrl+l
(clear-screen
), I do not get the issue. But I want to keep using c+return
because I am used to it. Stubbornness, I guess. I want what I want.
So how do I essentially bind c+return
to clear-screen
at the prompt?
The solution
Turns out that one can create a function to call a readline command, and doing so circumvents a keybinding like Ctrl+l
.
Function:
c_clear_screen() {
if [[ $BUFFER == "c" ]]; then
zle clear-screen # Perform the clear-screen action
BUFFER="" # Clear the input buffer (remove "c")
else
zle accept-line # Execute the default "Return" behavior
fi
}
# Register the widget
zle -N c_clear_screen
# Bind "Return" to the custom function
bindkey '^M' c_clear_screen
The function is conditional since I don’t want to trap return
for all other commands.
Extra mile:
alias c='true'
Since c
is not recognised as a command, now plugins like zsh-syntax-highlighting
get confused. The last little snippet in the .zshrc
remediates this.
The conclusion
There are a bunch of readline commands. And for whatever reason – if you want to create a function, you can do this. Ain’t that fantastic!?