(text-mode-map): Remove the \t binding.
[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 ;; `/' rounds towards zero while `mod' returns a positive number,
120 ;; so we can't rely on (= a (+ (* 100 (/ a 100)) (mod a 100))).
121 (setq low (+ low (/ micro 1000000) (if (< micro 0) -1 0)))
122 (setq micro (mod micro 1000000))
123 (setq high (+ high (/ low 65536) (if (< low 0) -1 0)))
124 (setq low (logand low 65535))
125
126 (list high low (and (/= micro 0) micro))))
127
128 (defun timer-inc-time (timer secs &optional usecs)
129 "Increment the time set in TIMER by SECS seconds and USECS microseconds.
130 SECS may be a fraction."
131 (let ((time (timer-relative-time
132 (list (aref timer 1) (aref timer 2) (aref timer 3))
133 secs
134 usecs)))
135 (aset timer 1 (nth 0 time))
136 (aset timer 2 (nth 1 time))
137 (aset timer 3 (or (nth 2 time) 0))))
138
139 (defun timer-set-time-with-usecs (timer time usecs &optional delta)
140 "Set the trigger time of TIMER to TIME.
141 TIME must be in the internal format returned by, e.g., `current-time'.
142 If optional third argument DELTA is a non-zero integer, make the timer
143 fire repeatedly that many seconds apart."
144 (or (timerp timer)
145 (error "Invalid timer"))
146 (aset timer 1 (car time))
147 (aset timer 2 (if (consp (cdr time)) (car (cdr time)) (cdr time)))
148 (aset timer 3 usecs)
149 (aset timer 4 (and (numberp delta) (> delta 0) delta))
150 timer)
151
152 (defun timer-set-function (timer function &optional args)
153 "Make TIMER call FUNCTION with optional ARGS when triggering."
154 (or (timerp timer)
155 (error "Invalid timer"))
156 (aset timer 5 function)
157 (aset timer 6 args)
158 timer)
159 \f
160 (defun timer-activate (timer)
161 "Put TIMER on the list of active timers."
162 (if (and (timerp timer)
163 (integerp (aref timer 1))
164 (integerp (aref timer 2))
165 (integerp (aref timer 3))
166 (aref timer 5))
167 (let ((timers timer-list)
168 last)
169 ;; Skip all timers to trigger before the new one.
170 (while (and timers
171 (or (> (aref timer 1) (aref (car timers) 1))
172 (and (= (aref timer 1) (aref (car timers) 1))
173 (> (aref timer 2) (aref (car timers) 2)))
174 (and (= (aref timer 1) (aref (car timers) 1))
175 (= (aref timer 2) (aref (car timers) 2))
176 (> (aref timer 3) (aref (car timers) 3)))))
177 (setq last timers
178 timers (cdr timers)))
179 ;; Insert new timer after last which possibly means in front of queue.
180 (if last
181 (setcdr last (cons timer timers))
182 (setq timer-list (cons timer timers)))
183 (aset timer 0 nil)
184 (aset timer 7 nil)
185 nil)
186 (error "Invalid or uninitialized timer")))
187
188 (defun timer-activate-when-idle (timer &optional dont-wait)
189 "Arrange to activate TIMER whenever Emacs is next idle.
190 If optional argument DONT-WAIT is non-nil, then enable the
191 timer to activate immediately, or at the right time, if Emacs
192 is already idle."
193 (if (and (timerp timer)
194 (integerp (aref timer 1))
195 (integerp (aref timer 2))
196 (integerp (aref timer 3))
197 (aref timer 5))
198 (let ((timers timer-idle-list)
199 last)
200 ;; Skip all timers to trigger before the new one.
201 (while (and timers
202 (or (> (aref timer 1) (aref (car timers) 1))
203 (and (= (aref timer 1) (aref (car timers) 1))
204 (> (aref timer 2) (aref (car timers) 2)))
205 (and (= (aref timer 1) (aref (car timers) 1))
206 (= (aref timer 2) (aref (car timers) 2))
207 (> (aref timer 3) (aref (car timers) 3)))))
208 (setq last timers
209 timers (cdr timers)))
210 ;; Insert new timer after last which possibly means in front of queue.
211 (if last
212 (setcdr last (cons timer timers))
213 (setq timer-idle-list (cons timer timers)))
214 (aset timer 0 (not dont-wait))
215 (aset timer 7 t)
216 nil)
217 (error "Invalid or uninitialized timer")))
218
219 ;;;###autoload
220 (defalias 'disable-timeout 'cancel-timer)
221 ;;;###autoload
222 (defun cancel-timer (timer)
223 "Remove TIMER from the list of active timers."
224 (or (timerp timer)
225 (error "Invalid timer"))
226 (setq timer-list (delq timer timer-list))
227 (setq timer-idle-list (delq timer timer-idle-list))
228 nil)
229
230 ;;;###autoload
231 (defun cancel-function-timers (function)
232 "Cancel all timers scheduled by `run-at-time' which would run FUNCTION."
233 (interactive "aCancel timers of function: ")
234 (let ((tail timer-list))
235 (while tail
236 (if (eq (aref (car tail) 5) function)
237 (setq timer-list (delq (car tail) timer-list)))
238 (setq tail (cdr tail))))
239 (let ((tail timer-idle-list))
240 (while tail
241 (if (eq (aref (car tail) 5) function)
242 (setq timer-idle-list (delq (car tail) timer-idle-list)))
243 (setq tail (cdr tail)))))
244 \f
245 ;; Record the last few events, for debugging.
246 (defvar timer-event-last-2 nil)
247 (defvar timer-event-last-1 nil)
248 (defvar timer-event-last nil)
249
250 (defvar timer-max-repeats 10
251 "*Maximum number of times to repeat a timer, if real time jumps.")
252
253 (defun timer-until (timer time)
254 "Calculate number of seconds from when TIMER will run, until TIME.
255 TIMER is a timer, and stands for the time when its next repeat is scheduled.
256 TIME is a time-list."
257 (let ((high (- (car time) (aref timer 1)))
258 (low (- (nth 1 time) (aref timer 2))))
259 (+ low (* high 65536))))
260
261 (defun timer-event-handler (timer)
262 "Call the handler for the timer TIMER.
263 This function is called, by name, directly by the C code."
264 (setq timer-event-last-2 timer-event-last-1)
265 (setq timer-event-last-1 timer-event-last)
266 (setq timer-event-last timer)
267 (let ((inhibit-quit t))
268 (if (timerp timer)
269 (progn
270 ;; Delete from queue.
271 (cancel-timer timer)
272 ;; Re-schedule if requested.
273 (if (aref timer 4)
274 (if (aref timer 7)
275 (timer-activate-when-idle timer)
276 (timer-inc-time timer (aref timer 4) 0)
277 ;; If real time has jumped forward,
278 ;; perhaps because Emacs was suspended for a long time,
279 ;; limit how many times things get repeated.
280 (if (and (numberp timer-max-repeats)
281 (< 0 (timer-until timer (current-time))))
282 (let ((repeats (/ (timer-until timer (current-time))
283 (aref timer 4))))
284 (if (> repeats timer-max-repeats)
285 (timer-inc-time timer (* (aref timer 4) repeats)))))
286 (timer-activate timer)))
287 ;; Run handler.
288 ;; We do this after rescheduling so that the handler function
289 ;; can cancel its own timer successfully with cancel-timer.
290 (condition-case nil
291 (apply (aref timer 5) (aref timer 6))
292 (error nil)))
293 (error "Bogus timer event"))))
294
295 ;; This function is incompatible with the one in levents.el.
296 (defun timeout-event-p (event)
297 "Non-nil if EVENT is a timeout event."
298 (and (listp event) (eq (car event) 'timer-event)))
299 \f
300 ;;;###autoload
301 (defun run-at-time (time repeat function &rest args)
302 "Perform an action at time TIME.
303 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
304 TIME should be a string like \"11:23pm\", nil meaning now, a number of seconds
305 from now, a value from `current-time', or t (with non-nil REPEAT)
306 meaning the next integral multiple of REPEAT.
307 REPEAT may be an integer or floating point number.
308 The action is to call FUNCTION with arguments ARGS.
309
310 This function returns a timer object which you can use in `cancel-timer'."
311 (interactive "sRun at time: \nNRepeat interval: \naFunction: ")
312
313 (or (null repeat)
314 (and (numberp repeat) (< 0 repeat))
315 (error "Invalid repetition interval"))
316
317 ;; Special case: nil means "now" and is useful when repeating.
318 (if (null time)
319 (setq time (current-time)))
320
321 ;; Special case: t means the next integral multiple of REPEAT.
322 (if (and (eq time t) repeat)
323 (setq time (timer-next-integral-multiple-of-time (current-time) repeat)))
324
325 ;; Handle numbers as relative times in seconds.
326 (if (numberp time)
327 (setq time (timer-relative-time (current-time) time)))
328
329 ;; Handle relative times like "2 hours and 35 minutes"
330 (if (stringp time)
331 (let ((secs (timer-duration time)))
332 (if secs
333 (setq time (timer-relative-time (current-time) secs)))))
334
335 ;; Handle "11:23pm" and the like. Interpret it as meaning today
336 ;; which admittedly is rather stupid if we have passed that time
337 ;; already. (Though only Emacs hackers hack Emacs at that time.)
338 (if (stringp time)
339 (progn
340 (require 'diary-lib)
341 (let ((hhmm (diary-entry-time time))
342 (now (decode-time)))
343 (if (>= hhmm 0)
344 (setq time
345 (encode-time 0 (% hhmm 100) (/ hhmm 100) (nth 3 now)
346 (nth 4 now) (nth 5 now) (nth 8 now)))))))
347
348 (or (consp time)
349 (error "Invalid time format"))
350
351 (let ((timer (timer-create)))
352 (timer-set-time timer time repeat)
353 (timer-set-function timer function args)
354 (timer-activate timer)
355 timer))
356
357 ;;;###autoload
358 (defun run-with-timer (secs repeat function &rest args)
359 "Perform an action after a delay of SECS seconds.
360 Repeat the action every REPEAT seconds, if REPEAT is non-nil.
361 SECS and REPEAT may be integers or floating point numbers.
362 The action is to call FUNCTION with arguments ARGS.
363
364 This function returns a timer object which you can use in `cancel-timer'."
365 (interactive "sRun after delay (seconds): \nNRepeat interval: \naFunction: ")
366 (apply 'run-at-time secs repeat function args))
367
368 ;;;###autoload
369 (defun add-timeout (secs function object &optional repeat)
370 "Add a timer to run SECS seconds from now, to call FUNCTION on OBJECT.
371 If REPEAT is non-nil, repeat the timer every REPEAT seconds.
372 This function is for compatibility; see also `run-with-timer'."
373 (run-with-timer secs repeat function object))
374
375 ;;;###autoload
376 (defun run-with-idle-timer (secs repeat function &rest args)
377 "Perform an action the next time Emacs is idle for SECS seconds.
378 The action is to call FUNCTION with arguments ARGS.
379 SECS may be an integer or a floating point number.
380
381 If REPEAT is non-nil, do the action each time Emacs has been idle for
382 exactly SECS seconds (that is, only once for each time Emacs becomes idle).
383
384 This function returns a timer object which you can use in `cancel-timer'."
385 (interactive
386 (list (read-from-minibuffer "Run after idle (seconds): " nil nil t)
387 (y-or-n-p "Repeat each time Emacs is idle? ")
388 (intern (completing-read "Function: " obarray 'fboundp t))))
389 (let ((timer (timer-create)))
390 (timer-set-function timer function args)
391 (timer-set-idle-time timer secs repeat)
392 (timer-activate-when-idle timer)
393 timer))
394 \f
395 (defun with-timeout-handler (tag)
396 (throw tag 'timeout))
397
398 ;;;###autoload (put 'with-timeout 'lisp-indent-function 1)
399
400 ;;;###autoload
401 (defmacro with-timeout (list &rest body)
402 "Run BODY, but if it doesn't finish in SECONDS seconds, give up.
403 If we give up, we run the TIMEOUT-FORMS and return the value of the last one.
404 The call should look like:
405 (with-timeout (SECONDS TIMEOUT-FORMS...) BODY...)
406 The timeout is checked whenever Emacs waits for some kind of external
407 event \(such as keyboard input, input from subprocesses, or a certain time);
408 if the program loops without waiting in any way, the timeout will not
409 be detected."
410 (let ((seconds (car list))
411 (timeout-forms (cdr list)))
412 `(let ((with-timeout-tag (cons nil nil))
413 with-timeout-value with-timeout-timer)
414 (if (catch with-timeout-tag
415 (progn
416 (setq with-timeout-timer
417 (run-with-timer ,seconds nil
418 'with-timeout-handler
419 with-timeout-tag))
420 (setq with-timeout-value (progn . ,body))
421 nil))
422 (progn . ,timeout-forms)
423 (cancel-timer with-timeout-timer)
424 with-timeout-value))))
425
426 (defun y-or-n-p-with-timeout (prompt seconds default-value)
427 "Like (y-or-n-p PROMPT), with a timeout.
428 If the user does not answer after SECONDS seconds, return DEFAULT-VALUE."
429 (with-timeout (seconds default-value)
430 (y-or-n-p prompt)))
431 \f
432 (defvar timer-duration-words
433 (list (cons "microsec" 0.000001)
434 (cons "microsecond" 0.000001)
435 (cons "millisec" 0.001)
436 (cons "millisecond" 0.001)
437 (cons "sec" 1)
438 (cons "second" 1)
439 (cons "min" 60)
440 (cons "minute" 60)
441 (cons "hour" (* 60 60))
442 (cons "day" (* 24 60 60))
443 (cons "week" (* 7 24 60 60))
444 (cons "fortnight" (* 14 24 60 60))
445 (cons "month" (* 30 24 60 60)) ; Approximation
446 (cons "year" (* 365.25 24 60 60)) ; Approximation
447 )
448 "Alist mapping temporal words to durations in seconds")
449
450 (defun timer-duration (string)
451 "Return number of seconds specified by STRING, or nil if parsing fails."
452 (let ((secs 0)
453 (start 0)
454 (case-fold-search t))
455 (while (string-match
456 "[ \t]*\\([0-9.]+\\)?[ \t]*\\([a-z]+[a-rt-z]\\)s?[ \t]*"
457 string start)
458 (let ((count (if (match-beginning 1)
459 (string-to-number (match-string 1 string))
460 1))
461 (itemsize (cdr (assoc (match-string 2 string)
462 timer-duration-words))))
463 (if itemsize
464 (setq start (match-end 0)
465 secs (+ secs (* count itemsize)))
466 (setq secs nil
467 start (length string)))))
468 (if (= start (length string))
469 secs
470 (if (string-match "\\`[0-9.]+\\'" string)
471 (string-to-number string)))))
472 \f
473 (provide 'timer)
474
475 ;;; timer.el ends here