add the functions needed for some keybindings
[zsh.git] / .zsh / functions / zbell
1 #!/usr/bin/env zsh
2
3 # This script prints a bell character when a command finishes
4 # if it has been running for longer than $zbell_duration seconds.
5 # If there are programs that you know run long that you don't
6 # want to bell after, then add them to $zbell_ignore.
7 #
8 # This script uses only zsh builtins so its fast, there's no needless
9 # forking, and its only dependency is zsh and its standard modules
10 #
11 # Written by Jean-Philippe Ouellet <jpo@vt.edu>
12 # Made available under the ISC license.
13
14 # only do this if we're in an interactive shell
15 [[ -o interactive ]] || exit
16
17 # get $EPOCHSECONDS. builtins are faster than date(1)
18 zmodload zsh/datetime || exit
19
20 # make sure we can register hooks
21 autoload -Uz add-zsh-hook || exit
22
23 # initialize zbell_duration if not set
24 (( ${+zbell_duration} )) || zbell_duration=15
25
26 # initialize zbell_ignore if not set
27 (( ${+zbell_ignore} )) || zbell_ignore=($EDITOR $PAGER)
28
29 # initialize it because otherwise we compare a date and an empty string
30 # the first time we see the prompt. it's fine to have lastcmd empty on the
31 # initial run because it evaluates to an empty string, and splitting an
32 # empty string just results in an empty array.
33 zbell_timestamp=$EPOCHSECONDS
34
35 # right before we begin to execute something, store the time it started at
36 zbell_begin() {
37 zbell_timestamp=$EPOCHSECONDS
38 zbell_lastcmd=$1
39 }
40
41 # when it finishes, if it's been running longer than $zbell_duration,
42 # and we dont have an ignored command in the line, then print a bell.
43 zbell_end() {
44 ran_long=$(( $EPOCHSECONDS - $zbell_timestamp >= $zbell_duration ))
45
46 has_ignored_cmd=0
47 for cmd in ${(s:;:)zbell_lastcmd//|/;}; do
48 words=(${(z)cmd})
49 util=${words[1]}
50 if (( ${zbell_ignore[(i)$util]} <= ${#zbell_ignore} )); then
51 has_ignored_cmd=1
52 break
53 fi
54 done
55
56 if (( ! $has_ignored_cmd )) && (( ran_long )); then
57 print -n "\a"
58 fi
59 }
60
61 # register the functions as hooks
62 add-zsh-hook preexec zbell_begin
63 add-zsh-hook precmd zbell_end