org-capture: Refresh clock mode line when finalizing capture
[org-mode/org-tableheadings.git] / lisp / org-clock.el
blob9fa136d03012425cdb3d92b4f32c6af6758dac93
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 (goto-char beg)
1505 (org-flag-drawer t)
1506 (forward-line))))
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-drawer t)
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 (org-cycle-hide-drawers 'children)
1752 (recenter org-clock-goto-before-context)
1753 (org-reveal)
1754 (if recent
1755 (message "No running clock, this is the most recently clocked task"))
1756 (run-hooks 'org-clock-goto-hook)))
1758 (defvar-local org-clock-file-total-minutes nil
1759 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1761 ;;;###autoload
1762 (defun org-clock-sum-today (&optional headline-filter)
1763 "Sum the times for each subtree for today."
1764 (let ((range (org-clock-special-range 'today)))
1765 (org-clock-sum (car range) (cadr range)
1766 headline-filter :org-clock-minutes-today)))
1768 (defun org-clock-sum-custom (&optional headline-filter range propname)
1769 "Sum the times for each subtree for today."
1770 (let ((r (or (and (symbolp range) (org-clock-special-range range))
1771 (org-clock-special-range
1772 (intern (completing-read
1773 "Range: "
1774 '("today" "yesterday" "thisweek" "lastweek"
1775 "thismonth" "lastmonth" "thisyear" "lastyear"
1776 "interactive")
1777 nil t))))))
1778 (org-clock-sum (car r) (cadr r)
1779 headline-filter (or propname :org-clock-minutes-custom))))
1781 ;;;###autoload
1782 (defun org-clock-sum (&optional tstart tend headline-filter propname)
1783 "Sum the times for each subtree.
1784 Puts the resulting times in minutes as a text property on each headline.
1785 TSTART and TEND can mark a time range to be considered.
1786 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1787 each headline in the time range with point at the headline. Headlines for
1788 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1789 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1790 (org-with-silent-modifications
1791 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1792 org-clock-string
1793 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1794 (lmax 30)
1795 (ltimes (make-vector lmax 0))
1796 (level 0)
1797 (tstart (cond ((stringp tstart) (org-time-string-to-seconds tstart))
1798 ((consp tstart) (float-time tstart))
1799 (t tstart)))
1800 (tend (cond ((stringp tend) (org-time-string-to-seconds tend))
1801 ((consp tend) (float-time tend))
1802 (t tend)))
1803 (t1 0)
1804 time)
1805 (remove-text-properties (point-min) (point-max)
1806 `(,(or propname :org-clock-minutes) t
1807 :org-clock-force-headline-inclusion t))
1808 (save-excursion
1809 (goto-char (point-max))
1810 (while (re-search-backward re nil t)
1811 (cond
1812 ((match-end 2)
1813 ;; Two time stamps.
1814 (let* ((ts (float-time
1815 (apply #'encode-time
1816 (save-match-data
1817 (org-parse-time-string (match-string 2))))))
1818 (te (float-time
1819 (apply #'encode-time
1820 (org-parse-time-string (match-string 3)))))
1821 (dt (- (if tend (min te tend) te)
1822 (if tstart (max ts tstart) ts))))
1823 (when (> dt 0) (cl-incf t1 (floor (/ dt 60))))))
1824 ((match-end 4)
1825 ;; A naked time.
1826 (setq t1 (+ t1 (string-to-number (match-string 5))
1827 (* 60 (string-to-number (match-string 4))))))
1828 (t ;A headline
1829 ;; Add the currently clocking item time to the total.
1830 (when (and org-clock-report-include-clocking-task
1831 (eq (org-clocking-buffer) (current-buffer))
1832 (eq (marker-position org-clock-hd-marker) (point))
1833 tstart
1834 tend
1835 (>= (float-time org-clock-start-time) tstart)
1836 (<= (float-time org-clock-start-time) tend))
1837 (let ((time (floor (- (float-time)
1838 (float-time org-clock-start-time))
1839 60)))
1840 (setq t1 (+ t1 time))))
1841 (let* ((headline-forced
1842 (get-text-property (point)
1843 :org-clock-force-headline-inclusion))
1844 (headline-included
1845 (or (null headline-filter)
1846 (save-excursion
1847 (save-match-data (funcall headline-filter))))))
1848 (setq level (- (match-end 1) (match-beginning 1)))
1849 (when (>= level lmax)
1850 (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
1851 (when (or (> t1 0) (> (aref ltimes level) 0))
1852 (when (or headline-included headline-forced)
1853 (if headline-included
1854 (cl-loop for l from 0 to level do
1855 (aset ltimes l (+ (aref ltimes l) t1))))
1856 (setq time (aref ltimes level))
1857 (goto-char (match-beginning 0))
1858 (put-text-property (point) (point-at-eol)
1859 (or propname :org-clock-minutes) time)
1860 (when headline-filter
1861 (save-excursion
1862 (save-match-data
1863 (while (org-up-heading-safe)
1864 (put-text-property
1865 (point) (line-end-position)
1866 :org-clock-force-headline-inclusion t))))))
1867 (setq t1 0)
1868 (cl-loop for l from level to (1- lmax) do
1869 (aset ltimes l 0)))))))
1870 (setq org-clock-file-total-minutes (aref ltimes 0))))))
1872 (defun org-clock-sum-current-item (&optional tstart)
1873 "Return time, clocked on current item in total."
1874 (save-excursion
1875 (save-restriction
1876 (org-narrow-to-subtree)
1877 (org-clock-sum tstart)
1878 org-clock-file-total-minutes)))
1880 ;;;###autoload
1881 (defun org-clock-display (&optional arg)
1882 "Show subtree times in the entire buffer.
1884 By default, show the total time for the range defined in
1885 `org-clock-display-default-range'. With `\\[universal-argument]' \
1886 prefix, show
1887 the total time for today instead.
1889 With `\\[universal-argument] \\[universal-argument]' prefix, \
1890 use a custom range, entered at prompt.
1892 With `\\[universal-argument] \ \\[universal-argument] \
1893 \\[universal-argument]' prefix, display the total time in the
1894 echo area.
1896 Use `\\[org-clock-remove-overlays]' to remove the subtree times."
1897 (interactive "P")
1898 (org-clock-remove-overlays)
1899 (let* ((todayp (equal arg '(4)))
1900 (customp (member arg '((16) today yesterday
1901 thisweek lastweek thismonth
1902 lastmonth thisyear lastyear
1903 untilnow interactive)))
1904 (prop (cond ((not arg) :org-clock-minutes-default)
1905 (todayp :org-clock-minutes-today)
1906 (customp :org-clock-minutes-custom)
1907 (t :org-clock-minutes))))
1908 (cond ((not arg) (org-clock-sum-custom
1909 nil org-clock-display-default-range prop))
1910 (todayp (org-clock-sum-today))
1911 (customp (org-clock-sum-custom nil arg))
1912 (t (org-clock-sum)))
1913 (unless (equal arg '(64))
1914 (save-excursion
1915 (goto-char (point-min))
1916 (let ((p nil))
1917 (while (or (and (equal (setq p (point)) (point-min))
1918 (get-text-property p prop))
1919 (setq p (next-single-property-change (point) prop)))
1920 (goto-char p)
1921 (let ((time (get-text-property p prop)))
1922 (when time (org-clock-put-overlay time)))))
1923 ;; Arrange to remove the overlays upon next change.
1924 (when org-remove-highlights-with-change
1925 (add-hook 'before-change-functions 'org-clock-remove-overlays
1926 nil 'local))))
1927 (let* ((h (/ org-clock-file-total-minutes 60))
1928 (m (- org-clock-file-total-minutes (* 60 h))))
1929 (message (concat (format "Total file time%s: "
1930 (cond (todayp " for today")
1931 (customp " (custom)")
1932 (t "")))
1933 (org-duration-from-minutes
1934 org-clock-file-total-minutes)
1935 " (%d hours and %d minutes)")
1936 h m))))
1938 (defvar-local org-clock-overlays nil)
1940 (defun org-clock-put-overlay (time)
1941 "Put an overlays on the current line, displaying TIME.
1942 This creates a new overlay and stores it in `org-clock-overlays', so that it
1943 will be easy to remove."
1944 (let (ov tx)
1945 (beginning-of-line)
1946 (let ((case-fold-search nil))
1947 (when (looking-at org-complex-heading-regexp)
1948 (goto-char (match-beginning 4))))
1949 (setq ov (make-overlay (point) (point-at-eol))
1950 tx (concat (buffer-substring-no-properties (point) (match-end 4))
1951 (org-add-props
1952 (make-string
1953 (max 0 (- (- 60 (current-column))
1954 (- (match-end 4) (match-beginning 4))
1955 (length (org-get-at-bol 'line-prefix))))
1956 ?\·)
1957 '(face shadow))
1958 (org-add-props
1959 (format " %9s " (org-duration-from-minutes time))
1960 '(face org-clock-overlay))
1961 ""))
1962 (overlay-put ov 'display tx)
1963 (push ov org-clock-overlays)))
1965 ;;;###autoload
1966 (defun org-clock-remove-overlays (&optional _beg _end noremove)
1967 "Remove the occur highlights from the buffer.
1968 If NOREMOVE is nil, remove this function from the
1969 `before-change-functions' in the current buffer."
1970 (interactive)
1971 (unless org-inhibit-highlight-removal
1972 (mapc #'delete-overlay org-clock-overlays)
1973 (setq org-clock-overlays nil)
1974 (unless noremove
1975 (remove-hook 'before-change-functions
1976 'org-clock-remove-overlays 'local))))
1978 (defvar org-state) ;; dynamically scoped into this function
1979 (defun org-clock-out-if-current ()
1980 "Clock out if the current entry contains the running clock.
1981 This is used to stop the clock after a TODO entry is marked DONE,
1982 and is only done if the variable `org-clock-out-when-done' is not nil."
1983 (when (and (org-clocking-p)
1984 org-clock-out-when-done
1985 (marker-buffer org-clock-marker)
1986 (or (and (eq t org-clock-out-when-done)
1987 (member org-state org-done-keywords))
1988 (and (listp org-clock-out-when-done)
1989 (member org-state org-clock-out-when-done)))
1990 (equal (or (buffer-base-buffer (org-clocking-buffer))
1991 (org-clocking-buffer))
1992 (or (buffer-base-buffer (current-buffer))
1993 (current-buffer)))
1994 (< (point) org-clock-marker)
1995 (> (save-excursion (outline-next-heading) (point))
1996 org-clock-marker))
1997 ;; Clock out, but don't accept a logging message for this.
1998 (let ((org-log-note-clock-out nil)
1999 (org-clock-out-switch-to-state nil))
2000 (org-clock-out))))
2002 (add-hook 'org-after-todo-state-change-hook
2003 'org-clock-out-if-current)
2005 ;;;###autoload
2006 (defun org-clock-get-clocktable (&rest props)
2007 "Get a formatted clocktable with parameters according to PROPS.
2008 The table is created in a temporary buffer, fully formatted and
2009 fontified, and then returned."
2010 ;; Set the defaults
2011 (setq props (plist-put props :name "clocktable"))
2012 (unless (plist-member props :maxlevel)
2013 (setq props (plist-put props :maxlevel 2)))
2014 (unless (plist-member props :scope)
2015 (setq props (plist-put props :scope 'agenda)))
2016 (with-temp-buffer
2017 (org-mode)
2018 (org-create-dblock props)
2019 (org-update-dblock)
2020 (org-font-lock-ensure)
2021 (forward-line 2)
2022 (buffer-substring (point) (progn
2023 (re-search-forward "^[ \t]*#\\+END" nil t)
2024 (point-at-bol)))))
2026 ;;;###autoload
2027 (defun org-clock-report (&optional arg)
2028 "Update or create a table containing a report about clocked time.
2030 If point is inside an existing clocktable block, update it.
2031 Otherwise, insert a new one.
2033 The new table inherits its properties from the variable
2034 `org-clock-clocktable-default-properties'. The scope of the
2035 clocktable, when not specified in the previous variable, is
2036 `subtree' when the function is called from within a subtree, and
2037 `file' elsewhere.
2039 When called with a prefix argument, move to the first clock table
2040 in the buffer and update it."
2041 (interactive "P")
2042 (org-clock-remove-overlays)
2043 (when arg
2044 (org-find-dblock "clocktable")
2045 (org-show-entry))
2046 (pcase (org-in-clocktable-p)
2047 (`nil
2048 (org-create-dblock
2049 (org-combine-plists
2050 (list :scope (if (org-before-first-heading-p) 'file 'subtree))
2051 org-clock-clocktable-default-properties
2052 '(:name "clocktable"))))
2053 (start (goto-char start)))
2054 (org-update-dblock))
2056 (defun org-day-of-week (day month year)
2057 "Returns the day of the week as an integer."
2058 (nth 6
2059 (decode-time
2060 (date-to-time
2061 (format "%d-%02d-%02dT00:00:00" year month day)))))
2063 (defun org-quarter-to-date (quarter year)
2064 "Get the date (week day year) of the first day of a given quarter."
2065 (let (startday)
2066 (cond
2067 ((= quarter 1)
2068 (setq startday (org-day-of-week 1 1 year))
2069 (cond
2070 ((= startday 0)
2071 (list 52 7 (- year 1)))
2072 ((= startday 6)
2073 (list 52 6 (- year 1)))
2074 ((<= startday 4)
2075 (list 1 startday year))
2076 ((> startday 4)
2077 (list 53 startday (- year 1)))
2080 ((= quarter 2)
2081 (setq startday (org-day-of-week 1 4 year))
2082 (cond
2083 ((= startday 0)
2084 (list 13 startday year))
2085 ((< startday 4)
2086 (list 14 startday year))
2087 ((>= startday 4)
2088 (list 13 startday year))
2091 ((= quarter 3)
2092 (setq startday (org-day-of-week 1 7 year))
2093 (cond
2094 ((= startday 0)
2095 (list 26 startday year))
2096 ((< startday 4)
2097 (list 27 startday year))
2098 ((>= startday 4)
2099 (list 26 startday year))
2102 ((= quarter 4)
2103 (setq startday (org-day-of-week 1 10 year))
2104 (cond
2105 ((= startday 0)
2106 (list 39 startday year))
2107 ((<= startday 4)
2108 (list 40 startday year))
2109 ((> startday 4)
2110 (list 39 startday year)))))))
2112 (defun org-clock-special-range (key &optional time as-strings wstart mstart)
2113 "Return two times bordering a special time range.
2115 KEY is a symbol specifying the range and can be one of `today',
2116 `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
2117 `thisyear', `lastyear' or `untilnow'. If set to `interactive',
2118 user is prompted for range boundaries. It can be a string or an
2119 integer.
2121 By default, a week starts Monday 0:00 and ends Sunday 24:00. The
2122 range is determined relative to TIME, which defaults to current
2123 time.
2125 The return value is a list containing two internal times, one for
2126 the beginning of the range and one for its end, like the ones
2127 returned by `current time' or `encode-time' and a string used to
2128 display information. If AS-STRINGS is non-nil, the returned
2129 times will be formatted strings.
2131 If WSTART is non-nil, use this number to specify the starting day
2132 of a week (monday is 1). If MSTART is non-nil, use this number
2133 to specify the starting day of a month (1 is the first day of the
2134 month). If you can combine both, the month starting day will
2135 have priority."
2136 (let* ((tm (decode-time time))
2137 (m (nth 1 tm))
2138 (h (nth 2 tm))
2139 (d (nth 3 tm))
2140 (month (nth 4 tm))
2141 (y (nth 5 tm))
2142 (dow (nth 6 tm))
2143 (skey (format "%s" key))
2144 (shift 0)
2145 (q (cond ((>= month 10) 4)
2146 ((>= month 7) 3)
2147 ((>= month 4) 2)
2148 (t 1)))
2149 m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq)
2150 (cond
2151 ((string-match "\\`[0-9]+\\'" skey)
2152 (setq y (string-to-number skey) month 1 d 1 key 'year))
2153 ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey)
2154 (setq y (string-to-number (match-string 1 skey))
2155 month (string-to-number (match-string 2 skey))
2157 key 'month))
2158 ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey)
2159 (require 'cal-iso)
2160 (let ((date (calendar-gregorian-from-absolute
2161 (calendar-iso-to-absolute
2162 (list (string-to-number (match-string 2 skey))
2164 (string-to-number (match-string 1 skey)))))))
2165 (setq d (nth 1 date)
2166 month (car date)
2167 y (nth 2 date)
2168 dow 1
2169 key 'week)))
2170 ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey)
2171 (require 'cal-iso)
2172 (setq q (string-to-number (match-string 2 skey)))
2173 (let ((date (calendar-gregorian-from-absolute
2174 (calendar-iso-to-absolute
2175 (org-quarter-to-date
2176 q (string-to-number (match-string 1 skey)))))))
2177 (setq d (nth 1 date)
2178 month (car date)
2179 y (nth 2 date)
2180 dow 1
2181 key 'quarter)))
2182 ((string-match
2183 "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
2184 skey)
2185 (setq y (string-to-number (match-string 1 skey))
2186 month (string-to-number (match-string 2 skey))
2187 d (string-to-number (match-string 3 skey))
2188 key 'day))
2189 ((string-match "\\([-+][0-9]+\\)\\'" skey)
2190 (setq shift (string-to-number (match-string 1 skey))
2191 key (intern (substring skey 0 (match-beginning 1))))
2192 (when (and (memq key '(quarter thisq)) (> shift 0))
2193 (error "Looking forward with quarters isn't implemented"))))
2194 (when (= shift 0)
2195 (pcase key
2196 (`yesterday (setq key 'today shift -1))
2197 (`lastweek (setq key 'week shift -1))
2198 (`lastmonth (setq key 'month shift -1))
2199 (`lastyear (setq key 'year shift -1))
2200 (`lastq (setq key 'quarter shift -1))))
2201 ;; Prepare start and end times depending on KEY's type.
2202 (pcase key
2203 ((or `day `today) (setq m 0 h 0 h1 24 d (+ d shift)))
2204 ((or `week `thisweek)
2205 (let* ((ws (or wstart 1))
2206 (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))))
2207 (setq m 0 h 0 d (- d diff) d1 (+ 7 d))))
2208 ((or `month `thismonth)
2209 (setq h 0 m 0 d (or mstart 1) month (+ month shift) month1 (1+ month)))
2210 ((or `quarter `thisq)
2211 ;; Compute if this shift remains in this year. If not, compute
2212 ;; how many years and quarters we have to shift (via floor*) and
2213 ;; compute the shifted years, months and quarters.
2214 (cond
2215 ((< (+ (- q 1) shift) 0) ; Shift not in this year.
2216 (let* ((interval (* -1 (+ (- q 1) shift)))
2217 ;; Set tmp to ((years to shift) (quarters to shift)).
2218 (tmp (cl-floor interval 4)))
2219 ;; Due to the use of floor, 0 quarters actually means 4.
2220 (if (= 0 (nth 1 tmp))
2221 (setq shiftedy (- y (nth 0 tmp))
2222 shiftedm 1
2223 shiftedq 1)
2224 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
2225 shiftedm (- 13 (* 3 (nth 1 tmp)))
2226 shiftedq (- 5 (nth 1 tmp)))))
2227 (setq m 0 h 0 d 1 month shiftedm month1 (+ 3 shiftedm) y shiftedy))
2228 ((> (+ q shift) 0) ; Shift is within this year.
2229 (setq shiftedq (+ q shift))
2230 (setq shiftedy y)
2231 (let ((qshift (* 3 (1- (+ q shift)))))
2232 (setq m 0 h 0 d 1 month (+ 1 qshift) month1 (+ 4 qshift))))))
2233 ((or `year `thisyear)
2234 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
2235 ((or `interactive `untilnow)) ; Special cases, ignore them.
2236 (_ (user-error "No such time block %s" key)))
2237 ;; Format start and end times according to AS-STRINGS.
2238 (let* ((start (pcase key
2239 (`interactive (org-read-date nil t nil "Range start? "))
2240 ;; In theory, all clocks started after the dawn of
2241 ;; humanity.
2242 (`untilnow (encode-time 0 0 0 0 0 -50000))
2243 (_ (encode-time 0 m h d month y))))
2244 (end (pcase key
2245 (`interactive (org-read-date nil t nil "Range end? "))
2246 (`untilnow (current-time))
2247 (_ (encode-time 0
2248 (or m1 m)
2249 (or h1 h)
2250 (or d1 d)
2251 (or month1 month)
2252 (or y1 y)))))
2253 (text
2254 (pcase key
2255 ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
2256 ((or `week `thisweek) (format-time-string "week %G-W%V" start))
2257 ((or `month `thismonth) (format-time-string "%B %Y" start))
2258 ((or `year `thisyear) (format-time-string "the year %Y" start))
2259 ((or `quarter `thisq)
2260 (concat (org-count-quarter shiftedq)
2261 " quarter of " (number-to-string shiftedy)))
2262 (`interactive "(Range interactively set)")
2263 (`untilnow "now"))))
2264 (if (not as-strings) (list start end text)
2265 (let ((f (cdr org-time-stamp-formats)))
2266 (list (format-time-string f start)
2267 (format-time-string f end)
2268 text))))))
2270 (defun org-count-quarter (n)
2271 (cond
2272 ((= n 1) "1st")
2273 ((= n 2) "2nd")
2274 ((= n 3) "3rd")
2275 ((= n 4) "4th")))
2277 ;;;###autoload
2278 (defun org-clocktable-shift (dir n)
2279 "Try to shift the :block date of the clocktable at point.
2280 Point must be in the #+BEGIN: line of a clocktable, or this function
2281 will throw an error.
2282 DIR is a direction, a symbol `left', `right', `up', or `down'.
2283 Both `left' and `down' shift the block toward the past, `up' and `right'
2284 push it toward the future.
2285 N is the number of shift steps to take. The size of the step depends on
2286 the currently selected interval size."
2287 (setq n (prefix-numeric-value n))
2288 (and (memq dir '(left down)) (setq n (- n)))
2289 (save-excursion
2290 (goto-char (point-at-bol))
2291 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2292 (error "Line needs a :block definition before this command works")
2293 (let* ((b (match-beginning 1)) (e (match-end 1))
2294 (s (match-string 1))
2295 block shift ins y mw d date wp m)
2296 (cond
2297 ((equal s "yesterday") (setq s "today-1"))
2298 ((equal s "lastweek") (setq s "thisweek-1"))
2299 ((equal s "lastmonth") (setq s "thismonth-1"))
2300 ((equal s "lastyear") (setq s "thisyear-1"))
2301 ((equal s "lastq") (setq s "thisq-1")))
2303 (cond
2304 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
2305 (setq block (match-string 1 s)
2306 shift (if (match-end 2)
2307 (string-to-number (match-string 2 s))
2309 (setq shift (+ shift n))
2310 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
2311 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
2312 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2313 (setq y (string-to-number (match-string 1 s))
2314 wp (and (match-end 3) (match-string 3 s))
2315 mw (and (match-end 4) (string-to-number (match-string 4 s)))
2316 d (and (match-end 6) (string-to-number (match-string 6 s))))
2317 (cond
2318 (d (setq ins (format-time-string
2319 "%Y-%m-%d"
2320 (encode-time 0 0 0 (+ d n) m y))))
2321 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2322 (require 'cal-iso)
2323 (setq date (calendar-gregorian-from-absolute
2324 (calendar-iso-to-absolute (list (+ mw n) 1 y))))
2325 (setq ins (format-time-string
2326 "%G-W%V"
2327 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2328 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2329 (require 'cal-iso)
2330 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2331 (if (> (+ mw n) 4)
2332 (setq mw 0
2333 y (+ 1 y))
2335 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2336 (if (= (+ mw n) 0)
2337 (setq mw 5
2338 y (- y 1))
2340 (setq date (calendar-gregorian-from-absolute
2341 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
2342 (setq ins (format-time-string
2343 (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
2344 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2346 (setq ins (format-time-string
2347 "%Y-%m"
2348 (encode-time 0 0 0 1 (+ mw n) y))))
2350 (setq ins (number-to-string (+ y n))))))
2351 (t (error "Cannot shift clocktable block")))
2352 (when ins
2353 (goto-char b)
2354 (insert ins)
2355 (delete-region (point) (+ (point) (- e b)))
2356 (beginning-of-line 1)
2357 (org-update-dblock)
2358 t)))))
2360 ;;;###autoload
2361 (defun org-dblock-write:clocktable (params)
2362 "Write the standard clocktable."
2363 (setq params (org-combine-plists org-clocktable-defaults params))
2364 (catch 'exit
2365 (let* ((scope (plist-get params :scope))
2366 (files (pcase scope
2367 (`agenda
2368 (org-agenda-files t))
2369 (`agenda-with-archives
2370 (org-add-archive-files (org-agenda-files t)))
2371 (`file-with-archives
2372 (and buffer-file-name
2373 (org-add-archive-files (list buffer-file-name))))
2374 ((pred functionp) (funcall scope))
2375 ((pred consp) scope)
2376 (_ (or (buffer-file-name) (current-buffer)))))
2377 (block (plist-get params :block))
2378 (ts (plist-get params :tstart))
2379 (te (plist-get params :tend))
2380 (ws (plist-get params :wstart))
2381 (ms (plist-get params :mstart))
2382 (step (plist-get params :step))
2383 (formatter (or (plist-get params :formatter)
2384 org-clock-clocktable-formatter
2385 'org-clocktable-write-default))
2387 ;; Check if we need to do steps
2388 (when block
2389 ;; Get the range text for the header
2390 (setq cc (org-clock-special-range block nil t ws ms)
2391 ts (car cc)
2392 te (nth 1 cc)))
2393 (when step
2394 ;; Write many tables, in steps
2395 (unless (or block (and ts te))
2396 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2397 (org-clocktable-steps params)
2398 (throw 'exit nil))
2400 (org-agenda-prepare-buffers (if (consp files) files (list files)))
2402 (let ((origin (point))
2403 (tables
2404 (if (consp files)
2405 (mapcar (lambda (file)
2406 (with-current-buffer (find-buffer-visiting file)
2407 (save-excursion
2408 (save-restriction
2409 (org-clock-get-table-data file params)))))
2410 files)
2411 ;; Get the right restriction for the scope.
2412 (save-restriction
2413 (cond
2414 ((not scope)) ;use the restriction as it is now
2415 ((eq scope 'file) (widen))
2416 ((eq scope 'subtree) (org-narrow-to-subtree))
2417 ((eq scope 'tree)
2418 (while (org-up-heading-safe))
2419 (org-narrow-to-subtree))
2420 ((and (symbolp scope)
2421 (string-match "\\`tree\\([0-9]+\\)\\'"
2422 (symbol-name scope)))
2423 (let ((level (string-to-number
2424 (match-string 1 (symbol-name scope)))))
2425 (catch 'exit
2426 (while (org-up-heading-safe)
2427 (looking-at org-outline-regexp)
2428 (when (<= (org-reduced-level (funcall outline-level))
2429 level)
2430 (throw 'exit nil))))
2431 (org-narrow-to-subtree))))
2432 (list (org-clock-get-table-data nil params)))))
2433 (multifile
2434 ;; Even though `file-with-archives' can consist of
2435 ;; multiple files, we consider this is one extended file
2436 ;; instead.
2437 (and (consp files) (not (eq scope 'file-with-archives)))))
2439 (funcall formatter
2440 origin
2441 tables
2442 (org-combine-plists params `(:multifile ,multifile)))))))
2444 (defun org-clocktable-write-default (ipos tables params)
2445 "Write out a clock table at position IPOS in the current buffer.
2446 TABLES is a list of tables with clocking data as produced by
2447 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2448 from the dynamic block definition."
2449 ;; This function looks quite complicated, mainly because there are a
2450 ;; lot of options which can add or remove columns. I have massively
2451 ;; commented this function, the I hope it is understandable. If
2452 ;; someone wants to write their own special formatter, this maybe
2453 ;; much easier because there can be a fixed format with a
2454 ;; well-defined number of columns...
2455 (let* ((lang (or (plist-get params :lang) "en"))
2456 (multifile (plist-get params :multifile))
2457 (block (plist-get params :block))
2458 (sort (plist-get params :sort))
2459 (header (plist-get params :header))
2460 (link (plist-get params :link))
2461 (maxlevel (or (plist-get params :maxlevel) 3))
2462 (emph (plist-get params :emphasize))
2463 (compact? (plist-get params :compact))
2464 (narrow (or (plist-get params :narrow) (and compact? '40!)))
2465 (level? (and (not compact?) (plist-get params :level)))
2466 (timestamp (plist-get params :timestamp))
2467 (properties (plist-get params :properties))
2468 (time-columns
2469 (if (or compact? (< maxlevel 2)) 1
2470 ;; Deepest headline level is a hard limit for the number
2471 ;; of time columns.
2472 (let ((levels
2473 (cl-mapcan
2474 (lambda (table)
2475 (pcase table
2476 (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
2477 (mapcar #'car entries))))
2478 tables)))
2479 (min maxlevel
2480 (or (plist-get params :tcolumns) 100)
2481 (if (null levels) 1 (apply #'max levels))))))
2482 (indent (or compact? (plist-get params :indent)))
2483 (formula (plist-get params :formula))
2484 (case-fold-search t)
2485 (total-time (apply #'+ (mapcar #'cadr tables)))
2486 recalc narrow-cut-p)
2488 (when (and narrow (integerp narrow) link)
2489 ;; We cannot have both integer narrow and link.
2490 (message "Using hard narrowing in clocktable to allow for links")
2491 (setq narrow (intern (format "%d!" narrow))))
2493 (pcase narrow
2494 ((or `nil (pred integerp)) nil) ;nothing to do
2495 ((and (pred symbolp)
2496 (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow))))
2497 (setq narrow-cut-p t)
2498 (setq narrow (string-to-number (symbol-name narrow))))
2499 (_ (error "Invalid value %s of :narrow property in clock table" narrow)))
2501 ;; Now we need to output this table stuff.
2502 (goto-char ipos)
2504 ;; Insert the text *before* the actual table.
2505 (insert-before-markers
2506 (or header
2507 ;; Format the standard header.
2508 (format "#+CAPTION: %s %s%s\n"
2509 (org-clock--translate "Clock summary at" lang)
2510 (format-time-string (org-time-stamp-format t t))
2511 (if block
2512 (let ((range-text
2513 (nth 2 (org-clock-special-range
2514 block nil t
2515 (plist-get params :wstart)
2516 (plist-get params :mstart)))))
2517 (format ", for %s." range-text))
2518 ""))))
2520 ;; Insert the narrowing line
2521 (when (and narrow (integerp narrow) (not narrow-cut-p))
2522 (insert-before-markers
2523 "|" ;table line starter
2524 (if multifile "|" "") ;file column, maybe
2525 (if level? "|" "") ;level column, maybe
2526 (if timestamp "|" "") ;timestamp column, maybe
2527 (if properties ;properties columns, maybe
2528 (make-string (length properties) ?|)
2530 (format "<%d>| |\n" narrow))) ;headline and time columns
2532 ;; Insert the table header line
2533 (insert-before-markers
2534 "|" ;table line starter
2535 (if multifile ;file column, maybe
2536 (concat (org-clock--translate "File" lang) "|")
2538 (if level? ;level column, maybe
2539 (concat (org-clock--translate "L" lang) "|")
2541 (if timestamp ;timestamp column, maybe
2542 (concat (org-clock--translate "Timestamp" lang) "|")
2544 (if properties ;properties columns, maybe
2545 (concat (mapconcat #'identity properties "|") "|")
2547 (concat (org-clock--translate "Headline" lang)"|")
2548 (concat (org-clock--translate "Time" lang) "|")
2549 (make-string (max 0 (1- time-columns)) ?|) ;other time columns
2550 (if (eq formula '%) "%|\n" "\n"))
2552 ;; Insert the total time in the table
2553 (insert-before-markers
2554 "|-\n" ;a hline
2555 "|" ;table line starter
2556 (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "")
2557 ;file column, maybe
2558 (if level? "|" "") ;level column, maybe
2559 (if timestamp "|" "") ;timestamp column, maybe
2560 (make-string (length properties) ?|) ;properties columns, maybe
2561 (concat (format org-clock-total-time-cell-format
2562 (org-clock--translate "Total time" lang))
2563 "| ")
2564 (format org-clock-total-time-cell-format
2565 (org-duration-from-minutes (or total-time 0))) ;time
2567 (make-string (max 0 (1- time-columns)) ?|)
2568 (cond ((not (eq formula '%)) "")
2569 ((or (not total-time) (= total-time 0)) "0.0|")
2570 (t "100.0|"))
2571 "\n")
2573 ;; Now iterate over the tables and insert the data but only if any
2574 ;; time has been collected.
2575 (when (and total-time (> total-time 0))
2576 (pcase-dolist (`(,file-name ,file-time ,entries) tables)
2577 (when (or (and file-time (> file-time 0))
2578 (not (plist-get params :fileskip0)))
2579 (insert-before-markers "|-\n") ;hline at new file
2580 ;; First the file time, if we have multiple files.
2581 (when multifile
2582 ;; Summarize the time collected from this file.
2583 (insert-before-markers
2584 (format (concat "| %s %s | %s%s"
2585 (format org-clock-file-time-cell-format
2586 (org-clock--translate "File time" lang))
2587 " | *%s*|\n")
2588 (file-name-nondirectory file-name)
2589 (if level? "| " "") ;level column, maybe
2590 (if timestamp "| " "") ;timestamp column, maybe
2591 (if properties ;properties columns, maybe
2592 (make-string (length properties) ?|)
2594 (org-duration-from-minutes file-time)))) ;time
2596 ;; Get the list of node entries and iterate over it
2597 (when (> maxlevel 0)
2598 (pcase-dolist (`(,level ,headline ,ts ,time ,props) entries)
2599 (when narrow-cut-p
2600 (setq headline
2601 (if (and (string-match
2602 (format "\\`%s\\'" org-bracket-link-regexp)
2603 headline)
2604 (match-end 3))
2605 (format "[[%s][%s]]"
2606 (match-string 1 headline)
2607 (org-shorten-string (match-string 3 headline)
2608 narrow))
2609 (org-shorten-string headline narrow))))
2610 (cl-flet ((format-field (f) (format (cond ((not emph) "%s |")
2611 ((= level 1) "*%s* |")
2612 ((= level 2) "/%s/ |")
2613 (t "%s |"))
2614 f)))
2615 (insert-before-markers
2616 "|" ;start the table line
2617 (if multifile "|" "") ;free space for file name column?
2618 (if level? (format "%d|" level) "") ;level, maybe
2619 (if timestamp (concat ts "|") "") ;timestamp, maybe
2620 (if properties ;properties columns, maybe
2621 (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) ""))
2622 properties
2623 "|")
2624 "|")
2626 (if indent ;indentation
2627 (org-clocktable-indent-string level)
2629 (format-field headline)
2630 ;; Empty fields for higher levels.
2631 (make-string (max 0 (1- (min time-columns level))) ?|)
2632 (format-field (org-duration-from-minutes time))
2633 (make-string (max 0 (- time-columns level)) ?|)
2634 (if (eq formula '%)
2635 (format "%.1f |" (* 100 (/ time (float total-time))))
2637 "\n")))))))
2638 (delete-char -1)
2639 (cond
2640 ;; Possibly rescue old formula?
2641 ((or (not formula) (eq formula '%))
2642 (let ((contents (org-string-nw-p (plist-get params :content))))
2643 (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
2644 (setq recalc t)
2645 (insert "\n" (match-string 1 contents))
2646 (beginning-of-line 0))))
2647 ;; Insert specified formula line.
2648 ((stringp formula)
2649 (insert "\n#+TBLFM: " formula)
2650 (setq recalc t))
2652 (user-error "Invalid :formula parameter in clocktable")))
2653 ;; Back to beginning, align the table, recalculate if necessary.
2654 (goto-char ipos)
2655 (skip-chars-forward "^|")
2656 (org-table-align)
2657 (when org-hide-emphasis-markers
2658 ;; We need to align a second time.
2659 (org-table-align))
2660 (when sort
2661 (save-excursion
2662 (org-table-goto-line 3)
2663 (org-table-goto-column (car sort))
2664 (org-table-sort-lines nil (cdr sort))))
2665 (when recalc (org-table-recalculate 'all))
2666 total-time))
2668 (defun org-clocktable-indent-string (level)
2669 "Return indentation string according to LEVEL.
2670 LEVEL is an integer. Indent by two spaces per level above 1."
2671 (if (= level 1) ""
2672 (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
2674 (defun org-clocktable-steps (params)
2675 "Step through the range to make a number of clock tables."
2676 (let* ((ts (plist-get params :tstart))
2677 (te (plist-get params :tend))
2678 (ws (plist-get params :wstart))
2679 (ms (plist-get params :mstart))
2680 (step0 (plist-get params :step))
2681 (step (cdr (assq step0 '((day . 86400) (week . 604800)))))
2682 (stepskip0 (plist-get params :stepskip0))
2683 (block (plist-get params :block))
2684 cc tsb)
2685 (when block
2686 (setq cc (org-clock-special-range block nil t ws ms)
2687 ts (car cc)
2688 te (nth 1 cc)))
2689 (cond
2690 ((numberp ts)
2691 ;; If ts is a number, it's an absolute day number from
2692 ;; org-agenda.
2693 (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute ts)))
2694 (setq ts (float-time (encode-time 0 0 0 day month year)))))
2696 (setq ts (float-time (apply #'encode-time (org-parse-time-string ts))))))
2697 (cond
2698 ((numberp te)
2699 ;; Likewise for te.
2700 (pcase-let ((`(,month ,day ,year) (calendar-gregorian-from-absolute te)))
2701 (setq te (float-time (encode-time 0 0 0 day month year)))))
2703 (setq te (float-time (apply #'encode-time (org-parse-time-string te))))))
2704 (setq tsb
2705 (if (eq step0 'week)
2706 (let ((dow (nth 6 (decode-time (seconds-to-time ts)))))
2707 (if (<= dow ws) ts
2708 (- ts (* 86400 (- dow ws)))))
2709 ts))
2710 (while (< tsb te)
2711 (unless (bolp) (insert "\n"))
2712 (let ((start-time (seconds-to-time (max tsb ts))))
2713 (cl-incf tsb (let ((dow (nth 6 (decode-time (seconds-to-time tsb)))))
2714 (if (or (eq step0 'day)
2715 (= dow ws))
2716 step
2717 (* 86400 (- ws dow)))))
2718 (insert "\n"
2719 (if (eq step0 'day) "Daily report: "
2720 "Weekly report starting on: ")
2721 (format-time-string (org-time-stamp-format nil t) start-time)
2722 "\n")
2723 (let ((table-begin (line-beginning-position 0))
2724 (step-time
2725 (org-dblock-write:clocktable
2726 (org-combine-plists
2727 params
2728 (list
2729 :header "" :step nil :block nil
2730 :tstart (format-time-string (org-time-stamp-format t t)
2731 start-time)
2732 :tend (format-time-string (org-time-stamp-format t t)
2733 (seconds-to-time (min te tsb))))))))
2734 (re-search-forward "^[ \t]*#\\+END:")
2735 (when (and stepskip0 (equal step-time 0))
2736 ;; Remove the empty table
2737 (delete-region (line-beginning-position) table-begin))))
2738 (end-of-line 0))))
2740 (defun org-clock-get-table-data (file params)
2741 "Get the clocktable data for file FILE, with parameters PARAMS.
2742 FILE is only for identification - this function assumes that
2743 the correct buffer is current, and that the wanted restriction is
2744 in place.
2745 The return value will be a list with the file name and the total
2746 file time (in minutes) as 1st and 2nd elements. The third element
2747 of this list will be a list of headline entries. Each entry has the
2748 following structure:
2750 (LEVEL HEADLINE TIMESTAMP TIME PROPERTIES)
2752 LEVEL: The level of the headline, as an integer. This will be
2753 the reduced level, so 1,2,3,... even if only odd levels
2754 are being used.
2755 HEADLINE: The text of the headline. Depending on PARAMS, this may
2756 already be formatted like a link.
2757 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2758 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2759 in this sequence.
2760 TIME: The sum of all time spend in this tree, in minutes. This time
2761 will of cause be restricted to the time block and tags match
2762 specified in PARAMS.
2763 PROPERTIES: The list properties specified in the `:properties' parameter
2764 along with their value, as an alist following the pattern
2765 (NAME . VALUE)."
2766 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2767 (timestamp (plist-get params :timestamp))
2768 (ts (plist-get params :tstart))
2769 (te (plist-get params :tend))
2770 (ws (plist-get params :wstart))
2771 (ms (plist-get params :mstart))
2772 (block (plist-get params :block))
2773 (link (plist-get params :link))
2774 (tags (plist-get params :tags))
2775 (properties (plist-get params :properties))
2776 (inherit-property-p (plist-get params :inherit-props))
2777 (matcher (and tags (cdr (org-make-tags-matcher tags))))
2778 cc st p tbl)
2780 (setq org-clock-file-total-minutes nil)
2781 (when block
2782 (setq cc (org-clock-special-range block nil t ws ms)
2783 ts (car cc)
2784 te (nth 1 cc)))
2785 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2786 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2787 (when (and ts (listp ts))
2788 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2789 (when (and te (listp te))
2790 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2791 ;; Now the times are strings we can parse.
2792 (if ts (setq ts (org-matcher-time ts)))
2793 (if te (setq te (org-matcher-time te)))
2794 (save-excursion
2795 (org-clock-sum ts te
2796 (when matcher
2797 `(lambda ()
2798 (let* ((tags-list (org-get-tags-at))
2799 (org-scanner-tags tags-list)
2800 (org-trust-scanner-tags t))
2801 (funcall ,matcher nil tags-list nil)))))
2802 (goto-char (point-min))
2803 (setq st t)
2804 (while (or (and (bobp) (prog1 st (setq st nil))
2805 (get-text-property (point) :org-clock-minutes)
2806 (setq p (point-min)))
2807 (setq p (next-single-property-change
2808 (point) :org-clock-minutes)))
2809 (goto-char p)
2810 (let ((time (get-text-property p :org-clock-minutes)))
2811 (when (and time (> time 0) (org-at-heading-p))
2812 (let ((level (org-reduced-level (org-current-level))))
2813 (when (<= level maxlevel)
2814 (let* ((headline (org-get-heading t t t t))
2815 (hdl
2816 (if (not link) headline
2817 (let ((search
2818 (org-make-org-heading-search-string headline)))
2819 (org-make-link-string
2820 (if (not (buffer-file-name)) search
2821 (format "file:%s::%s" (buffer-file-name) search))
2822 ;; Prune statistics cookies. Replace
2823 ;; links with their description, or
2824 ;; a plain link if there is none.
2825 (org-trim
2826 (org-link-display-format
2827 (replace-regexp-in-string
2828 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
2829 headline)))))))
2830 (tsp
2831 (and timestamp
2832 (cl-some (lambda (p) (org-entry-get (point) p))
2833 '("SCHEDULED" "DEADLINE" "TIMESTAMP"
2834 "TIMESTAMP_IA"))))
2835 (props
2836 (and properties
2837 (delq nil
2838 (mapcar
2839 (lambda (p)
2840 (let ((v (org-entry-get
2841 (point) p inherit-property-p)))
2842 (and v (cons p v))))
2843 properties)))))
2844 (push (list level hdl tsp time props) tbl)))))))
2845 (list file org-clock-file-total-minutes (nreverse tbl)))))
2847 ;; Saving and loading the clock
2849 (defvar org-clock-loaded nil
2850 "Was the clock file loaded?")
2852 ;;;###autoload
2853 (defun org-clock-update-time-maybe ()
2854 "If this is a CLOCK line, update it and return t.
2855 Otherwise, return nil."
2856 (interactive)
2857 (save-excursion
2858 (beginning-of-line 1)
2859 (skip-chars-forward " \t")
2860 (when (looking-at org-clock-string)
2861 (let ((re (concat "[ \t]*" org-clock-string
2862 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2863 "\\([ \t]*=>.*\\)?\\)?"))
2864 ts te h m s neg)
2865 (cond
2866 ((not (looking-at re))
2867 nil)
2868 ((not (match-end 2))
2869 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2870 (> org-clock-marker (point))
2871 (<= org-clock-marker (point-at-eol)))
2872 ;; The clock is running here
2873 (setq org-clock-start-time
2874 (apply 'encode-time
2875 (org-parse-time-string (match-string 1))))
2876 (org-clock-update-mode-line)))
2878 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2879 (end-of-line 1)
2880 (setq ts (match-string 1)
2881 te (match-string 3))
2882 (setq s (- (float-time
2883 (apply #'encode-time (org-parse-time-string te)))
2884 (float-time
2885 (apply #'encode-time (org-parse-time-string ts))))
2886 neg (< s 0)
2887 s (abs s)
2888 h (floor (/ s 3600))
2889 s (- s (* 3600 h))
2890 m (floor (/ s 60))
2891 s (- s (* 60 s)))
2892 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2893 t))))))
2895 (defun org-clock-save ()
2896 "Persist various clock-related data to disk.
2897 The details of what will be saved are regulated by the variable
2898 `org-clock-persist'."
2899 (when (and org-clock-persist
2900 (or org-clock-loaded
2901 org-clock-has-been-used
2902 (not (file-exists-p org-clock-persist-file))))
2903 (with-temp-file org-clock-persist-file
2904 (insert (format ";; %s - %s at %s\n"
2905 (file-name-nondirectory org-clock-persist-file)
2906 (system-name)
2907 (format-time-string (org-time-stamp-format t))))
2908 ;; Store clock to be resumed.
2909 (when (and (memq org-clock-persist '(t clock))
2910 (let ((b (org-base-buffer (org-clocking-buffer))))
2911 (and (buffer-live-p b)
2912 (buffer-file-name b)
2913 (or (not org-clock-persist-query-save)
2914 (y-or-n-p (format "Save current clock (%s) "
2915 org-clock-heading))))))
2916 (insert
2917 (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
2918 (buffer-file-name (org-base-buffer (org-clocking-buffer)))
2919 (marker-position org-clock-marker))))
2920 ;; Store clocked task history. Tasks are stored reversed to
2921 ;; make reading simpler.
2922 (when (and (memq org-clock-persist '(t history))
2923 org-clock-history)
2924 (insert
2925 (format "(setq org-clock-stored-history '(%s))\n"
2926 (mapconcat
2927 (lambda (m)
2928 (let ((b (org-base-buffer (marker-buffer m))))
2929 (when (and (buffer-live-p b)
2930 (buffer-file-name b))
2931 (format "(%S . %d)"
2932 (buffer-file-name b)
2933 (marker-position m)))))
2934 (reverse org-clock-history)
2935 " ")))))))
2937 (defun org-clock-load ()
2938 "Load clock-related data from disk, maybe resuming a stored clock."
2939 (when (and org-clock-persist (not org-clock-loaded))
2940 (if (not (file-readable-p org-clock-persist-file))
2941 (message "Not restoring clock data; %S not found" org-clock-persist-file)
2942 (message "Restoring clock data")
2943 ;; Load history.
2944 (load-file org-clock-persist-file)
2945 (setq org-clock-loaded t)
2946 (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
2947 org-clock-stored-history)
2948 (org-clock-history-push position (find-file-noselect file)))
2949 ;; Resume clock.
2950 (pcase org-clock-stored-resume-clock
2951 (`(,(and file (pred file-exists-p)) . ,position)
2952 (with-current-buffer (find-file-noselect file)
2953 (when (or (not org-clock-persist-query-resume)
2954 (y-or-n-p (format "Resume clock (%s) "
2955 (save-excursion
2956 (goto-char position)
2957 (org-get-heading t t)))))
2958 (goto-char position)
2959 (let ((org-clock-in-resume 'auto-restart)
2960 (org-clock-auto-clock-resolution nil))
2961 (org-clock-in)
2962 (when (org-invisible-p) (org-show-context))))))
2963 (_ nil)))))
2965 ;; Suggested bindings
2966 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2968 (provide 'org-clock)
2970 ;; Local variables:
2971 ;; generated-autoload-file: "org-loaddefs.el"
2972 ;; coding: utf-8
2973 ;; End:
2975 ;;; org-clock.el ends here