A ZLE widget for calculator
Vincent Bernat <[email protected]> Tue, 3 Feb 2026 08:16:44 +0100
| Newsgroups | gmane.comp.shells.zsh.user |
|---|---|
| Message-ID | <[email protected]> |
Hey!
I currently have this code in my zshrc:
# Simple calculator
_vbe_calc_accept_line() {
local expr
case $BUFFER in
"= "*) expr=${BUFFER#= } ;;
esac
case $expr in
"") ;;
\'*) BUFFER="= ${(q-)${(Q)expr}}" ;;
*) BUFFER="= ${(q-)expr}"
esac
zle .accept-line
}
zle -N accept-line _vbe_calc_accept_line
aliases[=]='numbat -e'
When I use the "=" alias, it will automatically quote what's after. This
is better than noglob.
08:12 ❱ = 1
1
08:12 ❱ = 1+2
3
08:12 ❱ = 'today() + 3 days'
2026-02-06 00:00:00 CET (UTC +01), Europe/Paris
08:12 ❱ = '47 km/h to miles/h'
29.2044 mi/h
This seems a bit clunky to detect when something was quoted and undo it.
Ideally, I would like to have the quoted alias executed, but for history
and display purpose keep the buffer unchanged.
# Simple calculator
_vbe_calc_accept_line() {
if [[ $BUFFER =~ "= *" ]]; then
local expr=${BUFFER#= }
zle -I
command numbat -e "$expr"
print
print -s $BUFFER
BUFFER=""
else
zle .accept-line
fi
}
zle -N accept-line _vbe_calc_accept_line
It almost work, but the buffer is not available in the immediate history
(because no accept-line was called). If I press the up arrow, I get the
previous one instead.
Any idea?
Thanks!