1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the time clocking code for Org-mode
37 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
38 (declare-function notifications-notify
"notifications" (&rest params
))
39 (defvar org-time-stamp-formats
)
41 (defgroup org-clock nil
42 "Options concerning clocking working time in Org-mode."
46 (defcustom org-clock-into-drawer org-log-into-drawer
47 "Should clocking info be wrapped into a drawer?
48 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
49 If necessary, the drawer will be created.
50 When nil, the drawer will not be created, but used when present.
51 When an integer and the number of clocking entries in an item
52 reaches or exceeds this number, a drawer will be created.
53 When a string, it names the drawer to be used.
55 The default for this variable is the value of `org-log-into-drawer',
60 (const :tag
"Always" t
)
61 (const :tag
"Only when drawer exists" nil
)
62 (integer :tag
"When at least N clock entries")
63 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
64 (string :tag
"Into Drawer named...")))
66 (defcustom org-clock-out-when-done t
67 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
68 DONE here means any DONE-like state.
69 A nil value means clock will keep running until stopped explicitly with
70 `C-c C-x C-o', or until the clock is started in a different item.
71 Instead of t, this can also be a list of TODO states that should trigger
76 (const :tag
"Yes, when done" t
)
77 (repeat :tag
"State list"
78 (string :tag
"TODO keyword"))))
80 (defcustom org-clock-out-remove-zero-time-clocks nil
81 "Non-nil means remove the clock line when the resulting time is zero."
85 (defcustom org-clock-in-switch-to-state nil
86 "Set task to a special todo state while clocking it.
87 The value should be the state to which the entry should be
88 switched. If the value is a function, it must take one
89 parameter (the current TODO state of the item) and return the
90 state to switch it to."
94 (const :tag
"Don't force a state" nil
)
96 (symbol :tag
"Function")))
98 (defcustom org-clock-out-switch-to-state nil
99 "Set task to a special todo state after clocking out.
100 The value should be the state to which the entry should be
101 switched. If the value is a function, it must take one
102 parameter (the current TODO state of the item) and return the
103 state to switch it to."
107 (const :tag
"Don't force a state" nil
)
108 (string :tag
"State")
109 (symbol :tag
"Function")))
111 (defcustom org-clock-history-length
5
112 "Number of clock tasks to remember in history."
116 (defcustom org-clock-goto-may-find-recent-task t
117 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
121 (defcustom org-clock-heading-function nil
122 "When non-nil, should be a function to create `org-clock-heading'.
123 This is the string shown in the mode line when a clock is running.
124 The function is called with point at the beginning of the headline."
128 (defcustom org-clock-string-limit
0
129 "Maximum length of clock strings in the modeline. 0 means no limit."
133 (defcustom org-clock-in-resume nil
134 "If non-nil, resume clock when clocking into task with open clock.
135 When clocking into a task with a clock entry which has not been closed,
136 the clock can be resumed from that point."
140 (defcustom org-clock-persist nil
141 "When non-nil, save the running clock when Emacs is closed.
142 The clock is resumed when Emacs restarts.
143 When this is t, both the running clock, and the entire clock
144 history are saved. When this is the symbol `clock', only the
145 running clock is saved.
147 When Emacs restarts with saved clock information, the file containing the
148 running clock as well as all files mentioned in the clock history will
150 All this depends on running `org-clock-persistence-insinuate' in .emacs"
153 (const :tag
"Just the running clock" clock
)
154 (const :tag
"Just the history" history
)
155 (const :tag
"Clock and history" t
)
156 (const :tag
"No persistence" nil
)))
158 (defcustom org-clock-persist-file
(convert-standard-filename
159 "~/.emacs.d/org-clock-save.el")
160 "File to save clock data to."
164 (defcustom org-clock-persist-query-save nil
165 "When non-nil, ask before saving the current clock on exit."
169 (defcustom org-clock-persist-query-resume t
170 "When non-nil, ask before resuming any stored clock during load."
174 (defcustom org-clock-sound nil
175 "Sound that will used for notifications.
179 t standard Emacs beep
180 file name play this sound file. If not possible, fall back to beep"
183 (const :tag
"No sound" nil
)
184 (const :tag
"Standard beep" t
)
185 (file :tag
"Play sound file")))
187 (defcustom org-clock-modeline-total
'auto
188 "Default setting for the time included for the modeline clock.
189 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
192 current Only the time in the current instance of the clock
193 today All time clocked into this task today
194 repeat All time clocked into this task since last repeat
195 all All time ever recorded for this task
196 auto Automatically, either `all', or `repeat' for repeating tasks"
199 (const :tag
"Current clock" current
)
200 (const :tag
"Today's task time" today
)
201 (const :tag
"Since last repeat" repeat
)
202 (const :tag
"All task time" all
)
203 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
205 (defcustom org-task-overrun-text nil
206 "The extra modeline text that should indicate that the clock is overrun.
207 The can be nil to indicate that instead of adding text, the clock time
208 should get a different face (`org-mode-line-clock-overrun').
209 When this is a string, it is prepended to the clock string as an indication,
210 also using the face `org-mode-line-clock-overrun'."
213 (const :tag
"Just mark the time string" nil
)
214 (string :tag
"Text to prepend")))
216 (defcustom org-show-notification-handler nil
217 "Function or program to send notification with.
218 The function or program will be called with the notification
222 (string :tag
"Program")
223 (function :tag
"Function")))
225 (defgroup org-clocktable nil
226 "Options concerning the clock table in Org-mode."
227 :tag
"Org Clock Table"
230 (defcustom org-clocktable-defaults
250 "Default properties for clock tables."
254 (defcustom org-clock-clocktable-formatter
'org-clocktable-write-default
255 "Function to turn clockng data into a table.
256 For more information, see `org-clocktable-write-default'."
257 :group
'org-clocktable
260 (defcustom org-clock-clocktable-default-properties
'(:maxlevel
2 :scope file
)
261 "Default properties for new clocktables.
262 These will be inserted into the BEGIN line, to make it easy for users to
264 :group
'org-clocktable
267 (defcustom org-clock-idle-time nil
268 "When non-nil, resolve open clocks if the user is idle more than X minutes."
271 (const :tag
"Never" nil
)
272 (integer :tag
"After N minutes")))
274 (defcustom org-clock-auto-clock-resolution
'when-no-clock-is-running
275 "When to automatically resolve open clocks found in Org buffers."
278 (const :tag
"Never" nil
)
279 (const :tag
"Always" t
)
280 (const :tag
"When no clock is running" when-no-clock-is-running
)))
282 (defcustom org-clock-report-include-clocking-task nil
283 "When non-nil, include the current clocking task time in clock reports."
287 (defcustom org-clock-resolve-expert nil
288 "Non-nil means do not show the splash buffer with the clock resolver."
292 (defvar org-clock-in-prepare-hook nil
293 "Hook run when preparing the clock.
294 This hook is run before anything happens to the task that
295 you want to clock in. For example, you can use this hook
296 to add an effort property.")
297 (defvar org-clock-in-hook nil
298 "Hook run when starting the clock.")
299 (defvar org-clock-out-hook nil
300 "Hook run when stopping the current clock.")
302 (defvar org-clock-cancel-hook nil
303 "Hook run when cancelling the current clock.")
304 (defvar org-clock-goto-hook nil
305 "Hook run when selecting the currently clocked-in entry.")
306 (defvar org-clock-has-been-used nil
307 "Has the clock been used during the current Emacs session?")
309 ;;; The clock for measuring work time.
311 (defvar org-mode-line-string
"")
312 (put 'org-mode-line-string
'risky-local-variable t
)
314 (defvar org-clock-mode-line-timer nil
)
315 (defvar org-clock-idle-timer nil
)
316 (defvar org-clock-heading
) ; defined in org.el
317 (defvar org-clock-heading-for-remember
"")
318 (defvar org-clock-start-time
"")
320 (defvar org-clock-leftover-time nil
321 "If non-nil, user cancelled a clock; this is when leftover time started.")
323 (defvar org-clock-effort
""
324 "Effort estimate of the currently clocking task.")
326 (defvar org-clock-total-time nil
327 "Holds total time, spent previously on currently clocked item.
328 This does not include the time in the currently running clock.")
330 (defvar org-clock-history nil
331 "List of marker pointing to recent clocked tasks.")
333 (defvar org-clock-default-task
(make-marker)
334 "Marker pointing to the default task that should clock time.
335 The clock can be made to switch to this task after clocking out
336 of a different task.")
338 (defvar org-clock-interrupted-task
(make-marker)
339 "Marker pointing to the task that has been interrupted by the current clock.")
341 (defvar org-clock-mode-line-map
(make-sparse-keymap))
342 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
343 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
345 (defun org-clock-menu ()
349 ["Clock out" org-clock-out t
]
350 ["Change effort estimate" org-clock-modify-effort-estimate t
]
351 ["Go to clock entry" org-clock-goto t
]
352 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
354 (defun org-clock-history-push (&optional pos buffer
)
355 "Push a marker to the clock history."
356 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
357 (let ((m (move-marker (make-marker)
358 (or pos
(point)) (org-base-buffer
359 (or buffer
(current-buffer)))))
361 (while (setq n
(member m org-clock-history
))
362 (move-marker (car n
) nil
))
363 (setq org-clock-history
365 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
367 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
368 (setq org-clock-history
370 (nthcdr (- l org-clock-history-length -
1)
371 (nreverse org-clock-history
)))))
372 (push m org-clock-history
)))
374 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
375 "Save relative positions of markers in region."
376 (org-check-and-save-marker org-clock-marker beg end
)
377 (org-check-and-save-marker org-clock-hd-marker beg end
)
378 (org-check-and-save-marker org-clock-default-task beg end
)
379 (org-check-and-save-marker org-clock-interrupted-task beg end
)
380 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
383 (defun org-clocking-buffer ()
384 "Return the clocking buffer if we are currently clocking a task or nil."
385 (marker-buffer org-clock-marker
))
387 (defun org-clocking-p ()
388 "Return t when clocking a task."
389 (not (equal (org-clocking-buffer) nil
)))
391 (defun org-clock-select-task (&optional prompt
)
392 "Select a task that recently was associated with clocking."
394 (let (sel-list rpl
(i 0) s
)
395 (save-window-excursion
396 (org-switch-to-buffer-other-window
397 (get-buffer-create "*Clock Task Select*"))
399 (when (marker-buffer org-clock-default-task
)
400 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
401 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
403 (when (marker-buffer org-clock-interrupted-task
)
404 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
405 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
407 (when (org-clocking-p)
408 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
409 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
411 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
414 (when (marker-buffer m
)
416 s
(org-clock-insert-selection-line
420 (if (fboundp 'int-to-char
) (setf (car s
) (int-to-char (car s
))))
423 (org-fit-window-to-buffer)
424 (message (or prompt
"Select task for clocking:"))
425 (setq rpl
(read-char-exclusive))
429 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
430 (t (error "Invalid task choice %c" rpl
))))))
432 (defun org-clock-insert-selection-line (i marker
)
433 "Insert a line for the clock selection menu.
434 And return a cons cell with the selection character integer and the marker
436 (when (marker-buffer marker
)
437 (let (file cat task heading prefix
)
438 (with-current-buffer (org-base-buffer (marker-buffer marker
))
444 (setq file
(buffer-file-name (marker-buffer marker
))
445 cat
(or (org-get-category)
446 (progn (org-refresh-category-properties)
448 heading
(org-get-heading 'notags
)
449 prefix
(save-excursion
450 (org-back-to-heading t
)
454 (org-fontify-like-in-org-mode
455 (concat prefix heading
)
457 (length prefix
)))))))
459 (insert (format "[%c] %-15s %s\n" i cat task
))
462 (defvar org-task-overrun nil
463 "Internal flag indicating if the clock has overrun the planned time.")
464 (defvar org-clock-update-period
60
465 "Number of seconds between mode line clock string updates.")
467 (defun org-clock-get-clock-string ()
468 "Form a clock-string, that will be shown in the mode line.
469 If an effort estimate was defined for the current item, use
470 01:30/01:50 format (clocked/estimated).
471 If not, show simply the clocked time like 01:50."
472 (let* ((clocked-time (org-clock-get-clocked-time))
473 (h (floor clocked-time
60))
474 (m (- clocked-time
(* 60 h
))))
476 (let* ((effort-in-minutes
477 (org-hh:mm-string-to-minutes org-clock-effort
))
478 (effort-h (floor effort-in-minutes
60))
479 (effort-m (- effort-in-minutes
(* effort-h
60)))
482 (format org-time-clocksum-format h m
)
483 'face
(if (and org-task-overrun
(not org-task-overrun-text
))
484 'org-mode-line-clock-overrun
'org-mode-line-clock
)))
485 (effort-str (format org-time-clocksum-format effort-h effort-m
))
486 (clockstr (org-propertize
487 (concat "[%s/" effort-str
488 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading
) ")")
489 'face
'org-mode-line-clock
)))
490 (format clockstr work-done-str
))
491 (org-propertize (format
492 (concat "[" org-time-clocksum-format
" (%s)]")
493 h m org-clock-heading
)
494 'face
'org-mode-line-clock
))))
496 (defun org-clock-update-mode-line ()
498 (org-clock-notify-once-if-expired)
499 (setq org-task-overrun nil
))
500 (setq org-mode-line-string
502 (let ((clock-string (org-clock-get-clock-string))
503 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
504 (if (and (> org-clock-string-limit
0)
505 (> (length clock-string
) org-clock-string-limit
))
507 (substring clock-string
0 org-clock-string-limit
)
508 'help-echo
(concat help-text
": " org-clock-heading
))
509 (org-propertize clock-string
'help-echo help-text
)))
510 'local-map org-clock-mode-line-map
511 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)
513 (if (and org-task-overrun org-task-overrun-text
)
514 (setq org-mode-line-string
515 (concat (org-propertize
516 org-task-overrun-text
517 'face
'org-mode-line-clock-overrun
) org-mode-line-string
)))
518 (force-mode-line-update))
520 (defun org-clock-get-clocked-time ()
521 "Get the clocked time for the current item in minutes.
522 The time returned includes the time spent on this task in
523 previous clocking intervals."
524 (let ((currently-clocked-time
525 (floor (- (org-float-time)
526 (org-float-time org-clock-start-time
)) 60)))
527 (+ currently-clocked-time
(or org-clock-total-time
0))))
529 (defun org-clock-modify-effort-estimate (&optional value
)
530 "Add to or set the effort estimate of the item currently being clocked.
531 VALUE can be a number of minutes, or a string with format hh:mm or mm.
532 When the string starts with a + or a - sign, the current value of the effort
533 property will be changed by that amount.
534 This will update the \"Effort\" property of currently clocked item, and
537 (when (org-clock-is-active)
538 (let ((current org-clock-effort
) sign
)
540 ;; Prompt user for a value or a change
543 (format "Set effort (hh:mm or mm%s): "
545 (format ", prefix + to add to %s" org-clock-effort
)
547 (when (stringp value
)
548 ;; A string. See if it is a delta
549 (setq sign
(string-to-char value
))
550 (if (member sign
'(?- ?
+))
551 (setq current
(org-hh:mm-string-to-minutes current
)
552 value
(substring value
1))
554 (setq value
(org-hh:mm-string-to-minutes value
))
556 (setq value
(- current value
))
557 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
558 (setq value
(max 0 value
)
559 org-clock-effort
(org-minutes-to-hh:mm-string value
))
560 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
561 (org-clock-update-mode-line)
562 (message "Effort is now %s" org-clock-effort
))))
564 (defvar org-clock-notification-was-shown nil
565 "Shows if we have shown notification already.")
567 (defun org-clock-notify-once-if-expired ()
568 "Show notification if we spent more time than we estimated before.
569 Notification is shown only once."
570 (when (org-clocking-p)
571 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort
))
572 (clocked-time (org-clock-get-clocked-time)))
573 (if (setq org-task-overrun
574 (if (or (null effort-in-minutes
) (zerop effort-in-minutes
))
576 (>= clocked-time effort-in-minutes
)))
577 (unless org-clock-notification-was-shown
578 (setq org-clock-notification-was-shown t
)
580 (format "Task '%s' should be finished by now. (%s)"
581 org-clock-heading org-clock-effort
) t
))
582 (setq org-clock-notification-was-shown nil
)))))
584 (defun org-notify (notification &optional play-sound
)
585 "Send a NOTIFICATION and maybe PLAY-SOUND."
586 (org-show-notification notification
)
587 (if play-sound
(org-clock-play-sound)))
589 (defun org-show-notification (notification)
591 Use `org-show-notification-handler' if defined,
592 use libnotify if available, or fall back on a message."
593 (cond ((functionp org-show-notification-handler
)
594 (funcall org-show-notification-handler notification
))
595 ((stringp org-show-notification-handler
)
596 (start-process "emacs-timer-notification" nil
597 org-show-notification-handler notification
))
598 ((featurep 'notifications
)
599 (require 'notifications
)
600 (notifications-notify
601 :title
"Org-mode message"
603 ;; FIXME how to link to the Org icon?
604 ;; :app-icon "~/.emacs.d/icons/mail.png"
606 ((org-program-exists "notify-send")
607 (start-process "emacs-timer-notification" nil
608 "notify-send" notification
))
609 ;; Maybe the handler will send a message, so only use message as
610 ;; a fall back option
611 (t (message "%s" notification
))))
613 (defun org-clock-play-sound ()
614 "Play sound as configured by `org-clock-sound'.
615 Use alsa's aplay tool if available."
617 ((not org-clock-sound
))
618 ((eq org-clock-sound t
) (beep t
) (beep t
))
619 ((stringp org-clock-sound
)
620 (let ((file (expand-file-name org-clock-sound
)))
621 (if (file-exists-p file
)
622 (if (org-program-exists "aplay")
623 (start-process "org-clock-play-notification" nil
626 (play-sound-file file
)
627 (error (beep t
) (beep t
)))))))))
629 (defun org-program-exists (program-name)
630 "Checks whenever we can locate program and launch it."
631 (if (eq system-type
'gnu
/linux
)
632 (= 0 (call-process "which" nil nil nil program-name
))))
634 (defvar org-clock-mode-line-entry nil
635 "Information for the modeline about the running clock.")
637 (defun org-find-open-clocks (file)
638 "Search through the given file and find all open clocks."
639 (let ((buf (or (get-file-buffer file
)
640 (find-file-noselect file
)))
642 (with-current-buffer buf
644 (goto-char (point-min))
645 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t
)
646 (push (cons (copy-marker (match-end 1) t
)
647 (org-time-string-to-time (match-string 1))) clocks
))))
650 (defsubst org-is-active-clock
(clock)
651 "Return t if CLOCK is the currently active clock."
652 (and (org-clock-is-active)
653 (= org-clock-marker
(car clock
))))
655 (defmacro org-with-clock-position
(clock &rest forms
)
656 "Evaluate FORMS with CLOCK as the current active clock."
657 `(with-current-buffer (marker-buffer (car ,clock
))
661 (goto-char (car ,clock
))
665 (put 'org-with-clock-position
'lisp-indent-function
1)
667 (defmacro org-with-clock
(clock &rest forms
)
668 "Evaluate FORMS with CLOCK as the current active clock.
669 This macro also protects the current active clock from being altered."
670 `(org-with-clock-position ,clock
671 (let ((org-clock-start-time (cdr ,clock
))
672 (org-clock-total-time)
675 (org-clock-marker (car ,clock
))
676 (org-clock-hd-marker (save-excursion
677 (outline-back-to-heading t
)
681 (put 'org-with-clock
'lisp-indent-function
1)
683 (defsubst org-clock-clock-in
(clock &optional resume start-time
)
684 "Clock in to the clock located by CLOCK.
685 If necessary, clock-out of the currently active clock."
686 (org-with-clock-position clock
687 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
688 (org-clock-in nil start-time
))))
690 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
691 "Clock out of the clock located by CLOCK."
692 (let ((temp (copy-marker (car clock
)
693 (marker-insertion-type (car clock
)))))
694 (if (org-is-active-clock clock
)
695 (org-clock-out fail-quietly at-time
)
696 (org-with-clock clock
697 (org-clock-out fail-quietly at-time
)))
698 (setcar clock temp
)))
700 (defsubst org-clock-clock-cancel
(clock)
701 "Cancel the clock located by CLOCK."
702 (let ((temp (copy-marker (car clock
)
703 (marker-insertion-type (car clock
)))))
704 (if (org-is-active-clock clock
)
706 (org-with-clock clock
708 (setcar clock temp
)))
710 (defvar org-clock-clocking-in nil
)
711 (defvar org-clock-resolving-clocks nil
)
712 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
714 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
715 &optional close-p restart-p fail-quietly
)
716 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
717 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
718 (let ((org-clock-resolving-clocks t
))
721 (org-clock-clock-cancel clock
)
722 (if (and restart-p
(not org-clock-clocking-in
))
723 (org-clock-clock-in clock
)))
725 ((eq resolve-to
'now
)
727 (error "RESTART-P is not valid here"))
728 (if (or close-p org-clock-clocking-in
)
729 (org-clock-clock-out clock fail-quietly
)
730 (unless (org-is-active-clock clock
)
731 (org-clock-clock-in clock t
))))
733 ((not (time-less-p resolve-to
(current-time)))
734 (error "RESOLVE-TO must refer to a time in the past"))
738 (error "RESTART-P is not valid here"))
739 (org-clock-clock-out clock fail-quietly
(or clock-out-time
741 (unless org-clock-clocking-in
743 (setq org-clock-leftover-time
(and (null clock-out-time
)
745 (org-clock-clock-in clock nil
(and clock-out-time
748 (defun org-clock-jump-to-current-clock (&optional effective-clock
)
750 (let ((clock (or effective-clock
(cons org-clock-marker
751 org-clock-start-time
))))
752 (unless (marker-buffer (car clock
))
753 (error "No clock is currently running"))
754 (org-with-clock clock
(org-clock-goto))
755 (with-current-buffer (marker-buffer (car clock
))
756 (goto-char (car clock
))
757 (if org-clock-into-drawer
759 (if (stringp org-clock-into-drawer
)
760 (concat ":" org-clock-into-drawer
":")
765 (outline-back-to-heading t
)
766 (search-forward logbook
)
767 (goto-char (match-beginning 0)))
769 (outline-back-to-heading t
)
770 (search-forward logbook
)
771 (search-forward ":END:")
772 (goto-char (match-end 0)))
775 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
776 "Resolve an open org-mode clock.
777 An open clock was found, with `dangling' possibly being non-nil.
778 If this function was invoked with a prefix argument, non-dangling
779 open clocks are ignored. The given clock requires some sort of
780 user intervention to resolve it, either because a clock was left
781 dangling or due to an idle timeout. The clock resolution can
784 (a) deleted, the user doesn't care about the clock
785 (b) restarted from the current time (if no other clock is open)
786 (c) closed, giving the clock X minutes
787 (d) closed and then restarted
788 (e) resumed, as if the user had never left
790 The format of clock is (CONS MARKER START-TIME), where MARKER
791 identifies the buffer and position the clock is open at (and
792 thus, the heading it's under), and START-TIME is when the clock
796 (save-window-excursion
798 (unless org-clock-resolving-clocks-due-to-idleness
799 (org-clock-jump-to-current-clock clock
))
800 (unless org-clock-resolve-expert
801 (with-output-to-temp-buffer "*Org Clock*"
802 (princ "Select a Clock Resolution Command:
804 i/q/C-g Ignore this question; the same as keeping all the idle time.
806 k/K Keep X minutes of the idle time (default is all). If this
807 amount is less than the default, you will be clocked out
808 that many minutes after the time that idling began, and then
809 clocked back in at the present time.
810 g/G Indicate that you \"got back\" X minutes ago. This is quite
811 different from 'k': it clocks you out from the beginning of
812 the idle period and clock you back in X minutes ago.
813 s/S Subtract the idle time from the current clock. This is the
814 same as keeping 0 minutes.
815 C Cancel the open timer altogether. It will be as though you
817 j/J Jump to the current clock, to make manual adjustments.
819 For all these options, using uppercase makes your final state
820 to be CLOCKED OUT.")))
821 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
823 (when (featurep 'xemacs
)
824 (message (concat (funcall prompt-fn clock
)
826 (setq char-pressed
(read-char-exclusive)))
827 (while (or (null char-pressed
)
828 (and (not (memq char-pressed
829 '(?k ?K ?g ?G ?s ?S ?C
833 (read-char (concat (funcall prompt-fn clock
)
836 (and (not (memq char-pressed
'(?i ?q
))) char-pressed
)))))
838 (floor (/ (org-float-time
839 (time-subtract (current-time) last-valid
)) 60)))
841 (and (memq ch
'(?k ?K
))
842 (read-number "Keep how many minutes? " default
)))
844 (and (memq ch
'(?g ?G
))
845 (read-number "Got back how many minutes ago? " default
)))
846 (subtractp (memq ch
'(?s ?S
)))
847 (barely-started-p (< (- (org-float-time last-valid
)
848 (org-float-time (cdr clock
))) 45))
849 (start-over (and subtractp barely-started-p
)))
853 (org-clock-resolve-clock clock
'now nil t nil fail-quietly
))
854 (org-clock-jump-to-current-clock clock
))
856 (not (memq ch
'(?k ?K ?g ?G ?s ?S ?C
))))
859 (org-clock-resolve-clock
862 ;; If the time on the clock was less than a minute before
863 ;; the user went away, and they've ask to subtract all the
868 (and gotback
(= gotback
0)))
870 ((or (and keep
(= keep default
))
871 (and gotback
(= gotback default
)))
874 (time-add last-valid
(seconds-to-time (* 60 keep
))))
876 (time-subtract (current-time)
877 (seconds-to-time (* 60 gotback
))))
879 (error "Unexpected, please report this as a bug")))
880 (and gotback last-valid
)
881 (memq ch
'(?K ?G ?S
))
883 (not (memq ch
'(?K ?G ?S ?C
))))
886 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid
)
887 "Resolve all currently open org-mode clocks.
888 If `only-dangling-p' is non-nil, only ask to resolve dangling
889 \(i.e., not currently open and valid) clocks."
891 (unless org-clock-resolving-clocks
892 (let ((org-clock-resolving-clocks t
))
893 (dolist (file (org-files-list))
894 (let ((clocks (org-find-open-clocks file
)))
895 (dolist (clock clocks
)
896 (let ((dangling (or (not (org-clock-is-active))
897 (/= (car clock
) org-clock-marker
))))
898 (if (or (not only-dangling-p
) dangling
)
905 "Dangling clock started %d mins ago"
907 (/ (- (org-float-time (current-time))
908 (org-float-time (cdr clock
))) 60))))))
910 (cdr clock
)))))))))))
912 (defun org-emacs-idle-seconds ()
913 "Return the current Emacs idle time in seconds, or nil if not idle."
914 (let ((idle-time (current-idle-time)))
916 (org-float-time idle-time
)
919 (defun org-mac-idle-seconds ()
920 "Return the current Mac idle time in seconds."
921 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
923 (defun org-x11-idle-seconds ()
924 "Return the current X11 idle time in seconds."
925 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
927 (defun org-user-idle-seconds ()
928 "Return the number of seconds the user has been idle for.
929 This routine returns a floating point number."
931 ((eq system-type
'darwin
)
932 (org-mac-idle-seconds))
933 ((eq window-system
'x
)
934 (org-x11-idle-seconds))
936 (org-emacs-idle-seconds))))
938 (defvar org-clock-user-idle-seconds
)
940 (defun org-resolve-clocks-if-idle ()
941 "Resolve all currently open org-mode clocks.
942 This is performed after `org-clock-idle-time' minutes, to check
943 if the user really wants to stay clocked in after being idle for
945 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
947 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
948 (org-clock-user-idle-start
949 (time-subtract (current-time)
950 (seconds-to-time org-clock-user-idle-seconds
)))
951 (org-clock-resolving-clocks-due-to-idleness t
))
952 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
954 (cons org-clock-marker
955 org-clock-start-time
)
958 (format "Clocked in & idle for %.1f mins"
960 (time-subtract (current-time)
961 org-clock-user-idle-start
))
963 org-clock-user-idle-start
)))))
965 (defun org-clock-in (&optional select start-time
)
966 "Start the clock on the current item.
967 If necessary, clock-out of the currently active clock.
968 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
969 recently clocked tasks to
970 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
971 clock into the current task and mark
972 is as the default task, a special task that will always be offered in
973 the clocking selection, associated with the letter `d'."
975 (setq org-clock-notification-was-shown nil
)
977 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
979 ts selected-task target-pos
(msg-extra "")
980 (leftover (and (not org-clock-resolving-clocks
)
981 org-clock-leftover-time
)))
982 (when (and org-clock-auto-clock-resolution
983 (or (not interrupting
)
984 (eq t org-clock-auto-clock-resolution
))
985 (not org-clock-clocking-in
)
986 (not org-clock-resolving-clocks
))
987 (setq org-clock-leftover-time nil
)
988 (let ((org-clock-clocking-in t
))
989 (org-resolve-clocks))) ; check if any clocks are dangling
990 (when (equal select
'(4))
991 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
993 (setq selected-task
(copy-marker selected-task
))
996 ;; We are interrupting the clocking of a different task.
997 ;; Save a marker to this task, so that we can go back.
998 ;; First check if we are trying to clock into the same task!
999 (when (save-excursion
1000 (unless selected-task
1001 (org-back-to-heading t
))
1002 (and (equal (marker-buffer org-clock-hd-marker
)
1004 (marker-buffer selected-task
)
1006 (= (marker-position org-clock-hd-marker
)
1008 (marker-position selected-task
)
1010 (message "Clock continues in \"%s\"" org-clock-heading
)
1012 (move-marker org-clock-interrupted-task
1013 (marker-position org-clock-marker
)
1014 (marker-buffer org-clock-marker
))
1015 (let ((org-clock-clocking-in t
))
1018 (when (equal select
'(16))
1019 ;; Mark as default clocking task
1020 (org-clock-mark-default-task))
1022 ;; Clock in at which position?
1024 (if (and (eobp) (not (org-on-heading-p)))
1027 (run-hooks 'org-clock-in-prepare-hook
)
1029 (when (and selected-task
(marker-buffer selected-task
))
1030 ;; There is a selected task, move to the correct buffer
1031 ;; and set the new target position.
1032 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
1033 (setq target-pos
(marker-position selected-task
))
1034 (move-marker selected-task nil
))
1038 (goto-char target-pos
)
1039 (org-back-to-heading t
)
1040 (or interrupting
(move-marker org-clock-interrupted-task nil
))
1041 (org-clock-history-push)
1042 (org-clock-set-current)
1043 (cond ((functionp org-clock-in-switch-to-state
)
1044 (looking-at org-complex-heading-regexp
)
1045 (let ((newstate (funcall org-clock-in-switch-to-state
1047 (if newstate
(org-todo newstate
))))
1048 ((and org-clock-in-switch-to-state
1049 (not (looking-at (concat outline-regexp
"[ \t]*"
1050 org-clock-in-switch-to-state
1052 (org-todo org-clock-in-switch-to-state
)))
1053 (setq org-clock-heading-for-remember
1054 (and (looking-at org-complex-heading-regexp
)
1056 (org-trim (buffer-substring (match-end 1)
1058 (setq org-clock-heading
1059 (cond ((and org-clock-heading-function
1060 (functionp org-clock-heading-function
))
1061 (funcall org-clock-heading-function
))
1062 ((looking-at org-complex-heading-regexp
)
1063 (replace-regexp-in-string
1064 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1067 (setq org-clock-heading
(org-propertize org-clock-heading
1069 (org-clock-find-position org-clock-in-resume
)
1071 ((and org-clock-in-resume
1073 (concat "^[ \t]* " org-clock-string
1074 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1075 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1076 (message "Matched %s" (match-string 1))
1077 (setq ts
(concat "[" (match-string 1) "]"))
1078 (goto-char (match-end 1))
1079 (setq org-clock-start-time
1081 (org-parse-time-string (match-string 1))))
1082 (setq org-clock-effort
(org-get-effort))
1083 (setq org-clock-total-time
(org-clock-sum-current-item
1084 (org-clock-get-sum-start))))
1085 ((eq org-clock-in-resume
'auto-restart
)
1086 ;; called from org-clock-load during startup,
1087 ;; do not interrupt, but warn!
1088 (message "Cannot restart clock because task does not contain unfinished clock")
1093 (insert-before-markers "\n")
1095 (org-indent-line-function)
1096 (when (and (save-excursion
1099 (beginning-of-line 1)
1100 (org-indent-line-to (- (org-get-indentation) 2)))
1101 (insert org-clock-string
" ")
1102 (setq org-clock-effort
(org-get-effort))
1103 (setq org-clock-total-time
(org-clock-sum-current-item
1104 (org-clock-get-sum-start)))
1105 (setq org-clock-start-time
1109 "You stopped another clock %d mins ago; start this one from then? "
1110 (/ (- (org-float-time (current-time))
1111 (org-float-time leftover
)) 60)))
1115 (setq ts
(org-insert-time-stamp org-clock-start-time
1116 'with-hm
'inactive
))))
1117 (move-marker org-clock-marker
(point) (buffer-base-buffer))
1118 (move-marker org-clock-hd-marker
1119 (save-excursion (org-back-to-heading t
) (point))
1120 (buffer-base-buffer))
1121 (setq org-clock-has-been-used t
)
1122 (or global-mode-string
(setq global-mode-string
'("")))
1123 (or (memq 'org-mode-line-string global-mode-string
)
1124 (setq global-mode-string
1125 (append global-mode-string
'(org-mode-line-string))))
1126 (org-clock-update-mode-line)
1127 (when org-clock-mode-line-timer
1128 (cancel-timer org-clock-mode-line-timer
)
1129 (setq org-clock-mode-line-timer nil
))
1130 (setq org-clock-mode-line-timer
1131 (run-with-timer org-clock-update-period
1132 org-clock-update-period
1133 'org-clock-update-mode-line
))
1134 (when org-clock-idle-timer
1135 (cancel-timer org-clock-idle-timer
)
1136 (setq org-clock-idle-timer nil
))
1137 (setq org-clock-idle-timer
1138 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
1139 (message "Clock starts at %s - %s" ts msg-extra
)
1140 (run-hooks 'org-clock-in-hook
)))))))
1142 (defvar org-clock-current-task nil
1143 "Task currently clocked in.")
1144 (defun org-clock-set-current ()
1145 "Set `org-clock-current-task' to the task currently clocked in."
1146 (setq org-clock-current-task
(nth 4 (org-heading-components))))
1148 (defun org-clock-delete-current ()
1149 "Reset `org-clock-current-task' to nil."
1150 (setq org-clock-current-task nil
))
1152 (defun org-clock-mark-default-task ()
1153 "Mark current task as default task."
1156 (org-back-to-heading t
)
1157 (move-marker org-clock-default-task
(point))))
1160 (defun org-clock-get-sum-start ()
1161 "Return the time from which clock times should be counted.
1162 This is for the currently running clock as it is displayed
1163 in the mode line. This function looks at the properties
1164 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1165 corresponding variable `org-clock-modeline-total' and then
1166 decides which time to use."
1167 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
1168 (symbol-name org-clock-modeline-total
)))
1169 (lr (org-entry-get nil
"LAST_REPEAT")))
1171 ((equal cmt
"current")
1172 (setq msg-extra
"showing time in current clock instance")
1174 ((equal cmt
"today")
1175 (setq msg-extra
"showing today's task time.")
1176 (let* ((dt (decode-time (current-time))))
1177 (setq dt
(append (list 0 0 0) (nthcdr 3 dt
)))
1178 (if org-extend-today-until
1179 (setf (nth 2 dt
) org-extend-today-until
))
1180 (apply 'encode-time dt
)))
1181 ((or (equal cmt
"all")
1182 (and (or (not cmt
) (equal cmt
"auto"))
1184 (setq msg-extra
"showing entire task time.")
1186 ((or (equal cmt
"repeat")
1187 (and (or (not cmt
) (equal cmt
"auto"))
1189 (setq msg-extra
"showing task time since last repeat.")
1192 (org-time-string-to-time lr
)))
1195 (defun org-clock-find-position (find-unclosed)
1196 "Find the location where the next clock line should be inserted.
1197 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1198 line and position cursor in that line."
1199 (org-back-to-heading t
)
1201 (let ((beg (save-excursion
1202 (beginning-of-line 2)
1203 (or (bolp) (newline))
1205 (end (progn (outline-next-heading) (point)))
1206 (re (concat "^[ \t]*" org-clock-string
))
1208 (drawer (if (stringp org-clock-into-drawer
)
1209 org-clock-into-drawer
"LOGBOOK"))
1210 first last ind-last
)
1212 (when (and find-unclosed
1214 (concat "^[ \t]* " org-clock-string
1215 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1216 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1218 (beginning-of-line 1)
1220 (when (eobp) (newline) (setq end
(max (point) end
)))
1221 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
1222 ;; we seem to have a CLOCK drawer, so go there.
1223 (beginning-of-line 2)
1224 (or org-log-states-order-reversed
1225 (and (re-search-forward org-property-end-re nil t
)
1226 (goto-char (match-beginning 0))))
1228 ;; Lets count the CLOCK lines
1230 (while (re-search-forward re end t
)
1231 (setq first
(or first
(match-beginning 0))
1232 last
(match-beginning 0)
1234 (when (and (integerp org-clock-into-drawer
)
1236 (>= (1+ cnt
) org-clock-into-drawer
))
1237 ;; Wrap current entries into a new drawer
1239 (setq ind-last
(org-get-indentation))
1240 (beginning-of-line 2)
1241 (if (and (>= (org-get-indentation) ind-last
)
1245 (beginning-of-line 0)
1246 (org-indent-line-to ind-last
)
1248 (insert ":" drawer
":\n")
1249 (beginning-of-line 0)
1250 (org-indent-line-function)
1252 (beginning-of-line 2)
1253 (or org-log-states-order-reversed
1254 (and (re-search-forward org-property-end-re nil t
)
1255 (goto-char (match-beginning 0))))
1259 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1260 (not (equal (match-string 1) org-clock-string
)))
1261 ;; Planning info, skip to after it
1262 (beginning-of-line 2)
1263 (or (bolp) (newline)))
1264 (when (or (eq org-clock-into-drawer t
)
1265 (stringp org-clock-into-drawer
)
1266 (and (integerp org-clock-into-drawer
)
1267 (< org-clock-into-drawer
2)))
1268 (insert ":" drawer
":\n:END:\n")
1269 (beginning-of-line -
1)
1270 (org-indent-line-function)
1272 (beginning-of-line 2)
1273 (org-indent-line-function)
1275 (or org-log-states-order-reversed
1276 (and (re-search-forward org-property-end-re nil t
)
1277 (goto-char (match-beginning 0))))))))
1279 (defun org-clock-out (&optional fail-quietly at-time
)
1280 "Stop the currently running clock.
1281 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1284 (when (not (org-clocking-p))
1285 (setq global-mode-string
1286 (delq 'org-mode-line-string global-mode-string
))
1287 (force-mode-line-update)
1288 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
1289 (let (ts te s h m remove
)
1290 (save-excursion ; Do not replace this with `with-current-buffer'.
1291 (with-no-warnings (set-buffer (org-clocking-buffer)))
1294 (goto-char org-clock-marker
)
1295 (beginning-of-line 1)
1296 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1297 (equal (match-string 1) org-clock-string
))
1298 (setq ts
(match-string 2))
1299 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1300 (goto-char (match-end 0))
1301 (delete-region (point) (point-at-eol))
1303 (setq te
(org-insert-time-stamp (or at-time
(current-time))
1304 'with-hm
'inactive
))
1305 (setq s
(- (org-float-time (apply 'encode-time
(org-parse-time-string te
)))
1306 (org-float-time (apply 'encode-time
(org-parse-time-string ts
))))
1307 h
(floor (/ s
3600))
1311 (insert " => " (format "%2d:%02d" h m
))
1312 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
1314 (beginning-of-line 1)
1315 (delete-region (point) (point-at-eol))
1316 (and (looking-at "\n") (> (point-max) (1+ (point)))
1318 (move-marker org-clock-marker nil
)
1319 (move-marker org-clock-hd-marker nil
)
1320 (when org-log-note-clock-out
1321 (org-add-log-setup 'clock-out nil nil nil nil
1322 (concat "# Task: " (org-get-heading t
) "\n\n")))
1323 (when org-clock-mode-line-timer
1324 (cancel-timer org-clock-mode-line-timer
)
1325 (setq org-clock-mode-line-timer nil
))
1326 (when org-clock-idle-timer
1327 (cancel-timer org-clock-idle-timer
)
1328 (setq org-clock-idle-timer nil
))
1329 (setq global-mode-string
1330 (delq 'org-mode-line-string global-mode-string
))
1331 (when org-clock-out-switch-to-state
1333 (org-back-to-heading t
)
1334 (let ((org-inhibit-logging t
)
1335 (org-clock-out-when-done nil
))
1337 ((functionp org-clock-out-switch-to-state
)
1338 (looking-at org-complex-heading-regexp
)
1339 (let ((newstate (funcall org-clock-out-switch-to-state
1341 (if newstate
(org-todo newstate
))))
1342 ((and org-clock-out-switch-to-state
1343 (not (looking-at (concat outline-regexp
"[ \t]*"
1344 org-clock-out-switch-to-state
1346 (org-todo org-clock-out-switch-to-state
))))))
1347 (force-mode-line-update)
1348 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
1349 (if remove
" => LINE REMOVED" ""))
1350 (run-hooks 'org-clock-out-hook
)
1351 (org-clock-delete-current))))))
1353 (defun org-clock-cancel ()
1354 "Cancel the running clock by removing the start timestamp."
1356 (when (not (org-clocking-p))
1357 (setq global-mode-string
1358 (delq 'org-mode-line-string global-mode-string
))
1359 (force-mode-line-update)
1360 (error "No active clock"))
1361 (save-excursion ; Do not replace this with `with-current-buffer'.
1362 (with-no-warnings (set-buffer (org-clocking-buffer)))
1363 (goto-char org-clock-marker
)
1364 (delete-region (1- (point-at-bol)) (point-at-eol))
1365 ;; Just in case, remove any empty LOGBOOK left over
1366 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1367 (move-marker org-clock-marker nil
)
1368 (move-marker org-clock-hd-marker nil
)
1369 (setq global-mode-string
1370 (delq 'org-mode-line-string global-mode-string
))
1371 (force-mode-line-update)
1372 (message "Clock canceled")
1373 (run-hooks 'org-clock-cancel-hook
))
1375 (defun org-clock-goto (&optional select
)
1376 "Go to the currently clocked-in entry, or to the most recently clocked one.
1377 With prefix arg SELECT, offer recently clocked tasks for selection."
1382 (or (org-clock-select-task "Select task to go to: ")
1383 (error "No task selected")))
1384 ((org-clocking-p) org-clock-marker
)
1385 ((and org-clock-goto-may-find-recent-task
1386 (car org-clock-history
)
1387 (marker-buffer (car org-clock-history
)))
1389 (car org-clock-history
))
1390 (t (error "No active or recent clock task")))))
1391 (switch-to-buffer (marker-buffer m
))
1392 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1395 (org-back-to-heading t
)
1396 (org-cycle-hide-drawers 'children
)
1400 (message "No running clock, this is the most recently clocked task"))
1401 (run-hooks 'org-clock-goto-hook
)))
1403 (defvar org-clock-file-total-minutes nil
1404 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1405 (make-variable-buffer-local 'org-clock-file-total-minutes
)
1407 (defun org-clock-sum (&optional tstart tend headline-filter
)
1408 "Sum the times for each subtree.
1409 Puts the resulting times in minutes as a text property on each headline.
1410 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1411 zero-arg function that, if specified, is called for each headline in the time
1412 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1413 nil are excluded from the clock summation."
1415 (let* ((bmp (buffer-modified-p))
1416 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1418 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1420 (ltimes (make-vector lmax
0))
1425 (if (stringp tstart
) (setq tstart
(org-time-string-to-seconds tstart
)))
1426 (if (stringp tend
) (setq tend
(org-time-string-to-seconds tend
)))
1427 (if (consp tstart
) (setq tstart
(org-float-time tstart
)))
1428 (if (consp tend
) (setq tend
(org-float-time tend
)))
1429 (remove-text-properties (point-min) (point-max)
1430 '(:org-clock-minutes t
1431 :org-clock-force-headline-inclusion t
))
1433 (goto-char (point-max))
1434 (while (re-search-backward re nil t
)
1438 (setq ts
(match-string 2)
1441 (apply 'encode-time
(org-parse-time-string ts
)))
1443 (apply 'encode-time
(org-parse-time-string te
)))
1444 ts
(if tstart
(max ts tstart
) ts
)
1445 te
(if tend
(min te tend
) te
)
1447 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
1450 (setq t1
(+ t1
(string-to-number (match-string 5))
1451 (* 60 (string-to-number (match-string 4))))))
1453 ;; Add the currently clocking item time to the total
1454 (when (and org-clock-report-include-clocking-task
1455 (equal (org-clocking-buffer) (current-buffer))
1456 (equal (marker-position org-clock-hd-marker
) (point))
1459 (>= (org-float-time org-clock-start-time
) tstart
)
1460 (<= (org-float-time org-clock-start-time
) tend
))
1461 (let ((time (floor (- (org-float-time)
1462 (org-float-time org-clock-start-time
)) 60)))
1463 (setq t1
(+ t1 time
))))
1464 (let* ((headline-forced
1465 (get-text-property (point)
1466 :org-clock-force-headline-inclusion
))
1468 (or (null headline-filter
)
1470 (save-match-data (funcall headline-filter
))))))
1471 (setq level
(- (match-end 1) (match-beginning 1)))
1472 (when (or (> t1
0) (> (aref ltimes level
) 0))
1473 (when (or headline-included headline-forced
)
1474 (if headline-included
1475 (loop for l from
0 to level do
1476 (aset ltimes l
(+ (aref ltimes l
) t1
))))
1477 (setq time
(aref ltimes level
))
1478 (goto-char (match-beginning 0))
1479 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)
1484 (> (funcall outline-level
) 1)
1485 (outline-up-heading 1 t
)
1487 (point) (point-at-eol)
1488 :org-clock-force-headline-inclusion t
))))))
1490 (loop for l from level to
(1- lmax
) do
1491 (aset ltimes l
0)))))))
1492 (setq org-clock-file-total-minutes
(aref ltimes
0)))
1493 (set-buffer-modified-p bmp
)))
1495 (defun org-clock-sum-current-item (&optional tstart
)
1496 "Return time, clocked on current item in total."
1499 (org-narrow-to-subtree)
1500 (org-clock-sum tstart
)
1501 org-clock-file-total-minutes
)))
1503 (defun org-clock-display (&optional total-only
)
1504 "Show subtree times in the entire buffer.
1505 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1508 (org-clock-remove-overlays)
1513 (goto-char (point-min))
1514 (while (or (and (equal (setq p
(point)) (point-min))
1515 (get-text-property p
:org-clock-minutes
))
1516 (setq p
(next-single-property-change
1517 (point) :org-clock-minutes
)))
1519 (when (setq time
(get-text-property p
:org-clock-minutes
))
1520 (org-clock-put-overlay time
(funcall outline-level
))))
1521 (setq h
(/ org-clock-file-total-minutes
60)
1522 m
(- org-clock-file-total-minutes
(* 60 h
)))
1523 ;; Arrange to remove the overlays upon next change.
1524 (when org-remove-highlights-with-change
1525 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
1527 (if org-time-clocksum-use-fractional
1528 (message (concat "Total file time: " org-time-clocksum-fractional-format
1529 " (%d hours and %d minutes)")
1530 (/ (+ (* h
60.0) m
) 60.0) h m
)
1531 (message (concat "Total file time: " org-time-clocksum-format
1532 " (%d hours and %d minutes)") h m h m
))))
1534 (defvar org-clock-overlays nil
)
1535 (make-variable-buffer-local 'org-clock-overlays
)
1537 (defun org-clock-put-overlay (time &optional level
)
1538 "Put an overlays on the current line, displaying TIME.
1539 If LEVEL is given, prefix time with a corresponding number of stars.
1540 This creates a new overlay and stores it in `org-clock-overlays', so that it
1541 will be easy to remove."
1542 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
1543 (l (if level
(org-get-valid-level level
0) 0))
1544 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1545 org-time-clocksum-fractional-format
1546 org-time-clocksum-format
) "%s"))
1549 (org-move-to-column c
)
1550 (unless (eolp) (skip-chars-backward "^ \t"))
1551 (skip-chars-backward " \t")
1552 (setq ov
(make-overlay (1- (point)) (point-at-eol))
1553 tx
(concat (buffer-substring (1- (point)) (point))
1554 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
1555 (org-add-props (if org-time-clocksum-use-fractional
1558 (/ (+ (* h
60.0) m
) 60.0)
1559 (make-string (- 16 l
) ?\
))
1561 (make-string l ?
*) h m
1562 (make-string (- 16 l
) ?\
)))
1563 (list 'face
'org-clock-overlay
))
1565 (if (not (featurep 'xemacs
))
1566 (overlay-put ov
'display tx
)
1567 (overlay-put ov
'invisible t
)
1568 (overlay-put ov
'end-glyph
(make-glyph tx
)))
1569 (push ov org-clock-overlays
)))
1571 (defun org-clock-remove-overlays (&optional beg end noremove
)
1572 "Remove the occur highlights from the buffer.
1573 BEG and END are ignored. If NOREMOVE is nil, remove this function
1574 from the `before-change-functions' in the current buffer."
1576 (unless org-inhibit-highlight-removal
1577 (mapc 'delete-overlay org-clock-overlays
)
1578 (setq org-clock-overlays nil
)
1580 (remove-hook 'before-change-functions
1581 'org-clock-remove-overlays
'local
))))
1583 (defvar state
) ;; dynamically scoped into this function
1584 (defun org-clock-out-if-current ()
1585 "Clock out if the current entry contains the running clock.
1586 This is used to stop the clock after a TODO entry is marked DONE,
1587 and is only done if the variable `org-clock-out-when-done' is not nil."
1588 (when (and org-clock-out-when-done
1589 (or (and (eq t org-clock-out-when-done
)
1590 (member state org-done-keywords
))
1591 (and (listp org-clock-out-when-done
)
1592 (member state org-clock-out-when-done
)))
1593 (equal (or (buffer-base-buffer (org-clocking-buffer))
1594 (org-clocking-buffer))
1595 (or (buffer-base-buffer (current-buffer))
1597 (< (point) org-clock-marker
)
1598 (> (save-excursion (outline-next-heading) (point))
1600 ;; Clock out, but don't accept a logging message for this.
1601 (let ((org-log-note-clock-out nil
)
1602 (org-clock-out-switch-to-state nil
))
1605 (add-hook 'org-after-todo-state-change-hook
1606 'org-clock-out-if-current
)
1609 (defun org-get-clocktable (&rest props
)
1610 "Get a formatted clocktable with parameters according to PROPS.
1611 The table is created in a temporary buffer, fully formatted and
1612 fontified, and then returned."
1614 (setq props
(plist-put props
:name
"clocktable"))
1615 (unless (plist-member props
:maxlevel
)
1616 (setq props
(plist-put props
:maxlevel
2)))
1617 (unless (plist-member props
:scope
)
1618 (setq props
(plist-put props
:scope
'agenda
)))
1621 (org-create-dblock props
)
1623 (font-lock-fontify-buffer)
1625 (buffer-substring (point) (progn
1626 (re-search-forward "^#\\+END" nil t
)
1629 (defun org-clock-report (&optional arg
)
1630 "Create a table containing a report about clocked time.
1631 If the cursor is inside an existing clocktable block, then the table
1632 will be updated. If not, a new clocktable will be inserted.
1633 When called with a prefix argument, move to the first clock table in the
1634 buffer and update it."
1636 (org-clock-remove-overlays)
1638 (org-find-dblock "clocktable")
1640 (if (org-in-clocktable-p)
1641 (goto-char (org-in-clocktable-p))
1642 (org-create-dblock (append (list :name
"clocktable")
1643 org-clock-clocktable-default-properties
)))
1644 (org-update-dblock))
1646 (defun org-in-clocktable-p ()
1647 "Check if the cursor is in a clocktable."
1648 (let ((pos (point)) start
)
1651 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
1652 (setq start
(match-beginning 0))
1653 (re-search-forward "^#\\+END:.*" nil t
)
1654 (>= (match-end 0) pos
)
1657 (defun org-clock-special-range (key &optional time as-strings
)
1658 "Return two times bordering a special time range.
1659 Key is a symbol specifying the range and can be one of `today', `yesterday',
1660 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1661 A week starts Monday 0:00 and ends Sunday 24:00.
1662 The range is determined relative to TIME. TIME defaults to the current time.
1663 The return value is a cons cell with two internal times like the ones
1664 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1665 the returned times will be formatted strings."
1666 (if (integerp key
) (setq key
(intern (number-to-string key
))))
1667 (let* ((tm (decode-time (or time
(current-time))))
1668 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
1669 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
1671 (skey (symbol-name key
))
1673 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
1675 ((string-match "^[0-9]+$" skey
)
1676 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
1677 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1678 (setq y
(string-to-number (match-string 1 skey
))
1679 month
(string-to-number (match-string 2 skey
))
1681 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
1683 (setq y
(string-to-number (match-string 1 skey
))
1684 w
(string-to-number (match-string 2 skey
)))
1685 (setq date
(calendar-gregorian-from-absolute
1686 (calendar-absolute-from-iso (list w
1 y
))))
1687 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1690 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1691 (setq y
(string-to-number (match-string 1 skey
))
1692 month
(string-to-number (match-string 2 skey
))
1693 d
(string-to-number (match-string 3 skey
))
1695 ((string-match "\\([-+][0-9]+\\)$" skey
)
1696 (setq shift
(string-to-number (match-string 1 skey
))
1697 key
(intern (substring skey
0 (match-beginning 1))))))
1699 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
1700 ((eq key
'lastweek
) (setq key
'week shift -
1))
1701 ((eq key
'lastmonth
) (setq key
'month shift -
1))
1702 ((eq key
'lastyear
) (setq key
'year shift -
1))))
1704 ((memq key
'(day today
))
1705 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
1706 ((memq key
'(week thisweek
))
1707 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
1708 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
1709 ((memq key
'(month thismonth
))
1710 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
1711 ((memq key
'(year thisyear
))
1712 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
1713 (t (error "No such time block %s" key
)))
1714 (setq ts
(encode-time s m h d month y
)
1715 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
1716 (or d1 d
) (or month1 month
) (or y1 y
)))
1717 (setq fm
(cdr org-time-stamp-formats
))
1719 ((memq key
'(day today
))
1720 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
1721 ((memq key
'(week thisweek
))
1722 (setq txt
(format-time-string "week %G-W%V" ts
)))
1723 ((memq key
'(month thismonth
))
1724 (setq txt
(format-time-string "%B %Y" ts
)))
1725 ((memq key
'(year thisyear
))
1726 (setq txt
(format-time-string "the year %Y" ts
))))
1728 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
1731 (defun org-clocktable-shift (dir n
)
1732 "Try to shift the :block date of the clocktable at point.
1733 Point must be in the #+BEGIN: line of a clocktable, or this function
1734 will throw an error.
1735 DIR is a direction, a symbol `left', `right', `up', or `down'.
1736 Both `left' and `down' shift the block toward the past, `up' and `right'
1737 push it toward the future.
1738 N is the number of shift steps to take. The size of the step depends on
1739 the currently selected interval size."
1740 (setq n
(prefix-numeric-value n
))
1741 (and (memq dir
'(left down
)) (setq n
(- n
)))
1743 (goto-char (point-at-bol))
1744 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1745 (error "Line needs a :block definition before this command works")
1746 (let* ((b (match-beginning 1)) (e (match-end 1))
1747 (s (match-string 1))
1748 block shift ins y mw d date wp m
)
1750 ((equal s
"yesterday") (setq s
"today-1"))
1751 ((equal s
"lastweek") (setq s
"thisweek-1"))
1752 ((equal s
"lastmonth") (setq s
"thismonth-1"))
1753 ((equal s
"lastyear") (setq s
"thisyear-1")))
1755 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
1756 (setq block
(match-string 1 s
)
1757 shift
(if (match-end 2)
1758 (string-to-number (match-string 2 s
))
1760 (setq shift
(+ shift n
))
1761 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
1762 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
1763 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1764 (setq y
(string-to-number (match-string 1 s
))
1765 wp
(and (match-end 3) (match-string 3 s
))
1766 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
1767 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
1769 (d (setq ins
(format-time-string
1771 (encode-time 0 0 0 (+ d n
) m y
))))
1772 ((and wp mw
(> (length wp
) 0))
1774 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
1775 (setq ins
(format-time-string
1777 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1779 (setq ins
(format-time-string
1781 (encode-time 0 0 0 1 (+ mw n
) y
))))
1783 (setq ins
(number-to-string (+ y n
))))))
1784 (t (error "Cannot shift clocktable block")))
1788 (delete-region (point) (+ (point) (- e b
)))
1789 (beginning-of-line 1)
1793 (defun org-dblock-write:clocktable
(params)
1794 "Write the standard clocktable."
1795 (setq params
(org-combine-plists org-clocktable-defaults params
))
1797 (let* ((scope (plist-get params
:scope
))
1798 (block (plist-get params
:block
))
1799 (ts (plist-get params
:tstart
))
1800 (te (plist-get params
:tend
))
1801 (link (plist-get params
:link
))
1802 (maxlevel (or (plist-get params
:maxlevel
) 3))
1803 (step (plist-get params
:step
))
1804 (timestamp (plist-get params
:timestamp
))
1805 (formatter (or (plist-get params
:formatter
)
1806 org-clock-clocktable-formatter
1807 'org-clocktable-write-default
))
1808 cc range-text ipos pos one-file-with-archives
1809 scope-is-list tbls level link
)
1811 ;; Check if we need to do steps
1813 ;; Get the range text for the header
1814 (setq cc
(org-clock-special-range block nil t
)
1815 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1817 ;; Write many tables, in steps
1818 (unless (or block
(and ts te
))
1819 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1820 (org-clocktable-steps params
)
1823 (setq ipos
(point)) ; remember the insertion position
1825 ;; Get the right scope
1828 ((and scope
(listp scope
) (symbolp (car scope
)))
1829 (setq scope
(eval scope
)))
1831 (setq scope
(org-agenda-files t
)))
1832 ((eq scope
'agenda-with-archives
)
1833 (setq scope
(org-agenda-files t
))
1834 (setq scope
(org-add-archive-files scope
)))
1835 ((eq scope
'file-with-archives
)
1836 (setq scope
(org-add-archive-files (list (buffer-file-name)))
1837 one-file-with-archives t
)))
1838 (setq scope-is-list
(and scope
(listp scope
)))
1840 ;; we collect from several files
1841 (let* ((files scope
)
1843 (org-prepare-agenda-buffers files
)
1844 (while (setq file
(pop files
))
1845 (with-current-buffer (find-buffer-visiting file
)
1848 (push (org-clock-get-table-data file params
) tbls
))))))
1849 ;; Just from the current file
1851 ;; get the right range into the restriction
1852 (org-prepare-agenda-buffers (list (buffer-file-name)))
1854 ((not scope
)) ; use the restriction as it is now
1855 ((eq scope
'file
) (widen))
1856 ((eq scope
'subtree
) (org-narrow-to-subtree))
1858 (while (org-up-heading-safe))
1859 (org-narrow-to-subtree))
1860 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
1861 (symbol-name scope
)))
1862 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
1864 (while (org-up-heading-safe)
1865 (looking-at outline-regexp
)
1866 (if (<= (org-reduced-level (funcall outline-level
)) level
)
1867 (throw 'exit nil
))))
1868 (org-narrow-to-subtree)))
1869 ;; do the table, with no file name.
1870 (push (org-clock-get-table-data nil params
) tbls
)))
1872 ;; OK, at this point we tbls as a list of tables, one per file
1873 (setq tbls
(nreverse tbls
))
1875 (setq params
(plist-put params
:multifile scope-is-list
))
1876 (setq params
(plist-put params
:one-file-with-archives
1877 one-file-with-archives
))
1879 (funcall formatter ipos tbls params
))))
1881 (defun org-clocktable-write-default (ipos tables params
)
1882 "Write out a clock table at position IPOS in the current buffer
1883 TABLES is a list of tables with clocking data as produced by
1884 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
1885 from the dynamic block defintion."
1886 ;; This function looks quite complicated, mainly because there are a lot
1887 ;; of options which can add or remove columns. I have massively commented
1888 ;; function, to I hope it is understandable. If someone want to write
1889 ;; there own special formatter, this maybe much easier because there can
1890 ;; be a fixed format with a well-defined number of columns...
1891 (let* ((hlchars '((1 .
"*") (2 .
"/")))
1892 (multifile (plist-get params
:multifile
))
1893 (block (plist-get params
:block
))
1894 (ts (plist-get params
:tstart
))
1895 (te (plist-get params
:tend
))
1896 (header (plist-get params
:header
))
1897 (narrow (plist-get params
:narrow
))
1898 (link (plist-get params
:link
))
1899 (maxlevel (or (plist-get params
:maxlevel
) 3))
1900 (emph (plist-get params
:emphasize
))
1901 (level-p (plist-get params
:level
))
1902 (timestamp (plist-get params
:timestamp
))
1903 (ntcol (max 1 (or (plist-get params
:tcolumns
) 100)))
1904 (rm-file-column (plist-get params
:one-file-with-archives
))
1905 (indent (plist-get params
:indent
))
1906 range-text total-time tbl level hlc formula pcol
1907 file-time entries entry headline
1908 recalc content narrow-cut-p
)
1910 ;; Implement abbreviations
1911 (when (plist-get params
:compact
)
1912 (setq level nil indent t narrow
(or narrow
'40!) ntcol
1))
1914 ;; Some consistency test for parameters
1915 (unless (integerp ntcol
)
1916 (setq params
(plist-put params
:tcolumns
(setq ntcol
100))))
1918 (when (and narrow
(integerp narrow
) link
)
1919 ;; We cannot have both integer narrow and link
1921 "Using hard narrowing in clocktable to allow for links")
1922 (setq narrow
(intern (format "%d!" narrow
))))
1927 ((and (symbolp narrow
)
1928 (string-match "\\`[0-9]+!\\'" (symbol-name narrow
)))
1929 (setq narrow-cut-p t
1930 narrow
(string-to-number (substring (symbol-name narrow
)
1933 (error "Invalid value %s of :narrow property in clock table"
1937 ;; Get the range text for the header
1938 (setq range-text
(nth 2 (org-clock-special-range block nil t
))))
1940 ;; Compute the total time
1941 (setq total-time
(apply '+ (mapcar 'cadr tables
)))
1943 ;; Now we need to output this tsuff
1946 ;; Insert the text *before* the actual table
1947 (insert-before-markers
1949 ;; Format the standard header
1951 "Clock summary at ["
1953 (format-time-string (cdr org-time-stamp-formats
))
1956 (if block
(concat ", for " range-text
".") "")
1959 ;; Insert the narrowing line
1960 (when (and narrow
(integerp narrow
) (not narrow-cut-p
))
1961 (insert-before-markers
1962 "|" ; table line starter
1963 (if multifile
"|" "") ; file column, maybe
1964 (if level-p
"|" "") ; level column, maybe
1965 (if timestamp
"|" "") ; timestamp column, maybe
1966 (format "<%d>| |\n" narrow
))) ; headline and time columns
1968 ;; Insert the table header line
1969 (insert-before-markers
1970 "|" ; table line starter
1971 (if multifile
"File|" "") ; file column, maybe
1972 (if level-p
"L|" "") ; level column, maybe
1973 (if timestamp
"Timestamp|" "") ; timestamp column, maybe
1974 "Headline|Time|\n") ; headline and time columns
1976 ;; Insert the total time in the table
1977 (insert-before-markers
1979 "|" ; table line starter
1980 (if multifile
"| ALL " "") ; file column, maybe
1981 (if level-p
"|" "") ; level column, maybe
1982 (if timestamp
"|" "") ; timestamp column, maybe
1983 "*Total time*| " ; instead of a headline
1985 (org-minutes-to-hh:mm-string
(or total-time
0)) ; the time
1986 "*|\n") ; close line
1988 ;; Now iterate over the tables and insert the data
1989 ;; but only if any time has been collected
1990 (when (and total-time
(> total-time
0))
1992 (while (setq tbl
(pop tables
))
1993 ;; now tbl is the table resulting from one file.
1994 (setq file-time
(nth 1 tbl
))
1995 (when (or (and file-time
(> file-time
0))
1996 (not (plist-get params
:fileskip0
)))
1997 (insert-before-markers "|-\n") ; a hline because a new file starts
1998 ;; First the file time, if we have multiple files
2000 ;; Summarize the time colleted from this file
2001 (insert-before-markers
2002 (format "| %s %s | %s*File time* | *%s*|\n"
2003 (file-name-nondirectory (car tbl
))
2004 (if level-p
"| " "") ; level column, maybe
2005 (if timestamp
"| " "") ; timestamp column, maybe
2006 (org-minutes-to-hh:mm-string
(nth 1 tbl
))))) ; the time
2008 ;; Get the list of node entries and iterate over it
2009 (setq entries
(nth 2 tbl
))
2010 (while (setq entry
(pop entries
))
2011 (setq level
(car entry
)
2012 headline
(nth 1 entry
)
2013 hlc
(if emph
(or (cdr (assoc level hlchars
)) "") ""))
2015 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2020 (format "[[%s][%s]]"
2021 (match-string 1 headline
)
2022 (org-shorten-string (match-string 3 headline
)
2024 (setq headline
(org-shorten-string headline narrow
))))
2025 (insert-before-markers
2026 "|" ; start the table line
2027 (if multifile
"|" "") ; free space for file name column?
2028 (if level-p
(format "%d|" (car entry
)) "") ; level, maybe
2029 (if timestamp
(concat (nth 2 entry
) "|") "") ; timestamp, maybe
2030 (if indent
(org-clocktable-indent-string level
) "") ; indentation
2031 hlc headline hlc
"|" ; headline
2032 (make-string (min (1- ntcol
) (or (- level
1))) ?|
)
2033 ; empty fields for higher levels
2034 hlc
(org-minutes-to-hh:mm-string
(nth 3 entry
)) hlc
; time
2037 (backward-delete-char 1)
2038 (if (setq formula
(plist-get params
:formula
))
2043 (min maxlevel
(or ntcol
100))
2044 (if timestamp
1 0)))
2047 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2049 (+ 2 (if narrow
1 0))
2050 (+ 3 (if multifile
1 0))
2051 (+ (if multifile
1 0) 3)
2055 (insert "\n#+TBLFM: " formula
)
2057 (t (error "invalid formula in clocktable")))
2058 ;; Should we rescue an old formula?
2059 (when (stringp (setq content
(plist-get params
:content
)))
2060 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content
)
2062 (insert "\n" (match-string 1 (plist-get params
:content
)))
2063 (beginning-of-line 0))))
2064 ;; Back to beginning, align the table, recalculate if necessary
2066 (skip-chars-forward "^|")
2068 (when org-hide-emphasis-markers
2069 ;; we need to align a second time
2074 (if narrow
(beginning-of-line 2))
2075 (org-table-goto-column pcol nil
'force
)
2077 (org-table-recalculate 'all
))
2078 (when rm-file-column
2079 ;; The file column is actually not wanted
2081 (org-table-delete-column))
2084 (defun org-clocktable-indent-string (level)
2089 (setq level
(1- level
)
2090 str
(concat str
"___")))
2093 (defun org-clocktable-steps (params)
2094 "Step through the range to make a number of clock tables."
2095 (let* ((p1 (copy-sequence params
))
2096 (ts (plist-get p1
:tstart
))
2097 (te (plist-get p1
:tend
))
2098 (step0 (plist-get p1
:step
))
2099 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
2100 (stepskip0 (plist-get p1
:stepskip0
))
2101 (block (plist-get p1
:block
))
2102 cc range-text step-time
)
2104 (setq cc
(org-clock-special-range block nil t
)
2105 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
2108 ;; If ts is a number, it's an absolute day number from org-agenda.
2109 (destructuring-bind (month day year
) (calendar-gregorian-from-absolute ts
)
2110 (setq ts
(org-float-time (encode-time 0 0 0 day month year
)))))
2112 (setq ts
(org-float-time
2113 (apply 'encode-time
(org-parse-time-string ts
))))))
2117 (destructuring-bind (month day year
) (calendar-gregorian-from-absolute te
)
2118 (setq te
(org-float-time (encode-time 0 0 0 day month year
)))))
2120 (setq te
(org-float-time
2121 (apply 'encode-time
(org-parse-time-string te
))))))
2122 (setq p1
(plist-put p1
:header
""))
2123 (setq p1
(plist-put p1
:step nil
))
2124 (setq p1
(plist-put p1
:block nil
))
2126 (or (bolp) (insert "\n"))
2127 (setq p1
(plist-put p1
:tstart
(format-time-string
2128 (org-time-stamp-format nil t
)
2129 (seconds-to-time ts
))))
2130 (setq p1
(plist-put p1
:tend
(format-time-string
2131 (org-time-stamp-format nil t
)
2132 (seconds-to-time (setq ts
(+ ts step
))))))
2133 (insert "\n" (if (eq step0
'day
) "Daily report: "
2134 "Weekly report starting on: ")
2135 (plist-get p1
:tstart
) "\n")
2136 (setq step-time
(org-dblock-write:clocktable p1
))
2137 (re-search-forward "#\\+END:")
2138 (when (and (equal step-time
0) stepskip0
)
2139 ;; Remove the empty table
2140 (delete-region (point-at-bol)
2142 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2147 (defun org-clock-get-table-data (file params
)
2148 "Get the clocktable data for file FILE, with parameters PARAMS.
2149 FILE is only for identification - this function assumes that
2150 the correct buffer is current, and that the wanted restriction is
2152 The return value will be a list with the file name and the total
2153 file time (in minutes) as 1st and 2nd elements. The third element
2154 of this list will be a list of headline entries. Each entry has the
2155 following structure:
2157 (LEVEL HEADLINE TIMESTAMP TIME)
2159 LEVEL: The level of the headline, as an integer. This will be
2160 the reduced leve, so 1,2,3,... even if only odd levels
2162 HEADLINE: The text of the headline. Depending on PARAMS, this may
2163 already be formatted like a link.
2164 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2165 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2167 TIME: The sum of all time spend in this tree, in minutes. This time
2168 will of cause be restricted to the time block and tags match
2169 specified in PARAMS."
2170 (let* ((maxlevel (or (plist-get params
:maxlevel
) 3))
2171 (timestamp (plist-get params
:timestamp
))
2172 (ts (plist-get params
:tstart
))
2173 (te (plist-get params
:tend
))
2174 (block (plist-get params
:block
))
2175 (link (plist-get params
:link
))
2176 (tags (plist-get params
:tags
))
2177 (matcher (if tags
(cdr (org-make-tags-matcher tags
))))
2178 cc range-text st p time level hdl props tsp tbl
)
2180 (setq org-clock-file-total-minutes nil
)
2182 (setq cc
(org-clock-special-range block nil t
)
2183 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
2184 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
2185 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
2186 (when (and ts
(listp ts
))
2187 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
2188 (when (and te
(listp te
))
2189 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
2190 ;; Now the times are strings we can parse.
2191 (if ts
(setq ts
(org-float-time
2192 (apply 'encode-time
(org-parse-time-string ts
)))))
2193 (if te
(setq te
(org-float-time
2194 (apply 'encode-time
(org-parse-time-string te
)))))
2196 (org-clock-sum ts te
2197 (unless (null matcher
)
2199 (let ((tags-list (org-get-tags-at)))
2201 (goto-char (point-min))
2203 (while (or (and (bobp) (prog1 st
(setq st nil
))
2204 (get-text-property (point) :org-clock-minutes
)
2205 (setq p
(point-min)))
2206 (setq p
(next-single-property-change
2207 (point) :org-clock-minutes
)))
2209 (when (setq time
(get-text-property p
:org-clock-minutes
))
2211 (beginning-of-line 1)
2212 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2213 (setq level
(org-reduced-level
2214 (- (match-end 1) (match-beginning 1))))
2215 (<= level maxlevel
))
2216 (setq hdl
(if (not link
)
2218 (org-make-link-string
2219 (format "file:%s::%s"
2222 (org-make-org-heading-search-string
2226 (setq props
(org-entry-properties (point)))
2227 (or (cdr (assoc "SCHEDULED" props
))
2228 (cdr (assoc "DEADLINE" props
))
2229 (cdr (assoc "TIMESTAMP" props
))
2230 (cdr (assoc "TIMESTAMP_IA" props
)))))
2231 (when (> time
0) (push (list level hdl tsp time
) tbl
))))))
2232 (setq tbl
(nreverse tbl
))
2233 (list file org-clock-file-total-minutes tbl
))))
2236 (defun org-clock-time%
(total &rest strings
)
2237 "Compute a time fraction in percent.
2238 TOTAL s a time string like 10:21 specifying the total times.
2239 STRINGS is a list of strings that should be checked for a time.
2240 The first string that does have a time will be used.
2241 This function is made for clock tables."
2242 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2246 (if (not (string-match re total
))
2248 (setq tot
(+ (string-to-number (match-string 2 total
))
2249 (* 60 (string-to-number (match-string 1 total
)))))
2250 (if (= tot
0.
) (throw 'exit
0.
)))
2251 (while (setq s
(pop strings
))
2252 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
2254 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
2255 (* 60 (string-to-number
2256 (match-string 1 s
)))))
2260 (defvar org-clock-loaded nil
2261 "Was the clock file loaded?")
2263 (defun org-clock-save ()
2264 "Persist various clock-related data to disk.
2265 The details of what will be saved are regulated by the variable
2266 `org-clock-persist'."
2267 (when (and org-clock-persist
2268 (or org-clock-loaded
2269 org-clock-has-been-used
2270 (not (file-exists-p org-clock-persist-file
))))
2272 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
2274 (delete-region (point-min) (point-max))
2276 (insert (format ";; org-persist.el - %s at %s\n"
2277 system-name
(format-time-string
2278 (cdr org-time-stamp-formats
))))
2279 (if (and (memq org-clock-persist
'(t clock
))
2280 (setq b
(org-clocking-buffer))
2281 (setq b
(or (buffer-base-buffer b
) b
))
2283 (buffer-file-name b
)
2284 (or (not org-clock-persist-query-save
)
2285 (y-or-n-p (concat "Save current clock ("
2286 (substring-no-properties
2289 (insert "(setq resume-clock '(\""
2290 (buffer-file-name (org-clocking-buffer))
2291 "\" . " (int-to-string (marker-position org-clock-marker
))
2293 ;; Store clocked task history. Tasks are stored reversed to make
2295 (when (and (memq org-clock-persist
'(t history
))
2298 "(setq stored-clock-history '("
2301 (when (and (setq b
(marker-buffer m
))
2302 (setq b
(or (buffer-base-buffer b
) b
))
2304 (buffer-file-name b
))
2305 (concat "(\"" (buffer-file-name b
)
2306 "\" . " (int-to-string (marker-position m
))
2308 (reverse org-clock-history
) " ") "))\n"))
2310 (kill-buffer (current-buffer)))))))
2312 (defun org-clock-load ()
2313 "Load clock-related data from disk, maybe resuming a stored clock."
2314 (when (and org-clock-persist
(not org-clock-loaded
))
2315 (let ((filename (expand-file-name org-clock-persist-file
))
2316 (org-clock-in-resume 'auto-restart
)
2317 resume-clock stored-clock-history
)
2318 (if (not (file-readable-p filename
))
2319 (message "Not restoring clock data; %s not found"
2320 org-clock-persist-file
)
2321 (message "%s" "Restoring clock data")
2322 (setq org-clock-loaded t
)
2323 (load-file filename
)
2325 (when stored-clock-history
2326 (save-window-excursion
2327 (mapc (lambda (task)
2328 (if (file-exists-p (car task
))
2329 (org-clock-history-push (cdr task
)
2330 (find-file (car task
)))))
2331 stored-clock-history
)))
2333 (when (and resume-clock org-clock-persist
2334 (file-exists-p (car resume-clock
))
2335 (or (not org-clock-persist-query-resume
)
2339 (with-current-buffer (find-file (car resume-clock
))
2341 (goto-char (cdr resume-clock
))
2342 (org-back-to-heading t
)
2343 (and (looking-at org-complex-heading-regexp
)
2346 (when (file-exists-p (car resume-clock
))
2347 (with-current-buffer (find-file (car resume-clock
))
2348 (goto-char (cdr resume-clock
))
2349 (let ((org-clock-auto-clock-resolution nil
))
2351 (if (org-invisible-p)
2352 (org-show-context))))))))))
2355 (defun org-clock-persistence-insinuate ()
2356 "Set up hooks for clock persistence."
2357 (add-hook 'org-mode-hook
'org-clock-load
)
2358 (add-hook 'kill-emacs-hook
'org-clock-save
))
2360 ;; Suggested bindings
2361 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
2363 (provide 'org-clock
)
2365 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2367 ;;; org-clock.el ends here