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