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 <https://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the time clocking code for Org mode
34 (declare-function calendar-iso-to-absolute
"cal-iso" (date))
35 (declare-function notifications-notify
"notifications" (&rest params
))
36 (declare-function org-element-property
"org-element" (property element
))
37 (declare-function org-element-type
"org-element" (element))
38 (declare-function org-table-goto-line
"org-table" (n))
40 (defvar org-frame-title-format-backup frame-title-format
)
41 (defvar org-time-stamp-formats
)
44 (defgroup org-clock nil
45 "Options concerning clocking working time in Org mode."
49 (defcustom org-clock-into-drawer t
50 "Non-nil when clocking info should be wrapped into a drawer.
52 When non-nil, clocking info will be inserted into the same drawer
53 as log notes (see variable `org-log-into-drawer'), if it exists,
54 or \"LOGBOOK\" otherwise. If necessary, the drawer will be
57 When an integer, the drawer is created only when the number of
58 clocking entries in an item reaches or exceeds this value.
60 When a string, it becomes the name of the drawer, ignoring the
61 log notes drawer altogether.
63 Do not check directly this variable in a Lisp program. Call
64 function `org-clock-into-drawer' instead."
68 :package-version
'(Org .
"8.3")
70 (const :tag
"Always" t
)
71 (const :tag
"Only when drawer exists" nil
)
72 (integer :tag
"When at least N clock entries")
73 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
74 (string :tag
"Into Drawer named...")))
76 (defun org-clock-into-drawer ()
77 "Value of `org-clock-into-drawer'. but let properties overrule.
79 If the current entry has or inherits a CLOCK_INTO_DRAWER
80 property, it will be used instead of the default value.
82 Return value is either a string, an integer, or nil."
83 (let ((p (org-entry-get nil
"CLOCK_INTO_DRAWER" 'inherit t
)))
84 (cond ((equal p
"nil") nil
)
85 ((equal p
"t") (or (org-log-into-drawer) "LOGBOOK"))
87 (if (string-match-p "\\`[0-9]+\\'" p
) (string-to-number p
) p
))
88 ((org-string-nw-p org-clock-into-drawer
))
89 ((integerp org-clock-into-drawer
) org-clock-into-drawer
)
90 ((not org-clock-into-drawer
) nil
)
91 ((org-log-into-drawer))
94 (defcustom org-clock-out-when-done t
95 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
97 DONE here means any DONE-like state.
98 A nil value means clock will keep running until stopped explicitly with
99 `\\[org-clock-out]', or until the clock is started in a different item.
100 Instead of t, this can also be a list of TODO states that should trigger
104 (const :tag
"No" nil
)
105 (const :tag
"Yes, when done" t
)
106 (repeat :tag
"State list"
107 (string :tag
"TODO keyword"))))
109 (defcustom org-clock-rounding-minutes
0
110 "Rounding minutes when clocking in or out.
111 The default value is 0 so that no rounding is done.
112 When set to a non-integer value, use the car of
113 `org-time-stamp-rounding-minutes', like for setting a time-stamp.
115 E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
116 and you clock in: then the clock starts at 14:45. If you clock
117 out within the next 5 minutes, the clock line will be removed;
118 if you clock out 8 minutes after your clocked in, the clock
119 out time will be 14:50."
122 :package-version
'(Org .
"8.0")
124 (integer :tag
"Minutes (0 for no rounding)")
125 (symbol :tag
"Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp
)))
127 (defcustom org-clock-out-remove-zero-time-clocks nil
128 "Non-nil means remove the clock line when the resulting time is zero."
132 (defcustom org-clock-in-switch-to-state nil
133 "Set task to a special todo state while clocking it.
134 The value should be the state to which the entry should be
135 switched. If the value is a function, it must take one
136 parameter (the current TODO state of the item) and return the
137 state to switch it to."
141 (const :tag
"Don't force a state" nil
)
142 (string :tag
"State")
143 (symbol :tag
"Function")))
145 (defcustom org-clock-out-switch-to-state nil
146 "Set task to a special todo state after clocking out.
147 The value should be the state to which the entry should be
148 switched. If the value is a function, it must take one
149 parameter (the current TODO state of the item) and return the
150 state to switch it to."
154 (const :tag
"Don't force a state" nil
)
155 (string :tag
"State")
156 (symbol :tag
"Function")))
158 (defcustom org-clock-history-length
5
159 "Number of clock tasks to remember in history."
163 (defcustom org-clock-goto-may-find-recent-task t
164 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
168 (defcustom org-clock-heading-function nil
169 "When non-nil, should be a function to create `org-clock-heading'.
170 This is the string shown in the mode line when a clock is running.
171 The function is called with point at the beginning of the headline."
173 :type
'(choice (const nil
) (function)))
175 (defcustom org-clock-string-limit
0
176 "Maximum length of clock strings in the mode line. 0 means no limit."
180 (defcustom org-clock-in-resume nil
181 "If non-nil, resume clock when clocking into task with open clock.
182 When clocking into a task with a clock entry which has not been closed,
183 the clock can be resumed from that point."
187 (defcustom org-clock-persist nil
188 "When non-nil, save the running clock when Emacs is closed.
189 The clock is resumed when Emacs restarts.
190 When this is t, both the running clock, and the entire clock
191 history are saved. When this is the symbol `clock', only the
192 running clock is saved. When this is the symbol `history', only
193 the clock history is saved.
195 When Emacs restarts with saved clock information, the file containing
196 the running clock as well as all files mentioned in the clock history
199 All this depends on running `org-clock-persistence-insinuate' in your
200 Emacs initialization file."
203 (const :tag
"Just the running clock" clock
)
204 (const :tag
"Just the history" history
)
205 (const :tag
"Clock and history" t
)
206 (const :tag
"No persistence" nil
)))
208 (defcustom org-clock-persist-file
(convert-standard-filename
209 (concat user-emacs-directory
"org-clock-save.el"))
210 "File to save clock data to."
214 (defcustom org-clock-persist-query-save nil
215 "When non-nil, ask before saving the current clock on exit."
219 (defcustom org-clock-persist-query-resume t
220 "When non-nil, ask before resuming any stored clock during load."
224 (defcustom org-clock-sound nil
225 "Sound to use for notifications.
229 t Standard Emacs beep
230 file name Play this sound file, fall back to beep"
233 (const :tag
"No sound" nil
)
234 (const :tag
"Standard beep" t
)
235 (file :tag
"Play sound file")))
237 (defcustom org-clock-mode-line-total
'auto
238 "Default setting for the time included for the mode line clock.
239 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
242 current Only the time in the current instance of the clock
243 today All time clocked into this task today
244 repeat All time clocked into this task since last repeat
245 all All time ever recorded for this task
246 auto Automatically, either `all', or `repeat' for repeating tasks"
249 (const :tag
"Current clock" current
)
250 (const :tag
"Today's task time" today
)
251 (const :tag
"Since last repeat" repeat
)
252 (const :tag
"All task time" all
)
253 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
255 (defvaralias 'org-task-overrun-text
'org-clock-task-overrun-text
)
256 (defcustom org-clock-task-overrun-text nil
257 "Extra mode line text to indicate that the clock is overrun.
258 The can be nil to indicate that instead of adding text, the clock time
259 should get a different face (`org-mode-line-clock-overrun').
260 When this is a string, it is prepended to the clock string as an indication,
261 also using the face `org-mode-line-clock-overrun'."
265 (const :tag
"Just mark the time string" nil
)
266 (string :tag
"Text to prepend")))
268 (defcustom org-show-notification-handler nil
269 "Function or program to send notification with.
270 The function or program will be called with the notification
275 (string :tag
"Program")
276 (function :tag
"Function")))
278 (defgroup org-clocktable nil
279 "Options concerning the clock table in Org mode."
280 :tag
"Org Clock Table"
283 (defcustom org-clocktable-defaults
286 :lang
(or (bound-and-true-p org-export-default-language
) "en")
306 "Default properties for clock tables."
311 (defcustom org-clock-clocktable-formatter
'org-clocktable-write-default
312 "Function to turn clocking data into a table.
313 For more information, see `org-clocktable-write-default'."
314 :group
'org-clocktable
318 ;; FIXME: translate es and nl last string "Clock summary at"
319 (defcustom org-clock-clocktable-language-setup
320 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
321 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
322 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à ")
323 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
324 ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT"
325 "Gesamtdauer" "Dateizeit" "Erstellt am"))
326 "Terms used in clocktable, translated to different languages."
327 :group
'org-clocktable
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
)))))
482 ;; libc in macOS 10.6 hangs when decoding times
483 ;; around year -2**31. Limit `high' not to go
484 ;; any earlier than that.
485 (unless (and (eq system-type
'darwin
)
487 "10\\.6\\.[[:digit:]]"
488 (shell-command-to-string
489 "sw_vers -productVersion"))
490 (<= m -
1034058203136))
491 (ignore-errors (decode-time (list m
0)))))))
496 (lambda (m) (ignore-errors (decode-time (list high m
)))))))
498 "Internal time for oldest date representable on the system.")
500 ;;; The clock for measuring work time.
502 (defvar org-mode-line-string
"")
503 (put 'org-mode-line-string
'risky-local-variable t
)
505 (defvar org-clock-mode-line-timer nil
)
506 (defvar org-clock-idle-timer nil
)
507 (defvar org-clock-heading
) ; defined in org.el
508 (defvar org-clock-start-time
"")
510 (defvar org-clock-leftover-time nil
511 "If non-nil, user canceled a clock; this is when leftover time started.")
513 (defvar org-clock-effort
""
514 "Effort estimate of the currently clocking task.")
516 (defvar org-clock-total-time nil
517 "Holds total time, spent previously on currently clocked item.
518 This does not include the time in the currently running clock.")
520 (defvar org-clock-history nil
521 "List of marker pointing to recent clocked tasks.")
523 (defvar org-clock-default-task
(make-marker)
524 "Marker pointing to the default task that should clock time.
525 The clock can be made to switch to this task after clocking out
526 of a different task.")
528 (defvar org-clock-interrupted-task
(make-marker)
529 "Marker pointing to the task that has been interrupted by the current clock.")
531 (defvar org-clock-mode-line-map
(make-sparse-keymap))
532 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
533 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
535 (defun org-clock--translate (s language
)
536 "Translate string S into using string LANGUAGE.
537 Assume S in the English term to translate. Return S as-is if it
538 cannot be translated."
540 ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5)
541 ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9))
542 (assoc-string language org-clock-clocktable-language-setup t
))
545 (defun org-clock-menu ()
549 ["Clock out" org-clock-out t
]
550 ["Change effort estimate" org-clock-modify-effort-estimate t
]
551 ["Go to clock entry" org-clock-goto t
]
552 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
554 (defun org-clock-history-push (&optional pos buffer
)
555 "Push a marker to the clock history."
556 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
557 (let ((m (move-marker (make-marker)
558 (or pos
(point)) (org-base-buffer
559 (or buffer
(current-buffer)))))
561 (while (setq n
(member m org-clock-history
))
562 (move-marker (car n
) nil
))
563 (setq org-clock-history
565 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
567 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
568 (setq org-clock-history
570 (nthcdr (- l org-clock-history-length -
1)
571 (nreverse org-clock-history
)))))
572 (push m org-clock-history
)))
574 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
575 "Save relative positions of markers in region."
576 (org-check-and-save-marker org-clock-marker beg end
)
577 (org-check-and-save-marker org-clock-hd-marker beg end
)
578 (org-check-and-save-marker org-clock-default-task beg end
)
579 (org-check-and-save-marker org-clock-interrupted-task beg end
)
580 (dolist (m org-clock-history
)
581 (org-check-and-save-marker m beg end
)))
583 (defun org-clock-drawer-name ()
584 "Return clock drawer's name for current entry, or nil."
585 (let ((drawer (org-clock-into-drawer)))
586 (cond ((integerp drawer
)
587 (let ((log-drawer (org-log-into-drawer)))
588 (if (stringp log-drawer
) log-drawer
"LOGBOOK")))
589 ((stringp drawer
) drawer
)
592 (defun org-clocking-buffer ()
593 "Return the clocking buffer if we are currently clocking a task or nil."
594 (marker-buffer org-clock-marker
))
596 (defun org-clocking-p ()
597 "Return t when clocking a task."
598 (not (equal (org-clocking-buffer) nil
)))
600 (defvar org-clock-before-select-task-hook nil
601 "Hook called in task selection just before prompting the user.")
603 (defun org-clock-select-task (&optional prompt
)
604 "Select a task that was recently associated with clocking.
605 Return marker position of the selected task. Raise an error if
606 there is no recent clock to choose from."
607 (let (och chl sel-list rpl
(i 0) s
)
608 ;; Remove successive dups from the clock history to consider
609 (dolist (c org-clock-history
)
610 (unless (equal c
(car och
)) (push c och
)))
611 (setq och
(reverse och
) chl
(length och
))
613 (user-error "No recent clock")
614 (save-window-excursion
615 (org-switch-to-buffer-other-window
616 (get-buffer-create "*Clock Task Select*"))
618 (when (marker-buffer org-clock-default-task
)
619 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
620 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
622 (when (marker-buffer org-clock-interrupted-task
)
623 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
624 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
626 (when (org-clocking-p)
627 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
628 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
630 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
632 (when (marker-buffer m
)
634 s
(org-clock-insert-selection-line
638 (if (fboundp 'int-to-char
) (setf (car s
) (int-to-char (car s
))))
640 (run-hooks 'org-clock-before-select-task-hook
)
641 (goto-char (point-min))
642 ;; Set min-height relatively to circumvent a possible but in
643 ;; `fit-window-to-buffer'
644 (fit-window-to-buffer nil nil
(if (< chl
10) chl
(+ 5 chl
)))
645 (message (or prompt
"Select task for clocking:"))
646 (setq cursor-type nil rpl
(read-char-exclusive))
651 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
652 (t (user-error "Invalid task choice %c" rpl
)))))))
654 (defun org-clock-insert-selection-line (i marker
)
655 "Insert a line for the clock selection menu.
656 And return a cons cell with the selection character integer and the marker
658 (when (marker-buffer marker
)
659 (let (cat task heading prefix
)
660 (with-current-buffer (org-base-buffer (marker-buffer marker
))
661 (org-with-wide-buffer
664 (setq cat
(org-get-category)
665 heading
(org-get-heading 'notags
)
666 prefix
(save-excursion
667 (org-back-to-heading t
)
668 (looking-at org-outline-regexp
)
671 (org-fontify-like-in-org-mode
672 (concat prefix heading
)
676 (insert (format "[%c] %-12s %s\n" i cat task
))
679 (defvar org-clock-task-overrun nil
680 "Internal flag indicating if the clock has overrun the planned time.")
681 (defvar org-clock-update-period
60
682 "Number of seconds between mode line clock string updates.")
684 (defun org-clock-get-clock-string ()
685 "Form a clock-string, that will be shown in the mode line.
686 If an effort estimate was defined for the current item, use
687 01:30/01:50 format (clocked/estimated).
688 If not, show simply the clocked time like 01:50."
689 (let ((clocked-time (org-clock-get-clocked-time)))
691 (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort
))
694 (org-duration-from-minutes clocked-time
)
695 'face
(if (and org-clock-task-overrun
(not org-clock-task-overrun-text
))
696 'org-mode-line-clock-overrun
'org-mode-line-clock
)))
697 (effort-str (org-duration-from-minutes effort-in-minutes
))
698 (clockstr (propertize
699 (concat " [%s/" effort-str
700 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading
) ")")
701 'face
'org-mode-line-clock
)))
702 (format clockstr work-done-str
))
703 (propertize (concat " [" (org-duration-from-minutes clocked-time
)
704 "]" (format " (%s)" org-clock-heading
))
705 'face
'org-mode-line-clock
))))
707 (defun org-clock-get-last-clock-out-time ()
708 "Get the last clock-out time for the current subtree."
710 (let ((end (save-excursion (org-end-of-subtree))))
711 (when (re-search-forward (concat org-clock-string
712 ".*\\]--\\(\\[[^]]+\\]\\)") end t
)
713 (org-time-string-to-time (match-string 1))))))
715 (defun org-clock-update-mode-line ()
717 (org-clock-notify-once-if-expired)
718 (setq org-clock-task-overrun nil
))
719 (setq org-mode-line-string
721 (let ((clock-string (org-clock-get-clock-string))
722 (help-text "Org mode clock is running.\nmouse-1 shows a \
723 menu\nmouse-2 will jump to task"))
724 (if (and (> org-clock-string-limit
0)
725 (> (length clock-string
) org-clock-string-limit
))
727 (substring clock-string
0 org-clock-string-limit
)
728 'help-echo
(concat help-text
": " org-clock-heading
))
729 (propertize clock-string
'help-echo help-text
)))
730 'local-map org-clock-mode-line-map
731 'mouse-face
'mode-line-highlight
))
732 (if (and org-clock-task-overrun org-clock-task-overrun-text
)
733 (setq org-mode-line-string
735 org-clock-task-overrun-text
736 'face
'org-mode-line-clock-overrun
) org-mode-line-string
)))
737 (force-mode-line-update))
739 (defun org-clock-get-clocked-time ()
740 "Get the clocked time for the current item in minutes.
741 The time returned includes the time spent on this task in
742 previous clocking intervals."
743 (let ((currently-clocked-time
744 (floor (- (float-time)
745 (float-time org-clock-start-time
)) 60)))
746 (+ currently-clocked-time
(or org-clock-total-time
0))))
748 (defun org-clock-modify-effort-estimate (&optional value
)
749 "Add to or set the effort estimate of the item currently being clocked.
750 VALUE can be a number of minutes, or a string with format hh:mm or mm.
751 When the string starts with a + or a - sign, the current value of the effort
752 property will be changed by that amount. If the effort value is expressed
753 as an `org-effort-durations' (e.g. \"3h\"), the modified value will be
754 converted to a hh:mm duration.
756 This command will update the \"Effort\" property of the currently
757 clocked item, and the value displayed in the mode line."
759 (if (org-clock-is-active)
760 (let ((current org-clock-effort
) sign
)
762 ;; Prompt user for a value or a change
765 (format "Set effort (hh:mm or mm%s): "
767 (format ", prefix + to add to %s" org-clock-effort
)
769 (when (stringp value
)
770 ;; A string. See if it is a delta
771 (setq sign
(string-to-char value
))
772 (if (member sign
'(?- ?
+))
773 (setq current
(org-duration-to-minutes current
)
774 value
(substring value
1))
776 (setq value
(org-duration-to-minutes value
))
778 (setq value
(- current value
))
779 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
780 (setq value
(max 0 value
)
781 org-clock-effort
(org-duration-from-minutes value
))
782 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
783 (org-clock-update-mode-line)
784 (message "Effort is now %s" org-clock-effort
))
785 (message "Clock is not currently active")))
787 (defvar org-clock-notification-was-shown nil
788 "Shows if we have shown notification already.")
790 (defun org-clock-notify-once-if-expired ()
791 "Show notification if we spent more time than we estimated before.
792 Notification is shown only once."
793 (when (org-clocking-p)
794 (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort
))
795 (clocked-time (org-clock-get-clocked-time)))
796 (if (setq org-clock-task-overrun
797 (if (or (null effort-in-minutes
) (zerop effort-in-minutes
))
799 (>= clocked-time effort-in-minutes
)))
800 (unless org-clock-notification-was-shown
801 (setq org-clock-notification-was-shown t
)
803 (format-message "Task `%s' should be finished by now. (%s)"
804 org-clock-heading org-clock-effort
)
806 (setq org-clock-notification-was-shown nil
)))))
808 (defun org-notify (notification &optional play-sound
)
809 "Send a NOTIFICATION and maybe PLAY-SOUND.
810 If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
811 (org-show-notification notification
)
812 (if play-sound
(org-clock-play-sound play-sound
)))
814 (defun org-show-notification (notification)
816 Use `org-show-notification-handler' if defined,
817 use libnotify if available, or fall back on a message."
818 (cond ((functionp org-show-notification-handler
)
819 (funcall org-show-notification-handler notification
))
820 ((stringp org-show-notification-handler
)
821 (start-process "emacs-timer-notification" nil
822 org-show-notification-handler notification
))
823 ((fboundp 'notifications-notify
)
824 (notifications-notify
825 :title
"Org mode message"
827 ;; FIXME how to link to the Org icon?
828 ;; :app-icon "~/.emacs.d/icons/mail.png"
830 ((executable-find "notify-send")
831 (start-process "emacs-timer-notification" nil
832 "notify-send" notification
))
833 ;; Maybe the handler will send a message, so only use message as
834 ;; a fall back option
835 (t (message "%s" notification
))))
837 (defun org-clock-play-sound (&optional clock-sound
)
838 "Play sound as configured by `org-clock-sound'.
839 Use alsa's aplay tool if available.
840 If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
841 (let ((org-clock-sound (or clock-sound org-clock-sound
)))
843 ((not org-clock-sound
))
844 ((eq org-clock-sound t
) (beep t
) (beep t
))
845 ((stringp org-clock-sound
)
846 (let ((file (expand-file-name org-clock-sound
)))
847 (if (file-exists-p file
)
848 (if (executable-find "aplay")
849 (start-process "org-clock-play-notification" nil
852 (play-sound-file file
)
853 (error (beep t
) (beep t
))))))))))
855 (defvar org-clock-mode-line-entry nil
856 "Information for the mode line about the running clock.")
858 (defun org-find-open-clocks (file)
859 "Search through the given file and find all open clocks."
860 (let ((buf (or (get-file-buffer file
)
861 (find-file-noselect file
)))
862 (org-clock-re (concat org-clock-string
" \\(\\[.*?\\]\\)$"))
864 (with-current-buffer buf
866 (goto-char (point-min))
867 (while (re-search-forward org-clock-re nil t
)
868 (push (cons (copy-marker (match-end 1) t
)
869 (org-time-string-to-time (match-string 1))) clocks
))))
872 (defsubst org-is-active-clock
(clock)
873 "Return t if CLOCK is the currently active clock."
874 (and (org-clock-is-active)
875 (= org-clock-marker
(car clock
))))
877 (defmacro org-with-clock-position
(clock &rest forms
)
878 "Evaluate FORMS with CLOCK as the current active clock."
879 `(with-current-buffer (marker-buffer (car ,clock
))
880 (org-with-wide-buffer
881 (goto-char (car ,clock
))
884 (def-edebug-spec org-with-clock-position
(form body
))
885 (put 'org-with-clock-position
'lisp-indent-function
1)
887 (defmacro org-with-clock
(clock &rest forms
)
888 "Evaluate FORMS with CLOCK as the current active clock.
889 This macro also protects the current active clock from being altered."
890 `(org-with-clock-position ,clock
891 (let ((org-clock-start-time (cdr ,clock
))
892 (org-clock-total-time)
895 (org-clock-marker (car ,clock
))
896 (org-clock-hd-marker (save-excursion
897 (org-back-to-heading t
)
900 (def-edebug-spec org-with-clock
(form body
))
901 (put 'org-with-clock
'lisp-indent-function
1)
903 (defsubst org-clock-clock-in
(clock &optional resume start-time
)
904 "Clock in to the clock located by CLOCK.
905 If necessary, clock-out of the currently active clock."
906 (org-with-clock-position clock
907 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
908 (org-clock-in nil start-time
))))
910 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
911 "Clock out of the clock located by CLOCK."
912 (let ((temp (copy-marker (car clock
)
913 (marker-insertion-type (car clock
)))))
914 (if (org-is-active-clock clock
)
915 (org-clock-out nil fail-quietly at-time
)
916 (org-with-clock clock
917 (org-clock-out nil fail-quietly at-time
)))
918 (setcar clock temp
)))
920 (defsubst org-clock-clock-cancel
(clock)
921 "Cancel the clock located by CLOCK."
922 (let ((temp (copy-marker (car clock
)
923 (marker-insertion-type (car clock
)))))
924 (if (org-is-active-clock clock
)
926 (org-with-clock clock
928 (setcar clock temp
)))
930 (defvar org-clock-clocking-in nil
)
931 (defvar org-clock-resolving-clocks nil
)
932 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
934 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
935 &optional close-p restart-p fail-quietly
)
936 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
937 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
938 (let ((org-clock-resolving-clocks t
))
941 (org-clock-clock-cancel clock
)
942 (if (and restart-p
(not org-clock-clocking-in
))
943 (org-clock-clock-in clock
)))
945 ((eq resolve-to
'now
)
947 (error "RESTART-P is not valid here"))
948 (if (or close-p org-clock-clocking-in
)
949 (org-clock-clock-out clock fail-quietly
)
950 (unless (org-is-active-clock clock
)
951 (org-clock-clock-in clock t
))))
953 ((not (time-less-p resolve-to
(current-time)))
954 (error "RESOLVE-TO must refer to a time in the past"))
958 (error "RESTART-P is not valid here"))
959 (org-clock-clock-out clock fail-quietly
(or clock-out-time
961 (unless org-clock-clocking-in
963 (setq org-clock-leftover-time
(and (null clock-out-time
)
965 (org-clock-clock-in clock nil
(and clock-out-time
968 (defun org-clock-jump-to-current-clock (&optional effective-clock
)
970 (let ((drawer (org-clock-into-drawer))
971 (clock (or effective-clock
(cons org-clock-marker
972 org-clock-start-time
))))
973 (unless (marker-buffer (car clock
))
974 (error "No clock is currently running"))
975 (org-with-clock clock
(org-clock-goto))
976 (with-current-buffer (marker-buffer (car clock
))
977 (goto-char (car clock
))
979 (org-with-wide-buffer
980 (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
981 (regexp-quote (if (stringp drawer
) drawer
"LOGBOOK"))))
982 (beg (save-excursion (org-back-to-heading t
) (point))))
984 (while (re-search-backward drawer-re beg t
)
985 (let ((element (org-element-at-point)))
986 (when (eq (org-element-type element
) 'drawer
)
987 (when (> (org-element-property :end element
) (car clock
))
988 (org-flag-drawer nil element
))
989 (throw 'exit nil
)))))))))))
991 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
992 "Resolve an open Org clock.
993 An open clock was found, with `dangling' possibly being non-nil.
994 If this function was invoked with a prefix argument, non-dangling
995 open clocks are ignored. The given clock requires some sort of
996 user intervention to resolve it, either because a clock was left
997 dangling or due to an idle timeout. The clock resolution can
1000 (a) deleted, the user doesn't care about the clock
1001 (b) restarted from the current time (if no other clock is open)
1002 (c) closed, giving the clock X minutes
1003 (d) closed and then restarted
1004 (e) resumed, as if the user had never left
1006 The format of clock is (CONS MARKER START-TIME), where MARKER
1007 identifies the buffer and position the clock is open at (and
1008 thus, the heading it's under), and START-TIME is when the clock
1012 (save-window-excursion
1014 (unless org-clock-resolving-clocks-due-to-idleness
1015 (org-clock-jump-to-current-clock clock
))
1016 (unless org-clock-resolve-expert
1017 (with-output-to-temp-buffer "*Org Clock*"
1018 (princ (format-message "Select a Clock Resolution Command:
1020 i/q Ignore this question; the same as keeping all the idle time.
1022 k/K Keep X minutes of the idle time (default is all). If this
1023 amount is less than the default, you will be clocked out
1024 that many minutes after the time that idling began, and then
1025 clocked back in at the present time.
1027 g/G Indicate that you \"got back\" X minutes ago. This is quite
1028 different from `k': it clocks you out from the beginning of
1029 the idle period and clock you back in X minutes ago.
1031 s/S Subtract the idle time from the current clock. This is the
1032 same as keeping 0 minutes.
1034 C Cancel the open timer altogether. It will be as though you
1037 j/J Jump to the current clock, to make manual adjustments.
1039 For all these options, using uppercase makes your final state
1040 to be CLOCKED OUT."))))
1041 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
1043 (while (or (null char-pressed
)
1044 (and (not (memq char-pressed
1045 '(?k ?K ?g ?G ?s ?S ?C
1049 (read-char (concat (funcall prompt-fn clock
)
1052 (and (not (memq char-pressed
'(?i ?q
))) char-pressed
)))))
1054 (floor (/ (float-time
1055 (time-subtract (current-time) last-valid
)) 60)))
1057 (and (memq ch
'(?k ?K
))
1058 (read-number "Keep how many minutes? " default
)))
1060 (and (memq ch
'(?g ?G
))
1061 (read-number "Got back how many minutes ago? " default
)))
1062 (subtractp (memq ch
'(?s ?S
)))
1063 (barely-started-p (< (- (float-time last-valid
)
1064 (float-time (cdr clock
))) 45))
1065 (start-over (and subtractp barely-started-p
)))
1069 (org-clock-resolve-clock clock
'now nil t nil fail-quietly
))
1070 (org-clock-jump-to-current-clock clock
))
1072 (not (memq ch
'(?k ?K ?g ?G ?s ?S ?C
))))
1075 (org-clock-resolve-clock
1078 ;; If the time on the clock was less than a minute before
1079 ;; the user went away, and they've ask to subtract all the
1084 (and gotback
(= gotback
0)))
1086 ((or (and keep
(= keep default
))
1087 (and gotback
(= gotback default
)))
1090 (time-add last-valid
(seconds-to-time (* 60 keep
))))
1092 (time-subtract (current-time)
1093 (seconds-to-time (* 60 gotback
))))
1095 (error "Unexpected, please report this as a bug")))
1096 (and gotback last-valid
)
1097 (memq ch
'(?K ?G ?S
))
1099 (not (memq ch
'(?K ?G ?S ?C
))))
1103 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid
)
1104 "Resolve all currently open Org clocks.
1105 If `only-dangling-p' is non-nil, only ask to resolve dangling
1106 \(i.e., not currently open and valid) clocks."
1108 (unless org-clock-resolving-clocks
1109 (let ((org-clock-resolving-clocks t
))
1110 (dolist (file (org-files-list))
1111 (let ((clocks (org-find-open-clocks file
)))
1112 (dolist (clock clocks
)
1113 (let ((dangling (or (not (org-clock-is-active))
1114 (/= (car clock
) org-clock-marker
))))
1115 (if (or (not only-dangling-p
) dangling
)
1122 "Dangling clock started %d mins ago"
1123 (floor (- (float-time)
1124 (float-time (cdr clock
)))
1127 (cdr clock
)))))))))))
1129 (defun org-emacs-idle-seconds ()
1130 "Return the current Emacs idle time in seconds, or nil if not idle."
1131 (let ((idle-time (current-idle-time)))
1133 (float-time idle-time
)
1136 (defun org-mac-idle-seconds ()
1137 "Return the current Mac idle time in seconds."
1138 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
1140 (defvar org-x11idle-exists-p
1141 ;; Check that x11idle exists
1142 (and (eq window-system
'x
)
1143 (eq 0 (call-process-shell-command
1144 (format "command -v %s" org-clock-x11idle-program-name
)))
1145 ;; Check that x11idle can retrieve the idle time
1146 ;; FIXME: Why "..-shell-command" rather than just `call-process'?
1147 (eq 0 (call-process-shell-command org-clock-x11idle-program-name
))))
1149 (defun org-x11-idle-seconds ()
1150 "Return the current X11 idle time in seconds."
1151 (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name
)) 1000))
1153 (defun org-user-idle-seconds ()
1154 "Return the number of seconds the user has been idle for.
1155 This routine returns a floating point number."
1157 ((eq system-type
'darwin
)
1158 (org-mac-idle-seconds))
1159 ((and (eq window-system
'x
) org-x11idle-exists-p
)
1160 (org-x11-idle-seconds))
1162 (org-emacs-idle-seconds))))
1164 (defvar org-clock-user-idle-seconds
)
1166 (defun org-resolve-clocks-if-idle ()
1167 "Resolve all currently open Org clocks.
1168 This is performed after `org-clock-idle-time' minutes, to check
1169 if the user really wants to stay clocked in after being idle for
1171 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
1172 org-clock-marker
(marker-buffer org-clock-marker
))
1173 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
1174 (org-clock-user-idle-start
1175 (time-subtract (current-time)
1176 (seconds-to-time org-clock-user-idle-seconds
)))
1177 (org-clock-resolving-clocks-due-to-idleness t
))
1178 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
1180 (cons org-clock-marker
1181 org-clock-start-time
)
1183 (format "Clocked in & idle for %.1f mins"
1185 (time-subtract (current-time)
1186 org-clock-user-idle-start
))
1188 org-clock-user-idle-start
)))))
1190 (defvar org-clock-current-task nil
"Task currently clocked in.")
1191 (defvar org-clock-out-time nil
) ; store the time of the last clock-out
1192 (defvar org--msg-extra
)
1195 (defun org-clock-in (&optional select start-time
)
1196 "Start the clock on the current item.
1198 If necessary, clock-out of the currently active clock.
1200 With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
1202 tasks to clock into.
1204 When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
1205 clock into the current task and mark it as
1206 the default task, a special task that will always be offered in the
1207 clocking selection, associated with the letter `d'.
1209 When SELECT is `\\[universal-argument] \\[universal-argument] \
1210 \\[universal-argument]', clock in by using the last clock-out
1211 time as the start time. See `org-clock-continuously' to make this
1212 the default behavior."
1214 (setq org-clock-notification-was-shown nil
)
1215 (org-refresh-effort-properties)
1217 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
1219 ts selected-task target-pos
(org--msg-extra "")
1220 (leftover (and (not org-clock-resolving-clocks
)
1221 org-clock-leftover-time
)))
1223 (when (and org-clock-auto-clock-resolution
1224 (or (not interrupting
)
1225 (eq t org-clock-auto-clock-resolution
))
1226 (not org-clock-clocking-in
)
1227 (not org-clock-resolving-clocks
))
1228 (setq org-clock-leftover-time nil
)
1229 (let ((org-clock-clocking-in t
))
1230 (org-resolve-clocks))) ; check if any clocks are dangling
1232 (when (equal select
'(64))
1233 ;; Set start-time to `org-clock-out-time'
1234 (let ((org-clock-continuously t
))
1235 (org-clock-in nil org-clock-out-time
)))
1237 (when (equal select
'(4))
1238 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
1240 (setq selected-task
(copy-marker selected-task
))
1243 (when (equal select
'(16))
1244 ;; Mark as default clocking task
1245 (org-clock-mark-default-task))
1248 ;; We are interrupting the clocking of a different task.
1249 ;; Save a marker to this task, so that we can go back.
1250 ;; First check if we are trying to clock into the same task!
1251 (when (save-excursion
1252 (unless selected-task
1253 (org-back-to-heading t
))
1254 (and (equal (marker-buffer org-clock-hd-marker
)
1256 (marker-buffer selected-task
)
1258 (= (marker-position org-clock-hd-marker
)
1260 (marker-position selected-task
)
1262 (equal org-clock-current-task
(nth 4 (org-heading-components)))))
1263 (message "Clock continues in \"%s\"" org-clock-heading
)
1265 (move-marker org-clock-interrupted-task
1266 (marker-position org-clock-marker
)
1267 (marker-buffer org-clock-marker
))
1268 (let ((org-clock-clocking-in t
))
1269 (org-clock-out nil t
)))
1271 ;; Clock in at which position?
1273 (if (and (eobp) (not (org-at-heading-p)))
1277 (when (and selected-task
(marker-buffer selected-task
))
1278 ;; There is a selected task, move to the correct buffer
1279 ;; and set the new target position.
1280 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
1281 (setq target-pos
(marker-position selected-task
))
1282 (move-marker selected-task nil
))
1283 (org-with-wide-buffer
1284 (goto-char target-pos
)
1285 (org-back-to-heading t
)
1286 (or interrupting
(move-marker org-clock-interrupted-task nil
))
1287 (run-hooks 'org-clock-in-prepare-hook
)
1288 (org-clock-history-push)
1289 (setq org-clock-current-task
(nth 4 (org-heading-components)))
1290 (cond ((functionp org-clock-in-switch-to-state
)
1291 (let ((case-fold-search nil
))
1292 (looking-at org-complex-heading-regexp
))
1293 (let ((newstate (funcall org-clock-in-switch-to-state
1295 (when newstate
(org-todo newstate
))))
1296 ((and org-clock-in-switch-to-state
1297 (not (looking-at (concat org-outline-regexp
"[ \t]*"
1298 org-clock-in-switch-to-state
1300 (org-todo org-clock-in-switch-to-state
)))
1301 (setq org-clock-heading
1302 (cond ((and org-clock-heading-function
1303 (functionp org-clock-heading-function
))
1304 (funcall org-clock-heading-function
))
1305 ((nth 4 (org-heading-components))
1306 (replace-regexp-in-string
1307 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1308 (match-string-no-properties 4)))
1310 (org-clock-find-position org-clock-in-resume
)
1312 ((and org-clock-in-resume
1314 (concat "^[ \t]*" org-clock-string
1315 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1316 " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1317 (message "Matched %s" (match-string 1))
1318 (setq ts
(concat "[" (match-string 1) "]"))
1319 (goto-char (match-end 1))
1320 (setq org-clock-start-time
1322 (org-parse-time-string (match-string 1))))
1323 (setq org-clock-effort
(org-entry-get (point) org-effort-property
))
1324 (setq org-clock-total-time
(org-clock-sum-current-item
1325 (org-clock-get-sum-start))))
1326 ((eq org-clock-in-resume
'auto-restart
)
1327 ;; called from org-clock-load during startup,
1328 ;; do not interrupt, but warn!
1329 (message "Cannot restart clock because task does not contain unfinished clock")
1334 (insert-before-markers "\n")
1337 (when (and (save-excursion
1340 (beginning-of-line 1)
1341 (indent-line-to (- (org-get-indentation) 2)))
1342 (insert org-clock-string
" ")
1343 (setq org-clock-effort
(org-entry-get (point) org-effort-property
))
1344 (setq org-clock-total-time
(org-clock-sum-current-item
1345 (org-clock-get-sum-start)))
1346 (setq org-clock-start-time
1347 (or (and org-clock-continuously org-clock-out-time
)
1351 "You stopped another clock %d mins ago; start this one from then? "
1353 (org-current-time org-clock-rounding-minutes t
))
1354 (float-time leftover
))
1358 (org-current-time org-clock-rounding-minutes t
)))
1359 (setq ts
(org-insert-time-stamp org-clock-start-time
1360 'with-hm
'inactive
))))
1361 (move-marker org-clock-marker
(point) (buffer-base-buffer))
1362 (move-marker org-clock-hd-marker
1363 (save-excursion (org-back-to-heading t
) (point))
1364 (buffer-base-buffer))
1365 (setq org-clock-has-been-used t
)
1367 (when (or (eq org-clock-clocked-in-display
'mode-line
)
1368 (eq org-clock-clocked-in-display
'both
))
1369 (or global-mode-string
(setq global-mode-string
'("")))
1370 (or (memq 'org-mode-line-string global-mode-string
)
1371 (setq global-mode-string
1372 (append global-mode-string
'(org-mode-line-string)))))
1373 ;; add to frame title
1374 (when (or (eq org-clock-clocked-in-display
'frame-title
)
1375 (eq org-clock-clocked-in-display
'both
))
1376 (setq frame-title-format org-clock-frame-title-format
))
1377 (org-clock-update-mode-line)
1378 (when org-clock-mode-line-timer
1379 (cancel-timer org-clock-mode-line-timer
)
1380 (setq org-clock-mode-line-timer nil
))
1381 (when org-clock-clocked-in-display
1382 (setq org-clock-mode-line-timer
1383 (run-with-timer org-clock-update-period
1384 org-clock-update-period
1385 'org-clock-update-mode-line
)))
1386 (when org-clock-idle-timer
1387 (cancel-timer org-clock-idle-timer
)
1388 (setq org-clock-idle-timer nil
))
1389 (setq org-clock-idle-timer
1390 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
1391 (message "Clock starts at %s - %s" ts org--msg-extra
)
1392 (run-hooks 'org-clock-in-hook
))))))
1395 (defun org-clock-in-last (&optional arg
)
1396 "Clock in the last closed clocked item.
1397 When already clocking in, send an warning.
1398 With a universal prefix argument, select the task you want to
1399 clock in from the last clocked in tasks.
1400 With two universal prefix arguments, start clocking using the
1401 last clock-out time, if any.
1402 With three universal prefix arguments, interactively prompt
1403 for a todo state to switch to, overriding the existing value
1404 `org-clock-in-switch-to-state'."
1406 (if (equal arg
'(4)) (org-clock-in arg
)
1407 (let ((start-time (if (or org-clock-continuously
(equal arg
'(16)))
1408 (or org-clock-out-time
1409 (org-current-time org-clock-rounding-minutes t
))
1410 (org-current-time org-clock-rounding-minutes t
))))
1411 (if (null org-clock-history
)
1412 (message "No last clock")
1413 (let ((org-clock-in-switch-to-state
1414 (if (and (not org-clock-current-task
) (equal arg
'(64)))
1415 (completing-read "Switch to state: "
1416 (and org-clock-history
1417 (with-current-buffer
1418 (marker-buffer (car org-clock-history
))
1419 org-todo-keywords-1
)))
1420 org-clock-in-switch-to-state
))
1421 (already-clocking org-clock-current-task
))
1422 (org-clock-clock-in (list (car org-clock-history
)) nil start-time
)
1423 (or already-clocking
1424 ;; Don't display a message if we are already clocking in
1425 (message "Clocking back: %s (in %s)"
1426 org-clock-current-task
1427 (buffer-name (marker-buffer org-clock-marker
)))))))))
1429 (defun org-clock-mark-default-task ()
1430 "Mark current task as default task."
1433 (org-back-to-heading t
)
1434 (move-marker org-clock-default-task
(point))))
1436 (defun org-clock-get-sum-start ()
1437 "Return the time from which clock times should be counted.
1439 This is for the currently running clock as it is displayed in the
1440 mode line. This function looks at the properties LAST_REPEAT and
1441 in particular CLOCK_MODELINE_TOTAL and the corresponding variable
1442 `org-clock-mode-line-total' and then decides which time to use.
1444 The time is always returned as UTC."
1445 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
1446 (symbol-name org-clock-mode-line-total
)))
1447 (lr (org-entry-get nil
"LAST_REPEAT")))
1449 ((equal cmt
"current")
1450 (setq org--msg-extra
"showing time in current clock instance")
1452 ((equal cmt
"today")
1453 (setq org--msg-extra
"showing today's task time.")
1454 (let* ((dt (org-decode-time nil t
))
1457 (if (< hour org-extend-today-until
) (setf (nth 3 dt
) (1- day
)))
1458 (setf (nth 2 dt
) org-extend-today-until
)
1459 (setq dt
(append (list 0 0) (nthcdr 2 dt
) '(t)))
1460 (apply #'encode-time dt
)))
1461 ((or (equal cmt
"all")
1462 (and (or (not cmt
) (equal cmt
"auto"))
1464 (setq org--msg-extra
"showing entire task time.")
1466 ((or (equal cmt
"repeat")
1467 (and (or (not cmt
) (equal cmt
"auto"))
1469 (setq org--msg-extra
"showing task time since last repeat.")
1470 (and lr
(org-time-string-to-time lr t
)))
1473 (defun org-clock-find-position (find-unclosed)
1474 "Find the location where the next clock line should be inserted.
1475 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1476 line and position cursor in that line."
1477 (org-back-to-heading t
)
1479 (let* ((beg (line-beginning-position))
1480 (end (save-excursion (outline-next-heading) (point)))
1481 (org-clock-into-drawer (org-clock-into-drawer))
1482 (drawer (org-clock-drawer-name)))
1483 ;; Look for a running clock if FIND-UNCLOSED in non-nil.
1485 (let ((open-clock-re
1488 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1489 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1490 (while (re-search-forward open-clock-re end t
)
1491 (let ((element (org-element-at-point)))
1492 (when (and (eq (org-element-type element
) 'clock
)
1493 (eq (org-element-property :status element
) 'running
))
1495 (throw 'exit t
))))))
1496 ;; Look for an existing clock drawer.
1499 (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer
) ":[ \t]*$")))
1500 (while (re-search-forward drawer-re end t
)
1501 (let ((element (org-element-at-point)))
1502 (when (eq (org-element-type element
) 'drawer
)
1503 (let ((cend (org-element-property :contents-end element
)))
1504 (if (and (not org-log-states-order-reversed
) cend
)
1507 (throw 'exit t
)))))))
1509 (let ((clock-re (concat "^[ \t]*" org-clock-string
))
1512 ;; Count the CLOCK lines and store their positions.
1514 (while (re-search-forward clock-re end t
)
1515 (let ((element (org-element-at-point)))
1516 (when (eq (org-element-type element
) 'clock
)
1517 (setq positions
(cons (line-beginning-position) positions
)
1518 count
(1+ count
))))))
1521 ;; Skip planning line and property drawer, if any.
1522 (org-end-of-meta-data)
1523 (unless (bolp) (insert "\n"))
1524 ;; Create a new drawer if necessary.
1525 (when (and org-clock-into-drawer
1526 (or (not (wholenump org-clock-into-drawer
))
1527 (< org-clock-into-drawer
2)))
1528 (let ((beg (point)))
1529 (insert ":" drawer
":\n:END:\n")
1530 (org-indent-region beg
(point))
1534 ;; When a clock drawer needs to be created because of the
1535 ;; number of clock items or simply if it is missing, collect
1536 ;; all clocks in the section and wrap them within the drawer.
1537 ((if (wholenump org-clock-into-drawer
)
1538 (>= (1+ count
) org-clock-into-drawer
)
1540 ;; Skip planning line and property drawer, if any.
1541 (org-end-of-meta-data)
1542 (let ((beg (point)))
1548 (org-trim (delete-and-extract-region
1549 (save-excursion (skip-chars-backward " \r\t\n")
1550 (line-beginning-position 2))
1551 (line-beginning-position 2)))))
1554 (let ((end (point-marker)))
1556 (save-excursion (insert ":" drawer
":\n"))
1558 (org-indent-region (point) end
)
1560 (unless org-log-states-order-reversed
1562 (beginning-of-line -
1))
1563 (set-marker end nil
))))
1564 (org-log-states-order-reversed (goto-char (car (last positions
))))
1565 (t (goto-char (car positions
))))))))
1568 (defun org-clock-out (&optional switch-to-state fail-quietly at-time
)
1569 "Stop the currently running clock.
1570 Throw an error if there is no running clock and FAIL-QUIETLY is nil.
1571 With a universal prefix, prompt for a state to switch the clocked out task
1572 to, overriding the existing value of `org-clock-out-switch-to-state'."
1575 (when (not (org-clocking-p))
1576 (setq global-mode-string
1577 (delq 'org-mode-line-string global-mode-string
))
1578 (setq frame-title-format org-frame-title-format-backup
)
1579 (force-mode-line-update)
1580 (if fail-quietly
(throw 'exit t
) (user-error "No active clock")))
1581 (let ((org-clock-out-switch-to-state
1583 (completing-read "Switch to state: "
1584 (with-current-buffer
1585 (marker-buffer org-clock-marker
)
1586 org-todo-keywords-1
)
1588 org-clock-out-switch-to-state
))
1589 (now (org-current-time org-clock-rounding-minutes
))
1591 (setq org-clock-out-time now
)
1592 (save-excursion ; Do not replace this with `with-current-buffer'.
1593 (with-no-warnings (set-buffer (org-clocking-buffer)))
1596 (goto-char org-clock-marker
)
1597 (beginning-of-line 1)
1598 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1599 (equal (match-string 1) org-clock-string
))
1600 (setq ts
(match-string 2))
1601 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1602 (goto-char (match-end 0))
1603 (delete-region (point) (point-at-eol))
1605 (setq te
(org-insert-time-stamp (or at-time now
) 'with-hm
'inactive
))
1606 (setq s
(- (float-time
1607 (apply #'encode-time
(org-parse-time-string te nil t
)))
1609 (apply #'encode-time
(org-parse-time-string ts nil t
))))
1610 h
(floor (/ s
3600))
1614 (insert " => " (format "%2d:%02d" h m
))
1615 (move-marker org-clock-marker nil
)
1616 (move-marker org-clock-hd-marker nil
)
1617 ;; Possibly remove zero time clocks. However, do not add
1618 ;; a note associated to the CLOCK line in this case.
1619 (cond ((and org-clock-out-remove-zero-time-clocks
1622 (delete-region (line-beginning-position)
1623 (line-beginning-position 2)))
1624 (org-log-note-clock-out
1626 'clock-out nil nil nil
1627 (concat "# Task: " (org-get-heading t
) "\n\n"))))
1628 (when org-clock-mode-line-timer
1629 (cancel-timer org-clock-mode-line-timer
)
1630 (setq org-clock-mode-line-timer nil
))
1631 (when org-clock-idle-timer
1632 (cancel-timer org-clock-idle-timer
)
1633 (setq org-clock-idle-timer nil
))
1634 (setq global-mode-string
1635 (delq 'org-mode-line-string global-mode-string
))
1636 (setq frame-title-format org-frame-title-format-backup
)
1637 (when org-clock-out-switch-to-state
1639 (org-back-to-heading t
)
1640 (let ((org-clock-out-when-done nil
))
1642 ((functionp org-clock-out-switch-to-state
)
1643 (let ((case-fold-search nil
))
1644 (looking-at org-complex-heading-regexp
))
1645 (let ((newstate (funcall org-clock-out-switch-to-state
1647 (when newstate
(org-todo newstate
))))
1648 ((and org-clock-out-switch-to-state
1649 (not (looking-at (concat org-outline-regexp
"[ \t]*"
1650 org-clock-out-switch-to-state
1652 (org-todo org-clock-out-switch-to-state
))))))
1653 (force-mode-line-update)
1654 (message (concat "Clock stopped at %s after "
1655 (org-duration-from-minutes (+ (* 60 h
) m
)) "%s")
1656 te
(if remove
" => LINE REMOVED" ""))
1657 (run-hooks 'org-clock-out-hook
)
1658 (unless (org-clocking-p)
1659 (setq org-clock-current-task nil
)))))))
1661 (add-hook 'org-clock-out-hook
'org-clock-remove-empty-clock-drawer
)
1663 (defun org-clock-remove-empty-clock-drawer ()
1664 "Remove empty clock drawers in current subtree."
1666 (org-back-to-heading t
)
1669 (let ((drawer (org-clock-drawer-name))
1670 (case-fold-search t
))
1672 (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer
)))
1673 (end (save-excursion (outline-next-heading))))
1674 (while (re-search-forward re end t
)
1675 (org-remove-empty-drawer-at (point))))))))))
1677 (defun org-clock-timestamps-up (&optional n
)
1678 "Increase CLOCK timestamps at cursor.
1679 Optional argument N tells to change by that many units."
1681 (org-clock-timestamps-change 'up n
))
1683 (defun org-clock-timestamps-down (&optional n
)
1684 "Increase CLOCK timestamps at cursor.
1685 Optional argument N tells to change by that many units."
1687 (org-clock-timestamps-change 'down n
))
1689 (defun org-clock-timestamps-change (updown &optional n
)
1690 "Change CLOCK timestamps synchronously at cursor.
1691 UPDOWN tells whether to change `up' or `down'.
1692 Optional argument N tells to change by that many units."
1693 (let ((tschange (if (eq updown
'up
) 'org-timestamp-up
1694 'org-timestamp-down
))
1695 (timestamp?
(org-at-timestamp-p 'lax
))
1696 ts1 begts1 ts2 begts2 updatets1 tdiff
)
1699 (move-beginning-of-line 1)
1700 (re-search-forward org-ts-regexp3 nil t
)
1701 (setq ts1
(match-string 0) begts1
(match-beginning 0))
1702 (when (re-search-forward org-ts-regexp3 nil t
)
1703 (setq ts2
(match-string 0) begts2
(match-beginning 0))))
1704 ;; Are we on the second timestamp?
1705 (if (<= begts2
(point)) (setq updatets1 t
))
1707 ;; fall back on org-timestamp-up if there is only one
1708 (funcall tschange n
)
1709 (funcall tschange n
)
1710 (let ((ts (if updatets1 ts2 ts1
))
1711 (begts (if updatets1 begts1 begts2
)))
1714 (org-time-string-to-time org-last-changed-timestamp t
)
1715 (org-time-string-to-time ts t
)))
1718 (org-timestamp-change
1719 (round (/ (float-time tdiff
)
1724 (`month
(* 24 3600 31))
1725 (`year
(* 24 3600 365.2)))))
1726 timestamp?
'updown
)))))))
1729 (defun org-clock-cancel ()
1730 "Cancel the running clock by removing the start timestamp."
1732 (when (not (org-clocking-p))
1733 (setq global-mode-string
1734 (delq 'org-mode-line-string global-mode-string
))
1735 (setq frame-title-format org-frame-title-format-backup
)
1736 (force-mode-line-update)
1737 (error "No active clock"))
1738 (save-excursion ; Do not replace this with `with-current-buffer'.
1739 (with-no-warnings (set-buffer (org-clocking-buffer)))
1740 (goto-char org-clock-marker
)
1741 (if (looking-back (concat "^[ \t]*" org-clock-string
".*")
1742 (line-beginning-position))
1743 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1744 (org-remove-empty-drawer-at (point)))
1745 (message "Clock gone, cancel the timer anyway")
1747 (move-marker org-clock-marker nil
)
1748 (move-marker org-clock-hd-marker nil
)
1749 (setq global-mode-string
1750 (delq 'org-mode-line-string global-mode-string
))
1751 (setq frame-title-format org-frame-title-format-backup
)
1752 (force-mode-line-update)
1753 (message "Clock canceled")
1754 (run-hooks 'org-clock-cancel-hook
))
1757 (defun org-clock-goto (&optional select
)
1758 "Go to the currently clocked-in entry, or to the most recently clocked one.
1759 With prefix arg SELECT, offer recently clocked tasks for selection."
1764 (or (org-clock-select-task "Select task to go to: ")
1765 (error "No task selected")))
1766 ((org-clocking-p) org-clock-marker
)
1767 ((and org-clock-goto-may-find-recent-task
1768 (car org-clock-history
)
1769 (marker-buffer (car org-clock-history
)))
1771 (car org-clock-history
))
1772 (t (error "No active or recent clock task")))))
1773 (pop-to-buffer-same-window (marker-buffer m
))
1774 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1777 (org-back-to-heading t
)
1778 (org-cycle-hide-drawers 'children
)
1779 (recenter org-clock-goto-before-context
)
1782 (message "No running clock, this is the most recently clocked task"))
1783 (run-hooks 'org-clock-goto-hook
)))
1785 (defvar-local org-clock-file-total-minutes nil
1786 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1788 (defun org-clock-sum-today (&optional headline-filter
)
1789 "Sum the times for each subtree for today."
1790 (let ((range (org-clock-special-range 'today
)))
1791 (org-clock-sum (car range
) (cadr range
)
1792 headline-filter
:org-clock-minutes-today
)))
1794 (defun org-clock-sum-custom (&optional headline-filter range propname
)
1795 "Sum the times for each subtree for today."
1796 (let ((r (or (and (symbolp range
) (org-clock-special-range range
))
1797 (org-clock-special-range
1798 (intern (completing-read
1800 '("today" "yesterday" "thisweek" "lastweek"
1801 "thismonth" "lastmonth" "thisyear" "lastyear"
1804 (org-clock-sum (car r
) (cadr r
)
1805 headline-filter
(or propname
:org-clock-minutes-custom
))))
1808 (defun org-clock-sum (&optional tstart tend headline-filter propname
)
1809 "Sum the times for each subtree.
1810 Puts the resulting times in minutes as a text property on each headline.
1811 TSTART and TEND can mark a time range to be considered.
1812 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1813 each headline in the time range with point at the headline. Headlines for
1814 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1815 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1816 (org-with-silent-modifications
1817 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1819 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1821 (ltimes (make-vector lmax
0))
1823 (tstart (cond ((stringp tstart
) (org-time-string-to-seconds tstart t
))
1824 ((consp tstart
) (float-time tstart
))
1826 (tend (cond ((stringp tend
) (org-time-string-to-seconds tend t
))
1827 ((consp tend
) (float-time tend
))
1831 (remove-text-properties (point-min) (point-max)
1832 `(,(or propname
:org-clock-minutes
) t
1833 :org-clock-force-headline-inclusion t
))
1835 (goto-char (point-max))
1836 (while (re-search-backward re nil t
)
1840 (let* ((ts (float-time
1841 (apply #'encode-time
1843 (org-parse-time-string
1844 (match-string 2) nil t
)))))
1846 (apply #'encode-time
1847 (org-parse-time-string (match-string 3) nil t
))))
1848 (dt (- (if tend
(min te tend
) te
)
1849 (if tstart
(max ts tstart
) ts
))))
1850 (when (> dt
0) (cl-incf t1
(floor (/ dt
60))))))
1853 (setq t1
(+ t1
(string-to-number (match-string 5))
1854 (* 60 (string-to-number (match-string 4))))))
1856 ;; Add the currently clocking item time to the total.
1857 (when (and org-clock-report-include-clocking-task
1858 (eq (org-clocking-buffer) (current-buffer))
1859 (eq (marker-position org-clock-hd-marker
) (point))
1862 (>= (float-time org-clock-start-time
) tstart
)
1863 (<= (float-time org-clock-start-time
) tend
))
1864 (let ((time (floor (- (float-time)
1865 (float-time org-clock-start-time
))
1867 (setq t1
(+ t1 time
))))
1868 (let* ((headline-forced
1869 (get-text-property (point)
1870 :org-clock-force-headline-inclusion
))
1872 (or (null headline-filter
)
1874 (save-match-data (funcall headline-filter
))))))
1875 (setq level
(- (match-end 1) (match-beginning 1)))
1876 (when (>= level lmax
)
1877 (setq ltimes
(vconcat ltimes
(make-vector lmax
0)) lmax
(* 2 lmax
)))
1878 (when (or (> t1
0) (> (aref ltimes level
) 0))
1879 (when (or headline-included headline-forced
)
1880 (if headline-included
1881 (cl-loop for l from
0 to level do
1882 (aset ltimes l
(+ (aref ltimes l
) t1
))))
1883 (setq time
(aref ltimes level
))
1884 (goto-char (match-beginning 0))
1885 (put-text-property (point) (point-at-eol)
1886 (or propname
:org-clock-minutes
) time
)
1887 (when headline-filter
1890 (while (org-up-heading-safe)
1892 (point) (line-end-position)
1893 :org-clock-force-headline-inclusion t
))))))
1895 (cl-loop for l from level to
(1- lmax
) do
1896 (aset ltimes l
0)))))))
1897 (setq org-clock-file-total-minutes
(aref ltimes
0))))))
1899 (defun org-clock-sum-current-item (&optional tstart
)
1900 "Return time, clocked on current item in total."
1903 (org-narrow-to-subtree)
1904 (org-clock-sum tstart
)
1905 org-clock-file-total-minutes
)))
1908 (defun org-clock-display (&optional arg
)
1909 "Show subtree times in the entire buffer.
1911 By default, show the total time for the range defined in
1912 `org-clock-display-default-range'. With `\\[universal-argument]' \
1914 the total time for today instead.
1916 With `\\[universal-argument] \\[universal-argument]' prefix, \
1917 use a custom range, entered at prompt.
1919 With `\\[universal-argument] \ \\[universal-argument] \
1920 \\[universal-argument]' prefix, display the total time in the
1923 Use `\\[org-clock-remove-overlays]' to remove the subtree times."
1925 (org-clock-remove-overlays)
1926 (let* ((todayp (equal arg
'(4)))
1927 (customp (member arg
'((16) today yesterday
1928 thisweek lastweek thismonth
1929 lastmonth thisyear lastyear
1930 untilnow interactive
)))
1931 (prop (cond ((not arg
) :org-clock-minutes-default
)
1932 (todayp :org-clock-minutes-today
)
1933 (customp :org-clock-minutes-custom
)
1934 (t :org-clock-minutes
)))
1936 (cond ((not arg
) (org-clock-sum-custom
1937 nil org-clock-display-default-range prop
))
1938 (todayp (org-clock-sum-today))
1939 (customp (org-clock-sum-custom nil arg
))
1940 (t (org-clock-sum)))
1941 (unless (eq arg
'(64))
1943 (goto-char (point-min))
1944 (while (or (and (equal (setq p
(point)) (point-min))
1945 (get-text-property p prop
))
1946 (setq p
(next-single-property-change
1949 (when (setq time
(get-text-property p prop
))
1950 (org-clock-put-overlay time
)))
1951 (setq h
(/ org-clock-file-total-minutes
60)
1952 m
(- org-clock-file-total-minutes
(* 60 h
)))
1953 ;; Arrange to remove the overlays upon next change.
1954 (when org-remove-highlights-with-change
1955 (add-hook 'before-change-functions
'org-clock-remove-overlays
1957 (message (concat (format "Total file time%s: "
1958 (cond (todayp " for today")
1959 (customp " (custom)")
1961 (org-duration-from-minutes
1962 org-clock-file-total-minutes
)
1963 " (%d hours and %d minutes)")
1966 (defvar-local org-clock-overlays nil
)
1968 (defun org-clock-put-overlay (time)
1969 "Put an overlays on the current line, displaying TIME.
1970 This creates a new overlay and stores it in `org-clock-overlays', so that it
1971 will be easy to remove."
1974 (let ((case-fold-search nil
))
1975 (when (looking-at org-complex-heading-regexp
)
1976 (goto-char (match-beginning 4))))
1977 (setq ov
(make-overlay (point) (point-at-eol))
1978 tx
(concat (buffer-substring-no-properties (point) (match-end 4))
1981 (max 0 (- (- 60 (current-column))
1982 (- (match-end 4) (match-beginning 4))
1983 (length (org-get-at-bol 'line-prefix
))))
1987 (format " %9s " (org-duration-from-minutes time
))
1988 '(face org-clock-overlay
))
1990 (overlay-put ov
'display tx
)
1991 (push ov org-clock-overlays
)))
1994 (defun org-clock-remove-overlays (&optional _beg _end noremove
)
1995 "Remove the occur highlights from the buffer.
1996 If NOREMOVE is nil, remove this function from the
1997 `before-change-functions' in the current buffer."
1999 (unless org-inhibit-highlight-removal
2000 (mapc #'delete-overlay org-clock-overlays
)
2001 (setq org-clock-overlays nil
)
2003 (remove-hook 'before-change-functions
2004 'org-clock-remove-overlays
'local
))))
2006 (defvar org-state
) ;; dynamically scoped into this function
2007 (defun org-clock-out-if-current ()
2008 "Clock out if the current entry contains the running clock.
2009 This is used to stop the clock after a TODO entry is marked DONE,
2010 and is only done if the variable `org-clock-out-when-done' is not nil."
2011 (when (and (org-clocking-p)
2012 org-clock-out-when-done
2013 (marker-buffer org-clock-marker
)
2014 (or (and (eq t org-clock-out-when-done
)
2015 (member org-state org-done-keywords
))
2016 (and (listp org-clock-out-when-done
)
2017 (member org-state org-clock-out-when-done
)))
2018 (equal (or (buffer-base-buffer (org-clocking-buffer))
2019 (org-clocking-buffer))
2020 (or (buffer-base-buffer (current-buffer))
2022 (< (point) org-clock-marker
)
2023 (> (save-excursion (outline-next-heading) (point))
2025 ;; Clock out, but don't accept a logging message for this.
2026 (let ((org-log-note-clock-out nil
)
2027 (org-clock-out-switch-to-state nil
))
2030 (add-hook 'org-after-todo-state-change-hook
2031 'org-clock-out-if-current
)
2034 (defun org-clock-get-clocktable (&rest props
)
2035 "Get a formatted clocktable with parameters according to PROPS.
2036 The table is created in a temporary buffer, fully formatted and
2037 fontified, and then returned."
2039 (setq props
(plist-put props
:name
"clocktable"))
2040 (unless (plist-member props
:maxlevel
)
2041 (setq props
(plist-put props
:maxlevel
2)))
2042 (unless (plist-member props
:scope
)
2043 (setq props
(plist-put props
:scope
'agenda
)))
2046 (org-create-dblock props
)
2048 (org-font-lock-ensure)
2050 (buffer-substring (point) (progn
2051 (re-search-forward "^[ \t]*#\\+END" nil t
)
2055 (defun org-clock-report (&optional arg
)
2056 "Create a table containing a report about clocked time.
2057 If the cursor is inside an existing clocktable block, then the table
2058 will be updated. If not, a new clocktable will be inserted. The scope
2059 of the new clock will be subtree when called from within a subtree, and
2062 When called with a prefix argument, move to the first clock table in the
2063 buffer and update it."
2065 (org-clock-remove-overlays)
2067 (org-find-dblock "clocktable")
2069 (if (org-in-clocktable-p)
2070 (goto-char (org-in-clocktable-p))
2071 (let ((props (if (ignore-errors
2072 (save-excursion (org-back-to-heading)))
2073 (list :name
"clocktable" :scope
'subtree
)
2074 (list :name
"clocktable"))))
2076 (org-combine-plists org-clock-clocktable-default-properties props
))))
2077 (org-update-dblock))
2079 (defun org-day-of-week (day month year
)
2080 "Returns the day of the week as an integer."
2084 (format "%d-%02d-%02dT00:00:00" year month day
)))))
2086 (defun org-quarter-to-date (quarter year
)
2087 "Get the date (week day year) of the first day of a given quarter."
2091 (setq startday
(org-day-of-week 1 1 year
))
2094 (list 52 7 (- year
1)))
2096 (list 52 6 (- year
1)))
2098 (list 1 startday year
))
2100 (list 53 startday
(- year
1)))
2104 (setq startday
(org-day-of-week 1 4 year
))
2107 (list 13 startday year
))
2109 (list 14 startday year
))
2111 (list 13 startday year
))
2115 (setq startday
(org-day-of-week 1 7 year
))
2118 (list 26 startday year
))
2120 (list 27 startday year
))
2122 (list 26 startday year
))
2126 (setq startday
(org-day-of-week 1 10 year
))
2129 (list 39 startday year
))
2131 (list 40 startday year
))
2133 (list 39 startday year
)))))))
2135 (defun org-clock-special-range (key &optional time as-strings wstart mstart
)
2136 "Return two times bordering a special time range.
2138 KEY is a symbol specifying the range and can be one of `today',
2139 `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
2140 `thisyear', `lastyear' or `untilnow'. If set to `interactive',
2141 user is prompted for range boundaries. It can be a string or an
2144 By default, a week starts Monday 0:00 and ends Sunday 24:00. The
2145 range is determined relative to TIME, which defaults to current
2148 The return value is a list containing two internal times, one for
2149 the beginning of the range and one for its end, like the ones
2150 returned by `current time' or `encode-time' and a string used to
2151 display information. If AS-STRINGS is non-nil, the returned
2152 times will be formatted strings.
2154 If WSTART is non-nil, use this number to specify the starting day
2155 of a week (monday is 1). If MSTART is non-nil, use this number
2156 to specify the starting day of a month (1 is the first day of the
2157 month). If you can combine both, the month starting day will
2159 (let* ((tm (decode-time time
))
2166 (skey (format "%s" key
))
2168 (q (cond ((>= month
10) 4)
2172 m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq
)
2174 ((string-match "\\`[0-9]+\\'" skey
)
2175 (setq y
(string-to-number skey
) month
1 d
1 key
'year
))
2176 ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey
)
2177 (setq y
(string-to-number (match-string 1 skey
))
2178 month
(string-to-number (match-string 2 skey
))
2181 ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey
)
2183 (let ((date (calendar-gregorian-from-absolute
2184 (calendar-iso-to-absolute
2185 (list (string-to-number (match-string 2 skey
))
2187 (string-to-number (match-string 1 skey
)))))))
2188 (setq d
(nth 1 date
)
2193 ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey
)
2195 (setq q
(string-to-number (match-string 2 skey
)))
2196 (let ((date (calendar-gregorian-from-absolute
2197 (calendar-iso-to-absolute
2198 (org-quarter-to-date
2199 q
(string-to-number (match-string 1 skey
)))))))
2200 (setq d
(nth 1 date
)
2206 "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
2208 (setq y
(string-to-number (match-string 1 skey
))
2209 month
(string-to-number (match-string 2 skey
))
2210 d
(string-to-number (match-string 3 skey
))
2212 ((string-match "\\([-+][0-9]+\\)\\'" skey
)
2213 (setq shift
(string-to-number (match-string 1 skey
))
2214 key
(intern (substring skey
0 (match-beginning 1))))
2215 (when (and (memq key
'(quarter thisq
)) (> shift
0))
2216 (error "Looking forward with quarters isn't implemented"))))
2219 (`yesterday
(setq key
'today shift -
1))
2220 (`lastweek
(setq key
'week shift -
1))
2221 (`lastmonth
(setq key
'month shift -
1))
2222 (`lastyear
(setq key
'year shift -
1))
2223 (`lastq
(setq key
'quarter shift -
1))))
2224 ;; Prepare start and end times depending on KEY's type.
2226 ((or `day
`today
) (setq m
0 h
0 h1
24 d
(+ d shift
)))
2227 ((or `week
`thisweek
)
2228 (let* ((ws (or wstart
1))
2229 (diff (+ (* -
7 shift
) (if (= dow
0) (- 7 ws
) (- dow ws
)))))
2230 (setq m
0 h
0 d
(- d diff
) d1
(+ 7 d
))))
2231 ((or `month
`thismonth
)
2232 (setq h
0 m
0 d
(or mstart
1) month
(+ month shift
) month1
(1+ month
)))
2233 ((or `quarter
`thisq
)
2234 ;; Compute if this shift remains in this year. If not, compute
2235 ;; how many years and quarters we have to shift (via floor*) and
2236 ;; compute the shifted years, months and quarters.
2238 ((< (+ (- q
1) shift
) 0) ; Shift not in this year.
2239 (let* ((interval (* -
1 (+ (- q
1) shift
)))
2240 ;; Set tmp to ((years to shift) (quarters to shift)).
2241 (tmp (cl-floor interval
4)))
2242 ;; Due to the use of floor, 0 quarters actually means 4.
2243 (if (= 0 (nth 1 tmp
))
2244 (setq shiftedy
(- y
(nth 0 tmp
))
2247 (setq shiftedy
(- y
(+ 1 (nth 0 tmp
)))
2248 shiftedm
(- 13 (* 3 (nth 1 tmp
)))
2249 shiftedq
(- 5 (nth 1 tmp
)))))
2250 (setq m
0 h
0 d
1 month shiftedm month1
(+ 3 shiftedm
) y shiftedy
))
2251 ((> (+ q shift
) 0) ; Shift is within this year.
2252 (setq shiftedq
(+ q shift
))
2254 (let ((qshift (* 3 (1- (+ q shift
)))))
2255 (setq m
0 h
0 d
1 month
(+ 1 qshift
) month1
(+ 4 qshift
))))))
2256 ((or `year
`thisyear
)
2257 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
2258 ((or `interactive
`untilnow
)) ; Special cases, ignore them.
2259 (_ (user-error "No such time block %s" key
)))
2260 ;; Format start and end times according to AS-STRINGS.
2261 (let* ((start (pcase key
2262 (`interactive
(org-read-date nil t nil
"Range start? "))
2263 (`untilnow org-clock--oldest-date
)
2264 (_ (encode-time 0 m h d month y
))))
2266 (`interactive
(org-read-date nil t nil
"Range end? "))
2267 (`untilnow
(current-time))
2276 ((or `day
`today
) (format-time-string "%A, %B %d, %Y" start
))
2277 ((or `week
`thisweek
) (format-time-string "week %G-W%V" start
))
2278 ((or `month
`thismonth
) (format-time-string "%B %Y" start
))
2279 ((or `year
`thisyear
) (format-time-string "the year %Y" start
))
2280 ((or `quarter
`thisq
)
2281 (concat (org-count-quarter shiftedq
)
2282 " quarter of " (number-to-string shiftedy
)))
2283 (`interactive
"(Range interactively set)")
2284 (`untilnow
"now"))))
2285 (if (not as-strings
) (list start end text
)
2286 (let ((f (cdr org-time-stamp-formats
)))
2287 (list (format-time-string f start
)
2288 (format-time-string f end
)
2291 (defun org-count-quarter (n)
2299 (defun org-clocktable-shift (dir n
)
2300 "Try to shift the :block date of the clocktable at point.
2301 Point must be in the #+BEGIN: line of a clocktable, or this function
2302 will throw an error.
2303 DIR is a direction, a symbol `left', `right', `up', or `down'.
2304 Both `left' and `down' shift the block toward the past, `up' and `right'
2305 push it toward the future.
2306 N is the number of shift steps to take. The size of the step depends on
2307 the currently selected interval size."
2308 (setq n
(prefix-numeric-value n
))
2309 (and (memq dir
'(left down
)) (setq n
(- n
)))
2311 (goto-char (point-at-bol))
2312 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2313 (error "Line needs a :block definition before this command works")
2314 (let* ((b (match-beginning 1)) (e (match-end 1))
2315 (s (match-string 1))
2316 block shift ins y mw d date wp m
)
2318 ((equal s
"yesterday") (setq s
"today-1"))
2319 ((equal s
"lastweek") (setq s
"thisweek-1"))
2320 ((equal s
"lastmonth") (setq s
"thismonth-1"))
2321 ((equal s
"lastyear") (setq s
"thisyear-1"))
2322 ((equal s
"lastq") (setq s
"thisq-1")))
2325 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s
)
2326 (setq block
(match-string 1 s
)
2327 shift
(if (match-end 2)
2328 (string-to-number (match-string 2 s
))
2330 (setq shift
(+ shift n
))
2331 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
2332 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
2333 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2334 (setq y
(string-to-number (match-string 1 s
))
2335 wp
(and (match-end 3) (match-string 3 s
))
2336 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
2337 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
2339 (d (setq ins
(format-time-string
2341 (encode-time 0 0 0 (+ d n
) m y
))))
2342 ((and wp
(string-match "w\\|W" wp
) mw
(> (length wp
) 0))
2344 (setq date
(calendar-gregorian-from-absolute
2345 (calendar-iso-to-absolute (list (+ mw n
) 1 y
))))
2346 (setq ins
(format-time-string
2348 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
2349 ((and wp
(string-match "q\\|Q" wp
) mw
(> (length wp
) 0))
2351 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2356 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2361 (setq date
(calendar-gregorian-from-absolute
2362 (calendar-iso-to-absolute (org-quarter-to-date (+ mw n
) y
))))
2363 (setq ins
(format-time-string
2364 (concat (number-to-string y
) "-Q" (number-to-string (+ mw n
)))
2365 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
2367 (setq ins
(format-time-string
2369 (encode-time 0 0 0 1 (+ mw n
) y
))))
2371 (setq ins
(number-to-string (+ y n
))))))
2372 (t (error "Cannot shift clocktable block")))
2376 (delete-region (point) (+ (point) (- e b
)))
2377 (beginning-of-line 1)
2382 (defun org-dblock-write:clocktable
(params)
2383 "Write the standard clocktable."
2384 (setq params
(org-combine-plists org-clocktable-defaults params
))
2386 (let* ((scope (plist-get params
:scope
))
2389 (org-agenda-files t
))
2390 (`agenda-with-archives
2391 (org-add-archive-files (org-agenda-files t
)))
2392 (`file-with-archives
2393 (and buffer-file-name
2394 (org-add-archive-files (list buffer-file-name
))))
2395 ((pred functionp
) (funcall scope
))
2396 ((pred consp
) scope
)
2397 (_ (or (buffer-file-name) (current-buffer)))))
2398 (block (plist-get params
:block
))
2399 (ts (plist-get params
:tstart
))
2400 (te (plist-get params
:tend
))
2401 (ws (plist-get params
:wstart
))
2402 (ms (plist-get params
:mstart
))
2403 (step (plist-get params
:step
))
2404 (formatter (or (plist-get params
:formatter
)
2405 org-clock-clocktable-formatter
2406 'org-clocktable-write-default
))
2408 ;; Check if we need to do steps
2410 ;; Get the range text for the header
2411 (setq cc
(org-clock-special-range block nil t ws ms
)
2415 ;; Write many tables, in steps
2416 (unless (or block
(and ts te
))
2417 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2418 (org-clocktable-steps params
)
2421 (org-agenda-prepare-buffers (if (consp files
) files
(list files
)))
2423 (let ((origin (point))
2426 (mapcar (lambda (file)
2427 (with-current-buffer (find-buffer-visiting file
)
2430 (org-clock-get-table-data file params
)))))
2432 ;; Get the right restriction for the scope.
2435 ((not scope
)) ;use the restriction as it is now
2436 ((eq scope
'file
) (widen))
2437 ((eq scope
'subtree
) (org-narrow-to-subtree))
2439 (while (org-up-heading-safe))
2440 (org-narrow-to-subtree))
2441 ((and (symbolp scope
)
2442 (string-match "\\`tree\\([0-9]+\\)\\'"
2443 (symbol-name scope
)))
2444 (let ((level (string-to-number
2445 (match-string 1 (symbol-name scope
)))))
2447 (while (org-up-heading-safe)
2448 (looking-at org-outline-regexp
)
2449 (when (<= (org-reduced-level (funcall outline-level
))
2451 (throw 'exit nil
))))
2452 (org-narrow-to-subtree))))
2453 (list (org-clock-get-table-data nil params
)))))
2455 ;; Even though `file-with-archives' can consist of
2456 ;; multiple files, we consider this is one extended file
2458 (and (consp files
) (not (eq scope
'file-with-archives
)))))
2463 (org-combine-plists params
`(:multifile
,multifile
)))))))
2465 (defun org-clocktable-write-default (ipos tables params
)
2466 "Write out a clock table at position IPOS in the current buffer.
2467 TABLES is a list of tables with clocking data as produced by
2468 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2469 from the dynamic block definition."
2470 ;; This function looks quite complicated, mainly because there are a
2471 ;; lot of options which can add or remove columns. I have massively
2472 ;; commented this function, the I hope it is understandable. If
2473 ;; someone wants to write their own special formatter, this maybe
2474 ;; much easier because there can be a fixed format with a
2475 ;; well-defined number of columns...
2476 (let* ((lang (or (plist-get params
:lang
) "en"))
2477 (multifile (plist-get params
:multifile
))
2478 (block (plist-get params
:block
))
2479 (sort (plist-get params
:sort
))
2480 (header (plist-get params
:header
))
2481 (link (plist-get params
:link
))
2482 (maxlevel (or (plist-get params
:maxlevel
) 3))
2483 (emph (plist-get params
:emphasize
))
2484 (compact?
(plist-get params
:compact
))
2485 (narrow (or (plist-get params
:narrow
) (and compact?
'40!)))
2486 (level?
(and (not compact?
) (plist-get params
:level
)))
2487 (timestamp (plist-get params
:timestamp
))
2488 (properties (plist-get params
:properties
))
2490 (if (or compact?
(< maxlevel
2)) 1
2491 ;; Deepest headline level is a hard limit for the number
2497 (`(,_
,(and (pred wholenump
) (pred (/= 0))) ,entries
)
2498 (mapcar #'car entries
))))
2501 (or (plist-get params
:tcolumns
) 100)
2502 (if (null levels
) 1 (apply #'max levels
))))))
2503 (indent (or compact?
(plist-get params
:indent
)))
2504 (formula (plist-get params
:formula
))
2505 (case-fold-search t
)
2506 (total-time (apply #'+ (mapcar #'cadr tables
)))
2507 recalc narrow-cut-p
)
2509 (when (and narrow
(integerp narrow
) link
)
2510 ;; We cannot have both integer narrow and link.
2511 (message "Using hard narrowing in clocktable to allow for links")
2512 (setq narrow
(intern (format "%d!" narrow
))))
2515 ((or `nil
(pred integerp
)) nil
) ;nothing to do
2516 ((and (pred symbolp
)
2517 (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow
))))
2518 (setq narrow-cut-p t
)
2519 (setq narrow
(string-to-number (symbol-name narrow
))))
2520 (_ (error "Invalid value %s of :narrow property in clock table" narrow
)))
2522 ;; Now we need to output this table stuff.
2525 ;; Insert the text *before* the actual table.
2526 (insert-before-markers
2528 ;; Format the standard header.
2529 (format "#+CAPTION: %s %s%s\n"
2530 (org-clock--translate "Clock summary at" lang
)
2531 (format-time-string (org-time-stamp-format t t
))
2534 (nth 2 (org-clock-special-range
2536 (plist-get params
:wstart
)
2537 (plist-get params
:mstart
)))))
2538 (format ", for %s." range-text
))
2541 ;; Insert the narrowing line
2542 (when (and narrow
(integerp narrow
) (not narrow-cut-p
))
2543 (insert-before-markers
2544 "|" ;table line starter
2545 (if multifile
"|" "") ;file column, maybe
2546 (if level?
"|" "") ;level column, maybe
2547 (if timestamp
"|" "") ;timestamp column, maybe
2548 (if properties
;properties columns, maybe
2549 (make-string (length properties
) ?|
)
2551 (format "<%d>| |\n" narrow
))) ;headline and time columns
2553 ;; Insert the table header line
2554 (insert-before-markers
2555 "|" ;table line starter
2556 (if multifile
;file column, maybe
2557 (concat (org-clock--translate "File" lang
) "|")
2559 (if level?
;level column, maybe
2560 (concat (org-clock--translate "L" lang
) "|")
2562 (if timestamp
;timestamp column, maybe
2563 (concat (org-clock--translate "Timestamp" lang
) "|")
2565 (if properties
;properties columns, maybe
2566 (concat (mapconcat #'identity properties
"|") "|")
2568 (concat (org-clock--translate "Headline" lang
)"|")
2569 (concat (org-clock--translate "Time" lang
) "|")
2570 (make-string (max 0 (1- time-columns
)) ?|
) ;other time columns
2571 (if (eq formula
'%
) "%|\n" "\n"))
2573 ;; Insert the total time in the table
2574 (insert-before-markers
2576 "|" ;table line starter
2577 (if multifile
(format "| %s " (org-clock--translate "ALL" lang
)) "")
2579 (if level?
"|" "") ;level column, maybe
2580 (if timestamp
"|" "") ;timestamp column, maybe
2581 (make-string (length properties
) ?|
) ;properties columns, maybe
2582 (concat (format org-clock-total-time-cell-format
2583 (org-clock--translate "Total time" lang
))
2585 (format org-clock-total-time-cell-format
2586 (org-duration-from-minutes (or total-time
0))) ;time
2588 (make-string (max 0 (1- time-columns
)) ?|
)
2589 (cond ((not (eq formula
'%
)) "")
2590 ((or (not total-time
) (= total-time
0)) "0.0|")
2594 ;; Now iterate over the tables and insert the data but only if any
2595 ;; time has been collected.
2596 (when (and total-time
(> total-time
0))
2597 (pcase-dolist (`(,file-name
,file-time
,entries
) tables
)
2598 (when (or (and file-time
(> file-time
0))
2599 (not (plist-get params
:fileskip0
)))
2600 (insert-before-markers "|-\n") ;hline at new file
2601 ;; First the file time, if we have multiple files.
2603 ;; Summarize the time collected from this file.
2604 (insert-before-markers
2605 (format (concat "| %s %s | %s%s"
2606 (format org-clock-file-time-cell-format
2607 (org-clock--translate "File time" lang
))
2609 (file-name-nondirectory file-name
)
2610 (if level?
"| " "") ;level column, maybe
2611 (if timestamp
"| " "") ;timestamp column, maybe
2612 (if properties
;properties columns, maybe
2613 (make-string (length properties
) ?|
)
2615 (org-duration-from-minutes file-time
)))) ;time
2617 ;; Get the list of node entries and iterate over it
2618 (when (> maxlevel
0)
2619 (pcase-dolist (`(,level
,headline
,ts
,time
,props
) entries
)
2622 (if (and (string-match
2623 (format "\\`%s\\'" org-bracket-link-regexp
)
2626 (format "[[%s][%s]]"
2627 (match-string 1 headline
)
2628 (org-shorten-string (match-string 3 headline
)
2630 (org-shorten-string headline narrow
))))
2631 (cl-flet ((format-field (f) (format (cond ((not emph
) "%s |")
2632 ((= level
1) "*%s* |")
2633 ((= level
2) "/%s/ |")
2636 (insert-before-markers
2637 "|" ;start the table line
2638 (if multifile
"|" "") ;free space for file name column?
2639 (if level?
(format "%d|" level
) "") ;level, maybe
2640 (if timestamp
(concat ts
"|") "") ;timestamp, maybe
2641 (if properties
;properties columns, maybe
2642 (concat (mapconcat (lambda (p) (or (cdr (assoc p props
)) ""))
2647 (if indent
;indentation
2648 (org-clocktable-indent-string level
)
2650 (format-field headline
)
2651 ;; Empty fields for higher levels.
2652 (make-string (max 0 (1- (min time-columns level
))) ?|
)
2653 (format-field (org-duration-from-minutes time
))
2654 (make-string (max 0 (- time-columns level
)) ?|
)
2656 (format "%.1f |" (* 100 (/ time
(float total-time
))))
2661 ;; Possibly rescue old formula?
2662 ((or (not formula
) (eq formula
'%
))
2663 (let ((contents (org-string-nw-p (plist-get params
:content
))))
2664 (when (and contents
(string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents
))
2666 (insert "\n" (match-string 1 contents
))
2667 (beginning-of-line 0))))
2668 ;; Insert specified formula line.
2670 (insert "\n#+TBLFM: " formula
)
2673 (user-error "Invalid :formula parameter in clocktable")))
2674 ;; Back to beginning, align the table, recalculate if necessary.
2676 (skip-chars-forward "^|")
2678 (when org-hide-emphasis-markers
2679 ;; We need to align a second time.
2683 (org-table-goto-line 3)
2684 (org-table-goto-column (car sort
))
2685 (org-table-sort-lines nil
(cdr sort
))))
2686 (when recalc
(org-table-recalculate 'all
))
2689 (defun org-clocktable-indent-string (level)
2690 "Return indentation string according to LEVEL.
2691 LEVEL is an integer. Indent by two spaces per level above 1."
2693 (concat "\\_" (make-string (* 2 (1- level
)) ?\s
))))
2695 (defun org-clocktable-steps (params)
2696 "Step through the range to make a number of clock tables."
2697 (let* ((p1 (copy-sequence params
))
2698 (ts (plist-get p1
:tstart
))
2699 (te (plist-get p1
:tend
))
2700 (ws (plist-get p1
:wstart
))
2701 (ms (plist-get p1
:mstart
))
2702 (step0 (plist-get p1
:step
))
2703 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
2704 (stepskip0 (plist-get p1
:stepskip0
))
2705 (block (plist-get p1
:block
))
2708 (setq cc
(org-clock-special-range block nil t ws ms
)
2713 ;; If ts is a number, it's an absolute day number from
2715 (pcase-let ((`(,month
,day
,year
) (calendar-gregorian-from-absolute ts
)))
2716 (setq ts
(float-time (encode-time 0 0 0 day month year
)))))
2718 (setq ts
(float-time (apply #'encode-time
(org-parse-time-string ts
))))))
2722 (pcase-let ((`(,month
,day
,year
) (calendar-gregorian-from-absolute te
)))
2723 (setq te
(float-time (encode-time 0 0 0 day month year
)))))
2725 (setq te
(float-time (apply #'encode-time
(org-parse-time-string te
))))))
2727 (if (eq step0
'week
)
2728 (let ((dow (nth 6 (decode-time (seconds-to-time ts
)))))
2730 (- ts
(* 86400 (- dow ws
)))))
2732 (setq p1
(plist-put p1
:header
""))
2733 (setq p1
(plist-put p1
:step nil
))
2734 (setq p1
(plist-put p1
:block nil
))
2736 (or (bolp) (insert "\n"))
2737 (setq p1
(plist-put p1
:tstart
(format-time-string
2738 (org-time-stamp-format nil t
)
2739 (seconds-to-time (max tsb ts
)))))
2740 (cl-incf tsb
(let ((dow (nth 6 (decode-time (seconds-to-time tsb
)))))
2741 (if (or (eq step0
'day
)
2744 (* 86400 (- ws dow
)))))
2745 (setq p1
(plist-put p1
:tend
(format-time-string
2746 (org-time-stamp-format nil t
)
2747 (seconds-to-time (min te tsb
)))))
2748 (insert "\n" (if (eq step0
'day
) "Daily report: "
2749 "Weekly report starting on: ")
2750 (plist-get p1
:tstart
) "\n")
2751 (setq step-time
(org-dblock-write:clocktable p1
))
2752 (re-search-forward "^[ \t]*#\\+END:")
2753 (when (and (equal step-time
0) stepskip0
)
2754 ;; Remove the empty table
2755 (delete-region (point-at-bol)
2757 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2762 (defun org-clock-get-table-data (file params
)
2763 "Get the clocktable data for file FILE, with parameters PARAMS.
2764 FILE is only for identification - this function assumes that
2765 the correct buffer is current, and that the wanted restriction is
2767 The return value will be a list with the file name and the total
2768 file time (in minutes) as 1st and 2nd elements. The third element
2769 of this list will be a list of headline entries. Each entry has the
2770 following structure:
2772 (LEVEL HEADLINE TIMESTAMP TIME PROPERTIES)
2774 LEVEL: The level of the headline, as an integer. This will be
2775 the reduced level, so 1,2,3,... even if only odd levels
2777 HEADLINE: The text of the headline. Depending on PARAMS, this may
2778 already be formatted like a link.
2779 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2780 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2782 TIME: The sum of all time spend in this tree, in minutes. This time
2783 will of cause be restricted to the time block and tags match
2784 specified in PARAMS.
2785 PROPERTIES: The list properties specified in the `:properties' parameter
2786 along with their value, as an alist following the pattern
2788 (let* ((maxlevel (or (plist-get params
:maxlevel
) 3))
2789 (timestamp (plist-get params
:timestamp
))
2790 (ts (plist-get params
:tstart
))
2791 (te (plist-get params
:tend
))
2792 (ws (plist-get params
:wstart
))
2793 (ms (plist-get params
:mstart
))
2794 (block (plist-get params
:block
))
2795 (link (plist-get params
:link
))
2796 (tags (plist-get params
:tags
))
2797 (properties (plist-get params
:properties
))
2798 (inherit-property-p (plist-get params
:inherit-props
))
2799 (matcher (and tags
(cdr (org-make-tags-matcher tags
))))
2802 (setq org-clock-file-total-minutes nil
)
2804 (setq cc
(org-clock-special-range block nil t ws ms
)
2807 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
2808 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
2809 (when (and ts
(listp ts
))
2810 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
2811 (when (and te
(listp te
))
2812 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
2813 ;; Now the times are strings we can parse.
2814 (if ts
(setq ts
(org-matcher-time ts
)))
2815 (if te
(setq te
(org-matcher-time te
)))
2817 (org-clock-sum ts te
2820 (let* ((tags-list (org-get-tags-at))
2821 (org-scanner-tags tags-list
)
2822 (org-trust-scanner-tags t
))
2823 (funcall ,matcher nil tags-list nil
)))))
2824 (goto-char (point-min))
2826 (while (or (and (bobp) (prog1 st
(setq st nil
))
2827 (get-text-property (point) :org-clock-minutes
)
2828 (setq p
(point-min)))
2829 (setq p
(next-single-property-change
2830 (point) :org-clock-minutes
)))
2832 (let ((time (get-text-property p
:org-clock-minutes
)))
2833 (when (and time
(> time
0) (org-at-heading-p))
2834 (let ((level (org-reduced-level (org-current-level))))
2835 (when (<= level maxlevel
)
2836 (let* ((headline (org-get-heading t t t t
))
2838 (if (not link
) headline
2840 (org-make-org-heading-search-string headline
)))
2841 (org-make-link-string
2842 (if (not (buffer-file-name)) search
2843 (format "file:%s::%s" (buffer-file-name) search
))
2844 ;; Prune statistics cookies. Replace
2845 ;; links with their description, or
2846 ;; a plain link if there is none.
2848 (org-link-display-format
2849 (replace-regexp-in-string
2850 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
2854 (cl-some (lambda (p) (org-entry-get (point) p
))
2855 '("SCHEDULED" "DEADLINE" "TIMESTAMP"
2862 (let ((v (org-entry-get
2863 (point) p inherit-property-p
)))
2864 (and v
(cons p v
))))
2866 (push (list level hdl tsp time props
) tbl
)))))))
2867 (list file org-clock-file-total-minutes
(nreverse tbl
)))))
2869 ;; Saving and loading the clock
2871 (defvar org-clock-loaded nil
2872 "Was the clock file loaded?")
2875 (defun org-clock-update-time-maybe ()
2876 "If this is a CLOCK line, update it and return t.
2877 Otherwise, return nil."
2880 (beginning-of-line 1)
2881 (skip-chars-forward " \t")
2882 (when (looking-at org-clock-string
)
2883 (let ((re (concat "[ \t]*" org-clock-string
2884 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2885 "\\([ \t]*=>.*\\)?\\)?"))
2888 ((not (looking-at re
))
2890 ((not (match-end 2))
2891 (when (and (equal (marker-buffer org-clock-marker
) (current-buffer))
2892 (> org-clock-marker
(point))
2893 (<= org-clock-marker
(point-at-eol)))
2894 ;; The clock is running here
2895 (setq org-clock-start-time
2897 (org-parse-time-string (match-string 1))))
2898 (org-clock-update-mode-line)))
2900 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2902 (setq ts
(match-string 1)
2903 te
(match-string 3))
2904 (setq s
(- (float-time
2905 (apply #'encode-time
(org-parse-time-string te nil t
)))
2907 (apply #'encode-time
(org-parse-time-string ts nil t
))))
2910 h
(floor (/ s
3600))
2914 (insert " => " (format (if neg
"-%d:%02d" "%2d:%02d") h m
))
2917 (defun org-clock-save ()
2918 "Persist various clock-related data to disk.
2919 The details of what will be saved are regulated by the variable
2920 `org-clock-persist'."
2921 (when (and org-clock-persist
2922 (or org-clock-loaded
2923 org-clock-has-been-used
2924 (not (file-exists-p org-clock-persist-file
))))
2925 (with-temp-file org-clock-persist-file
2926 (insert (format ";; %s - %s at %s\n"
2927 (file-name-nondirectory org-clock-persist-file
)
2929 (format-time-string (org-time-stamp-format t
))))
2930 ;; Store clock to be resumed.
2931 (when (and (memq org-clock-persist
'(t clock
))
2932 (let ((b (org-base-buffer (org-clocking-buffer))))
2933 (and (buffer-live-p b
)
2934 (buffer-file-name b
)
2935 (or (not org-clock-persist-query-save
)
2936 (y-or-n-p (format "Save current clock (%s) "
2937 org-clock-heading
))))))
2939 (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
2940 (buffer-file-name (org-base-buffer (org-clocking-buffer)))
2941 (marker-position org-clock-marker
))))
2942 ;; Store clocked task history. Tasks are stored reversed to
2943 ;; make reading simpler.
2944 (when (and (memq org-clock-persist
'(t history
))
2947 (format "(setq org-clock-stored-history '(%s))\n"
2950 (let ((b (org-base-buffer (marker-buffer m
))))
2951 (when (and (buffer-live-p b
)
2952 (buffer-file-name b
))
2954 (buffer-file-name b
)
2955 (marker-position m
)))))
2956 (reverse org-clock-history
)
2959 (defun org-clock-load ()
2960 "Load clock-related data from disk, maybe resuming a stored clock."
2961 (when (and org-clock-persist
(not org-clock-loaded
))
2962 (if (not (file-readable-p org-clock-persist-file
))
2963 (message "Not restoring clock data; %S not found" org-clock-persist-file
)
2964 (message "Restoring clock data")
2966 (load-file org-clock-persist-file
)
2967 (setq org-clock-loaded t
)
2968 (pcase-dolist (`(,(and file
(pred file-exists-p
)) .
,position
)
2969 org-clock-stored-history
)
2970 (org-clock-history-push position
(find-file-noselect file
)))
2972 (pcase org-clock-stored-resume-clock
2973 (`(,(and file
(pred file-exists-p
)) .
,position
)
2974 (with-current-buffer (find-file-noselect file
)
2975 (when (or (not org-clock-persist-query-resume
)
2976 (y-or-n-p (format "Resume clock (%s) "
2978 (goto-char position
)
2979 (org-get-heading t t
)))))
2980 (goto-char position
)
2981 (let ((org-clock-in-resume 'auto-restart
)
2982 (org-clock-auto-clock-resolution nil
))
2984 (when (org-invisible-p) (org-show-context))))))
2987 ;; Suggested bindings
2988 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
2990 (provide 'org-clock
)
2993 ;; generated-autoload-file: "org-loaddefs.el"
2997 ;;; org-clock.el ends here