puntos/.config/zsh/bg_notify.zsh

45 lines
1.4 KiB
Bash

#!/usr/bin/env zsh
# Based on https://github.com/t413/zsh-background-notify/blob/master/bgnotify.plugin.zsh
[[ -o interactive ]] || return
zmodload zsh/datetime || { print "can't load zsh/datetime"; return } # faster than date()
autoload -Uz add-zsh-hook || { print "can't add zsh hook!"; return }
(( ${+bgnotify_threshold} )) || bgnotify_threshold=5 # default 5 seconds
if ! (type bgnotify_formatted | grep -q 'function'); then ## allow custom function override
function bgnotify_formatted { ## args: (exit_status, command, elapsed_seconds)
elapsed="$(( $3 % 60 ))s"
(( $3 >= 60 )) && elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
(( $3 >= 3600 )) && elapsed="$(( $3 / 3600 ))h $elapsed"
[ $1 -eq 0 ] && bgnotify "success (took $elapsed)" "$2" || bgnotify "fail (took $elapsed)" "$2"
}
fi
bgnotify () { ## args: (title, subtitle)
title="$1"
"$REMOTE" && title="[$(hostname)] $title"
echo -e "\033]777;notify;$title;$2\a"
}
## ZSH hooks ##
bgnotify_begin() {
bgnotify_timestamp=$EPOCHSECONDS
bgnotify_lastcmd="$1"
}
bgnotify_end() {
didexit=$?
elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
past_threshold=$(( elapsed >= bgnotify_threshold ))
if (( bgnotify_timestamp > 0 )) && (( past_threshold )); then
print -n "\a"
bgnotify_formatted "$didexit" "$bgnotify_lastcmd" "$elapsed"
fi
bgnotify_timestamp=0
}
add-zsh-hook preexec bgnotify_begin
add-zsh-hook precmd bgnotify_end