]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - zsh/functions/compatibility/add-zsh-hook
Simulate hooks using _functions arrays for older versions.
[config/dotfiles.git] / zsh / functions / compatibility / add-zsh-hook
1 # Add to HOOK the given FUNCTION.
2 # HOOK is one of chpwd, precmd, preexec, periodic, zshaddhistory,
3 # zshexit (the _functions subscript is not required).
4 #
5 # With -d, remove the function from the hook instead; delete the hook
6 # variable if it is empty.
7 #
8 # -D behaves like -d, but pattern characters are active in the
9 # function name, so any matching function will be deleted from the hook.
10 #
11 # Without -d, the FUNCTION is marked for autoload; -U is passed down to
12 # autoload if that is given, as are -z and -k.  (This is harmless if the
13 # function is actually defined inline.)
14
15 emulate -L zsh
16
17 local -a hooktypes
18 hooktypes=(chpwd precmd preexec periodic zshaddhistory zshexit)
19
20 local opt
21 local -a autoopts
22 integer del
23
24 while getopts "dDUzk" opt; do
25   case $opt in
26     (d)
27     del=1
28     ;;
29
30     (D)
31     del=2
32     ;;
33
34     ([Uzk])
35     autoopts+=(-$opt)
36     ;;
37
38     (*)
39     return 1
40     ;;
41   esac
42 done
43 shift $(( OPTIND - 1 ))
44
45 if (( $# != 2 || ${hooktypes[(I)$1]} == 0 )); then
46   print "Usage: $0 hook function\nValid hooks are:\n  $hooktypes"
47   return 1
48 fi
49
50 local hook="${1}_functions"
51 local fn="$2"
52
53 if (( del )); then
54   # delete, if hook is set
55   if (( ${(P)+hook} )); then
56     if (( del == 2 )); then
57       set -A $hook ${(P)hook:#${~fn}}
58     else
59       set -A $hook ${(P)hook:#$fn}
60     fi
61     # unset if no remaining entries --- this can give better
62     # performance in some cases
63     if (( ! ${(P)#hook} )); then
64       unset $hook
65     fi
66   fi
67 else
68   if (( ${(P)+hook} )); then
69     if (( ${${(P)hook}[(I)$fn]} == 0 )); then
70       set -A $hook ${(P)hook} $fn
71     fi
72   else
73     set -A $hook $fn
74   fi
75   autoload $autoopts -- $fn
76 fi