1#autoload
2
3local expl disp jobs job jids pfx='%' desc how expls sep
4
5if [[ "$1" = -t ]]; then
6  zstyle -T ":completion:${curcontext}:jobs" prefix-needed &&
7      [[ "$PREFIX" != %* && compstate[nmatches] -ne 0 ]] && return 1
8  shift
9fi
10zstyle -t ":completion:${curcontext}:jobs" prefix-hidden && pfx=''
11zstyle -T ":completion:${curcontext}:jobs" verbose       && desc=yes
12
13if [[ "$1" = -r ]]; then
14  jids=( "${(@k)jobstates[(R)running*]}" )
15  shift
16  expls='running job'
17elif [[ "$1" = -s ]]; then
18  jids=( "${(@k)jobstates[(R)suspended*]}" )
19  shift
20  expls='suspended job'
21else
22  [[ "$1" = - ]] && shift
23  jids=( "${(@k)jobtexts}" )
24  expls=job
25fi
26
27if [[ -n "$desc" ]]; then
28  disp=()
29  zstyle -s ":completion:${curcontext}:jobs" list-separator sep || sep=--
30  for job in "$jids[@]"; do
31    [[ -n "$desc" ]] &&
32        disp=( "$disp[@]" "${pfx}${(r:2:: :)job} $sep ${(r:COLUMNS-8:: :)jobtexts[$job]}" )
33  done
34fi
35
36zstyle -s ":completion:${curcontext}:jobs" numbers how
37
38if [[ "$how" = (yes|true|on|1) ]]; then
39  jobs=( "$jids[@]" )
40else
41  local texts i text str tmp num max=0
42
43  # Find shortest unambiguous strings.
44
45  texts=( "$jobtexts[@]" )
46  jobs=()
47  for i in "$jids[@]"; do
48    text="$jobtexts[$i]"
49    str="${text%% *}"
50    if [[ "$text" = *\ * ]]; then
51      text="${text#* }"
52    else
53      text=""
54    fi
55    tmp=( "${(@M)texts:#${str}*}" )
56    num=1
57    while [[ -n "$text" && $#tmp -ge 2 ]]; do
58      str="${str} ${text%% *}"
59      if [[ "$text" = *\ * ]]; then
60        text="${text#* }"
61      else
62        text=""
63      fi
64      tmp=( "${(@M)texts:#${str}*}" )
65      (( num++ ))
66    done
67
68    [[ num -gt max ]] && max="$num"
69
70    jobs=( "$jobs[@]" "$str" )
71  done
72
73  if [[ "$how" = [0-9]## && max -gt how ]]; then
74    jobs=( "$jids[@]" )
75  else
76    [[ -z "$pfx" && -n "$desc" ]] && disp=( "${(@)disp#%}" )
77  fi
78fi
79
80if [[ -n "$desc" ]]; then
81  _wanted jobs expl "$expls" compadd "$@" -ld disp - "%$^jobs[@]"
82else
83  _wanted jobs expl "$expls" compadd "$@" - "%$^jobs[@]"
84fi
85