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