(timer-event-handler): Take timer as arg directly.
[bpt/emacs.git] / lisp / timer.el
1 ;;; timer.el --- run a function with args at some time in future.
2
3 ;; Copyright (C) 1996 Free Software Foundation, Inc.
4
5 ;; Maintainer: FSF
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;; This package gives you the capability to run Emacs Lisp commands at
27 ;; specified times in the future, either as one-shots or periodically.
28
29 ;;; Code:
30
31 ;; Layout of a timer vector:
32 ;; [triggered-p high-seconds low-seconds usecs repeat-delay
33 ;; function args idle-delay]
34
35 (defun timer-create ()
36 "Create a timer object."
37 (let ((timer (make-vector 8 nil)))
38 (aset timer 0 t)
39 timer))
40
41 (defun timerp (object)
42 "Return t if OBJECT is a timer."
43 (and (vectorp object) (= (length object) 8)))
44
45 (defun timer-set-time (timer time &optional delta)
46 "Set the trigger time of TIMER to TIME.
47 TIME must be in the internal format returned by, e.g., `current-time'.
48 If optional third argument DELTA is a non-zero integer, make the timer
49 fire repeatedly that many seconds apart."
50 (or (timerp timer)
51 (error "Invalid timer"))
52 (aset timer 1 (car time))
53 (aset timer 2 (if (consp (cdr time)) (car (cdr time)) (cdr time)))
54 (aset timer 3 (or (and (consp (cdr time)) (consp (cdr (cdr time)))
55 (nth 2 time))
56 0))
57 (aset timer 4 (and (numberp delta) (> delta 0) delta))
58 timer)
59
60 (defun timer-set-idle-time (timer secs &optional repeat)
61 "Set the trigger idle time of TIMER to SECS.
62 If optional third argument REPEAT is non-nil, make the timer
63 fire each time Emacs is idle for that many seconds."
64 (or (timerp timer)
65 (error "Invalid timer"))
66 (aset timer 1 0)
67 (aset timer 2 0)
68 (aset timer 3 0)
69 (timer-inc-time timer secs)
70 (aset timer 4 repeat)
71 timer)
72
73 (defun timer-next-integral-multiple-of-time (time secs)
74 "Yield the next value after TIME that is an integral multiple of SECS.
75 More precisely, the next value, after TIME, that is an integral multiple
76 of SECS seconds since the epoch. SECS may be a fraction."
77 (let ((time-base (ash 1 16)))
78 (if (fboundp 'atan)
79 ;; Use floating point, taking care to not lose precision.
80 (let* ((float-time-base (float time-base))
81 (million 1000000.0)
82 (time-usec (+ (* million
83 (+ (* float-time-base (nth 0 time))
84 (nth 1 time)))
85 (nth 2 time)))
86 (secs-usec (* million secs))
87 (mod-usec (mod time-usec secs-usec))
88 (next-usec (+ (- time-usec mod-usec) secs-usec))
89 (time-base-million (* float-time-base million)))
90 (list (floor next-usec time-base-million)
91 (floor (mod next-usec time-base-million) million)
92 (floor (mod next-usec million))))
93 ;; Floating point is not supported.
94 ;; Use integer arithmetic, avoiding overflow if possible.
95 (let* ((mod-sec (mod (+ (* (mod time-base secs)
96 (mod (nth 0 time) secs))
97 (nth 1 time))
98 secs))
99 (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
100 (list (+ (nth 0 time) (floor next-1-sec time-base))
101 (mod next-1-sec time-base)
102 0)))))
103
104 (defun timer-relative-time (time secs &optional usecs)
105 "Advance TIME by SECS seconds and optionally USECS microseconds.
106 SECS may be a fraction."
107 (let ((high (car time))
108 (low (if (consp (cdr time)) (nth 1 time) (cdr time)))
109 (micro (if (numberp (car-safe (cdr-safe (cdr time))))
110 (nth 2 time)
111 0)))
112 ;; Add
113 (if usecs (setq micro (+ micro usecs)))
114 (if (floatp secs)
115 (setq micro (+ micro (floor (* 1000000 (- secs (floor secs)))))))
116 (setq low (+ low (floor secs)))
117
118 ;; Normalize
119 (setq low (+ low (/ micro 1000000)))
120 (setq micro (mod micro 1000000))
121 (setq high (+ high (/ low 65536)))
122 (setq low (logand low 65535))
123
124 (list high low (and (/= micro 0) micro))))
125
126 (defun timer-inc-time (timer secs &optional usecs)
127 "Increment the time set in TIMER by SECS seconds and USECS microseconds.
128 SECS may be a fraction."
129 (let ((time (timer-relative-time
130 (list (aref timer 1) (aref timer 2) (aref timer 3))
131 secs
132 usecs)))
133 (aset timer 1 (nth 0 time))
134 (aset timer 2 (nth 1 time))
135 (aset timer 3 (or (nth 2 time) 0))))
136
137 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
138 "Set the trigger time of TIMER to TIME.
139 TIME must be in the internal format returned by, e.g., `current-time'.
140 If optional third argument DELTA is a non-zero integer, make the timer
141 fire repeatedly that many seconds apart."
142 (or (timerp timer)
143 (error "Invalid timer"))
144 (aset timer 1 (car time))
145 (aset timer 2 (if (consp (cdr time)) (car (cdr time)) (cdr time)))
146 (aset timer 3 usecs)
147 (aset timer 4 (and (numberp delta) (> delta 0) delta))
148 timer)
149
150 (defun timer-set-function (timer function &optional args)
151 "Make TIMER call FUNCTION with optional ARGS when triggering."
152 (or (timerp timer)
153 (error "Invalid timer"))
154 (aset timer 5 function)
155 (aset timer 6 args)
156 timer)
157 \f
158 (defun timer-activate (timer)
159 "Put TIMER on the list of active timers."
160 (if (and (timerp timer)
161 (integerp (aref timer 1))
162 (integerp (aref timer 2))
163 (integerp (aref timer 3))
164 (aref timer 5))
165 (let ((timers timer-list)
166 last)
167 ;; Skip all timers to trigger before the new one.
168 (while (and timers
169 (or (> (aref timer 1) (aref (car timers) 1))
170 (and (= (aref timer 1) (aref (car timers) 1))
171 (> (aref timer 2) (aref (car timers) 2)))
172 (and (= (aref timer 1) (aref (car timers) 1))
173 (= (aref timer 2) (aref (car timers) 2))
174 (> (aref timer 3) (aref (car timers) 3)))))
175 (setq last timers
176 timers (cdr timers)))
177 ;; Insert new timer after last which possibly means in front of queue.
178 (if last
179 (setcdr last (cons timer timers))
180 (setq timer-list (cons timer timers)))
181 (aset timer 0 nil)
182 (aset timer 7 nil)
183 nil)
184 (error "Invalid or uninitialized timer")))
185
186 (defun timer-activate-when-idle (timer)
187 "Arrange to activate TIMER whenever Emacs is next idle."
188 (if (and (timerp timer)
189 (integerp (aref timer 1))
190 (integerp (aref timer 2))
191 (integerp (aref timer 3))
192 (aref timer 5))
193 (let ((timers timer-idle-list)
194 last)
195 ;; Skip all timers to trigger before the new one.
196 (while (and timers
197 (or (> (aref timer 1) (aref (car timers) 1))
198 (and (= (aref timer 1) (aref (car timers) 1))
199 (> (aref timer 2) (aref (car timers) 2)))
200 (and (= (aref timer 1) (aref (car timers) 1))
201 (= (aref timer 2) (aref (car timers) 2))
202 (> (aref timer 3) (aref (car timers) 3)))))
203 (setq last timers
204 timers (cdr timers)))
205 ;; Insert new timer after last which possibly means in front of queue.
206 (if last
207 (setcdr last (cons timer timers))
208 (setq timer-idle-list (cons timer timers)))
209 (aset timer 0 t)
210 (aset timer 7 t)
211 nil)
212 (error "Invalid or uninitialized timer")))
213
214 ;;;###autoload
215 (defalias 'disable-timeout 'cancel-timer)
216 ;;;###autoload
217 (defun cancel-timer (timer)
218 "Remove TIMER from the list of active timers."
219 (or (timerp timer)
220 (error "Invalid timer"))
221 (setq timer-list (delq timer timer-list))
222 (setq timer-idle-list (delq timer timer-idle-list))
223 nil)
224
225 ;;;###autoload
226 (defun cancel-function-timers (function)
227 "Cancel all timers scheduled by `run-at-time' which would run FUNCTION."
228 (interactive "aCancel timers of function: ")
229 (let ((tail timer-list))
230 (while tail
231 (if (eq (aref (car tail) 5) function)
232 (setq timer-list (delq (car tail) timer-list)))
233 (setq tail (cdr tail))))
234 (let ((tail timer-idle-list))
235 (while tail
236 (if (eq (aref (car tail) 5) function)
237 (setq timer-idle-list (delq (car tail) timer-idle-list)))
238 (setq tail (cdr tail)))))
239 \f
240 ;; Record the last few events, for debugging.
241 (defvar timer-event-last-2 nil)
242 (defvar timer-event-last-1 nil)
243 (defvar timer-event-last nil)
244
245 (defvar timer-max-repeats 10
246 "*Maximum number of times to repeat a timer, if real time jumps.")
247
248 (defun timer-until (timer time)
249 "Calculate number of seconds from when TIMER will run, until TIME.
250 TIMER is a timer, and stands for the time when its next repeat is scheduled.
251 TIME is a time-list."
252 (let ((high (- (car time) (aref timer 1)))
253 (low (- (nth 1 time) (aref timer 2))))
254 (+ low (* high 65536))))
255
256 (defun timer-event-handler (timer)
257 "Call the handler for the timer TIMER.
258 This function is called, by name, directly by the C code."
259 (setq timer-event-last-2 timer-event-last-1)
260 (setq timer-event-last-1 timer-event-last)
261 (setq timer-event-last timer)
262 (let ((inhibit-quit t))
263 (if (timerp timer)
264 (progn
265 ;; Delete from queue.
266 (cancel-timer timer)
267 ;; Run handler
268 (condition-case nil
269 (apply (aref timer 5) (aref timer 6))
270 (error nil))
271 ;; Re-schedule if requested.
272 (if (aref timer 4)
273 (if (aref timer 7)
274 (timer-activate-when-idle timer)
275 (timer-inc-time timer (aref timer 4) 0)
276 ;; If real time has jumped forward,
277 ;; perhaps because Emacs was suspended for a long time,
278 ;; limit how many times things get repeated.
279 (if (and (numberp timer-max-repeats)
280 (< 0 (timer-until timer (current-time))))
281 (let ((repeats (/ (timer-until timer (current-time))
282 (aref timer 4))))
283 (if (> repeats timer-max-repeats)
284 (timer-inc-time timer (* (aref timer 4) repeats)))))
285 (timer-activate timer))))
286 (error "Bogus timer event"))))
287
288 ;; This function is incompatible with the one in levents.el.
289 (defun timeout-event-p (event)
290 "Non-nil if EVENT is a timeout event."
291 (and (listp event) (eq (car event) 'timer-event)))
292 \f
293 ;;;###autoload
294 (defun run-at-time (time repeat function &rest args)
295 "Perform an action at time TIME.
296 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
297 TIME should be a string like \"11:23pm\", nil meaning now, a number of seconds
298 from now, a value from `current-time', or t (with non-nil REPEAT)
299 meaning the next integral multiple of REPEAT.
300 REPEAT may be an integer or floating point number.
301 The action is to call FUNCTION with arguments ARGS.
302
303 This function returns a timer object which you can use in `cancel-timer'."
304 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
305
306 (or (null repeat)
307 (and (numberp repeat) (< 0 repeat))
308 (error "Invalid repetition interval"))
309
310 ;; Special case: nil means "now" and is useful when repeating.
311 (if (null time)
312 (setq time (current-time)))
313
314 ;; Special case: t means the next integral multiple of REPEAT.
315 (if (and (eq time t) repeat)
316 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
317
318 ;; Handle numbers as relative times in seconds.
319 (if (numberp time)
320 (setq time (timer-relative-time (current-time) time)))
321
322 ;; Handle relative times like "2 hours and 35 minutes"
323 (if (stringp time)
324 (let ((secs (timer-duration time)))
325 (if secs
326 (setq time (timer-relative-time (current-time) secs)))))
327
328 ;; Handle "11:23pm" and the like. Interpret it as meaning today
329 ;; which admittedly is rather stupid if we have passed that time
330 ;; already. (Though only Emacs hackers hack Emacs at that time.)
331 (if (stringp time)
332 (progn
333 (require 'diary-lib)
334 (let ((hhmm (diary-entry-time time))
335 (now (decode-time)))
336 (if (>= hhmm 0)
337 (setq time
338 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
339 (nth 4 now) (nth 5 now) (nth 8 now)))))))
340
341 (or (consp time)
342 (error "Invalid time format"))
343
344 (let ((timer (timer-create)))
345 (timer-set-time timer time repeat)
346 (timer-set-function timer function args)
347 (timer-activate timer)
348 timer))
349
350 ;;;###autoload
351 (defun run-with-timer (secs repeat function &rest args)
352 "Perform an action after a delay of SECS seconds.
353 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
354 SECS and REPEAT may be integers or floating point numbers.
355 The action is to call FUNCTION with arguments ARGS.
356
357 This function returns a timer object which you can use in `cancel-timer'."
358 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
359 (apply 'run-at-time secs repeat function args))
360
361 ;;;###autoload
362 (defun add-timeout (secs function object &optional repeat)
363 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
364 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
365 This function is for compatibility; see also `run-with-timer'."
366 (run-with-timer secs repeat function object))
367
368 ;;;###autoload
369 (defun run-with-idle-timer (secs repeat function &rest args)
370 "Perform an action the next time Emacs is idle for SECS seconds.
371 If REPEAT is non-nil, do this each time Emacs is idle for SECS seconds.
372 SECS may be an integer or a floating point number.
373 The action is to call FUNCTION with arguments ARGS.
374
375 This function returns a timer object which you can use in `cancel-timer'."
376 (interactive
377 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
378 (y-or-n-p "Repeat each time Emacs is idle? ")
379 (intern (completing-read "Function: " obarray 'fboundp t))))
380 (let ((timer (timer-create)))
381 (timer-set-function timer function args)
382 (timer-set-idle-time timer secs repeat)
383 (timer-activate-when-idle timer)
384 timer))
385 \f
386 (defun with-timeout-handler (tag)
387 (throw tag 'timeout))
388
389 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
390
391 ;;;###autoload
392 (defmacro with-timeout (list &rest body)
393 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
394 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
395 The call should look like:
396 (with-timeout (SECONDS TIMEOUT-FORMS...) BODY...)
397 The timeout is checked whenever Emacs waits for some kind of external
398 event \(such as keyboard input, input from subprocesses, or a certain time);
399 if the program loops without waiting in any way, the timeout will not
400 be detected."
401 (let ((seconds (car list))
402 (timeout-forms (cdr list)))
403 `(let ((with-timeout-tag (cons nil nil))
404 with-timeout-value with-timeout-timer)
405 (if (catch with-timeout-tag
406 (progn
407 (setq with-timeout-timer
408 (run-with-timer ,seconds nil
409 'with-timeout-handler
410 with-timeout-tag))
411 (setq with-timeout-value (progn . ,body))
412 nil))
413 (progn . ,timeout-forms)
414 (cancel-timer with-timeout-timer)
415 with-timeout-value))))
416
417 (defun y-or-n-p-with-timeout (prompt seconds default-value)
418 "Like (y-or-n-p PROMPT), with a timeout.
419 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
420 (with-timeout (seconds default-value)
421 (y-or-n-p prompt)))
422 \f
423 (defvar timer-duration-words
424 (list (cons "microsec" 0.000001)
425 (cons "microsecond" 0.000001)
426 (cons "millisec" 0.001)
427 (cons "millisecond" 0.001)
428 (cons "sec" 1)
429 (cons "second" 1)
430 (cons "min" 60)
431 (cons "minute" 60)
432 (cons "hour" (* 60 60))
433 (cons "day" (* 24 60 60))
434 (cons "week" (* 7 24 60 60))
435 (cons "fortnight" (* 14 24 60 60))
436 (cons "month" (* 30 24 60 60)) ; Approximation
437 (cons "year" (* 365.25 24 60 60)) ; Approximation
438 )
439 "Alist mapping temporal words to durations in seconds")
440
441 (defun timer-duration (string)
442 "Return number of seconds specified by STRING, or nil if parsing fails."
443 (let ((secs 0)
444 (start 0)
445 (case-fold-search t))
446 (while (string-match
447 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
448 string start)
449 (let ((count (if (match-beginning 1)
450 (string-to-number (match-string 1 string))
451 1))
452 (itemsize (cdr (assoc (match-string 2 string)
453 timer-duration-words))))
454 (if itemsize
455 (setq start (match-end 0)
456 secs (+ secs (* count itemsize)))
457 (setq secs nil
458 start (length string)))))
459 (if (= start (length string))
460 secs
461 (if (string-match "\\`[0-9.]+\\'" string)
462 (string-to-number string)))))
463 \f
464 (provide 'timer)
465
466 ;;; timer.el ends here