summary refs log tree commit diff
path: root/Functions/Calendar/calendar
blob: 08903d04cf23d4de09ebebd81f541aa6dbf4746c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
emulate -L zsh
setopt extendedglob

local line restline REPLY REPLY2 userange pruned nobackup datefmt
local calendar donefile sched newfile warnstr mywarnstr newdate
integer time start stop today ndays y m d next=-1 shown done nodone
integer verbose warntime mywarntime t tcalc tsched i rstat remaining
integer showcount icount repeating repeattime resched showall
local -a calendar_entries calendar_addlines
local -a times calopts showprog lockfiles match mbegin mend

zmodload -i zsh/datetime || return 1
zmodload -i zsh/zutil || return 1

autoload -U calendar_{add,read,scandate,show,lockfiles}

# Read the calendar file from the calendar-file style
zstyle -s ':datetime:calendar:' calendar-file calendar || calendar=~/calendar
newfile=$calendar.new.$HOST.$$
zstyle -s ':datetime:calendar:' done-file donefile || donefile="$calendar.done"
# Read the programme to show the message from the show-prog style.
zstyle -a ':datetime:calendar:' show-prog showprog ||
  showprog=(calendar_show)
# Amount of time before an event when it should be flagged.
# May be overridden in individual entries
zstyle -s ':datetime:calendar:' warn-time warnstr || warnstr="0:05"
# default to standard ctime date/time format
zstyle -s ':datetime:calendar:' date-format datefmt ||
  datefmt="%a %b %d %H:%M:%S %Z %Y"

if [[ -n $warnstr ]]; then
  if [[ $warnstr = <-> ]]; then
    (( warntime = warnstr ))
  elif ! calendar_scandate -ar $warnstr; then
    print >&2 \
      "warn-time value '$warnstr' not understood; using default 5 minutes"
    warnstr="5 mins"
    (( warntime = 5 * 60 ))
  else
    (( warntime = REPLY ))
  fi
fi

[[ -f $calendar ]] || return 1

# We're not using getopts because we want +... to refer to a
# relative time, not an option, and allow some other additions
# like handling -<->.
integer opti=0
local opt optrest optarg

