Merge branch 'maint'
[org-mode.git] / lisp / org-clock.el
blob7d2aa8d9bc7adb848b8aaf809381b13137e982ed
1 ;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-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 <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the time clocking code for Org mode
29 ;;; Code:
31 (require 'cl-lib)
32 (require 'org)
34 (declare-function calendar-iso-to-absolute "cal-iso" (date))
35 (declare-function notifications-notify "notifications" (&rest params))
36 (declare-function org-element-property "org-element" (property element))
37 (declare-function org-element-type "org-element" (element))
38 (declare-function org-table-goto-line "org-table" (n))
40 (defvar org-frame-title-format-backup frame-title-format)
41 (defvar org-time-stamp-formats)
44 (defgroup org-clock nil
45 "Options concerning clocking working time in Org mode."
46 :tag "Org Clock"
47 :group 'org-progress)
49 (defcustom org-clock-into-drawer t
50 "Non-nil when clocking info should be wrapped into a drawer.
52 When non-nil, clocking info will be inserted into the same drawer
53 as log notes (see variable `org-log-into-drawer'), if it exists,
54 or \"LOGBOOK\" otherwise. If necessary, the drawer will be
55 created.
57 When an integer, the drawer is created only when the number of
58 clocking entries in an item reaches or exceeds this value.
60 When a string, it becomes the name of the drawer, ignoring the
61 log notes drawer altogether.
63 Do not check directly this variable in a Lisp program. Call
64 function `org-clock-into-drawer' instead."
65 :group 'org-todo
66 :group 'org-clock
67 :version "26.1"
68 :package-version '(Org . "8.3")
69 :type '(choice
70 (const :tag "Always" t)
71 (const :tag "Only when drawer exists" nil)
72 (integer :tag "When at least N clock entries")
73 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
74 (string :tag "Into Drawer named...")))
76 (defun org-clock-into-drawer ()
77 "Value of `org-clock-into-drawer'. but let properties overrule.
79 If the current entry has or inherits a CLOCK_INTO_DRAWER
80 property, it will be used instead of the default value.
82 Return value is either a string, an integer, or nil."
83 (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit t)))
84 (cond ((equal p "nil") nil)
85 ((equal p "t") (or (org-log-into-drawer) "LOGBOOK"))
86 ((org-string-nw-p p)
87 (if (string-match-p "\\`[0-9]+\\'" p) (string-to-number p) p))
88 ((org-string-nw-p org-clock-into-drawer))
89 ((integerp org-clock-into-drawer) org-clock-into-drawer)
90 ((not org-clock-into-drawer) nil)
91 ((org-log-into-drawer))
92 (t "LOGBOOK"))))
94 (defcustom org-clock-out-when-done t
95 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
96 \\<org-mode-map>\
97 DONE here means any DONE-like state.
98 A nil value means clock will keep running until stopped explicitly with
99 `\\[org-clock-out]', or until the clock is started in a different item.
100 Instead of t, this can also be a list of TODO states that should trigger
101 clocking out."
102 :group 'org-clock
103 :type '(choice
104 (const :tag "No" nil)
105 (const :tag "Yes, when done" t)
106 (repeat :tag "State list"
107 (string :tag "TODO keyword"))))
109 (defcustom org-clock-rounding-minutes 0
110 "Rounding minutes when clocking in or out.
111 The default value is 0 so that no rounding is done.
112 When set to a non-integer value, use the car of
113 `org-time-stamp-rounding-minutes', like for setting a time-stamp.
115 E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
116 and you clock in: then the clock starts at 14:45. If you clock
117 out within the next 5 minutes, the clock line will be removed;
118 if you clock out 8 minutes after your clocked in, the clock
119 out time will be 14:50."
120 :group 'org-clock
121 :version "24.4"
122 :package-version '(Org . "8.0")
123 :type '(choice
124 (integer :tag "Minutes (0 for no rounding)")
125 (symbol :tag "Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp)))
127 (defcustom org-clock-out-remove-zero-time-clocks nil
128 "Non-nil means remove the clock line when the resulting time is zero."
129 :group 'org-clock
130 :type 'boolean)
132 (defcustom org-clock-in-switch-to-state nil
133 "Set task to a special todo state while clocking it.
134 The value should be the state to which the entry should be
135 switched. If the value is a function, it must take one
136 parameter (the current TODO state of the item) and return the
137 state to switch it to."
138 :group 'org-clock
139 :group 'org-todo
140 :type '(choice
141 (const :tag "Don't force a state" nil)
142 (string :tag "State")
143 (symbol :tag "Function")))
145 (defcustom org-clock-out-switch-to-state nil
146 "Set task to a special todo state after clocking out.
147 The value should be the state to which the entry should be
148 switched. If the value is a function, it must take one
149 parameter (the current TODO state of the item) and return the
150 state to switch it to."
151 :group 'org-clock
152 :group 'org-todo
153 :type '(choice
154 (const :tag "Don't force a state" nil)
155 (string :tag "State")
156 (symbol :tag "Function")))
158 (defcustom org-clock-history-length 5
159 "Number of clock tasks to remember in history."
160 :group 'org-clock
161 :type 'integer)
163 (defcustom org-clock-goto-may-find-recent-task t
164 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
165 :group 'org-clock
166 :type 'boolean)
168 (defcustom org-clock-heading-function nil
169 "When non-nil, should be a function to create `org-clock-heading'.
170 This is the string shown in the mode line when a clock is running.
171 The function is called with point at the beginning of the headline."
172 :group 'org-clock
173 :type '(choice (const nil) (function)))
175 (defcustom org-clock-string-limit 0
176 "Maximum length of clock strings in the mode line. 0 means no limit."
177 :group 'org-clock
178 :type 'integer)
180 (defcustom org-clock-in-resume nil
181 "If non-nil, resume clock when clocking into task with open clock.
182 When clocking into a task with a clock entry which has not been closed,
183 the clock can be resumed from that point."
184 :group 'org-clock
185 :type 'boolean)
187 (defcustom org-clock-persist nil
188 "When non-nil, save the running clock when Emacs is closed.
189 The clock is resumed when Emacs restarts.
190 When this is t, both the running clock, and the entire clock
191 history are saved. When this is the symbol `clock', only the
192 running clock is saved. When this is the symbol `history', only
193 the clock history is saved.
195 When Emacs restarts with saved clock information, the file containing
196 the running clock as well as all files mentioned in the clock history
197 will be visited.
199 All this depends on running `org-clock-persistence-insinuate' in your
200 Emacs initialization file."
201 :group 'org-clock
202 :type '(choice
203 (const :tag "Just the running clock" clock)
204 (const :tag "Just the history" history)
205 (const :tag "Clock and history" t)
206 (const :tag "No persistence" nil)))
208 (defcustom org-clock-persist-file (convert-standard-filename
209 (concat user-emacs-directory "org-clock-save.el"))
210 "File to save clock data to."
211 :group 'org-clock
212 :type 'string)
214 (defcustom org-clock-persist-query-save nil
215 "When non-nil, ask before saving the current clock on exit."
216 :group 'org-clock
217 :type 'boolean)
219 (defcustom org-clock-persist-query-resume t
220 "When non-nil, ask before resuming any stored clock during load."
221 :group 'org-clock
222 :type 'boolean)
224 (defcustom org-clock-sound nil
225 "Sound to use for notifications.
226 Possible values are:
228 nil No sound played
229 t Standard Emacs beep
230 file name Play this sound file, fall back to beep"
231 :group 'org-clock
232 :type '(choice
233 (const :tag "No sound" nil)
234 (const :tag "Standard beep" t)
235 (file :tag "Play sound file")))
237 (defcustom org-clock-mode-line-total 'auto
238 "Default setting for the time included for the mode line clock.
239 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
240 Allowed values are:
242 current Only the time in the current instance of the clock
243 today All time clocked into this task today
244 repeat All time clocked into this task since last repeat
245 all All time ever recorded for this task
246 auto Automatically, either `all', or `repeat' for repeating tasks"
247 :group 'org-clock
248 :type '(choice
249 (const :tag "Current clock" current)
250 (const :tag "Today's task time" today)
251 (const :tag "Since last repeat" repeat)
252 (const :tag "All task time" all)
253 (const :tag "Automatically, `all' or since `repeat'" auto)))
255 (defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
256 (defcustom org-clock-task-overrun-text nil
257 "Extra mode line text to indicate that the clock is overrun.
258 The can be nil to indicate that instead of adding text, the clock time
259 should get a different face (`org-mode-line-clock-overrun').
260 When this is a string, it is prepended to the clock string as an indication,
261 also using the face `org-mode-line-clock-overrun'."
262 :group 'org-clock
263 :version "24.1"
264 :type '(choice
265 (const :tag "Just mark the time string" nil)
266 (string :tag "Text to prepend")))
268 (defcustom org-show-notification-handler nil
269 "Function or program to send notification with.
270 The function or program will be called with the notification
271 string as argument."
272 :group 'org-clock
273 :type '(choice
274 (const nil)
275 (string :tag "Program")
276 (function :tag "Function")))
278 (defgroup org-clocktable nil
279 "Options concerning the clock table in Org mode."
280 :tag "Org Clock Table"
281 :group 'org-clock)
283 (defcustom org-clocktable-defaults
284 (list
285 :maxlevel 2
286 :lang (or (bound-and-true-p org-export-default-language) "en")
287 :scope 'file
288 :block nil
289 :wstart 1
290 :mstart 1
291 :tstart nil
292 :tend nil
293 :step nil
294 :stepskip0 nil
295 :fileskip0 nil
296 :tags nil
297 :emphasize nil
298 :link nil
299 :narrow '40!
300 :indent t
301 :formula nil
302 :timestamp nil
303 :level nil
304 :tcolumns nil
305 :formatter nil)
306 "Default properties for clock tables."
307 :group 'org-clock
308 :version "24.1"
309 :type 'plist)
311 (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
312 "Function to turn clocking data into a table.
313 For more information, see `org-clocktable-write-default'."
314 :group 'org-clocktable
315 :version "24.1"
316 :type 'function)
318 ;; FIXME: translate es and nl last string "Clock summary at"
319 (defcustom org-clock-clocktable-language-setup
320 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
321 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
322 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à")
323 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
324 ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT"
325 "Gesamtdauer" "Dateizeit" "Erstellt am"))
326 "Terms used in clocktable, translated to different languages."
327 :group 'org-clocktable
328 :version "24.1"
329 :type 'alist)
331 (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
332 "Default properties for new clocktables.
333 These will be inserted into the BEGIN line, to make it easy for users to
334 play with them."
335 :group 'org-clocktable
336 :type 'plist)
338 (defcustom org-clock-idle-time nil
339 "When non-nil, resolve open clocks if the user is idle more than X minutes."
340 :group 'org-clock
341 :type '(choice
342 (const :tag "Never" nil)
343 (integer :tag "After N minutes")))
345 (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
346 "When to automatically resolve open clocks found in Org buffers."
347 :group 'org-clock
348 :type '(choice
349 (const :tag "Never" nil)
350 (const :tag "Always" t)
351 (const :tag "When no clock is running" when-no-clock-is-running)))
353 (defcustom org-clock-report-include-clocking-task nil
354 "When non-nil, include the current clocking task time in clock reports."
355 :group 'org-clock
356 :version "24.1"
357 :type 'boolean)
359 (defcustom org-clock-resolve-expert nil
360 "Non-nil means do not show the splash buffer with the clock resolver."
361 :group 'org-clock
362 :version "24.1"
363 :type 'boolean)
365 (defcustom org-clock-continuously nil
366 "Non-nil means to start clocking from the last clock-out time, if any."
367 :type 'boolean
368 :version "24.1"
369 :group 'org-clock)
371 (defcustom org-clock-total-time-cell-format "*%s*"
372 "Format string for the total time cells."
373 :group 'org-clock
374 :version "24.1"
375 :type 'string)
377 (defcustom org-clock-file-time-cell-format "*%s*"
378 "Format string for the file time cells."
379 :group 'org-clock
380 :version "24.1"
381 :type 'string)
383 (defcustom org-clock-clocked-in-display 'mode-line
384 "When clocked in for a task, Org can display the current
385 task and accumulated time in the mode line and/or frame title.
386 Allowed values are:
388 both displays in both mode line and frame title
389 mode-line displays only in mode line (default)
390 frame-title displays only in frame title
391 nil current clock is not displayed"
392 :group 'org-clock
393 :type '(choice
394 (const :tag "Mode line" mode-line)
395 (const :tag "Frame title" frame-title)
396 (const :tag "Both" both)
397 (const :tag "None" nil)))
399 (defcustom org-clock-frame-title-format '(t org-mode-line-string)
400 "The value for `frame-title-format' when clocking in.
402 When `org-clock-clocked-in-display' is set to `frame-title'
403 or `both', clocking in will replace `frame-title-format' with
404 this value. Clocking out will restore `frame-title-format'.
406 `org-frame-title-string' is a format string using the same
407 specifications than `frame-title-format', which see."
408 :version "24.1"
409 :group 'org-clock
410 :type 'sexp)
412 (defcustom org-clock-x11idle-program-name "x11idle"
413 "Name of the program which prints X11 idle time in milliseconds.
415 You can find x11idle.c in the contrib/scripts directory of the
416 Org git distribution. Or, you can do:
418 sudo apt-get install xprintidle
420 if you are using Debian."
421 :group 'org-clock
422 :version "24.4"
423 :package-version '(Org . "8.0")
424 :type 'string)
426 (defcustom org-clock-goto-before-context 2
427 "Number of lines of context to display before currently clocked-in entry.
428 This applies when using `org-clock-goto'."
429 :group 'org-clock
430 :type 'integer)
432 (defcustom org-clock-display-default-range 'thisyear
433 "Default range when displaying clocks with `org-clock-display'."
434 :group 'org-clock
435 :type '(choice (const today)
436 (const yesterday)
437 (const thisweek)
438 (const lastweek)
439 (const thismonth)
440 (const lastmonth)
441 (const thisyear)
442 (const lastyear)
443 (const untilnow)
444 (const :tag "Select range interactively" interactive)))
446 (defvar org-clock-in-prepare-hook nil
447 "Hook run when preparing the clock.
448 This hook is run before anything happens to the task that
449 you want to clock in. For example, you can use this hook
450 to add an effort property.")
451 (defvar org-clock-in-hook nil
452 "Hook run when starting the clock.")
453 (defvar org-clock-out-hook nil
454 "Hook run when stopping the current clock.")
456 (defvar org-clock-cancel-hook nil
457 "Hook run when canceling the current clock.")
458 (defvar org-clock-goto-hook nil
459 "Hook run when selecting the currently clocked-in entry.")
460 (defvar org-clock-has-been-used nil
461 "Has the clock been used during the current Emacs session?")
463 (defvar org-clock-stored-history nil
464 "Clock history, populated by `org-clock-load'")
465 (defvar org-clock-stored-resume-clock nil
466 "Clock to resume, saved by `org-clock-load'")
468 (defconst org-clock--oldest-date
469 (let* ((dichotomy
470 (lambda (min max pred)
471 (if (funcall pred min) min
472 (cl-incf min)
473 (while (> (- max min) 1)
474 (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
475 (if (funcall pred mean) (setq max mean) (setq min mean)))))
476 max))
477 (high
478 (funcall dichotomy
479 most-negative-fixnum
481 (lambda (m) (ignore-errors (decode-time (list m 0))))))
482 (low
483 (funcall dichotomy
484 most-negative-fixnum
486 (lambda (m) (ignore-errors (decode-time (list high m)))))))
487 (list high low))
488 "Internal time for oldest date representable on the system.")
490 ;;; The clock for measuring work time.
492 (defvar org-mode-line-string "")
493 (put 'org-mode-line-string 'risky-local-variable t)
495 (defvar org-clock-mode-line-timer nil)
496 (defvar org-clock-idle-timer nil)
497 (defvar org-clock-heading) ; defined in org.el
498 (defvar org-clock-start-time "")
500 (defvar org-clock-leftover-time nil
501 "If non-nil, user canceled a clock; this is when leftover time started.")
503 (defvar org-clock-effort ""
504 "Effort estimate of the currently clocking task.")
506 (defvar org-clock-total-time nil
507 "Holds total time, spent previously on currently clocked item.
508 This does not include the time in the currently running clock.")
510 (defvar org-clock-history nil
511 "List of marker pointing to recent clocked tasks.")
513 (defvar org-clock-default-task (make-marker)
514 "Marker pointing to the default task that should clock time.
515 The clock can be made to switch to this task after clocking out
516 of a different task.")
518 (defvar org-clock-interrupted-task (make-marker)
519 "Marker pointing to the task that has been interrupted by the current clock.")
521 (defvar org-clock-mode-line-map (make-sparse-keymap))
522 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
523 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
525 (defun org-clock--translate (s language)
526 "Translate string S into using string LANGUAGE.
527 Assume S in the English term to translate. Return S as-is if it
528 cannot be translated."
529 (or (nth (pcase s
530 ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5)
531 ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9))
532 (assoc-string language org-clock-clocktable-language-setup t))
535 (defun org-clock-menu ()
536 (interactive)
537 (popup-menu
538 '("Clock"
539 ["Clock out" org-clock-out t]
540 ["Change effort estimate" org-clock-modify-effort-estimate t]
541 ["Go to clock entry" org-clock-goto t]
542 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
544 (defun org-clock-history-push (&optional pos buffer)
545 "Push a marker to the clock history."
546 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
547 (let ((m (move-marker (make-marker)
548 (or pos (point)) (org-base-buffer
549 (or buffer (current-buffer)))))
550 n l)
551 (while (setq n (member m org-clock-history))
552 (move-marker (car n) nil))
553 (setq org-clock-history
554 (delq nil
555 (mapcar (lambda (x) (if (marker-buffer x) x nil))
556 org-clock-history)))
557 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
558 (setq org-clock-history
559 (nreverse
560 (nthcdr (- l org-clock-history-length -1)
561 (nreverse org-clock-history)))))
562 (push m org-clock-history)))
564 (defun org-clock-save-markers-for-cut-and-paste (beg end)
565 "Save relative positions of markers in region."
566 (org-check-and-save-marker org-clock-marker beg end)
567 (org-check-and-save-marker org-clock-hd-marker beg end)
568 (org-check-and-save-marker org-clock-default-task beg end)
569 (org-check-and-save-marker org-clock-interrupted-task beg end)
570 (dolist (m org-clock-history)
571 (org-check-and-save-marker m beg end)))
573 (defun org-clock-drawer-name ()
574 "Return clock drawer's name for current entry, or nil."
575 (let ((drawer (org-clock-into-drawer)))
576 (cond ((integerp drawer)
577 (let ((log-drawer (org-log-into-drawer)))
578 (if (stringp log-drawer) log-drawer "LOGBOOK")))
579 ((stringp drawer) drawer)
580 (t nil))))
582 (defun org-clocking-buffer ()
583 "Return the clocking buffer if we are currently clocking a task or nil."
584 (marker-buffer org-clock-marker))
586 (defun org-clocking-p ()
587 "Return t when clocking a task."
588 (not (equal (org-clocking-buffer) nil)))
590 (defvar org-clock-before-select-task-hook nil
591 "Hook called in task selection just before prompting the user.")
593 (defun org-clock-select-task (&optional prompt)
594 "Select a task that was recently associated with clocking."
595 (interactive)
596 (let (och chl sel-list rpl (i 0) s)
597 ;; Remove successive dups from the clock history to consider
598 (dolist (c org-clock-history)
599 (unless (equal c (car och)) (push c och)))
600 (setq och (reverse och) chl (length och))
601 (if (zerop chl)
602 (user-error "No recent clock")
603 (save-window-excursion
604 (org-switch-to-buffer-other-window
605 (get-buffer-create "*Clock Task Select*"))
606 (erase-buffer)
607 (when (marker-buffer org-clock-default-task)
608 (insert (org-add-props "Default Task\n" nil 'face 'bold))
609 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
610 (push s sel-list))
611 (when (marker-buffer org-clock-interrupted-task)
612 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
613 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
614 (push s sel-list))
615 (when (org-clocking-p)
616 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
617 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
618 (push s sel-list))
619 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
620 (dolist (m och)
621 (when (marker-buffer m)
622 (setq i (1+ i)
623 s (org-clock-insert-selection-line
624 (if (< i 10)
625 (+ i ?0)
626 (+ i (- ?A 10))) m))
627 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
628 (push s sel-list)))
629 (run-hooks 'org-clock-before-select-task-hook)
630 (goto-char (point-min))
631 ;; Set min-height relatively to circumvent a possible but in
632 ;; `fit-window-to-buffer'
633 (fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl)))
634 (message (or prompt "Select task for clocking:"))
635 (setq cursor-type nil rpl (read-char-exclusive))
636 (kill-buffer)
637 (cond
638 ((eq rpl ?q) nil)
639 ((eq rpl ?x) nil)
640 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
641 (t (user-error "Invalid task choice %c" rpl)))))))
643 (defun org-clock-insert-selection-line (i marker)
644 "Insert a line for the clock selection menu.
645 And return a cons cell with the selection character integer and the marker
646 pointing to it."
647 (when (marker-buffer marker)
648 (let (cat task heading prefix)
649 (with-current-buffer (org-base-buffer (marker-buffer marker))
650 (org-with-wide-buffer
651 (ignore-errors
652 (goto-char marker)
653 (setq cat (org-get-category)
654 heading (org-get-heading 'notags)
655 prefix (save-excursion
656 (org-back-to-heading t)
657 (looking-at org-outline-regexp)
658 (match-string 0))
659 task (substring
660 (org-fontify-like-in-org-mode
661 (concat prefix heading)
662 org-odd-levels-only)
663 (length prefix))))))
664 (when (and cat task)
665 (insert (format "[%c] %-12s %s\n" i cat task))
666 (cons i marker)))))
668 (defvar org-clock-task-overrun nil
669 "Internal flag indicating if the clock has overrun the planned time.")
670 (defvar org-clock-update-period 60
671 "Number of seconds between mode line clock string updates.")
673 (defun org-clock-get-clock-string ()
674 "Form a clock-string, that will be shown in the mode line.
675 If an effort estimate was defined for the current item, use
676 01:30/01:50 format (clocked/estimated).
677 If not, show simply the clocked time like 01:50."
678 (let ((clocked-time (org-clock-get-clocked-time)))
679 (if org-clock-effort
680 (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
681 (work-done-str
682 (propertize
683 (org-duration-from-minutes clocked-time)
684 'face (if (and org-clock-task-overrun (not org-clock-task-overrun-text))
685 'org-mode-line-clock-overrun 'org-mode-line-clock)))
686 (effort-str (org-duration-from-minutes effort-in-minutes))
687 (clockstr (propertize
688 (concat " [%s/" effort-str
689 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
690 'face 'org-mode-line-clock)))
691 (format clockstr work-done-str))
692 (propertize (concat " [" (org-duration-from-minutes clocked-time)
693 "]" (format " (%s)" org-clock-heading))
694 'face 'org-mode-line-clock))))
696 (defun org-clock-get-last-clock-out-time ()
697 "Get the last clock-out time for the current subtree."
698 (save-excursion
699 (let ((end (save-excursion (org-end-of-subtree))))
700 (when (re-search-forward (concat org-clock-string
701 ".*\\]--\\(\\[[^]]+\\]\\)") end t)
702 (org-time-string-to-time (match-string 1))))))
704 (defun org-clock-update-mode-line ()
705 (if org-clock-effort
706 (org-clock-notify-once-if-expired)
707 (setq org-clock-task-overrun nil))
708 (setq org-mode-line-string
709 (propertize
710 (let ((clock-string (org-clock-get-clock-string))
711 (help-text "Org mode clock is running.\nmouse-1 shows a \
712 menu\nmouse-2 will jump to task"))
713 (if (and (> org-clock-string-limit 0)
714 (> (length clock-string) org-clock-string-limit))
715 (propertize
716 (substring clock-string 0 org-clock-string-limit)
717 'help-echo (concat help-text ": " org-clock-heading))
718 (propertize clock-string 'help-echo help-text)))
719 'local-map org-clock-mode-line-map
720 'mouse-face 'mode-line-highlight))
721 (if (and org-clock-task-overrun org-clock-task-overrun-text)
722 (setq org-mode-line-string
723 (concat (propertize
724 org-clock-task-overrun-text
725 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
726 (force-mode-line-update))
728 (defun org-clock-get-clocked-time ()
729 "Get the clocked time for the current item in minutes.
730 The time returned includes the time spent on this task in
731 previous clocking intervals."
732 (let ((currently-clocked-time
733 (floor (- (float-time)
734 (float-time org-clock-start-time)) 60)))
735 (+ currently-clocked-time (or org-clock-total-time 0))))
737 (defun org-clock-modify-effort-estimate (&optional value)
738 "Add to or set the effort estimate of the item currently being clocked.
739 VALUE can be a number of minutes, or a string with format hh:mm or mm.
740 When the string starts with a + or a - sign, the current value of the effort
741 property will be changed by that amount. If the effort value is expressed
742 as an `org-effort-durations' (e.g. \"3h\"), the modified value will be
743 converted to a hh:mm duration.
745 This command will update the \"Effort\" property of the currently
746 clocked item, and the value displayed in the mode line."
747 (interactive)
748 (if (org-clock-is-active)
749 (let ((current org-clock-effort) sign)
750 (unless value
751 ;; Prompt user for a value or a change
752 (setq value
753 (read-string
754 (format "Set effort (hh:mm or mm%s): "
755 (if current
756 (format ", prefix + to add to %s" org-clock-effort)
757 "")))))
758 (when (stringp value)
759 ;; A string. See if it is a delta
760 (setq sign (string-to-char value))
761 (if (member sign '(?- ?+))
762 (setq current (org-duration-to-minutes current)
763 value (substring value 1))
764 (setq current 0))
765 (setq value (org-duration-to-minutes value))
766 (if (equal ?- sign)
767 (setq value (- current value))
768 (if (equal ?+ sign) (setq value (+ current value)))))
769 (setq value (max 0 value)
770 org-clock-effort (org-duration-from-minutes value))
771 (org-entry-put org-clock-marker "Effort" org-clock-effort)
772 (org-clock-update-mode-line)
773 (message "Effort is now %s" org-clock-effort))
774 (message "Clock is not currently active")))
776 (defvar org-clock-notification-was-shown nil
777 "Shows if we have shown notification already.")
779 (defun org-clock-notify-once-if-expired ()
780 "Show notification if we spent more time than we estimated before.
781 Notification is shown only once."
782 (when (org-clocking-p)
783 (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
784 (clocked-time (org-clock-get-clocked-time)))
785 (if (setq org-clock-task-overrun
786 (if (or (null effort-in-minutes) (zerop effort-in-minutes))
788 (>= clocked-time effort-in-minutes)))
789 (unless org-clock-notification-was-shown
790 (setq org-clock-notification-was-shown t)
791 (org-notify
792 (format-message "Task `%s' should be finished by now. (%s)"
793 org-clock-heading org-clock-effort)
794 org-clock-sound))
795 (setq org-clock-notification-was-shown nil)))))
797 (defun org-notify (notification &optional play-sound)
798 "Send a NOTIFICATION and maybe PLAY-SOUND.
799 If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
800 (org-show-notification notification)
801 (if play-sound (org-clock-play-sound play-sound)))
803 (defun org-show-notification (notification)
804 "Show notification.
805 Use `org-show-notification-handler' if defined,
806 use libnotify if available, or fall back on a message."
807 (cond ((functionp org-show-notification-handler)
808 (funcall org-show-notification-handler notification))
809 ((stringp org-show-notification-handler)
810 (start-process "emacs-timer-notification" nil
811 org-show-notification-handler notification))
812 ((fboundp 'notifications-notify)
813 (notifications-notify
814 :title "Org mode message"
815 :body notification
816 ;; FIXME how to link to the Org icon?
817 ;; :app-icon "~/.emacs.d/icons/mail.png"
818 :urgency 'low))
819 ((executable-find "notify-send")
820 (start-process "emacs-timer-notification" nil
821 "notify-send" notification))
822 ;; Maybe the handler will send a message, so only use message as
823 ;; a fall back option
824 (t (message "%s" notification))))
826 (defun org-clock-play-sound (&optional clock-sound)
827 "Play sound as configured by `org-clock-sound'.
828 Use alsa's aplay tool if available.
829 If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
830 (let ((org-clock-sound (or clock-sound org-clock-sound)))
831 (cond
832 ((not org-clock-sound))
833 ((eq org-clock-sound t) (beep t) (beep t))
834 ((stringp org-clock-sound)
835 (let ((file (expand-file-name org-clock-sound)))
836 (if (file-exists-p file)
837 (if (executable-find "aplay")
838 (start-process "org-clock-play-notification" nil
839 "aplay" file)
840 (condition-case nil
841 (play-sound-file file)
842 (error (beep t) (beep t))))))))))
844 (defvar org-clock-mode-line-entry nil
845 "Information for the mode line about the running clock.")
847 (defun org-find-open-clocks (file)
848 "Search through the given file and find all open clocks."
849 (let ((buf (or (get-file-buffer file)
850 (find-file-noselect file)))
851 (org-clock-re (concat org-clock-string " \\(\\[.*?\\]\\)$"))
852 clocks)
853 (with-current-buffer buf
854 (save-excursion
855 (goto-char (point-min))
856 (while (re-search-forward org-clock-re nil t)
857 (push (cons (copy-marker (match-end 1) t)
858 (org-time-string-to-time (match-string 1))) clocks))))
859 clocks))
861 (defsubst org-is-active-clock (clock)
862 "Return t if CLOCK is the currently active clock."
863 (and (org-clock-is-active)
864 (= org-clock-marker (car clock))))
866 (defmacro org-with-clock-position (clock &rest forms)
867 "Evaluate FORMS with CLOCK as the current active clock."
868 `(with-current-buffer (marker-buffer (car ,clock))
869 (org-with-wide-buffer
870 (goto-char (car ,clock))
871 (beginning-of-line)
872 ,@forms)))
873 (def-edebug-spec org-with-clock-position (form body))
874 (put 'org-with-clock-position 'lisp-indent-function 1)
876 (defmacro org-with-clock (clock &rest forms)
877 "Evaluate FORMS with CLOCK as the current active clock.
878 This macro also protects the current active clock from being altered."
879 `(org-with-clock-position ,clock
880 (let ((org-clock-start-time (cdr ,clock))
881 (org-clock-total-time)
882 (org-clock-history)
883 (org-clock-effort)
884 (org-clock-marker (car ,clock))
885 (org-clock-hd-marker (save-excursion
886 (org-back-to-heading t)
887 (point-marker))))
888 ,@forms)))
889 (def-edebug-spec org-with-clock (form body))
890 (put 'org-with-clock 'lisp-indent-function 1)
892 (defsubst org-clock-clock-in (clock &optional resume start-time)
893 "Clock in to the clock located by CLOCK.
894 If necessary, clock-out of the currently active clock."
895 (org-with-clock-position clock
896 (let ((org-clock-in-resume (or resume org-clock-in-resume)))
897 (org-clock-in nil start-time))))
899 (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
900 "Clock out of the clock located by CLOCK."
901 (let ((temp (copy-marker (car clock)
902 (marker-insertion-type (car clock)))))
903 (if (org-is-active-clock clock)
904 (org-clock-out nil fail-quietly at-time)
905 (org-with-clock clock
906 (org-clock-out nil fail-quietly at-time)))
907 (setcar clock temp)))
909 (defsubst org-clock-clock-cancel (clock)
910 "Cancel the clock located by CLOCK."
911 (let ((temp (copy-marker (car clock)
912 (marker-insertion-type (car clock)))))
913 (if (org-is-active-clock clock)
914 (org-clock-cancel)
915 (org-with-clock clock
916 (org-clock-cancel)))
917 (setcar clock temp)))
919 (defvar org-clock-clocking-in nil)
920 (defvar org-clock-resolving-clocks nil)
921 (defvar org-clock-resolving-clocks-due-to-idleness nil)
923 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
924 &optional close-p restart-p fail-quietly)
925 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
926 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
927 (let ((org-clock-resolving-clocks t))
928 (cond
929 ((null resolve-to)
930 (org-clock-clock-cancel clock)
931 (if (and restart-p (not org-clock-clocking-in))
932 (org-clock-clock-in clock)))
934 ((eq resolve-to 'now)
935 (if restart-p
936 (error "RESTART-P is not valid here"))
937 (if (or close-p org-clock-clocking-in)
938 (org-clock-clock-out clock fail-quietly)
939 (unless (org-is-active-clock clock)
940 (org-clock-clock-in clock t))))
942 ((not (time-less-p resolve-to (current-time)))
943 (error "RESOLVE-TO must refer to a time in the past"))
946 (if restart-p
947 (error "RESTART-P is not valid here"))
948 (org-clock-clock-out clock fail-quietly (or clock-out-time
949 resolve-to))
950 (unless org-clock-clocking-in
951 (if close-p
952 (setq org-clock-leftover-time (and (null clock-out-time)
953 resolve-to))
954 (org-clock-clock-in clock nil (and clock-out-time
955 resolve-to))))))))
957 (defun org-clock-jump-to-current-clock (&optional effective-clock)
958 (interactive)
959 (let ((drawer (org-clock-into-drawer))
960 (clock (or effective-clock (cons org-clock-marker
961 org-clock-start-time))))
962 (unless (marker-buffer (car clock))
963 (error "No clock is currently running"))
964 (org-with-clock clock (org-clock-goto))
965 (with-current-buffer (marker-buffer (car clock))
966 (goto-char (car clock))
967 (when drawer
968 (org-with-wide-buffer
969 (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
970 (regexp-quote (if (stringp drawer) drawer "LOGBOOK"))))
971 (beg (save-excursion (org-back-to-heading t) (point))))
972 (catch 'exit
973 (while (re-search-backward drawer-re beg t)
974 (let ((element (org-element-at-point)))
975 (when (eq (org-element-type element) 'drawer)
976 (when (> (org-element-property :end element) (car clock))
977 (org-flag-drawer nil element))
978 (throw 'exit nil)))))))))))
980 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
981 "Resolve an open Org clock.
982 An open clock was found, with `dangling' possibly being non-nil.
983 If this function was invoked with a prefix argument, non-dangling
984 open clocks are ignored. The given clock requires some sort of
985 user intervention to resolve it, either because a clock was left
986 dangling or due to an idle timeout. The clock resolution can
987 either be:
989 (a) deleted, the user doesn't care about the clock
990 (b) restarted from the current time (if no other clock is open)
991 (c) closed, giving the clock X minutes
992 (d) closed and then restarted
993 (e) resumed, as if the user had never left
995 The format of clock is (CONS MARKER START-TIME), where MARKER
996 identifies the buffer and position the clock is open at (and
997 thus, the heading it's under), and START-TIME is when the clock
998 was started."
999 (cl-assert clock)
1000 (let* ((ch
1001 (save-window-excursion
1002 (save-excursion
1003 (unless org-clock-resolving-clocks-due-to-idleness
1004 (org-clock-jump-to-current-clock clock))
1005 (unless org-clock-resolve-expert
1006 (with-output-to-temp-buffer "*Org Clock*"
1007 (princ (format-message "Select a Clock Resolution Command:
1009 i/q Ignore this question; the same as keeping all the idle time.
1011 k/K Keep X minutes of the idle time (default is all). If this
1012 amount is less than the default, you will be clocked out
1013 that many minutes after the time that idling began, and then
1014 clocked back in at the present time.
1016 g/G Indicate that you \"got back\" X minutes ago. This is quite
1017 different from `k': it clocks you out from the beginning of
1018 the idle period and clock you back in X minutes ago.
1020 s/S Subtract the idle time from the current clock. This is the
1021 same as keeping 0 minutes.
1023 C Cancel the open timer altogether. It will be as though you
1024 never clocked in.
1026 j/J Jump to the current clock, to make manual adjustments.
1028 For all these options, using uppercase makes your final state
1029 to be CLOCKED OUT."))))
1030 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
1031 (let (char-pressed)
1032 (while (or (null char-pressed)
1033 (and (not (memq char-pressed
1034 '(?k ?K ?g ?G ?s ?S ?C
1035 ?j ?J ?i ?q)))
1036 (or (ding) t)))
1037 (setq char-pressed
1038 (read-char (concat (funcall prompt-fn clock)
1039 " [jkKgGSscCiq]? ")
1040 nil 45)))
1041 (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
1042 (default
1043 (floor (/ (float-time
1044 (time-subtract (current-time) last-valid)) 60)))
1045 (keep
1046 (and (memq ch '(?k ?K))
1047 (read-number "Keep how many minutes? " default)))
1048 (gotback
1049 (and (memq ch '(?g ?G))
1050 (read-number "Got back how many minutes ago? " default)))
1051 (subtractp (memq ch '(?s ?S)))
1052 (barely-started-p (< (- (float-time last-valid)
1053 (float-time (cdr clock))) 45))
1054 (start-over (and subtractp barely-started-p)))
1055 (cond
1056 ((memq ch '(?j ?J))
1057 (if (eq ch ?J)
1058 (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
1059 (org-clock-jump-to-current-clock clock))
1060 ((or (null ch)
1061 (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
1062 (message ""))
1064 (org-clock-resolve-clock
1065 clock (cond
1066 ((or (eq ch ?C)
1067 ;; If the time on the clock was less than a minute before
1068 ;; the user went away, and they've ask to subtract all the
1069 ;; time...
1070 start-over)
1071 nil)
1072 ((or subtractp
1073 (and gotback (= gotback 0)))
1074 last-valid)
1075 ((or (and keep (= keep default))
1076 (and gotback (= gotback default)))
1077 'now)
1078 (keep
1079 (time-add last-valid (seconds-to-time (* 60 keep))))
1080 (gotback
1081 (time-subtract (current-time)
1082 (seconds-to-time (* 60 gotback))))
1084 (error "Unexpected, please report this as a bug")))
1085 (and gotback last-valid)
1086 (memq ch '(?K ?G ?S))
1087 (and start-over
1088 (not (memq ch '(?K ?G ?S ?C))))
1089 fail-quietly)))))
1091 ;;;###autoload
1092 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
1093 "Resolve all currently open Org clocks.
1094 If `only-dangling-p' is non-nil, only ask to resolve dangling
1095 \(i.e., not currently open and valid) clocks."
1096 (interactive "P")
1097 (unless org-clock-resolving-clocks
1098 (let ((org-clock-resolving-clocks t))
1099 (dolist (file (org-files-list))
1100 (let ((clocks (org-find-open-clocks file)))
1101 (dolist (clock clocks)
1102 (let ((dangling (or (not (org-clock-is-active))
1103 (/= (car clock) org-clock-marker))))
1104 (if (or (not only-dangling-p) dangling)
1105 (org-clock-resolve
1106 clock
1107 (or prompt-fn
1108 (function
1109 (lambda (clock)
1110 (format
1111 "Dangling clock started %d mins ago"
1112 (floor (- (float-time)
1113 (float-time (cdr clock)))
1114 60)))))
1115 (or last-valid
1116 (cdr clock)))))))))))
1118 (defun org-emacs-idle-seconds ()
1119 "Return the current Emacs idle time in seconds, or nil if not idle."
1120 (let ((idle-time (current-idle-time)))
1121 (if idle-time
1122 (float-time idle-time)
1123 0)))
1125 (defun org-mac-idle-seconds ()
1126 "Return the current Mac idle time in seconds."
1127 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
1129 (defvar org-x11idle-exists-p
1130 ;; Check that x11idle exists
1131 (and (eq window-system 'x)
1132 (eq 0 (call-process-shell-command
1133 (format "command -v %s" org-clock-x11idle-program-name)))
1134 ;; Check that x11idle can retrieve the idle time
1135 ;; FIXME: Why "..-shell-command" rather than just `call-process'?
1136 (eq 0 (call-process-shell-command org-clock-x11idle-program-name))))
1138 (defun org-x11-idle-seconds ()
1139 "Return the current X11 idle time in seconds."
1140 (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name)) 1000))
1142 (defun org-user-idle-seconds ()
1143 "Return the number of seconds the user has been idle for.
1144 This routine returns a floating point number."
1145 (cond
1146 ((eq system-type 'darwin)
1147 (org-mac-idle-seconds))
1148 ((and (eq window-system 'x) org-x11idle-exists-p)
1149 (org-x11-idle-seconds))
1151 (org-emacs-idle-seconds))))
1153 (defvar org-clock-user-idle-seconds)
1155 (defun org-resolve-clocks-if-idle ()
1156 "Resolve all currently open Org clocks.
1157 This is performed after `org-clock-idle-time' minutes, to check
1158 if the user really wants to stay clocked in after being idle for
1159 so long."
1160 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
1161 org-clock-marker (marker-buffer org-clock-marker))
1162 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
1163 (org-clock-user-idle-start
1164 (time-subtract (current-time)
1165 (seconds-to-time org-clock-user-idle-seconds)))
1166 (org-clock-resolving-clocks-due-to-idleness t))
1167 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
1168 (org-clock-resolve
1169 (cons org-clock-marker
1170 org-clock-start-time)
1171 (lambda (_)
1172 (format "Clocked in & idle for %.1f mins"
1173 (/ (float-time
1174 (time-subtract (current-time)
1175 org-clock-user-idle-start))
1176 60.0)))
1177 org-clock-user-idle-start)))))
1179 (defvar org-clock-current-task nil "Task currently clocked in.")
1180 (defvar org-clock-out-time nil) ; store the time of the last clock-out
1181 (defvar org--msg-extra)
1183 ;;;###autoload
1184 (defun org-clock-in (&optional select start-time)
1185 "Start the clock on the current item.
1187 If necessary, clock-out of the currently active clock.
1189 With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
1190 recently clocked
1191 tasks to clock into.
1193 When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
1194 clock into the current task and mark it as
1195 the default task, a special task that will always be offered in the
1196 clocking selection, associated with the letter `d'.
1198 When SELECT is `\\[universal-argument] \\[universal-argument] \
1199 \\[universal-argument]', clock in by using the last clock-out
1200 time as the start time. See `org-clock-continuously' to make this
1201 the default behavior."
1202 (interactive "P")
1203 (setq org-clock-notification-was-shown nil)
1204 (org-refresh-effort-properties)
1205 (catch 'abort
1206 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
1207 (org-clocking-p)))
1208 ts selected-task target-pos (org--msg-extra "")
1209 (leftover (and (not org-clock-resolving-clocks)
1210 org-clock-leftover-time)))
1212 (when (and org-clock-auto-clock-resolution
1213 (or (not interrupting)
1214 (eq t org-clock-auto-clock-resolution))
1215 (not org-clock-clocking-in)
1216 (not org-clock-resolving-clocks))
1217 (setq org-clock-leftover-time nil)
1218 (let ((org-clock-clocking-in t))
1219 (org-resolve-clocks))) ; check if any clocks are dangling
1221 (when (equal select '(64))
1222 ;; Set start-time to `org-clock-out-time'
1223 (let ((org-clock-continuously t))
1224 (org-clock-in nil org-clock-out-time)))
1226 (when (equal select '(4))
1227 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1228 (if selected-task
1229 (setq selected-task (copy-marker selected-task))
1230 (error "Abort")))
1232 (when (equal select '(16))
1233 ;; Mark as default clocking task
1234 (org-clock-mark-default-task))
1236 (when interrupting
1237 ;; We are interrupting the clocking of a different task.
1238 ;; Save a marker to this task, so that we can go back.
1239 ;; First check if we are trying to clock into the same task!
1240 (when (save-excursion
1241 (unless selected-task
1242 (org-back-to-heading t))
1243 (and (equal (marker-buffer org-clock-hd-marker)
1244 (if selected-task
1245 (marker-buffer selected-task)
1246 (current-buffer)))
1247 (= (marker-position org-clock-hd-marker)
1248 (if selected-task
1249 (marker-position selected-task)
1250 (point)))
1251 (equal org-clock-current-task (nth 4 (org-heading-components)))))
1252 (message "Clock continues in \"%s\"" org-clock-heading)
1253 (throw 'abort nil))
1254 (move-marker org-clock-interrupted-task
1255 (marker-position org-clock-marker)
1256 (marker-buffer org-clock-marker))
1257 (let ((org-clock-clocking-in t))
1258 (org-clock-out nil t)))
1260 ;; Clock in at which position?
1261 (setq target-pos
1262 (if (and (eobp) (not (org-at-heading-p)))
1263 (point-at-bol 0)
1264 (point)))
1265 (save-excursion
1266 (when (and selected-task (marker-buffer selected-task))
1267 ;; There is a selected task, move to the correct buffer
1268 ;; and set the new target position.
1269 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1270 (setq target-pos (marker-position selected-task))
1271 (move-marker selected-task nil))
1272 (org-with-wide-buffer
1273 (goto-char target-pos)
1274 (org-back-to-heading t)
1275 (or interrupting (move-marker org-clock-interrupted-task nil))
1276 (run-hooks 'org-clock-in-prepare-hook)
1277 (org-clock-history-push)
1278 (setq org-clock-current-task (nth 4 (org-heading-components)))
1279 (cond ((functionp org-clock-in-switch-to-state)
1280 (let ((case-fold-search nil))
1281 (looking-at org-complex-heading-regexp))
1282 (let ((newstate (funcall org-clock-in-switch-to-state
1283 (match-string 2))))
1284 (when newstate (org-todo newstate))))
1285 ((and org-clock-in-switch-to-state
1286 (not (looking-at (concat org-outline-regexp "[ \t]*"
1287 org-clock-in-switch-to-state
1288 "\\>"))))
1289 (org-todo org-clock-in-switch-to-state)))
1290 (setq org-clock-heading
1291 (cond ((and org-clock-heading-function
1292 (functionp org-clock-heading-function))
1293 (funcall org-clock-heading-function))
1294 ((nth 4 (org-heading-components))
1295 (replace-regexp-in-string
1296 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1297 (match-string-no-properties 4)))
1298 (t "???")))
1299 (org-clock-find-position org-clock-in-resume)
1300 (cond
1301 ((and org-clock-in-resume
1302 (looking-at
1303 (concat "^[ \t]*" org-clock-string
1304 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1305 " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1306 (message "Matched %s" (match-string 1))
1307 (setq ts (concat "[" (match-string 1) "]"))
1308 (goto-char (match-end 1))
1309 (setq org-clock-start-time
1310 (apply 'encode-time
1311 (org-parse-time-string (match-string 1))))
1312 (setq org-clock-effort (org-entry-get (point) org-effort-property))
1313 (setq org-clock-total-time (org-clock-sum-current-item
1314 (org-clock-get-sum-start))))
1315 ((eq org-clock-in-resume 'auto-restart)
1316 ;; called from org-clock-load during startup,
1317 ;; do not interrupt, but warn!
1318 (message "Cannot restart clock because task does not contain unfinished clock")
1319 (ding)
1320 (sit-for 2)
1321 (throw 'abort nil))
1323 (insert-before-markers "\n")
1324 (backward-char 1)
1325 (org-indent-line)
1326 (when (and (save-excursion
1327 (end-of-line 0)
1328 (org-in-item-p)))
1329 (beginning-of-line 1)
1330 (indent-line-to (- (org-get-indentation) 2)))
1331 (insert org-clock-string " ")
1332 (setq org-clock-effort (org-entry-get (point) org-effort-property))
1333 (setq org-clock-total-time (org-clock-sum-current-item
1334 (org-clock-get-sum-start)))
1335 (setq org-clock-start-time
1336 (or (and org-clock-continuously org-clock-out-time)
1337 (and leftover
1338 (y-or-n-p
1339 (format
1340 "You stopped another clock %d mins ago; start this one from then? "
1341 (/ (- (float-time
1342 (org-current-time org-clock-rounding-minutes t))
1343 (float-time leftover))
1344 60)))
1345 leftover)
1346 start-time
1347 (org-current-time org-clock-rounding-minutes t)))
1348 (setq ts (org-insert-time-stamp org-clock-start-time
1349 'with-hm 'inactive))))
1350 (move-marker org-clock-marker (point) (buffer-base-buffer))
1351 (move-marker org-clock-hd-marker
1352 (save-excursion (org-back-to-heading t) (point))
1353 (buffer-base-buffer))
1354 (setq org-clock-has-been-used t)
1355 ;; add to mode line
1356 (when (or (eq org-clock-clocked-in-display 'mode-line)
1357 (eq org-clock-clocked-in-display 'both))
1358 (or global-mode-string (setq global-mode-string '("")))
1359 (or (memq 'org-mode-line-string global-mode-string)
1360 (setq global-mode-string
1361 (append global-mode-string '(org-mode-line-string)))))
1362 ;; add to frame title
1363 (when (or (eq org-clock-clocked-in-display 'frame-title)
1364 (eq org-clock-clocked-in-display 'both))
1365 (setq frame-title-format org-clock-frame-title-format))
1366 (org-clock-update-mode-line)
1367 (when org-clock-mode-line-timer
1368 (cancel-timer org-clock-mode-line-timer)
1369 (setq org-clock-mode-line-timer nil))
1370 (when org-clock-clocked-in-display
1371 (setq org-clock-mode-line-timer
1372 (run-with-timer org-clock-update-period
1373 org-clock-update-period
1374 'org-clock-update-mode-line)))
1375 (when org-clock-idle-timer
1376 (cancel-timer org-clock-idle-timer)
1377 (setq org-clock-idle-timer nil))
1378 (setq org-clock-idle-timer
1379 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1380 (message "Clock starts at %s - %s" ts org--msg-extra)
1381 (run-hooks 'org-clock-in-hook))))))
1383 ;;;###autoload
1384 (defun org-clock-in-last (&optional arg)
1385 "Clock in the last closed clocked item.
1386 When already clocking in, send an warning.
1387 With a universal prefix argument, select the task you want to
1388 clock in from the last clocked in tasks.
1389 With two universal prefix arguments, start clocking using the
1390 last clock-out time, if any.
1391 With three universal prefix arguments, interactively prompt
1392 for a todo state to switch to, overriding the existing value
1393 `org-clock-in-switch-to-state'."
1394 (interactive "P")
1395 (if (equal arg '(4)) (org-clock-in arg)
1396 (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
1397 (or org-clock-out-time
1398 (org-current-time org-clock-rounding-minutes t))
1399 (org-current-time org-clock-rounding-minutes t))))
1400 (if (null org-clock-history)
1401 (message "No last clock")
1402 (let ((org-clock-in-switch-to-state
1403 (if (and (not org-clock-current-task) (equal arg '(64)))
1404 (completing-read "Switch to state: "
1405 (and org-clock-history
1406 (with-current-buffer
1407 (marker-buffer (car org-clock-history))
1408 org-todo-keywords-1)))
1409 org-clock-in-switch-to-state))
1410 (already-clocking org-clock-current-task))
1411 (org-clock-clock-in (list (car org-clock-history)) nil start-time)
1412 (or already-clocking
1413 ;; Don't display a message if we are already clocking in
1414 (message "Clocking back: %s (in %s)"
1415 org-clock-current-task
1416 (buffer-name (marker-buffer org-clock-marker)))))))))
1418 (defun org-clock-mark-default-task ()
1419 "Mark current task as default task."
1420 (interactive)
1421 (save-excursion
1422 (org-back-to-heading t)
1423 (move-marker org-clock-default-task (point))))
1425 (defun org-clock-get-sum-start ()
1426 "Return the time from which clock times should be counted.
1427 This is for the currently running clock as it is displayed
1428 in the mode line. This function looks at the properties
1429 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1430 corresponding variable `org-clock-mode-line-total' and then
1431 decides which time to use."
1432 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1433 (symbol-name org-clock-mode-line-total)))
1434 (lr (org-entry-get nil "LAST_REPEAT")))
1435 (cond
1436 ((equal cmt "current")
1437 (setq org--msg-extra "showing time in current clock instance")
1438 (current-time))
1439 ((equal cmt "today")
1440 (setq org--msg-extra "showing today's task time.")
1441 (let* ((dt (decode-time))
1442 (hour (nth 2 dt))
1443 (day (nth 3 dt)))
1444 (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
1445 (setf (nth 2 dt) org-extend-today-until)
1446 (setq dt (append (list 0 0) (nthcdr 2 dt)))
1447 (apply 'encode-time dt)))
1448 ((or (equal cmt "all")
1449 (and (or (not cmt) (equal cmt "auto"))
1450 (not lr)))
1451 (setq org--msg-extra "showing entire task time.")
1452 nil)
1453 ((or (equal cmt "repeat")
1454 (and (or (not cmt) (equal cmt "auto"))
1455 lr))
1456 (setq org--msg-extra "showing task time since last repeat.")
1457 (if (not lr)
1459 (org-time-string-to-time lr)))
1460 (t nil))))
1462 (defun org-clock-find-position (find-unclosed)
1463 "Find the location where the next clock line should be inserted.
1464 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1465 line and position cursor in that line."
1466 (org-back-to-heading t)
1467 (catch 'exit
1468 (let* ((beg (line-beginning-position))
1469 (end (save-excursion (outline-next-heading) (point)))
1470 (org-clock-into-drawer (org-clock-into-drawer))
1471 (drawer (org-clock-drawer-name)))
1472 ;; Look for a running clock if FIND-UNCLOSED in non-nil.
1473 (when find-unclosed
1474 (let ((open-clock-re
1475 (concat "^[ \t]*"
1476 org-clock-string
1477 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1478 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1479 (while (re-search-forward open-clock-re end t)
1480 (let ((element (org-element-at-point)))
1481 (when (and (eq (org-element-type element) 'clock)
1482 (eq (org-element-property :status element) 'running))
1483 (beginning-of-line)
1484 (throw 'exit t))))))
1485 ;; Look for an existing clock drawer.
1486 (when drawer
1487 (goto-char beg)
1488 (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")))
1489 (while (re-search-forward drawer-re end t)
1490 (let ((element (org-element-at-point)))
1491 (when (eq (org-element-type element) 'drawer)
1492 (let ((cend (org-element-property :contents-end element)))
1493 (if (and (not org-log-states-order-reversed) cend)
1494 (goto-char cend)
1495 (forward-line))
1496 (throw 'exit t)))))))
1497 (goto-char beg)
1498 (let ((clock-re (concat "^[ \t]*" org-clock-string))
1499 (count 0)
1500 positions)
1501 ;; Count the CLOCK lines and store their positions.
1502 (save-excursion
1503 (while (re-search-forward clock-re end t)
1504 (let ((element (org-element-at-point)))
1505 (when (eq (org-element-type element) 'clock)
1506 (setq positions (cons (line-beginning-position) positions)
1507 count (1+ count))))))
1508 (cond
1509 ((null positions)
1510 ;; Skip planning line and property drawer, if any.
1511 (org-end-of-meta-data)
1512 (unless (bolp) (insert "\n"))
1513 ;; Create a new drawer if necessary.
1514 (when (and org-clock-into-drawer
1515 (or (not (wholenump org-clock-into-drawer))
1516 (< org-clock-into-drawer 2)))
1517 (let ((beg (point)))
1518 (insert ":" drawer ":\n:END:\n")
1519 (org-indent-region beg (point))
1520 (goto-char beg)
1521 (org-flag-drawer t)
1522 (forward-line))))
1523 ;; When a clock drawer needs to be created because of the
1524 ;; number of clock items or simply if it is missing, collect
1525 ;; all clocks in the section and wrap them within the drawer.
1526 ((if (wholenump org-clock-into-drawer)
1527 (>= (1+ count) org-clock-into-drawer)
1528 drawer)
1529 ;; Skip planning line and property drawer, if any.
1530 (org-end-of-meta-data)
1531 (let ((beg (point)))
1532 (insert
1533 (mapconcat
1534 (lambda (p)
1535 (save-excursion
1536 (goto-char p)
1537 (org-trim (delete-and-extract-region
1538 (save-excursion (skip-chars-backward " \r\t\n")
1539 (line-beginning-position 2))
1540 (line-beginning-position 2)))))
1541 positions "\n")
1542 "\n:END:\n")
1543 (let ((end (point-marker)))
1544 (goto-char beg)
1545 (save-excursion (insert ":" drawer ":\n"))
1546 (org-flag-drawer t)
1547 (org-indent-region (point) end)
1548 (forward-line)
1549 (unless org-log-states-order-reversed
1550 (goto-char end)
1551 (beginning-of-line -1))
1552 (set-marker end nil))))
1553 (org-log-states-order-reversed (goto-char (car (last positions))))
1554 (t (goto-char (car positions))))))))
1556 ;;;###autoload
1557 (defun org-clock-out (&optional switch-to-state fail-quietly at-time)
1558 "Stop the currently running clock.
1559 Throw an error if there is no running clock and FAIL-QUIETLY is nil.
1560 With a universal prefix, prompt for a state to switch the clocked out task
1561 to, overriding the existing value of `org-clock-out-switch-to-state'."
1562 (interactive "P")
1563 (catch 'exit
1564 (when (not (org-clocking-p))
1565 (setq global-mode-string
1566 (delq 'org-mode-line-string global-mode-string))
1567 (setq frame-title-format org-frame-title-format-backup)
1568 (force-mode-line-update)
1569 (if fail-quietly (throw 'exit t) (user-error "No active clock")))
1570 (let ((org-clock-out-switch-to-state
1571 (if switch-to-state
1572 (completing-read "Switch to state: "
1573 (with-current-buffer
1574 (marker-buffer org-clock-marker)
1575 org-todo-keywords-1)
1576 nil t "DONE")
1577 org-clock-out-switch-to-state))
1578 (now (org-current-time org-clock-rounding-minutes))
1579 ts te s h m remove)
1580 (setq org-clock-out-time now)
1581 (save-excursion ; Do not replace this with `with-current-buffer'.
1582 (with-no-warnings (set-buffer (org-clocking-buffer)))
1583 (save-restriction
1584 (widen)
1585 (goto-char org-clock-marker)
1586 (beginning-of-line 1)
1587 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1588 (equal (match-string 1) org-clock-string))
1589 (setq ts (match-string 2))
1590 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1591 (goto-char (match-end 0))
1592 (delete-region (point) (point-at-eol))
1593 (insert "--")
1594 (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
1595 (setq s (- (float-time
1596 (apply #'encode-time (org-parse-time-string te nil t)))
1597 (float-time
1598 (apply #'encode-time (org-parse-time-string ts nil t))))
1599 h (floor (/ s 3600))
1600 s (- s (* 3600 h))
1601 m (floor (/ s 60))
1602 s (- s (* 60 s)))
1603 (insert " => " (format "%2d:%02d" h m))
1604 (move-marker org-clock-marker nil)
1605 (move-marker org-clock-hd-marker nil)
1606 ;; Possibly remove zero time clocks. However, do not add
1607 ;; a note associated to the CLOCK line in this case.
1608 (cond ((and org-clock-out-remove-zero-time-clocks
1609 (= (+ h m) 0))
1610 (setq remove t)
1611 (delete-region (line-beginning-position)
1612 (line-beginning-position 2)))
1613 (org-log-note-clock-out
1614 (org-add-log-setup
1615 'clock-out nil nil nil
1616 (concat "# Task: " (org-get-heading t) "\n\n"))))
1617 (when org-clock-mode-line-timer
1618 (cancel-timer org-clock-mode-line-timer)
1619 (setq org-clock-mode-line-timer nil))
1620 (when org-clock-idle-timer
1621 (cancel-timer org-clock-idle-timer)
1622 (setq org-clock-idle-timer nil))
1623 (setq global-mode-string
1624 (delq 'org-mode-line-string global-mode-string))
1625 (setq frame-title-format org-frame-title-format-backup)
1626 (when org-clock-out-switch-to-state
1627 (save-excursion
1628 (org-back-to-heading t)
1629 (let ((org-inhibit-logging t)
1630 (org-clock-out-when-done nil))
1631 (cond
1632 ((functionp org-clock-out-switch-to-state)
1633 (let ((case-fold-search nil))
1634 (looking-at org-complex-heading-regexp))
1635 (let ((newstate (funcall org-clock-out-switch-to-state
1636 (match-string 2))))
1637 (when newstate (org-todo newstate))))
1638 ((and org-clock-out-switch-to-state
1639 (not (looking-at (concat org-outline-regexp "[ \t]*"
1640 org-clock-out-switch-to-state
1641 "\\>"))))
1642 (org-todo org-clock-out-switch-to-state))))))
1643 (force-mode-line-update)
1644 (message (concat "Clock stopped at %s after "
1645 (org-duration-from-minutes (+ (* 60 h) m)) "%s")
1646 te (if remove " => LINE REMOVED" ""))
1647 (run-hooks 'org-clock-out-hook)
1648 (unless (org-clocking-p)
1649 (setq org-clock-current-task nil)))))))
1651 (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
1653 (defun org-clock-remove-empty-clock-drawer ()
1654 "Remove empty clock drawers in current subtree."
1655 (save-excursion
1656 (org-back-to-heading t)
1657 (org-map-tree
1658 (lambda ()
1659 (let ((drawer (org-clock-drawer-name))
1660 (case-fold-search t))
1661 (when drawer
1662 (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer)))
1663 (end (save-excursion (outline-next-heading))))
1664 (while (re-search-forward re end t)
1665 (org-remove-empty-drawer-at (point))))))))))
1667 (defun org-clock-timestamps-up (&optional n)
1668 "Increase CLOCK timestamps at cursor.
1669 Optional argument N tells to change by that many units."
1670 (interactive "P")
1671 (org-clock-timestamps-change 'up n))
1673 (defun org-clock-timestamps-down (&optional n)
1674 "Increase CLOCK timestamps at cursor.
1675 Optional argument N tells to change by that many units."
1676 (interactive "P")
1677 (org-clock-timestamps-change 'down n))
1679 (defun org-clock-timestamps-change (updown &optional n)
1680 "Change CLOCK timestamps synchronously at cursor.
1681 UPDOWN tells whether to change `up' or `down'.
1682 Optional argument N tells to change by that many units."
1683 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1684 'org-timestamp-down))
1685 (timestamp? (org-at-timestamp-p 'lax))
1686 ts1 begts1 ts2 begts2 updatets1 tdiff)
1687 (when timestamp?
1688 (save-excursion
1689 (move-beginning-of-line 1)
1690 (re-search-forward org-ts-regexp3 nil t)
1691 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1692 (when (re-search-forward org-ts-regexp3 nil t)
1693 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1694 ;; Are we on the second timestamp?
1695 (if (<= begts2 (point)) (setq updatets1 t))
1696 (if (not ts2)
1697 ;; fall back on org-timestamp-up if there is only one
1698 (funcall tschange n)
1699 (funcall tschange n)
1700 (let ((ts (if updatets1 ts2 ts1))
1701 (begts (if updatets1 begts1 begts2)))
1702 (setq tdiff
1703 (time-subtract
1704 (org-time-string-to-time org-last-changed-timestamp)
1705 (org-time-string-to-time ts)))
1706 (save-excursion
1707 (goto-char begts)
1708 (org-timestamp-change
1709 (round (/ (float-time tdiff)
1710 (pcase timestamp?
1711 (`minute 60)
1712 (`hour 3600)
1713 (`day (* 24 3600))
1714 (`month (* 24 3600 31))
1715 (`year (* 24 3600 365.2)))))
1716 timestamp? 'updown)))))))
1718 ;;;###autoload
1719 (defun org-clock-cancel ()
1720 "Cancel the running clock by removing the start timestamp."
1721 (interactive)
1722 (when (not (org-clocking-p))
1723 (setq global-mode-string
1724 (delq 'org-mode-line-string global-mode-string))
1725 (setq frame-title-format org-frame-title-format-backup)
1726 (force-mode-line-update)
1727 (error "No active clock"))
1728 (save-excursion ; Do not replace this with `with-current-buffer'.
1729 (with-no-warnings (set-buffer (org-clocking-buffer)))
1730 (goto-char org-clock-marker)
1731 (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
1732 (line-beginning-position))
1733 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1734 (org-remove-empty-drawer-at (point)))
1735 (message "Clock gone, cancel the timer anyway")
1736 (sit-for 2)))
1737 (move-marker org-clock-marker nil)
1738 (move-marker org-clock-hd-marker nil)
1739 (setq global-mode-string
1740 (delq 'org-mode-line-string global-mode-string))
1741 (setq frame-title-format org-frame-title-format-backup)
1742 (force-mode-line-update)
1743 (message "Clock canceled")
1744 (run-hooks 'org-clock-cancel-hook))
1746 ;;;###autoload
1747 (defun org-clock-goto (&optional select)
1748 "Go to the currently clocked-in entry, or to the most recently clocked one.
1749 With prefix arg SELECT, offer recently clocked tasks for selection."
1750 (interactive "@P")
1751 (let* ((recent nil)
1752 (m (cond
1753 (select
1754 (or (org-clock-select-task "Select task to go to: ")
1755 (error "No task selected")))
1756 ((org-clocking-p) org-clock-marker)
1757 ((and org-clock-goto-may-find-recent-task
1758 (car org-clock-history)
1759 (marker-buffer (car org-clock-history)))
1760 (setq recent t)
1761 (car org-clock-history))
1762 (t (error "No active or recent clock task")))))
1763 (pop-to-buffer-same-window (marker-buffer m))
1764 (if (or (< m (point-min)) (> m (point-max))) (widen))
1765 (goto-char m)
1766 (org-show-entry)
1767 (org-back-to-heading t)
1768 (org-cycle-hide-drawers 'children)
1769 (recenter org-clock-goto-before-context)
1770 (org-reveal)
1771 (if recent
1772 (message "No running clock, this is the most recently clocked task"))
1773 (run-hooks 'org-clock-goto-hook)))
1775 (defvar-local org-clock-file-total-minutes nil
1776 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1778 (defun org-clock-sum-today (&optional headline-filter)
1779 "Sum the times for each subtree for today."
1780 (let ((range (org-clock-special-range 'today)))
1781 (org-clock-sum (car range) (cadr range)
1782 headline-filter :org-clock-minutes-today)))
1784 (defun org-clock-sum-custom (&optional headline-filter range propname)
1785 "Sum the times for each subtree for today."
1786 (let ((r (or (and (symbolp range) (org-clock-special-range range))
1787 (org-clock-special-range
1788 (intern (completing-read
1789 "Range: "
1790 '("today" "yesterday" "thisweek" "lastweek"
1791 "thismonth" "lastmonth" "thisyear" "lastyear"
1792 "interactive")
1793 nil t))))))
1794 (org-clock-sum (car r) (cadr r)
1795 headline-filter (or propname :org-clock-minutes-custom))))
1797 ;;;###autoload
1798 (defun org-clock-sum (&optional tstart tend headline-filter propname)
1799 "Sum the times for each subtree.
1800 Puts the resulting times in minutes as a text property on each headline.
1801 TSTART and TEND can mark a time range to be considered.
1802 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1803 each headline in the time range with point at the headline. Headlines for
1804 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1805 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1806 (org-with-silent-modifications
1807 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1808 org-clock-string
1809 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1810 (lmax 30)
1811 (ltimes (make-vector lmax 0))
1812 (t1 0)
1813 (level 0)
1814 ts te dt
1815 time)
1816 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1817 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1818 (if (consp tstart) (setq tstart (float-time tstart)))
1819 (if (consp tend) (setq tend (float-time tend)))
1820 (remove-text-properties (point-min) (point-max)
1821 `(,(or propname :org-clock-minutes) t
1822 :org-clock-force-headline-inclusion t))
1823 (save-excursion
1824 (goto-char (point-max))
1825 (while (re-search-backward re nil t)
1826 (cond
1827 ((match-end 2)
1828 ;; Two time stamps
1829 (setq ts (match-string 2)
1830 te (match-string 3)
1831 ts (float-time
1832 (apply #'encode-time (org-parse-time-string ts nil t)))
1833 te (float-time
1834 (apply #'encode-time (org-parse-time-string te nil t)))
1835 ts (if tstart (max ts tstart) ts)
1836 te (if tend (min te tend) te)
1837 dt (- te ts)
1838 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1839 ((match-end 4)
1840 ;; A naked time
1841 (setq t1 (+ t1 (string-to-number (match-string 5))
1842 (* 60 (string-to-number (match-string 4))))))
1843 (t ;; A headline
1844 ;; Add the currently clocking item time to the total
1845 (when (and org-clock-report-include-clocking-task
1846 (equal (org-clocking-buffer) (current-buffer))
1847 (equal (marker-position org-clock-hd-marker) (point))
1848 tstart
1849 tend
1850 (>= (float-time org-clock-start-time) tstart)
1851 (<= (float-time org-clock-start-time) tend))
1852 (let ((time (floor (- (float-time)
1853 (float-time org-clock-start-time))
1854 60)))
1855 (setq t1 (+ t1 time))))
1856 (let* ((headline-forced
1857 (get-text-property (point)
1858 :org-clock-force-headline-inclusion))
1859 (headline-included
1860 (or (null headline-filter)
1861 (save-excursion
1862 (save-match-data (funcall headline-filter))))))
1863 (setq level (- (match-end 1) (match-beginning 1)))
1864 (when (>= level lmax)
1865 (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
1866 (when (or (> t1 0) (> (aref ltimes level) 0))
1867 (when (or headline-included headline-forced)
1868 (if headline-included
1869 (cl-loop for l from 0 to level do
1870 (aset ltimes l (+ (aref ltimes l) t1))))
1871 (setq time (aref ltimes level))
1872 (goto-char (match-beginning 0))
1873 (put-text-property (point) (point-at-eol)
1874 (or propname :org-clock-minutes) time)
1875 (when headline-filter
1876 (save-excursion
1877 (save-match-data
1878 (while (org-up-heading-safe)
1879 (put-text-property
1880 (point) (line-end-position)
1881 :org-clock-force-headline-inclusion t))))))
1882 (setq t1 0)
1883 (cl-loop for l from level to (1- lmax) do
1884 (aset ltimes l 0)))))))
1885 (setq org-clock-file-total-minutes (aref ltimes 0))))))
1887 (defun org-clock-sum-current-item (&optional tstart)
1888 "Return time, clocked on current item in total."
1889 (save-excursion
1890 (save-restriction
1891 (org-narrow-to-subtree)
1892 (org-clock-sum tstart)
1893 org-clock-file-total-minutes)))
1895 ;;;###autoload
1896 (defun org-clock-display (&optional arg)
1897 "Show subtree times in the entire buffer.
1899 By default, show the total time for the range defined in
1900 `org-clock-display-default-range'. With `\\[universal-argument]' \
1901 prefix, show
1902 the total time for today instead.
1904 With `\\[universal-argument] \\[universal-argument]' prefix, \
1905 use a custom range, entered at prompt.
1907 With `\\[universal-argument] \ \\[universal-argument] \
1908 \\[universal-argument]' prefix, display the total time in the
1909 echo area.
1911 Use `\\[org-clock-remove-overlays]' to remove the subtree times."
1912 (interactive "P")
1913 (org-clock-remove-overlays)
1914 (let* ((todayp (equal arg '(4)))
1915 (customp (member arg '((16) today yesterday
1916 thisweek lastweek thismonth
1917 lastmonth thisyear lastyear
1918 untilnow interactive)))
1919 (prop (cond ((not arg) :org-clock-minutes-default)
1920 (todayp :org-clock-minutes-today)
1921 (customp :org-clock-minutes-custom)
1922 (t :org-clock-minutes)))
1923 time h m p)
1924 (cond ((not arg) (org-clock-sum-custom
1925 nil org-clock-display-default-range prop))
1926 (todayp (org-clock-sum-today))
1927 (customp (org-clock-sum-custom nil arg))
1928 (t (org-clock-sum)))
1929 (unless (eq arg '(64))
1930 (save-excursion
1931 (goto-char (point-min))
1932 (while (or (and (equal (setq p (point)) (point-min))
1933 (get-text-property p prop))
1934 (setq p (next-single-property-change
1935 (point) prop)))
1936 (goto-char p)
1937 (when (setq time (get-text-property p prop))
1938 (org-clock-put-overlay time)))
1939 (setq h (/ org-clock-file-total-minutes 60)
1940 m (- org-clock-file-total-minutes (* 60 h)))
1941 ;; Arrange to remove the overlays upon next change.
1942 (when org-remove-highlights-with-change
1943 (add-hook 'before-change-functions 'org-clock-remove-overlays
1944 nil 'local))))
1945 (message (concat (format "Total file time%s: "
1946 (cond (todayp " for today")
1947 (customp " (custom)")
1948 (t "")))
1949 (org-duration-from-minutes
1950 org-clock-file-total-minutes)
1951 " (%d hours and %d minutes)")
1952 h m)))
1954 (defvar-local org-clock-overlays nil)
1956 (defun org-clock-put-overlay (time)
1957 "Put an overlays on the current line, displaying TIME.
1958 This creates a new overlay and stores it in `org-clock-overlays', so that it
1959 will be easy to remove."
1960 (let (ov tx)
1961 (beginning-of-line)
1962 (let ((case-fold-search nil))
1963 (when (looking-at org-complex-heading-regexp)
1964 (goto-char (match-beginning 4))))
1965 (setq ov (make-overlay (point) (point-at-eol))
1966 tx (concat (buffer-substring-no-properties (point) (match-end 4))
1967 (org-add-props
1968 (make-string
1969 (max 0 (- (- 60 (current-column))
1970 (- (match-end 4) (match-beginning 4))
1971 (length (org-get-at-bol 'line-prefix))))
1972 ?\·)
1973 '(face shadow))
1974 (org-add-props
1975 (format " %9s " (org-duration-from-minutes time))
1976 '(face org-clock-overlay))
1977 ""))
1978 (overlay-put ov 'display tx)
1979 (push ov org-clock-overlays)))
1981 ;;;###autoload
1982 (defun org-clock-remove-overlays (&optional _beg _end noremove)
1983 "Remove the occur highlights from the buffer.
1984 If NOREMOVE is nil, remove this function from the
1985 `before-change-functions' in the current buffer."
1986 (interactive)
1987 (unless org-inhibit-highlight-removal
1988 (mapc #'delete-overlay org-clock-overlays)
1989 (setq org-clock-overlays nil)
1990 (unless noremove
1991 (remove-hook 'before-change-functions
1992 'org-clock-remove-overlays 'local))))
1994 (defvar org-state) ;; dynamically scoped into this function
1995 (defun org-clock-out-if-current ()
1996 "Clock out if the current entry contains the running clock.
1997 This is used to stop the clock after a TODO entry is marked DONE,
1998 and is only done if the variable `org-clock-out-when-done' is not nil."
1999 (when (and (org-clocking-p)
2000 org-clock-out-when-done
2001 (marker-buffer org-clock-marker)
2002 (or (and (eq t org-clock-out-when-done)
2003 (member org-state org-done-keywords))
2004 (and (listp org-clock-out-when-done)
2005 (member org-state org-clock-out-when-done)))
2006 (equal (or (buffer-base-buffer (org-clocking-buffer))
2007 (org-clocking-buffer))
2008 (or (buffer-base-buffer (current-buffer))
2009 (current-buffer)))
2010 (< (point) org-clock-marker)
2011 (> (save-excursion (outline-next-heading) (point))
2012 org-clock-marker))
2013 ;; Clock out, but don't accept a logging message for this.
2014 (let ((org-log-note-clock-out nil)
2015 (org-clock-out-switch-to-state nil))
2016 (org-clock-out))))
2018 (add-hook 'org-after-todo-state-change-hook
2019 'org-clock-out-if-current)
2021 ;;;###autoload
2022 (defun org-clock-get-clocktable (&rest props)
2023 "Get a formatted clocktable with parameters according to PROPS.
2024 The table is created in a temporary buffer, fully formatted and
2025 fontified, and then returned."
2026 ;; Set the defaults
2027 (setq props (plist-put props :name "clocktable"))
2028 (unless (plist-member props :maxlevel)
2029 (setq props (plist-put props :maxlevel 2)))
2030 (unless (plist-member props :scope)
2031 (setq props (plist-put props :scope 'agenda)))
2032 (with-temp-buffer
2033 (org-mode)
2034 (org-create-dblock props)
2035 (org-update-dblock)
2036 (org-font-lock-ensure)
2037 (forward-line 2)
2038 (buffer-substring (point) (progn
2039 (re-search-forward "^[ \t]*#\\+END" nil t)
2040 (point-at-bol)))))
2042 ;;;###autoload
2043 (defun org-clock-report (&optional arg)
2044 "Create a table containing a report about clocked time.
2045 If the cursor is inside an existing clocktable block, then the table
2046 will be updated. If not, a new clocktable will be inserted. The scope
2047 of the new clock will be subtree when called from within a subtree, and
2048 file elsewhere.
2050 When called with a prefix argument, move to the first clock table in the
2051 buffer and update it."
2052 (interactive "P")
2053 (org-clock-remove-overlays)
2054 (when arg
2055 (org-find-dblock "clocktable")
2056 (org-show-entry))
2057 (if (org-in-clocktable-p)
2058 (goto-char (org-in-clocktable-p))
2059 (let ((props (if (ignore-errors
2060 (save-excursion (org-back-to-heading)))
2061 (list :name "clocktable" :scope 'subtree)
2062 (list :name "clocktable"))))
2063 (org-create-dblock
2064 (org-combine-plists org-clock-clocktable-default-properties props))))
2065 (org-update-dblock))
2067 (defun org-day-of-week (day month year)
2068 "Returns the day of the week as an integer."
2069 (nth 6
2070 (decode-time
2071 (date-to-time
2072 (format "%d-%02d-%02dT00:00:00" year month day)))))
2074 (defun org-quarter-to-date (quarter year)
2075 "Get the date (week day year) of the first day of a given quarter."
2076 (let (startday)
2077 (cond
2078 ((= quarter 1)
2079 (setq startday (org-day-of-week 1 1 year))
2080 (cond
2081 ((= startday 0)
2082 (list 52 7 (- year 1)))
2083 ((= startday 6)
2084 (list 52 6 (- year 1)))
2085 ((<= startday 4)
2086 (list 1 startday year))
2087 ((> startday 4)
2088 (list 53 startday (- year 1)))
2091 ((= quarter 2)
2092 (setq startday (org-day-of-week 1 4 year))
2093 (cond
2094 ((= startday 0)
2095 (list 13 startday year))
2096 ((< startday 4)
2097 (list 14 startday year))
2098 ((>= startday 4)
2099 (list 13 startday year))
2102 ((= quarter 3)
2103 (setq startday (org-day-of-week 1 7 year))
2104 (cond
2105 ((= startday 0)
2106 (list 26 startday year))
2107 ((< startday 4)
2108 (list 27 startday year))
2109 ((>= startday 4)
2110 (list 26 startday year))
2113 ((= quarter 4)
2114 (setq startday (org-day-of-week 1 10 year))
2115 (cond
2116 ((= startday 0)
2117 (list 39 startday year))
2118 ((<= startday 4)
2119 (list 40 startday year))
2120 ((> startday 4)
2121 (list 39 startday year)))))))
2123 (defun org-clock-special-range (key &optional time as-strings wstart mstart)
2124 "Return two times bordering a special time range.
2126 KEY is a symbol specifying the range and can be one of `today',
2127 `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
2128 `thisyear', `lastyear' or `untilnow'. If set to `interactive',
2129 user is prompted for range boundaries. It can be a string or an
2130 integer.
2132 By default, a week starts Monday 0:00 and ends Sunday 24:00. The
2133 range is determined relative to TIME, which defaults to current
2134 time.
2136 The return value is a list containing two internal times, one for
2137 the beginning of the range and one for its end, like the ones
2138 returned by `current time' or `encode-time' and a string used to
2139 display information. If AS-STRINGS is non-nil, the returned
2140 times will be formatted strings.
2142 If WSTART is non-nil, use this number to specify the starting day
2143 of a week (monday is 1). If MSTART is non-nil, use this number
2144 to specify the starting day of a month (1 is the first day of the
2145 month). If you can combine both, the month starting day will
2146 have priority."
2147 (let* ((tm (decode-time time))
2148 (m (nth 1 tm))
2149 (h (nth 2 tm))
2150 (d (nth 3 tm))
2151 (month (nth 4 tm))
2152 (y (nth 5 tm))
2153 (dow (nth 6 tm))
2154 (skey (format "%s" key))
2155 (shift 0)
2156 (q (cond ((>= month 10) 4)
2157 ((>= month 7) 3)
2158 ((>= month 4) 2)
2159 (t 1)))
2160 m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq)
2161 (cond
2162 ((string-match "\\`[0-9]+\\'" skey)
2163 (setq y (string-to-number skey) month 1 d 1 key 'year))
2164 ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey)
2165 (setq y (string-to-number (match-string 1 skey))
2166 month (string-to-number (match-string 2 skey))
2168 key 'month))
2169 ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey)
2170 (require 'cal-iso)
2171 (let ((date (calendar-gregorian-from-absolute
2172 (calendar-iso-to-absolute
2173 (list (string-to-number (match-string 2 skey))
2175 (string-to-number (match-string 1 skey)))))))
2176 (setq d (nth 1 date)
2177 month (car date)
2178 y (nth 2 date)
2179 dow 1
2180 key 'week)))
2181 ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey)
2182 (require 'cal-iso)
2183 (setq q (string-to-number (match-string 2 skey)))
2184 (let ((date (calendar-gregorian-from-absolute
2185 (calendar-iso-to-absolute
2186 (org-quarter-to-date
2187 q (string-to-number (match-string 1 skey)))))))
2188 (setq d (nth 1 date)
2189 month (car date)
2190 y (nth 2 date)
2191 dow 1
2192 key 'quarter)))
2193 ((string-match
2194 "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
2195 skey)
2196 (setq y (string-to-number (match-string 1 skey))
2197 month (string-to-number (match-string 2 skey))
2198 d (string-to-number (match-string 3 skey))
2199 key 'day))
2200 ((string-match "\\([-+][0-9]+\\)\\'" skey)
2201 (setq shift (string-to-number (match-string 1 skey))
2202 key (intern (substring skey 0 (match-beginning 1))))
2203 (when (and (memq key '(quarter thisq)) (> shift 0))
2204 (error "Looking forward with quarters isn't implemented"))))
2205 (when (= shift 0)
2206 (pcase key
2207 (`yesterday (setq key 'today shift -1))
2208 (`lastweek (setq key 'week shift -1))
2209 (`lastmonth (setq key 'month shift -1))
2210 (`lastyear (setq key 'year shift -1))
2211 (`lastq (setq key 'quarter shift -1))))
2212 ;; Prepare start and end times depending on KEY's type.
2213 (pcase key
2214 ((or `day `today) (setq m 0 h 0 h1 24 d (+ d shift)))
2215 ((or `week `thisweek)
2216 (let* ((ws (or wstart 1))
2217 (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))))
2218 (setq m 0 h 0 d (- d diff) d1 (+ 7 d))))
2219 ((or `month `thismonth)
2220 (setq h 0 m 0 d (or mstart 1) month (+ month shift) month1 (1+ month)))
2221 ((or `quarter `thisq)
2222 ;; Compute if this shift remains in this year. If not, compute
2223 ;; how many years and quarters we have to shift (via floor*) and
2224 ;; compute the shifted years, months and quarters.
2225 (cond
2226 ((< (+ (- q 1) shift) 0) ; Shift not in this year.
2227 (let* ((interval (* -1 (+ (- q 1) shift)))
2228 ;; Set tmp to ((years to shift) (quarters to shift)).
2229 (tmp (cl-floor interval 4)))
2230 ;; Due to the use of floor, 0 quarters actually means 4.
2231 (if (= 0 (nth 1 tmp))
2232 (setq shiftedy (- y (nth 0 tmp))
2233 shiftedm 1
2234 shiftedq 1)
2235 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
2236 shiftedm (- 13 (* 3 (nth 1 tmp)))
2237 shiftedq (- 5 (nth 1 tmp)))))
2238 (setq m 0 h 0 d 1 month shiftedm month1 (+ 3 shiftedm) y shiftedy))
2239 ((> (+ q shift) 0) ; Shift is within this year.
2240 (setq shiftedq (+ q shift))
2241 (setq shiftedy y)
2242 (let ((qshift (* 3 (1- (+ q shift)))))
2243 (setq m 0 h 0 d 1 month (+ 1 qshift) month1 (+ 4 qshift))))))
2244 ((or `year `thisyear)
2245 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
2246 ((or `interactive `untilnow)) ; Special cases, ignore them.
2247 (_ (user-error "No such time block %s" key)))
2248 ;; Format start and end times according to AS-STRINGS.
2249 (let* ((start (pcase key
2250 (`interactive (org-read-date nil t nil "Range start? "))
2251 (`untilnow org-clock--oldest-date)
2252 (_ (encode-time 0 m h d month y))))
2253 (end (pcase key
2254 (`interactive (org-read-date nil t nil "Range end? "))
2255 (`untilnow (current-time))
2256 (_ (encode-time 0
2257 (or m1 m)
2258 (or h1 h)
2259 (or d1 d)
2260 (or month1 month)
2261 (or y1 y)))))
2262 (text
2263 (pcase key
2264 ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
2265 ((or `week `thisweek) (format-time-string "week %G-W%V" start))
2266 ((or `month `thismonth) (format-time-string "%B %Y" start))
2267 ((or `year `thisyear) (format-time-string "the year %Y" start))
2268 ((or `quarter `thisq)
2269 (concat (org-count-quarter shiftedq)
2270 " quarter of " (number-to-string shiftedy)))
2271 (`interactive "(Range interactively set)")
2272 (`untilnow "now"))))
2273 (if (not as-strings) (list start end text)
2274 (let ((f (cdr org-time-stamp-formats)))
2275 (list (format-time-string f start)
2276 (format-time-string f end)
2277 text))))))
2279 (defun org-count-quarter (n)
2280 (cond
2281 ((= n 1) "1st")
2282 ((= n 2) "2nd")
2283 ((= n 3) "3rd")
2284 ((= n 4) "4th")))
2286 ;;;###autoload
2287 (defun org-clocktable-shift (dir n)
2288 "Try to shift the :block date of the clocktable at point.
2289 Point must be in the #+BEGIN: line of a clocktable, or this function
2290 will throw an error.
2291 DIR is a direction, a symbol `left', `right', `up', or `down'.
2292 Both `left' and `down' shift the block toward the past, `up' and `right'
2293 push it toward the future.
2294 N is the number of shift steps to take. The size of the step depends on
2295 the currently selected interval size."
2296 (setq n (prefix-numeric-value n))
2297 (and (memq dir '(left down)) (setq n (- n)))
2298 (save-excursion
2299 (goto-char (point-at-bol))
2300 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2301 (error "Line needs a :block definition before this command works")
2302 (let* ((b (match-beginning 1)) (e (match-end 1))
2303 (s (match-string 1))
2304 block shift ins y mw d date wp m)
2305 (cond
2306 ((equal s "yesterday") (setq s "today-1"))
2307 ((equal s "lastweek") (setq s "thisweek-1"))
2308 ((equal s "lastmonth") (setq s "thismonth-1"))
2309 ((equal s "lastyear") (setq s "thisyear-1"))
2310 ((equal s "lastq") (setq s "thisq-1")))
2312 (cond
2313 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
2314 (setq block (match-string 1 s)
2315 shift (if (match-end 2)
2316 (string-to-number (match-string 2 s))
2318 (setq shift (+ shift n))
2319 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
2320 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
2321 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2322 (setq y (string-to-number (match-string 1 s))
2323 wp (and (match-end 3) (match-string 3 s))
2324 mw (and (match-end 4) (string-to-number (match-string 4 s)))
2325 d (and (match-end 6) (string-to-number (match-string 6 s))))
2326 (cond
2327 (d (setq ins (format-time-string
2328 "%Y-%m-%d"
2329 (encode-time 0 0 0 (+ d n) m y))))
2330 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2331 (require 'cal-iso)
2332 (setq date (calendar-gregorian-from-absolute
2333 (calendar-iso-to-absolute (list (+ mw n) 1 y))))
2334 (setq ins (format-time-string
2335 "%G-W%V"
2336 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2337 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2338 (require 'cal-iso)
2339 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2340 (if (> (+ mw n) 4)
2341 (setq mw 0
2342 y (+ 1 y))
2344 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2345 (if (= (+ mw n) 0)
2346 (setq mw 5
2347 y (- y 1))
2349 (setq date (calendar-gregorian-from-absolute
2350 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
2351 (setq ins (format-time-string
2352 (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
2353 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2355 (setq ins (format-time-string
2356 "%Y-%m"
2357 (encode-time 0 0 0 1 (+ mw n) y))))
2359 (setq ins (number-to-string (+ y n))))))
2360 (t (error "Cannot shift clocktable block")))
2361 (when ins
2362 (goto-char b)
2363 (insert ins)
2364 (delete-region (point) (+ (point) (- e b)))
2365 (beginning-of-line 1)
2366 (org-update-dblock)
2367 t)))))
2369 ;;;###autoload
2370 (defun org-dblock-write:clocktable (params)
2371 "Write the standard clocktable."
2372 (setq params (org-combine-plists org-clocktable-defaults params))
2373 (catch 'exit
2374 (let* ((scope (plist-get params :scope))
2375 (files (pcase scope
2376 (`agenda
2377 (org-agenda-files t))
2378 (`agenda-with-archives
2379 (org-add-archive-files (org-agenda-files t)))
2380 (`file-with-archives
2381 (and buffer-file-name
2382 (org-add-archive-files (list buffer-file-name))))
2383 ((pred functionp) (funcall scope))
2384 ((pred consp) scope)
2385 (_ (or (buffer-file-name) (current-buffer)))))
2386 (block (plist-get params :block))
2387 (ts (plist-get params :tstart))
2388 (te (plist-get params :tend))
2389 (ws (plist-get params :wstart))
2390 (ms (plist-get params :mstart))
2391 (step (plist-get params :step))
2392 (formatter (or (plist-get params :formatter)
2393 org-clock-clocktable-formatter
2394 'org-clocktable-write-default))
2396 ;; Check if we need to do steps
2397 (when block
2398 ;; Get the range text for the header
2399 (setq cc (org-clock-special-range block nil t ws ms)
2400 ts (car cc)
2401 te (nth 1 cc)))
2402 (when step
2403 ;; Write many tables, in steps
2404 (unless (or block (and ts te))
2405 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2406 (org-clocktable-steps params)
2407 (throw 'exit nil))
2409 (org-agenda-prepare-buffers (if (consp files) files (list files)))
2411 (let ((origin (point))
2412 (tables
2413 (if (consp files)
2414 (mapcar (lambda (file)
2415 (with-current-buffer (find-buffer-visiting file)
2416 (save-excursion
2417 (save-restriction
2418 (org-clock-get-table-data file params)))))
2419 files)
2420 ;; Get the right restriction for the scope.
2421 (save-restriction
2422 (cond
2423 ((not scope)) ;use the restriction as it is now
2424 ((eq scope 'file) (widen))
2425 ((eq scope 'subtree) (org-narrow-to-subtree))
2426 ((eq scope 'tree)
2427 (while (org-up-heading-safe))
2428 (org-narrow-to-subtree))
2429 ((and (symbolp scope)
2430 (string-match "\\`tree\\([0-9]+\\)\\'"
2431 (symbol-name scope)))
2432 (let ((level (string-to-number
2433 (match-string 1 (symbol-name scope)))))
2434 (catch 'exit
2435 (while (org-up-heading-safe)
2436 (looking-at org-outline-regexp)
2437 (when (<= (org-reduced-level (funcall outline-level))
2438 level)
2439 (throw 'exit nil))))
2440 (org-narrow-to-subtree))))
2441 (list (org-clock-get-table-data nil params)))))
2442 (multifile
2443 ;; Even though `file-with-archives' can consist of
2444 ;; multiple files, we consider this is one extended file
2445 ;; instead.
2446 (and (consp files) (not (eq scope 'file-with-archives)))))
2448 (funcall formatter
2449 origin
2450 tables
2451 (org-combine-plists params `(:multifile ,multifile)))))))
2453 (defun org-clocktable-write-default (ipos tables params)
2454 "Write out a clock table at position IPOS in the current buffer.
2455 TABLES is a list of tables with clocking data as produced by
2456 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2457 from the dynamic block definition."
2458 ;; This function looks quite complicated, mainly because there are a
2459 ;; lot of options which can add or remove columns. I have massively
2460 ;; commented this function, the I hope it is understandable. If
2461 ;; someone wants to write their own special formatter, this maybe
2462 ;; much easier because there can be a fixed format with a
2463 ;; well-defined number of columns...
2464 (let* ((lang (or (plist-get params :lang) "en"))
2465 (multifile (plist-get params :multifile))
2466 (block (plist-get params :block))
2467 (sort (plist-get params :sort))
2468 (header (plist-get params :header))
2469 (link (plist-get params :link))
2470 (maxlevel (or (plist-get params :maxlevel) 3))
2471 (emph (plist-get params :emphasize))
2472 (compact? (plist-get params :compact))
2473 (narrow (or (plist-get params :narrow) (and compact? '40!)))
2474 (level? (and (not compact?) (plist-get params :level)))
2475 (timestamp (plist-get params :timestamp))
2476 (properties (plist-get params :properties))
2477 (time-columns
2478 (if (or compact? (< maxlevel 2)) 1
2479 ;; Deepest headline level is a hard limit for the number
2480 ;; of time columns.
2481 (let ((levels
2482 (cl-mapcan
2483 (lambda (table)
2484 (pcase table
2485 (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
2486 (mapcar #'car entries))))
2487 tables)))
2488 (min maxlevel
2489 (or (plist-get params :tcolumns) 100)
2490 (if (null levels) 1 (apply #'max levels))))))
2491 (indent (or compact? (plist-get params :indent)))
2492 (formula (plist-get params :formula))
2493 (case-fold-search t)
2494 (total-time (apply #'+ (mapcar #'cadr tables)))
2495 recalc narrow-cut-p)
2497 (when (and narrow (integerp narrow) link)
2498 ;; We cannot have both integer narrow and link.
2499 (message "Using hard narrowing in clocktable to allow for links")
2500 (setq narrow (intern (format "%d!" narrow))))
2502 (pcase narrow
2503 ((or `nil (pred integerp)) nil) ;nothing to do
2504 ((and (pred symbolp)
2505 (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow))))
2506 (setq narrow-cut-p t)
2507 (setq narrow (string-to-number (symbol-name narrow))))
2508 (_ (error "Invalid value %s of :narrow property in clock table" narrow)))
2510 ;; Now we need to output this table stuff.
2511 (goto-char ipos)
2513 ;; Insert the text *before* the actual table.
2514 (insert-before-markers
2515 (or header
2516 ;; Format the standard header.
2517 (format "#+CAPTION: %s %s%s\n"
2518 (org-clock--translate "Clock summary at" lang)
2519 (format-time-string (org-time-stamp-format t t))
2520 (if block
2521 (let ((range-text
2522 (nth 2 (org-clock-special-range
2523 block nil t
2524 (plist-get params :wstart)
2525 (plist-get params :mstart)))))
2526 (format ", for %s." range-text))
2527 ""))))
2529 ;; Insert the narrowing line
2530 (when (and narrow (integerp narrow) (not narrow-cut-p))
2531 (insert-before-markers
2532 "|" ;table line starter
2533 (if multifile "|" "") ;file column, maybe
2534 (if level? "|" "") ;level column, maybe
2535 (if timestamp "|" "") ;timestamp column, maybe
2536 (if properties ;properties columns, maybe
2537 (make-string (length properties) ?|)
2539 (format "<%d>| |\n" narrow))) ;headline and time columns
2541 ;; Insert the table header line
2542 (insert-before-markers
2543 "|" ;table line starter
2544 (if multifile ;file column, maybe
2545 (concat (org-clock--translate "File" lang) "|")
2547 (if level? ;level column, maybe
2548 (concat (org-clock--translate "L" lang) "|")
2550 (if timestamp ;timestamp column, maybe
2551 (concat (org-clock--translate "Timestamp" lang) "|")
2553 (if properties ;properties columns, maybe
2554 (concat (mapconcat #'identity properties "|") "|")
2556 (concat (org-clock--translate "Headline" lang)"|")
2557 (concat (org-clock--translate "Time" lang) "|")
2558 (make-string (max 0 (1- time-columns)) ?|) ;other time columns
2559 (if (eq formula '%) "%|\n" "\n"))
2561 ;; Insert the total time in the table
2562 (insert-before-markers
2563 "|-\n" ;a hline
2564 "|" ;table line starter
2565 (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "")
2566 ;file column, maybe
2567 (if level? "|" "") ;level column, maybe
2568 (if timestamp "|" "") ;timestamp column, maybe
2569 (make-string (length properties) ?|) ;properties columns, maybe
2570 (concat (format org-clock-total-time-cell-format
2571 (org-clock--translate "Total time" lang))
2572 "| ")
2573 (format org-clock-total-time-cell-format
2574 (org-duration-from-minutes (or total-time 0))) ;time
2576 (make-string (max 0 (1- time-columns)) ?|)
2577 (cond ((not (eq formula '%)) "")
2578 ((or (not total-time) (= total-time 0)) "0.0|")
2579 (t "100.0|"))
2580 "\n")
2582 ;; Now iterate over the tables and insert the data but only if any
2583 ;; time has been collected.
2584 (when (and total-time (> total-time 0))
2585 (pcase-dolist (`(,file-name ,file-time ,entries) tables)
2586 (when (or (and file-time (> file-time 0))
2587 (not (plist-get params :fileskip0)))
2588 (insert-before-markers "|-\n") ;hline at new file
2589 ;; First the file time, if we have multiple files.
2590 (when multifile
2591 ;; Summarize the time collected from this file.
2592 (insert-before-markers
2593 (format (concat "| %s %s | %s%s"
2594 (format org-clock-file-time-cell-format
2595 (org-clock--translate "File time" lang))
2596 " | *%s*|\n")
2597 (file-name-nondirectory file-name)
2598 (if level? "| " "") ;level column, maybe
2599 (if timestamp "| " "") ;timestamp column, maybe
2600 (if properties ;properties columns, maybe
2601 (make-string (length properties) ?|)
2603 (org-duration-from-minutes file-time)))) ;time
2605 ;; Get the list of node entries and iterate over it
2606 (when (> maxlevel 0)
2607 (pcase-dolist (`(,level ,headline ,ts ,time ,props) entries)
2608 (when narrow-cut-p
2609 (setq headline
2610 (if (and (string-match
2611 (format "\\`%s\\'" org-bracket-link-regexp)
2612 headline)
2613 (match-end 3))
2614 (format "[[%s][%s]]"
2615 (match-string 1 headline)
2616 (org-shorten-string (match-string 3 headline)
2617 narrow))
2618 (org-shorten-string headline narrow))))
2619 (cl-flet ((format-field (f) (format (cond ((not emph) "%s |")
2620 ((= level 1) "*%s* |")
2621 ((= level 2) "/%s/ |")
2622 (t "%s |"))
2623 f)))
2624 (insert-before-markers
2625 "|" ;start the table line
2626 (if multifile "|" "") ;free space for file name column?
2627 (if level? (format "%d|" level) "") ;level, maybe
2628 (if timestamp (concat ts "|") "") ;timestamp, maybe
2629 (if properties ;properties columns, maybe
2630 (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) ""))
2631 properties
2632 "|")
2633 "|")
2635 (if indent ;indentation
2636 (org-clocktable-indent-string level)
2638 (format-field headline)
2639 ;; Empty fields for higher levels.
2640 (make-string (max 0 (1- (min time-columns level))) ?|)
2641 (format-field (org-duration-from-minutes time))
2642 (make-string (max 0 (- time-columns level)) ?|)
2643 (if (eq formula '%)
2644 (format "%.1f |" (* 100 (/ time (float total-time))))
2646 "\n")))))))
2647 (delete-char -1)
2648 (cond
2649 ;; Possibly rescue old formula?
2650 ((or (not formula) (eq formula '%))
2651 (let ((contents (org-string-nw-p (plist-get params :content))))
2652 (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
2653 (setq recalc t)
2654 (insert "\n" (match-string 1 contents))
2655 (beginning-of-line 0))))
2656 ;; Insert specified formula line.
2657 ((stringp formula)
2658 (insert "\n#+TBLFM: " formula)
2659 (setq recalc t))
2661 (user-error "Invalid :formula parameter in clocktable")))
2662 ;; Back to beginning, align the table, recalculate if necessary.
2663 (goto-char ipos)
2664 (skip-chars-forward "^|")
2665 (org-table-align)
2666 (when org-hide-emphasis-markers
2667 ;; We need to align a second time.
2668 (org-table-align))
2669 (when sort
2670 (save-excursion
2671 (org-table-goto-line 3)
2672 (org-table-goto-column (car sort))
2673 (org-table-sort-lines nil (cdr sort))))
2674 (when recalc (org-table-recalculate 'all))
2675 total-time))
2677 (defun org-clocktable-indent-string (level)
2678 "Return indentation string according to LEVEL.
2679 LEVEL is an integer. Indent by two spaces per level above 1."
2680 (if (= level 1) ""
2681 (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
2683 (defun org-clocktable-steps (params)
2684 "Step through the range to make a number of clock tables."
2685 (let* ((p1 (copy-sequence params))
2686 (ts (plist-get p1 :tstart))
2687 (te (plist-get p1 :tend))
2688 (ws (plist-get p1 :wstart))
2689 (ms (plist-get p1 :mstart))
2690 (step0 (plist-get p1 :step))
2691 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2692 (stepskip0 (plist-get p1 :stepskip0))
2693 (block (plist-get p1 :block))
2694 cc step-time tsb)
2695 (when block
2696 (setq cc (org-clock-special-range block nil t ws ms)
2697 ts (car cc)
2698 te (nth 1 cc)))
2699 (cond
2700 ((numberp ts)
2701 ;; If ts is a number, it's an absolute day number from
2702 ;; org-agenda.
2703 (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts)))
2704 (setq ts (float-time (encode-time 0 0 0 day month year)))))
2706 (setq ts (float-time
2707 (apply #'encode-time (org-parse-time-string ts nil t))))))
2708 (cond
2709 ((numberp te)
2710 ;; Likewise for te.
2711 (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te)))
2712 (setq te (float-time (encode-time 0 0 0 day month year)))))
2714 (setq te (float-time
2715 (apply #'encode-time (org-parse-time-string te nil t))))))
2716 (setq tsb
2717 (if (eq step0 'week)
2718 (- ts (* 86400 (- (nth 6 (decode-time (seconds-to-time ts))) ws)))
2719 ts))
2720 (setq p1 (plist-put p1 :header ""))
2721 (setq p1 (plist-put p1 :step nil))
2722 (setq p1 (plist-put p1 :block nil))
2723 (while (< tsb te)
2724 (or (bolp) (insert "\n"))
2725 (setq p1 (plist-put p1 :tstart (format-time-string
2726 (org-time-stamp-format nil t)
2727 (seconds-to-time (max tsb ts)))))
2728 (setq p1 (plist-put p1 :tend (format-time-string
2729 (org-time-stamp-format nil t)
2730 (seconds-to-time (min te (setq tsb (+ tsb step)))))))
2731 (insert "\n" (if (eq step0 'day) "Daily report: "
2732 "Weekly report starting on: ")
2733 (plist-get p1 :tstart) "\n")
2734 (setq step-time (org-dblock-write:clocktable p1))
2735 (re-search-forward "^[ \t]*#\\+END:")
2736 (when (and (equal step-time 0) stepskip0)
2737 ;; Remove the empty table
2738 (delete-region (point-at-bol)
2739 (save-excursion
2740 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2741 nil t)
2742 (point))))
2743 (end-of-line 0))))
2745 (defun org-clock-get-table-data (file params)
2746 "Get the clocktable data for file FILE, with parameters PARAMS.
2747 FILE is only for identification - this function assumes that
2748 the correct buffer is current, and that the wanted restriction is
2749 in place.
2750 The return value will be a list with the file name and the total
2751 file time (in minutes) as 1st and 2nd elements. The third element
2752 of this list will be a list of headline entries. Each entry has the
2753 following structure:
2755 (LEVEL HEADLINE TIMESTAMP TIME PROPERTIES)
2757 LEVEL: The level of the headline, as an integer. This will be
2758 the reduced level, so 1,2,3,... even if only odd levels
2759 are being used.
2760 HEADLINE: The text of the headline. Depending on PARAMS, this may
2761 already be formatted like a link.
2762 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2763 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2764 in this sequence.
2765 TIME: The sum of all time spend in this tree, in minutes. This time
2766 will of cause be restricted to the time block and tags match
2767 specified in PARAMS.
2768 PROPERTIES: The list properties specified in the `:properties' parameter
2769 along with their value, as an alist following the pattern
2770 (NAME . VALUE)."
2771 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2772 (timestamp (plist-get params :timestamp))
2773 (ts (plist-get params :tstart))
2774 (te (plist-get params :tend))
2775 (ws (plist-get params :wstart))
2776 (ms (plist-get params :mstart))
2777 (block (plist-get params :block))
2778 (link (plist-get params :link))
2779 (tags (plist-get params :tags))
2780 (properties (plist-get params :properties))
2781 (inherit-property-p (plist-get params :inherit-props))
2782 (matcher (and tags (cdr (org-make-tags-matcher tags))))
2783 cc st p tbl)
2785 (setq org-clock-file-total-minutes nil)
2786 (when block
2787 (setq cc (org-clock-special-range block nil t ws ms)
2788 ts (car cc)
2789 te (nth 1 cc)))
2790 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2791 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2792 (when (and ts (listp ts))
2793 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2794 (when (and te (listp te))
2795 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2796 ;; Now the times are strings we can parse.
2797 (if ts (setq ts (org-matcher-time ts)))
2798 (if te (setq te (org-matcher-time te)))
2799 (save-excursion
2800 (org-clock-sum ts te
2801 (when matcher
2802 `(lambda ()
2803 (let* ((tags-list (org-get-tags-at))
2804 (org-scanner-tags tags-list)
2805 (org-trust-scanner-tags t))
2806 (funcall ,matcher nil tags-list nil)))))
2807 (goto-char (point-min))
2808 (setq st t)
2809 (while (or (and (bobp) (prog1 st (setq st nil))
2810 (get-text-property (point) :org-clock-minutes)
2811 (setq p (point-min)))
2812 (setq p (next-single-property-change
2813 (point) :org-clock-minutes)))
2814 (goto-char p)
2815 (let ((time (get-text-property p :org-clock-minutes)))
2816 (when (and time (> time 0) (org-at-heading-p))
2817 (let ((level (org-reduced-level (org-current-level))))
2818 (when (<= level maxlevel)
2819 (let* ((headline (org-get-heading t t t t))
2820 (hdl
2821 (if (not link) headline
2822 (let ((search
2823 (org-make-org-heading-search-string headline)))
2824 (org-make-link-string
2825 (if (not (buffer-file-name)) search
2826 (format "file:%s::%s" (buffer-file-name) search))
2827 ;; Prune statistics cookies. Replace
2828 ;; links with their description, or
2829 ;; a plain link if there is none.
2830 (org-trim
2831 (org-link-display-format
2832 (replace-regexp-in-string
2833 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
2834 headline)))))))
2835 (tsp
2836 (and timestamp
2837 (cl-some (lambda (p) (org-entry-get (point) p))
2838 '("SCHEDULED" "DEADLINE" "TIMESTAMP"
2839 "TIMESTAMP_IA"))))
2840 (props
2841 (and properties
2842 (delq nil
2843 (mapcar
2844 (lambda (p)
2845 (let ((v (org-entry-get
2846 (point) p inherit-property-p)))
2847 (and v (cons p v))))
2848 properties)))))
2849 (push (list level hdl tsp time props) tbl)))))))
2850 (list file org-clock-file-total-minutes (nreverse tbl)))))
2852 ;; Saving and loading the clock
2854 (defvar org-clock-loaded nil
2855 "Was the clock file loaded?")
2857 ;;;###autoload
2858 (defun org-clock-update-time-maybe ()
2859 "If this is a CLOCK line, update it and return t.
2860 Otherwise, return nil."
2861 (interactive)
2862 (save-excursion
2863 (beginning-of-line 1)
2864 (skip-chars-forward " \t")
2865 (when (looking-at org-clock-string)
2866 (let ((re (concat "[ \t]*" org-clock-string
2867 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2868 "\\([ \t]*=>.*\\)?\\)?"))
2869 ts te h m s neg)
2870 (cond
2871 ((not (looking-at re))
2872 nil)
2873 ((not (match-end 2))
2874 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2875 (> org-clock-marker (point))
2876 (<= org-clock-marker (point-at-eol)))
2877 ;; The clock is running here
2878 (setq org-clock-start-time
2879 (apply 'encode-time
2880 (org-parse-time-string (match-string 1))))
2881 (org-clock-update-mode-line)))
2883 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2884 (end-of-line 1)
2885 (setq ts (match-string 1)
2886 te (match-string 3))
2887 (setq s (- (float-time
2888 (apply #'encode-time (org-parse-time-string te nil t)))
2889 (float-time
2890 (apply #'encode-time (org-parse-time-string ts nil t))))
2891 neg (< s 0)
2892 s (abs s)
2893 h (floor (/ s 3600))
2894 s (- s (* 3600 h))
2895 m (floor (/ s 60))
2896 s (- s (* 60 s)))
2897 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2898 t))))))
2900 (defun org-clock-save ()
2901 "Persist various clock-related data to disk.
2902 The details of what will be saved are regulated by the variable
2903 `org-clock-persist'."
2904 (when (and org-clock-persist
2905 (or org-clock-loaded
2906 org-clock-has-been-used
2907 (not (file-exists-p org-clock-persist-file))))
2908 (with-temp-file org-clock-persist-file
2909 (insert (format ";; %s - %s at %s\n"
2910 (file-name-nondirectory org-clock-persist-file)
2911 (system-name)
2912 (format-time-string (org-time-stamp-format t))))
2913 ;; Store clock to be resumed.
2914 (when (and (memq org-clock-persist '(t clock))
2915 (let ((b (org-base-buffer (org-clocking-buffer))))
2916 (and (buffer-live-p b)
2917 (buffer-file-name b)
2918 (or (not org-clock-persist-query-save)
2919 (y-or-n-p (format "Save current clock (%s) "
2920 org-clock-heading))))))
2921 (insert
2922 (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
2923 (buffer-file-name (org-base-buffer (org-clocking-buffer)))
2924 (marker-position org-clock-marker))))
2925 ;; Store clocked task history. Tasks are stored reversed to
2926 ;; make reading simpler.
2927 (when (and (memq org-clock-persist '(t history))
2928 org-clock-history)
2929 (insert
2930 (format "(setq org-clock-stored-history '(%s))\n"
2931 (mapconcat
2932 (lambda (m)
2933 (let ((b (org-base-buffer (marker-buffer m))))
2934 (when (and (buffer-live-p b)
2935 (buffer-file-name b))
2936 (format "(%S . %d)"
2937 (buffer-file-name b)
2938 (marker-position m)))))
2939 (reverse org-clock-history)
2940 " ")))))))
2942 (defun org-clock-load ()
2943 "Load clock-related data from disk, maybe resuming a stored clock."
2944 (when (and org-clock-persist (not org-clock-loaded))
2945 (if (not (file-readable-p org-clock-persist-file))
2946 (message "Not restoring clock data; %S not found" org-clock-persist-file)
2947 (message "Restoring clock data")
2948 ;; Load history.
2949 (load-file org-clock-persist-file)
2950 (setq org-clock-loaded t)
2951 (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
2952 org-clock-stored-history)
2953 (org-clock-history-push position (find-file-noselect file)))
2954 ;; Resume clock.
2955 (pcase org-clock-stored-resume-clock
2956 (`(,(and file (pred file-exists-p)) . ,position)
2957 (with-current-buffer (find-file-noselect file)
2958 (when (or (not org-clock-persist-query-resume)
2959 (y-or-n-p (format "Resume clock (%s) "
2960 (save-excursion
2961 (goto-char position)
2962 (org-get-heading t t)))))
2963 (goto-char position)
2964 (let ((org-clock-in-resume 'auto-restart)
2965 (org-clock-auto-clock-resolution nil))
2966 (org-clock-in)
2967 (when (org-invisible-p) (org-show-context))))))
2968 (_ nil)))))
2970 ;; Suggested bindings
2971 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2973 (provide 'org-clock)
2975 ;; Local variables:
2976 ;; generated-autoload-file: "org-loaddefs.el"
2977 ;; End:
2979 ;;; org-clock.el ends here