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