1 ;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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-table-goto-line
"org-table" (n))
40 (defvar org-frame-title-format-backup frame-title-format
)
41 (defvar org-time-stamp-formats
)
45 (defgroup org-clock nil
46 "Options concerning clocking working time in Org mode."
50 (defcustom org-clock-into-drawer t
51 "Non-nil when clocking info should be wrapped into a drawer.
53 When non-nil, clocking info will be inserted into the same drawer
54 as log notes (see variable `org-log-into-drawer'), if it exists,
55 or \"LOGBOOK\" otherwise. If necessary, the drawer will be
58 When an integer, the drawer is created only when the number of
59 clocking entries in an item reaches or exceeds this value.
61 When a string, it becomes the name of the drawer, ignoring the
62 log notes drawer altogether.
64 Do not check directly this variable in a Lisp program. Call
65 function `org-clock-into-drawer' instead."
69 :package-version
'(Org .
"8.3")
71 (const :tag
"Always" t
)
72 (const :tag
"Only when drawer exists" nil
)
73 (integer :tag
"When at least N clock entries")
74 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
75 (string :tag
"Into Drawer named...")))
77 (defun org-clock-into-drawer ()
78 "Value of `org-clock-into-drawer'. but let properties overrule.
80 If the current entry has or inherits a CLOCK_INTO_DRAWER
81 property, it will be used instead of the default value.
83 Return value is either a string, an integer, or nil."
84 (let ((p (org-entry-get nil
"CLOCK_INTO_DRAWER" 'inherit t
)))
85 (cond ((equal p
"nil") nil
)
86 ((equal p
"t") (or (org-log-into-drawer) "LOGBOOK"))
88 (if (string-match-p "\\`[0-9]+\\'" p
) (string-to-number p
) p
))
89 ((org-string-nw-p org-clock-into-drawer
))
90 ((integerp org-clock-into-drawer
) org-clock-into-drawer
)
91 ((not org-clock-into-drawer
) nil
)
92 ((org-log-into-drawer))
95 (defcustom org-clock-out-when-done t
96 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
98 DONE here means any DONE-like state.
99 A nil value means clock will keep running until stopped explicitly with
100 `\\[org-clock-out]', or until the clock is started in a different item.
101 Instead of t, this can also be a list of TODO states that should trigger
105 (const :tag
"No" nil
)
106 (const :tag
"Yes, when done" t
)
107 (repeat :tag
"State list"
108 (string :tag
"TODO keyword"))))
110 (defcustom org-clock-rounding-minutes
0
111 "Rounding minutes when clocking in or out.
112 The default value is 0 so that no rounding is done.
113 When set to a non-integer value, use the car of
114 `org-time-stamp-rounding-minutes', like for setting a time-stamp.
116 E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
117 and you clock in: then the clock starts at 14:45. If you clock
118 out within the next 5 minutes, the clock line will be removed;
119 if you clock out 8 minutes after your clocked in, the clock
120 out time will be 14:50."
123 :package-version
'(Org .
"8.0")
125 (integer :tag
"Minutes (0 for no rounding)")
126 (symbol :tag
"Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp
)))
128 (defcustom org-clock-out-remove-zero-time-clocks nil
129 "Non-nil means remove the clock line when the resulting time is zero."
133 (defcustom org-clock-in-switch-to-state nil
134 "Set task to a special todo state while clocking it.
135 The value should be the state to which the entry should be
136 switched. If the value is a function, it must take one
137 parameter (the current TODO state of the item) and return the
138 state to switch it to."
142 (const :tag
"Don't force a state" nil
)
143 (string :tag
"State")
144 (symbol :tag
"Function")))
146 (defcustom org-clock-out-switch-to-state nil
147 "Set task to a special todo state after clocking out.
148 The value should be the state to which the entry should be
149 switched. If the value is a function, it must take one
150 parameter (the current TODO state of the item) and return the
151 state to switch it to."
155 (const :tag
"Don't force a state" nil
)
156 (string :tag
"State")
157 (symbol :tag
"Function")))
159 (defcustom org-clock-history-length
5
160 "Number of clock tasks to remember in history."
164 (defcustom org-clock-goto-may-find-recent-task t
165 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
169 (defcustom org-clock-heading-function nil
170 "When non-nil, should be a function to create `org-clock-heading'.
171 This is the string shown in the mode line when a clock is running.
172 The function is called with point at the beginning of the headline."
174 :type
'(choice (const nil
) (function)))
176 (defcustom org-clock-string-limit
0
177 "Maximum length of clock strings in the mode line. 0 means no limit."
181 (defcustom org-clock-in-resume nil
182 "If non-nil, resume clock when clocking into task with open clock.
183 When clocking into a task with a clock entry which has not been closed,
184 the clock can be resumed from that point."
188 (defcustom org-clock-persist nil
189 "When non-nil, save the running clock when Emacs is closed.
190 The clock is resumed when Emacs restarts.
191 When this is t, both the running clock, and the entire clock
192 history are saved. When this is the symbol `clock', only the
193 running clock is saved. When this is the symbol `history', only
194 the clock history is saved.
196 When Emacs restarts with saved clock information, the file containing
197 the running clock as well as all files mentioned in the clock history
200 All this depends on running `org-clock-persistence-insinuate' in your
201 Emacs initialization file."
204 (const :tag
"Just the running clock" clock
)
205 (const :tag
"Just the history" history
)
206 (const :tag
"Clock and history" t
)
207 (const :tag
"No persistence" nil
)))
209 (defcustom org-clock-persist-file
(convert-standard-filename
210 (concat user-emacs-directory
"org-clock-save.el"))
211 "File to save clock data to."
215 (defcustom org-clock-persist-query-save nil
216 "When non-nil, ask before saving the current clock on exit."
220 (defcustom org-clock-persist-query-resume t
221 "When non-nil, ask before resuming any stored clock during load."
225 (defcustom org-clock-sound nil
226 "Sound to use for notifications.
230 t Standard Emacs beep
231 file name Play this sound file, fall back to beep"
234 (const :tag
"No sound" nil
)
235 (const :tag
"Standard beep" t
)
236 (file :tag
"Play sound file")))
238 (defcustom org-clock-mode-line-total
'auto
239 "Default setting for the time included for the mode line clock.
240 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
243 current Only the time in the current instance of the clock
244 today All time clocked into this task today
245 repeat All time clocked into this task since last repeat
246 all All time ever recorded for this task
247 auto Automatically, either `all', or `repeat' for repeating tasks"
250 (const :tag
"Current clock" current
)
251 (const :tag
"Today's task time" today
)
252 (const :tag
"Since last repeat" repeat
)
253 (const :tag
"All task time" all
)
254 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
256 (defvaralias 'org-task-overrun-text
'org-clock-task-overrun-text
)
257 (defcustom org-clock-task-overrun-text nil
258 "Extra mode line text to indicate that the clock is overrun.
259 The can be nil to indicate that instead of adding text, the clock time
260 should get a different face (`org-mode-line-clock-overrun').
261 When this is a string, it is prepended to the clock string as an indication,
262 also using the face `org-mode-line-clock-overrun'."
266 (const :tag
"Just mark the time string" nil
)
267 (string :tag
"Text to prepend")))
269 (defcustom org-show-notification-handler nil
270 "Function or program to send notification with.
271 The function or program will be called with the notification
276 (string :tag
"Program")
277 (function :tag
"Function")))
279 (defgroup org-clocktable nil
280 "Options concerning the clock table in Org mode."
281 :tag
"Org Clock Table"
284 (defcustom org-clocktable-defaults
287 :lang
(or (bound-and-true-p org-export-default-language
) "en")
307 "Default properties for clock tables."
312 (defcustom org-clock-clocktable-formatter
'org-clocktable-write-default
313 "Function to turn clocking data into a table.
314 For more information, see `org-clocktable-write-default'."
315 :group
'org-clocktable
319 ;; FIXME: translate es and nl last string "Clock summary at"
320 (defcustom org-clock-clocktable-language-setup
321 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
322 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
323 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à ")
324 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
325 ("de" "Datei" "N" "Timestamp" "Tätigkeit" "Dauer" "ALLES" "Gesamtdauer" "Datei Zeit" "Erstellt am"))
326 "Terms used in clocktable, translated to different languages."
327 :group
'org-clocktable
331 (defcustom org-clock-clocktable-default-properties
'(:maxlevel
2 :scope file
)
332 "Default properties for new clocktables.
333 These will be inserted into the BEGIN line, to make it easy for users to
335 :group
'org-clocktable
338 (defcustom org-clock-idle-time nil
339 "When non-nil, resolve open clocks if the user is idle more than X minutes."
342 (const :tag
"Never" nil
)
343 (integer :tag
"After N minutes")))
345 (defcustom org-clock-auto-clock-resolution
'when-no-clock-is-running
346 "When to automatically resolve open clocks found in Org buffers."
349 (const :tag
"Never" nil
)
350 (const :tag
"Always" t
)
351 (const :tag
"When no clock is running" when-no-clock-is-running
)))
353 (defcustom org-clock-report-include-clocking-task nil
354 "When non-nil, include the current clocking task time in clock reports."
359 (defcustom org-clock-resolve-expert nil
360 "Non-nil means do not show the splash buffer with the clock resolver."
365 (defcustom org-clock-continuously nil
366 "Non-nil means to start clocking from the last clock-out time, if any."
371 (defcustom org-clock-total-time-cell-format
"*%s*"
372 "Format string for the total time cells."
377 (defcustom org-clock-file-time-cell-format
"*%s*"
378 "Format string for the file time cells."
383 (defcustom org-clock-clocked-in-display
'mode-line
384 "When clocked in for a task, Org can display the current
385 task and accumulated time in the mode line and/or frame title.
388 both displays in both mode line and frame title
389 mode-line displays only in mode line (default)
390 frame-title displays only in frame title
391 nil current clock is not displayed"
394 (const :tag
"Mode line" mode-line
)
395 (const :tag
"Frame title" frame-title
)
396 (const :tag
"Both" both
)
397 (const :tag
"None" nil
)))
399 (defcustom org-clock-frame-title-format
'(t org-mode-line-string
)
400 "The value for `frame-title-format' when clocking in.
402 When `org-clock-clocked-in-display' is set to `frame-title'
403 or `both', clocking in will replace `frame-title-format' with
404 this value. Clocking out will restore `frame-title-format'.
406 `org-frame-title-string' is a format string using the same
407 specifications than `frame-title-format', which see."
412 (defcustom org-clock-x11idle-program-name
"x11idle"
413 "Name of the program which prints X11 idle time in milliseconds.
415 You can find x11idle.c in the contrib/scripts directory of the
416 Org git distribution. Or, you can do:
418 sudo apt-get install xprintidle
420 if you are using Debian."
423 :package-version
'(Org .
"8.0")
426 (defcustom org-clock-goto-before-context
2
427 "Number of lines of context to display before currently clocked-in entry.
428 This applies when using `org-clock-goto'."
432 (defcustom org-clock-display-default-range
'thisyear
433 "Default range when displaying clocks with `org-clock-display'."
435 :type
'(choice (const today
)
444 (const :tag
"Select range interactively" interactive
)))
446 (defvar org-clock-in-prepare-hook nil
447 "Hook run when preparing the clock.
448 This hook is run before anything happens to the task that
449 you want to clock in. For example, you can use this hook
450 to add an effort property.")
451 (defvar org-clock-in-hook nil
452 "Hook run when starting the clock.")
453 (defvar org-clock-out-hook nil
454 "Hook run when stopping the current clock.")
456 (defvar org-clock-cancel-hook nil
457 "Hook run when canceling the current clock.")
458 (defvar org-clock-goto-hook nil
459 "Hook run when selecting the currently clocked-in entry.")
460 (defvar org-clock-has-been-used nil
461 "Has the clock been used during the current Emacs session?")
463 (defvar org-clock-stored-history nil
464 "Clock history, populated by `org-clock-load'")
465 (defvar org-clock-stored-resume-clock nil
466 "Clock to resume, saved by `org-clock-load'")
468 (defconst org-clock--oldest-date
470 (lambda (min max pred
)
471 (if (funcall pred min
) min
473 (while (> (- max min
) 1)
474 (let ((mean (+ (ash min -
1) (ash max -
1) (logand min max
1))))
475 (if (funcall pred mean
) (setq max mean
) (setq min mean
)))))
481 (lambda (m) (ignore-errors (decode-time (list m
0))))))
486 (lambda (m) (ignore-errors (decode-time (list high m
)))))))
488 "Internal time for oldest date representable on the system.")
490 ;;; The clock for measuring work time.
492 (defvar org-mode-line-string
"")
493 (put 'org-mode-line-string
'risky-local-variable t
)
495 (defvar org-clock-mode-line-timer nil
)
496 (defvar org-clock-idle-timer nil
)
497 (defvar org-clock-heading
) ; defined in org.el
498 (defvar org-clock-start-time
"")
500 (defvar org-clock-leftover-time nil
501 "If non-nil, user canceled a clock; this is when leftover time started.")
503 (defvar org-clock-effort
""
504 "Effort estimate of the currently clocking task.")
506 (defvar org-clock-total-time nil
507 "Holds total time, spent previously on currently clocked item.
508 This does not include the time in the currently running clock.")
510 (defvar org-clock-history nil
511 "List of marker pointing to recent clocked tasks.")
513 (defvar org-clock-default-task
(make-marker)
514 "Marker pointing to the default task that should clock time.
515 The clock can be made to switch to this task after clocking out
516 of a different task.")
518 (defvar org-clock-interrupted-task
(make-marker)
519 "Marker pointing to the task that has been interrupted by the current clock.")
521 (defvar org-clock-mode-line-map
(make-sparse-keymap))
522 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
523 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
525 (defun org-clock-menu ()
529 ["Clock out" org-clock-out t
]
530 ["Change effort estimate" org-clock-modify-effort-estimate t
]
531 ["Go to clock entry" org-clock-goto t
]
532 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
534 (defun org-clock-history-push (&optional pos buffer
)
535 "Push a marker to the clock history."
536 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
537 (let ((m (move-marker (make-marker)
538 (or pos
(point)) (org-base-buffer
539 (or buffer
(current-buffer)))))
541 (while (setq n
(member m org-clock-history
))
542 (move-marker (car n
) nil
))
543 (setq org-clock-history
545 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
547 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
548 (setq org-clock-history
550 (nthcdr (- l org-clock-history-length -
1)
551 (nreverse org-clock-history
)))))
552 (push m org-clock-history
)))
554 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
555 "Save relative positions of markers in region."
556 (org-check-and-save-marker org-clock-marker beg end
)
557 (org-check-and-save-marker org-clock-hd-marker beg end
)
558 (org-check-and-save-marker org-clock-default-task beg end
)
559 (org-check-and-save-marker org-clock-interrupted-task beg end
)
560 (dolist (m org-clock-history
)
561 (org-check-and-save-marker m beg end
)))
563 (defun org-clock-drawer-name ()
564 "Return clock drawer's name for current entry, or nil."
565 (let ((drawer (org-clock-into-drawer)))
566 (cond ((integerp drawer
)
567 (let ((log-drawer (org-log-into-drawer)))
568 (if (stringp log-drawer
) log-drawer
"LOGBOOK")))
569 ((stringp drawer
) drawer
)
572 (defun org-clocking-buffer ()
573 "Return the clocking buffer if we are currently clocking a task or nil."
574 (marker-buffer org-clock-marker
))
576 (defun org-clocking-p ()
577 "Return t when clocking a task."
578 (not (equal (org-clocking-buffer) nil
)))
580 (defvar org-clock-before-select-task-hook nil
581 "Hook called in task selection just before prompting the user.")
583 (defun org-clock-select-task (&optional prompt
)
584 "Select a task that was recently associated with clocking."
586 (let (och chl sel-list rpl
(i 0) s
)
587 ;; Remove successive dups from the clock history to consider
588 (dolist (c org-clock-history
)
589 (unless (equal c
(car och
)) (push c och
)))
590 (setq och
(reverse och
) chl
(length och
))
592 (user-error "No recent clock")
593 (save-window-excursion
594 (org-switch-to-buffer-other-window
595 (get-buffer-create "*Clock Task Select*"))
597 (when (marker-buffer org-clock-default-task
)
598 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
599 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
601 (when (marker-buffer org-clock-interrupted-task
)
602 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
603 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
605 (when (org-clocking-p)
606 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
607 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
609 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
611 (when (marker-buffer m
)
613 s
(org-clock-insert-selection-line
617 (if (fboundp 'int-to-char
) (setf (car s
) (int-to-char (car s
))))
619 (run-hooks 'org-clock-before-select-task-hook
)
620 (goto-char (point-min))
621 ;; Set min-height relatively to circumvent a possible but in
622 ;; `fit-window-to-buffer'
623 (fit-window-to-buffer nil nil
(if (< chl
10) chl
(+ 5 chl
)))
624 (message (or prompt
"Select task for clocking:"))
625 (setq cursor-type nil rpl
(read-char-exclusive))
630 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
631 (t (user-error "Invalid task choice %c" rpl
)))))))
633 (defun org-clock-insert-selection-line (i marker
)
634 "Insert a line for the clock selection menu.
635 And return a cons cell with the selection character integer and the marker
637 (when (marker-buffer marker
)
638 (let (cat task heading prefix
)
639 (with-current-buffer (org-base-buffer (marker-buffer marker
))
640 (org-with-wide-buffer
643 (setq cat
(org-get-category)
644 heading
(org-get-heading 'notags
)
645 prefix
(save-excursion
646 (org-back-to-heading t
)
647 (looking-at org-outline-regexp
)
650 (org-fontify-like-in-org-mode
651 (concat prefix heading
)
655 (insert (format "[%c] %-12s %s\n" i cat task
))
658 (defvar org-clock-task-overrun nil
659 "Internal flag indicating if the clock has overrun the planned time.")
660 (defvar org-clock-update-period
60
661 "Number of seconds between mode line clock string updates.")
663 (defun org-clock-get-clock-string ()
664 "Form a clock-string, that will be shown in the mode line.
665 If an effort estimate was defined for the current item, use
666 01:30/01:50 format (clocked/estimated).
667 If not, show simply the clocked time like 01:50."
668 (let ((clocked-time (org-clock-get-clocked-time)))
670 (let* ((effort-in-minutes
671 (org-duration-string-to-minutes org-clock-effort
))
674 (org-minutes-to-clocksum-string clocked-time
)
675 'face
(if (and org-clock-task-overrun
(not org-clock-task-overrun-text
))
676 'org-mode-line-clock-overrun
'org-mode-line-clock
)))
677 (effort-str (org-minutes-to-clocksum-string effort-in-minutes
))
678 (clockstr (propertize
679 (concat " [%s/" effort-str
680 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading
) ")")
681 'face
'org-mode-line-clock
)))
682 (format clockstr work-done-str
))
683 (propertize (concat " [" (org-minutes-to-clocksum-string clocked-time
)
684 "]" (format " (%s)" org-clock-heading
))
685 'face
'org-mode-line-clock
))))
687 (defun org-clock-get-last-clock-out-time ()
688 "Get the last clock-out time for the current subtree."
690 (let ((end (save-excursion (org-end-of-subtree))))
691 (when (re-search-forward (concat org-clock-string
692 ".*\\]--\\(\\[[^]]+\\]\\)") end t
)
693 (org-time-string-to-time (match-string 1))))))
695 (defun org-clock-update-mode-line ()
697 (org-clock-notify-once-if-expired)
698 (setq org-clock-task-overrun nil
))
699 (setq org-mode-line-string
701 (let ((clock-string (org-clock-get-clock-string))
702 (help-text "Org mode clock is running.\nmouse-1 shows a \
703 menu\nmouse-2 will jump to task"))
704 (if (and (> org-clock-string-limit
0)
705 (> (length clock-string
) org-clock-string-limit
))
707 (substring clock-string
0 org-clock-string-limit
)
708 'help-echo
(concat help-text
": " org-clock-heading
))
709 (propertize clock-string
'help-echo help-text
)))
710 'local-map org-clock-mode-line-map
711 'mouse-face
'mode-line-highlight
))
712 (if (and org-clock-task-overrun org-clock-task-overrun-text
)
713 (setq org-mode-line-string
715 org-clock-task-overrun-text
716 'face
'org-mode-line-clock-overrun
) org-mode-line-string
)))
717 (force-mode-line-update))
719 (defun org-clock-get-clocked-time ()
720 "Get the clocked time for the current item in minutes.
721 The time returned includes the time spent on this task in
722 previous clocking intervals."
723 (let ((currently-clocked-time
724 (floor (- (float-time)
725 (float-time org-clock-start-time
)) 60)))
726 (+ currently-clocked-time
(or org-clock-total-time
0))))
728 (defun org-clock-modify-effort-estimate (&optional value
)
729 "Add to or set the effort estimate of the item currently being clocked.
730 VALUE can be a number of minutes, or a string with format hh:mm or mm.
731 When the string starts with a + or a - sign, the current value of the effort
732 property will be changed by that amount. If the effort value is expressed
733 as an `org-effort-durations' (e.g. \"3h\"), the modified value will be
734 converted to a hh:mm duration.
736 This command will update the \"Effort\" property of the currently
737 clocked item, and the value displayed in the mode line."
739 (if (org-clock-is-active)
740 (let ((current org-clock-effort
) sign
)
742 ;; Prompt user for a value or a change
745 (format "Set effort (hh:mm or mm%s): "
747 (format ", prefix + to add to %s" org-clock-effort
)
749 (when (stringp value
)
750 ;; A string. See if it is a delta
751 (setq sign
(string-to-char value
))
752 (if (member sign
'(?- ?
+))
753 (setq current
(org-duration-string-to-minutes current
)
754 value
(substring value
1))
756 (setq value
(org-duration-string-to-minutes value
))
758 (setq value
(- current value
))
759 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
760 (setq value
(max 0 value
)
761 org-clock-effort
(org-minutes-to-clocksum-string value
))
762 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
763 (org-clock-update-mode-line)
764 (message "Effort is now %s" org-clock-effort
))
765 (message "Clock is not currently active")))
767 (defvar org-clock-notification-was-shown nil
768 "Shows if we have shown notification already.")
770 (defun org-clock-notify-once-if-expired ()
771 "Show notification if we spent more time than we estimated before.
772 Notification is shown only once."
773 (when (org-clocking-p)
774 (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort
))
775 (clocked-time (org-clock-get-clocked-time)))
776 (if (setq org-clock-task-overrun
777 (if (or (null effort-in-minutes
) (zerop effort-in-minutes
))
779 (>= clocked-time effort-in-minutes
)))
780 (unless org-clock-notification-was-shown
781 (setq org-clock-notification-was-shown t
)
783 (format-message "Task `%s' should be finished by now. (%s)"
784 org-clock-heading org-clock-effort
)
786 (setq org-clock-notification-was-shown nil
)))))
788 (defun org-notify (notification &optional play-sound
)
789 "Send a NOTIFICATION and maybe PLAY-SOUND.
790 If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
791 (org-show-notification notification
)
792 (if play-sound
(org-clock-play-sound play-sound
)))
794 (defun org-show-notification (notification)
796 Use `org-show-notification-handler' if defined,
797 use libnotify if available, or fall back on a message."
798 (cond ((functionp org-show-notification-handler
)
799 (funcall org-show-notification-handler notification
))
800 ((stringp org-show-notification-handler
)
801 (start-process "emacs-timer-notification" nil
802 org-show-notification-handler notification
))
803 ((fboundp 'notifications-notify
)
804 (notifications-notify
805 :title
"Org mode message"
807 ;; FIXME how to link to the Org icon?
808 ;; :app-icon "~/.emacs.d/icons/mail.png"
810 ((executable-find "notify-send")
811 (start-process "emacs-timer-notification" nil
812 "notify-send" notification
))
813 ;; Maybe the handler will send a message, so only use message as
814 ;; a fall back option
815 (t (message "%s" notification
))))
817 (defun org-clock-play-sound (&optional clock-sound
)
818 "Play sound as configured by `org-clock-sound'.
819 Use alsa's aplay tool if available.
820 If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
821 (let ((org-clock-sound (or clock-sound org-clock-sound
)))
823 ((not org-clock-sound
))
824 ((eq org-clock-sound t
) (beep t
) (beep t
))
825 ((stringp org-clock-sound
)
826 (let ((file (expand-file-name org-clock-sound
)))
827 (if (file-exists-p file
)
828 (if (executable-find "aplay")
829 (start-process "org-clock-play-notification" nil
832 (play-sound-file file
)
833 (error (beep t
) (beep t
))))))))))
835 (defvar org-clock-mode-line-entry nil
836 "Information for the mode line about the running clock.")
838 (defun org-find-open-clocks (file)
839 "Search through the given file and find all open clocks."
840 (let ((buf (or (get-file-buffer file
)
841 (find-file-noselect file
)))
842 (org-clock-re (concat org-clock-string
" \\(\\[.*?\\]\\)$"))
844 (with-current-buffer buf
846 (goto-char (point-min))
847 (while (re-search-forward org-clock-re nil t
)
848 (push (cons (copy-marker (match-end 1) t
)
849 (org-time-string-to-time (match-string 1))) clocks
))))
852 (defsubst org-is-active-clock
(clock)
853 "Return t if CLOCK is the currently active clock."
854 (and (org-clock-is-active)
855 (= org-clock-marker
(car clock
))))
857 (defmacro org-with-clock-position
(clock &rest forms
)
858 "Evaluate FORMS with CLOCK as the current active clock."
859 `(with-current-buffer (marker-buffer (car ,clock
))
860 (org-with-wide-buffer
861 (goto-char (car ,clock
))
864 (def-edebug-spec org-with-clock-position
(form body
))
865 (put 'org-with-clock-position
'lisp-indent-function
1)
867 (defmacro org-with-clock
(clock &rest forms
)
868 "Evaluate FORMS with CLOCK as the current active clock.
869 This macro also protects the current active clock from being altered."
870 `(org-with-clock-position ,clock
871 (let ((org-clock-start-time (cdr ,clock
))
872 (org-clock-total-time)
875 (org-clock-marker (car ,clock
))
876 (org-clock-hd-marker (save-excursion
877 (org-back-to-heading t
)
880 (def-edebug-spec org-with-clock
(form body
))
881 (put 'org-with-clock
'lisp-indent-function
1)
883 (defsubst org-clock-clock-in
(clock &optional resume start-time
)
884 "Clock in to the clock located by CLOCK.
885 If necessary, clock-out of the currently active clock."
886 (org-with-clock-position clock
887 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
888 (org-clock-in nil start-time
))))
890 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
891 "Clock out of the clock located by CLOCK."
892 (let ((temp (copy-marker (car clock
)
893 (marker-insertion-type (car clock
)))))
894 (if (org-is-active-clock clock
)
895 (org-clock-out nil fail-quietly at-time
)
896 (org-with-clock clock
897 (org-clock-out nil fail-quietly at-time
)))
898 (setcar clock temp
)))
900 (defsubst org-clock-clock-cancel
(clock)
901 "Cancel the clock located by CLOCK."
902 (let ((temp (copy-marker (car clock
)
903 (marker-insertion-type (car clock
)))))
904 (if (org-is-active-clock clock
)
906 (org-with-clock clock
908 (setcar clock temp
)))
910 (defvar org-clock-clocking-in nil
)
911 (defvar org-clock-resolving-clocks nil
)
912 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
914 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
915 &optional close-p restart-p fail-quietly
)
916 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
917 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
918 (let ((org-clock-resolving-clocks t
))
921 (org-clock-clock-cancel clock
)
922 (if (and restart-p
(not org-clock-clocking-in
))
923 (org-clock-clock-in clock
)))
925 ((eq resolve-to
'now
)
927 (error "RESTART-P is not valid here"))
928 (if (or close-p org-clock-clocking-in
)
929 (org-clock-clock-out clock fail-quietly
)
930 (unless (org-is-active-clock clock
)
931 (org-clock-clock-in clock t
))))
933 ((not (time-less-p resolve-to
(current-time)))
934 (error "RESOLVE-TO must refer to a time in the past"))
938 (error "RESTART-P is not valid here"))
939 (org-clock-clock-out clock fail-quietly
(or clock-out-time
941 (unless org-clock-clocking-in
943 (setq org-clock-leftover-time
(and (null clock-out-time
)
945 (org-clock-clock-in clock nil
(and clock-out-time
948 (defun org-clock-jump-to-current-clock (&optional effective-clock
)
950 (let ((drawer (org-clock-into-drawer))
951 (clock (or effective-clock
(cons org-clock-marker
952 org-clock-start-time
))))
953 (unless (marker-buffer (car clock
))
954 (error "No clock is currently running"))
955 (org-with-clock clock
(org-clock-goto))
956 (with-current-buffer (marker-buffer (car clock
))
957 (goto-char (car clock
))
959 (org-with-wide-buffer
960 (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
961 (regexp-quote (if (stringp drawer
) drawer
"LOGBOOK"))))
962 (beg (save-excursion (org-back-to-heading t
) (point))))
964 (while (re-search-backward drawer-re beg t
)
965 (let ((element (org-element-at-point)))
966 (when (eq (org-element-type element
) 'drawer
)
967 (when (> (org-element-property :end element
) (car clock
))
968 (org-flag-drawer nil element
))
969 (throw 'exit nil
)))))))))))
971 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
972 "Resolve an open Org clock.
973 An open clock was found, with `dangling' possibly being non-nil.
974 If this function was invoked with a prefix argument, non-dangling
975 open clocks are ignored. The given clock requires some sort of
976 user intervention to resolve it, either because a clock was left
977 dangling or due to an idle timeout. The clock resolution can
980 (a) deleted, the user doesn't care about the clock
981 (b) restarted from the current time (if no other clock is open)
982 (c) closed, giving the clock X minutes
983 (d) closed and then restarted
984 (e) resumed, as if the user had never left
986 The format of clock is (CONS MARKER START-TIME), where MARKER
987 identifies the buffer and position the clock is open at (and
988 thus, the heading it's under), and START-TIME is when the clock
992 (save-window-excursion
994 (unless org-clock-resolving-clocks-due-to-idleness
995 (org-clock-jump-to-current-clock clock
))
996 (unless org-clock-resolve-expert
997 (with-output-to-temp-buffer "*Org Clock*"
998 (princ (format-message "Select a Clock Resolution Command:
1000 i/q Ignore this question; the same as keeping all the idle time.
1002 k/K Keep X minutes of the idle time (default is all). If this
1003 amount is less than the default, you will be clocked out
1004 that many minutes after the time that idling began, and then
1005 clocked back in at the present time.
1007 g/G Indicate that you \"got back\" X minutes ago. This is quite
1008 different from `k': it clocks you out from the beginning of
1009 the idle period and clock you back in X minutes ago.
1011 s/S Subtract the idle time from the current clock. This is the
1012 same as keeping 0 minutes.
1014 C Cancel the open timer altogether. It will be as though you
1017 j/J Jump to the current clock, to make manual adjustments.
1019 For all these options, using uppercase makes your final state
1020 to be CLOCKED OUT."))))
1021 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
1023 (while (or (null char-pressed
)
1024 (and (not (memq char-pressed
1025 '(?k ?K ?g ?G ?s ?S ?C
1029 (read-char (concat (funcall prompt-fn clock
)
1032 (and (not (memq char-pressed
'(?i ?q
))) char-pressed
)))))
1034 (floor (/ (float-time
1035 (time-subtract (current-time) last-valid
)) 60)))
1037 (and (memq ch
'(?k ?K
))
1038 (read-number "Keep how many minutes? " default
)))
1040 (and (memq ch
'(?g ?G
))
1041 (read-number "Got back how many minutes ago? " default
)))
1042 (subtractp (memq ch
'(?s ?S
)))
1043 (barely-started-p (< (- (float-time last-valid
)
1044 (float-time (cdr clock
))) 45))
1045 (start-over (and subtractp barely-started-p
)))
1049 (org-clock-resolve-clock clock
'now nil t nil fail-quietly
))
1050 (org-clock-jump-to-current-clock clock
))
1052 (not (memq ch
'(?k ?K ?g ?G ?s ?S ?C
))))
1055 (org-clock-resolve-clock
1058 ;; If the time on the clock was less than a minute before
1059 ;; the user went away, and they've ask to subtract all the
1064 (and gotback
(= gotback
0)))
1066 ((or (and keep
(= keep default
))
1067 (and gotback
(= gotback default
)))
1070 (time-add last-valid
(seconds-to-time (* 60 keep
))))
1072 (time-subtract (current-time)
1073 (seconds-to-time (* 60 gotback
))))
1075 (error "Unexpected, please report this as a bug")))
1076 (and gotback last-valid
)
1077 (memq ch
'(?K ?G ?S
))
1079 (not (memq ch
'(?K ?G ?S ?C
))))
1083 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid
)
1084 "Resolve all currently open Org clocks.
1085 If `only-dangling-p' is non-nil, only ask to resolve dangling
1086 \(i.e., not currently open and valid) clocks."
1088 (unless org-clock-resolving-clocks
1089 (let ((org-clock-resolving-clocks t
))
1090 (dolist (file (org-files-list))
1091 (let ((clocks (org-find-open-clocks file
)))
1092 (dolist (clock clocks
)
1093 (let ((dangling (or (not (org-clock-is-active))
1094 (/= (car clock
) org-clock-marker
))))
1095 (if (or (not only-dangling-p
) dangling
)
1102 "Dangling clock started %d mins ago"
1103 (floor (- (float-time)
1104 (float-time (cdr clock
)))
1107 (cdr clock
)))))))))))
1109 (defun org-emacs-idle-seconds ()
1110 "Return the current Emacs idle time in seconds, or nil if not idle."
1111 (let ((idle-time (current-idle-time)))
1113 (float-time idle-time
)
1116 (defun org-mac-idle-seconds ()
1117 "Return the current Mac idle time in seconds."
1118 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
1120 (defvar org-x11idle-exists-p
1121 ;; Check that x11idle exists
1122 (and (eq window-system
'x
)
1123 (eq 0 (call-process-shell-command
1124 (format "command -v %s" org-clock-x11idle-program-name
)))
1125 ;; Check that x11idle can retrieve the idle time
1126 ;; FIXME: Why "..-shell-command" rather than just `call-process'?
1127 (eq 0 (call-process-shell-command org-clock-x11idle-program-name
))))
1129 (defun org-x11-idle-seconds ()
1130 "Return the current X11 idle time in seconds."
1131 (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name
)) 1000))
1133 (defun org-user-idle-seconds ()
1134 "Return the number of seconds the user has been idle for.
1135 This routine returns a floating point number."
1137 ((eq system-type
'darwin
)
1138 (org-mac-idle-seconds))
1139 ((and (eq window-system
'x
) org-x11idle-exists-p
)
1140 (org-x11-idle-seconds))
1142 (org-emacs-idle-seconds))))
1144 (defvar org-clock-user-idle-seconds
)
1146 (defun org-resolve-clocks-if-idle ()
1147 "Resolve all currently open Org clocks.
1148 This is performed after `org-clock-idle-time' minutes, to check
1149 if the user really wants to stay clocked in after being idle for
1151 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
1152 org-clock-marker
(marker-buffer org-clock-marker
))
1153 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
1154 (org-clock-user-idle-start
1155 (time-subtract (current-time)
1156 (seconds-to-time org-clock-user-idle-seconds
)))
1157 (org-clock-resolving-clocks-due-to-idleness t
))
1158 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
1160 (cons org-clock-marker
1161 org-clock-start-time
)
1163 (format "Clocked in & idle for %.1f mins"
1165 (time-subtract (current-time)
1166 org-clock-user-idle-start
))
1168 org-clock-user-idle-start
)))))
1170 (defvar org-clock-current-task nil
"Task currently clocked in.")
1171 (defvar org-clock-out-time nil
) ; store the time of the last clock-out
1172 (defvar org--msg-extra
)
1175 (defun org-clock-in (&optional select start-time
)
1176 "Start the clock on the current item.
1178 If necessary, clock-out of the currently active clock.
1180 With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
1182 tasks to clock into.
1184 When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
1185 clock into the current task and mark it as
1186 the default task, a special task that will always be offered in the
1187 clocking selection, associated with the letter `d'.
1189 When SELECT is `\\[universal-argument] \\[universal-argument] \
1190 \\[universal-argument]', clock in by using the last clock-out
1191 time as the start time. See `org-clock-continuously' to make this
1192 the default behavior."
1194 (setq org-clock-notification-was-shown nil
)
1195 (org-refresh-properties
1196 org-effort-property
'((effort . identity
)
1197 (effort-minutes . org-duration-string-to-minutes
)))
1199 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
1201 ts selected-task target-pos
(org--msg-extra "")
1202 (leftover (and (not org-clock-resolving-clocks
)
1203 org-clock-leftover-time
)))
1205 (when (and org-clock-auto-clock-resolution
1206 (or (not interrupting
)
1207 (eq t org-clock-auto-clock-resolution
))
1208 (not org-clock-clocking-in
)
1209 (not org-clock-resolving-clocks
))
1210 (setq org-clock-leftover-time nil
)
1211 (let ((org-clock-clocking-in t
))
1212 (org-resolve-clocks))) ; check if any clocks are dangling
1214 (when (equal select
'(64))
1215 ;; Set start-time to `org-clock-out-time'
1216 (let ((org-clock-continuously t
))
1217 (org-clock-in nil org-clock-out-time
)))
1219 (when (equal select
'(4))
1220 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
1222 (setq selected-task
(copy-marker selected-task
))
1225 (when (equal select
'(16))
1226 ;; Mark as default clocking task
1227 (org-clock-mark-default-task))
1230 ;; We are interrupting the clocking of a different task.
1231 ;; Save a marker to this task, so that we can go back.
1232 ;; First check if we are trying to clock into the same task!
1233 (when (save-excursion
1234 (unless selected-task
1235 (org-back-to-heading t
))
1236 (and (equal (marker-buffer org-clock-hd-marker
)
1238 (marker-buffer selected-task
)
1240 (= (marker-position org-clock-hd-marker
)
1242 (marker-position selected-task
)
1244 (equal org-clock-current-task
(nth 4 (org-heading-components)))))
1245 (message "Clock continues in \"%s\"" org-clock-heading
)
1247 (move-marker org-clock-interrupted-task
1248 (marker-position org-clock-marker
)
1249 (marker-buffer org-clock-marker
))
1250 (let ((org-clock-clocking-in t
))
1251 (org-clock-out nil t
)))
1253 ;; Clock in at which position?
1255 (if (and (eobp) (not (org-at-heading-p)))
1259 (when (and selected-task
(marker-buffer selected-task
))
1260 ;; There is a selected task, move to the correct buffer
1261 ;; and set the new target position.
1262 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
1263 (setq target-pos
(marker-position selected-task
))
1264 (move-marker selected-task nil
))
1265 (org-with-wide-buffer
1266 (goto-char target-pos
)
1267 (org-back-to-heading t
)
1268 (or interrupting
(move-marker org-clock-interrupted-task nil
))
1269 (run-hooks 'org-clock-in-prepare-hook
)
1270 (org-clock-history-push)
1271 (setq org-clock-current-task
(nth 4 (org-heading-components)))
1272 (cond ((functionp org-clock-in-switch-to-state
)
1273 (let ((case-fold-search nil
))
1274 (looking-at org-complex-heading-regexp
))
1275 (let ((newstate (funcall org-clock-in-switch-to-state
1277 (when newstate
(org-todo newstate
))))
1278 ((and org-clock-in-switch-to-state
1279 (not (looking-at (concat org-outline-regexp
"[ \t]*"
1280 org-clock-in-switch-to-state
1282 (org-todo org-clock-in-switch-to-state
)))
1283 (setq org-clock-heading
1284 (cond ((and org-clock-heading-function
1285 (functionp org-clock-heading-function
))
1286 (funcall org-clock-heading-function
))
1287 ((nth 4 (org-heading-components))
1288 (replace-regexp-in-string
1289 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1290 (match-string-no-properties 4)))
1292 (org-clock-find-position org-clock-in-resume
)
1294 ((and org-clock-in-resume
1296 (concat "^[ \t]*" org-clock-string
1297 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1298 " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1299 (message "Matched %s" (match-string 1))
1300 (setq ts
(concat "[" (match-string 1) "]"))
1301 (goto-char (match-end 1))
1302 (setq org-clock-start-time
1304 (org-parse-time-string (match-string 1))))
1305 (setq org-clock-effort
(org-entry-get (point) org-effort-property
))
1306 (setq org-clock-total-time
(org-clock-sum-current-item
1307 (org-clock-get-sum-start))))
1308 ((eq org-clock-in-resume
'auto-restart
)
1309 ;; called from org-clock-load during startup,
1310 ;; do not interrupt, but warn!
1311 (message "Cannot restart clock because task does not contain unfinished clock")
1316 (insert-before-markers "\n")
1319 (when (and (save-excursion
1322 (beginning-of-line 1)
1323 (indent-line-to (- (org-get-indentation) 2)))
1324 (insert org-clock-string
" ")
1325 (setq org-clock-effort
(org-entry-get (point) org-effort-property
))
1326 (setq org-clock-total-time
(org-clock-sum-current-item
1327 (org-clock-get-sum-start)))
1328 (setq org-clock-start-time
1329 (or (and org-clock-continuously org-clock-out-time
)
1333 "You stopped another clock %d mins ago; start this one from then? "
1335 (org-current-time org-clock-rounding-minutes t
))
1336 (float-time leftover
))
1340 (org-current-time org-clock-rounding-minutes t
)))
1341 (setq ts
(org-insert-time-stamp org-clock-start-time
1342 'with-hm
'inactive
))))
1343 (move-marker org-clock-marker
(point) (buffer-base-buffer))
1344 (move-marker org-clock-hd-marker
1345 (save-excursion (org-back-to-heading t
) (point))
1346 (buffer-base-buffer))
1347 (setq org-clock-has-been-used t
)
1349 (when (or (eq org-clock-clocked-in-display
'mode-line
)
1350 (eq org-clock-clocked-in-display
'both
))
1351 (or global-mode-string
(setq global-mode-string
'("")))
1352 (or (memq 'org-mode-line-string global-mode-string
)
1353 (setq global-mode-string
1354 (append global-mode-string
'(org-mode-line-string)))))
1355 ;; add to frame title
1356 (when (or (eq org-clock-clocked-in-display
'frame-title
)
1357 (eq org-clock-clocked-in-display
'both
))
1358 (setq frame-title-format org-clock-frame-title-format
))
1359 (org-clock-update-mode-line)
1360 (when org-clock-mode-line-timer
1361 (cancel-timer org-clock-mode-line-timer
)
1362 (setq org-clock-mode-line-timer nil
))
1363 (when org-clock-clocked-in-display
1364 (setq org-clock-mode-line-timer
1365 (run-with-timer org-clock-update-period
1366 org-clock-update-period
1367 'org-clock-update-mode-line
)))
1368 (when org-clock-idle-timer
1369 (cancel-timer org-clock-idle-timer
)
1370 (setq org-clock-idle-timer nil
))
1371 (setq org-clock-idle-timer
1372 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
1373 (message "Clock starts at %s - %s" ts org--msg-extra
)
1374 (run-hooks 'org-clock-in-hook
))))))
1377 (defun org-clock-in-last (&optional arg
)
1378 "Clock in the last closed clocked item.
1379 When already clocking in, send an warning.
1380 With a universal prefix argument, select the task you want to
1381 clock in from the last clocked in tasks.
1382 With two universal prefix arguments, start clocking using the
1383 last clock-out time, if any.
1384 With three universal prefix arguments, interactively prompt
1385 for a todo state to switch to, overriding the existing value
1386 `org-clock-in-switch-to-state'."
1388 (if (equal arg
'(4)) (org-clock-in arg
)
1389 (let ((start-time (if (or org-clock-continuously
(equal arg
'(16)))
1390 (or org-clock-out-time
1391 (org-current-time org-clock-rounding-minutes t
))
1392 (org-current-time org-clock-rounding-minutes t
))))
1393 (if (null org-clock-history
)
1394 (message "No last clock")
1395 (let ((org-clock-in-switch-to-state
1396 (if (and (not org-clock-current-task
) (equal arg
'(64)))
1397 (completing-read "Switch to state: "
1398 (and org-clock-history
1399 (with-current-buffer
1400 (marker-buffer (car org-clock-history
))
1401 org-todo-keywords-1
)))
1402 org-clock-in-switch-to-state
))
1403 (already-clocking org-clock-current-task
))
1404 (org-clock-clock-in (list (car org-clock-history
)) nil start-time
)
1405 (or already-clocking
1406 ;; Don't display a message if we are already clocking in
1407 (message "Clocking back: %s (in %s)"
1408 org-clock-current-task
1409 (buffer-name (marker-buffer org-clock-marker
)))))))))
1411 (defun org-clock-mark-default-task ()
1412 "Mark current task as default task."
1415 (org-back-to-heading t
)
1416 (move-marker org-clock-default-task
(point))))
1418 (defun org-clock-get-sum-start ()
1419 "Return the time from which clock times should be counted.
1420 This is for the currently running clock as it is displayed
1421 in the mode line. This function looks at the properties
1422 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1423 corresponding variable `org-clock-mode-line-total' and then
1424 decides which time to use."
1425 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
1426 (symbol-name org-clock-mode-line-total
)))
1427 (lr (org-entry-get nil
"LAST_REPEAT")))
1429 ((equal cmt
"current")
1430 (setq org--msg-extra
"showing time in current clock instance")
1432 ((equal cmt
"today")
1433 (setq org--msg-extra
"showing today's task time.")
1434 (let* ((dt (decode-time))
1437 (if (< hour org-extend-today-until
) (setf (nth 3 dt
) (1- day
)))
1438 (setf (nth 2 dt
) org-extend-today-until
)
1439 (setq dt
(append (list 0 0) (nthcdr 2 dt
)))
1440 (apply 'encode-time dt
)))
1441 ((or (equal cmt
"all")
1442 (and (or (not cmt
) (equal cmt
"auto"))
1444 (setq org--msg-extra
"showing entire task time.")
1446 ((or (equal cmt
"repeat")
1447 (and (or (not cmt
) (equal cmt
"auto"))
1449 (setq org--msg-extra
"showing task time since last repeat.")
1452 (org-time-string-to-time lr
)))
1455 (defun org-clock-find-position (find-unclosed)
1456 "Find the location where the next clock line should be inserted.
1457 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1458 line and position cursor in that line."
1459 (org-back-to-heading t
)
1461 (let* ((beg (line-beginning-position))
1462 (end (save-excursion (outline-next-heading) (point)))
1463 (org-clock-into-drawer (org-clock-into-drawer))
1464 (drawer (org-clock-drawer-name)))
1465 ;; Look for a running clock if FIND-UNCLOSED in non-nil.
1467 (let ((open-clock-re
1470 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1471 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1472 (while (re-search-forward open-clock-re end t
)
1473 (let ((element (org-element-at-point)))
1474 (when (and (eq (org-element-type element
) 'clock
)
1475 (eq (org-element-property :status element
) 'running
))
1477 (throw 'exit t
))))))
1478 ;; Look for an existing clock drawer.
1481 (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer
) ":[ \t]*$")))
1482 (while (re-search-forward drawer-re end t
)
1483 (let ((element (org-element-at-point)))
1484 (when (eq (org-element-type element
) 'drawer
)
1485 (let ((cend (org-element-property :contents-end element
)))
1486 (if (and (not org-log-states-order-reversed
) cend
)
1489 (throw 'exit t
)))))))
1491 (let ((clock-re (concat "^[ \t]*" org-clock-string
))
1494 ;; Count the CLOCK lines and store their positions.
1496 (while (re-search-forward clock-re end t
)
1497 (let ((element (org-element-at-point)))
1498 (when (eq (org-element-type element
) 'clock
)
1499 (setq positions
(cons (line-beginning-position) positions
)
1500 count
(1+ count
))))))
1503 ;; Skip planning line and property drawer, if any.
1504 (org-end-of-meta-data)
1505 (unless (bolp) (insert "\n"))
1506 ;; Create a new drawer if necessary.
1507 (when (and org-clock-into-drawer
1508 (or (not (wholenump org-clock-into-drawer
))
1509 (< org-clock-into-drawer
2)))
1510 (let ((beg (point)))
1511 (insert ":" drawer
":\n:END:\n")
1512 (org-indent-region beg
(point))
1516 ;; When a clock drawer needs to be created because of the
1517 ;; number of clock items or simply if it is missing, collect
1518 ;; all clocks in the section and wrap them within the drawer.
1519 ((if (wholenump org-clock-into-drawer
)
1520 (>= (1+ count
) org-clock-into-drawer
)
1522 ;; Skip planning line and property drawer, if any.
1523 (org-end-of-meta-data)
1524 (let ((beg (point)))
1530 (org-trim (delete-and-extract-region
1531 (save-excursion (skip-chars-backward " \r\t\n")
1532 (line-beginning-position 2))
1533 (line-beginning-position 2)))))
1536 (let ((end (point-marker)))
1538 (save-excursion (insert ":" drawer
":\n"))
1540 (org-indent-region (point) end
)
1542 (unless org-log-states-order-reversed
1544 (beginning-of-line -
1))
1545 (set-marker end nil
))))
1546 (org-log-states-order-reversed (goto-char (car (last positions
))))
1547 (t (goto-char (car positions
))))))))
1550 (defun org-clock-out (&optional switch-to-state fail-quietly at-time
)
1551 "Stop the currently running clock.
1552 Throw an error if there is no running clock and FAIL-QUIETLY is nil.
1553 With a universal prefix, prompt for a state to switch the clocked out task
1554 to, overriding the existing value of `org-clock-out-switch-to-state'."
1557 (when (not (org-clocking-p))
1558 (setq global-mode-string
1559 (delq 'org-mode-line-string global-mode-string
))
1560 (setq frame-title-format org-frame-title-format-backup
)
1561 (force-mode-line-update)
1562 (if fail-quietly
(throw 'exit t
) (user-error "No active clock")))
1563 (let ((org-clock-out-switch-to-state
1565 (completing-read "Switch to state: "
1566 (with-current-buffer
1567 (marker-buffer org-clock-marker
)
1568 org-todo-keywords-1
)
1570 org-clock-out-switch-to-state
))
1571 (now (org-current-time org-clock-rounding-minutes
))
1573 (setq org-clock-out-time now
)
1574 (save-excursion ; Do not replace this with `with-current-buffer'.
1575 (with-no-warnings (set-buffer (org-clocking-buffer)))
1578 (goto-char org-clock-marker
)
1579 (beginning-of-line 1)
1580 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1581 (equal (match-string 1) org-clock-string
))
1582 (setq ts
(match-string 2))
1583 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1584 (goto-char (match-end 0))
1585 (delete-region (point) (point-at-eol))
1587 (setq te
(org-insert-time-stamp (or at-time now
) 'with-hm
'inactive
))
1588 (setq s
(- (float-time
1589 (apply #'encode-time
(org-parse-time-string te
)))
1591 (apply #'encode-time
(org-parse-time-string ts
))))
1592 h
(floor (/ s
3600))
1596 (insert " => " (format "%2d:%02d" h m
))
1597 (move-marker org-clock-marker nil
)
1598 (move-marker org-clock-hd-marker nil
)
1599 ;; Possibly remove zero time clocks. However, do not add
1600 ;; a note associated to the CLOCK line in this case.
1601 (cond ((and org-clock-out-remove-zero-time-clocks
1604 (delete-region (line-beginning-position)
1605 (line-beginning-position 2)))
1606 (org-log-note-clock-out
1608 'clock-out nil nil nil
1609 (concat "# Task: " (org-get-heading t
) "\n\n"))))
1610 (when org-clock-mode-line-timer
1611 (cancel-timer org-clock-mode-line-timer
)
1612 (setq org-clock-mode-line-timer nil
))
1613 (when org-clock-idle-timer
1614 (cancel-timer org-clock-idle-timer
)
1615 (setq org-clock-idle-timer nil
))
1616 (setq global-mode-string
1617 (delq 'org-mode-line-string global-mode-string
))
1618 (setq frame-title-format org-frame-title-format-backup
)
1619 (when org-clock-out-switch-to-state
1621 (org-back-to-heading t
)
1622 (let ((org-inhibit-logging t
)
1623 (org-clock-out-when-done nil
))
1625 ((functionp org-clock-out-switch-to-state
)
1626 (let ((case-fold-search nil
))
1627 (looking-at org-complex-heading-regexp
))
1628 (let ((newstate (funcall org-clock-out-switch-to-state
1630 (when newstate
(org-todo newstate
))))
1631 ((and org-clock-out-switch-to-state
1632 (not (looking-at (concat org-outline-regexp
"[ \t]*"
1633 org-clock-out-switch-to-state
1635 (org-todo org-clock-out-switch-to-state
))))))
1636 (force-mode-line-update)
1637 (message (concat "Clock stopped at %s after "
1638 (org-minutes-to-clocksum-string (+ (* 60 h
) m
)) "%s")
1639 te
(if remove
" => LINE REMOVED" ""))
1640 (run-hooks 'org-clock-out-hook
)
1641 (unless (org-clocking-p)
1642 (setq org-clock-current-task nil
)))))))
1644 (add-hook 'org-clock-out-hook
'org-clock-remove-empty-clock-drawer
)
1646 (defun org-clock-remove-empty-clock-drawer ()
1647 "Remove empty clock drawers in current subtree."
1649 (org-back-to-heading t
)
1652 (let ((drawer (org-clock-drawer-name))
1653 (case-fold-search t
))
1655 (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer
)))
1656 (end (save-excursion (outline-next-heading))))
1657 (while (re-search-forward re end t
)
1658 (org-remove-empty-drawer-at (point))))))))))
1660 (defun org-clock-timestamps-up (&optional n
)
1661 "Increase CLOCK timestamps at cursor.
1662 Optional argument N tells to change by that many units."
1664 (org-clock-timestamps-change 'up n
))
1666 (defun org-clock-timestamps-down (&optional n
)
1667 "Increase CLOCK timestamps at cursor.
1668 Optional argument N tells to change by that many units."
1670 (org-clock-timestamps-change 'down n
))
1672 (defun org-clock-timestamps-change (updown &optional n
)
1673 "Change CLOCK timestamps synchronously at cursor.
1674 UPDOWN tells whether to change `up' or `down'.
1675 Optional argument N tells to change by that many units."
1676 (setq org-ts-what nil
)
1677 (when (org-at-timestamp-p t
)
1678 (let ((tschange (if (eq updown
'up
) 'org-timestamp-up
1679 'org-timestamp-down
))
1680 ts1 begts1 ts2 begts2 updatets1 tdiff
)
1682 (move-beginning-of-line 1)
1683 (re-search-forward org-ts-regexp3 nil t
)
1684 (setq ts1
(match-string 0) begts1
(match-beginning 0))
1685 (when (re-search-forward org-ts-regexp3 nil t
)
1686 (setq ts2
(match-string 0) begts2
(match-beginning 0))))
1687 ;; Are we on the second timestamp?
1688 (if (<= begts2
(point)) (setq updatets1 t
))
1690 ;; fall back on org-timestamp-up if there is only one
1691 (funcall tschange n
)
1692 ;; setq this so that (boundp 'org-ts-what is non-nil)
1693 (funcall tschange n
)
1694 (let ((ts (if updatets1 ts2 ts1
))
1695 (begts (if updatets1 begts1 begts2
)))
1698 (org-time-string-to-time org-last-changed-timestamp
)
1699 (org-time-string-to-time ts
)))
1702 (org-timestamp-change
1703 (round (/ (float-time tdiff
)
1704 (cond ((eq org-ts-what
'minute
) 60)
1705 ((eq org-ts-what
'hour
) 3600)
1706 ((eq org-ts-what
'day
) (* 24 3600))
1707 ((eq org-ts-what
'month
) (* 24 3600 31))
1708 ((eq org-ts-what
'year
) (* 24 3600 365.2)))))
1709 org-ts-what
'updown
)))))))
1712 (defun org-clock-cancel ()
1713 "Cancel the running clock by removing the start timestamp."
1715 (when (not (org-clocking-p))
1716 (setq global-mode-string
1717 (delq 'org-mode-line-string global-mode-string
))
1718 (setq frame-title-format org-frame-title-format-backup
)
1719 (force-mode-line-update)
1720 (error "No active clock"))
1721 (save-excursion ; Do not replace this with `with-current-buffer'.
1722 (with-no-warnings (set-buffer (org-clocking-buffer)))
1723 (goto-char org-clock-marker
)
1724 (if (looking-back (concat "^[ \t]*" org-clock-string
".*")
1725 (line-beginning-position))
1726 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1727 (org-remove-empty-drawer-at (point)))
1728 (message "Clock gone, cancel the timer anyway")
1730 (move-marker org-clock-marker nil
)
1731 (move-marker org-clock-hd-marker nil
)
1732 (setq global-mode-string
1733 (delq 'org-mode-line-string global-mode-string
))
1734 (setq frame-title-format org-frame-title-format-backup
)
1735 (force-mode-line-update)
1736 (message "Clock canceled")
1737 (run-hooks 'org-clock-cancel-hook
))
1740 (defun org-clock-goto (&optional select
)
1741 "Go to the currently clocked-in entry, or to the most recently clocked one.
1742 With prefix arg SELECT, offer recently clocked tasks for selection."
1747 (or (org-clock-select-task "Select task to go to: ")
1748 (error "No task selected")))
1749 ((org-clocking-p) org-clock-marker
)
1750 ((and org-clock-goto-may-find-recent-task
1751 (car org-clock-history
)
1752 (marker-buffer (car org-clock-history
)))
1754 (car org-clock-history
))
1755 (t (error "No active or recent clock task")))))
1756 (pop-to-buffer-same-window (marker-buffer m
))
1757 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1760 (org-back-to-heading t
)
1761 (org-cycle-hide-drawers 'children
)
1762 (recenter org-clock-goto-before-context
)
1765 (message "No running clock, this is the most recently clocked task"))
1766 (run-hooks 'org-clock-goto-hook
)))
1768 (defvar-local org-clock-file-total-minutes nil
1769 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1771 (defun org-clock-sum-today (&optional headline-filter
)
1772 "Sum the times for each subtree for today."
1773 (let ((range (org-clock-special-range 'today
)))
1774 (org-clock-sum (car range
) (cadr range
)
1775 headline-filter
:org-clock-minutes-today
)))
1777 (defun org-clock-sum-custom (&optional headline-filter range propname
)
1778 "Sum the times for each subtree for today."
1779 (let ((r (or (and (symbolp range
) (org-clock-special-range range
))
1780 (org-clock-special-range
1781 (intern (completing-read
1783 '("today" "yesterday" "thisweek" "lastweek"
1784 "thismonth" "lastmonth" "thisyear" "lastyear"
1787 (org-clock-sum (car r
) (cadr r
)
1788 headline-filter
(or propname
:org-clock-minutes-custom
))))
1791 (defun org-clock-sum (&optional tstart tend headline-filter propname
)
1792 "Sum the times for each subtree.
1793 Puts the resulting times in minutes as a text property on each headline.
1794 TSTART and TEND can mark a time range to be considered.
1795 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1796 each headline in the time range with point at the headline. Headlines for
1797 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1798 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1799 (org-with-silent-modifications
1800 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1802 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1804 (ltimes (make-vector lmax
0))
1809 (if (stringp tstart
) (setq tstart
(org-time-string-to-seconds tstart
)))
1810 (if (stringp tend
) (setq tend
(org-time-string-to-seconds tend
)))
1811 (if (consp tstart
) (setq tstart
(float-time tstart
)))
1812 (if (consp tend
) (setq tend
(float-time tend
)))
1813 (remove-text-properties (point-min) (point-max)
1814 `(,(or propname
:org-clock-minutes
) t
1815 :org-clock-force-headline-inclusion t
))
1817 (goto-char (point-max))
1818 (while (re-search-backward re nil t
)
1822 (setq ts
(match-string 2)
1825 (apply #'encode-time
(org-parse-time-string ts
)))
1827 (apply #'encode-time
(org-parse-time-string te
)))
1828 ts
(if tstart
(max ts tstart
) ts
)
1829 te
(if tend
(min te tend
) te
)
1831 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
1834 (setq t1
(+ t1
(string-to-number (match-string 5))
1835 (* 60 (string-to-number (match-string 4))))))
1837 ;; Add the currently clocking item time to the total
1838 (when (and org-clock-report-include-clocking-task
1839 (equal (org-clocking-buffer) (current-buffer))
1840 (equal (marker-position org-clock-hd-marker
) (point))
1843 (>= (float-time org-clock-start-time
) tstart
)
1844 (<= (float-time org-clock-start-time
) tend
))
1845 (let ((time (floor (- (float-time)
1846 (float-time org-clock-start-time
))
1848 (setq t1
(+ t1 time
))))
1849 (let* ((headline-forced
1850 (get-text-property (point)
1851 :org-clock-force-headline-inclusion
))
1853 (or (null headline-filter
)
1855 (save-match-data (funcall headline-filter
))))))
1856 (setq level
(- (match-end 1) (match-beginning 1)))
1857 (when (>= level lmax
)
1858 (setq ltimes
(vconcat ltimes
(make-vector lmax
0)) lmax
(* 2 lmax
)))
1859 (when (or (> t1
0) (> (aref ltimes level
) 0))
1860 (when (or headline-included headline-forced
)
1861 (if headline-included
1862 (cl-loop for l from
0 to level do
1863 (aset ltimes l
(+ (aref ltimes l
) t1
))))
1864 (setq time
(aref ltimes level
))
1865 (goto-char (match-beginning 0))
1866 (put-text-property (point) (point-at-eol)
1867 (or propname
:org-clock-minutes
) time
)
1868 (when headline-filter
1871 (while (org-up-heading-safe)
1873 (point) (line-end-position)
1874 :org-clock-force-headline-inclusion t
))))))
1876 (cl-loop for l from level to
(1- lmax
) do
1877 (aset ltimes l
0)))))))
1878 (setq org-clock-file-total-minutes
(aref ltimes
0))))))
1880 (defun org-clock-sum-current-item (&optional tstart
)
1881 "Return time, clocked on current item in total."
1884 (org-narrow-to-subtree)
1885 (org-clock-sum tstart
)
1886 org-clock-file-total-minutes
)))
1889 (defun org-clock-display (&optional arg
)
1890 "Show subtree times in the entire buffer.
1892 By default, show the total time for the range defined in
1893 `org-clock-display-default-range'. With `\\[universal-argument]' \
1895 the total time for today instead.
1897 With `\\[universal-argument] \\[universal-argument]' prefix, \
1898 use a custom range, entered at prompt.
1900 With `\\[universal-argument] \ \\[universal-argument] \
1901 \\[universal-argument]' prefix, display the total time in the
1904 Use `\\[org-clock-remove-overlays]' to remove the subtree times."
1906 (org-clock-remove-overlays)
1907 (let* ((todayp (equal arg
'(4)))
1908 (customp (member arg
'((16) today yesterday
1909 thisweek lastweek thismonth
1910 lastmonth thisyear lastyear
1911 untilnow interactive
)))
1912 (prop (cond ((not arg
) :org-clock-minutes-default
)
1913 (todayp :org-clock-minutes-today
)
1914 (customp :org-clock-minutes-custom
)
1915 (t :org-clock-minutes
)))
1917 (cond ((not arg
) (org-clock-sum-custom
1918 nil org-clock-display-default-range prop
))
1919 (todayp (org-clock-sum-today))
1920 (customp (org-clock-sum-custom nil arg
))
1921 (t (org-clock-sum)))
1922 (unless (eq arg
'(64))
1924 (goto-char (point-min))
1925 (while (or (and (equal (setq p
(point)) (point-min))
1926 (get-text-property p prop
))
1927 (setq p
(next-single-property-change
1930 (when (setq time
(get-text-property p prop
))
1931 (org-clock-put-overlay time
)))
1932 (setq h
(/ org-clock-file-total-minutes
60)
1933 m
(- org-clock-file-total-minutes
(* 60 h
)))
1934 ;; Arrange to remove the overlays upon next change.
1935 (when org-remove-highlights-with-change
1936 (add-hook 'before-change-functions
'org-clock-remove-overlays
1938 (message (concat (format "Total file time%s: "
1939 (cond (todayp " for today")
1940 (customp " (custom)")
1942 (org-minutes-to-clocksum-string
1943 org-clock-file-total-minutes
)
1944 " (%d hours and %d minutes)")
1947 (defvar-local org-clock-overlays nil
)
1949 (defun org-clock-put-overlay (time)
1950 "Put an overlays on the current line, displaying TIME.
1951 This creates a new overlay and stores it in `org-clock-overlays', so that it
1952 will be easy to remove."
1955 (let ((case-fold-search nil
))
1956 (when (looking-at org-complex-heading-regexp
)
1957 (goto-char (match-beginning 4))))
1958 (setq ov
(make-overlay (point) (point-at-eol))
1959 tx
(concat (buffer-substring-no-properties (point) (match-end 4))
1962 (max 0 (- (- 60 (current-column))
1963 (- (match-end 4) (match-beginning 4))
1964 (length (org-get-at-bol 'line-prefix
)))) ?·
)
1967 (format " %9s " (org-minutes-to-clocksum-string time
))
1968 '(face org-clock-overlay
))
1970 (overlay-put ov
'display tx
)
1971 (push ov org-clock-overlays
)))
1974 (defun org-clock-remove-overlays (&optional _beg _end noremove
)
1975 "Remove the occur highlights from the buffer.
1976 If NOREMOVE is nil, remove this function from the
1977 `before-change-functions' in the current buffer."
1979 (unless org-inhibit-highlight-removal
1980 (mapc #'delete-overlay org-clock-overlays
)
1981 (setq org-clock-overlays nil
)
1983 (remove-hook 'before-change-functions
1984 'org-clock-remove-overlays
'local
))))
1986 (defvar org-state
) ;; dynamically scoped into this function
1987 (defun org-clock-out-if-current ()
1988 "Clock out if the current entry contains the running clock.
1989 This is used to stop the clock after a TODO entry is marked DONE,
1990 and is only done if the variable `org-clock-out-when-done' is not nil."
1991 (when (and (org-clocking-p)
1992 org-clock-out-when-done
1993 (marker-buffer org-clock-marker
)
1994 (or (and (eq t org-clock-out-when-done
)
1995 (member org-state org-done-keywords
))
1996 (and (listp org-clock-out-when-done
)
1997 (member org-state org-clock-out-when-done
)))
1998 (equal (or (buffer-base-buffer (org-clocking-buffer))
1999 (org-clocking-buffer))
2000 (or (buffer-base-buffer (current-buffer))
2002 (< (point) org-clock-marker
)
2003 (> (save-excursion (outline-next-heading) (point))
2005 ;; Clock out, but don't accept a logging message for this.
2006 (let ((org-log-note-clock-out nil
)
2007 (org-clock-out-switch-to-state nil
))
2010 (add-hook 'org-after-todo-state-change-hook
2011 'org-clock-out-if-current
)
2014 (defun org-clock-get-clocktable (&rest props
)
2015 "Get a formatted clocktable with parameters according to PROPS.
2016 The table is created in a temporary buffer, fully formatted and
2017 fontified, and then returned."
2019 (setq props
(plist-put props
:name
"clocktable"))
2020 (unless (plist-member props
:maxlevel
)
2021 (setq props
(plist-put props
:maxlevel
2)))
2022 (unless (plist-member props
:scope
)
2023 (setq props
(plist-put props
:scope
'agenda
)))
2026 (org-create-dblock props
)
2028 (org-font-lock-ensure)
2030 (buffer-substring (point) (progn
2031 (re-search-forward "^[ \t]*#\\+END" nil t
)
2035 (defun org-clock-report (&optional arg
)
2036 "Create a table containing a report about clocked time.
2037 If the cursor is inside an existing clocktable block, then the table
2038 will be updated. If not, a new clocktable will be inserted. The scope
2039 of the new clock will be subtree when called from within a subtree, and
2042 When called with a prefix argument, move to the first clock table in the
2043 buffer and update it."
2045 (org-clock-remove-overlays)
2047 (org-find-dblock "clocktable")
2049 (if (org-in-clocktable-p)
2050 (goto-char (org-in-clocktable-p))
2051 (let ((props (if (ignore-errors
2052 (save-excursion (org-back-to-heading)))
2053 (list :name
"clocktable" :scope
'subtree
)
2054 (list :name
"clocktable"))))
2056 (org-combine-plists org-clock-clocktable-default-properties props
))))
2057 (org-update-dblock))
2059 (defun org-day-of-week (day month year
)
2060 "Returns the day of the week as an integer."
2064 (format "%d-%02d-%02dT00:00:00" year month day
)))))
2066 (defun org-quarter-to-date (quarter year
)
2067 "Get the date (week day year) of the first day of a given quarter."
2071 (setq startday
(org-day-of-week 1 1 year
))
2074 (list 52 7 (- year
1)))
2076 (list 52 6 (- year
1)))
2078 (list 1 startday year
))
2080 (list 53 startday
(- year
1)))
2084 (setq startday
(org-day-of-week 1 4 year
))
2087 (list 13 startday year
))
2089 (list 14 startday year
))
2091 (list 13 startday year
))
2095 (setq startday
(org-day-of-week 1 7 year
))
2098 (list 26 startday year
))
2100 (list 27 startday year
))
2102 (list 26 startday year
))
2106 (setq startday
(org-day-of-week 1 10 year
))
2109 (list 39 startday year
))
2111 (list 40 startday year
))
2113 (list 39 startday year
)))))))
2115 (defun org-clock-special-range (key &optional time as-strings wstart mstart
)
2116 "Return two times bordering a special time range.
2118 KEY is a symbol specifying the range and can be one of `today',
2119 `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
2120 `thisyear', `lastyear' or `untilnow'. If set to `interactive',
2121 user is prompted for range boundaries. It can be a string or an
2124 By default, a week starts Monday 0:00 and ends Sunday 24:00. The
2125 range is determined relative to TIME, which defaults to current
2128 The return value is a list containing two internal times, one for
2129 the beginning of the range and one for its end, like the ones
2130 returned by `current time' or `encode-time' and a string used to
2131 display information. If AS-STRINGS is non-nil, the returned
2132 times will be formatted strings.
2134 If WSTART is non-nil, use this number to specify the starting day
2135 of a week (monday is 1). If MSTART is non-nil, use this number
2136 to specify the starting day of a month (1 is the first day of the
2137 month). If you can combine both, the month starting day will
2139 (let* ((tm (decode-time time
))
2146 (skey (format "%s" key
))
2148 (q (cond ((>= month
10) 4)
2152 m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq
)
2154 ((string-match "\\`[0-9]+\\'" skey
)
2155 (setq y
(string-to-number skey
) month
1 d
1 key
'year
))
2156 ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey
)
2157 (setq y
(string-to-number (match-string 1 skey
))
2158 month
(string-to-number (match-string 2 skey
))
2161 ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey
)
2163 (let ((date (calendar-gregorian-from-absolute
2164 (calendar-iso-to-absolute
2165 (list (string-to-number (match-string 2 skey
))
2167 (string-to-number (match-string 1 skey
)))))))
2168 (setq d
(nth 1 date
)
2173 ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey
)
2175 (setq q
(string-to-number (match-string 2 skey
)))
2176 (let ((date (calendar-gregorian-from-absolute
2177 (calendar-iso-to-absolute
2178 (org-quarter-to-date
2179 q
(string-to-number (match-string 1 skey
)))))))
2180 (setq d
(nth 1 date
)
2186 "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
2188 (setq y
(string-to-number (match-string 1 skey
))
2189 month
(string-to-number (match-string 2 skey
))
2190 d
(string-to-number (match-string 3 skey
))
2192 ((string-match "\\([-+][0-9]+\\)\\'" skey
)
2193 (setq shift
(string-to-number (match-string 1 skey
))
2194 key
(intern (substring skey
0 (match-beginning 1))))
2195 (when (and (memq key
'(quarter thisq
)) (> shift
0))
2196 (error "Looking forward with quarters isn't implemented"))))
2199 (`yesterday
(setq key
'today shift -
1))
2200 (`lastweek
(setq key
'week shift -
1))
2201 (`lastmonth
(setq key
'month shift -
1))
2202 (`lastyear
(setq key
'year shift -
1))
2203 (`lastq
(setq key
'quarter shift -
1))))
2204 ;; Prepare start and end times depending on KEY's type.
2206 ((or `day
`today
) (setq m
0 h
0 h1
24 d
(+ d shift
)))
2207 ((or `week
`thisweek
)
2208 (let* ((ws (or wstart
1))
2209 (diff (+ (* -
7 shift
) (if (= dow
0) (- 7 ws
) (- dow ws
)))))
2210 (setq m
0 h
0 d
(- d diff
) d1
(+ 7 d
))))
2211 ((or `month
`thismonth
)
2212 (setq h
0 m
0 d
(or mstart
1) month
(+ month shift
) month1
(1+ month
)))
2213 ((or `quarter
`thisq
)
2214 ;; Compute if this shift remains in this year. If not, compute
2215 ;; how many years and quarters we have to shift (via floor*) and
2216 ;; compute the shifted years, months and quarters.
2218 ((< (+ (- q
1) shift
) 0) ; Shift not in this year.
2219 (let* ((interval (* -
1 (+ (- q
1) shift
)))
2220 ;; Set tmp to ((years to shift) (quarters to shift)).
2221 (tmp (cl-floor interval
4)))
2222 ;; Due to the use of floor, 0 quarters actually means 4.
2223 (if (= 0 (nth 1 tmp
))
2224 (setq shiftedy
(- y
(nth 0 tmp
))
2227 (setq shiftedy
(- y
(+ 1 (nth 0 tmp
)))
2228 shiftedm
(- 13 (* 3 (nth 1 tmp
)))
2229 shiftedq
(- 5 (nth 1 tmp
)))))
2230 (setq m
0 h
0 d
1 month shiftedm month1
(+ 3 shiftedm
) y shiftedy
))
2231 ((> (+ q shift
) 0) ; Shift is within this year.
2232 (setq shiftedq
(+ q shift
))
2234 (let ((qshift (* 3 (1- (+ q shift
)))))
2235 (setq m
0 h
0 d
1 month
(+ 1 qshift
) month1
(+ 4 qshift
))))))
2236 ((or `year
`thisyear
)
2237 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
2238 ((or `interactive
`untilnow
)) ; Special cases, ignore them.
2239 (_ (user-error "No such time block %s" key
)))
2240 ;; Format start and end times according to AS-STRINGS.
2241 (let* ((start (pcase key
2242 (`interactive
(org-read-date nil t nil
"Range start? "))
2243 (`untilnow org-clock--oldest-date
)
2244 (_ (encode-time 0 m h d month y
))))
2246 (`interactive
(org-read-date nil t nil
"Range end? "))
2247 (`untilnow
(current-time))
2256 ((or `day
`today
) (format-time-string "%A, %B %d, %Y" start
))
2257 ((or `week
`thisweek
) (format-time-string "week %G-W%V" start
))
2258 ((or `month
`thismonth
) (format-time-string "%B %Y" start
))
2259 ((or `year
`thisyear
) (format-time-string "the year %Y" start
))
2260 ((or `quarter
`thisq
)
2261 (concat (org-count-quarter shiftedq
)
2262 " quarter of " (number-to-string shiftedy
)))
2263 (`interactive
"(Range interactively set)")
2264 (`untilnow
"now"))))
2265 (if (not as-strings
) (list start end text
)
2266 (let ((f (cdr org-time-stamp-formats
)))
2267 (list (format-time-string f start
)
2268 (format-time-string f end
)
2271 (defun org-count-quarter (n)
2279 (defun org-clocktable-shift (dir n
)
2280 "Try to shift the :block date of the clocktable at point.
2281 Point must be in the #+BEGIN: line of a clocktable, or this function
2282 will throw an error.
2283 DIR is a direction, a symbol `left', `right', `up', or `down'.
2284 Both `left' and `down' shift the block toward the past, `up' and `right'
2285 push it toward the future.
2286 N is the number of shift steps to take. The size of the step depends on
2287 the currently selected interval size."
2288 (setq n
(prefix-numeric-value n
))
2289 (and (memq dir
'(left down
)) (setq n
(- n
)))
2291 (goto-char (point-at-bol))
2292 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2293 (error "Line needs a :block definition before this command works")
2294 (let* ((b (match-beginning 1)) (e (match-end 1))
2295 (s (match-string 1))
2296 block shift ins y mw d date wp m
)
2298 ((equal s
"yesterday") (setq s
"today-1"))
2299 ((equal s
"lastweek") (setq s
"thisweek-1"))
2300 ((equal s
"lastmonth") (setq s
"thismonth-1"))
2301 ((equal s
"lastyear") (setq s
"thisyear-1"))
2302 ((equal s
"lastq") (setq s
"thisq-1")))
2305 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s
)
2306 (setq block
(match-string 1 s
)
2307 shift
(if (match-end 2)
2308 (string-to-number (match-string 2 s
))
2310 (setq shift
(+ shift n
))
2311 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
2312 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
2313 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2314 (setq y
(string-to-number (match-string 1 s
))
2315 wp
(and (match-end 3) (match-string 3 s
))
2316 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
2317 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
2319 (d (setq ins
(format-time-string
2321 (encode-time 0 0 0 (+ d n
) m y
))))
2322 ((and wp
(string-match "w\\|W" wp
) mw
(> (length wp
) 0))
2324 (setq date
(calendar-gregorian-from-absolute
2325 (calendar-iso-to-absolute (list (+ mw n
) 1 y
))))
2326 (setq ins
(format-time-string
2328 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
2329 ((and wp
(string-match "q\\|Q" wp
) mw
(> (length wp
) 0))
2331 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2336 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2341 (setq date
(calendar-gregorian-from-absolute
2342 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n
) y
))))
2343 (setq ins
(format-time-string
2344 (concat (number-to-string y
) "-Q" (number-to-string (+ mw n
)))
2345 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
2347 (setq ins
(format-time-string
2349 (encode-time 0 0 0 1 (+ mw n
) y
))))
2351 (setq ins
(number-to-string (+ y n
))))))
2352 (t (error "Cannot shift clocktable block")))
2356 (delete-region (point) (+ (point) (- e b
)))
2357 (beginning-of-line 1)
2362 (defun org-dblock-write:clocktable
(params)
2363 "Write the standard clocktable."
2364 (setq params
(org-combine-plists org-clocktable-defaults params
))
2366 (let* ((scope (plist-get params
:scope
))
2369 (org-agenda-files t
))
2370 (`agenda-with-archives
2371 (org-add-archive-files (org-agenda-files t
)))
2372 (`file-with-archives
2373 (and buffer-file-name
2374 (org-add-archive-files (list buffer-file-name
))))
2375 ((pred consp
) scope
)
2376 (_ (or (buffer-file-name) (current-buffer)))))
2377 (block (plist-get params
:block
))
2378 (ts (plist-get params
:tstart
))
2379 (te (plist-get params
:tend
))
2380 (ws (plist-get params
:wstart
))
2381 (ms (plist-get params
:mstart
))
2382 (step (plist-get params
:step
))
2383 (formatter (or (plist-get params
:formatter
)
2384 org-clock-clocktable-formatter
2385 'org-clocktable-write-default
))
2387 ;; Check if we need to do steps
2389 ;; Get the range text for the header
2390 (setq cc
(org-clock-special-range block nil t ws ms
)
2394 ;; Write many tables, in steps
2395 (unless (or block
(and ts te
))
2396 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2397 (org-clocktable-steps params
)
2400 (org-agenda-prepare-buffers (if (consp files
) files
(list files
)))
2402 (let ((origin (point))
2405 (mapcar (lambda (file)
2406 (with-current-buffer (find-buffer-visiting file
)
2409 (org-clock-get-table-data file params
)))))
2411 ;; Get the right restriction for the scope.
2413 ((not scope
)) ;use the restriction as it is now
2414 ((eq scope
'file
) (widen))
2415 ((eq scope
'subtree
) (org-narrow-to-subtree))
2417 (while (org-up-heading-safe))
2418 (org-narrow-to-subtree))
2419 ((and (symbolp scope
)
2420 (string-match "\\`tree\\([0-9]+\\)\\'"
2421 (symbol-name scope
)))
2422 (let ((level (string-to-number
2423 (match-string 1 (symbol-name scope
)))))
2425 (while (org-up-heading-safe)
2426 (looking-at org-outline-regexp
)
2427 (when (<= (org-reduced-level (funcall outline-level
))
2429 (throw 'exit nil
))))
2430 (org-narrow-to-subtree))))
2431 (list (org-clock-get-table-data nil params
))))
2433 ;; Even though `file-with-archives' can consist of
2434 ;; multiple files, we consider this is one extended file
2436 (and (consp files
) (not (eq scope
'file-with-archives
)))))
2441 (org-combine-plists params
`(:multifile
,multifile
)))))))
2443 (defun org-clocktable-write-default (ipos tables params
)
2444 "Write out a clock table at position IPOS in the current buffer.
2445 TABLES is a list of tables with clocking data as produced by
2446 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2447 from the dynamic block definition."
2448 ;; This function looks quite complicated, mainly because there are a
2449 ;; lot of options which can add or remove columns. I have massively
2450 ;; commented this function, the I hope it is understandable. If
2451 ;; someone wants to write their own special formatter, this maybe
2452 ;; much easier because there can be a fixed format with a
2453 ;; well-defined number of columns...
2454 (let* ((hlchars '((1 .
"*") (2 .
"/")))
2455 (lwords (assoc (or (plist-get params
:lang
)
2456 (bound-and-true-p org-export-default-language
)
2458 org-clock-clocktable-language-setup
))
2459 (multifile (plist-get params
:multifile
))
2460 (block (plist-get params
:block
))
2461 (sort (plist-get params
:sort
))
2462 (header (plist-get params
:header
))
2463 (ws (or (plist-get params
:wstart
) 1))
2464 (ms (or (plist-get params
:mstart
) 1))
2465 (link (plist-get params
:link
))
2466 (org-time-clocksum-use-effort-durations
2467 (plist-get params
:effort-durations
))
2468 (maxlevel (or (plist-get params
:maxlevel
) 3))
2469 (emph (plist-get params
:emphasize
))
2470 (compact?
(plist-get params
:compact
))
2471 (narrow (or (plist-get params
:narrow
) (and compact?
'40!)))
2472 (level?
(and (not compact?
) (plist-get params
:level
)))
2473 (timestamp (plist-get params
:timestamp
))
2474 (properties (plist-get params
:properties
))
2475 (time-columns (if compact?
1
2476 (min maxlevel
(or (plist-get params
:tcolumns
) 100))))
2477 (indent (or compact?
(plist-get params
:indent
)))
2478 (formula (plist-get params
:formula
))
2479 (case-fold-search t
)
2480 range-text total-time recalc narrow-cut-p
)
2482 (when (and narrow
(integerp narrow
) link
)
2483 ;; We cannot have both integer narrow and link.
2485 "Using hard narrowing in clocktable to allow for links")
2486 (setq narrow
(intern (format "%d!" narrow
))))
2491 ((and (symbolp narrow
)
2492 (string-match "\\`[0-9]+!\\'" (symbol-name narrow
)))
2493 (setq narrow-cut-p t
2494 narrow
(string-to-number (substring (symbol-name narrow
)
2497 (error "Invalid value %s of :narrow property in clock table"
2501 ;; Get the range text for the header.
2502 (setq range-text
(nth 2 (org-clock-special-range block nil t ws ms
))))
2504 ;; Compute the total time.
2505 (setq total-time
(apply #'+ (mapcar #'cadr tables
)))
2507 ;; Now we need to output this tsuff.
2510 ;; Insert the text *before* the actual table.
2511 (insert-before-markers
2513 ;; Format the standard header.
2518 (format-time-string (cdr org-time-stamp-formats
))
2521 (if block
(concat ", for " range-text
".") "")
2524 ;; Insert the narrowing line
2525 (when (and narrow
(integerp narrow
) (not narrow-cut-p
))
2526 (insert-before-markers
2527 "|" ;table line starter
2528 (if multifile
"|" "") ;file column, maybe
2529 (if level?
"|" "") ;level column, maybe
2530 (if timestamp
"|" "") ;timestamp column, maybe
2531 (if properties
(make-string (length properties
) ?|
) "") ;properties columns, maybe
2532 (format "<%d>| |\n" narrow
))) ; headline and time columns
2534 ;; Insert the table header line
2535 (insert-before-markers
2536 "|" ;table line starter
2537 (if multifile
(concat (nth 1 lwords
) "|") "") ;file column, maybe
2538 (if level?
(concat (nth 2 lwords
) "|") "") ;level column, maybe
2539 (if timestamp
(concat (nth 3 lwords
) "|") "") ;timestamp column, maybe
2540 (if properties
;properties columns, maybe
2541 (concat (mapconcat #'identity properties
"|") "|")
2543 (concat (nth 4 lwords
) "|") ;headline
2544 (concat (nth 5 lwords
) "|") ;time column
2545 (make-string (max 0 (1- time-columns
)) ?|
) ;other time columns
2546 (if (eq formula
'%
) "%|\n" "\n"))
2548 ;; Insert the total time in the table
2549 (insert-before-markers
2551 "|" ;table line starter
2552 (if multifile
(concat "| " (nth 6 lwords
) " ") "")
2554 (if level?
"|" "") ;level column, maybe
2555 (if timestamp
"|" "") ;timestamp column, maybe
2556 (make-string (length properties
) ?|
) ;properties columns, maybe
2557 (concat (format org-clock-total-time-cell-format
(nth 7 lwords
))
2559 (format org-clock-total-time-cell-format
2560 (org-minutes-to-clocksum-string (or total-time
0))) ;time
2562 (make-string (max 0 (1- time-columns
)) ?|
)
2563 (cond ((not (eq formula
'%
)) "")
2564 ((or (not total-time
) (= total-time
0)) "0.0|")
2568 ;; Now iterate over the tables and insert the data but only if any
2569 ;; time has been collected.
2570 (when (and total-time
(> total-time
0))
2571 (pcase-dolist (`(,file-name
,file-time
,entries
) tables
)
2572 (when (or (and file-time
(> file-time
0))
2573 (not (plist-get params
:fileskip0
)))
2574 (insert-before-markers "|-\n") ;hline at new file
2575 ;; First the file time, if we have multiple files.
2577 ;; Summarize the time collected from this file.
2578 (insert-before-markers
2579 (format (concat "| %s %s | %s%s"
2580 (format org-clock-file-time-cell-format
2583 (file-name-nondirectory file-name
)
2584 (if level?
"| " "") ;level column, maybe
2585 (if timestamp
"| " "") ;timestamp column, maybe
2586 (if properties
;properties columns, maybe
2587 (make-string (length properties
) ?|
)
2589 (org-minutes-to-clocksum-string file-time
)))) ;time
2591 ;; Get the list of node entries and iterate over it
2592 (when (> maxlevel
0)
2593 (pcase-dolist (`(,level
,headline
,ts
,time .
,props
) entries
)
2596 (if (and (string-match
2597 (format "\\`%s\\'" org-bracket-link-regexp
)
2600 (format "[[%s][%s]]"
2601 (match-string 1 headline
)
2602 (org-shorten-string (match-string 3 headline
)
2604 (org-shorten-string headline narrow
))))
2605 (let ((hlc (if emph
(or (cdr (assoc level hlchars
)) "") "")))
2606 (insert-before-markers
2607 "|" ;start the table line
2608 (if multifile
"|" "") ;free space for file name column?
2609 (if level?
(format "%d|" level
) "") ;level, maybe
2610 (if timestamp
(concat ts
"|") "") ;timestamp, maybe
2611 (if properties
;properties columns, maybe
2612 (concat (mapconcat (lambda (p)
2613 (or (cdr (assoc p props
)) ""))
2618 (if indent
;indentation
2619 (org-clocktable-indent-string level
)
2621 hlc headline hlc
"|" ;headline
2622 ;; Empty fields for higher levels.
2623 (make-string (max 0 (1- (min time-columns level
))) ?|
)
2624 hlc
(org-minutes-to-clocksum-string time
) hlc
"|" ; time
2626 (format "%.1f |" (* 100 (/ time
(float total-time
))))
2631 ;; Possibly rescue old formula?
2632 ((or (not formula
) (eq formula
'%
))
2633 (let ((contents (org-string-nw-p (plist-get params
:content
))))
2634 (when (and contents
(string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents
))
2636 (insert "\n" (match-string 1 contents
))
2637 (beginning-of-line 0))))
2638 ;; Insert specified formula line.
2640 (insert "\n#+TBLFM: " formula
)
2643 (user-error "Invalid :formula parameter in clocktable")))
2644 ;; Back to beginning, align the table, recalculate if necessary.
2646 (skip-chars-forward "^|")
2648 (when org-hide-emphasis-markers
2649 ;; We need to align a second time.
2653 (org-table-goto-line 3)
2654 (org-table-goto-column (car sort
))
2655 (org-table-sort-lines nil
(cdr sort
))))
2656 (when recalc
(org-table-recalculate 'all
))
2659 (defun org-clocktable-indent-string (level)
2660 "Return indentation string according to LEVEL.
2661 LEVEL is an integer. Indent by two spaces per level above 1."
2663 (concat "\\_" (make-string (* 2 (1- level
)) ?\s
))))
2665 (defun org-clocktable-steps (params)
2666 "Step through the range to make a number of clock tables."
2667 (let* ((p1 (copy-sequence params
))
2668 (ts (plist-get p1
:tstart
))
2669 (te (plist-get p1
:tend
))
2670 (ws (plist-get p1
:wstart
))
2671 (ms (plist-get p1
:mstart
))
2672 (step0 (plist-get p1
:step
))
2673 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
2674 (stepskip0 (plist-get p1
:stepskip0
))
2675 (block (plist-get p1
:block
))
2678 (setq cc
(org-clock-special-range block nil t ws ms
)
2683 ;; If ts is a number, it's an absolute day number from
2685 (pcase-let ((`(,month
,day
,year
) (calendar-gregorian-from-absolute ts
)))
2686 (setq ts
(float-time (encode-time 0 0 0 day month year
)))))
2688 (setq ts
(float-time (apply #'encode-time
(org-parse-time-string ts
))))))
2692 (pcase-let ((`(,month
,day
,year
) (calendar-gregorian-from-absolute te
)))
2693 (setq te
(float-time (encode-time 0 0 0 day month year
)))))
2695 (setq te
(float-time (apply #'encode-time
(org-parse-time-string te
))))))
2697 (if (eq step0
'week
)
2698 (- ts
(* 86400 (- (nth 6 (decode-time (seconds-to-time ts
))) ws
)))
2700 (setq p1
(plist-put p1
:header
""))
2701 (setq p1
(plist-put p1
:step nil
))
2702 (setq p1
(plist-put p1
:block nil
))
2704 (or (bolp) (insert "\n"))
2705 (setq p1
(plist-put p1
:tstart
(format-time-string
2706 (org-time-stamp-format nil t
)
2707 (seconds-to-time (max tsb ts
)))))
2708 (setq p1
(plist-put p1
:tend
(format-time-string
2709 (org-time-stamp-format nil t
)
2710 (seconds-to-time (min te
(setq tsb
(+ tsb step
)))))))
2711 (insert "\n" (if (eq step0
'day
) "Daily report: "
2712 "Weekly report starting on: ")
2713 (plist-get p1
:tstart
) "\n")
2714 (setq step-time
(org-dblock-write:clocktable p1
))
2715 (re-search-forward "^[ \t]*#\\+END:")
2716 (when (and (equal step-time
0) stepskip0
)
2717 ;; Remove the empty table
2718 (delete-region (point-at-bol)
2720 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2725 (defun org-clock-get-table-data (file params
)
2726 "Get the clocktable data for file FILE, with parameters PARAMS.
2727 FILE is only for identification - this function assumes that
2728 the correct buffer is current, and that the wanted restriction is
2730 The return value will be a list with the file name and the total
2731 file time (in minutes) as 1st and 2nd elements. The third element
2732 of this list will be a list of headline entries. Each entry has the
2733 following structure:
2735 (LEVEL HEADLINE TIMESTAMP TIME)
2737 LEVEL: The level of the headline, as an integer. This will be
2738 the reduced level, so 1,2,3,... even if only odd levels
2740 HEADLINE: The text of the headline. Depending on PARAMS, this may
2741 already be formatted like a link.
2742 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2743 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2745 TIME: The sum of all time spend in this tree, in minutes. This time
2746 will of cause be restricted to the time block and tags match
2747 specified in PARAMS."
2748 (let* ((maxlevel (or (plist-get params
:maxlevel
) 3))
2749 (timestamp (plist-get params
:timestamp
))
2750 (ts (plist-get params
:tstart
))
2751 (te (plist-get params
:tend
))
2752 (ws (plist-get params
:wstart
))
2753 (ms (plist-get params
:mstart
))
2754 (block (plist-get params
:block
))
2755 (link (plist-get params
:link
))
2756 (tags (plist-get params
:tags
))
2757 (properties (plist-get params
:properties
))
2758 (inherit-property-p (plist-get params
:inherit-props
))
2759 (matcher (and tags
(cdr (org-make-tags-matcher tags
))))
2760 cc st p time level hdl props tsp tbl
)
2762 (setq org-clock-file-total-minutes nil
)
2764 (setq cc
(org-clock-special-range block nil t ws ms
)
2767 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
2768 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
2769 (when (and ts
(listp ts
))
2770 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
2771 (when (and te
(listp te
))
2772 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
2773 ;; Now the times are strings we can parse.
2774 (if ts
(setq ts
(org-matcher-time ts
)))
2775 (if te
(setq te
(org-matcher-time te
)))
2777 (org-clock-sum ts te
2780 (let* ((tags-list (org-get-tags-at))
2781 (org-scanner-tags tags-list
)
2782 (org-trust-scanner-tags t
))
2783 (funcall ,matcher nil tags-list nil
)))))
2784 (goto-char (point-min))
2786 (while (or (and (bobp) (prog1 st
(setq st nil
))
2787 (get-text-property (point) :org-clock-minutes
)
2788 (setq p
(point-min)))
2789 (setq p
(next-single-property-change
2790 (point) :org-clock-minutes
)))
2792 (when (setq time
(get-text-property p
:org-clock-minutes
))
2794 (beginning-of-line 1)
2795 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$")
2796 (setq level
(org-reduced-level
2797 (- (match-end 1) (match-beginning 1))))
2798 (<= level maxlevel
))
2799 (setq hdl
(if (not link
)
2801 (org-make-link-string
2802 (format "file:%s::%s"
2806 (org-make-org-heading-search-string
2807 (replace-regexp-in-string
2808 org-bracket-link-regexp
2809 (lambda (m) (or (match-string 3 m
)
2810 (match-string 1 m
)))
2811 (match-string 2)))))
2813 (setq props
(org-entry-properties (point)))
2814 (or (cdr (assoc "SCHEDULED" props
))
2815 (cdr (assoc "DEADLINE" props
))
2816 (cdr (assoc "TIMESTAMP" props
))
2817 (cdr (assoc "TIMESTAMP_IA" props
))))
2818 props
(when properties
2822 (when (org-entry-get (point) p inherit-property-p
)
2823 (cons p
(org-entry-get (point) p inherit-property-p
))))
2825 (when (> time
0) (push (list level hdl tsp time props
) tbl
))))))
2826 (setq tbl
(nreverse tbl
))
2827 (list file org-clock-file-total-minutes tbl
))))
2829 ;; Saving and loading the clock
2831 (defvar org-clock-loaded nil
2832 "Was the clock file loaded?")
2835 (defun org-clock-update-time-maybe ()
2836 "If this is a CLOCK line, update it and return t.
2837 Otherwise, return nil."
2840 (beginning-of-line 1)
2841 (skip-chars-forward " \t")
2842 (when (looking-at org-clock-string
)
2843 (let ((re (concat "[ \t]*" org-clock-string
2844 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2845 "\\([ \t]*=>.*\\)?\\)?"))
2848 ((not (looking-at re
))
2850 ((not (match-end 2))
2851 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
2852 (> org-clock-marker
(point))
2853 (<= org-clock-marker
(point-at-eol)))
2854 ;; The clock is running here
2855 (setq org-clock-start-time
2857 (org-parse-time-string (match-string 1))))
2858 (org-clock-update-mode-line)))
2860 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2862 (setq ts
(match-string 1)
2863 te
(match-string 3))
2864 (setq s
(- (float-time
2865 (apply #'encode-time
(org-parse-time-string te
)))
2867 (apply #'encode-time
(org-parse-time-string ts
))))
2870 h
(floor (/ s
3600))
2874 (insert " => " (format (if neg
"-%d:%02d" "%2d:%02d") h m
))
2877 (defun org-clock-save ()
2878 "Persist various clock-related data to disk.
2879 The details of what will be saved are regulated by the variable
2880 `org-clock-persist'."
2881 (when (and org-clock-persist
2882 (or org-clock-loaded
2883 org-clock-has-been-used
2884 (not (file-exists-p org-clock-persist-file
))))
2885 (with-temp-file org-clock-persist-file
2886 (insert (format ";; %s - %s at %s\n"
2887 (file-name-nondirectory org-clock-persist-file
)
2889 (format-time-string (org-time-stamp-format t
))))
2890 ;; Store clock to be resumed.
2891 (when (and (memq org-clock-persist
'(t clock
))
2892 (let ((b (org-base-buffer (org-clocking-buffer))))
2893 (and (buffer-live-p b
)
2894 (buffer-file-name b
)
2895 (or (not org-clock-persist-query-save
)
2896 (y-or-n-p (format "Save current clock (%s) "
2897 org-clock-heading
))))))
2899 (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
2900 (buffer-file-name (org-base-buffer (org-clocking-buffer)))
2901 (marker-position org-clock-marker
))))
2902 ;; Store clocked task history. Tasks are stored reversed to
2903 ;; make reading simpler.
2904 (when (and (memq org-clock-persist
'(t history
))
2907 (format "(setq org-clock-stored-history '(%s))\n"
2910 (let ((b (org-base-buffer (marker-buffer m
))))
2911 (when (and (buffer-live-p b
)
2912 (buffer-file-name b
))
2914 (buffer-file-name b
)
2915 (marker-position m
)))))
2916 (reverse org-clock-history
)
2919 (defun org-clock-load ()
2920 "Load clock-related data from disk, maybe resuming a stored clock."
2921 (when (and org-clock-persist
(not org-clock-loaded
))
2922 (if (not (file-readable-p org-clock-persist-file
))
2923 (message "Not restoring clock data; %S not found" org-clock-persist-file
)
2924 (message "Restoring clock data")
2926 (load-file org-clock-persist-file
)
2927 (setq org-clock-loaded t
)
2928 (pcase-dolist (`(,(and file
(pred file-exists-p
)) .
,position
)
2929 org-clock-stored-history
)
2930 (org-clock-history-push position
(find-file-noselect file
)))
2932 (pcase org-clock-stored-resume-clock
2933 (`(,(and file
(pred file-exists-p
)) .
,position
)
2934 (with-current-buffer (find-file-noselect file
)
2935 (when (or (not org-clock-persist-query-resume
)
2936 (y-or-n-p (format "Resume clock (%s) "
2938 (goto-char position
)
2939 (org-get-heading t t
)))))
2940 (goto-char position
)
2941 (let ((org-clock-in-resume 'auto-restart
)
2942 (org-clock-auto-clock-resolution nil
))
2944 (when (outline-invisible-p) (org-show-context))))))
2947 ;; Suggested bindings
2948 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
2950 (provide 'org-clock
)
2953 ;; generated-autoload-file: "org-loaddefs.el"
2956 ;;; org-clock.el ends here