* lisp/emacs-lisp/timer.el (timer-event-handler): Don't retrigger a canceled
[bpt/emacs.git] / lisp / emacs-lisp / timer.el
1 ;;; timer.el --- run a function with args at some time in future
2
3 ;; Copyright (C) 1996, 2001-2013 Free Software Foundation, Inc.
4
5 ;; Maintainer: FSF
6 ;; Package: emacs
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This package gives you the capability to run Emacs Lisp commands at
26 ;; specified times in the future, either as one-shots or periodically.
27
28 ;;; Code:
29
30 ;; Layout of a timer vector:
31 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
32 ;; function args idle-delay psecs]
33 ;; triggered-p is nil if the timer is active (waiting to be triggered),
34 ;; t if it is inactive ("already triggered", in theory)
35
36 (eval-when-compile (require 'cl-lib))
37
38 (cl-defstruct (timer
39 (:constructor nil)
40 (:copier nil)
41 (:constructor timer-create ())
42 (:type vector)
43 (:conc-name timer--))
44 (triggered t)
45 high-seconds low-seconds usecs repeat-delay function args idle-delay psecs)
46
47 (defun timerp (object)
48 "Return t if OBJECT is a timer."
49 (and (vectorp object) (= (length object) 9)))
50
51 ;; Pseudo field `time'.
52 (defun timer--time (timer)
53 (list (timer--high-seconds timer)
54 (timer--low-seconds timer)
55 (timer--usecs timer)
56 (timer--psecs timer)))
57
58 (gv-define-simple-setter timer--time
59 (lambda (timer time)
60 (or (timerp timer) (error "Invalid timer"))
61 (setf (timer--high-seconds timer) (pop time))
62 (let ((low time) (usecs 0) (psecs 0))
63 (if (consp time)
64 (progn
65 (setq low (pop time))
66 (if time
67 (progn
68 (setq usecs (pop time))
69 (if time
70 (setq psecs (car time)))))))
71 (setf (timer--low-seconds timer) low)
72 (setf (timer--usecs timer) usecs)
73 (setf (timer--psecs timer) psecs))))
74
75
76 (defun timer-set-time (timer time &optional delta)
77 "Set the trigger time of TIMER to TIME.
78 TIME must be in the internal format returned by, e.g., `current-time'.
79 If optional third argument DELTA is a positive number, make the timer
80 fire repeatedly that many seconds apart."
81 (setf (timer--time timer) time)
82 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
83 timer)
84
85 (defun timer-set-idle-time (timer secs &optional repeat)
86 "Set the trigger idle time of TIMER to SECS.
87 SECS may be an integer, floating point number, or the internal
88 time format returned by, e.g., `current-idle-time'.
89 If optional third argument REPEAT is non-nil, make the timer
90 fire each time Emacs is idle for that many seconds."
91 (if (consp secs)
92 (setf (timer--time timer) secs)
93 (setf (timer--time timer) '(0 0 0))
94 (timer-inc-time timer secs))
95 (setf (timer--repeat-delay timer) repeat)
96 timer)
97
98 (defun timer-next-integral-multiple-of-time (time secs)
99 "Yield the next value after TIME that is an integral multiple of SECS.
100 More precisely, the next value, after TIME, that is an integral multiple
101 of SECS seconds since the epoch. SECS may be a fraction."
102 (let* ((trillion 1e12)
103 (time-sec (+ (nth 1 time)
104 (* 65536.0 (nth 0 time))))
105 (delta-sec (mod (- time-sec) secs))
106 (next-sec (+ time-sec (ffloor delta-sec)))
107 (next-sec-psec (ffloor (* trillion (mod delta-sec 1))))
108 (sub-time-psec (+ (or (nth 3 time) 0)
109 (* 1e6 (nth 2 time))))
110 (psec-diff (- sub-time-psec next-sec-psec)))
111 (if (and (<= next-sec time-sec) (< 0 psec-diff))
112 (setq next-sec-psec (+ sub-time-psec
113 (mod (- psec-diff) (* trillion secs)))))
114 (setq next-sec (+ next-sec (floor next-sec-psec trillion)))
115 (setq next-sec-psec (mod next-sec-psec trillion))
116 (list (floor next-sec 65536)
117 (floor (mod next-sec 65536))
118 (floor next-sec-psec 1000000)
119 (floor (mod next-sec-psec 1000000)))))
120
121 (defun timer-relative-time (time secs &optional usecs psecs)
122 "Advance TIME by SECS seconds and optionally USECS nanoseconds
123 and PSECS picoseconds. SECS may be either an integer or a
124 floating point number."
125 (let ((delta (if (floatp secs)
126 (seconds-to-time secs)
127 (list (floor secs 65536) (mod secs 65536)))))
128 (if (or usecs psecs)
129 (setq delta (time-add delta (list 0 0 (or usecs 0) (or psecs 0)))))
130 (time-add time delta)))
131
132 (defun timer--time-less-p (t1 t2)
133 "Say whether time value T1 is less than time value T2."
134 (time-less-p (timer--time t1) (timer--time t2)))
135
136 (defun timer-inc-time (timer secs &optional usecs psecs)
137 "Increment the time set in TIMER by SECS seconds, USECS nanoseconds,
138 and PSECS picoseconds. SECS may be a fraction. If USECS or PSECS are
139 omitted, they are treated as zero."
140 (setf (timer--time timer)
141 (timer-relative-time (timer--time timer) secs usecs psecs)))
142
143 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
144 "Set the trigger time of TIMER to TIME plus USECS.
145 TIME must be in the internal format returned by, e.g., `current-time'.
146 The microsecond count from TIME is ignored, and USECS is used instead.
147 If optional fourth argument DELTA is a positive number, make the timer
148 fire repeatedly that many seconds apart."
149 (declare (obsolete "use `timer-set-time' and `timer-inc-time' instead."
150 "22.1"))
151 (setf (timer--time timer) time)
152 (setf (timer--usecs timer) usecs)
153 (setf (timer--psecs timer) 0)
154 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
155 timer)
156
157 (defun timer-set-function (timer function &optional args)
158 "Make TIMER call FUNCTION with optional ARGS when triggering."
159 (or (timerp timer)
160 (error "Invalid timer"))
161 (setf (timer--function timer) function)
162 (setf (timer--args timer) args)
163 timer)
164 \f
165 (defun timer--activate (timer &optional triggered-p reuse-cell idle)
166 (if (and (timerp timer)
167 (integerp (timer--high-seconds timer))
168 (integerp (timer--low-seconds timer))
169 (integerp (timer--usecs timer))
170 (integerp (timer--psecs timer))
171 (timer--function timer))
172 (let ((timers (if idle timer-idle-list timer-list))
173 last)
174 ;; Skip all timers to trigger before the new one.
175 (while (and timers (timer--time-less-p (car timers) timer))
176 (setq last timers
177 timers (cdr timers)))
178 (if reuse-cell
179 (progn
180 (setcar reuse-cell timer)
181 (setcdr reuse-cell timers))
182 (setq reuse-cell (cons timer timers)))
183 ;; Insert new timer after last which possibly means in front of queue.
184 (cond (last (setcdr last reuse-cell))
185 (idle (setq timer-idle-list reuse-cell))
186 (t (setq timer-list reuse-cell)))
187 (setf (timer--triggered timer) triggered-p)
188 (setf (timer--idle-delay timer) idle)
189 nil)
190 (error "Invalid or uninitialized timer")))
191
192 (defun timer-activate (timer &optional triggered-p reuse-cell)
193 "Insert TIMER into `timer-list'.
194 If TRIGGERED-P is t, make TIMER inactive (put it on the list, but
195 mark it as already triggered). To remove it, use `cancel-timer'.
196
197 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
198 TIMER into `timer-list' (usually a cell removed from that list by
199 `cancel-timer-internal'; using this reduces consing for repeat
200 timers). If nil, allocate a new cell."
201 (timer--activate timer triggered-p reuse-cell nil))
202
203 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
204 "Insert TIMER into `timer-idle-list'.
205 This arranges to activate TIMER whenever Emacs is next idle.
206 If optional argument DONT-WAIT is non-nil, set TIMER to activate
207 immediately \(see below\), or at the right time, if Emacs is
208 already idle.
209
210 REUSE-CELL, if non-nil, is a cons cell to reuse when inserting
211 TIMER into `timer-idle-list' (usually a cell removed from that
212 list by `cancel-timer-internal'; using this reduces consing for
213 repeat timers). If nil, allocate a new cell.
214
215 Using non-nil DONT-WAIT is not recommended when activating an
216 idle timer from an idle timer handler, if the timer being
217 activated has an idleness time that is smaller or equal to
218 the time of the current timer. That's because the activated
219 timer will fire right away."
220 (timer--activate timer (not dont-wait) reuse-cell 'idle))
221
222 (defalias 'disable-timeout 'cancel-timer)
223
224 (defun cancel-timer (timer)
225 "Remove TIMER from the list of active timers."
226 (or (timerp timer)
227 (error "Invalid timer"))
228 (setq timer-list (delq timer timer-list))
229 (setq timer-idle-list (delq timer timer-idle-list))
230 nil)
231
232 (defun cancel-timer-internal (timer)
233 "Remove TIMER from the list of active timers or idle timers.
234 Only to be used in this file. It returns the cons cell
235 that was removed from the timer list."
236 (let ((cell1 (memq timer timer-list))
237 (cell2 (memq timer timer-idle-list)))
238 (if cell1
239 (setq timer-list (delq timer timer-list)))
240 (if cell2
241 (setq timer-idle-list (delq timer timer-idle-list)))
242 (or cell1 cell2)))
243
244 (defun cancel-function-timers (function)
245 "Cancel all timers which would run FUNCTION.
246 This affects ordinary timers such as are scheduled by `run-at-time',
247 and idle timers such as are scheduled by `run-with-idle-timer'."
248 (interactive "aCancel timers of function: ")
249 (dolist (timer timer-list)
250 (if (eq (timer--function timer) function)
251 (setq timer-list (delq timer timer-list))))
252 (dolist (timer timer-idle-list)
253 (if (eq (timer--function timer) function)
254 (setq timer-idle-list (delq timer timer-idle-list)))))
255 \f
256 ;; Record the last few events, for debugging.
257 (defvar timer-event-last nil
258 "Last timer that was run.")
259 (defvar timer-event-last-1 nil
260 "Next-to-last timer that was run.")
261 (defvar timer-event-last-2 nil
262 "Third-to-last timer that was run.")
263
264 (defcustom timer-max-repeats 10
265 "Maximum number of times to repeat a timer, if many repeats are delayed.
266 Timer invocations can be delayed because Emacs is suspended or busy,
267 or because the system's time changes. If such an occurrence makes it
268 appear that many invocations are overdue, this variable controls
269 how many will really happen."
270 :type 'integer
271 :group 'internal)
272
273 (defun timer-until (timer time)
274 "Calculate number of seconds from when TIMER will run, until TIME.
275 TIMER is a timer, and stands for the time when its next repeat is scheduled.
276 TIME is a time-list."
277 (- (float-time time) (float-time (timer--time timer))))
278
279 (defun timer-event-handler (timer)
280 "Call the handler for the timer TIMER.
281 This function is called, by name, directly by the C code."
282 (setq timer-event-last-2 timer-event-last-1)
283 (setq timer-event-last-1 timer-event-last)
284 (setq timer-event-last timer)
285 (let ((inhibit-quit t))
286 (if (timerp timer)
287 (let (retrigger cell)
288 ;; Delete from queue. Record the cons cell that was used.
289 (setq cell (cancel-timer-internal timer))
290 ;; Re-schedule if requested.
291 (if (timer--repeat-delay timer)
292 (if (timer--idle-delay timer)
293 (timer-activate-when-idle timer nil cell)
294 (timer-inc-time timer (timer--repeat-delay timer) 0)
295 ;; If real time has jumped forward,
296 ;; perhaps because Emacs was suspended for a long time,
297 ;; limit how many times things get repeated.
298 (if (and (numberp timer-max-repeats)
299 (< 0 (timer-until timer (current-time))))
300 (let ((repeats (/ (timer-until timer (current-time))
301 (timer--repeat-delay timer))))
302 (if (> repeats timer-max-repeats)
303 (timer-inc-time timer (* (timer--repeat-delay timer)
304 repeats)))))
305 (timer-activate timer t cell)
306 (setq retrigger t)))
307 ;; Run handler.
308 ;; We do this after rescheduling so that the handler function
309 ;; can cancel its own timer successfully with cancel-timer.
310 (condition-case-unless-debug err
311 ;; Timer functions should not change the current buffer.
312 ;; If they do, all kinds of nasty surprises can happen,
313 ;; and it can be hellish to track down their source.
314 (save-current-buffer
315 (apply (timer--function timer) (timer--args timer)))
316 (error (message "Error in timer: %S" err)))
317 (when (and retrigger
318 ;; If the timer's been canceled, don't "retrigger" it
319 ;; since it might still be in the copy of timer-list kept
320 ;; by keyboard.c:timer_check (bug#14156).
321 (memq timer timer-list))
322 (setf (timer--triggered timer) nil)))
323 (error "Bogus timer event"))))
324
325 ;; This function is incompatible with the one in levents.el.
326 (defun timeout-event-p (event)
327 "Non-nil if EVENT is a timeout event."
328 (and (listp event) (eq (car event) 'timer-event)))
329 \f
330
331 (declare-function diary-entry-time "diary-lib" (s))
332
333 (defun run-at-time (time repeat function &rest args)
334 "Perform an action at time TIME.
335 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
336 TIME should be one of: a string giving an absolute time like
337 \"11:23pm\" (the acceptable formats are those recognized by
338 `diary-entry-time'; note that such times are interpreted as times
339 today, even if in the past); a string giving a relative time like
340 \"2 hours 35 minutes\" (the acceptable formats are those
341 recognized by `timer-duration'); nil meaning now; a number of
342 seconds from now; a value from `encode-time'; or t (with non-nil
343 REPEAT) meaning the next integral multiple of REPEAT. REPEAT may
344 be an integer or floating point number. The action is to call
345 FUNCTION with arguments ARGS.
346
347 This function returns a timer object which you can use in `cancel-timer'."
348 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
349
350 (or (null repeat)
351 (and (numberp repeat) (< 0 repeat))
352 (error "Invalid repetition interval"))
353
354 ;; Special case: nil means "now" and is useful when repeating.
355 (if (null time)
356 (setq time (current-time)))
357
358 ;; Special case: t means the next integral multiple of REPEAT.
359 (if (and (eq time t) repeat)
360 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
361
362 ;; Handle numbers as relative times in seconds.
363 (if (numberp time)
364 (setq time (timer-relative-time (current-time) time)))
365
366 ;; Handle relative times like "2 hours 35 minutes"
367 (if (stringp time)
368 (let ((secs (timer-duration time)))
369 (if secs
370 (setq time (timer-relative-time (current-time) secs)))))
371
372 ;; Handle "11:23pm" and the like. Interpret it as meaning today
373 ;; which admittedly is rather stupid if we have passed that time
374 ;; already. (Though only Emacs hackers hack Emacs at that time.)
375 (if (stringp time)
376 (progn
377 (require 'diary-lib)
378 (let ((hhmm (diary-entry-time time))
379 (now (decode-time)))
380 (if (>= hhmm 0)
381 (setq time
382 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
383 (nth 4 now) (nth 5 now) (nth 8 now)))))))
384
385 (or (consp time)
386 (error "Invalid time format"))
387
388 (let ((timer (timer-create)))
389 (timer-set-time timer time repeat)
390 (timer-set-function timer function args)
391 (timer-activate timer)
392 timer))
393
394 (defun run-with-timer (secs repeat function &rest args)
395 "Perform an action after a delay of SECS seconds.
396 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
397 SECS and REPEAT may be integers or floating point numbers.
398 The action is to call FUNCTION with arguments ARGS.
399
400 This function returns a timer object which you can use in `cancel-timer'."
401 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
402 (apply 'run-at-time secs repeat function args))
403
404 (defun add-timeout (secs function object &optional repeat)
405 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
406 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
407 This function is for compatibility; see also `run-with-timer'."
408 (run-with-timer secs repeat function object))
409
410 (defun run-with-idle-timer (secs repeat function &rest args)
411 "Perform an action the next time Emacs is idle for SECS seconds.
412 The action is to call FUNCTION with arguments ARGS.
413 SECS may be an integer, a floating point number, or the internal
414 time format returned by, e.g., `current-idle-time'.
415 If Emacs is currently idle, and has been idle for N seconds (N < SECS),
416 then it will call FUNCTION in SECS - N seconds from now. Using
417 SECS <= N is not recommended if this function is invoked from an idle
418 timer, because FUNCTION will then be called immediately.
419
420 If REPEAT is non-nil, do the action each time Emacs has been idle for
421 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
422
423 This function returns a timer object which you can use in `cancel-timer'."
424 (interactive
425 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
426 (y-or-n-p "Repeat each time Emacs is idle? ")
427 (intern (completing-read "Function: " obarray 'fboundp t))))
428 (let ((timer (timer-create)))
429 (timer-set-function timer function args)
430 (timer-set-idle-time timer secs repeat)
431 (timer-activate-when-idle timer t)
432 timer))
433 \f
434 (defvar with-timeout-timers nil
435 "List of all timers used by currently pending `with-timeout' calls.")
436
437 (defmacro with-timeout (list &rest body)
438 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
439 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
440 The timeout is checked whenever Emacs waits for some kind of external
441 event (such as keyboard input, input from subprocesses, or a certain time);
442 if the program loops without waiting in any way, the timeout will not
443 be detected.
444 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
445 (declare (indent 1) (debug ((form body) body)))
446 (let ((seconds (car list))
447 (timeout-forms (cdr list))
448 (timeout (make-symbol "timeout")))
449 `(let ((-with-timeout-value-
450 (catch ',timeout
451 (let* ((-with-timeout-timer-
452 (run-with-timer ,seconds nil
453 (lambda () (throw ',timeout ',timeout))))
454 (with-timeout-timers
455 (cons -with-timeout-timer- with-timeout-timers)))
456 (unwind-protect
457 (progn ,@body)
458 (cancel-timer -with-timeout-timer-))))))
459 ;; It is tempting to avoid the `if' altogether and instead run
460 ;; timeout-forms in the timer, just before throwing `timeout'.
461 ;; But that would mean that timeout-forms are run in the deeper
462 ;; dynamic context of the timer, with inhibit-quit set etc...
463 (if (eq -with-timeout-value- ',timeout)
464 (progn ,@timeout-forms)
465 -with-timeout-value-))))
466
467 (defun with-timeout-suspend ()
468 "Stop the clock for `with-timeout'. Used by debuggers.
469 The idea is that the time you spend in the debugger should not
470 count against these timeouts.
471
472 The value is a list that the debugger can pass to `with-timeout-unsuspend'
473 when it exits, to make these timers start counting again."
474 (mapcar (lambda (timer)
475 (cancel-timer timer)
476 (list timer (time-subtract (timer--time timer) (current-time))))
477 with-timeout-timers))
478
479 (defun with-timeout-unsuspend (timer-spec-list)
480 "Restart the clock for `with-timeout'.
481 The argument should be a value previously returned by `with-timeout-suspend'."
482 (dolist (elt timer-spec-list)
483 (let ((timer (car elt))
484 (delay (cadr elt)))
485 (timer-set-time timer (time-add (current-time) delay))
486 (timer-activate timer))))
487
488 (defun y-or-n-p-with-timeout (prompt seconds default-value)
489 "Like (y-or-n-p PROMPT), with a timeout.
490 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
491 (with-timeout (seconds default-value)
492 (y-or-n-p prompt)))
493 \f
494 (defconst timer-duration-words
495 (list (cons "microsec" 0.000001)
496 (cons "microsecond" 0.000001)
497 (cons "millisec" 0.001)
498 (cons "millisecond" 0.001)
499 (cons "sec" 1)
500 (cons "second" 1)
501 (cons "min" 60)
502 (cons "minute" 60)
503 (cons "hour" (* 60 60))
504 (cons "day" (* 24 60 60))
505 (cons "week" (* 7 24 60 60))
506 (cons "fortnight" (* 14 24 60 60))
507 (cons "month" (* 30 24 60 60)) ; Approximation
508 (cons "year" (* 365.25 24 60 60)) ; Approximation
509 )
510 "Alist mapping temporal words to durations in seconds.")
511
512 (defun timer-duration (string)
513 "Return number of seconds specified by STRING, or nil if parsing fails."
514 (let ((secs 0)
515 (start 0)
516 (case-fold-search t))
517 (while (string-match
518 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
519 string start)
520 (let ((count (if (match-beginning 1)
521 (string-to-number (match-string 1 string))
522 1))
523 (itemsize (cdr (assoc (match-string 2 string)
524 timer-duration-words))))
525 (if itemsize
526 (setq start (match-end 0)
527 secs (+ secs (* count itemsize)))
528 (setq secs nil
529 start (length string)))))
530 (if (= start (length string))
531 secs
532 (if (string-match-p "\\`[0-9.]+\\'" string)
533 (string-to-number string)))))
534 \f
535 (provide 'timer)
536
537 ;;; timer.el ends here