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