Don't use png_jmpbuf, it doesn't work with dynamic loading.
[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, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
4 ;; 2009, 2010, 2011 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
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]
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))
37
38 (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)
46
47 (defun timerp (object)
48 "Return t if OBJECT is a timer."
49 (and (vectorp object) (= (length object) 8)))
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
57 (defsetf timer--time
58 (lambda (timer time)
59 (or (timerp timer) (error "Invalid timer"))
60 (setf (timer--high-seconds timer) (pop time))
61 (setf (timer--low-seconds timer)
62 (if (consp time) (car time) time))
63 (setf (timer--usecs timer) (or (and (consp time) (consp (cdr time))
64 (cadr time))
65 0))))
66
67
68 (defun timer-set-time (timer time &optional delta)
69 "Set the trigger time of TIMER to TIME.
70 TIME must be in the internal format returned by, e.g., `current-time'.
71 If optional third argument DELTA is a positive number, make the timer
72 fire repeatedly that many seconds apart."
73 (setf (timer--time timer) time)
74 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
75 timer)
76
77 (defun timer-set-idle-time (timer secs &optional repeat)
78 "Set the trigger idle time of TIMER to SECS.
79 SECS may be an integer, floating point number, or the internal
80 time format (HIGH LOW USECS) returned by, e.g., `current-idle-time'.
81 If optional third argument REPEAT is non-nil, make the timer
82 fire each time Emacs is idle for that many seconds."
83 (if (consp secs)
84 (setf (timer--time timer) secs)
85 (setf (timer--time timer) '(0 0 0))
86 (timer-inc-time timer secs))
87 (setf (timer--repeat-delay timer) repeat)
88 timer)
89
90 (defun timer-next-integral-multiple-of-time (time secs)
91 "Yield the next value after TIME that is an integral multiple of SECS.
92 More precisely, the next value, after TIME, that is an integral multiple
93 of SECS seconds since the epoch. SECS may be a fraction."
94 (let ((time-base (ash 1 16)))
95 (if (fboundp 'atan)
96 ;; Use floating point, taking care to not lose precision.
97 (let* ((float-time-base (float time-base))
98 (million 1000000.0)
99 (time-usec (+ (* million
100 (+ (* float-time-base (nth 0 time))
101 (nth 1 time)))
102 (nth 2 time)))
103 (secs-usec (* million secs))
104 (mod-usec (mod time-usec secs-usec))
105 (next-usec (+ (- time-usec mod-usec) secs-usec))
106 (time-base-million (* float-time-base million)))
107 (list (floor next-usec time-base-million)
108 (floor (mod next-usec time-base-million) million)
109 (floor (mod next-usec million))))
110 ;; Floating point is not supported.
111 ;; Use integer arithmetic, avoiding overflow if possible.
112 (let* ((mod-sec (mod (+ (* (mod time-base secs)
113 (mod (nth 0 time) secs))
114 (nth 1 time))
115 secs))
116 (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
117 (list (+ (nth 0 time) (floor next-1-sec time-base))
118 (mod next-1-sec time-base)
119 0)))))
120
121 (defun timer-relative-time (time secs &optional usecs)
122 "Advance TIME by SECS seconds and optionally USECS microseconds.
123 SECS may be either an integer or a floating point number."
124 ;; FIXME: we should just use (time-add time (list 0 secs usecs))
125 (let ((high (car time))
126 (low (if (consp (cdr time)) (nth 1 time) (cdr time)))
127 (micro (if (numberp (car-safe (cdr-safe (cdr time))))
128 (nth 2 time)
129 0)))
130 ;; Add
131 (if usecs (setq micro (+ micro usecs)))
132 (if (floatp secs)
133 (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
134 (setq low (+ low (floor secs)))
135
136 ;; Normalize
137 ;; `/' rounds towards zero while `mod' returns a positive number,
138 ;; so we can't rely on (= a (+ (* 100 (/ a 100)) (mod a 100))).
139 (setq low (+ low (/ micro 1000000) (if (< micro 0) -1 0)))
140 (setq micro (mod micro 1000000))
141 (setq high (+ high (/ low 65536) (if (< low 0) -1 0)))
142 (setq low (logand low 65535))
143
144 (list high low (and (/= micro 0) micro))))
145
146 (defun timer--time-less-p (t1 t2)
147 "Say whether time value T1 is less than time value T2."
148 ;; FIXME just use time-less-p.
149 (destructuring-bind (high1 low1 micro1) (timer--time t1)
150 (destructuring-bind (high2 low2 micro2) (timer--time t2)
151 (or (< high1 high2)
152 (and (= high1 high2)
153 (or (< low1 low2)
154 (and (= low1 low2)
155 (< micro1 micro2))))))))
156
157 (defun timer-inc-time (timer secs &optional usecs)
158 "Increment the time set in TIMER by SECS seconds and USECS microseconds.
159 SECS may be a fraction. If USECS is omitted, that means it is zero."
160 (setf (timer--time timer)
161 (timer-relative-time (timer--time timer) secs usecs)))
162
163 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
164 "Set the trigger time of TIMER to TIME plus USECS.
165 TIME must be in the internal format returned by, e.g., `current-time'.
166 The microsecond count from TIME is ignored, and USECS is used instead.
167 If optional fourth argument DELTA is a positive number, make the timer
168 fire repeatedly that many seconds apart."
169 (setf (timer--time timer) time)
170 (setf (timer--usecs timer) usecs)
171 (setf (timer--repeat-delay timer) (and (numberp delta) (> delta 0) delta))
172 timer)
173 (make-obsolete 'timer-set-time-with-usecs
174 "use `timer-set-time' and `timer-inc-time' instead."
175 "22.1")
176
177 (defun timer-set-function (timer function &optional args)
178 "Make TIMER call FUNCTION with optional ARGS when triggering."
179 (or (timerp timer)
180 (error "Invalid timer"))
181 (setf (timer--function timer) function)
182 (setf (timer--args timer) args)
183 timer)
184 \f
185 (defun timer--activate (timer &optional triggered-p reuse-cell idle)
186 (if (and (timerp timer)
187 (integerp (timer--high-seconds timer))
188 (integerp (timer--low-seconds timer))
189 (integerp (timer--usecs timer))
190 (timer--function timer))
191 (let ((timers (if idle timer-idle-list timer-list))
192 last)
193 ;; Skip all timers to trigger before the new one.
194 (while (and timers (timer--time-less-p (car timers) timer))
195 (setq last timers
196 timers (cdr timers)))
197 (if reuse-cell
198 (progn
199 (setcar reuse-cell timer)
200 (setcdr reuse-cell timers))
201 (setq reuse-cell (cons timer timers)))
202 ;; Insert new timer after last which possibly means in front of queue.
203 (if last
204 (setcdr last reuse-cell)
205 (if idle
206 (setq timer-idle-list reuse-cell)
207 (setq timer-list reuse-cell)))
208 (setf (timer--triggered timer) triggered-p)
209 (setf (timer--idle-delay timer) idle)
210 nil)
211 (error "Invalid or uninitialized timer")))
212
213 (defun timer-activate (timer &optional triggered-p reuse-cell idle)
214 "Put TIMER on the list of active timers.
215
216 If TRIGGERED-P is t, that means to make the timer inactive
217 \(put it on the list, but mark it as already triggered).
218 To remove from the list, use `cancel-timer'.
219
220 REUSE-CELL, if non-nil, is a cons cell to reuse instead
221 of allocating a new one."
222 (timer--activate timer triggered-p reuse-cell nil))
223
224 (defun timer-activate-when-idle (timer &optional dont-wait reuse-cell)
225 "Arrange to activate TIMER whenever Emacs is next idle.
226 If optional argument DONT-WAIT is non-nil, then enable the
227 timer to activate immediately, or at the right time, if Emacs
228 is already idle.
229
230 REUSE-CELL, if non-nil, is a cons cell to reuse instead
231 of allocating a new one."
232 (timer--activate timer (not dont-wait) reuse-cell 'idle))
233
234 (defalias 'disable-timeout 'cancel-timer)
235
236 (defun cancel-timer (timer)
237 "Remove TIMER from the list of active timers."
238 (or (timerp timer)
239 (error "Invalid timer"))
240 (setq timer-list (delq timer timer-list))
241 (setq timer-idle-list (delq timer timer-idle-list))
242 nil)
243
244 (defun cancel-timer-internal (timer)
245 "Remove TIMER from the list of active timers or idle timers.
246 Only to be used in this file. It returns the cons cell
247 that was removed from the timer list."
248 (let ((cell1 (memq timer timer-list))
249 (cell2 (memq timer timer-idle-list)))
250 (if cell1
251 (setq timer-list (delq timer timer-list)))
252 (if cell2
253 (setq timer-idle-list (delq timer timer-idle-list)))
254 (or cell1 cell2)))
255
256 (defun cancel-function-timers (function)
257 "Cancel all timers which would run FUNCTION.
258 This affects ordinary timers such as are scheduled by `run-at-time',
259 and idle timers such as are scheduled by `run-with-idle-timer'."
260 (interactive "aCancel timers of function: ")
261 (dolist (timer timer-list)
262 (if (eq (timer--function timer) function)
263 (setq timer-list (delq timer timer-list))))
264 (dolist (timer timer-idle-list)
265 (if (eq (timer--function timer) function)
266 (setq timer-idle-list (delq timer timer-idle-list)))))
267 \f
268 ;; Record the last few events, for debugging.
269 (defvar timer-event-last nil
270 "Last timer that was run.")
271 (defvar timer-event-last-1 nil
272 "Next-to-last timer that was run.")
273 (defvar timer-event-last-2 nil
274 "Third-to-last timer that was run.")
275
276 (defvar timer-max-repeats 10
277 "*Maximum number of times to repeat a timer, if many repeats are delayed.
278 Timer invocations can be delayed because Emacs is suspended or busy,
279 or because the system's time changes. If such an occurrence makes it
280 appear that many invocations are overdue, this variable controls
281 how many will really happen.")
282
283 (defun timer-until (timer time)
284 "Calculate number of seconds from when TIMER will run, until TIME.
285 TIMER is a timer, and stands for the time when its next repeat is scheduled.
286 TIME is a time-list."
287 ;; FIXME: (float-time (time-subtract (timer--time timer) time))
288 (let ((high (- (car time) (timer--high-seconds timer)))
289 (low (- (nth 1 time) (timer--low-seconds timer))))
290 (+ low (* high 65536))))
291
292 (defun timer-event-handler (timer)
293 "Call the handler for the timer TIMER.
294 This function is called, by name, directly by the C code."
295 (setq timer-event-last-2 timer-event-last-1)
296 (setq timer-event-last-1 timer-event-last)
297 (setq timer-event-last timer)
298 (let ((inhibit-quit t))
299 (if (timerp timer)
300 (let (retrigger cell)
301 ;; Delete from queue. Record the cons cell that was used.
302 (setq cell (cancel-timer-internal timer))
303 ;; Re-schedule if requested.
304 (if (timer--repeat-delay timer)
305 (if (timer--idle-delay timer)
306 (timer-activate-when-idle timer nil cell)
307 (timer-inc-time timer (timer--repeat-delay timer) 0)
308 ;; If real time has jumped forward,
309 ;; perhaps because Emacs was suspended for a long time,
310 ;; limit how many times things get repeated.
311 (if (and (numberp timer-max-repeats)
312 (< 0 (timer-until timer (current-time))))
313 (let ((repeats (/ (timer-until timer (current-time))
314 (timer--repeat-delay timer))))
315 (if (> repeats timer-max-repeats)
316 (timer-inc-time timer (* (timer--repeat-delay timer)
317 repeats)))))
318 (timer-activate timer t cell)
319 (setq retrigger t)))
320 ;; Run handler.
321 ;; We do this after rescheduling so that the handler function
322 ;; can cancel its own timer successfully with cancel-timer.
323 (condition-case nil
324 (apply (timer--function timer) (timer--args timer))
325 (error nil))
326 (if retrigger
327 (setf (timer--triggered timer) nil)))
328 (error "Bogus timer event"))))
329
330 ;; This function is incompatible with the one in levents.el.
331 (defun timeout-event-p (event)
332 "Non-nil if EVENT is a timeout event."
333 (and (listp event) (eq (car event) 'timer-event)))
334 \f
335
336 (declare-function diary-entry-time "diary-lib" (s))
337
338 (defun run-at-time (time repeat function &rest args)
339 "Perform an action at time TIME.
340 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
341 TIME should be one of: a string giving an absolute time like
342 \"11:23pm\" (the acceptable formats are those recognized by
343 `diary-entry-time'; note that such times are interpreted as times
344 today, even if in the past); a string giving a relative time like
345 \"2 hours 35 minutes\" (the acceptable formats are those
346 recognized by `timer-duration'); nil meaning now; a number of
347 seconds from now; a value from `encode-time'; or t (with non-nil
348 REPEAT) meaning the next integral multiple of REPEAT. REPEAT may
349 be an integer or floating point number. The action is to call
350 FUNCTION with arguments ARGS.
351
352 This function returns a timer object which you can use in `cancel-timer'."
353 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
354
355 (or (null repeat)
356 (and (numberp repeat) (< 0 repeat))
357 (error "Invalid repetition interval"))
358
359 ;; Special case: nil means "now" and is useful when repeating.
360 (if (null time)
361 (setq time (current-time)))
362
363 ;; Special case: t means the next integral multiple of REPEAT.
364 (if (and (eq time t) repeat)
365 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
366
367 ;; Handle numbers as relative times in seconds.
368 (if (numberp time)
369 (setq time (timer-relative-time (current-time) time)))
370
371 ;; Handle relative times like "2 hours 35 minutes"
372 (if (stringp time)
373 (let ((secs (timer-duration time)))
374 (if secs
375 (setq time (timer-relative-time (current-time) secs)))))
376
377 ;; Handle "11:23pm" and the like. Interpret it as meaning today
378 ;; which admittedly is rather stupid if we have passed that time
379 ;; already. (Though only Emacs hackers hack Emacs at that time.)
380 (if (stringp time)
381 (progn
382 (require 'diary-lib)
383 (let ((hhmm (diary-entry-time time))
384 (now (decode-time)))
385 (if (>= hhmm 0)
386 (setq time
387 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
388 (nth 4 now) (nth 5 now) (nth 8 now)))))))
389
390 (or (consp time)
391 (error "Invalid time format"))
392
393 (let ((timer (timer-create)))
394 (timer-set-time timer time repeat)
395 (timer-set-function timer function args)
396 (timer-activate timer)
397 timer))
398
399 (defun run-with-timer (secs repeat function &rest args)
400 "Perform an action after a delay of SECS seconds.
401 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
402 SECS and REPEAT may be integers or floating point numbers.
403 The action is to call FUNCTION with arguments ARGS.
404
405 This function returns a timer object which you can use in `cancel-timer'."
406 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
407 (apply 'run-at-time secs repeat function args))
408
409 (defun add-timeout (secs function object &optional repeat)
410 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
411 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
412 This function is for compatibility; see also `run-with-timer'."
413 (run-with-timer secs repeat function object))
414
415 (defun run-with-idle-timer (secs repeat function &rest args)
416 "Perform an action the next time Emacs is idle for SECS seconds.
417 The action is to call FUNCTION with arguments ARGS.
418 SECS may be an integer, a floating point number, or the internal
419 time format (HIGH LOW USECS) returned by, e.g., `current-idle-time'.
420 If Emacs is currently idle, and has been idle for N seconds (N < SECS),
421 then it will call FUNCTION in SECS - N seconds from now.
422
423 If REPEAT is non-nil, do the action each time Emacs has been idle for
424 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
425
426 This function returns a timer object which you can use in `cancel-timer'."
427 (interactive
428 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
429 (y-or-n-p "Repeat each time Emacs is idle? ")
430 (intern (completing-read "Function: " obarray 'fboundp t))))
431 (let ((timer (timer-create)))
432 (timer-set-function timer function args)
433 (timer-set-idle-time timer secs repeat)
434 (timer-activate-when-idle timer t)
435 timer))
436 \f
437 (defun with-timeout-handler (tag)
438 "This is the timer function used for the timer made by `with-timeout'."
439 (throw tag 'timeout))
440
441 (put 'with-timeout 'lisp-indent-function 1)
442
443 (defvar with-timeout-timers nil
444 "List of all timers used by currently pending `with-timeout' calls.")
445
446 (defmacro with-timeout (list &rest body)
447 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
448 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
449 The timeout is checked whenever Emacs waits for some kind of external
450 event (such as keyboard input, input from subprocesses, or a certain time);
451 if the program loops without waiting in any way, the timeout will not
452 be detected.
453 \n(fn (SECONDS TIMEOUT-FORMS...) BODY)"
454 (let ((seconds (car list))
455 (timeout-forms (cdr list)))
456 `(let ((with-timeout-tag (cons nil nil))
457 with-timeout-value with-timeout-timer
458 (with-timeout-timers with-timeout-timers))
459 (if (catch with-timeout-tag
460 (progn
461 (setq with-timeout-timer
462 (run-with-timer ,seconds nil
463 'with-timeout-handler
464 with-timeout-tag))
465 (push with-timeout-timer with-timeout-timers)
466 (setq with-timeout-value (progn . ,body))
467 nil))
468 (progn . ,timeout-forms)
469 (cancel-timer with-timeout-timer)
470 with-timeout-value))))
471
472 (defun with-timeout-suspend ()
473 "Stop the clock for `with-timeout'. Used by debuggers.
474 The idea is that the time you spend in the debugger should not
475 count against these timeouts.
476
477 The value is a list that the debugger can pass to `with-timeout-unsuspend'
478 when it exits, to make these timers start counting again."
479 (mapcar (lambda (timer)
480 (cancel-timer timer)
481 (list timer (time-subtract (timer--time timer) (current-time))))
482 with-timeout-timers))
483
484 (defun with-timeout-unsuspend (timer-spec-list)
485 "Restart the clock for `with-timeout'.
486 The argument should be a value previously returned by `with-timeout-suspend'."
487 (dolist (elt timer-spec-list)
488 (let ((timer (car elt))
489 (delay (cadr elt)))
490 (timer-set-time timer (time-add (current-time) delay))
491 (timer-activate timer))))
492
493 (defun y-or-n-p-with-timeout (prompt seconds default-value)
494 "Like (y-or-n-p PROMPT), with a timeout.
495 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
496 (with-timeout (seconds default-value)
497 (y-or-n-p prompt)))
498 \f
499 (defconst timer-duration-words
500 (list (cons "microsec" 0.000001)
501 (cons "microsecond" 0.000001)
502 (cons "millisec" 0.001)
503 (cons "millisecond" 0.001)
504 (cons "sec" 1)
505 (cons "second" 1)
506 (cons "min" 60)
507 (cons "minute" 60)
508 (cons "hour" (* 60 60))
509 (cons "day" (* 24 60 60))
510 (cons "week" (* 7 24 60 60))
511 (cons "fortnight" (* 14 24 60 60))
512 (cons "month" (* 30 24 60 60)) ; Approximation
513 (cons "year" (* 365.25 24 60 60)) ; Approximation
514 )
515 "Alist mapping temporal words to durations in seconds.")
516
517 (defun timer-duration (string)
518 "Return number of seconds specified by STRING, or nil if parsing fails."
519 (let ((secs 0)
520 (start 0)
521 (case-fold-search t))
522 (while (string-match
523 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
524 string start)
525 (let ((count (if (match-beginning 1)
526 (string-to-number (match-string 1 string))
527 1))
528 (itemsize (cdr (assoc (match-string 2 string)
529 timer-duration-words))))
530 (if itemsize
531 (setq start (match-end 0)
532 secs (+ secs (* count itemsize)))
533 (setq secs nil
534 start (length string)))))
535 (if (= start (length string))
536 secs
537 (if (string-match-p "\\`[0-9.]+\\'" string)
538 (string-to-number string)))))
539 \f
540 (provide 'timer)
541
542 ;; arch-tag: b1a9237b-7787-4382-9e46-8f2c3b3273e0
543 ;;; timer.el ends here