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