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