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