Improve `org-fix-tags-on-the-fly'
[org-mode/org-tableheadings.git] / lisp / org-clock.el
blobeb5f923e7acfb7315e3ecc8f94b67bbf3030f54a
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 `org-effort-durations' (e.g. \"3h\"), the modified value will be
737 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 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1223 (if selected-task
1224 (setq selected-task (copy-marker selected-task))
1225 (error "Abort")))
1227 (when (equal select '(16))
1228 ;; Mark as default clocking task
1229 (org-clock-mark-default-task))
1231 (when interrupting
1232 ;; We are interrupting the clocking of a different task.
1233 ;; Save a marker to this task, so that we can go back.
1234 ;; First check if we are trying to clock into the same task!
1235 (when (save-excursion
1236 (unless selected-task
1237 (org-back-to-heading t))
1238 (and (equal (marker-buffer org-clock-hd-marker)
1239 (if selected-task
1240 (marker-buffer selected-task)
1241 (current-buffer)))
1242 (= (marker-position org-clock-hd-marker)
1243 (if selected-task
1244 (marker-position selected-task)
1245 (point)))
1246 (equal org-clock-current-task (nth 4 (org-heading-components)))))
1247 (message "Clock continues in \"%s\"" org-clock-heading)
1248 (throw 'abort nil))
1249 (move-marker org-clock-interrupted-task
1250 (marker-position org-clock-marker)
1251 (marker-buffer org-clock-marker))
1252 (let ((org-clock-clocking-in t))
1253 (org-clock-out nil t)))
1255 ;; Clock in at which position?
1256 (setq target-pos
1257 (if (and (eobp) (not (org-at-heading-p)))
1258 (point-at-bol 0)
1259 (point)))
1260 (save-excursion
1261 (when (and selected-task (marker-buffer selected-task))
1262 ;; There is a selected task, move to the correct buffer
1263 ;; and set the new target position.
1264 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1265 (setq target-pos (marker-position selected-task))
1266 (move-marker selected-task nil))
1267 (org-with-wide-buffer
1268 (goto-char target-pos)
1269 (org-back-to-heading t)
1270 (or interrupting (move-marker org-clock-interrupted-task nil))
1271 (run-hooks 'org-clock-in-prepare-hook)
1272 (org-clock-history-push)
1273 (setq org-clock-current-task (nth 4 (org-heading-components)))
1274 (cond ((functionp org-clock-in-switch-to-state)
1275 (let ((case-fold-search nil))
1276 (looking-at org-complex-heading-regexp))
1277 (let ((newstate (funcall org-clock-in-switch-to-state
1278 (match-string 2))))
1279 (when newstate (org-todo newstate))))
1280 ((and org-clock-in-switch-to-state
1281 (not (looking-at (concat org-outline-regexp "[ \t]*"
1282 org-clock-in-switch-to-state
1283 "\\>"))))
1284 (org-todo org-clock-in-switch-to-state)))
1285 (setq org-clock-heading (org-clock--mode-line-heading))
1286 (org-clock-find-position org-clock-in-resume)
1287 (cond
1288 ((and org-clock-in-resume
1289 (looking-at
1290 (concat "^[ \t]*" org-clock-string
1291 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1292 " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1293 (message "Matched %s" (match-string 1))
1294 (setq ts (concat "[" (match-string 1) "]"))
1295 (goto-char (match-end 1))
1296 (setq org-clock-start-time
1297 (apply 'encode-time
1298 (org-parse-time-string (match-string 1))))
1299 (setq org-clock-effort (org-entry-get (point) org-effort-property))
1300 (setq org-clock-total-time (org-clock-sum-current-item
1301 (org-clock-get-sum-start))))
1302 ((eq org-clock-in-resume 'auto-restart)
1303 ;; called from org-clock-load during startup,
1304 ;; do not interrupt, but warn!
1305 (message "Cannot restart clock because task does not contain unfinished clock")
1306 (ding)
1307 (sit-for 2)
1308 (throw 'abort nil))
1310 (insert-before-markers "\n")
1311 (backward-char 1)
1312 (org-indent-line)
1313 (when (and (save-excursion
1314 (end-of-line 0)
1315 (org-in-item-p)))
1316 (beginning-of-line 1)
1317 (indent-line-to (- (org-get-indentation) 2)))
1318 (insert org-clock-string " ")
1319 (setq org-clock-effort (org-entry-get (point) org-effort-property))
1320 (setq org-clock-total-time (org-clock-sum-current-item
1321 (org-clock-get-sum-start)))
1322 (setq org-clock-start-time
1323 (or (and org-clock-continuously org-clock-out-time)
1324 (and leftover
1325 (y-or-n-p
1326 (format
1327 "You stopped another clock %d mins ago; start this one from then? "
1328 (/ (- (float-time
1329 (org-current-time org-clock-rounding-minutes t))
1330 (float-time leftover))
1331 60)))
1332 leftover)
1333 start-time
1334 (org-current-time org-clock-rounding-minutes t)))
1335 (setq ts (org-insert-time-stamp org-clock-start-time
1336 'with-hm 'inactive))))
1337 (move-marker org-clock-marker (point) (buffer-base-buffer))
1338 (move-marker org-clock-hd-marker
1339 (save-excursion (org-back-to-heading t) (point))
1340 (buffer-base-buffer))
1341 (setq org-clock-has-been-used t)
1342 ;; add to mode line
1343 (when (or (eq org-clock-clocked-in-display 'mode-line)
1344 (eq org-clock-clocked-in-display 'both))
1345 (or global-mode-string (setq global-mode-string '("")))
1346 (or (memq 'org-mode-line-string global-mode-string)
1347 (setq global-mode-string
1348 (append global-mode-string '(org-mode-line-string)))))
1349 ;; add to frame title
1350 (when (or (eq org-clock-clocked-in-display 'frame-title)
1351 (eq org-clock-clocked-in-display 'both))
1352 (setq frame-title-format org-clock-frame-title-format))
1353 (org-clock-update-mode-line)
1354 (when org-clock-mode-line-timer
1355 (cancel-timer org-clock-mode-line-timer)
1356 (setq org-clock-mode-line-timer nil))
1357 (when org-clock-clocked-in-display
1358 (setq org-clock-mode-line-timer
1359 (run-with-timer org-clock-update-period
1360 org-clock-update-period
1361 'org-clock-update-mode-line)))
1362 (when org-clock-idle-timer
1363 (cancel-timer org-clock-idle-timer)
1364 (setq org-clock-idle-timer nil))
1365 (setq org-clock-idle-timer
1366 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1367 (message "Clock starts at %s - %s" ts org--msg-extra)
1368 (run-hooks 'org-clock-in-hook))))))
1370 ;;;###autoload
1371 (defun org-clock-in-last (&optional arg)
1372 "Clock in the last closed clocked item.
1373 When already clocking in, send a warning.
1374 With a universal prefix argument, select the task you want to
1375 clock in from the last clocked in tasks.
1376 With two universal prefix arguments, start clocking using the
1377 last clock-out time, if any.
1378 With three universal prefix arguments, interactively prompt
1379 for a todo state to switch to, overriding the existing value
1380 `org-clock-in-switch-to-state'."
1381 (interactive "P")
1382 (if (equal arg '(4)) (org-clock-in arg)
1383 (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
1384 (or org-clock-out-time
1385 (org-current-time org-clock-rounding-minutes t))
1386 (org-current-time org-clock-rounding-minutes t))))
1387 (if (null org-clock-history)
1388 (message "No last clock")
1389 (let ((org-clock-in-switch-to-state
1390 (if (and (not org-clock-current-task) (equal arg '(64)))
1391 (completing-read "Switch to state: "
1392 (and org-clock-history
1393 (with-current-buffer
1394 (marker-buffer (car org-clock-history))
1395 org-todo-keywords-1)))
1396 org-clock-in-switch-to-state))
1397 (already-clocking org-clock-current-task))
1398 (org-clock-clock-in (list (car org-clock-history)) nil start-time)
1399 (or already-clocking
1400 ;; Don't display a message if we are already clocking in
1401 (message "Clocking back: %s (in %s)"
1402 org-clock-current-task
1403 (buffer-name (marker-buffer org-clock-marker)))))))))
1405 (defun org-clock-mark-default-task ()
1406 "Mark current task as default task."
1407 (interactive)
1408 (save-excursion
1409 (org-back-to-heading t)
1410 (move-marker org-clock-default-task (point))))
1412 (defun org-clock-get-sum-start ()
1413 "Return the time from which clock times should be counted.
1415 This is for the currently running clock as it is displayed in the
1416 mode line. This function looks at the properties LAST_REPEAT and
1417 in particular CLOCK_MODELINE_TOTAL and the corresponding variable
1418 `org-clock-mode-line-total' and then decides which time to use.
1420 The time is always returned as UTC."
1421 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL" 'selective)
1422 (symbol-name org-clock-mode-line-total)))
1423 (lr (org-entry-get nil "LAST_REPEAT")))
1424 (cond
1425 ((equal cmt "current")
1426 (setq org--msg-extra "showing time in current clock instance")
1427 (current-time))
1428 ((equal cmt "today")
1429 (setq org--msg-extra "showing today's task time.")
1430 (let* ((dt (decode-time))
1431 (hour (nth 2 dt))
1432 (day (nth 3 dt)))
1433 (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
1434 (setf (nth 2 dt) org-extend-today-until)
1435 (apply #'encode-time (append (list 0 0) (nthcdr 2 dt)))))
1436 ((or (equal cmt "all")
1437 (and (or (not cmt) (equal cmt "auto"))
1438 (not lr)))
1439 (setq org--msg-extra "showing entire task time.")
1440 nil)
1441 ((or (equal cmt "repeat")
1442 (and (or (not cmt) (equal cmt "auto"))
1443 lr))
1444 (setq org--msg-extra "showing task time since last repeat.")
1445 (and lr (org-time-string-to-time lr)))
1446 (t nil))))
1448 (defun org-clock-find-position (find-unclosed)
1449 "Find the location where the next clock line should be inserted.
1450 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1451 line and position cursor in that line."
1452 (org-back-to-heading t)
1453 (catch 'exit
1454 (let* ((beg (line-beginning-position))
1455 (end (save-excursion (outline-next-heading) (point)))
1456 (org-clock-into-drawer (org-clock-into-drawer))
1457 (drawer (org-clock-drawer-name)))
1458 ;; Look for a running clock if FIND-UNCLOSED in non-nil.
1459 (when find-unclosed
1460 (let ((open-clock-re
1461 (concat "^[ \t]*"
1462 org-clock-string
1463 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1464 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1465 (while (re-search-forward open-clock-re end t)
1466 (let ((element (org-element-at-point)))
1467 (when (and (eq (org-element-type element) 'clock)
1468 (eq (org-element-property :status element) 'running))
1469 (beginning-of-line)
1470 (throw 'exit t))))))
1471 ;; Look for an existing clock drawer.
1472 (when drawer
1473 (goto-char beg)
1474 (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")))
1475 (while (re-search-forward drawer-re end t)
1476 (let ((element (org-element-at-point)))
1477 (when (eq (org-element-type element) 'drawer)
1478 (let ((cend (org-element-property :contents-end element)))
1479 (if (and (not org-log-states-order-reversed) cend)
1480 (goto-char cend)
1481 (forward-line))
1482 (throw 'exit t)))))))
1483 (goto-char beg)
1484 (let ((clock-re (concat "^[ \t]*" org-clock-string))
1485 (count 0)
1486 positions)
1487 ;; Count the CLOCK lines and store their positions.
1488 (save-excursion
1489 (while (re-search-forward clock-re end t)
1490 (let ((element (org-element-at-point)))
1491 (when (eq (org-element-type element) 'clock)
1492 (setq positions (cons (line-beginning-position) positions)
1493 count (1+ count))))))
1494 (cond
1495 ((null positions)
1496 ;; Skip planning line and property drawer, if any.
1497 (org-end-of-meta-data)
1498 (unless (bolp) (insert "\n"))
1499 ;; Create a new drawer if necessary.
1500 (when (and org-clock-into-drawer
1501 (or (not (wholenump org-clock-into-drawer))
1502 (< org-clock-into-drawer 2)))
1503 (let ((beg (point)))
1504 (insert ":" drawer ":\n:END:\n")
1505 (org-indent-region beg (point))
1506 (org-flag-region
1507 (line-end-position -1) (1- (point)) t 'org-hide-drawer)
1508 (forward-line -1))))
1509 ;; When a clock drawer needs to be created because of the
1510 ;; number of clock items or simply if it is missing, collect
1511 ;; all clocks in the section and wrap them within the drawer.
1512 ((if (wholenump org-clock-into-drawer)
1513 (>= (1+ count) org-clock-into-drawer)
1514 drawer)
1515 ;; Skip planning line and property drawer, if any.
1516 (org-end-of-meta-data)
1517 (let ((beg (point)))
1518 (insert
1519 (mapconcat
1520 (lambda (p)
1521 (save-excursion
1522 (goto-char p)
1523 (org-trim (delete-and-extract-region
1524 (save-excursion (skip-chars-backward " \r\t\n")
1525 (line-beginning-position 2))
1526 (line-beginning-position 2)))))
1527 positions "\n")
1528 "\n:END:\n")
1529 (let ((end (point-marker)))
1530 (goto-char beg)
1531 (save-excursion (insert ":" drawer ":\n"))
1532 (org-flag-region (line-end-position) (1- end) t 'org-hide-drawer)
1533 (org-indent-region (point) end)
1534 (forward-line)
1535 (unless org-log-states-order-reversed
1536 (goto-char end)
1537 (beginning-of-line -1))
1538 (set-marker end nil))))
1539 (org-log-states-order-reversed (goto-char (car (last positions))))
1540 (t (goto-char (car positions))))))))
1542 ;;;###autoload
1543 (defun org-clock-out (&optional switch-to-state fail-quietly at-time)
1544 "Stop the currently running clock.
1545 Throw an error if there is no running clock and FAIL-QUIETLY is nil.
1546 With a universal prefix, prompt for a state to switch the clocked out task
1547 to, overriding the existing value of `org-clock-out-switch-to-state'."
1548 (interactive "P")
1549 (catch 'exit
1550 (when (not (org-clocking-p))
1551 (setq global-mode-string
1552 (delq 'org-mode-line-string global-mode-string))
1553 (setq frame-title-format org-frame-title-format-backup)
1554 (force-mode-line-update)
1555 (if fail-quietly (throw 'exit t) (user-error "No active clock")))
1556 (let ((org-clock-out-switch-to-state
1557 (if switch-to-state
1558 (completing-read "Switch to state: "
1559 (with-current-buffer
1560 (marker-buffer org-clock-marker)
1561 org-todo-keywords-1)
1562 nil t "DONE")
1563 org-clock-out-switch-to-state))
1564 (now (org-current-time org-clock-rounding-minutes))
1565 ts te s h m remove)
1566 (setq org-clock-out-time now)
1567 (save-excursion ; Do not replace this with `with-current-buffer'.
1568 (with-no-warnings (set-buffer (org-clocking-buffer)))
1569 (save-restriction
1570 (widen)
1571 (goto-char org-clock-marker)
1572 (beginning-of-line 1)
1573 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1574 (equal (match-string 1) org-clock-string))
1575 (setq ts (match-string 2))
1576 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1577 (goto-char (match-end 0))
1578 (delete-region (point) (point-at-eol))
1579 (insert "--")
1580 (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
1581 (setq s (- (float-time
1582 (apply #'encode-time (org-parse-time-string te)))
1583 (float-time
1584 (apply #'encode-time (org-parse-time-string ts))))
1585 h (floor (/ s 3600))
1586 s (- s (* 3600 h))
1587 m (floor (/ s 60))
1588 s (- s (* 60 s)))
1589 (insert " => " (format "%2d:%02d" h m))
1590 (move-marker org-clock-marker nil)
1591 (move-marker org-clock-hd-marker nil)
1592 ;; Possibly remove zero time clocks. However, do not add
1593 ;; a note associated to the CLOCK line in this case.
1594 (cond ((and org-clock-out-remove-zero-time-clocks
1595 (= (+ h m) 0))
1596 (setq remove t)
1597 (delete-region (line-beginning-position)
1598 (line-beginning-position 2)))
1599 (org-log-note-clock-out
1600 (org-add-log-setup
1601 'clock-out nil nil nil
1602 (concat "# Task: " (org-get-heading t) "\n\n"))))
1603 (when org-clock-mode-line-timer
1604 (cancel-timer org-clock-mode-line-timer)
1605 (setq org-clock-mode-line-timer nil))
1606 (when org-clock-idle-timer
1607 (cancel-timer org-clock-idle-timer)
1608 (setq org-clock-idle-timer nil))
1609 (setq global-mode-string
1610 (delq 'org-mode-line-string global-mode-string))
1611 (setq frame-title-format org-frame-title-format-backup)
1612 (when org-clock-out-switch-to-state
1613 (save-excursion
1614 (org-back-to-heading t)
1615 (let ((org-clock-out-when-done nil))
1616 (cond
1617 ((functionp org-clock-out-switch-to-state)
1618 (let ((case-fold-search nil))
1619 (looking-at org-complex-heading-regexp))
1620 (let ((newstate (funcall org-clock-out-switch-to-state
1621 (match-string 2))))
1622 (when newstate (org-todo newstate))))
1623 ((and org-clock-out-switch-to-state
1624 (not (looking-at (concat org-outline-regexp "[ \t]*"
1625 org-clock-out-switch-to-state
1626 "\\>"))))
1627 (org-todo org-clock-out-switch-to-state))))))
1628 (force-mode-line-update)
1629 (message (concat "Clock stopped at %s after "
1630 (org-duration-from-minutes (+ (* 60 h) m)) "%s")
1631 te (if remove " => LINE REMOVED" ""))
1632 (run-hooks 'org-clock-out-hook)
1633 (unless (org-clocking-p)
1634 (setq org-clock-current-task nil)))))))
1636 (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
1638 (defun org-clock-remove-empty-clock-drawer ()
1639 "Remove empty clock drawers in current subtree."
1640 (save-excursion
1641 (org-back-to-heading t)
1642 (org-map-tree
1643 (lambda ()
1644 (let ((drawer (org-clock-drawer-name))
1645 (case-fold-search t))
1646 (when drawer
1647 (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer)))
1648 (end (save-excursion (outline-next-heading))))
1649 (while (re-search-forward re end t)
1650 (org-remove-empty-drawer-at (point))))))))))
1652 (defun org-clock-timestamps-up (&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 'up n))
1658 (defun org-clock-timestamps-down (&optional n)
1659 "Increase CLOCK timestamps at cursor.
1660 Optional argument N tells to change by that many units."
1661 (interactive "P")
1662 (org-clock-timestamps-change 'down n))
1664 (defun org-clock-timestamps-change (updown &optional n)
1665 "Change CLOCK timestamps synchronously at cursor.
1666 UPDOWN tells whether to change `up' or `down'.
1667 Optional argument N tells to change by that many units."
1668 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1669 'org-timestamp-down))
1670 (timestamp? (org-at-timestamp-p 'lax))
1671 ts1 begts1 ts2 begts2 updatets1 tdiff)
1672 (when timestamp?
1673 (save-excursion
1674 (move-beginning-of-line 1)
1675 (re-search-forward org-ts-regexp3 nil t)
1676 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1677 (when (re-search-forward org-ts-regexp3 nil t)
1678 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1679 ;; Are we on the second timestamp?
1680 (if (<= begts2 (point)) (setq updatets1 t))
1681 (if (not ts2)
1682 ;; fall back on org-timestamp-up if there is only one
1683 (funcall tschange n)
1684 (funcall tschange n)
1685 (let ((ts (if updatets1 ts2 ts1))
1686 (begts (if updatets1 begts1 begts2)))
1687 (setq tdiff
1688 (time-subtract
1689 (org-time-string-to-time org-last-changed-timestamp)
1690 (org-time-string-to-time ts)))
1691 (save-excursion
1692 (goto-char begts)
1693 (org-timestamp-change
1694 (round (/ (float-time tdiff)
1695 (pcase timestamp?
1696 (`minute 60)
1697 (`hour 3600)
1698 (`day (* 24 3600))
1699 (`month (* 24 3600 31))
1700 (`year (* 24 3600 365.2)))))
1701 timestamp? 'updown)))))))
1703 ;;;###autoload
1704 (defun org-clock-cancel ()
1705 "Cancel the running clock by removing the start timestamp."
1706 (interactive)
1707 (when (not (org-clocking-p))
1708 (setq global-mode-string
1709 (delq 'org-mode-line-string global-mode-string))
1710 (setq frame-title-format org-frame-title-format-backup)
1711 (force-mode-line-update)
1712 (error "No active clock"))
1713 (save-excursion ; Do not replace this with `with-current-buffer'.
1714 (with-no-warnings (set-buffer (org-clocking-buffer)))
1715 (goto-char org-clock-marker)
1716 (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
1717 (line-beginning-position))
1718 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1719 (org-remove-empty-drawer-at (point)))
1720 (message "Clock gone, cancel the timer anyway")
1721 (sit-for 2)))
1722 (move-marker org-clock-marker nil)
1723 (move-marker org-clock-hd-marker nil)
1724 (setq global-mode-string
1725 (delq 'org-mode-line-string global-mode-string))
1726 (setq frame-title-format org-frame-title-format-backup)
1727 (force-mode-line-update)
1728 (message "Clock canceled")
1729 (run-hooks 'org-clock-cancel-hook))
1731 ;;;###autoload
1732 (defun org-clock-goto (&optional select)
1733 "Go to the currently clocked-in entry, or to the most recently clocked one.
1734 With prefix arg SELECT, offer recently clocked tasks for selection."
1735 (interactive "@P")
1736 (let* ((recent nil)
1737 (m (cond
1738 (select
1739 (or (org-clock-select-task "Select task to go to: ")
1740 (error "No task selected")))
1741 ((org-clocking-p) org-clock-marker)
1742 ((and org-clock-goto-may-find-recent-task
1743 (car org-clock-history)
1744 (marker-buffer (car org-clock-history)))
1745 (setq recent t)
1746 (car org-clock-history))
1747 (t (error "No active or recent clock task")))))
1748 (pop-to-buffer-same-window (marker-buffer m))
1749 (if (or (< m (point-min)) (> m (point-max))) (widen))
1750 (goto-char m)
1751 (org-show-entry)
1752 (org-back-to-heading t)
1753 (recenter org-clock-goto-before-context)
1754 (org-reveal)
1755 (if recent
1756 (message "No running clock, this is the most recently clocked task"))
1757 (run-hooks 'org-clock-goto-hook)))
1759 (defvar-local org-clock-file-total-minutes nil
1760 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1762 ;;;###autoload
1763 (defun org-clock-sum-today (&optional headline-filter)
1764 "Sum the times for each subtree for today."
1765 (let ((range (org-clock-special-range 'today)))
1766 (org-clock-sum (car range) (cadr range)
1767 headline-filter :org-clock-minutes-today)))
1769 (defun org-clock-sum-custom (&optional headline-filter range propname)
1770 "Sum the times for each subtree for today."
1771 (let ((r (or (and (symbolp range) (org-clock-special-range range))
1772 (org-clock-special-range
1773 (intern (completing-read
1774 "Range: "
1775 '("today" "yesterday" "thisweek" "lastweek"
1776 "thismonth" "lastmonth" "thisyear" "lastyear"
1777 "interactive")
1778 nil t))))))
1779 (org-clock-sum (car r) (cadr r)
1780 headline-filter (or propname :org-clock-minutes-custom))))
1782 ;;;###autoload
1783 (defun org-clock-sum (&optional tstart tend headline-filter propname)
1784 "Sum the times for each subtree.
1785 Puts the resulting times in minutes as a text property on each headline.
1786 TSTART and TEND can mark a time range to be considered.
1787 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1788 each headline in the time range with point at the headline. Headlines for
1789 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1790 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1791 (org-with-silent-modifications
1792 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1793 org-clock-string
1794 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1795 (lmax 30)
1796 (ltimes (make-vector lmax 0))
1797 (level 0)
1798 (tstart (cond ((stringp tstart) (org-time-string-to-seconds tstart))
1799 ((consp tstart) (float-time tstart))
1800 (t tstart)))
1801 (tend (cond ((stringp tend) (org-time-string-to-seconds tend))
1802 ((consp tend) (float-time tend))
1803 (t tend)))
1804 (t1 0)
1805 time)
1806 (remove-text-properties (point-min) (point-max)
1807 `(,(or propname :org-clock-minutes) t
1808 :org-clock-force-headline-inclusion t))
1809 (save-excursion
1810 (goto-char (point-max))
1811 (while (re-search-backward re nil t)
1812 (cond
1813 ((match-end 2)
1814 ;; Two time stamps.
1815 (let* ((ts (float-time
1816 (apply #'encode-time
1817 (save-match-data
1818 (org-parse-time-string (match-string 2))))))
1819 (te (float-time
1820 (apply #'encode-time
1821 (org-parse-time-string (match-string 3)))))
1822 (dt (- (if tend (min te tend) te)
1823 (if tstart (max ts tstart) ts))))
1824 (when (> dt 0) (cl-incf t1 (floor (/ dt 60))))))
1825 ((match-end 4)
1826 ;; A naked time.
1827 (setq t1 (+ t1 (string-to-number (match-string 5))
1828 (* 60 (string-to-number (match-string 4))))))
1829 (t ;A headline
1830 ;; Add the currently clocking item time to the total.
1831 (when (and org-clock-report-include-clocking-task
1832 (eq (org-clocking-buffer) (current-buffer))
1833 (eq (marker-position org-clock-hd-marker) (point))
1834 tstart
1835 tend
1836 (>= (float-time org-clock-start-time) tstart)
1837 (<= (float-time org-clock-start-time) tend))
1838 (let ((time (floor (- (float-time)
1839 (float-time org-clock-start-time))
1840 60)))
1841 (setq t1 (+ t1 time))))
1842 (let* ((headline-forced
1843 (get-text-property (point)
1844 :org-clock-force-headline-inclusion))
1845 (headline-included
1846 (or (null headline-filter)
1847 (save-excursion
1848 (save-match-data (funcall headline-filter))))))
1849 (setq level (- (match-end 1) (match-beginning 1)))
1850 (when (>= level lmax)
1851 (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
1852 (when (or (> t1 0) (> (aref ltimes level) 0))
1853 (when (or headline-included headline-forced)
1854 (if headline-included
1855 (cl-loop for l from 0 to level do
1856 (aset ltimes l (+ (aref ltimes l) t1))))
1857 (setq time (aref ltimes level))
1858 (goto-char (match-beginning 0))
1859 (put-text-property (point) (point-at-eol)
1860 (or propname :org-clock-minutes) time)
1861 (when headline-filter
1862 (save-excursion
1863 (save-match-data
1864 (while (org-up-heading-safe)
1865 (put-text-property
1866 (point) (line-end-position)
1867 :org-clock-force-headline-inclusion t))))))
1868 (setq t1 0)
1869 (cl-loop for l from level to (1- lmax) do
1870 (aset ltimes l 0)))))))
1871 (setq org-clock-file-total-minutes (aref ltimes 0))))))
1873 (defun org-clock-sum-current-item (&optional tstart)
1874 "Return time, clocked on current item in total."
1875 (save-excursion
1876 (save-restriction
1877 (org-narrow-to-subtree)
1878 (org-clock-sum tstart)
1879 org-clock-file-total-minutes)))
1881 ;;;###autoload
1882 (defun org-clock-display (&optional arg)
1883 "Show subtree times in the entire buffer.
1885 By default, show the total time for the range defined in
1886 `org-clock-display-default-range'. With `\\[universal-argument]' \
1887 prefix, show
1888 the total time for today instead.
1890 With `\\[universal-argument] \\[universal-argument]' prefix, \
1891 use a custom range, entered at prompt.
1893 With `\\[universal-argument] \ \\[universal-argument] \
1894 \\[universal-argument]' prefix, display the total time in the
1895 echo area.
1897 Use `\\[org-clock-remove-overlays]' to remove the subtree times."
1898 (interactive "P")
1899 (org-clock-remove-overlays)
1900 (let* ((todayp (equal arg '(4)))
1901 (customp (member arg '((16) today yesterday
1902 thisweek lastweek thismonth
1903 lastmonth thisyear lastyear
1904 untilnow interactive)))
1905 (prop (cond ((not arg) :org-clock-minutes-default)
1906 (todayp :org-clock-minutes-today)
1907 (customp :org-clock-minutes-custom)
1908 (t :org-clock-minutes))))
1909 (cond ((not arg) (org-clock-sum-custom
1910 nil org-clock-display-default-range prop))
1911 (todayp (org-clock-sum-today))
1912 (customp (org-clock-sum-custom nil arg))
1913 (t (org-clock-sum)))
1914 (unless (equal arg '(64))
1915 (save-excursion
1916 (goto-char (point-min))
1917 (let ((p nil))
1918 (while (or (and (equal (setq p (point)) (point-min))
1919 (get-text-property p prop))
1920 (setq p (next-single-property-change (point) prop)))
1921 (goto-char p)
1922 (let ((time (get-text-property p prop)))
1923 (when time (org-clock-put-overlay time)))))
1924 ;; Arrange to remove the overlays upon next change.
1925 (when org-remove-highlights-with-change
1926 (add-hook 'before-change-functions 'org-clock-remove-overlays
1927 nil 'local))))
1928 (let* ((h (/ org-clock-file-total-minutes 60))
1929 (m (- org-clock-file-total-minutes (* 60 h))))
1930 (message (concat (format "Total file time%s: "
1931 (cond (todayp " for today")
1932 (customp " (custom)")
1933 (t "")))
1934 (org-duration-from-minutes
1935 org-clock-file-total-minutes)
1936 " (%d hours and %d minutes)")
1937 h m))))
1939 (defvar-local org-clock-overlays nil)
1941 (defun org-clock-put-overlay (time)
1942 "Put an overlays on the current line, displaying TIME.
1943 This creates a new overlay and stores it in `org-clock-overlays', so that it
1944 will be easy to remove."
1945 (let (ov tx)
1946 (beginning-of-line)
1947 (let ((case-fold-search nil))
1948 (when (looking-at org-complex-heading-regexp)
1949 (goto-char (match-beginning 4))))
1950 (setq ov (make-overlay (point) (point-at-eol))
1951 tx (concat (buffer-substring-no-properties (point) (match-end 4))
1952 (org-add-props
1953 (make-string
1954 (max 0 (- (- 60 (current-column))
1955 (- (match-end 4) (match-beginning 4))
1956 (length (org-get-at-bol 'line-prefix))))
1957 ?\·)
1958 '(face shadow))
1959 (org-add-props
1960 (format " %9s " (org-duration-from-minutes time))
1961 '(face org-clock-overlay))
1962 ""))
1963 (overlay-put ov 'display tx)
1964 (push ov org-clock-overlays)))
1966 ;;;###autoload
1967 (defun org-clock-remove-overlays (&optional _beg _end noremove)
1968 "Remove the occur highlights from the buffer.
1969 If NOREMOVE is nil, remove this function from the
1970 `before-change-functions' in the current buffer."
1971 (interactive)
1972 (unless org-inhibit-highlight-removal
1973 (mapc #'delete-overlay org-clock-overlays)
1974 (setq org-clock-overlays nil)
1975 (unless noremove
1976 (remove-hook 'before-change-functions
1977 'org-clock-remove-overlays 'local))))
1979 (defvar org-state) ;; dynamically scoped into this function
1980 (defun org-clock-out-if-current ()
1981 "Clock out if the current entry contains the running clock.
1982 This is used to stop the clock after a TODO entry is marked DONE,
1983 and is only done if the variable `org-clock-out-when-done' is not nil."
1984 (when (and (org-clocking-p)
1985 org-clock-out-when-done
1986 (marker-buffer org-clock-marker)
1987 (or (and (eq t org-clock-out-when-done)
1988 (member org-state org-done-keywords))
1989 (and (listp org-clock-out-when-done)
1990 (member org-state org-clock-out-when-done)))
1991 (equal (or (buffer-base-buffer (org-clocking-buffer))
1992 (org-clocking-buffer))
1993 (or (buffer-base-buffer (current-buffer))
1994 (current-buffer)))
1995 (< (point) org-clock-marker)
1996 (> (save-excursion (outline-next-heading) (point))
1997 org-clock-marker))
1998 ;; Clock out, but don't accept a logging message for this.
1999 (let ((org-log-note-clock-out nil)
2000 (org-clock-out-switch-to-state nil))
2001 (org-clock-out))))
2003 (add-hook 'org-after-todo-state-change-hook
2004 'org-clock-out-if-current)
2006 ;;;###autoload
2007 (defun org-clock-get-clocktable (&rest props)
2008 "Get a formatted clocktable with parameters according to PROPS.
2009 The table is created in a temporary buffer, fully formatted and
2010 fontified, and then returned."
2011 ;; Set the defaults
2012 (setq props (plist-put props :name "clocktable"))
2013 (unless (plist-member props :maxlevel)
2014 (setq props (plist-put props :maxlevel 2)))
2015 (unless (plist-member props :scope)
2016 (setq props (plist-put props :scope 'agenda)))
2017 (with-temp-buffer
2018 (org-mode)
2019 (org-create-dblock props)
2020 (org-update-dblock)
2021 (org-font-lock-ensure)
2022 (forward-line 2)
2023 (buffer-substring (point) (progn
2024 (re-search-forward "^[ \t]*#\\+END" nil t)
2025 (point-at-bol)))))
2027 ;;;###autoload
2028 (defun org-clock-report (&optional arg)
2029 "Update or create a table containing a report about clocked time.
2031 If point is inside an existing clocktable block, update it.
2032 Otherwise, insert a new one.
2034 The new table inherits its properties from the variable
2035 `org-clock-clocktable-default-properties'. The scope of the
2036 clocktable, when not specified in the previous variable, is
2037 `subtree' when the function is called from within a subtree, and
2038 `file' elsewhere.
2040 When called with a prefix argument, move to the first clock table
2041 in the buffer and update it."
2042 (interactive "P")
2043 (org-clock-remove-overlays)
2044 (when arg
2045 (org-find-dblock "clocktable")
2046 (org-show-entry))
2047 (pcase (org-in-clocktable-p)
2048 (`nil
2049 (org-create-dblock
2050 (org-combine-plists
2051 (list :scope (if (org-before-first-heading-p) 'file 'subtree))
2052 org-clock-clocktable-default-properties
2053 '(:name "clocktable"))))
2054 (start (goto-char start)))
2055 (org-update-dblock))
2057 (defun org-day-of-week (day month year)
2058 "Returns the day of the week as an integer."
2059 (nth 6
2060 (decode-time
2061 (date-to-time
2062 (format "%d-%02d-%02dT00:00:00" year month day)))))
2064 (defun org-quarter-to-date (quarter year)
2065 "Get the date (week day year) of the first day of a given quarter."
2066 (let (startday)
2067 (cond
2068 ((= quarter 1)
2069 (setq startday (org-day-of-week 1 1 year))
2070 (cond
2071 ((= startday 0)
2072 (list 52 7 (- year 1)))
2073 ((= startday 6)
2074 (list 52 6 (- year 1)))
2075 ((<= startday 4)
2076 (list 1 startday year))
2077 ((> startday 4)
2078 (list 53 startday (- year 1)))
2081 ((= quarter 2)
2082 (setq startday (org-day-of-week 1 4 year))
2083 (cond
2084 ((= startday 0)
2085 (list 13 startday year))
2086 ((< startday 4)
2087 (list 14 startday year))
2088 ((>= startday 4)
2089 (list 13 startday year))
2092 ((= quarter 3)
2093 (setq startday (org-day-of-week 1 7 year))
2094 (cond
2095 ((= startday 0)
2096 (list 26 startday year))
2097 ((< startday 4)
2098 (list 27 startday year))
2099 ((>= startday 4)
2100 (list 26 startday year))
2103 ((= quarter 4)
2104 (setq startday (org-day-of-week 1 10 year))
2105 (cond
2106 ((= startday 0)
2107 (list 39 startday year))
2108 ((<= startday 4)
2109 (list 40 startday year))
2110 ((> startday 4)
2111 (list 39 startday year)))))))
2113 (defun org-clock-special-range (key &optional time as-strings wstart mstart)
2114 "Return two times bordering a special time range.
2116 KEY is a symbol specifying the range and can be one of `today',
2117 `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
2118 `thisyear', `lastyear' or `untilnow'. If set to `interactive',
2119 user is prompted for range boundaries. It can be a string or an
2120 integer.
2122 By default, a week starts Monday 0:00 and ends Sunday 24:00. The
2123 range is determined relative to TIME, which defaults to current
2124 time.
2126 The return value is a list containing two internal times, one for
2127 the beginning of the range and one for its end, like the ones
2128 returned by `current time' or `encode-time' and a string used to
2129 display information. If AS-STRINGS is non-nil, the returned
2130 times will be formatted strings.
2132 If WSTART is non-nil, use this number to specify the starting day
2133 of a week (monday is 1). If MSTART is non-nil, use this number
2134 to specify the starting day of a month (1 is the first day of the
2135 month). If you can combine both, the month starting day will
2136 have priority."
2137 (let* ((tm (decode-time time))
2138 (m (nth 1 tm))
2139 (h (nth 2 tm))
2140 (d (nth 3 tm))
2141 (month (nth 4 tm))
2142 (y (nth 5 tm))
2143 (dow (nth 6 tm))
2144 (skey (format "%s" key))
2145 (shift 0)
2146 (q (cond ((>= month 10) 4)
2147 ((>= month 7) 3)
2148 ((>= month 4) 2)
2149 (t 1)))
2150 m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq)
2151 (cond
2152 ((string-match "\\`[0-9]+\\'" skey)
2153 (setq y (string-to-number skey) month 1 d 1 key 'year))
2154 ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey)
2155 (setq y (string-to-number (match-string 1 skey))
2156 month (string-to-number (match-string 2 skey))
2158 key 'month))
2159 ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey)
2160 (require 'cal-iso)
2161 (let ((date (calendar-gregorian-from-absolute
2162 (calendar-iso-to-absolute
2163 (list (string-to-number (match-string 2 skey))
2165 (string-to-number (match-string 1 skey)))))))
2166 (setq d (nth 1 date)
2167 month (car date)
2168 y (nth 2 date)
2169 dow 1
2170 key 'week)))
2171 ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey)
2172 (require 'cal-iso)
2173 (setq q (string-to-number (match-string 2 skey)))
2174 (let ((date (calendar-gregorian-from-absolute
2175 (calendar-iso-to-absolute
2176 (org-quarter-to-date
2177 q (string-to-number (match-string 1 skey)))))))
2178 (setq d (nth 1 date)
2179 month (car date)
2180 y (nth 2 date)
2181 dow 1
2182 key 'quarter)))
2183 ((string-match
2184 "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
2185 skey)
2186 (setq y (string-to-number (match-string 1 skey))
2187 month (string-to-number (match-string 2 skey))
2188 d (string-to-number (match-string 3 skey))
2189 key 'day))
2190 ((string-match "\\([-+][0-9]+\\)\\'" skey)
2191 (setq shift (string-to-number (match-string 1 skey))
2192 key (intern (substring skey 0 (match-beginning 1))))
2193 (when (and (memq key '(quarter thisq)) (> shift 0))
2194 (error "Looking forward with quarters isn't implemented"))))
2195 (when (= shift 0)
2196 (pcase key
2197 (`yesterday (setq key 'today shift -1))
2198 (`lastweek (setq key 'week shift -1))
2199 (`lastmonth (setq key 'month shift -1))
2200 (`lastyear (setq key 'year shift -1))
2201 (`lastq (setq key 'quarter shift -1))))
2202 ;; Prepare start and end times depending on KEY's type.
2203 (pcase key
2204 ((or `day `today) (setq m 0 h 0 h1 24 d (+ d shift)))
2205 ((or `week `thisweek)
2206 (let* ((ws (or wstart 1))
2207 (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))))
2208 (setq m 0 h 0 d (- d diff) d1 (+ 7 d))))
2209 ((or `month `thismonth)
2210 (setq h 0 m 0 d (or mstart 1) month (+ month shift) month1 (1+ month)))
2211 ((or `quarter `thisq)
2212 ;; Compute if this shift remains in this year. If not, compute
2213 ;; how many years and quarters we have to shift (via floor*) and
2214 ;; compute the shifted years, months and quarters.
2215 (cond
2216 ((< (+ (- q 1) shift) 0) ; Shift not in this year.
2217 (let* ((interval (* -1 (+ (- q 1) shift)))
2218 ;; Set tmp to ((years to shift) (quarters to shift)).
2219 (tmp (cl-floor interval 4)))
2220 ;; Due to the use of floor, 0 quarters actually means 4.
2221 (if (= 0 (nth 1 tmp))
2222 (setq shiftedy (- y (nth 0 tmp))
2223 shiftedm 1
2224 shiftedq 1)
2225 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
2226 shiftedm (- 13 (* 3 (nth 1 tmp)))
2227 shiftedq (- 5 (nth 1 tmp)))))
2228 (setq m 0 h 0 d 1 month shiftedm month1 (+ 3 shiftedm) y shiftedy))
2229 ((> (+ q shift) 0) ; Shift is within this year.
2230 (setq shiftedq (+ q shift))
2231 (setq shiftedy y)
2232 (let ((qshift (* 3 (1- (+ q shift)))))
2233 (setq m 0 h 0 d 1 month (+ 1 qshift) month1 (+ 4 qshift))))))
2234 ((or `year `thisyear)
2235 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
2236 ((or `interactive `untilnow)) ; Special cases, ignore them.
2237 (_ (user-error "No such time block %s" key)))
2238 ;; Format start and end times according to AS-STRINGS.
2239 (let* ((start (pcase key
2240 (`interactive (org-read-date nil t nil "Range start? "))
2241 ;; In theory, all clocks started after the dawn of
2242 ;; humanity.
2243 (`untilnow (encode-time 0 0 0 0 0 -50000))
2244 (_ (encode-time 0 m h d month y))))
2245 (end (pcase key
2246 (`interactive (org-read-date nil t nil "Range end? "))
2247 (`untilnow (current-time))
2248 (_ (encode-time 0
2249 (or m1 m)
2250 (or h1 h)
2251 (or d1 d)
2252 (or month1 month)
2253 (or y1 y)))))
2254 (text
2255 (pcase key
2256 ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
2257 ((or `week `thisweek) (format-time-string "week %G-W%V" start))
2258 ((or `month `thismonth) (format-time-string "%B %Y" start))
2259 ((or `year `thisyear) (format-time-string "the year %Y" start))
2260 ((or `quarter `thisq)
2261 (concat (org-count-quarter shiftedq)
2262 " quarter of " (number-to-string shiftedy)))
2263 (`interactive "(Range interactively set)")
2264 (`untilnow "now"))))
2265 (if (not as-strings) (list start end text)
2266 (let ((f (cdr org-time-stamp-formats)))
2267 (list (format-time-string f start)
2268 (format-time-string f end)
2269 text))))))
2271 (defun org-count-quarter (n)
2272 (cond
2273 ((= n 1) "1st")
2274 ((= n 2) "2nd")
2275 ((= n 3) "3rd")
2276 ((= n 4) "4th")))
2278 ;;;###autoload
2279 (defun org-clocktable-shift (dir n)
2280 "Try to shift the :block date of the clocktable at point.
2281 Point must be in the #+BEGIN: line of a clocktable, or this function
2282 will throw an error.
2283 DIR is a direction, a symbol `left', `right', `up', or `down'.
2284 Both `left' and `down' shift the block toward the past, `up' and `right'
2285 push it toward the future.
2286 N is the number of shift steps to take. The size of the step depends on
2287 the currently selected interval size."
2288 (setq n (prefix-numeric-value n))
2289 (and (memq dir '(left down)) (setq n (- n)))
2290 (save-excursion
2291 (goto-char (point-at-bol))
2292 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2293 (error "Line needs a :block definition before this command works")
2294 (let* ((b (match-beginning 1)) (e (match-end 1))
2295 (s (match-string 1))
2296 block shift ins y mw d date wp m)
2297 (cond
2298 ((equal s "yesterday") (setq s "today-1"))
2299 ((equal s "lastweek") (setq s "thisweek-1"))
2300 ((equal s "lastmonth") (setq s "thismonth-1"))
2301 ((equal s "lastyear") (setq s "thisyear-1"))
2302 ((equal s "lastq") (setq s "thisq-1")))
2304 (cond
2305 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
2306 (setq block (match-string 1 s)
2307 shift (if (match-end 2)
2308 (string-to-number (match-string 2 s))
2310 (setq shift (+ shift n))
2311 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
2312 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
2313 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2314 (setq y (string-to-number (match-string 1 s))
2315 wp (and (match-end 3) (match-string 3 s))
2316 mw (and (match-end 4) (string-to-number (match-string 4 s)))
2317 d (and (match-end 6) (string-to-number (match-string 6 s))))
2318 (cond
2319 (d (setq ins (format-time-string
2320 "%Y-%m-%d"
2321 (encode-time 0 0 0 (+ d n) m y))))
2322 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2323 (require 'cal-iso)
2324 (setq date (calendar-gregorian-from-absolute
2325 (calendar-iso-to-absolute (list (+ mw n) 1 y))))
2326 (setq ins (format-time-string
2327 "%G-W%V"
2328 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2329 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2330 (require 'cal-iso)
2331 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2332 (if (> (+ mw n) 4)
2333 (setq mw 0
2334 y (+ 1 y))
2336 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2337 (if (= (+ mw n) 0)
2338 (setq mw 5
2339 y (- y 1))
2341 (setq date (calendar-gregorian-from-absolute
2342 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
2343 (setq ins (format-time-string
2344 (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
2345 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2347 (setq ins (format-time-string
2348 "%Y-%m"
2349 (encode-time 0 0 0 1 (+ mw n) y))))
2351 (setq ins (number-to-string (+ y n))))))
2352 (t (error "Cannot shift clocktable block")))
2353 (when ins
2354 (goto-char b)
2355 (insert ins)
2356 (delete-region (point) (+ (point) (- e b)))
2357 (beginning-of-line 1)
2358 (org-update-dblock)
2359 t)))))
2361 ;;;###autoload
2362 (defun org-dblock-write:clocktable (params)
2363 "Write the standard clocktable."
2364 (setq params (org-combine-plists org-clocktable-defaults params))
2365 (catch 'exit
2366 (let* ((scope (plist-get params :scope))
2367 (files (pcase scope
2368 (`agenda
2369 (org-agenda-files t))
2370 (`agenda-with-archives
2371 (org-add-archive-files (org-agenda-files t)))
2372 (`file-with-archives
2373 (and buffer-file-name
2374 (org-add-archive-files (list buffer-file-name))))
2375 ((pred functionp) (funcall scope))
2376 ((pred consp) scope)
2377 (_ (or (buffer-file-name) (current-buffer)))))
2378 (block (plist-get params :block))
2379 (ts (plist-get params :tstart))
2380 (te (plist-get params :tend))
2381 (ws (plist-get params :wstart))
2382 (ms (plist-get params :mstart))
2383 (step (plist-get params :step))
2384 (formatter (or (plist-get params :formatter)
2385 org-clock-clocktable-formatter
2386 'org-clocktable-write-default))
2388 ;; Check if we need to do steps
2389 (when block
2390 ;; Get the range text for the header
2391 (setq cc (org-clock-special-range block nil t ws ms)
2392 ts (car cc)
2393 te (nth 1 cc)))
2394 (when step
2395 ;; Write many tables, in steps
2396 (unless (or block (and ts te))
2397 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2398 (org-clocktable-steps params)
2399 (throw 'exit nil))
2401 (org-agenda-prepare-buffers (if (consp files) files (list files)))
2403 (let ((origin (point))
2404 (tables
2405 (if (consp files)
2406 (mapcar (lambda (file)
2407 (with-current-buffer (find-buffer-visiting file)
2408 (save-excursion
2409 (save-restriction
2410 (org-clock-get-table-data file params)))))
2411 files)
2412 ;; Get the right restriction for the scope.
2413 (save-restriction
2414 (cond
2415 ((not scope)) ;use the restriction as it is now
2416 ((eq scope 'file) (widen))
2417 ((eq scope 'subtree) (org-narrow-to-subtree))
2418 ((eq scope 'tree)
2419 (while (org-up-heading-safe))
2420 (org-narrow-to-subtree))
2421 ((and (symbolp scope)
2422 (string-match "\\`tree\\([0-9]+\\)\\'"
2423 (symbol-name scope)))
2424 (let ((level (string-to-number
2425 (match-string 1 (symbol-name scope)))))
2426 (catch 'exit
2427 (while (org-up-heading-safe)
2428 (looking-at org-outline-regexp)
2429 (when (<= (org-reduced-level (funcall outline-level))
2430 level)
2431 (throw 'exit nil))))
2432 (org-narrow-to-subtree))))
2433 (list (org-clock-get-table-data nil params)))))
2434 (multifile
2435 ;; Even though `file-with-archives' can consist of
2436 ;; multiple files, we consider this is one extended file
2437 ;; instead.
2438 (and (consp files) (not (eq scope 'file-with-archives)))))
2440 (funcall formatter
2441 origin
2442 tables
2443 (org-combine-plists params `(:multifile ,multifile)))))))
2445 (defun org-clocktable-write-default (ipos tables params)
2446 "Write out a clock table at position IPOS in the current buffer.
2447 TABLES is a list of tables with clocking data as produced by
2448 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2449 from the dynamic block definition."
2450 ;; This function looks quite complicated, mainly because there are a
2451 ;; lot of options which can add or remove columns. I have massively
2452 ;; commented this function, the I hope it is understandable. If
2453 ;; someone wants to write their own special formatter, this maybe
2454 ;; much easier because there can be a fixed format with a
2455 ;; well-defined number of columns...
2456 (let* ((lang (or (plist-get params :lang) "en"))
2457 (multifile (plist-get params :multifile))
2458 (block (plist-get params :block))
2459 (sort (plist-get params :sort))
2460 (header (plist-get params :header))
2461 (link (plist-get params :link))
2462 (maxlevel (or (plist-get params :maxlevel) 3))
2463 (emph (plist-get params :emphasize))
2464 (compact? (plist-get params :compact))
2465 (narrow (or (plist-get params :narrow) (and compact? '40!)))
2466 (level? (and (not compact?) (plist-get params :level)))
2467 (timestamp (plist-get params :timestamp))
2468 (tags (plist-get params :tags))
2469 (properties (plist-get params :properties))
2470 (time-columns
2471 (if (or compact? (< maxlevel 2)) 1
2472 ;; Deepest headline level is a hard limit for the number
2473 ;; of time columns.
2474 (let ((levels
2475 (cl-mapcan
2476 (lambda (table)
2477 (pcase table
2478 (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
2479 (mapcar #'car entries))))
2480 tables)))
2481 (min maxlevel
2482 (or (plist-get params :tcolumns) 100)
2483 (if (null levels) 1 (apply #'max levels))))))
2484 (indent (or compact? (plist-get params :indent)))
2485 (formula (plist-get params :formula))
2486 (case-fold-search t)
2487 (total-time (apply #'+ (mapcar #'cadr tables)))
2488 recalc narrow-cut-p)
2490 (when (and narrow (integerp narrow) link)
2491 ;; We cannot have both integer narrow and link.
2492 (message "Using hard narrowing in clocktable to allow for links")
2493 (setq narrow (intern (format "%d!" narrow))))
2495 (pcase narrow
2496 ((or `nil (pred integerp)) nil) ;nothing to do
2497 ((and (pred symbolp)
2498 (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow))))
2499 (setq narrow-cut-p t)
2500 (setq narrow (string-to-number (symbol-name narrow))))
2501 (_ (error "Invalid value %s of :narrow property in clock table" narrow)))
2503 ;; Now we need to output this table stuff.
2504 (goto-char ipos)
2506 ;; Insert the text *before* the actual table.
2507 (insert-before-markers
2508 (or header
2509 ;; Format the standard header.
2510 (format "#+CAPTION: %s %s%s\n"
2511 (org-clock--translate "Clock summary at" lang)
2512 (format-time-string (org-time-stamp-format t t))
2513 (if block
2514 (let ((range-text
2515 (nth 2 (org-clock-special-range
2516 block nil t
2517 (plist-get params :wstart)
2518 (plist-get params :mstart)))))
2519 (format ", for %s." range-text))
2520 ""))))
2522 ;; Insert the narrowing line
2523 (when (and narrow (integerp narrow) (not narrow-cut-p))
2524 (insert-before-markers
2525 "|" ;table line starter
2526 (if multifile "|" "") ;file column, maybe
2527 (if level? "|" "") ;level column, maybe
2528 (if timestamp "|" "") ;timestamp column, maybe
2529 (if tags "|" "") ;tags columns, maybe
2530 (if properties ;properties columns, maybe
2531 (make-string (length properties) ?|)
2533 (format "<%d>| |\n" narrow))) ;headline and time columns
2535 ;; Insert the table header line
2536 (insert-before-markers
2537 "|" ;table line starter
2538 (if multifile ;file column, maybe
2539 (concat (org-clock--translate "File" lang) "|")
2541 (if level? ;level column, maybe
2542 (concat (org-clock--translate "L" lang) "|")
2544 (if timestamp ;timestamp column, maybe
2545 (concat (org-clock--translate "Timestamp" lang) "|")
2547 (if tags "Tags |" "") ;tags columns, maybe
2549 (if properties ;properties columns, maybe
2550 (concat (mapconcat #'identity properties "|") "|")
2552 (concat (org-clock--translate "Headline" lang)"|")
2553 (concat (org-clock--translate "Time" lang) "|")
2554 (make-string (max 0 (1- time-columns)) ?|) ;other time columns
2555 (if (eq formula '%) "%|\n" "\n"))
2557 ;; Insert the total time in the table
2558 (insert-before-markers
2559 "|-\n" ;a hline
2560 "|" ;table line starter
2561 (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "")
2562 ;file column, maybe
2563 (if level? "|" "") ;level column, maybe
2564 (if timestamp "|" "") ;timestamp column, maybe
2565 (if tags "|" "") ;timestamp column, maybe
2566 (make-string (length properties) ?|) ;properties columns, maybe
2567 (concat (format org-clock-total-time-cell-format
2568 (org-clock--translate "Total time" lang))
2569 "| ")
2570 (format org-clock-total-time-cell-format
2571 (org-duration-from-minutes (or total-time 0))) ;time
2573 (make-string (max 0 (1- time-columns)) ?|)
2574 (cond ((not (eq formula '%)) "")
2575 ((or (not total-time) (= total-time 0)) "0.0|")
2576 (t "100.0|"))
2577 "\n")
2579 ;; Now iterate over the tables and insert the data but only if any
2580 ;; time has been collected.
2581 (when (and total-time (> total-time 0))
2582 (pcase-dolist (`(,file-name ,file-time ,entries) tables)
2583 (when (or (and file-time (> file-time 0))
2584 (not (plist-get params :fileskip0)))
2585 (insert-before-markers "|-\n") ;hline at new file
2586 ;; First the file time, if we have multiple files.
2587 (when multifile
2588 ;; Summarize the time collected from this file.
2589 (insert-before-markers
2590 (format (concat "| %s %s | %s%s"
2591 (format org-clock-file-time-cell-format
2592 (org-clock--translate "File time" lang))
2593 " | *%s*|\n")
2594 (file-name-nondirectory file-name)
2595 (if level? "| " "") ;level column, maybe
2596 (if timestamp "| " "") ;timestamp column, maybe
2597 (if tags "| " "") ;tags column, maybe
2598 (if properties ;properties columns, maybe
2599 (make-string (length properties) ?|)
2601 (org-duration-from-minutes file-time)))) ;time
2603 ;; Get the list of node entries and iterate over it
2604 (when (> maxlevel 0)
2605 (pcase-dolist (`(,level ,headline ,tgs ,ts ,time ,props) entries)
2606 (when narrow-cut-p
2607 (setq headline
2608 (if (and (string-match
2609 (format "\\`%s\\'" org-bracket-link-regexp)
2610 headline)
2611 (match-end 3))
2612 (format "[[%s][%s]]"
2613 (match-string 1 headline)
2614 (org-shorten-string (match-string 3 headline)
2615 narrow))
2616 (org-shorten-string headline narrow))))
2617 (cl-flet ((format-field (f) (format (cond ((not emph) "%s |")
2618 ((= level 1) "*%s* |")
2619 ((= level 2) "/%s/ |")
2620 (t "%s |"))
2621 f)))
2622 (insert-before-markers
2623 "|" ;start the table line
2624 (if multifile "|" "") ;free space for file name column?
2625 (if level? (format "%d|" level) "") ;level, maybe
2626 (if timestamp (concat ts "|") "") ;timestamp, maybe
2627 (if tags (concat (mapconcat #'identity tgs ", ") "|") "") ;tags, maybe
2628 (if properties ;properties columns, maybe
2629 (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) ""))
2630 properties
2631 "|")
2632 "|")
2634 (if indent ;indentation
2635 (org-clocktable-indent-string level)
2637 (format-field headline)
2638 ;; Empty fields for higher levels.
2639 (make-string (max 0 (1- (min time-columns level))) ?|)
2640 (format-field (org-duration-from-minutes time))
2641 (make-string (max 0 (- time-columns level)) ?|)
2642 (if (eq formula '%)
2643 (format "%.1f |" (* 100 (/ time (float total-time))))
2645 "\n")))))))
2646 (delete-char -1)
2647 (cond
2648 ;; Possibly rescue old formula?
2649 ((or (not formula) (eq formula '%))
2650 (let ((contents (org-string-nw-p (plist-get params :content))))
2651 (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
2652 (setq recalc t)
2653 (insert "\n" (match-string 1 contents))
2654 (beginning-of-line 0))))
2655 ;; Insert specified formula line.
2656 ((stringp formula)
2657 (insert "\n#+TBLFM: " formula)
2658 (setq recalc t))
2660 (user-error "Invalid :formula parameter in clocktable")))
2661 ;; Back to beginning, align the table, recalculate if necessary.
2662 (goto-char ipos)
2663 (skip-chars-forward "^|")
2664 (org-table-align)
2665 (when org-hide-emphasis-markers
2666 ;; We need to align a second time.
2667 (org-table-align))
2668 (when sort
2669 (save-excursion
2670 (org-table-goto-line 3)
2671 (org-table-goto-column (car sort))
2672 (org-table-sort-lines nil (cdr sort))))
2673 (when recalc (org-table-recalculate 'all))
2674 total-time))
2676 (defun org-clocktable-indent-string (level)
2677 "Return indentation string according to LEVEL.
2678 LEVEL is an integer. Indent by two spaces per level above 1."
2679 (if (= level 1) ""
2680 (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
2682 (defun org-clocktable-steps (params)
2683 "Step through the range to make a number of clock tables."
2684 (let* ((ts (plist-get params :tstart))
2685 (te (plist-get params :tend))
2686 (ws (plist-get params :wstart))
2687 (ms (plist-get params :mstart))
2688 (step0 (plist-get params :step))
2689 (step (cdr (assq step0 '((day . 86400) (week . 604800)))))
2690 (stepskip0 (plist-get params :stepskip0))
2691 (block (plist-get params :block))
2692 cc tsb)
2693 (when block
2694 (setq cc (org-clock-special-range block nil t ws ms)
2695 ts (car cc)
2696 te (nth 1 cc)))
2697 (cond
2698 ((numberp ts)
2699 ;; If ts is a number, it's an absolute day number from
2700 ;; org-agenda.
2701 (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts)))
2702 (setq ts (float-time (encode-time 0 0 0 day month year)))))
2704 (setq ts (float-time (apply #'encode-time (org-parse-time-string ts))))))
2705 (cond
2706 ((numberp te)
2707 ;; Likewise for te.
2708 (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te)))
2709 (setq te (float-time (encode-time 0 0 0 day month year)))))
2711 (setq te (float-time (apply #'encode-time (org-parse-time-string te))))))
2712 (setq tsb
2713 (if (eq step0 'week)
2714 (let ((dow (nth 6 (decode-time (seconds-to-time ts)))))
2715 (if (<= dow ws) ts
2716 (- ts (* 86400 (- dow ws)))))
2717 ts))
2718 (while (< tsb te)
2719 (unless (bolp) (insert "\n"))
2720 (let ((start-time (seconds-to-time (max tsb ts))))
2721 (cl-incf tsb (let ((dow (nth 6 (decode-time (seconds-to-time tsb)))))
2722 (if (or (eq step0 'day)
2723 (= dow ws))
2724 step
2725 (* 86400 (- ws dow)))))
2726 (insert "\n"
2727 (if (eq step0 'day) "Daily report: "
2728 "Weekly report starting on: ")
2729 (format-time-string (org-time-stamp-format nil t) start-time)
2730 "\n")
2731 (let ((table-begin (line-beginning-position 0))
2732 (step-time
2733 (org-dblock-write:clocktable
2734 (org-combine-plists
2735 params
2736 (list
2737 :header "" :step nil :block nil
2738 :tstart (format-time-string (org-time-stamp-format t t)
2739 start-time)
2740 :tend (format-time-string (org-time-stamp-format t t)
2741 (seconds-to-time (min te tsb))))))))
2742 (re-search-forward "^[ \t]*#\\+END:")
2743 (when (and stepskip0 (equal step-time 0))
2744 ;; Remove the empty table
2745 (delete-region (line-beginning-position) table-begin))))
2746 (end-of-line 0))))
2748 (defun org-clock-get-table-data (file params)
2749 "Get the clocktable data for file FILE, with parameters PARAMS.
2750 FILE is only for identification - this function assumes that
2751 the correct buffer is current, and that the wanted restriction is
2752 in place.
2753 The return value will be a list with the file name and the total
2754 file time (in minutes) as 1st and 2nd elements. The third element
2755 of this list will be a list of headline entries. Each entry has the
2756 following structure:
2758 (LEVEL HEADLINE TAGS TIMESTAMP TIME PROPERTIES)
2760 LEVEL: The level of the headline, as an integer. This will be
2761 the reduced level, so 1,2,3,... even if only odd levels
2762 are being used.
2763 HEADLINE: The text of the headline. Depending on PARAMS, this may
2764 already be formatted like a link.
2765 TAGS: The list of tags of the headline.
2766 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2767 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2768 in this sequence.
2769 TIME: The sum of all time spend in this tree, in minutes. This time
2770 will of cause be restricted to the time block and tags match
2771 specified in PARAMS.
2772 PROPERTIES: The list properties specified in the `:properties' parameter
2773 along with their value, as an alist following the pattern
2774 (NAME . VALUE)."
2775 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2776 (timestamp (plist-get params :timestamp))
2777 (ts (plist-get params :tstart))
2778 (te (plist-get params :tend))
2779 (ws (plist-get params :wstart))
2780 (ms (plist-get params :mstart))
2781 (block (plist-get params :block))
2782 (link (plist-get params :link))
2783 (tags (plist-get params :tags))
2784 (match (plist-get params :match))
2785 (properties (plist-get params :properties))
2786 (inherit-property-p (plist-get params :inherit-props))
2787 (matcher (and match (cdr (org-make-tags-matcher match))))
2788 cc st p tbl)
2790 (setq org-clock-file-total-minutes nil)
2791 (when block
2792 (setq cc (org-clock-special-range block nil t ws ms)
2793 ts (car cc)
2794 te (nth 1 cc)))
2795 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2796 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2797 (when (and ts (listp ts))
2798 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2799 (when (and te (listp te))
2800 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2801 ;; Now the times are strings we can parse.
2802 (if ts (setq ts (org-matcher-time ts)))
2803 (if te (setq te (org-matcher-time te)))
2804 (save-excursion
2805 (org-clock-sum ts te
2806 (when matcher
2807 `(lambda ()
2808 (let* ((todo (org-get-todo-state))
2809 (tags-list (org-get-tags))
2810 (org-scanner-tags tags-list)
2811 (org-trust-scanner-tags t))
2812 (funcall ,matcher todo tags-list nil)))))
2813 (goto-char (point-min))
2814 (setq st t)
2815 (while (or (and (bobp) (prog1 st (setq st nil))
2816 (get-text-property (point) :org-clock-minutes)
2817 (setq p (point-min)))
2818 (setq p (next-single-property-change
2819 (point) :org-clock-minutes)))
2820 (goto-char p)
2821 (let ((time (get-text-property p :org-clock-minutes)))
2822 (when (and time (> time 0) (org-at-heading-p))
2823 (let ((level (org-reduced-level (org-current-level))))
2824 (when (<= level maxlevel)
2825 (let* ((headline (org-get-heading t t t t))
2826 (hdl
2827 (if (not link) headline
2828 (let ((search
2829 (org-make-org-heading-search-string headline)))
2830 (org-make-link-string
2831 (if (not (buffer-file-name)) search
2832 (format "file:%s::%s" (buffer-file-name) search))
2833 ;; Prune statistics cookies. Replace
2834 ;; links with their description, or
2835 ;; a plain link if there is none.
2836 (org-trim
2837 (org-link-display-format
2838 (replace-regexp-in-string
2839 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
2840 headline)))))))
2841 (tgs (and tags (org-get-tags)))
2842 (tsp
2843 (and timestamp
2844 (cl-some (lambda (p) (org-entry-get (point) p))
2845 '("SCHEDULED" "DEADLINE" "TIMESTAMP"
2846 "TIMESTAMP_IA"))))
2847 (props
2848 (and properties
2849 (delq nil
2850 (mapcar
2851 (lambda (p)
2852 (let ((v (org-entry-get
2853 (point) p inherit-property-p)))
2854 (and v (cons p v))))
2855 properties)))))
2856 (push (list level hdl tgs tsp time props) tbl)))))))
2857 (list file org-clock-file-total-minutes (nreverse tbl)))))
2859 ;; Saving and loading the clock
2861 (defvar org-clock-loaded nil
2862 "Was the clock file loaded?")
2864 ;;;###autoload
2865 (defun org-clock-update-time-maybe ()
2866 "If this is a CLOCK line, update it and return t.
2867 Otherwise, return nil."
2868 (interactive)
2869 (save-excursion
2870 (beginning-of-line 1)
2871 (skip-chars-forward " \t")
2872 (when (looking-at org-clock-string)
2873 (let ((re (concat "[ \t]*" org-clock-string
2874 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2875 "\\([ \t]*=>.*\\)?\\)?"))
2876 ts te h m s neg)
2877 (cond
2878 ((not (looking-at re))
2879 nil)
2880 ((not (match-end 2))
2881 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2882 (> org-clock-marker (point))
2883 (<= org-clock-marker (point-at-eol)))
2884 ;; The clock is running here
2885 (setq org-clock-start-time
2886 (apply 'encode-time
2887 (org-parse-time-string (match-string 1))))
2888 (org-clock-update-mode-line)))
2890 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2891 (end-of-line 1)
2892 (setq ts (match-string 1)
2893 te (match-string 3))
2894 (setq s (- (float-time
2895 (apply #'encode-time (org-parse-time-string te)))
2896 (float-time
2897 (apply #'encode-time (org-parse-time-string ts))))
2898 neg (< s 0)
2899 s (abs s)
2900 h (floor (/ s 3600))
2901 s (- s (* 3600 h))
2902 m (floor (/ s 60))
2903 s (- s (* 60 s)))
2904 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2905 t))))))
2907 (defun org-clock-save ()
2908 "Persist various clock-related data to disk.
2909 The details of what will be saved are regulated by the variable
2910 `org-clock-persist'."
2911 (when (and org-clock-persist
2912 (or org-clock-loaded
2913 org-clock-has-been-used
2914 (not (file-exists-p org-clock-persist-file))))
2915 (with-temp-file org-clock-persist-file
2916 (insert (format ";; %s - %s at %s\n"
2917 (file-name-nondirectory org-clock-persist-file)
2918 (system-name)
2919 (format-time-string (org-time-stamp-format t))))
2920 ;; Store clock to be resumed.
2921 (when (and (memq org-clock-persist '(t clock))
2922 (let ((b (org-base-buffer (org-clocking-buffer))))
2923 (and (buffer-live-p b)
2924 (buffer-file-name b)
2925 (or (not org-clock-persist-query-save)
2926 (y-or-n-p (format "Save current clock (%s) "
2927 org-clock-heading))))))
2928 (insert
2929 (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
2930 (buffer-file-name (org-base-buffer (org-clocking-buffer)))
2931 (marker-position org-clock-marker))))
2932 ;; Store clocked task history. Tasks are stored reversed to
2933 ;; make reading simpler.
2934 (when (and (memq org-clock-persist '(t history))
2935 org-clock-history)
2936 (insert
2937 (format "(setq org-clock-stored-history '(%s))\n"
2938 (mapconcat
2939 (lambda (m)
2940 (let ((b (org-base-buffer (marker-buffer m))))
2941 (when (and (buffer-live-p b)
2942 (buffer-file-name b))
2943 (format "(%S . %d)"
2944 (buffer-file-name b)
2945 (marker-position m)))))
2946 (reverse org-clock-history)
2947 " ")))))))
2949 (defun org-clock-load ()
2950 "Load clock-related data from disk, maybe resuming a stored clock."
2951 (when (and org-clock-persist (not org-clock-loaded))
2952 (if (not (file-readable-p org-clock-persist-file))
2953 (message "Not restoring clock data; %S not found" org-clock-persist-file)
2954 (message "Restoring clock data")
2955 ;; Load history.
2956 (load-file org-clock-persist-file)
2957 (setq org-clock-loaded t)
2958 (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
2959 org-clock-stored-history)
2960 (org-clock-history-push position (find-file-noselect file)))
2961 ;; Resume clock.
2962 (pcase org-clock-stored-resume-clock
2963 (`(,(and file (pred file-exists-p)) . ,position)
2964 (with-current-buffer (find-file-noselect file)
2965 (when (or (not org-clock-persist-query-resume)
2966 (y-or-n-p (format "Resume clock (%s) "
2967 (save-excursion
2968 (goto-char position)
2969 (org-get-heading t t)))))
2970 (goto-char position)
2971 (let ((org-clock-in-resume 'auto-restart)
2972 (org-clock-auto-clock-resolution nil))
2973 (org-clock-in)
2974 (when (org-invisible-p) (org-show-context))))))
2975 (_ nil)))))
2977 ;; Suggested bindings
2978 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2980 (provide 'org-clock)
2982 ;; Local variables:
2983 ;; generated-autoload-file: "org-loaddefs.el"
2984 ;; coding: utf-8
2985 ;; End:
2987 ;;; org-clock.el ends here