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