while [[ ${argv[opti+1]} = -* ]]; do
  (( opti++ ))
  opt=${argv[opti][2]}
  optrest=${argv[opti][3,-1]}
  [[ -z $opt || $opt = - ]] && break
  while [[ -n $opt ]]; do
    case $opt in
      ########################
      # Options with arguments
      ########################
      ([CnS])
      if [[ -n $optrest ]]; then
	optarg=$optrest
	optrest=
      elif (( opti < $# )); then
	optarg=$argv[++opti]
	optrest=
      else
	print -r "$0: option -$opt requires an argument." >&2
	return 1
      fi
      case $opt in
	(C)
	# Pick the calendar file, overriding style and default.
	calendar=$optarg
	;;

	(n)
	# Show this many remaining events regardless of date.
	showcount=$optarg
	if (( showcount <= 0 )); then
	  print -r "$0: option -$opt requires a positive integer." >&2
	  return 1
	fi
	;;

	(S)
	# Explicitly specify a show programme, overriding style and default.
	# Colons in the argument are turned into space.
	showprog=(${(s.:.)optarg})
	;;
      esac
      ;;

      ###########################
      # Options without arguments
      ###########################
      (a)
      # Show all entries
      (( showall = 1 ))
      ;;

      (d)
      # Move out of date items to the done file.
      (( done = 1 ))
      ;;

      (D)
      # Don't use done; needed with sched
      (( nodone = 1 ))
      ;;

      (r)
      # Show all remaining options in the calendar, i.e.
      # respect start time but ignore end time.
      # Any argument is treated as a start time.
      (( remaining = 1 ))
      ;;

      (s)
      # Use the "sched" builtin to scan at the appropriate time.
      sched=sched
      (( done = 1 ))
      ;;

      (v)
      # Verbose
      verbose=1
      ;;

      (<->)
      # Shorthand for -n <->
      showcount=$opt
      ;;

      (*)
      print "$0: unrecognised option: -$opt" >&2
      return 1
      ;;
    esac
    opt=$optrest[1]
    optrest=$optrest[2,-1]
  done
done
calopts=($argv[1,opti])
shift $(( opti ))

# Use of donefile requires explicit or implicit option request, plus
# no explicit -D.  It may already be empty because of the style.
(( done && !nodone )) || donefile=

if (( $# > 1 || ($# == 1 && remaining) )); then
  if [[ $1 = now ]]; then
    start=$EPOCHSECONDS
  elif [[ $1 = <-> ]]; then
    start=$1
  else
    if ! calendar_scandate -a $1; then
      print "$0: failed to parse date/time: $1" >&2
      return 1
    fi
    start=$REPLY
  fi
  shift
else
  # Get the time at which today started.
  y=${(%):-"%D{%Y}"} m=${(%):-"%D{%m}"} d=${(%):-"%D{%d}"}
  strftime -s today -r "%Y/%m/%d" "$y/$m/$d"
  start=$today
fi
# day of week of start time
strftime -s wd "%u" $start

if (( $# && !remaining )); then
  if [[ $1 = +* ]]; then
    if ! calendar_scandate -a -R $start ${1[2,-1]}; then
      print "$0: failed to parse relative time: $1" >&2
      return 1
    fi
    (( stop = REPLY ))
  elif [[ $1 = <-> ]]; then
    stop=$1
  else
    if ! calendar_scandate -a $1; then
      print "$0: failed to parse date/time: $1" >&2
      return 1
    fi
    stop=$REPLY
  fi
  if (( stop < start )); then
    strftime -s REPLY $datefmt $start
    strftime -s REPLY2 $datefmt $stop
    print "$0: requested end time is before start time:
  start: $REPLY
  end: $REPLY2" >&2
    return 1
  fi
  shift
else
  # By default, show 2 days.  If it's Friday (5) show up to end
  # of Monday (4) days; likewise on Saturday show 3 days.
  # If -r, this is calculated but not used.  This is paranoia,
  # to avoid an unusable value of stop; but it shouldn't get used.
  case $wd in
    (5)
    ndays=4
    ;;

    (6)
    ndays=3
    ;;

    (*)
    ndays=2
    ;;
  esac
  stop=$(( start + ndays * 24 * 60 * 60 ))
fi

if (( $# )); then
  print "Usage: $0 [ start-date-time stop-date-time ]" >&2
  return 1
fi

autoload -Uz matchdate

[[ -n $donefile ]] && rm -f $newfile

if (( verbose )); then
  print -n "start: "
  strftime $datefmt $start
  print -n "stop: "
  if (( remaining )); then
    print "none"
  else
    strftime $datefmt $stop
  fi
fi

# start of block for following always to clear up lockfiles.
{
  if [[ -n $donefile ]]; then
    # Attempt to lock both $donefile and $calendar.
    # Don't lock $newfile; we've tried our best to make
    # the name unique.
    calendar_lockfiles $calendar $donefile || return 1
  fi

  calendar_read $calendar
  for line in $calendar_entries; do
    # This call sets REPLY to the date and time in seconds since the epoch,
    # REPLY2 to the line with the date and time removed.
    calendar_scandate -as $line || continue
    (( t = REPLY ))
    restline=$REPLY2

    # Look for specific warn time.
    pruned=${restline#(|*[[:space:],])WARN[[:space:]]}
    (( mywarntime = warntime ))
    mywarnstr=$warnstr
    if [[ $pruned != $restline ]]; then
      if calendar_scandate -asm -R $t $pruned; then
	(( mywarntime = t - REPLY ))
	mywarnstr=${pruned%%"$REPLY2"}
      fi
    fi

    # Look for a repeat time.
    (( repeating = 0 ))
    pruned=${restline#(|*[[:space:],])RPT[[:space:]]}
    if [[ $pruned != $restline ]]; then
      if calendar_scandate -a -R $t $pruned; then
	(( repeattime = REPLY, repeating = 1 ))
      fi
    fi

    if (( verbose )); then
      print "Examining: $line"
      print -n "  Date/time: "
      strftime $datefmt $t
      if [[ -n $sched ]]; then
	print "  Warning $mywarntime seconds ($mywarnstr) before"
      fi
    fi
    (( shown = 0 ))
    if (( showall || (t >= start && (remaining || t <= stop || icount < showcount)) ))
    then
      $showprog $start $stop "$line"
      (( icount++ ))
      # Doesn't count as "shown" unless the event has now passed.
      (( t <= EPOCHSECONDS )) && (( shown = 1 ))
    elif [[ -n $sched ]]; then
      (( tsched = t - mywarntime ))
      if (( tsched >= start && tsched <= stop)); then
	$showprog $start $stop "due in ${mywarnstr}: $line"
      fi
    fi
    if [[ -n $sched ]]; then
      if (( shown && repeating )); then
	# Done and dusted, but a repeated event is due.
	strftime -s newdate $datefmt $repeattime
	calendar_addlines+=("$newdate$restline")

	# We'll add this back in below, but we check in case the
	# repeated event is the next one due.  It's not
	# actually a disaster if there's an error and we fail
	# to add the time.  Always try to reschedule this event.
	(( tcalc = repeattime, resched = 1 ))
      else
	(( tcalc = t ))
      fi

      if (( tcalc - mywarntime > EPOCHSECONDS )); then
	# schedule for a warning
	(( tsched = tcalc - mywarntime, resched = 1 ))
      else
	# schedule for event itself
	(( tsched = tcalc ))
	# but don't schedule unless the event has not yet been shown.
	(( !shown )) && (( resched = 1 ))
      fi
      if (( resched && (next < 0 || tsched < next) )); then
	(( next = tsched ))
      fi
    fi
    if [[ -n $donefile ]]; then
      if (( shown )); then
	# Done and dusted.
	if ! print -r $line >>$donefile; then
	  if (( done != 3 )); then
	    (( done = 3 ))
	    print "Failed to append to $donefile" >&2
	  fi
	elif (( done != 3 )); then
	  (( done = 2 ))
	fi
      else
	# Still not over.
	if ! print -r $line >>$newfile; then
	  if (( done != 3 )); then
	    (( done = 3 ))
	    print "Failed to append to $newfile" >&2
	  fi
	elif (( done != 3 )); then
	  (( done = 2 ))
	fi
      fi
    fi
  done

  if [[ -n $sched ]]; then
    if [[ $next -ge 0 ]]; then
      # Remove any existing calendar scheduling.
      # Luckily sched doesn't delete its schedule in a subshell.
      sched | while read line; do
	if [[ $line = (#b)[[:space:]]#(<->)[[:space:]]##*[[:space:]]'calendar -s'* ]]; then
	  # End of pipeline run in current shell, so delete directly.
	  sched -1 $match[1]
	fi
      done
      $sched $next calendar "${calopts[@]}" $next $next
    else
      $showprog $start $stop \
"No more calendar events: calendar not rescheduled.
Run \"calendar -s\" again if you add to it."
    fi
  fi

  if (( done == 2 )); then
    if ! mv $calendar $calendar.old; then
      print "Couldn't back up $calendar to $calendar.old.
New calendar left in $newfile." >&2
      (( rstat = 1 ))
    elif ! mv $newfile $calendar; then
      print "Failed to rename $newfile to $calendar.
Old calendar left in $calendar.old." >&2
      (( rstat = 1 ))
    fi
    nobackup=-B
  elif [[ -n $donefile ]]; then
    rm -f $newfile
  fi

  # Reschedule repeating events.
  for line in $calendar_addlines; do
    calendar_add -L $nobackup $line
  done
} always {
  (( ${#lockfiles} )) && rm -f $lockfiles
}

return $rstat