Merge branch 'maint'
[org-mode.git] / lisp / org-timer.el
blob5acf526f183121dd3ee470e573b6e25abae1a643
1 ;;; org-timer.el --- Timer code for Org mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2008-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file implements two types of timers for Org buffers:
29 ;; - A relative timer that counts up (from 0 or a specified offset)
30 ;; - A countdown timer that counts down from a specified time
32 ;; The relative and countdown timers differ in their entry points.
33 ;; Use `org-timer' or `org-timer-start' to start the relative timer,
34 ;; and `org-timer-set-timer' to start the countdown timer.
36 ;;; Code:
38 (require 'cl-lib)
39 (require 'org-clock)
41 (declare-function org-agenda-error "org-agenda" ())
43 (defvar org-timer-start-time nil
44 "t=0 for the running timer.")
46 (defvar org-timer-pause-time nil
47 "Time when the timer was paused.")
49 (defvar org-timer-countdown-timer nil
50 "Current countdown timer.
51 This is a timer object if there is an active countdown timer,
52 `paused' if there is a paused countdown timer, and nil
53 otherwise.")
55 (defvar org-timer-countdown-timer-title nil
56 "Title for notification displayed when a countdown finishes.")
58 (defconst org-timer-re "\\([-+]?[0-9]+\\):\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)"
59 "Regular expression used to match timer stamps.")
61 (defcustom org-timer-format "%s "
62 "The format to insert the time of the timer.
63 This format must contain one instance of \"%s\" which will be replaced by
64 the value of the timer."
65 :group 'org-time
66 :type 'string)
68 (defcustom org-timer-default-timer "0"
69 "The default timer when a timer is set, in minutes or hh:mm:ss format.
70 When 0, the user is prompted for a value."
71 :group 'org-time
72 :version "26.1"
73 :package-version '(Org . "8.3")
74 :type 'string)
76 (defcustom org-timer-display 'mode-line
77 "Define where running timer is displayed, if at all.
78 When a timer is running, Org can display it in the mode line
79 and/or frame title. Allowed values are:
81 both displays in both mode line and frame title
82 mode-line displays only in mode line (default)
83 frame-title displays only in frame title
84 nil current timer is not displayed"
85 :group 'org-time
86 :type '(choice
87 (const :tag "Mode line" mode-line)
88 (const :tag "Frame title" frame-title)
89 (const :tag "Both" both)
90 (const :tag "None" nil)))
92 (defvar org-timer-start-hook nil
93 "Hook run after relative timer is started.")
95 (defvar org-timer-stop-hook nil
96 "Hook run before relative or countdown timer is stopped.")
98 (defvar org-timer-pause-hook nil
99 "Hook run before relative or countdown timer is paused.")
101 (defvar org-timer-continue-hook nil
102 "Hook run after relative or countdown timer is continued.")
104 (defvar org-timer-set-hook nil
105 "Hook run after countdown timer is set.")
107 (defvar org-timer-done-hook nil
108 "Hook run after countdown timer reaches zero.")
110 ;;;###autoload
111 (defun org-timer-start (&optional offset)
112 "Set the starting time for the relative timer to now.
113 When called with prefix argument OFFSET, prompt the user for an offset time,
114 with the default taken from a timer stamp at point, if any.
115 If OFFSET is a string or an integer, it is directly taken to be the offset
116 without user interaction.
117 When called with a double prefix arg, all timer strings in the active
118 region will be shifted by a specific amount. You will be prompted for
119 the amount, with the default to make the first timer string in
120 the region 0:00:00."
121 (interactive "P")
122 (cond
123 ((equal offset '(16))
124 (call-interactively 'org-timer-change-times-in-region))
125 (org-timer-countdown-timer
126 (user-error "Countdown timer is running. Cancel first"))
128 (let (delta def s)
129 (if (not offset)
130 (setq org-timer-start-time (current-time))
131 (cond
132 ((integerp offset) (setq delta offset))
133 ((stringp offset) (setq delta (org-timer-hms-to-secs offset)))
135 (setq def (if (org-in-regexp org-timer-re)
136 (match-string 0)
137 "0:00:00")
138 s (read-string
139 (format "Restart timer with offset [%s]: " def)))
140 (unless (string-match "\\S-" s) (setq s def))
141 (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete s)))))
142 (setq org-timer-start-time
143 (seconds-to-time
144 ;; Pass `current-time' result to `float-time' (instead
145 ;; of calling without arguments) so that only
146 ;; `current-time' has to be overridden in tests.
147 (- (float-time (current-time)) delta))))
148 (setq org-timer-pause-time nil)
149 (org-timer-set-mode-line 'on)
150 (message "Timer start time set to %s, current value is %s"
151 (format-time-string "%T" org-timer-start-time)
152 (org-timer-secs-to-hms (or delta 0)))
153 (run-hooks 'org-timer-start-hook)))))
155 (defun org-timer-pause-or-continue (&optional stop)
156 "Pause or continue the relative or countdown timer.
157 With prefix arg STOP, stop it entirely."
158 (interactive "P")
159 (cond
160 (stop (org-timer-stop))
161 ((not org-timer-start-time) (error "No timer is running"))
162 (org-timer-pause-time
163 (let ((start-secs (float-time org-timer-start-time))
164 (pause-secs (float-time org-timer-pause-time)))
165 (if org-timer-countdown-timer
166 (let ((new-secs (- start-secs pause-secs)))
167 (setq org-timer-countdown-timer
168 (org-timer--run-countdown-timer
169 new-secs org-timer-countdown-timer-title))
170 (setq org-timer-start-time
171 (time-add (current-time) (seconds-to-time new-secs))))
172 (setq org-timer-start-time
173 ;; Pass `current-time' result to `float-time' (instead
174 ;; of calling without arguments) so that only
175 ;; `current-time' has to be overridden in tests.
176 (seconds-to-time (- (float-time (current-time))
177 (- pause-secs start-secs)))))
178 (setq org-timer-pause-time nil)
179 (org-timer-set-mode-line 'on)
180 (run-hooks 'org-timer-continue-hook)
181 (message "Timer continues at %s" (org-timer-value-string))))
183 ;; pause timer
184 (when org-timer-countdown-timer
185 (cancel-timer org-timer-countdown-timer)
186 (setq org-timer-countdown-timer 'paused))
187 (run-hooks 'org-timer-pause-hook)
188 (setq org-timer-pause-time (current-time))
189 (org-timer-set-mode-line 'paused)
190 (message "Timer paused at %s" (org-timer-value-string)))))
192 (defun org-timer-stop ()
193 "Stop the relative or countdown timer."
194 (interactive)
195 (unless org-timer-start-time
196 (user-error "No timer running"))
197 (when (timerp org-timer-countdown-timer)
198 (cancel-timer org-timer-countdown-timer))
199 (run-hooks 'org-timer-stop-hook)
200 (setq org-timer-start-time nil
201 org-timer-pause-time nil
202 org-timer-countdown-timer nil)
203 (org-timer-set-mode-line 'off)
204 (message "Timer stopped"))
206 ;;;###autoload
207 (defun org-timer (&optional restart no-insert)
208 "Insert a H:MM:SS string from the timer into the buffer.
209 The first time this command is used, the timer is started.
211 When used with a `\\[universal-argument]' prefix, force restarting the timer.
213 When used with a `\\[universal-argument] \\[universal-argument]' \
214 prefix, change all the timer strings
215 in the region by a fixed amount. This can be used to re-calibrate
216 a timer that was not started at the correct moment.
218 If NO-INSERT is non-nil, return the string instead of inserting
219 it in the buffer."
220 (interactive "P")
221 (if (equal restart '(16))
222 (org-timer-start restart)
223 (when (or (equal restart '(4)) (not org-timer-start-time))
224 (org-timer-start))
225 (if no-insert
226 (org-timer-value-string)
227 (insert (org-timer-value-string)))))
229 (defun org-timer-value-string ()
230 "Set the timer string."
231 (format org-timer-format
232 (org-timer-secs-to-hms
233 (abs (floor (org-timer-seconds))))))
235 (defun org-timer-seconds ()
236 ;; Pass `current-time' result to `float-time' (instead of calling
237 ;; without arguments) so that only `current-time' has to be
238 ;; overridden in tests.
239 (if org-timer-countdown-timer
240 (- (float-time org-timer-start-time)
241 (float-time (or org-timer-pause-time (current-time))))
242 (- (float-time (or org-timer-pause-time (current-time)))
243 (float-time org-timer-start-time))))
245 ;;;###autoload
246 (defun org-timer-change-times-in-region (beg end delta)
247 "Change all h:mm:ss time in region by a DELTA."
248 (interactive
249 "r\nsEnter time difference like \"-1:08:26\". Default is first time to zero: ")
250 (let ((re "[-+]?[0-9]+:[0-9]\\{2\\}:[0-9]\\{2\\}") p)
251 (unless (string-match "\\S-" delta)
252 (save-excursion
253 (goto-char beg)
254 (when (re-search-forward re end t)
255 (setq delta (match-string 0))
256 (if (equal (string-to-char delta) ?-)
257 (setq delta (substring delta 1))
258 (setq delta (concat "-" delta))))))
259 (setq delta (org-timer-hms-to-secs (org-timer-fix-incomplete delta)))
260 (when (= delta 0) (error "No change"))
261 (save-excursion
262 (goto-char end)
263 (while (re-search-backward re beg t)
264 (setq p (point))
265 (replace-match
266 (save-match-data
267 (org-timer-secs-to-hms (+ (org-timer-hms-to-secs (match-string 0)) delta)))
268 t t)
269 (goto-char p)))))
271 ;;;###autoload
272 (defun org-timer-item (&optional arg)
273 "Insert a description-type item with the current timer value."
274 (interactive "P")
275 (let ((itemp (org-in-item-p)) (pos (point)))
276 (cond
277 ;; In a timer list, insert with `org-list-insert-item',
278 ;; then fix the list.
279 ((and itemp (goto-char itemp) (org-at-item-timer-p))
280 (let* ((struct (org-list-struct))
281 (prevs (org-list-prevs-alist struct))
282 (s (concat (org-timer (when arg '(4)) t) ":: ")))
283 (setq struct (org-list-insert-item pos struct prevs nil s))
284 (org-list-write-struct struct (org-list-parents-alist struct))
285 (looking-at org-list-full-item-re)
286 (goto-char (match-end 0))))
287 ;; In a list of another type, don't break anything: throw an error.
288 (itemp (goto-char pos) (error "This is not a timer list"))
289 ;; Else, start a new list.
291 (beginning-of-line)
292 (org-indent-line)
293 (insert "- ")
294 (org-timer (when arg '(4)))
295 (insert ":: ")))))
297 (defun org-timer-fix-incomplete (hms)
298 "If hms is a H:MM:SS string with missing hour or hour and minute, fix it."
299 (if (string-match "\\(?:\\([0-9]+:\\)?\\([0-9]+:\\)\\)?\\([0-9]+\\)" hms)
300 (replace-match
301 (format "%d:%02d:%02d"
302 (if (match-end 1) (string-to-number (match-string 1 hms)) 0)
303 (if (match-end 2) (string-to-number (match-string 2 hms)) 0)
304 (string-to-number (match-string 3 hms)))
305 t t hms)
306 (error "Cannot parse HMS string \"%s\"" hms)))
308 (defun org-timer-hms-to-secs (hms)
309 "Convert h:mm:ss string to an integer time.
310 If the string starts with a minus sign, the integer will be negative."
311 (if (not (string-match
312 "\\([-+]?[0-9]+\\):\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)"
313 hms))
315 (let* ((h (string-to-number (match-string 1 hms)))
316 (m (string-to-number (match-string 2 hms)))
317 (s (string-to-number (match-string 3 hms)))
318 (sign (equal (substring (match-string 1 hms) 0 1) "-")))
319 (setq h (abs h))
320 (* (if sign -1 1) (+ s (* 60 (+ m (* 60 h))))))))
322 (defun org-timer-secs-to-hms (s)
323 "Convert integer S into h:mm:ss.
324 If the integer is negative, the string will start with \"-\"."
325 (let (sign m h)
326 (setq sign (if (< s 0) "-" "")
327 s (abs s)
328 m (/ s 60) s (- s (* 60 m))
329 h (/ m 60) m (- m (* 60 h)))
330 (format "%s%d:%02d:%02d" sign h m s)))
332 (defvar org-timer-mode-line-timer nil)
333 (defvar org-timer-mode-line-string nil)
335 (defun org-timer-set-mode-line (value)
336 "Set the mode-line display for relative or countdown timer.
337 VALUE can be `on', `off', or `paused'."
338 (when (or (eq org-timer-display 'mode-line)
339 (eq org-timer-display 'both))
340 (or global-mode-string (setq global-mode-string '("")))
341 (or (memq 'org-timer-mode-line-string global-mode-string)
342 (setq global-mode-string
343 (append global-mode-string '(org-timer-mode-line-string)))))
344 (when (or (eq org-timer-display 'frame-title)
345 (eq org-timer-display 'both))
346 (or (memq 'org-timer-mode-line-string frame-title-format)
347 (setq frame-title-format
348 (append frame-title-format '(org-timer-mode-line-string)))))
349 (cl-case value
350 (off
351 (when org-timer-mode-line-timer
352 (cancel-timer org-timer-mode-line-timer)
353 (setq org-timer-mode-line-timer nil))
354 (when (or (eq org-timer-display 'mode-line)
355 (eq org-timer-display 'both))
356 (setq global-mode-string
357 (delq 'org-timer-mode-line-string global-mode-string)))
358 (when (or (eq org-timer-display 'frame-title)
359 (eq org-timer-display 'both))
360 (setq frame-title-format
361 (delq 'org-timer-mode-line-string frame-title-format)))
362 (force-mode-line-update))
363 (paused
364 (when org-timer-mode-line-timer
365 (cancel-timer org-timer-mode-line-timer)
366 (setq org-timer-mode-line-timer nil)))
368 (when (or (eq org-timer-display 'mode-line)
369 (eq org-timer-display 'both))
370 (or global-mode-string (setq global-mode-string '("")))
371 (or (memq 'org-timer-mode-line-string global-mode-string)
372 (setq global-mode-string
373 (append global-mode-string '(org-timer-mode-line-string)))))
374 (when (or (eq org-timer-display 'frame-title)
375 (eq org-timer-display 'both))
376 (or (memq 'org-timer-mode-line-string frame-title-format)
377 (setq frame-title-format
378 (append frame-title-format '(org-timer-mode-line-string)))))
379 (org-timer-update-mode-line)
380 (when org-timer-mode-line-timer
381 (cancel-timer org-timer-mode-line-timer)
382 (setq org-timer-mode-line-timer nil))
383 (when org-timer-display
384 (setq org-timer-mode-line-timer
385 (run-with-timer 1 1 'org-timer-update-mode-line))))))
387 (defun org-timer-update-mode-line ()
388 "Update the timer time in the mode line."
389 (if org-timer-pause-time
391 (setq org-timer-mode-line-string
392 (concat " <" (substring (org-timer-value-string) 0 -1) ">"))
393 (force-mode-line-update)))
395 (defun org-timer-show-remaining-time ()
396 "Display the remaining time before the timer ends."
397 (interactive)
398 (require 'time)
399 (if (not org-timer-countdown-timer)
400 (message "No timer set")
401 (let* ((rtime (decode-time
402 (time-subtract (timer--time org-timer-countdown-timer)
403 (current-time))))
404 (rsecs (nth 0 rtime))
405 (rmins (nth 1 rtime)))
406 (message "%d minute(s) %d seconds left before next time out"
407 rmins rsecs))))
409 ;;;###autoload
410 (defun org-timer-set-timer (&optional opt)
411 "Prompt for a duration in minutes or hh:mm:ss and set a timer.
413 If `org-timer-default-timer' is not \"0\", suggest this value as
414 the default duration for the timer. If a timer is already set,
415 prompt the user if she wants to replace it.
417 Called with a numeric prefix argument, use this numeric value as
418 the duration of the timer in minutes.
420 Called with a `C-u' prefix arguments, use `org-timer-default-timer'
421 without prompting the user for a duration.
423 With two `C-u' prefix arguments, use `org-timer-default-timer'
424 without prompting the user for a duration and automatically
425 replace any running timer.
427 By default, the timer duration will be set to the number of
428 minutes in the Effort property, if any. You can ignore this by
429 using three `C-u' prefix arguments."
430 (interactive "P")
431 (when (and org-timer-start-time
432 (not org-timer-countdown-timer))
433 (user-error "Relative timer is running. Stop first"))
434 (let* ((default-timer
435 ;; `org-timer-default-timer' used to be a number, don't choke:
436 (if (numberp org-timer-default-timer)
437 (number-to-string org-timer-default-timer)
438 org-timer-default-timer))
439 (effort-minutes (ignore-errors (floor (org-get-at-eol 'effort-minutes 1))))
440 (minutes (or (and (numberp opt) (number-to-string opt))
441 (and (not (equal opt '(64)))
442 effort-minutes
443 (number-to-string effort-minutes))
444 (and (consp opt) default-timer)
445 (and (stringp opt) opt)
446 (read-from-minibuffer
447 "How much time left? (minutes or h:mm:ss) "
448 (and (not (string-equal default-timer "0")) default-timer)))))
449 (when (string-match "\\`[0-9]+\\'" minutes)
450 (setq minutes (concat minutes ":00")))
451 (if (not (string-match "[0-9]+" minutes))
452 (org-timer-show-remaining-time)
453 (let ((secs (org-timer-hms-to-secs (org-timer-fix-incomplete minutes))))
454 (if (and org-timer-countdown-timer
455 (not (or (equal opt '(16))
456 (y-or-n-p "Replace current timer? "))))
457 (message "No timer set")
458 (when (timerp org-timer-countdown-timer)
459 (cancel-timer org-timer-countdown-timer))
460 (setq org-timer-countdown-timer-title
461 (org-timer--get-timer-title))
462 (setq org-timer-countdown-timer
463 (org-timer--run-countdown-timer
464 secs org-timer-countdown-timer-title))
465 (run-hooks 'org-timer-set-hook)
466 (setq org-timer-start-time
467 (time-add (current-time) (seconds-to-time secs)))
468 (setq org-timer-pause-time nil)
469 (org-timer-set-mode-line 'on))))))
471 (defun org-timer--run-countdown-timer (secs title)
472 "Start countdown timer that will last SECS.
473 TITLE will be appended to the notification message displayed when
474 time is up."
475 (let ((msg (format "%s: time out" title)))
476 (run-with-timer
477 secs nil `(lambda ()
478 (setq org-timer-countdown-timer nil
479 org-timer-start-time nil)
480 (org-notify ,msg ,org-clock-sound)
481 (org-timer-set-mode-line 'off)
482 (run-hooks 'org-timer-done-hook)))))
484 (defun org-timer--get-timer-title ()
485 "Construct timer title from heading or file name of Org buffer."
486 (cond
487 ((derived-mode-p 'org-agenda-mode)
488 (let* ((marker (or (get-text-property (point) 'org-marker)
489 (org-agenda-error)))
490 (hdmarker (or (get-text-property (point) 'org-hd-marker)
491 marker)))
492 (with-current-buffer (marker-buffer marker)
493 (org-with-wide-buffer
494 (goto-char hdmarker)
495 (org-show-entry)
496 (or (ignore-errors (org-get-heading))
497 (buffer-name (buffer-base-buffer)))))))
498 ((derived-mode-p 'org-mode)
499 (or (ignore-errors (org-get-heading))
500 (buffer-name (buffer-base-buffer))))
501 (t (error "Not in an Org buffer"))))
503 (provide 'org-timer)
505 ;; Local variables:
506 ;; generated-autoload-file: "org-loaddefs.el"
507 ;; End:
509 ;;; org-timer.el ends here