1 ;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the time clocking code for Org mode
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-link-display-format
"ol" (s))
39 (declare-function org-link-heading-search-string
"ol" (&optional string
))
40 (declare-function org-link-make-string
"ol" (link &optional description
))
41 (declare-function org-table-goto-line
"org-table" (n))
42 (declare-function org-dynamic-block-define
"org" (type func
))
44 (defvar org-frame-title-format-backup frame-title-format
)
46 (defvar org-link-bracket-re
)
47 (defvar org-time-stamp-formats
)
49 (defgroup org-clock nil
50 "Options concerning clocking working time in Org mode."
54 (defcustom org-clock-into-drawer t
55 "Non-nil when clocking info should be wrapped into a drawer.
57 When non-nil, clocking info will be inserted into the same drawer
58 as log notes (see variable `org-log-into-drawer'), if it exists,
59 or \"LOGBOOK\" otherwise. If necessary, the drawer will be
62 When an integer, the drawer is created only when the number of
63 clocking entries in an item reaches or exceeds this value.
65 When a string, it becomes the name of the drawer, ignoring the
66 log notes drawer altogether.
68 Do not check directly this variable in a Lisp program. Call
69 function `org-clock-into-drawer' instead."
73 :package-version
'(Org .
"8.3")
75 (const :tag
"Always" t
)
76 (const :tag
"Only when drawer exists" nil
)
77 (integer :tag
"When at least N clock entries")
78 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
79 (string :tag
"Into Drawer named...")))
81 (defun org-clock-into-drawer ()
82 "Value of `org-clock-into-drawer'. but let properties overrule.
84 If the current entry has or inherits a CLOCK_INTO_DRAWER
85 property, it will be used instead of the default value.
87 Return value is either a string, an integer, or nil."
88 (let ((p (org-entry-get nil
"CLOCK_INTO_DRAWER" 'inherit t
)))
89 (cond ((equal p
"nil") nil
)
90 ((equal p
"t") (or (org-log-into-drawer) "LOGBOOK"))
92 (if (string-match-p "\\`[0-9]+\\'" p
) (string-to-number p
) p
))
93 ((org-string-nw-p org-clock-into-drawer
))
94 ((integerp org-clock-into-drawer
) org-clock-into-drawer
)
95 ((not org-clock-into-drawer
) nil
)
96 ((org-log-into-drawer))
99 (defcustom org-clock-out-when-done t
100 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
102 DONE here means any DONE-like state.
103 A nil value means clock will keep running until stopped explicitly with
104 `\\[org-clock-out]', or until the clock is started in a different item.
105 Instead of t, this can also be a list of TODO states that should trigger
109 (const :tag
"No" nil
)
110 (const :tag
"Yes, when done" t
)
111 (repeat :tag
"State list"
112 (string :tag
"TODO keyword"))))
114 (defcustom org-clock-rounding-minutes
0
115 "Rounding minutes when clocking in or out.
116 The default value is 0 so that no rounding is done.
117 When set to a non-integer value, use the car of
118 `org-time-stamp-rounding-minutes', like for setting a time-stamp.
120 E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
121 and you clock in: then the clock starts at 14:45. If you clock
122 out within the next 5 minutes, the clock line will be removed;
123 if you clock out 8 minutes after your clocked in, the clock
124 out time will be 14:50."
127 :package-version
'(Org .
"8.0")
129 (integer :tag
"Minutes (0 for no rounding)")
130 (symbol :tag
"Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp
)))
132 (defcustom org-clock-out-remove-zero-time-clocks nil
133 "Non-nil means remove the clock line when the resulting time is zero."
137 (defcustom org-clock-in-switch-to-state nil
138 "Set task to a special todo state while clocking it.
139 The value should be the state to which the entry should be
140 switched. If the value is a function, it must take one
141 parameter (the current TODO state of the item) and return the
142 state to switch it to."
146 (const :tag
"Don't force a state" nil
)
147 (string :tag
"State")
148 (symbol :tag
"Function")))
150 (defcustom org-clock-out-switch-to-state nil
151 "Set task to a special todo state after clocking out.
152 The value should be the state to which the entry should be
153 switched. If the value is a function, it must take one
154 parameter (the current TODO state of the item) and return the
155 state to switch it to."
159 (const :tag
"Don't force a state" nil
)
160 (string :tag
"State")
161 (symbol :tag
"Function")))
163 (defcustom org-clock-history-length
5
164 "Number of clock tasks to remember in history.
165 Clocking in using history works best if this is at most 35, in
166 which case all digits and capital letters are used up by the
167 *Clock Task Select* buffer."
171 (defcustom org-clock-goto-may-find-recent-task t
172 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
176 (defcustom org-clock-heading-function nil
177 "When non-nil, should be a function to create `org-clock-heading'.
178 This is the string shown in the mode line when a clock is running.
179 The function is called with point at the beginning of the headline."
181 :type
'(choice (const nil
) (function)))
183 (defcustom org-clock-string-limit
0
184 "Maximum length of clock strings in the mode line. 0 means no limit."
188 (defcustom org-clock-in-resume nil
189 "If non-nil, resume clock when clocking into task with open clock.
190 When clocking into a task with a clock entry which has not been closed,
191 the clock can be resumed from that point."
195 (defcustom org-clock-persist nil
196 "When non-nil, save the running clock when Emacs is closed.
197 The clock is resumed when Emacs restarts.
198 When this is t, both the running clock, and the entire clock
199 history are saved. When this is the symbol `clock', only the
200 running clock is saved. When this is the symbol `history', only
201 the clock history is saved.
203 When Emacs restarts with saved clock information, the file containing
204 the running clock as well as all files mentioned in the clock history
207 All this depends on running `org-clock-persistence-insinuate' in your
208 Emacs initialization file."
211 (const :tag
"Just the running clock" clock
)
212 (const :tag
"Just the history" history
)
213 (const :tag
"Clock and history" t
)
214 (const :tag
"No persistence" nil
)))
216 (defcustom org-clock-persist-file
(convert-standard-filename
217 (concat user-emacs-directory
"org-clock-save.el"))
218 "File to save clock data to."
222 (defcustom org-clock-persist-query-save nil
223 "When non-nil, ask before saving the current clock on exit."
227 (defcustom org-clock-persist-query-resume t
228 "When non-nil, ask before resuming any stored clock during load."
232 (defcustom org-clock-sound nil
233 "Sound to use for notifications.
237 t Standard Emacs beep
238 file name Play this sound file, fall back to beep"
241 (const :tag
"No sound" nil
)
242 (const :tag
"Standard beep" t
)
243 (file :tag
"Play sound file")))
245 (defcustom org-clock-mode-line-total
'auto
246 "Default setting for the time included for the mode line clock.
247 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
250 current Only the time in the current instance of the clock
251 today All time clocked into this task today
252 repeat All time clocked into this task since last repeat
253 all All time ever recorded for this task
254 auto Automatically, either `all', or `repeat' for repeating tasks"
257 (const :tag
"Current clock" current
)
258 (const :tag
"Today's task time" today
)
259 (const :tag
"Since last repeat" repeat
)
260 (const :tag
"All task time" all
)
261 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
263 (defvaralias 'org-task-overrun-text
'org-clock-task-overrun-text
)
264 (defcustom org-clock-task-overrun-text nil
265 "Extra mode line text to indicate that the clock is overrun.
266 The can be nil to indicate that instead of adding text, the clock time
267 should get a different face (`org-mode-line-clock-overrun').
268 When this is a string, it is prepended to the clock string as an indication,
269 also using the face `org-mode-line-clock-overrun'."
273 (const :tag
"Just mark the time string" nil
)
274 (string :tag
"Text to prepend")))
276 (defcustom org-show-notification-handler nil
277 "Function or program to send notification with.
278 The function or program will be called with the notification
283 (string :tag
"Program")
284 (function :tag
"Function")))
286 (defgroup org-clocktable nil
287 "Options concerning the clock table in Org mode."
288 :tag
"Org Clock Table"
291 (defcustom org-clocktable-defaults
294 :lang
(or (bound-and-true-p org-export-default-language
) "en")
315 "Default properties for clock tables."
320 (defcustom org-clock-clocktable-formatter
'org-clocktable-write-default
321 "Function to turn clocking data into a table.
322 For more information, see `org-clocktable-write-default'."
323 :group
'org-clocktable
327 ;; FIXME: translate es and nl last string "Clock summary at"
328 (defcustom org-clock-clocktable-language-setup
329 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
330 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
331 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à ")
332 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
333 ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT"
334 "Gesamtdauer" "Dateizeit" "Erstellt am"))
335 "Terms used in clocktable, translated to different languages."
336 :group
'org-clocktable
340 (defcustom org-clock-clocktable-default-properties
'(:maxlevel
2)
341 "Default properties for new clocktables.
342 These will be inserted into the BEGIN line, to make it easy for users to
344 :group
'org-clocktable
345 :package-version
'(Org .
"9.2")
348 (defcustom org-clock-idle-time nil
349 "When non-nil, resolve open clocks if the user is idle more than X minutes."
352 (const :tag
"Never" nil
)
353 (integer :tag
"After N minutes")))
355 (defcustom org-clock-auto-clock-resolution
'when-no-clock-is-running
356 "When to automatically resolve open clocks found in Org buffers."
359 (const :tag
"Never" nil
)
360 (const :tag
"Always" t
)
361 (const :tag
"When no clock is running" when-no-clock-is-running
)))
363 (defcustom org-clock-report-include-clocking-task nil
364 "When non-nil, include the current clocking task time in clock reports."
369 (defcustom org-clock-resolve-expert nil
370 "Non-nil means do not show the splash buffer with the clock resolver."
375 (defcustom org-clock-continuously nil
376 "Non-nil means to start clocking from the last clock-out time, if any."
381 (defcustom org-clock-total-time-cell-format
"*%s*"
382 "Format string for the total time cells."
387 (defcustom org-clock-file-time-cell-format
"*%s*"
388 "Format string for the file time cells."
393 (defcustom org-clock-clocked-in-display
'mode-line
394 "When clocked in for a task, Org can display the current
395 task and accumulated time in the mode line and/or frame title.
398 both displays in both mode line and frame title
399 mode-line displays only in mode line (default)
400 frame-title displays only in frame title
401 nil current clock is not displayed"
404 (const :tag
"Mode line" mode-line
)
405 (const :tag
"Frame title" frame-title
)
406 (const :tag
"Both" both
)
407 (const :tag
"None" nil
)))
409 (defcustom org-clock-frame-title-format
'(t org-mode-line-string
)
410 "The value for `frame-title-format' when clocking in.
412 When `org-clock-clocked-in-display' is set to `frame-title'
413 or `both', clocking in will replace `frame-title-format' with
414 this value. Clocking out will restore `frame-title-format'.
416 `org-frame-title-string' is a format string using the same
417 specifications than `frame-title-format', which see."
422 (defcustom org-clock-x11idle-program-name
"x11idle"
423 "Name of the program which prints X11 idle time in milliseconds.
425 You can find x11idle.c in the contrib/scripts directory of the
426 Org git distribution. Or, you can do:
428 sudo apt-get install xprintidle
430 if you are using Debian."
433 :package-version
'(Org .
"8.0")
436 (defcustom org-clock-goto-before-context
2
437 "Number of lines of context to display before currently clocked-in entry.
438 This applies when using `org-clock-goto'."
442 (defcustom org-clock-display-default-range
'thisyear
443 "Default range when displaying clocks with `org-clock-display'.
444 Valid values are: `today', `yesterday', `thisweek', `lastweek',
445 `thismonth', `lastmonth', `thisyear', `lastyear' and `untilnow'."
447 :type
'(choice (const today
)
456 (const :tag
"Select range interactively" interactive
))
459 (defvar org-clock-in-prepare-hook nil
460 "Hook run when preparing the clock.
461 This hook is run before anything happens to the task that
462 you want to clock in. For example, you can use this hook
463 to add an effort property.")
464 (defvar org-clock-in-hook nil
465 "Hook run when starting the clock.")
466 (defvar org-clock-out-hook nil
467 "Hook run when stopping the current clock.")
469 (defvar org-clock-cancel-hook nil
470 "Hook run when canceling the current clock.")
471 (defvar org-clock-goto-hook nil
472 "Hook run when selecting the currently clocked-in entry.")
473 (defvar org-clock-has-been-used nil
474 "Has the clock been used during the current Emacs session?")
476 (defvar org-clock-stored-history nil
477 "Clock history, populated by `org-clock-load'")
478 (defvar org-clock-stored-resume-clock nil
479 "Clock to resume, saved by `org-clock-load'")
481 ;;; The clock for measuring work time.
483 (defvar org-mode-line-string
"")
484 (put 'org-mode-line-string
'risky-local-variable t
)
486 (defvar org-clock-mode-line-timer nil
)
487 (defvar org-clock-idle-timer nil
)
488 (defvar org-clock-heading
) ; defined in org.el
489 (defvar org-clock-start-time
"")
491 (defvar org-clock-leftover-time nil
492 "If non-nil, user canceled a clock; this is when leftover time started.")
494 (defvar org-clock-effort
""
495 "Effort estimate of the currently clocking task.")
497 (defvar org-clock-total-time nil
498 "Holds total time, spent previously on currently clocked item.
499 This does not include the time in the currently running clock.")
501 (defvar org-clock-history nil
502 "List of marker pointing to recent clocked tasks.")
504 (defvar org-clock-default-task
(make-marker)
505 "Marker pointing to the default task that should clock time.
506 The clock can be made to switch to this task after clocking out
507 of a different task.")
509 (defvar org-clock-interrupted-task
(make-marker)
510 "Marker pointing to the task that has been interrupted by the current clock.")
512 (defvar org-clock-mode-line-map
(make-sparse-keymap))
513 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
514 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
516 (defun org-clock--translate (s language
)
517 "Translate string S into using string LANGUAGE.
518 Assume S in the English term to translate. Return S as-is if it
519 cannot be translated."
521 ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5)
522 ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9))
523 (assoc-string language org-clock-clocktable-language-setup t
))
526 (defun org-clock--mode-line-heading ()
527 "Return currently clocked heading, formatted for mode line."
528 (cond ((functionp org-clock-heading-function
)
529 (funcall org-clock-heading-function
))
530 ((org-before-first-heading-p) "???")
531 (t (org-link-display-format
532 (org-no-properties (org-get-heading t t t t
))))))
534 (defun org-clock-menu ()
538 ["Clock out" org-clock-out t
]
539 ["Change effort estimate" org-clock-modify-effort-estimate t
]
540 ["Go to clock entry" org-clock-goto t
]
541 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
543 (defun org-clock-history-push (&optional pos buffer
)
544 "Push a marker to the clock history."
545 (setq org-clock-history-length
(max 1 org-clock-history-length
))
546 (let ((m (move-marker (make-marker)
547 (or pos
(point)) (org-base-buffer
548 (or buffer
(current-buffer)))))
550 (while (setq n
(member m org-clock-history
))
551 (move-marker (car n
) nil
))
552 (setq org-clock-history
554 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
556 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
557 (setq org-clock-history
559 (nthcdr (- l org-clock-history-length -
1)
560 (nreverse org-clock-history
)))))
561 (push m org-clock-history
)))
563 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
564 "Save relative positions of markers in region."
565 (org-check-and-save-marker org-clock-marker beg end
)
566 (org-check-and-save-marker org-clock-hd-marker beg end
)
567 (org-check-and-save-marker org-clock-default-task beg end
)
568 (org-check-and-save-marker org-clock-interrupted-task beg end
)
569 (dolist (m org-clock-history
)
570 (org-check-and-save-marker m beg end
)))
572 (defun org-clock-drawer-name ()
573 "Return clock drawer's name for current entry, or nil."
574 (let ((drawer (org-clock-into-drawer)))
575 (cond ((integerp drawer
)
576 (let ((log-drawer (org-log-into-drawer)))
577 (if (stringp log-drawer
) log-drawer
"LOGBOOK")))
578 ((stringp drawer
) drawer
)
581 (defun org-clocking-buffer ()
582 "Return the clocking buffer if we are currently clocking a task or nil."
583 (marker-buffer org-clock-marker
))
585 (defun org-clocking-p ()
586 "Return t when clocking a task."
587 (not (equal (org-clocking-buffer) nil
)))
589 (defvar org-clock-before-select-task-hook nil
590 "Hook called in task selection just before prompting the user.")
592 (defun org-clock-select-task (&optional prompt
)
593 "Select a task that was recently associated with clocking.
594 Return marker position of the selected task. Raise an error if
595 there is no recent clock to choose from."
596 (let (och chl sel-list rpl
(i 0) s
)
597 ;; Remove successive dups from the clock history to consider
598 (dolist (c org-clock-history
)
599 (unless (equal c
(car och
)) (push c och
)))
600 (setq och
(reverse och
) chl
(length och
))
602 (user-error "No recent clock")
603 (save-window-excursion
604 (org-switch-to-buffer-other-window
605 (get-buffer-create "*Clock Task Select*"))
607 (when (marker-buffer org-clock-default-task
)
608 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
609 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
611 (when (marker-buffer org-clock-interrupted-task
)
612 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
613 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
615 (when (org-clocking-p)
616 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
617 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
619 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
621 (when (marker-buffer m
)
623 s
(org-clock-insert-selection-line
627 (if (fboundp 'int-to-char
) (setf (car s
) (int-to-char (car s
))))
629 (run-hooks 'org-clock-before-select-task-hook
)
630 (goto-char (point-min))
631 ;; Set min-height relatively to circumvent a possible but in
632 ;; `fit-window-to-buffer'
633 (fit-window-to-buffer nil nil
(if (< chl
10) chl
(+ 5 chl
)))
634 (message (or prompt
"Select task for clocking:"))
635 (setq cursor-type nil rpl
(read-char-exclusive))
640 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
641 (t (user-error "Invalid task choice %c" rpl
)))))))
643 (defun org-clock-insert-selection-line (i marker
)
644 "Insert a line for the clock selection menu.
645 And return a cons cell with the selection character integer and the marker
647 (when (marker-buffer marker
)
648 (let (cat task heading prefix
)
649 (with-current-buffer (org-base-buffer (marker-buffer marker
))
650 (org-with-wide-buffer
653 (setq cat
(org-get-category)
654 heading
(org-get-heading 'notags
)
655 prefix
(save-excursion
656 (org-back-to-heading t
)
657 (looking-at org-outline-regexp
)
660 (org-fontify-like-in-org-mode
661 (concat prefix heading
)
665 (insert (format "[%c] %-12s %s\n" i cat task
))
668 (defvar org-clock-task-overrun nil
669 "Internal flag indicating if the clock has overrun the planned time.")
670 (defvar org-clock-update-period
60
671 "Number of seconds between mode line clock string updates.")
673 (defun org-clock-get-clock-string ()
674 "Form a clock-string, that will be shown in the mode line.
675 If an effort estimate was defined for the current item, use
676 01:30/01:50 format (clocked/estimated).
677 If not, show simply the clocked time like 01:50."
678 (let ((clocked-time (org-clock-get-clocked-time)))
680 (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort
))
682 (propertize (org-duration-from-minutes clocked-time
)
684 (if (and org-clock-task-overrun
685 (not org-clock-task-overrun-text
))
686 'org-mode-line-clock-overrun
687 'org-mode-line-clock
)))
688 (effort-str (org-duration-from-minutes effort-in-minutes
)))
689 (format (propertize " [%s/%s] (%s)" 'face
'org-mode-line-clock
)
690 work-done-str effort-str org-clock-heading
))
691 (format (propertize " [%s] (%s)" 'face
'org-mode-line-clock
)
692 (org-duration-from-minutes clocked-time
)
693 org-clock-heading
))))
695 (defun org-clock-get-last-clock-out-time ()
696 "Get the last clock-out time for the current subtree."
698 (let ((end (save-excursion (org-end-of-subtree))))
699 (when (re-search-forward (concat org-clock-string
700 ".*\\]--\\(\\[[^]]+\\]\\)") end t
)
701 (org-time-string-to-time (match-string 1))))))
703 (defun org-clock-update-mode-line (&optional refresh
)
704 "Update mode line with clock information.
705 When optional argument is non-nil, refresh cached heading."
707 (org-clock-notify-once-if-expired)
708 (setq org-clock-task-overrun nil
))
709 (when refresh
(setq org-clock-heading
(org-clock--mode-line-heading)))
710 (setq org-mode-line-string
712 (let ((clock-string (org-clock-get-clock-string))
713 (help-text "Org mode clock is running.\nmouse-1 shows a \
714 menu\nmouse-2 will jump to task"))
715 (if (and (> org-clock-string-limit
0)
716 (> (length clock-string
) org-clock-string-limit
))
718 (substring clock-string
0 org-clock-string-limit
)
719 'help-echo
(concat help-text
": " org-clock-heading
))
720 (propertize clock-string
'help-echo help-text
)))
721 'local-map org-clock-mode-line-map
722 'mouse-face
'mode-line-highlight
))
723 (if (and org-clock-task-overrun org-clock-task-overrun-text
)
724 (setq org-mode-line-string
726 org-clock-task-overrun-text
727 'face
'org-mode-line-clock-overrun
) org-mode-line-string
)))
728 (force-mode-line-update))
730 (defun org-clock-get-clocked-time ()
731 "Get the clocked time for the current item in minutes.
732 The time returned includes the time spent on this task in
733 previous clocking intervals."
734 (let ((currently-clocked-time
735 (floor (- (float-time)
736 (float-time org-clock-start-time
)) 60)))
737 (+ currently-clocked-time
(or org-clock-total-time
0))))
739 (defun org-clock-modify-effort-estimate (&optional value
)
740 "Add to or set the effort estimate of the item currently being clocked.
741 VALUE can be a number of minutes, or a string with format hh:mm or mm.
742 When the string starts with a + or a - sign, the current value of the effort
743 property will be changed by that amount. If the effort value is expressed
744 as an unit defined in `org-duration-units' (e.g. \"3h\"), the modified
745 value will be converted to a hh:mm duration.
747 This command will update the \"Effort\" property of the currently
748 clocked item, and the value displayed in the mode line."
750 (if (org-clock-is-active)
751 (let ((current org-clock-effort
) sign
)
753 ;; Prompt user for a value or a change
756 (format "Set effort (hh:mm or mm%s): "
758 (format ", prefix + to add to %s" org-clock-effort
)
760 (when (stringp value
)
761 ;; A string. See if it is a delta
762 (setq sign
(string-to-char value
))
763 (if (member sign
'(?- ?
+))
764 (setq current
(org-duration-to-minutes current
)
765 value
(substring value
1))
767 (setq value
(org-duration-to-minutes value
))
769 (setq value
(- current value
))
770 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
771 (setq value
(max 0 value
)
772 org-clock-effort
(org-duration-from-minutes value
))
773 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
774 (org-clock-update-mode-line)
775 (message "Effort is now %s" org-clock-effort
))
776 (message "Clock is not currently active")))
778 (defvar org-clock-notification-was-shown nil
779 "Shows if we have shown notification already.")
781 (defun org-clock-notify-once-if-expired ()
782 "Show notification if we spent more time than we estimated before.
783 Notification is shown only once."
784 (when (org-clocking-p)
785 (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort
))
786 (clocked-time (org-clock-get-clocked-time)))
787 (if (setq org-clock-task-overrun
788 (if (or (null effort-in-minutes
) (zerop effort-in-minutes
))
790 (>= clocked-time effort-in-minutes
)))
791 (unless org-clock-notification-was-shown
792 (setq org-clock-notification-was-shown t
)
794 (format-message "Task `%s' should be finished by now. (%s)"
795 org-clock-heading org-clock-effort
)
797 (setq org-clock-notification-was-shown nil
)))))
799 (defun org-notify (notification &optional play-sound
)
800 "Send a NOTIFICATION and maybe PLAY-SOUND.
801 If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
802 (org-show-notification notification
)
803 (if play-sound
(org-clock-play-sound play-sound
)))
805 (defun org-show-notification (notification)
807 Use `org-show-notification-handler' if defined,
808 use libnotify if available, or fall back on a message."
809 (cond ((functionp org-show-notification-handler
)
810 (funcall org-show-notification-handler notification
))
811 ((stringp org-show-notification-handler
)
812 (start-process "emacs-timer-notification" nil
813 org-show-notification-handler notification
))
814 ((fboundp 'notifications-notify
)
815 (notifications-notify
816 :title
"Org mode message"
818 ;; FIXME how to link to the Org icon?
819 ;; :app-icon "~/.emacs.d/icons/mail.png"
821 ((executable-find "notify-send")
822 (start-process "emacs-timer-notification" nil
823 "notify-send" notification
))
824 ;; Maybe the handler will send a message, so only use message as
825 ;; a fall back option
826 (t (message "%s" notification
))))
828 (defun org-clock-play-sound (&optional clock-sound
)
829 "Play sound as configured by `org-clock-sound'.
830 Use alsa's aplay tool if available.
831 If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
832 (let ((org-clock-sound (or clock-sound org-clock-sound
)))
834 ((not org-clock-sound
))
835 ((eq org-clock-sound t
) (beep t
) (beep t
))
836 ((stringp org-clock-sound
)
837 (let ((file (expand-file-name org-clock-sound
)))
838 (if (file-exists-p file
)
839 (if (executable-find "aplay")
840 (start-process "org-clock-play-notification" nil
843 (play-sound-file file
)
844 (error (beep t
) (beep t
))))))))))
846 (defvar org-clock-mode-line-entry nil
847 "Information for the mode line about the running clock.")
849 (defun org-find-open-clocks (file)
850 "Search through the given file and find all open clocks."
851 (let ((buf (or (get-file-buffer file
)
852 (find-file-noselect file
)))
853 (org-clock-re (concat org-clock-string
" \\(\\[.*?\\]\\)$"))
855 (with-current-buffer buf
857 (goto-char (point-min))
858 (while (re-search-forward org-clock-re nil t
)
859 (push (cons (copy-marker (match-end 1) t
)
860 (org-time-string-to-time (match-string 1))) clocks
))))
863 (defsubst org-is-active-clock
(clock)
864 "Return t if CLOCK is the currently active clock."
865 (and (org-clock-is-active)
866 (= org-clock-marker
(car clock
))))
868 (defmacro org-with-clock-position
(clock &rest forms
)
869 "Evaluate FORMS with CLOCK as the current active clock."
870 `(with-current-buffer (marker-buffer (car ,clock
))
871 (org-with-wide-buffer
872 (goto-char (car ,clock
))
875 (def-edebug-spec org-with-clock-position
(form body
))
876 (put 'org-with-clock-position
'lisp-indent-function
1)
878 (defmacro org-with-clock
(clock &rest forms
)
879 "Evaluate FORMS with CLOCK as the current active clock.
880 This macro also protects the current active clock from being altered."
881 `(org-with-clock-position ,clock
882 (let ((org-clock-start-time (cdr ,clock
))
883 (org-clock-total-time)
886 (org-clock-marker (car ,clock
))
887 (org-clock-hd-marker (save-excursion
888 (org-back-to-heading t
)
891 (def-edebug-spec org-with-clock
(form body
))
892 (put 'org-with-clock
'lisp-indent-function
1)
894 (defsubst org-clock-clock-in
(clock &optional resume start-time
)
895 "Clock in to the clock located by CLOCK.
896 If necessary, clock-out of the currently active clock."
897 (org-with-clock-position clock
898 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
899 (org-clock-in nil start-time
))))
901 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
902 "Clock out of the clock located by CLOCK."
903 (let ((temp (copy-marker (car clock
)
904 (marker-insertion-type (car clock
)))))
905 (if (org-is-active-clock clock
)
906 (org-clock-out nil fail-quietly at-time
)
907 (org-with-clock clock
908 (org-clock-out nil fail-quietly at-time
)))
909 (setcar clock temp
)))
911 (defsubst org-clock-clock-cancel
(clock)
912 "Cancel the clock located by CLOCK."
913 (let ((temp (copy-marker (car clock
)
914 (marker-insertion-type (car clock
)))))
915 (if (org-is-active-clock clock
)
917 (org-with-clock clock
919 (setcar clock temp
)))
921 (defvar org-clock-clocking-in nil
)
922 (defvar org-clock-resolving-clocks nil
)
923 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
925 (defun org-clock-resolve-clock
926 (clock resolve-to clock-out-time close restart fail-quietly
)
927 "Resolve CLOCK given the time RESOLVE-TO, and the present.
928 CLOCK is a cons cell of the form (MARKER START-TIME)."
929 (let ((org-clock-resolving-clocks t
)
930 ;; If the clocked entry contained only a clock and possibly
931 ;; the associated drawer, and we either cancel it or clock it
932 ;; out, `org-clock-out-remove-zero-time-clocks' may clear all
933 ;; contents, and leave point on the /next/ headline. We store
934 ;; the current entry location to be able to get back here when
935 ;; we need to clock in again the previously clocked task.
936 (heading (org-with-point-at (car clock
)
937 (org-back-to-heading t
)
941 (org-clock-clock-cancel clock
)
942 (when (and restart
(not org-clock-clocking-in
))
943 (org-with-point-at heading
(org-clock-in))))
946 (restart (error "RESTART is not valid here"))
947 ((or close org-clock-clocking-in
)
948 (org-clock-clock-out clock fail-quietly
))
949 ((org-is-active-clock clock
) nil
)
950 (t (org-clock-clock-in clock t
))))
951 ((pred (time-less-p (current-time)))
952 ;; ^ NOTE: Here and in other `time-less-p' calls, we use
953 ;; (current-time) rather than nil for Emacs 24 compatibility.
954 (error "RESOLVE-TO must refer to a time in the past"))
956 (when restart
(error "RESTART is not valid here"))
957 (org-clock-clock-out clock fail-quietly
(or clock-out-time resolve-to
))
959 (org-clock-clocking-in nil
)
961 (setq org-clock-leftover-time
(and (null clock-out-time
) resolve-to
)))
963 (org-with-point-at heading
964 (org-clock-in nil
(and clock-out-time resolve-to
)))))))))
966 (defun org-clock-jump-to-current-clock (&optional effective-clock
)
967 "When an Org clock is running, jump to it."
968 (let ((drawer (org-clock-into-drawer))
969 (clock (or effective-clock
(cons org-clock-marker
970 org-clock-start-time
))))
971 (unless (marker-buffer (car clock
))
972 (user-error "No Org clock is currently running"))
973 (org-with-clock clock
(org-clock-goto))
974 (with-current-buffer (marker-buffer (car clock
))
975 (goto-char (car clock
))
977 (org-with-wide-buffer
978 (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
979 (regexp-quote (if (stringp drawer
) drawer
"LOGBOOK"))))
980 (beg (save-excursion (org-back-to-heading t
) (point))))
982 (while (re-search-backward drawer-re beg t
)
983 (let ((element (org-element-at-point)))
984 (when (eq (org-element-type element
) 'drawer
)
985 (when (> (org-element-property :end element
) (car clock
))
986 (org-flag-drawer nil element
))
987 (throw 'exit nil
)))))))))))
989 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
990 "Resolve an open Org clock.
991 An open clock was found, with `dangling' possibly being non-nil.
992 If this function was invoked with a prefix argument, non-dangling
993 open clocks are ignored. The given clock requires some sort of
994 user intervention to resolve it, either because a clock was left
995 dangling or due to an idle timeout. The clock resolution can
998 (a) deleted, the user doesn't care about the clock
999 (b) restarted from the current time (if no other clock is open)
1000 (c) closed, giving the clock X minutes
1001 (d) closed and then restarted
1002 (e) resumed, as if the user had never left
1004 The format of clock is (CONS MARKER START-TIME), where MARKER
1005 identifies the buffer and position the clock is open at (and
1006 thus, the heading it's under), and START-TIME is when the clock
1010 (save-window-excursion
1012 (unless org-clock-resolving-clocks-due-to-idleness
1013 (org-clock-jump-to-current-clock clock
))
1014 (unless org-clock-resolve-expert
1015 (with-output-to-temp-buffer "*Org Clock*"
1016 (princ (format-message "Select a Clock Resolution Command:
1018 i/q Ignore this question; the same as keeping all the idle time.
1020 k/K Keep X minutes of the idle time (default is all). If this
1021 amount is less than the default, you will be clocked out
1022 that many minutes after the time that idling began, and then
1023 clocked back in at the present time.
1025 g/G Indicate that you \"got back\" X minutes ago. This is quite
1026 different from `k': it clocks you out from the beginning of
1027 the idle period and clock you back in X minutes ago.
1029 s/S Subtract the idle time from the current clock. This is the
1030 same as keeping 0 minutes.
1032 C Cancel the open timer altogether. It will be as though you
1035 j/J Jump to the current clock, to make manual adjustments.
1037 For all these options, using uppercase makes your final state
1038 to be CLOCKED OUT."))))
1039 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
1041 (while (or (null char-pressed
)
1042 (and (not (memq char-pressed
1043 '(?k ?K ?g ?G ?s ?S ?C
1047 (read-char (concat (funcall prompt-fn clock
)
1050 (and (not (memq char-pressed
'(?i ?q
))) char-pressed
)))))
1052 (floor (/ (float-time
1053 ;; NOTE: Here and in other `time-subtract'
1054 ;; calls, we use (current-time) rather than nil
1055 ;; for Emacs 24 compatibility.
1056 (time-subtract (current-time) last-valid
)) 60)))
1058 (and (memq ch
'(?k ?K
))
1059 (read-number "Keep how many minutes? " default
)))
1061 (and (memq ch
'(?g ?G
))
1062 (read-number "Got back how many minutes ago? " default
)))
1063 (subtractp (memq ch
'(?s ?S
)))
1064 (barely-started-p (< (- (float-time last-valid
)
1065 (float-time (cdr clock
))) 45))
1066 (start-over (and subtractp barely-started-p
)))
1070 (org-clock-resolve-clock clock
'now nil t nil fail-quietly
))
1071 (org-clock-jump-to-current-clock clock
))
1073 (not (memq ch
'(?k ?K ?g ?G ?s ?S ?C
))))
1076 (org-clock-resolve-clock
1079 ;; If the time on the clock was less than a minute before
1080 ;; the user went away, and they've ask to subtract all the
1085 (and gotback
(= gotback
0)))
1087 ((or (and keep
(= keep default
))
1088 (and gotback
(= gotback default
)))
1091 (time-add last-valid
(seconds-to-time (* 60 keep
))))
1093 (time-subtract (current-time)
1094 (seconds-to-time (* 60 gotback
))))
1096 (error "Unexpected, please report this as a bug")))
1097 (and gotback last-valid
)
1098 (memq ch
'(?K ?G ?S
))
1100 (not (memq ch
'(?K ?G ?S ?C
))))
1104 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid
)
1105 "Resolve all currently open Org clocks.
1106 If `only-dangling-p' is non-nil, only ask to resolve dangling
1107 \(i.e., not currently open and valid) clocks."
1109 (unless org-clock-resolving-clocks
1110 (let ((org-clock-resolving-clocks t
))
1111 (dolist (file (org-files-list))
1112 (let ((clocks (org-find-open-clocks file
)))
1113 (dolist (clock clocks
)
1114 (let ((dangling (or (not (org-clock-is-active))
1115 (/= (car clock
) org-clock-marker
))))
1116 (if (or (not only-dangling-p
) dangling
)
1123 "Dangling clock started %d mins ago"
1124 (floor (- (float-time)
1125 (float-time (cdr clock
)))
1128 (cdr clock
)))))))))))
1130 (defun org-emacs-idle-seconds ()
1131 "Return the current Emacs idle time in seconds, or nil if not idle."
1132 (let ((idle-time (current-idle-time)))
1134 (float-time idle-time
)
1137 (defun org-mac-idle-seconds ()
1138 "Return the current Mac idle time in seconds."
1139 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
1141 (defvar org-x11idle-exists-p
1142 ;; Check that x11idle exists
1143 (and (eq window-system
'x
)
1144 (eq 0 (call-process-shell-command
1145 (format "command -v %s" org-clock-x11idle-program-name
)))
1146 ;; Check that x11idle can retrieve the idle time
1147 ;; FIXME: Why "..-shell-command" rather than just `call-process'?
1148 (eq 0 (call-process-shell-command org-clock-x11idle-program-name
))))
1150 (defun org-x11-idle-seconds ()
1151 "Return the current X11 idle time in seconds."
1152 (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name
)) 1000))
1154 (defun org-user-idle-seconds ()
1155 "Return the number of seconds the user has been idle for.
1156 This routine returns a floating point number."
1158 ((eq system-type
'darwin
)
1159 (org-mac-idle-seconds))
1160 ((and (eq window-system
'x
) org-x11idle-exists-p
)
1161 (org-x11-idle-seconds))
1163 (org-emacs-idle-seconds))))
1165 (defvar org-clock-user-idle-seconds
)
1167 (defun org-resolve-clocks-if-idle ()
1168 "Resolve all currently open Org clocks.
1169 This is performed after `org-clock-idle-time' minutes, to check
1170 if the user really wants to stay clocked in after being idle for
1172 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
1173 org-clock-marker
(marker-buffer org-clock-marker
))
1174 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
1175 (org-clock-user-idle-start
1176 (time-since (seconds-to-time org-clock-user-idle-seconds
)))
1177 (org-clock-resolving-clocks-due-to-idleness t
))
1178 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
1180 (cons org-clock-marker
1181 org-clock-start-time
)
1183 (format "Clocked in & idle for %.1f mins"
1185 (time-since org-clock-user-idle-start
))
1187 org-clock-user-idle-start
)))))
1189 (defvar org-clock-current-task nil
"Task currently clocked in.")
1190 (defvar org-clock-out-time nil
) ; store the time of the last clock-out
1191 (defvar org--msg-extra
)
1194 (defun org-clock-in (&optional select start-time
)
1195 "Start the clock on the current item.
1197 If necessary, clock-out of the currently active clock.
1199 With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
1201 tasks to clock into.
1203 When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
1204 clock into the current task and mark it as
1205 the default task, a special task that will always be offered in the
1206 clocking selection, associated with the letter `d'.
1208 When SELECT is `\\[universal-argument] \\[universal-argument] \
1209 \\[universal-argument]', clock in by using the last clock-out
1210 time as the start time. See `org-clock-continuously' to make this
1211 the default behavior."
1213 (setq org-clock-notification-was-shown nil
)
1214 (org-refresh-effort-properties)
1216 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
1218 ts selected-task target-pos
(org--msg-extra "")
1219 (leftover (and (not org-clock-resolving-clocks
)
1220 org-clock-leftover-time
)))
1222 (when (and org-clock-auto-clock-resolution
1223 (or (not interrupting
)
1224 (eq t org-clock-auto-clock-resolution
))
1225 (not org-clock-clocking-in
)
1226 (not org-clock-resolving-clocks
))
1227 (setq org-clock-leftover-time nil
)
1228 (let ((org-clock-clocking-in t
))
1229 (org-resolve-clocks))) ; check if any clocks are dangling
1231 (when (equal select
'(64))
1232 ;; Set start-time to `org-clock-out-time'
1233 (let ((org-clock-continuously t
))
1234 (org-clock-in nil org-clock-out-time
)
1235 (throw 'abort nil
)))
1237 (when (equal select
'(4))
1238 (pcase (org-clock-select-task "Clock-in on task: ")
1239 (`nil
(error "Abort"))
1240 (task (setq selected-task
(copy-marker task
)))))
1242 (when (equal select
'(16))
1243 ;; Mark as default clocking task
1244 (org-clock-mark-default-task))
1247 ;; We are interrupting the clocking of a different task. Save
1248 ;; a marker to this task, so that we can go back. First check
1249 ;; if we are trying to clock into the same task!
1250 (when (or selected-task
(derived-mode-p 'org-mode
))
1251 (org-with-point-at selected-task
1252 (unless selected-task
(org-back-to-heading t
))
1253 (when (and (eq (marker-buffer org-clock-hd-marker
)
1254 (org-base-buffer (current-buffer)))
1255 (= (point) (marker-position org-clock-hd-marker
))
1256 (equal org-clock-current-task
(org-get-heading t t t t
)))
1257 (message "Clock continues in %S" org-clock-heading
)
1258 (throw 'abort nil
))))
1259 (move-marker org-clock-interrupted-task
1260 (marker-position org-clock-marker
)
1261 (marker-buffer org-clock-marker
))
1262 (let ((org-clock-clocking-in t
))
1263 (org-clock-out nil t
)))
1265 ;; Clock in at which position?
1267 (if (and (eobp) (not (org-at-heading-p)))
1271 (when (and selected-task
(marker-buffer selected-task
))
1272 ;; There is a selected task, move to the correct buffer
1273 ;; and set the new target position.
1274 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
1275 (setq target-pos
(marker-position selected-task
))
1276 (move-marker selected-task nil
))
1277 (org-with-wide-buffer
1278 (goto-char target-pos
)
1279 (org-back-to-heading t
)
1280 (or interrupting
(move-marker org-clock-interrupted-task nil
))
1281 (run-hooks 'org-clock-in-prepare-hook
)
1282 (org-clock-history-push)
1283 (setq org-clock-current-task
(org-get-heading t t t t
))
1284 (cond ((functionp org-clock-in-switch-to-state
)
1285 (let ((case-fold-search nil
))
1286 (looking-at org-complex-heading-regexp
))
1287 (let ((newstate (funcall org-clock-in-switch-to-state
1289 (when newstate
(org-todo newstate
))))
1290 ((and org-clock-in-switch-to-state
1291 (not (looking-at (concat org-outline-regexp
"[ \t]*"
1292 org-clock-in-switch-to-state
1294 (org-todo org-clock-in-switch-to-state
)))
1295 (setq org-clock-heading
(org-clock--mode-line-heading))
1296 (org-clock-find-position org-clock-in-resume
)
1298 ((and org-clock-in-resume
1300 (concat "^[ \t]*" org-clock-string
1301 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1302 " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1303 (message "Matched %s" (match-string 1))
1304 (setq ts
(concat "[" (match-string 1) "]"))
1305 (goto-char (match-end 1))
1306 (setq org-clock-start-time
1308 (org-parse-time-string (match-string 1))))
1309 (setq org-clock-effort
(org-entry-get (point) org-effort-property
))
1310 (setq org-clock-total-time
(org-clock-sum-current-item
1311 (org-clock-get-sum-start))))
1312 ((eq org-clock-in-resume
'auto-restart
)
1313 ;; called from org-clock-load during startup,
1314 ;; do not interrupt, but warn!
1315 (message "Cannot restart clock because task does not contain unfinished clock")
1320 (insert-before-markers "\n")
1323 (when (and (save-excursion
1326 (beginning-of-line 1)
1327 (indent-line-to (- (current-indentation) 2)))
1328 (insert org-clock-string
" ")
1329 (setq org-clock-effort
(org-entry-get (point) org-effort-property
))
1330 (setq org-clock-total-time
(org-clock-sum-current-item
1331 (org-clock-get-sum-start)))
1332 (setq org-clock-start-time
1333 (or (and org-clock-continuously org-clock-out-time
)
1337 "You stopped another clock %d mins ago; start this one from then? "
1339 (org-current-time org-clock-rounding-minutes t
))
1340 (float-time leftover
))
1344 (org-current-time org-clock-rounding-minutes t
)))
1345 (setq ts
(org-insert-time-stamp org-clock-start-time
1346 'with-hm
'inactive
))))
1347 (move-marker org-clock-marker
(point) (buffer-base-buffer))
1348 (move-marker org-clock-hd-marker
1349 (save-excursion (org-back-to-heading t
) (point))
1350 (buffer-base-buffer))
1351 (setq org-clock-has-been-used t
)
1353 (when (or (eq org-clock-clocked-in-display
'mode-line
)
1354 (eq org-clock-clocked-in-display
'both
))
1355 (or global-mode-string
(setq global-mode-string
'("")))
1356 (or (memq 'org-mode-line-string global-mode-string
)
1357 (setq global-mode-string
1358 (append global-mode-string
'(org-mode-line-string)))))
1359 ;; add to frame title
1360 (when (or (eq org-clock-clocked-in-display
'frame-title
)
1361 (eq org-clock-clocked-in-display
'both
))
1362 (setq frame-title-format org-clock-frame-title-format
))
1363 (org-clock-update-mode-line)
1364 (when org-clock-mode-line-timer
1365 (cancel-timer org-clock-mode-line-timer
)
1366 (setq org-clock-mode-line-timer nil
))
1367 (when org-clock-clocked-in-display
1368 (setq org-clock-mode-line-timer
1369 (run-with-timer org-clock-update-period
1370 org-clock-update-period
1371 'org-clock-update-mode-line
)))
1372 (when org-clock-idle-timer
1373 (cancel-timer org-clock-idle-timer
)
1374 (setq org-clock-idle-timer nil
))
1375 (setq org-clock-idle-timer
1376 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
1377 (message "Clock starts at %s - %s" ts org--msg-extra
)
1378 (run-hooks 'org-clock-in-hook
))))))
1381 (defun org-clock-in-last (&optional arg
)
1382 "Clock in the last closed clocked item.
1383 When already clocking in, send a warning.
1384 With a universal prefix argument, select the task you want to
1385 clock in from the last clocked in tasks.
1386 With two universal prefix arguments, start clocking using the
1387 last clock-out time, if any.
1388 With three universal prefix arguments, interactively prompt
1389 for a todo state to switch to, overriding the existing value
1390 `org-clock-in-switch-to-state'."
1392 (if (equal arg
'(4)) (org-clock-in arg
)
1393 (let ((start-time (if (or org-clock-continuously
(equal arg
'(16)))
1394 (or org-clock-out-time
1395 (org-current-time org-clock-rounding-minutes t
))
1396 (org-current-time org-clock-rounding-minutes t
))))
1397 (if (null org-clock-history
)
1398 (message "No last clock")
1399 (let ((org-clock-in-switch-to-state
1400 (if (and (not org-clock-current-task
) (equal arg
'(64)))
1401 (completing-read "Switch to state: "
1402 (and org-clock-history
1403 (with-current-buffer
1404 (marker-buffer (car org-clock-history
))
1405 org-todo-keywords-1
)))
1406 org-clock-in-switch-to-state
))
1407 (already-clocking org-clock-current-task
))
1408 (org-clock-clock-in (list (car org-clock-history
)) nil start-time
)
1409 (or already-clocking
1410 ;; Don't display a message if we are already clocking in
1411 (message "Clocking back: %s (in %s)"
1412 org-clock-current-task
1413 (buffer-name (marker-buffer org-clock-marker
)))))))))
1415 (defun org-clock-mark-default-task ()
1416 "Mark current task as default task."
1419 (org-back-to-heading t
)
1420 (move-marker org-clock-default-task
(point))))
1422 (defun org-clock-get-sum-start ()
1423 "Return the time from which clock times should be counted.
1425 This is for the currently running clock as it is displayed in the
1426 mode line. This function looks at the properties LAST_REPEAT and
1427 in particular CLOCK_MODELINE_TOTAL and the corresponding variable
1428 `org-clock-mode-line-total' and then decides which time to use.
1430 The time is always returned as UTC."
1431 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL" 'selective
)
1432 (symbol-name org-clock-mode-line-total
)))
1433 (lr (org-entry-get nil
"LAST_REPEAT")))
1435 ((equal cmt
"current")
1436 (setq org--msg-extra
"showing time in current clock instance")
1438 ((equal cmt
"today")
1439 (setq org--msg-extra
"showing today's task time.")
1440 (let* ((dt (decode-time))
1443 (if (< hour org-extend-today-until
) (setf (nth 3 dt
) (1- day
)))
1444 (setf (nth 2 dt
) org-extend-today-until
)
1445 (apply #'encode-time
(append (list 0 0) (nthcdr 2 dt
)))))
1446 ((or (equal cmt
"all")
1447 (and (or (not cmt
) (equal cmt
"auto"))
1449 (setq org--msg-extra
"showing entire task time.")
1451 ((or (equal cmt
"repeat")
1452 (and (or (not cmt
) (equal cmt
"auto"))
1454 (setq org--msg-extra
"showing task time since last repeat.")
1455 (and lr
(org-time-string-to-time lr
)))
1458 (defun org-clock-find-position (find-unclosed)
1459 "Find the location where the next clock line should be inserted.
1460 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1461 line and position cursor in that line."
1462 (org-back-to-heading t
)
1464 (let* ((beg (line-beginning-position))
1465 (end (save-excursion (outline-next-heading) (point)))
1466 (org-clock-into-drawer (org-clock-into-drawer))
1467 (drawer (org-clock-drawer-name)))
1468 ;; Look for a running clock if FIND-UNCLOSED in non-nil.
1470 (let ((open-clock-re
1473 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1474 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1475 (while (re-search-forward open-clock-re end t
)
1476 (let ((element (org-element-at-point)))
1477 (when (and (eq (org-element-type element
) 'clock
)
1478 (eq (org-element-property :status element
) 'running
))
1480 (throw 'exit t
))))))
1481 ;; Look for an existing clock drawer.
1484 (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer
) ":[ \t]*$")))
1485 (while (re-search-forward drawer-re end t
)
1486 (let ((element (org-element-at-point)))
1487 (when (eq (org-element-type element
) 'drawer
)
1488 (let ((cend (org-element-property :contents-end element
)))
1489 (if (and (not org-log-states-order-reversed
) cend
)
1492 (throw 'exit t
)))))))
1494 (let ((clock-re (concat "^[ \t]*" org-clock-string
))
1497 ;; Count the CLOCK lines and store their positions.
1499 (while (re-search-forward clock-re end t
)
1500 (let ((element (org-element-at-point)))
1501 (when (eq (org-element-type element
) 'clock
)
1502 (setq positions
(cons (line-beginning-position) positions
)
1503 count
(1+ count
))))))
1506 ;; Skip planning line and property drawer, if any.
1507 (org-end-of-meta-data)
1508 (unless (bolp) (insert "\n"))
1509 ;; Create a new drawer if necessary.
1510 (when (and org-clock-into-drawer
1511 (or (not (wholenump org-clock-into-drawer
))
1512 (< org-clock-into-drawer
2)))
1513 (let ((beg (point)))
1514 (insert ":" drawer
":\n:END:\n")
1515 (org-indent-region beg
(point))
1517 (line-end-position -
1) (1- (point)) t
'org-hide-drawer
)
1518 (forward-line -
1))))
1519 ;; When a clock drawer needs to be created because of the
1520 ;; number of clock items or simply if it is missing, collect
1521 ;; all clocks in the section and wrap them within the drawer.
1522 ((if (wholenump org-clock-into-drawer
)
1523 (>= (1+ count
) org-clock-into-drawer
)
1525 ;; Skip planning line and property drawer, if any.
1526 (org-end-of-meta-data)
1527 (let ((beg (point)))
1533 (org-trim (delete-and-extract-region
1534 (save-excursion (skip-chars-backward " \r\t\n")
1535 (line-beginning-position 2))
1536 (line-beginning-position 2)))))
1539 (let ((end (point-marker)))
1541 (save-excursion (insert ":" drawer
":\n"))
1542 (org-flag-region (line-end-position) (1- end
) t
'org-hide-drawer
)
1543 (org-indent-region (point) end
)
1545 (unless org-log-states-order-reversed
1547 (beginning-of-line -
1))
1548 (set-marker end nil
))))
1549 (org-log-states-order-reversed (goto-char (car (last positions
))))
1550 (t (goto-char (car positions
))))))))
1553 (defun org-clock-out (&optional switch-to-state fail-quietly at-time
)
1554 "Stop the currently running clock.
1555 Throw an error if there is no running clock and FAIL-QUIETLY is nil.
1556 With a universal prefix, prompt for a state to switch the clocked out task
1557 to, overriding the existing value of `org-clock-out-switch-to-state'."
1560 (when (not (org-clocking-p))
1561 (setq global-mode-string
1562 (delq 'org-mode-line-string global-mode-string
))
1563 (setq frame-title-format org-frame-title-format-backup
)
1564 (force-mode-line-update)
1565 (if fail-quietly
(throw 'exit t
) (user-error "No active clock")))
1566 (let ((org-clock-out-switch-to-state
1568 (completing-read "Switch to state: "
1569 (with-current-buffer
1570 (marker-buffer org-clock-marker
)
1571 org-todo-keywords-1
)
1573 org-clock-out-switch-to-state
))
1574 (now (org-current-time org-clock-rounding-minutes
))
1576 (setq org-clock-out-time now
)
1577 (save-excursion ; Do not replace this with `with-current-buffer'.
1578 (with-no-warnings (set-buffer (org-clocking-buffer)))
1581 (goto-char org-clock-marker
)
1582 (beginning-of-line 1)
1583 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1584 (equal (match-string 1) org-clock-string
))
1585 (setq ts
(match-string 2))
1586 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1587 (goto-char (match-end 0))
1588 (delete-region (point) (point-at-eol))
1590 (setq te
(org-insert-time-stamp (or at-time now
) 'with-hm
'inactive
))
1591 (setq s
(- (float-time
1592 (apply #'encode-time
(org-parse-time-string te
)))
1594 (apply #'encode-time
(org-parse-time-string ts
))))
1595 h
(floor (/ s
3600))
1599 (insert " => " (format "%2d:%02d" h m
))
1600 (move-marker org-clock-marker nil
)
1601 (move-marker org-clock-hd-marker nil
)
1602 ;; Possibly remove zero time clocks. However, do not add
1603 ;; a note associated to the CLOCK line in this case.
1604 (cond ((and org-clock-out-remove-zero-time-clocks
1607 (delete-region (line-beginning-position)
1608 (line-beginning-position 2)))
1609 (org-log-note-clock-out
1611 'clock-out nil nil nil
1612 (concat "# Task: " (org-get-heading t
) "\n\n"))))
1613 (when org-clock-mode-line-timer
1614 (cancel-timer org-clock-mode-line-timer
)
1615 (setq org-clock-mode-line-timer nil
))
1616 (when org-clock-idle-timer
1617 (cancel-timer org-clock-idle-timer
)
1618 (setq org-clock-idle-timer nil
))
1619 (setq global-mode-string
1620 (delq 'org-mode-line-string global-mode-string
))
1621 (setq frame-title-format org-frame-title-format-backup
)
1622 (when org-clock-out-switch-to-state
1624 (org-back-to-heading t
)
1625 (let ((org-clock-out-when-done nil
))
1627 ((functionp org-clock-out-switch-to-state
)
1628 (let ((case-fold-search nil
))
1629 (looking-at org-complex-heading-regexp
))
1630 (let ((newstate (funcall org-clock-out-switch-to-state
1632 (when newstate
(org-todo newstate
))))
1633 ((and org-clock-out-switch-to-state
1634 (not (looking-at (concat org-outline-regexp
"[ \t]*"
1635 org-clock-out-switch-to-state
1637 (org-todo org-clock-out-switch-to-state
))))))
1638 (force-mode-line-update)
1640 "Clock stopped at %s after %s => LINE REMOVED"
1641 "Clock stopped at %s after %s")
1642 te
(org-duration-from-minutes (+ (* 60 h
) m
)))
1643 (run-hooks 'org-clock-out-hook
)
1644 (unless (org-clocking-p)
1645 (setq org-clock-current-task nil
)))))))
1647 (add-hook 'org-clock-out-hook
'org-clock-remove-empty-clock-drawer
)
1649 (defun org-clock-remove-empty-clock-drawer ()
1650 "Remove empty clock drawers in current subtree."
1652 (org-back-to-heading t
)
1655 (let ((drawer (org-clock-drawer-name))
1656 (case-fold-search t
))
1658 (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer
)))
1659 (end (save-excursion (outline-next-heading))))
1660 (while (re-search-forward re end t
)
1661 (org-remove-empty-drawer-at (point))))))))))
1663 (defun org-clock-timestamps-up (&optional n
)
1664 "Increase CLOCK timestamps at cursor.
1665 Optional argument N tells to change by that many units."
1667 (org-clock-timestamps-change 'up n
))
1669 (defun org-clock-timestamps-down (&optional n
)
1670 "Increase CLOCK timestamps at cursor.
1671 Optional argument N tells to change by that many units."
1673 (org-clock-timestamps-change 'down n
))
1675 (defun org-clock-timestamps-change (updown &optional n
)
1676 "Change CLOCK timestamps synchronously at cursor.
1677 UPDOWN tells whether to change `up' or `down'.
1678 Optional argument N tells to change by that many units."
1679 (let ((tschange (if (eq updown
'up
) 'org-timestamp-up
1680 'org-timestamp-down
))
1681 (timestamp?
(org-at-timestamp-p 'lax
))
1682 ts1 begts1 ts2 begts2 updatets1 tdiff
)
1685 (move-beginning-of-line 1)
1686 (re-search-forward org-ts-regexp3 nil t
)
1687 (setq ts1
(match-string 0) begts1
(match-beginning 0))
1688 (when (re-search-forward org-ts-regexp3 nil t
)
1689 (setq ts2
(match-string 0) begts2
(match-beginning 0))))
1690 ;; Are we on the second timestamp?
1691 (if (<= begts2
(point)) (setq updatets1 t
))
1693 ;; fall back on org-timestamp-up if there is only one
1694 (funcall tschange n
)
1695 (funcall tschange n
)
1696 (let ((ts (if updatets1 ts2 ts1
))
1697 (begts (if updatets1 begts1 begts2
)))
1700 (org-time-string-to-time org-last-changed-timestamp
)
1701 (org-time-string-to-time ts
)))
1704 (org-timestamp-change
1705 (round (/ (float-time tdiff
)
1710 (`month
(* 24 3600 31))
1711 (`year
(* 24 3600 365.2)))))
1712 timestamp?
'updown
)))))))
1715 (defun org-clock-cancel ()
1716 "Cancel the running clock by removing the start timestamp."
1718 (when (not (org-clocking-p))
1719 (setq global-mode-string
1720 (delq 'org-mode-line-string global-mode-string
))
1721 (setq frame-title-format org-frame-title-format-backup
)
1722 (force-mode-line-update)
1723 (error "No active clock"))
1724 (save-excursion ; Do not replace this with `with-current-buffer'.
1725 (with-no-warnings (set-buffer (org-clocking-buffer)))
1726 (goto-char org-clock-marker
)
1727 (if (looking-back (concat "^[ \t]*" org-clock-string
".*")
1728 (line-beginning-position))
1729 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1730 (org-remove-empty-drawer-at (point)))
1731 (message "Clock gone, cancel the timer anyway")
1733 (move-marker org-clock-marker nil
)
1734 (move-marker org-clock-hd-marker nil
)
1735 (setq global-mode-string
1736 (delq 'org-mode-line-string global-mode-string
))
1737 (setq frame-title-format org-frame-title-format-backup
)
1738 (force-mode-line-update)
1739 (message "Clock canceled")
1740 (run-hooks 'org-clock-cancel-hook
))
1743 (defun org-clock-goto (&optional select
)
1744 "Go to the currently clocked-in entry, or to the most recently clocked one.
1745 With prefix arg SELECT, offer recently clocked tasks for selection."
1750 (or (org-clock-select-task "Select task to go to: ")
1751 (error "No task selected")))
1752 ((org-clocking-p) org-clock-marker
)
1753 ((and org-clock-goto-may-find-recent-task
1754 (car org-clock-history
)
1755 (marker-buffer (car org-clock-history
)))
1757 (car org-clock-history
))
1758 (t (error "No active or recent clock task")))))
1759 (pop-to-buffer-same-window (marker-buffer m
))
1760 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1763 (org-back-to-heading t
)
1764 (recenter org-clock-goto-before-context
)
1767 (message "No running clock, this is the most recently clocked task"))
1768 (run-hooks 'org-clock-goto-hook
)))
1770 (defvar-local org-clock-file-total-minutes nil
1771 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1774 (defun org-clock-sum-today (&optional headline-filter
)
1775 "Sum the times for each subtree for today."
1776 (let ((range (org-clock-special-range 'today
)))
1777 (org-clock-sum (car range
) (cadr range
)
1778 headline-filter
:org-clock-minutes-today
)))
1780 (defun org-clock-sum-custom (&optional headline-filter range propname
)
1781 "Sum the times for each subtree for today."
1782 (let ((r (or (and (symbolp range
) (org-clock-special-range range
))
1783 (org-clock-special-range
1784 (intern (completing-read
1786 '("today" "yesterday" "thisweek" "lastweek"
1787 "thismonth" "lastmonth" "thisyear" "lastyear"
1790 (org-clock-sum (car r
) (cadr r
)
1791 headline-filter
(or propname
:org-clock-minutes-custom
))))
1794 (defun org-clock-sum (&optional tstart tend headline-filter propname
)
1795 "Sum the times for each subtree.
1796 Puts the resulting times in minutes as a text property on each headline.
1797 TSTART and TEND can mark a time range to be considered.
1798 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1799 each headline in the time range with point at the headline. Headlines for
1800 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1801 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1802 (with-silent-modifications
1803 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1805 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1807 (ltimes (make-vector lmax
0))
1809 (tstart (cond ((stringp tstart
) (org-time-string-to-seconds tstart
))
1810 ((consp tstart
) (float-time tstart
))
1812 (tend (cond ((stringp tend
) (org-time-string-to-seconds tend
))
1813 ((consp tend
) (float-time tend
))
1817 (remove-text-properties (point-min) (point-max)
1818 `(,(or propname
:org-clock-minutes
) t
1819 :org-clock-force-headline-inclusion t
))
1821 (goto-char (point-max))
1822 (while (re-search-backward re nil t
)
1826 (let* ((ts (float-time
1827 (apply #'encode-time
1829 (org-parse-time-string (match-string 2))))))
1831 (apply #'encode-time
1832 (org-parse-time-string (match-string 3)))))
1833 (dt (- (if tend
(min te tend
) te
)
1834 (if tstart
(max ts tstart
) ts
))))
1835 (when (> dt
0) (cl-incf t1
(floor (/ dt
60))))))
1838 (setq t1
(+ t1
(string-to-number (match-string 5))
1839 (* 60 (string-to-number (match-string 4))))))
1841 ;; Add the currently clocking item time to the total.
1842 (when (and org-clock-report-include-clocking-task
1843 (eq (org-clocking-buffer) (current-buffer))
1844 (eq (marker-position org-clock-hd-marker
) (point))
1847 (>= (float-time org-clock-start-time
) tstart
)
1848 (<= (float-time org-clock-start-time
) tend
))
1849 (let ((time (floor (- (float-time)
1850 (float-time org-clock-start-time
))
1852 (setq t1
(+ t1 time
))))
1853 (let* ((headline-forced
1854 (get-text-property (point)
1855 :org-clock-force-headline-inclusion
))
1857 (or (null headline-filter
)
1859 (save-match-data (funcall headline-filter
))))))
1860 (setq level
(- (match-end 1) (match-beginning 1)))
1861 (when (>= level lmax
)
1862 (setq ltimes
(vconcat ltimes
(make-vector lmax
0)) lmax
(* 2 lmax
)))
1863 (when (or (> t1
0) (> (aref ltimes level
) 0))
1864 (when (or headline-included headline-forced
)
1865 (if headline-included
1866 (cl-loop for l from
0 to level do
1867 (aset ltimes l
(+ (aref ltimes l
) t1
))))
1868 (setq time
(aref ltimes level
))
1869 (goto-char (match-beginning 0))
1870 (put-text-property (point) (point-at-eol)
1871 (or propname
:org-clock-minutes
) time
)
1872 (when headline-filter
1875 (while (org-up-heading-safe)
1877 (point) (line-end-position)
1878 :org-clock-force-headline-inclusion t
))))))
1880 (cl-loop for l from level to
(1- lmax
) do
1881 (aset ltimes l
0)))))))
1882 (setq org-clock-file-total-minutes
(aref ltimes
0))))))
1884 (defun org-clock-sum-current-item (&optional tstart
)
1885 "Return time, clocked on current item in total."
1888 (org-narrow-to-subtree)
1889 (org-clock-sum tstart
)
1890 org-clock-file-total-minutes
)))
1893 (defun org-clock-display (&optional arg
)
1894 "Show subtree times in the entire buffer.
1896 By default, show the total time for the range defined in
1897 `org-clock-display-default-range'. With `\\[universal-argument]' \
1899 the total time for today instead.
1901 With `\\[universal-argument] \\[universal-argument]' prefix, \
1902 use a custom range, entered at prompt.
1904 With `\\[universal-argument] \ \\[universal-argument] \
1905 \\[universal-argument]' prefix, display the total time in the
1908 Use `\\[org-clock-remove-overlays]' to remove the subtree times."
1910 (org-clock-remove-overlays)
1911 (let* ((todayp (equal arg
'(4)))
1912 (customp (member arg
'((16) today yesterday
1913 thisweek lastweek thismonth
1914 lastmonth thisyear lastyear
1915 untilnow interactive
)))
1916 (prop (cond ((not arg
) :org-clock-minutes-default
)
1917 (todayp :org-clock-minutes-today
)
1918 (customp :org-clock-minutes-custom
)
1919 (t :org-clock-minutes
))))
1920 (cond ((not arg
) (org-clock-sum-custom
1921 nil org-clock-display-default-range prop
))
1922 (todayp (org-clock-sum-today))
1923 (customp (org-clock-sum-custom nil arg
))
1924 (t (org-clock-sum)))
1925 (unless (equal arg
'(64))
1927 (goto-char (point-min))
1929 (while (or (and (equal (setq p
(point)) (point-min))
1930 (get-text-property p prop
))
1931 (setq p
(next-single-property-change (point) prop
)))
1933 (let ((time (get-text-property p prop
)))
1934 (when time
(org-clock-put-overlay time
)))))
1935 ;; Arrange to remove the overlays upon next change.
1936 (when org-remove-highlights-with-change
1937 (add-hook 'before-change-functions
'org-clock-remove-overlays
1939 (let* ((h (/ org-clock-file-total-minutes
60))
1940 (m (- org-clock-file-total-minutes
(* 60 h
))))
1943 "Total file time for today: %s (%d hours and %d minutes)")
1945 "Total file time (custom): %s (%d hours and %d minutes)")
1947 "Total file time: %s (%d hours and %d minutes)"))
1948 (org-duration-from-minutes org-clock-file-total-minutes
)
1951 (defvar-local org-clock-overlays nil
)
1953 (defun org-clock-put-overlay (time)
1954 "Put an overlay on the headline at point, displaying TIME.
1955 Create a new overlay and store it in `org-clock-overlays', so
1956 that it will be easy to remove. This function assumes point is
1958 (org-match-line org-complex-heading-regexp
)
1959 (goto-char (match-beginning 4))
1960 (let* ((headline (match-string 4))
1961 (text (concat headline
1964 (max (- (- 60 (current-column))
1965 (org-string-width headline
)
1966 (length (org-get-at-bol 'line-prefix
)))
1971 (format " %9s " (org-duration-from-minutes time
))
1972 '(face org-clock-overlay
))))
1973 (o (make-overlay (point) (line-end-position))))
1974 (org-overlay-display o text
)
1975 (push o org-clock-overlays
)))
1978 (defun org-clock-remove-overlays (&optional _beg _end noremove
)
1979 "Remove the occur highlights from the buffer.
1980 If NOREMOVE is nil, remove this function from the
1981 `before-change-functions' in the current buffer."
1983 (unless org-inhibit-highlight-removal
1984 (mapc #'delete-overlay org-clock-overlays
)
1985 (setq org-clock-overlays nil
)
1987 (remove-hook 'before-change-functions
1988 'org-clock-remove-overlays
'local
))))
1991 (defun org-clock-out-if-current ()
1992 "Clock out if the current entry contains the running clock.
1993 This is used to stop the clock after a TODO entry is marked DONE,
1994 and is only done if the variable `org-clock-out-when-done' is not nil."
1995 (when (and (org-clocking-p)
1996 org-clock-out-when-done
1997 (marker-buffer org-clock-marker
)
1998 (or (and (eq t org-clock-out-when-done
)
1999 (member org-state org-done-keywords
))
2000 (and (listp org-clock-out-when-done
)
2001 (member org-state org-clock-out-when-done
)))
2002 (equal (or (buffer-base-buffer (org-clocking-buffer))
2003 (org-clocking-buffer))
2004 (or (buffer-base-buffer (current-buffer))
2006 (< (point) org-clock-marker
)
2007 (> (org-with-wide-buffer (org-entry-end-position))
2009 ;; Clock out, but don't accept a logging message for this.
2010 (let ((org-log-note-clock-out nil
)
2011 (org-clock-out-switch-to-state nil
))
2015 (defun org-clock-get-clocktable (&rest props
)
2016 "Get a formatted clocktable with parameters according to PROPS.
2017 The table is created in a temporary buffer, fully formatted and
2018 fontified, and then returned."
2020 (setq props
(plist-put props
:name
"clocktable"))
2021 (unless (plist-member props
:maxlevel
)
2022 (setq props
(plist-put props
:maxlevel
2)))
2023 (unless (plist-member props
:scope
)
2024 (setq props
(plist-put props
:scope
'agenda
)))
2027 (org-create-dblock props
)
2029 (org-font-lock-ensure)
2031 (buffer-substring (point) (progn
2032 (re-search-forward "^[ \t]*#\\+END" nil t
)
2036 (defun org-clock-report (&optional arg
)
2037 "Update or create a table containing a report about clocked time.
2039 If point is inside an existing clocktable block, update it.
2040 Otherwise, insert a new one.
2042 The new table inherits its properties from the variable
2043 `org-clock-clocktable-default-properties'. The scope of the
2044 clocktable, when not specified in the previous variable, is
2045 `subtree' when the function is called from within a subtree, and
2048 When called with a prefix argument, move to the first clock table
2049 in the buffer and update it."
2051 (org-clock-remove-overlays)
2053 (org-find-dblock "clocktable")
2055 (pcase (org-in-clocktable-p)
2059 (list :scope
(if (org-before-first-heading-p) 'file
'subtree
))
2060 org-clock-clocktable-default-properties
2061 '(:name
"clocktable"))))
2062 (start (goto-char start
)))
2063 (org-update-dblock))
2065 (org-dynamic-block-define "clocktable" #'org-clock-report
)
2067 (defun org-day-of-week (day month year
)
2068 "Returns the day of the week as an integer."
2072 (format "%d-%02d-%02dT00:00:00" year month day
)))))
2074 (defun org-quarter-to-date (quarter year
)
2075 "Get the date (week day year) of the first day of a given quarter."
2079 (setq startday
(org-day-of-week 1 1 year
))
2082 (list 52 7 (- year
1)))
2084 (list 52 6 (- year
1)))
2086 (list 1 startday year
))
2088 (list 53 startday
(- year
1)))
2092 (setq startday
(org-day-of-week 1 4 year
))
2095 (list 13 startday year
))
2097 (list 14 startday year
))
2099 (list 13 startday year
))
2103 (setq startday
(org-day-of-week 1 7 year
))
2106 (list 26 startday year
))
2108 (list 27 startday year
))
2110 (list 26 startday year
))
2114 (setq startday
(org-day-of-week 1 10 year
))
2117 (list 39 startday year
))
2119 (list 40 startday year
))
2121 (list 39 startday year
)))))))
2123 (defun org-clock-special-range (key &optional time as-strings wstart mstart
)
2124 "Return two times bordering a special time range.
2126 KEY is a symbol specifying the range and can be one of `today',
2127 `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
2128 `thisyear', `lastyear' or `untilnow'. If set to `interactive',
2129 user is prompted for range boundaries. It can be a string or an
2132 By default, a week starts Monday 0:00 and ends Sunday 24:00. The
2133 range is determined relative to TIME, which defaults to current
2136 The return value is a list containing two internal times, one for
2137 the beginning of the range and one for its end, like the ones
2138 returned by `current-time' or `encode-time' and a string used to
2139 display information. If AS-STRINGS is non-nil, the returned
2140 times will be formatted strings. Note that the first element is
2141 always nil when KEY is `untilnow'.
2143 If WSTART is non-nil, use this number to specify the starting day
2144 of a week (monday is 1). If MSTART is non-nil, use this number
2145 to specify the starting day of a month (1 is the first day of the
2146 month). If you can combine both, the month starting day will
2148 (let* ((tm (decode-time time
))
2155 (skey (format "%s" key
))
2157 (q (cond ((>= month
10) 4)
2161 m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq
)
2163 ((string-match "\\`[0-9]+\\'" skey
)
2164 (setq y
(string-to-number skey
) month
1 d
1 key
'year
))
2165 ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey
)
2166 (setq y
(string-to-number (match-string 1 skey
))
2167 month
(string-to-number (match-string 2 skey
))
2170 ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey
)
2172 (let ((date (calendar-gregorian-from-absolute
2173 (calendar-iso-to-absolute
2174 (list (string-to-number (match-string 2 skey
))
2176 (string-to-number (match-string 1 skey
)))))))
2177 (setq d
(nth 1 date
)
2182 ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey
)
2184 (setq q
(string-to-number (match-string 2 skey
)))
2185 (let ((date (calendar-gregorian-from-absolute
2186 (calendar-iso-to-absolute
2187 (org-quarter-to-date
2188 q
(string-to-number (match-string 1 skey
)))))))
2189 (setq d
(nth 1 date
)
2195 "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
2197 (setq y
(string-to-number (match-string 1 skey
))
2198 month
(string-to-number (match-string 2 skey
))
2199 d
(string-to-number (match-string 3 skey
))
2201 ((string-match "\\([-+][0-9]+\\)\\'" skey
)
2202 (setq shift
(string-to-number (match-string 1 skey
))
2203 key
(intern (substring skey
0 (match-beginning 1))))
2204 (when (and (memq key
'(quarter thisq
)) (> shift
0))
2205 (error "Looking forward with quarters isn't implemented"))))
2208 (`yesterday
(setq key
'today shift -
1))
2209 (`lastweek
(setq key
'week shift -
1))
2210 (`lastmonth
(setq key
'month shift -
1))
2211 (`lastyear
(setq key
'year shift -
1))
2212 (`lastq
(setq key
'quarter shift -
1))))
2213 ;; Prepare start and end times depending on KEY's type.
2215 ((or `day
`today
) (setq m
0
2216 h org-extend-today-until
2217 h1
(+ 24 org-extend-today-until
)
2219 ((or `week
`thisweek
)
2220 (let* ((ws (or wstart
1))
2221 (diff (+ (* -
7 shift
) (if (= dow
0) (- 7 ws
) (- dow ws
)))))
2222 (setq m
0 h org-extend-today-until d
(- d diff
) d1
(+ 7 d
))))
2223 ((or `month
`thismonth
)
2224 (setq h org-extend-today-until m
0 d
(or mstart
1)
2225 month
(+ month shift
) month1
(1+ month
)))
2226 ((or `quarter
`thisq
)
2227 ;; Compute if this shift remains in this year. If not, compute
2228 ;; how many years and quarters we have to shift (via floor*) and
2229 ;; compute the shifted years, months and quarters.
2231 ((< (+ (- q
1) shift
) 0) ; Shift not in this year.
2232 (let* ((interval (* -
1 (+ (- q
1) shift
)))
2233 ;; Set tmp to ((years to shift) (quarters to shift)).
2234 (tmp (cl-floor interval
4)))
2235 ;; Due to the use of floor, 0 quarters actually means 4.
2236 (if (= 0 (nth 1 tmp
))
2237 (setq shiftedy
(- y
(nth 0 tmp
))
2240 (setq shiftedy
(- y
(+ 1 (nth 0 tmp
)))
2241 shiftedm
(- 13 (* 3 (nth 1 tmp
)))
2242 shiftedq
(- 5 (nth 1 tmp
)))))
2243 (setq m
0 h org-extend-today-until d
1
2244 month shiftedm month1
(+ 3 shiftedm
) y shiftedy
))
2245 ((> (+ q shift
) 0) ; Shift is within this year.
2246 (setq shiftedq
(+ q shift
))
2248 (let ((qshift (* 3 (1- (+ q shift
)))))
2249 (setq m
0 h org-extend-today-until d
1
2250 month
(+ 1 qshift
) month1
(+ 4 qshift
))))))
2251 ((or `year
`thisyear
)
2252 (setq m
0 h org-extend-today-until d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
2253 ((or `interactive
`untilnow
)) ; Special cases, ignore them.
2254 (_ (user-error "No such time block %s" key
)))
2255 ;; Format start and end times according to AS-STRINGS.
2256 (let* ((start (pcase key
2257 (`interactive
(org-read-date nil t nil
"Range start? "))
2259 (_ (encode-time 0 m h d month y
))))
2261 (`interactive
(org-read-date nil t nil
"Range end? "))
2262 (`untilnow
(current-time))
2271 ((or `day
`today
) (format-time-string "%A, %B %d, %Y" start
))
2272 ((or `week
`thisweek
) (format-time-string "week %G-W%V" start
))
2273 ((or `month
`thismonth
) (format-time-string "%B %Y" start
))
2274 ((or `year
`thisyear
) (format-time-string "the year %Y" start
))
2275 ((or `quarter
`thisq
)
2276 (concat (org-count-quarter shiftedq
)
2277 " quarter of " (number-to-string shiftedy
)))
2278 (`interactive
"(Range interactively set)")
2279 (`untilnow
"now"))))
2280 (if (not as-strings
) (list start end text
)
2281 (let ((f (cdr org-time-stamp-formats
)))
2282 (list (and start
(format-time-string f start
))
2283 (format-time-string f end
)
2286 (defun org-count-quarter (n)
2294 (defun org-clocktable-shift (dir n
)
2295 "Try to shift the :block date of the clocktable at point.
2296 Point must be in the #+BEGIN: line of a clocktable, or this function
2297 will throw an error.
2298 DIR is a direction, a symbol `left', `right', `up', or `down'.
2299 Both `left' and `down' shift the block toward the past, `up' and `right'
2300 push it toward the future.
2301 N is the number of shift steps to take. The size of the step depends on
2302 the currently selected interval size."
2303 (setq n
(prefix-numeric-value n
))
2304 (and (memq dir
'(left down
)) (setq n
(- n
)))
2306 (goto-char (point-at-bol))
2307 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2308 (error "Line needs a :block definition before this command works")
2309 (let* ((b (match-beginning 1)) (e (match-end 1))
2310 (s (match-string 1))
2311 block shift ins y mw d date wp m
)
2313 ((equal s
"yesterday") (setq s
"today-1"))
2314 ((equal s
"lastweek") (setq s
"thisweek-1"))
2315 ((equal s
"lastmonth") (setq s
"thismonth-1"))
2316 ((equal s
"lastyear") (setq s
"thisyear-1"))
2317 ((equal s
"lastq") (setq s
"thisq-1")))
2320 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s
)
2321 (setq block
(match-string 1 s
)
2322 shift
(if (match-end 2)
2323 (string-to-number (match-string 2 s
))
2325 (setq shift
(+ shift n
))
2326 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
2327 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
2328 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2329 (setq y
(string-to-number (match-string 1 s
))
2330 wp
(and (match-end 3) (match-string 3 s
))
2331 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
2332 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
2334 (d (setq ins
(format-time-string
2336 (encode-time 0 0 0 (+ d n
) m y
))))
2337 ((and wp
(string-match "w\\|W" wp
) mw
(> (length wp
) 0))
2339 (setq date
(calendar-gregorian-from-absolute
2340 (calendar-iso-to-absolute (list (+ mw n
) 1 y
))))
2341 (setq ins
(format-time-string
2343 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
2344 ((and wp
(string-match "q\\|Q" wp
) mw
(> (length wp
) 0))
2346 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2351 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2356 (setq date
(calendar-gregorian-from-absolute
2357 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n
) y
))))
2358 (setq ins
(format-time-string
2359 (concat (number-to-string y
) "-Q" (number-to-string (+ mw n
)))
2360 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
2362 (setq ins
(format-time-string
2364 (encode-time 0 0 0 1 (+ mw n
) y
))))
2366 (setq ins
(number-to-string (+ y n
))))))
2367 (t (error "Cannot shift clocktable block")))
2371 (delete-region (point) (+ (point) (- e b
)))
2372 (beginning-of-line 1)
2377 (defun org-dblock-write:clocktable
(params)
2378 "Write the standard clocktable."
2379 (setq params
(org-combine-plists org-clocktable-defaults params
))
2381 (let* ((scope (plist-get params
:scope
))
2384 (org-agenda-files t
))
2385 (`agenda-with-archives
2386 (org-add-archive-files (org-agenda-files t
)))
2387 (`file-with-archives
2388 (and buffer-file-name
2389 (org-add-archive-files (list buffer-file-name
))))
2390 ((or `nil
`file
`subtree
`tree
2392 (guard (string-match "\\`tree\\([0-9]+\\)\\'"
2393 (symbol-name scope
)))))
2394 (or (buffer-file-name (buffer-base-buffer))
2396 ((pred functionp
) (funcall scope
))
2397 ((pred consp
) scope
)
2398 (_ (user-error "Unknown scope: %S" scope
))))
2399 (block (plist-get params
:block
))
2400 (ts (plist-get params
:tstart
))
2401 (te (plist-get params
:tend
))
2402 (ws (plist-get params
:wstart
))
2403 (ms (plist-get params
:mstart
))
2404 (step (plist-get params
:step
))
2405 (formatter (or (plist-get params
:formatter
)
2406 org-clock-clocktable-formatter
2407 'org-clocktable-write-default
))
2409 ;; Check if we need to do steps
2411 ;; Get the range text for the header
2412 (setq cc
(org-clock-special-range block nil t ws ms
)
2416 ;; Write many tables, in steps
2417 (unless (or block
(and ts te
))
2418 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2419 (org-clocktable-steps params
)
2422 (org-agenda-prepare-buffers (if (consp files
) files
(list files
)))
2424 (let ((origin (point))
2427 (mapcar (lambda (file)
2428 (with-current-buffer (find-buffer-visiting file
)
2431 (org-clock-get-table-data file params
)))))
2433 ;; Get the right restriction for the scope.
2436 ((not scope
)) ;use the restriction as it is now
2437 ((eq scope
'file
) (widen))
2438 ((eq scope
'subtree
) (org-narrow-to-subtree))
2440 (while (org-up-heading-safe))
2441 (org-narrow-to-subtree))
2442 ((and (symbolp scope
)
2443 (string-match "\\`tree\\([0-9]+\\)\\'"
2444 (symbol-name scope
)))
2445 (let ((level (string-to-number
2446 (match-string 1 (symbol-name scope
)))))
2448 (while (org-up-heading-safe)
2449 (looking-at org-outline-regexp
)
2450 (when (<= (org-reduced-level (funcall outline-level
))
2452 (throw 'exit nil
))))
2453 (org-narrow-to-subtree))))
2454 (list (org-clock-get-table-data nil params
)))))
2456 ;; Even though `file-with-archives' can consist of
2457 ;; multiple files, we consider this is one extended file
2459 (and (consp files
) (not (eq scope
'file-with-archives
)))))
2464 (org-combine-plists params
`(:multifile
,multifile
)))))))
2466 (defun org-clocktable-write-default (ipos tables params
)
2467 "Write out a clock table at position IPOS in the current buffer.
2468 TABLES is a list of tables with clocking data as produced by
2469 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2470 from the dynamic block definition."
2471 ;; This function looks quite complicated, mainly because there are a
2472 ;; lot of options which can add or remove columns. I have massively
2473 ;; commented this function, the I hope it is understandable. If
2474 ;; someone wants to write their own special formatter, this maybe
2475 ;; much easier because there can be a fixed format with a
2476 ;; well-defined number of columns...
2477 (let* ((lang (or (plist-get params
:lang
) "en"))
2478 (multifile (plist-get params
:multifile
))
2479 (block (plist-get params
:block
))
2480 (sort (plist-get params
:sort
))
2481 (header (plist-get params
:header
))
2482 (link (plist-get params
:link
))
2483 (maxlevel (or (plist-get params
:maxlevel
) 3))
2484 (emph (plist-get params
:emphasize
))
2485 (compact?
(plist-get params
:compact
))
2486 (narrow (or (plist-get params
:narrow
) (and compact?
'40!)))
2487 (level?
(and (not compact?
) (plist-get params
:level
)))
2488 (timestamp (plist-get params
:timestamp
))
2489 (tags (plist-get params
:tags
))
2490 (properties (plist-get params
:properties
))
2492 (if (or compact?
(< maxlevel
2)) 1
2493 ;; Deepest headline level is a hard limit for the number
2499 (`(,_
,(and (pred wholenump
) (pred (/= 0))) ,entries
)
2500 (mapcar #'car entries
))))
2503 (or (plist-get params
:tcolumns
) 100)
2504 (if (null levels
) 1 (apply #'max levels
))))))
2505 (indent (or compact?
(plist-get params
:indent
)))
2506 (formula (plist-get params
:formula
))
2507 (case-fold-search t
)
2508 (total-time (apply #'+ (mapcar #'cadr tables
)))
2509 recalc narrow-cut-p
)
2511 (when (and narrow
(integerp narrow
) link
)
2512 ;; We cannot have both integer narrow and link.
2513 (message "Using hard narrowing in clocktable to allow for links")
2514 (setq narrow
(intern (format "%d!" narrow
))))
2517 ((or `nil
(pred integerp
)) nil
) ;nothing to do
2518 ((and (pred symbolp
)
2519 (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow
))))
2520 (setq narrow-cut-p t
)
2521 (setq narrow
(string-to-number (symbol-name narrow
))))
2522 (_ (error "Invalid value %s of :narrow property in clock table" narrow
)))
2524 ;; Now we need to output this table stuff.
2527 ;; Insert the text *before* the actual table.
2528 (insert-before-markers
2530 ;; Format the standard header.
2531 (format "#+CAPTION: %s %s%s\n"
2532 (org-clock--translate "Clock summary at" lang
)
2533 (format-time-string (org-time-stamp-format t t
))
2536 (nth 2 (org-clock-special-range
2538 (plist-get params
:wstart
)
2539 (plist-get params
:mstart
)))))
2540 (format ", for %s." range-text
))
2543 ;; Insert the narrowing line
2544 (when (and narrow
(integerp narrow
) (not narrow-cut-p
))
2545 (insert-before-markers
2546 "|" ;table line starter
2547 (if multifile
"|" "") ;file column, maybe
2548 (if level?
"|" "") ;level column, maybe
2549 (if timestamp
"|" "") ;timestamp column, maybe
2550 (if tags
"|" "") ;tags columns, maybe
2551 (if properties
;properties columns, maybe
2552 (make-string (length properties
) ?|
)
2554 (format "<%d>| |\n" narrow
))) ;headline and time columns
2556 ;; Insert the table header line
2557 (insert-before-markers
2558 "|" ;table line starter
2559 (if multifile
;file column, maybe
2560 (concat (org-clock--translate "File" lang
) "|")
2562 (if level?
;level column, maybe
2563 (concat (org-clock--translate "L" lang
) "|")
2565 (if timestamp
;timestamp column, maybe
2566 (concat (org-clock--translate "Timestamp" lang
) "|")
2568 (if tags
"Tags |" "") ;tags columns, maybe
2570 (if properties
;properties columns, maybe
2571 (concat (mapconcat #'identity properties
"|") "|")
2573 (concat (org-clock--translate "Headline" lang
)"|")
2574 (concat (org-clock--translate "Time" lang
) "|")
2575 (make-string (max 0 (1- time-columns
)) ?|
) ;other time columns
2576 (if (eq formula
'%
) "%|\n" "\n"))
2578 ;; Insert the total time in the table
2579 (insert-before-markers
2581 "|" ;table line starter
2582 (if multifile
(format "| %s " (org-clock--translate "ALL" lang
)) "")
2584 (if level?
"|" "") ;level column, maybe
2585 (if timestamp
"|" "") ;timestamp column, maybe
2586 (if tags
"|" "") ;timestamp column, maybe
2587 (make-string (length properties
) ?|
) ;properties columns, maybe
2588 (concat (format org-clock-total-time-cell-format
2589 (org-clock--translate "Total time" lang
))
2591 (format org-clock-total-time-cell-format
2592 (org-duration-from-minutes (or total-time
0))) ;time
2594 (make-string (max 0 (1- time-columns
)) ?|
)
2595 (cond ((not (eq formula
'%
)) "")
2596 ((or (not total-time
) (= total-time
0)) "0.0|")
2600 ;; Now iterate over the tables and insert the data but only if any
2601 ;; time has been collected.
2602 (when (and total-time
(> total-time
0))
2603 (pcase-dolist (`(,file-name
,file-time
,entries
) tables
)
2604 (when (or (and file-time
(> file-time
0))
2605 (not (plist-get params
:fileskip0
)))
2606 (insert-before-markers "|-\n") ;hline at new file
2607 ;; First the file time, if we have multiple files.
2609 ;; Summarize the time collected from this file.
2610 (insert-before-markers
2611 (format (concat "| %s %s | %s%s%s"
2612 (format org-clock-file-time-cell-format
2613 (org-clock--translate "File time" lang
))
2615 (file-name-nondirectory file-name
)
2616 (if level?
"| " "") ;level column, maybe
2617 (if timestamp
"| " "") ;timestamp column, maybe
2618 (if tags
"| " "") ;tags column, maybe
2619 (if properties
;properties columns, maybe
2620 (make-string (length properties
) ?|
)
2622 (org-duration-from-minutes file-time
)))) ;time
2624 ;; Get the list of node entries and iterate over it
2625 (when (> maxlevel
0)
2626 (pcase-dolist (`(,level
,headline
,tgs
,ts
,time
,props
) entries
)
2629 (if (and (string-match
2630 (format "\\`%s\\'" org-link-bracket-re
)
2633 (format "[[%s][%s]]"
2634 (match-string 1 headline
)
2635 (org-shorten-string (match-string 2 headline
)
2637 (org-shorten-string headline narrow
))))
2638 (cl-flet ((format-field (f) (format (cond ((not emph
) "%s |")
2639 ((= level
1) "*%s* |")
2640 ((= level
2) "/%s/ |")
2643 (insert-before-markers
2644 "|" ;start the table line
2645 (if multifile
"|" "") ;free space for file name column?
2646 (if level?
(format "%d|" level
) "") ;level, maybe
2647 (if timestamp
(concat ts
"|") "") ;timestamp, maybe
2648 (if tags
(concat (mapconcat #'identity tgs
", ") "|") "") ;tags, maybe
2649 (if properties
;properties columns, maybe
2650 (concat (mapconcat (lambda (p) (or (cdr (assoc p props
)) ""))
2655 (if indent
;indentation
2656 (org-clocktable-indent-string level
)
2658 (format-field headline
)
2659 ;; Empty fields for higher levels.
2660 (make-string (max 0 (1- (min time-columns level
))) ?|
)
2661 (format-field (org-duration-from-minutes time
))
2662 (make-string (max 0 (- time-columns level
)) ?|
)
2664 (format "%.1f |" (* 100 (/ time
(float total-time
))))
2669 ;; Possibly rescue old formula?
2670 ((or (not formula
) (eq formula
'%
))
2671 (let ((contents (org-string-nw-p (plist-get params
:content
))))
2672 (when (and contents
(string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents
))
2674 (insert "\n" (match-string 1 contents
))
2675 (beginning-of-line 0))))
2676 ;; Insert specified formula line.
2678 (insert "\n#+TBLFM: " formula
)
2681 (user-error "Invalid :formula parameter in clocktable")))
2682 ;; Back to beginning, align the table, recalculate if necessary.
2684 (skip-chars-forward "^|")
2686 (when org-hide-emphasis-markers
2687 ;; We need to align a second time.
2691 (org-table-goto-line 3)
2692 (org-table-goto-column (car sort
))
2693 (org-table-sort-lines nil
(cdr sort
))))
2694 (when recalc
(org-table-recalculate 'all
))
2697 (defun org-clocktable-indent-string (level)
2698 "Return indentation string according to LEVEL.
2699 LEVEL is an integer. Indent by two spaces per level above 1."
2701 (concat "\\_" (make-string (* 2 (1- level
)) ?\s
))))
2703 (defun org-clocktable-steps (params)
2704 "Create one or more clock tables, according to PARAMS.
2705 Step through the range specifications in plist PARAMS to make
2706 a number of clock tables."
2707 (let* ((ignore-empty-tables (plist-get params
:stepskip0
))
2708 (step (plist-get params
:step
))
2711 (`day
"Daily report: ")
2712 (`week
"Weekly report starting on: ")
2713 (`month
"Monthly report starting on: ")
2714 (`year
"Annual report starting on: ")
2715 (_ (user-error "Unknown `:step' specification: %S" step
))))
2716 (week-start (or (plist-get params
:wstart
) 1))
2717 (month-start (or (plist-get params
:mstart
) 1))
2719 (pcase (plist-get params
:block
)
2722 (org-clock-special-range range nil t week-start month-start
))))
2723 ;; For both START and END, any number is an absolute day
2724 ;; number from Agenda. Otherwise, consider value to be an Org
2725 ;; timestamp string. The `:block' property has precedence
2726 ;; over `:tstart' and `:tend'.
2728 (pcase (if range
(car range
) (plist-get params
:tstart
))
2729 ((and (pred numberp
) n
)
2730 (pcase-let ((`(,m
,d
,y
) (calendar-gregorian-from-absolute n
)))
2731 (apply #'encode-time
(list 0 0 org-extend-today-until d m y
))))
2734 (org-matcher-time (or timestamp
2735 ;; The year Org was born.
2736 "<2003-01-01 Thu 00:00>"))))))
2738 (pcase (if range
(nth 1 range
) (plist-get params
:tend
))
2739 ((and (pred numberp
) n
)
2740 (pcase-let ((`(,m
,d
,y
) (calendar-gregorian-from-absolute n
)))
2741 (apply #'encode-time
(list 0 0 org-extend-today-until d m y
))))
2742 (timestamp (seconds-to-time (org-matcher-time timestamp
))))))
2743 (while (time-less-p start end
)
2744 (unless (bolp) (insert "\n"))
2745 ;; Insert header before each clock table.
2748 (format-time-string (org-time-stamp-format nil t
) start
)
2750 ;; Compute NEXT, which is the end of the current clock table,
2751 ;; according to step.
2753 (apply #'encode-time
2755 ((`(,_
,_
,_
,d
,m
,y
,dow .
,_
) (decode-time start
)))
2757 (`day
(list 0 0 org-extend-today-until
(1+ d
) m y
))
2759 (let ((offset (if (= dow week-start
) 7
2760 (mod (- week-start dow
) 7))))
2761 (list 0 0 org-extend-today-until
(+ d offset
) m y
)))
2762 (`month
(list 0 0 0 month-start
(1+ m
) y
))
2763 (`year
(list 0 0 org-extend-today-until
1 1 (1+ y
)))))))
2764 (table-begin (line-beginning-position 0))
2766 ;; Write clock table between START and NEXT.
2767 (org-dblock-write:clocktable
2769 params
(list :header
""
2772 :tstart
(format-time-string
2773 (org-time-stamp-format t t
)
2775 :tend
(format-time-string
2776 (org-time-stamp-format t t
)
2777 ;; Never include clocks past END.
2778 (if (time-less-p end next
) end next
)))))))
2779 (let ((case-fold-search t
)) (re-search-forward "^[ \t]*#\\+END:"))
2780 ;; Remove the table if it is empty and `:stepskip0' is
2782 (when (and ignore-empty-tables
(equal step-time
0))
2783 (delete-region (line-beginning-position) table-begin
))
2787 (defun org-clock-get-table-data (file params
)
2788 "Get the clocktable data for file FILE, with parameters PARAMS.
2789 FILE is only for identification - this function assumes that
2790 the correct buffer is current, and that the wanted restriction is
2792 The return value will be a list with the file name and the total
2793 file time (in minutes) as 1st and 2nd elements. The third element
2794 of this list will be a list of headline entries. Each entry has the
2795 following structure:
2797 (LEVEL HEADLINE TAGS TIMESTAMP TIME PROPERTIES)
2799 LEVEL: The level of the headline, as an integer. This will be
2800 the reduced level, so 1,2,3,... even if only odd levels
2802 HEADLINE: The text of the headline. Depending on PARAMS, this may
2803 already be formatted like a link.
2804 TAGS: The list of tags of the headline.
2805 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2806 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2808 TIME: The sum of all time spend in this tree, in minutes. This time
2809 will of cause be restricted to the time block and tags match
2810 specified in PARAMS.
2811 PROPERTIES: The list properties specified in the `:properties' parameter
2812 along with their value, as an alist following the pattern
2814 (let* ((maxlevel (or (plist-get params
:maxlevel
) 3))
2815 (timestamp (plist-get params
:timestamp
))
2816 (ts (plist-get params
:tstart
))
2817 (te (plist-get params
:tend
))
2818 (ws (plist-get params
:wstart
))
2819 (ms (plist-get params
:mstart
))
2820 (block (plist-get params
:block
))
2821 (link (plist-get params
:link
))
2822 (tags (plist-get params
:tags
))
2823 (match (plist-get params
:match
))
2824 (properties (plist-get params
:properties
))
2825 (inherit-property-p (plist-get params
:inherit-props
))
2826 (matcher (and match
(cdr (org-make-tags-matcher match
))))
2829 (setq org-clock-file-total-minutes nil
)
2831 (setq cc
(org-clock-special-range block nil t ws ms
)
2834 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
2835 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
2836 (when (and ts
(listp ts
))
2837 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
2838 (when (and te
(listp te
))
2839 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
2840 ;; Now the times are strings we can parse.
2841 (if ts
(setq ts
(org-matcher-time ts
)))
2842 (if te
(setq te
(org-matcher-time te
)))
2844 (org-clock-sum ts te
2847 (let* ((todo (org-get-todo-state))
2848 (tags-list (org-get-tags))
2849 (org-scanner-tags tags-list
)
2850 (org-trust-scanner-tags t
))
2851 (funcall ,matcher todo tags-list nil
)))))
2852 (goto-char (point-min))
2854 (while (or (and (bobp) (prog1 st
(setq st nil
))
2855 (get-text-property (point) :org-clock-minutes
)
2856 (setq p
(point-min)))
2857 (setq p
(next-single-property-change
2858 (point) :org-clock-minutes
)))
2860 (let ((time (get-text-property p
:org-clock-minutes
)))
2861 (when (and time
(> time
0) (org-at-heading-p))
2862 (let ((level (org-reduced-level (org-current-level))))
2863 (when (<= level maxlevel
)
2864 (let* ((headline (org-get-heading t t t t
))
2866 (if (not link
) headline
2868 (org-link-heading-search-string headline
)))
2869 (org-link-make-string
2870 (if (not (buffer-file-name)) search
2871 (format "file:%s::%s" (buffer-file-name) search
))
2872 ;; Prune statistics cookies. Replace
2873 ;; links with their description, or
2874 ;; a plain link if there is none.
2876 (org-link-display-format
2877 (replace-regexp-in-string
2878 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
2880 (tgs (and tags
(org-get-tags)))
2883 (cl-some (lambda (p) (org-entry-get (point) p
))
2884 '("SCHEDULED" "DEADLINE" "TIMESTAMP"
2891 (let ((v (org-entry-get
2892 (point) p inherit-property-p
)))
2893 (and v
(cons p v
))))
2895 (push (list level hdl tgs tsp time props
) tbl
)))))))
2896 (list file org-clock-file-total-minutes
(nreverse tbl
)))))
2898 ;; Saving and loading the clock
2900 (defvar org-clock-loaded nil
2901 "Was the clock file loaded?")
2904 (defun org-clock-update-time-maybe ()
2905 "If this is a CLOCK line, update it and return t.
2906 Otherwise, return nil."
2909 (beginning-of-line 1)
2910 (skip-chars-forward " \t")
2911 (when (looking-at org-clock-string
)
2912 (let ((re (concat "[ \t]*" org-clock-string
2913 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2914 "\\([ \t]*=>.*\\)?\\)?"))
2917 ((not (looking-at re
))
2919 ((not (match-end 2))
2920 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
2921 (> org-clock-marker
(point))
2922 (<= org-clock-marker
(point-at-eol)))
2923 ;; The clock is running here
2924 (setq org-clock-start-time
2926 (org-parse-time-string (match-string 1))))
2927 (org-clock-update-mode-line)))
2929 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2931 (setq ts
(match-string 1)
2932 te
(match-string 3))
2933 (setq s
(- (float-time
2934 (apply #'encode-time
(org-parse-time-string te
)))
2936 (apply #'encode-time
(org-parse-time-string ts
))))
2939 h
(floor (/ s
3600))
2943 (insert " => " (format (if neg
"-%d:%02d" "%2d:%02d") h m
))
2946 (defun org-clock-save ()
2947 "Persist various clock-related data to disk.
2948 The details of what will be saved are regulated by the variable
2949 `org-clock-persist'."
2950 (when (and org-clock-persist
2951 (or org-clock-loaded
2952 org-clock-has-been-used
2953 (not (file-exists-p org-clock-persist-file
))))
2954 (with-temp-file org-clock-persist-file
2955 (insert (format ";; %s - %s at %s\n"
2956 (file-name-nondirectory org-clock-persist-file
)
2958 (format-time-string (org-time-stamp-format t
))))
2959 ;; Store clock to be resumed.
2960 (when (and (memq org-clock-persist
'(t clock
))
2961 (let ((b (org-base-buffer (org-clocking-buffer))))
2962 (and (buffer-live-p b
)
2963 (buffer-file-name b
)
2964 (or (not org-clock-persist-query-save
)
2965 (y-or-n-p (format "Save current clock (%s) "
2966 org-clock-heading
))))))
2968 (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
2969 (buffer-file-name (org-base-buffer (org-clocking-buffer)))
2970 (marker-position org-clock-marker
))))
2971 ;; Store clocked task history. Tasks are stored reversed to
2972 ;; make reading simpler.
2973 (when (and (memq org-clock-persist
'(t history
))
2976 (format "(setq org-clock-stored-history '(%s))\n"
2979 (let ((b (org-base-buffer (marker-buffer m
))))
2980 (when (and (buffer-live-p b
)
2981 (buffer-file-name b
))
2983 (buffer-file-name b
)
2984 (marker-position m
)))))
2985 (reverse org-clock-history
)
2988 (defun org-clock-load ()
2989 "Load clock-related data from disk, maybe resuming a stored clock."
2990 (when (and org-clock-persist
(not org-clock-loaded
))
2991 (if (not (file-readable-p org-clock-persist-file
))
2992 (message "Not restoring clock data; %S not found" org-clock-persist-file
)
2993 (message "Restoring clock data")
2995 (load-file org-clock-persist-file
)
2996 (setq org-clock-loaded t
)
2997 (pcase-dolist (`(,(and file
(pred file-exists-p
)) .
,position
)
2998 org-clock-stored-history
)
2999 (org-clock-history-push position
(find-file-noselect file
)))
3001 (pcase org-clock-stored-resume-clock
3002 (`(,(and file
(pred file-exists-p
)) .
,position
)
3003 (with-current-buffer (find-file-noselect file
)
3004 (when (or (not org-clock-persist-query-resume
)
3005 (y-or-n-p (format "Resume clock (%s) "
3007 (goto-char position
)
3008 (org-get-heading t t
)))))
3009 (goto-char position
)
3010 (let ((org-clock-in-resume 'auto-restart
)
3011 (org-clock-auto-clock-resolution nil
))
3013 (when (org-invisible-p) (org-show-context))))))
3016 ;; Suggested bindings
3017 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
3019 (provide 'org-clock
)
3022 ;; generated-autoload-file: "org-loaddefs.el"
3026 ;;; org-clock.el ends here