1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;; This file contains the time clocking code for Org-mode
36 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
37 (declare-function notifications-notify
"notifications" (&rest params
))
38 (defvar org-time-stamp-formats
)
40 (defgroup org-clock nil
41 "Options concerning clocking working time in Org-mode."
45 (defcustom org-clock-into-drawer org-log-into-drawer
46 "Should clocking info be wrapped into a drawer?
47 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
48 If necessary, the drawer will be created.
49 When nil, the drawer will not be created, but used when present.
50 When an integer and the number of clocking entries in an item
51 reaches or exceeds this number, a drawer will be created.
52 When a string, it names the drawer to be used.
54 The default for this variable is the value of `org-log-into-drawer',
59 (const :tag
"Always" t
)
60 (const :tag
"Only when drawer exists" nil
)
61 (integer :tag
"When at least N clock entries")
62 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
63 (string :tag
"Into Drawer named...")))
65 (defcustom org-clock-out-when-done t
66 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
67 DONE here means any DONE-like state.
68 A nil value means clock will keep running until stopped explicitly with
69 `C-c C-x C-o', or until the clock is started in a different item.
70 Instead of t, this can also be a list of TODO states that should trigger
75 (const :tag
"Yes, when done" t
)
76 (repeat :tag
"State list"
77 (string :tag
"TODO keyword"))))
79 (defcustom org-clock-out-remove-zero-time-clocks nil
80 "Non-nil means remove the clock line when the resulting time is zero."
84 (defcustom org-clock-in-switch-to-state nil
85 "Set task to a special todo state while clocking it.
86 The value should be the state to which the entry should be
87 switched. If the value is a function, it must take one
88 parameter (the current TODO state of the item) and return the
89 state to switch it to."
93 (const :tag
"Don't force a state" nil
)
95 (symbol :tag
"Function")))
97 (defcustom org-clock-out-switch-to-state nil
98 "Set task to a special todo state after clocking out.
99 The value should be the state to which the entry should be
100 switched. If the value is a function, it must take one
101 parameter (the current TODO state of the item) and return the
102 state to switch it to."
106 (const :tag
"Don't force a state" nil
)
107 (string :tag
"State")
108 (symbol :tag
"Function")))
110 (defcustom org-clock-history-length
5
111 "Number of clock tasks to remember in history."
115 (defcustom org-clock-goto-may-find-recent-task t
116 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
120 (defcustom org-clock-heading-function nil
121 "When non-nil, should be a function to create `org-clock-heading'.
122 This is the string shown in the mode line when a clock is running.
123 The function is called with point at the beginning of the headline."
127 (defcustom org-clock-string-limit
0
128 "Maximum length of clock strings in the modeline. 0 means no limit."
132 (defcustom org-clock-in-resume nil
133 "If non-nil, resume clock when clocking into task with open clock.
134 When clocking into a task with a clock entry which has not been closed,
135 the clock can be resumed from that point."
139 (defcustom org-clock-persist nil
140 "When non-nil, save the running clock when Emacs is closed.
141 The clock is resumed when Emacs restarts.
142 When this is t, both the running clock, and the entire clock
143 history are saved. When this is the symbol `clock', only the
144 running clock is saved.
146 When Emacs restarts with saved clock information, the file containing the
147 running clock as well as all files mentioned in the clock history will
149 All this depends on running `org-clock-persistence-insinuate' in .emacs"
152 (const :tag
"Just the running clock" clock
)
153 (const :tag
"Just the history" history
)
154 (const :tag
"Clock and history" t
)
155 (const :tag
"No persistence" nil
)))
157 (defcustom org-clock-persist-file
(convert-standard-filename
158 "~/.emacs.d/org-clock-save.el")
159 "File to save clock data to."
163 (defcustom org-clock-persist-query-save nil
164 "When non-nil, ask before saving the current clock on exit."
168 (defcustom org-clock-persist-query-resume t
169 "When non-nil, ask before resuming any stored clock during load."
173 (defcustom org-clock-sound nil
174 "Sound that will used for notifications.
178 t standard Emacs beep
179 file name play this sound file. If not possible, fall back to beep"
182 (const :tag
"No sound" nil
)
183 (const :tag
"Standard beep" t
)
184 (file :tag
"Play sound file")))
186 (defcustom org-clock-modeline-total
'auto
187 "Default setting for the time included for the modeline clock.
188 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
191 current Only the time in the current instance of the clock
192 today All time clocked into this task today
193 repeat All time clocked into this task since last repeat
194 all All time ever recorded for this task
195 auto Automatically, either `all', or `repeat' for repeating tasks"
198 (const :tag
"Current clock" current
)
199 (const :tag
"Today's task time" today
)
200 (const :tag
"Since last repeat" repeat
)
201 (const :tag
"All task time" all
)
202 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
204 (defcustom org-task-overrun-text nil
205 "The extra modeline text that should indicate that the clock is overrun.
206 The can be nil to indicate that instead of adding text, the clock time
207 should get a different face (`org-mode-line-clock-overrun').
208 When this is a string, it is prepended to the clock string as an indication,
209 also using the face `org-mode-line-clock-overrun'."
212 (const :tag
"Just mark the time string" nil
)
213 (string :tag
"Text to prepend")))
215 (defcustom org-show-notification-handler nil
216 "Function or program to send notification with.
217 The function or program will be called with the notification
221 (string :tag
"Program")
222 (function :tag
"Function")))
224 (defgroup org-clocktable nil
225 "Options concerning the clock table in Org-mode."
226 :tag
"Org Clock Table"
229 (defcustom org-clocktable-defaults
249 "Default properties for clock tables."
253 (defcustom org-clock-clocktable-formatter
'org-clocktable-write-default
254 "Function to turn clocking data into a table.
255 For more information, see `org-clocktable-write-default'."
256 :group
'org-clocktable
259 (defcustom org-clock-clocktable-default-properties
'(:maxlevel
2 :scope file
)
260 "Default properties for new clocktables.
261 These will be inserted into the BEGIN line, to make it easy for users to
263 :group
'org-clocktable
266 (defcustom org-clock-idle-time nil
267 "When non-nil, resolve open clocks if the user is idle more than X minutes."
270 (const :tag
"Never" nil
)
271 (integer :tag
"After N minutes")))
273 (defcustom org-clock-auto-clock-resolution
'when-no-clock-is-running
274 "When to automatically resolve open clocks found in Org buffers."
277 (const :tag
"Never" nil
)
278 (const :tag
"Always" t
)
279 (const :tag
"When no clock is running" when-no-clock-is-running
)))
281 (defcustom org-clock-report-include-clocking-task nil
282 "When non-nil, include the current clocking task time in clock reports."
286 (defcustom org-clock-resolve-expert nil
287 "Non-nil means do not show the splash buffer with the clock resolver."
291 (defvar org-clock-in-prepare-hook nil
292 "Hook run when preparing the clock.
293 This hook is run before anything happens to the task that
294 you want to clock in. For example, you can use this hook
295 to add an effort property.")
296 (defvar org-clock-in-hook nil
297 "Hook run when starting the clock.")
298 (defvar org-clock-out-hook nil
299 "Hook run when stopping the current clock.")
301 (defvar org-clock-cancel-hook nil
302 "Hook run when cancelling the current clock.")
303 (defvar org-clock-goto-hook nil
304 "Hook run when selecting the currently clocked-in entry.")
305 (defvar org-clock-has-been-used nil
306 "Has the clock been used during the current Emacs session?")
308 ;;; The clock for measuring work time.
310 (defvar org-mode-line-string
"")
311 (put 'org-mode-line-string
'risky-local-variable t
)
313 (defvar org-clock-mode-line-timer nil
)
314 (defvar org-clock-idle-timer nil
)
315 (defvar org-clock-heading
) ; defined in org.el
316 (defvar org-clock-heading-for-remember
"")
317 (defvar org-clock-start-time
"")
319 (defvar org-clock-leftover-time nil
320 "If non-nil, user cancelled a clock; this is when leftover time started.")
322 (defvar org-clock-effort
""
323 "Effort estimate of the currently clocking task.")
325 (defvar org-clock-total-time nil
326 "Holds total time, spent previously on currently clocked item.
327 This does not include the time in the currently running clock.")
329 (defvar org-clock-history nil
330 "List of marker pointing to recent clocked tasks.")
332 (defvar org-clock-default-task
(make-marker)
333 "Marker pointing to the default task that should clock time.
334 The clock can be made to switch to this task after clocking out
335 of a different task.")
337 (defvar org-clock-interrupted-task
(make-marker)
338 "Marker pointing to the task that has been interrupted by the current clock.")
340 (defvar org-clock-mode-line-map
(make-sparse-keymap))
341 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
342 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
344 (defun org-clock-menu ()
348 ["Clock out" org-clock-out t
]
349 ["Change effort estimate" org-clock-modify-effort-estimate t
]
350 ["Go to clock entry" org-clock-goto t
]
351 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
353 (defun org-clock-history-push (&optional pos buffer
)
354 "Push a marker to the clock history."
355 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
356 (let ((m (move-marker (make-marker)
357 (or pos
(point)) (org-base-buffer
358 (or buffer
(current-buffer)))))
360 (while (setq n
(member m org-clock-history
))
361 (move-marker (car n
) nil
))
362 (setq org-clock-history
364 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
366 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
367 (setq org-clock-history
369 (nthcdr (- l org-clock-history-length -
1)
370 (nreverse org-clock-history
)))))
371 (push m org-clock-history
)))
373 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
374 "Save relative positions of markers in region."
375 (org-check-and-save-marker org-clock-marker beg end
)
376 (org-check-and-save-marker org-clock-hd-marker beg end
)
377 (org-check-and-save-marker org-clock-default-task beg end
)
378 (org-check-and-save-marker org-clock-interrupted-task beg end
)
379 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
382 (defun org-clocking-buffer ()
383 "Return the clocking buffer if we are currently clocking a task or nil."
384 (marker-buffer org-clock-marker
))
386 (defun org-clocking-p ()
387 "Return t when clocking a task."
388 (not (equal (org-clocking-buffer) nil
)))
390 (defun org-clock-select-task (&optional prompt
)
391 "Select a task that recently was associated with clocking."
393 (let (sel-list rpl
(i 0) s
)
394 (save-window-excursion
395 (org-switch-to-buffer-other-window
396 (get-buffer-create "*Clock Task Select*"))
398 (when (marker-buffer org-clock-default-task
)
399 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
400 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
402 (when (marker-buffer org-clock-interrupted-task
)
403 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
404 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
406 (when (org-clocking-p)
407 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
408 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
410 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
413 (when (marker-buffer m
)
415 s
(org-clock-insert-selection-line
419 (if (fboundp 'int-to-char
) (setf (car s
) (int-to-char (car s
))))
422 (org-fit-window-to-buffer)
423 (message (or prompt
"Select task for clocking:"))
424 (setq rpl
(read-char-exclusive))
428 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
429 (t (error "Invalid task choice %c" rpl
))))))
431 (defun org-clock-insert-selection-line (i marker
)
432 "Insert a line for the clock selection menu.
433 And return a cons cell with the selection character integer and the marker
435 (when (marker-buffer marker
)
436 (let (file cat task heading prefix
)
437 (with-current-buffer (org-base-buffer (marker-buffer marker
))
443 (setq file
(buffer-file-name (marker-buffer marker
))
444 cat
(or (org-get-category)
445 (progn (org-refresh-category-properties)
447 heading
(org-get-heading 'notags
)
448 prefix
(save-excursion
449 (org-back-to-heading t
)
453 (org-fontify-like-in-org-mode
454 (concat prefix heading
)
456 (length prefix
)))))))
458 (insert (format "[%c] %-15s %s\n" i cat task
))
461 (defvar org-task-overrun nil
462 "Internal flag indicating if the clock has overrun the planned time.")
463 (defvar org-clock-update-period
60
464 "Number of seconds between mode line clock string updates.")
466 (defun org-clock-get-clock-string ()
467 "Form a clock-string, that will be shown in the mode line.
468 If an effort estimate was defined for the current item, use
469 01:30/01:50 format (clocked/estimated).
470 If not, show simply the clocked time like 01:50."
471 (let* ((clocked-time (org-clock-get-clocked-time))
472 (h (floor clocked-time
60))
473 (m (- clocked-time
(* 60 h
))))
475 (let* ((effort-in-minutes
476 (org-hh:mm-string-to-minutes org-clock-effort
))
477 (effort-h (floor effort-in-minutes
60))
478 (effort-m (- effort-in-minutes
(* effort-h
60)))
481 (format org-time-clocksum-format h m
)
482 'face
(if (and org-task-overrun
(not org-task-overrun-text
))
483 'org-mode-line-clock-overrun
'org-mode-line-clock
)))
484 (effort-str (format org-time-clocksum-format effort-h effort-m
))
485 (clockstr (org-propertize
486 (concat "[%s/" effort-str
487 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading
) ")")
488 'face
'org-mode-line-clock
)))
489 (format clockstr work-done-str
))
490 (org-propertize (format
491 (concat "[" org-time-clocksum-format
" (%s)]")
492 h m org-clock-heading
)
493 'face
'org-mode-line-clock
))))
495 (defun org-clock-update-mode-line ()
497 (org-clock-notify-once-if-expired)
498 (setq org-task-overrun nil
))
499 (setq org-mode-line-string
501 (let ((clock-string (org-clock-get-clock-string))
502 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
503 (if (and (> org-clock-string-limit
0)
504 (> (length clock-string
) org-clock-string-limit
))
506 (substring clock-string
0 org-clock-string-limit
)
507 'help-echo
(concat help-text
": " org-clock-heading
))
508 (org-propertize clock-string
'help-echo help-text
)))
509 'local-map org-clock-mode-line-map
510 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)
512 (if (and org-task-overrun org-task-overrun-text
)
513 (setq org-mode-line-string
514 (concat (org-propertize
515 org-task-overrun-text
516 'face
'org-mode-line-clock-overrun
) org-mode-line-string
)))
517 (force-mode-line-update))
519 (defun org-clock-get-clocked-time ()
520 "Get the clocked time for the current item in minutes.
521 The time returned includes the time spent on this task in
522 previous clocking intervals."
523 (let ((currently-clocked-time
524 (floor (- (org-float-time)
525 (org-float-time org-clock-start-time
)) 60)))
526 (+ currently-clocked-time
(or org-clock-total-time
0))))
528 (defun org-clock-modify-effort-estimate (&optional value
)
529 "Add to or set the effort estimate of the item currently being clocked.
530 VALUE can be a number of minutes, or a string with format hh:mm or mm.
531 When the string starts with a + or a - sign, the current value of the effort
532 property will be changed by that amount.
533 This will update the \"Effort\" property of currently clocked item, and
536 (when (org-clock-is-active)
537 (let ((current org-clock-effort
) sign
)
539 ;; Prompt user for a value or a change
542 (format "Set effort (hh:mm or mm%s): "
544 (format ", prefix + to add to %s" org-clock-effort
)
546 (when (stringp value
)
547 ;; A string. See if it is a delta
548 (setq sign
(string-to-char value
))
549 (if (member sign
'(?- ?
+))
550 (setq current
(org-hh:mm-string-to-minutes current
)
551 value
(substring value
1))
553 (setq value
(org-hh:mm-string-to-minutes value
))
555 (setq value
(- current value
))
556 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
557 (setq value
(max 0 value
)
558 org-clock-effort
(org-minutes-to-hh:mm-string value
))
559 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
560 (org-clock-update-mode-line)
561 (message "Effort is now %s" org-clock-effort
))))
563 (defvar org-clock-notification-was-shown nil
564 "Shows if we have shown notification already.")
566 (defun org-clock-notify-once-if-expired ()
567 "Show notification if we spent more time than we estimated before.
568 Notification is shown only once."
569 (when (org-clocking-p)
570 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort
))
571 (clocked-time (org-clock-get-clocked-time)))
572 (if (setq org-task-overrun
573 (if (or (null effort-in-minutes
) (zerop effort-in-minutes
))
575 (>= clocked-time effort-in-minutes
)))
576 (unless org-clock-notification-was-shown
577 (setq org-clock-notification-was-shown t
)
579 (format "Task '%s' should be finished by now. (%s)"
580 org-clock-heading org-clock-effort
) t
))
581 (setq org-clock-notification-was-shown nil
)))))
583 (defun org-notify (notification &optional play-sound
)
584 "Send a NOTIFICATION and maybe PLAY-SOUND."
585 (org-show-notification notification
)
586 (if play-sound
(org-clock-play-sound)))
588 (defun org-show-notification (notification)
590 Use `org-show-notification-handler' if defined,
591 use libnotify if available, or fall back on a message."
592 (cond ((functionp org-show-notification-handler
)
593 (funcall org-show-notification-handler notification
))
594 ((stringp org-show-notification-handler
)
595 (start-process "emacs-timer-notification" nil
596 org-show-notification-handler notification
))
597 ((featurep 'notifications
)
598 (require 'notifications
)
599 (notifications-notify
600 :title
"Org-mode message"
602 ;; FIXME how to link to the Org icon?
603 ;; :app-icon "~/.emacs.d/icons/mail.png"
605 ((org-program-exists "notify-send")
606 (start-process "emacs-timer-notification" nil
607 "notify-send" notification
))
608 ;; Maybe the handler will send a message, so only use message as
609 ;; a fall back option
610 (t (message "%s" notification
))))
612 (defun org-clock-play-sound ()
613 "Play sound as configured by `org-clock-sound'.
614 Use alsa's aplay tool if available."
616 ((not org-clock-sound
))
617 ((eq org-clock-sound t
) (beep t
) (beep t
))
618 ((stringp org-clock-sound
)
619 (let ((file (expand-file-name org-clock-sound
)))
620 (if (file-exists-p file
)
621 (if (org-program-exists "aplay")
622 (start-process "org-clock-play-notification" nil
625 (play-sound-file file
)
626 (error (beep t
) (beep t
)))))))))
628 (defun org-program-exists (program-name)
629 "Checks whenever we can locate program and launch it."
630 (if (eq system-type
'gnu
/linux
)
631 (= 0 (call-process "which" nil nil nil program-name
))))
633 (defvar org-clock-mode-line-entry nil
634 "Information for the modeline about the running clock.")
636 (defun org-find-open-clocks (file)
637 "Search through the given file and find all open clocks."
638 (let ((buf (or (get-file-buffer file
)
639 (find-file-noselect file
)))
641 (with-current-buffer buf
643 (goto-char (point-min))
644 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t
)
645 (push (cons (copy-marker (match-end 1) t
)
646 (org-time-string-to-time (match-string 1))) clocks
))))
649 (defsubst org-is-active-clock
(clock)
650 "Return t if CLOCK is the currently active clock."
651 (and (org-clock-is-active)
652 (= org-clock-marker
(car clock
))))
654 (defmacro org-with-clock-position
(clock &rest forms
)
655 "Evaluate FORMS with CLOCK as the current active clock."
656 `(with-current-buffer (marker-buffer (car ,clock
))
660 (goto-char (car ,clock
))
664 (put 'org-with-clock-position
'lisp-indent-function
1)
666 (defmacro org-with-clock
(clock &rest forms
)
667 "Evaluate FORMS with CLOCK as the current active clock.
668 This macro also protects the current active clock from being altered."
669 `(org-with-clock-position ,clock
670 (let ((org-clock-start-time (cdr ,clock
))
671 (org-clock-total-time)
674 (org-clock-marker (car ,clock
))
675 (org-clock-hd-marker (save-excursion
676 (outline-back-to-heading t
)
680 (put 'org-with-clock
'lisp-indent-function
1)
682 (defsubst org-clock-clock-in
(clock &optional resume start-time
)
683 "Clock in to the clock located by CLOCK.
684 If necessary, clock-out of the currently active clock."
685 (org-with-clock-position clock
686 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
687 (org-clock-in nil start-time
))))
689 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
690 "Clock out of the clock located by CLOCK."
691 (let ((temp (copy-marker (car clock
)
692 (marker-insertion-type (car clock
)))))
693 (if (org-is-active-clock clock
)
694 (org-clock-out fail-quietly at-time
)
695 (org-with-clock clock
696 (org-clock-out fail-quietly at-time
)))
697 (setcar clock temp
)))
699 (defsubst org-clock-clock-cancel
(clock)
700 "Cancel the clock located by CLOCK."
701 (let ((temp (copy-marker (car clock
)
702 (marker-insertion-type (car clock
)))))
703 (if (org-is-active-clock clock
)
705 (org-with-clock clock
707 (setcar clock temp
)))
709 (defvar org-clock-clocking-in nil
)
710 (defvar org-clock-resolving-clocks nil
)
711 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
713 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
714 &optional close-p restart-p fail-quietly
)
715 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
716 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
717 (let ((org-clock-resolving-clocks t
))
720 (org-clock-clock-cancel clock
)
721 (if (and restart-p
(not org-clock-clocking-in
))
722 (org-clock-clock-in clock
)))
724 ((eq resolve-to
'now
)
726 (error "RESTART-P is not valid here"))
727 (if (or close-p org-clock-clocking-in
)
728 (org-clock-clock-out clock fail-quietly
)
729 (unless (org-is-active-clock clock
)
730 (org-clock-clock-in clock t
))))
732 ((not (time-less-p resolve-to
(current-time)))
733 (error "RESOLVE-TO must refer to a time in the past"))
737 (error "RESTART-P is not valid here"))
738 (org-clock-clock-out clock fail-quietly
(or clock-out-time
740 (unless org-clock-clocking-in
742 (setq org-clock-leftover-time
(and (null clock-out-time
)
744 (org-clock-clock-in clock nil
(and clock-out-time
747 (defun org-clock-jump-to-current-clock (&optional effective-clock
)
749 (let ((clock (or effective-clock
(cons org-clock-marker
750 org-clock-start-time
))))
751 (unless (marker-buffer (car clock
))
752 (error "No clock is currently running"))
753 (org-with-clock clock
(org-clock-goto))
754 (with-current-buffer (marker-buffer (car clock
))
755 (goto-char (car clock
))
756 (if org-clock-into-drawer
758 (if (stringp org-clock-into-drawer
)
759 (concat ":" org-clock-into-drawer
":")
764 (outline-back-to-heading t
)
765 (search-forward logbook
)
766 (goto-char (match-beginning 0)))
768 (outline-back-to-heading t
)
769 (search-forward logbook
)
770 (search-forward ":END:")
771 (goto-char (match-end 0)))
774 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
775 "Resolve an open org-mode clock.
776 An open clock was found, with `dangling' possibly being non-nil.
777 If this function was invoked with a prefix argument, non-dangling
778 open clocks are ignored. The given clock requires some sort of
779 user intervention to resolve it, either because a clock was left
780 dangling or due to an idle timeout. The clock resolution can
783 (a) deleted, the user doesn't care about the clock
784 (b) restarted from the current time (if no other clock is open)
785 (c) closed, giving the clock X minutes
786 (d) closed and then restarted
787 (e) resumed, as if the user had never left
789 The format of clock is (CONS MARKER START-TIME), where MARKER
790 identifies the buffer and position the clock is open at (and
791 thus, the heading it's under), and START-TIME is when the clock
795 (save-window-excursion
797 (unless org-clock-resolving-clocks-due-to-idleness
798 (org-clock-jump-to-current-clock clock
))
799 (unless org-clock-resolve-expert
800 (with-output-to-temp-buffer "*Org Clock*"
801 (princ "Select a Clock Resolution Command:
803 i/q/C-g Ignore this question; the same as keeping all the idle time.
805 k/K Keep X minutes of the idle time (default is all). If this
806 amount is less than the default, you will be clocked out
807 that many minutes after the time that idling began, and then
808 clocked back in at the present time.
809 g/G Indicate that you \"got back\" X minutes ago. This is quite
810 different from 'k': it clocks you out from the beginning of
811 the idle period and clock you back in X minutes ago.
812 s/S Subtract the idle time from the current clock. This is the
813 same as keeping 0 minutes.
814 C Cancel the open timer altogether. It will be as though you
816 j/J Jump to the current clock, to make manual adjustments.
818 For all these options, using uppercase makes your final state
819 to be CLOCKED OUT.")))
820 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
822 (when (featurep 'xemacs
)
823 (message (concat (funcall prompt-fn clock
)
825 (setq char-pressed
(read-char-exclusive)))
826 (while (or (null char-pressed
)
827 (and (not (memq char-pressed
828 '(?k ?K ?g ?G ?s ?S ?C
832 (read-char (concat (funcall prompt-fn clock
)
835 (and (not (memq char-pressed
'(?i ?q
))) char-pressed
)))))
837 (floor (/ (org-float-time
838 (time-subtract (current-time) last-valid
)) 60)))
840 (and (memq ch
'(?k ?K
))
841 (read-number "Keep how many minutes? " default
)))
843 (and (memq ch
'(?g ?G
))
844 (read-number "Got back how many minutes ago? " default
)))
845 (subtractp (memq ch
'(?s ?S
)))
846 (barely-started-p (< (- (org-float-time last-valid
)
847 (org-float-time (cdr clock
))) 45))
848 (start-over (and subtractp barely-started-p
)))
852 (org-clock-resolve-clock clock
'now nil t nil fail-quietly
))
853 (org-clock-jump-to-current-clock clock
))
855 (not (memq ch
'(?k ?K ?g ?G ?s ?S ?C
))))
858 (org-clock-resolve-clock
861 ;; If the time on the clock was less than a minute before
862 ;; the user went away, and they've ask to subtract all the
867 (and gotback
(= gotback
0)))
869 ((or (and keep
(= keep default
))
870 (and gotback
(= gotback default
)))
873 (time-add last-valid
(seconds-to-time (* 60 keep
))))
875 (time-subtract (current-time)
876 (seconds-to-time (* 60 gotback
))))
878 (error "Unexpected, please report this as a bug")))
879 (and gotback last-valid
)
880 (memq ch
'(?K ?G ?S
))
882 (not (memq ch
'(?K ?G ?S ?C
))))
885 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid
)
886 "Resolve all currently open org-mode clocks.
887 If `only-dangling-p' is non-nil, only ask to resolve dangling
888 \(i.e., not currently open and valid) clocks."
890 (unless org-clock-resolving-clocks
891 (let ((org-clock-resolving-clocks t
))
892 (dolist (file (org-files-list))
893 (let ((clocks (org-find-open-clocks file
)))
894 (dolist (clock clocks
)
895 (let ((dangling (or (not (org-clock-is-active))
896 (/= (car clock
) org-clock-marker
))))
897 (if (or (not only-dangling-p
) dangling
)
904 "Dangling clock started %d mins ago"
906 (/ (- (org-float-time (current-time))
907 (org-float-time (cdr clock
))) 60))))))
909 (cdr clock
)))))))))))
911 (defun org-emacs-idle-seconds ()
912 "Return the current Emacs idle time in seconds, or nil if not idle."
913 (let ((idle-time (current-idle-time)))
915 (org-float-time idle-time
)
918 (defun org-mac-idle-seconds ()
919 "Return the current Mac idle time in seconds."
920 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
922 (defun org-x11-idle-seconds ()
923 "Return the current X11 idle time in seconds."
924 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
926 (defun org-user-idle-seconds ()
927 "Return the number of seconds the user has been idle for.
928 This routine returns a floating point number."
930 ((eq system-type
'darwin
)
931 (org-mac-idle-seconds))
932 ((eq window-system
'x
)
933 (org-x11-idle-seconds))
935 (org-emacs-idle-seconds))))
937 (defvar org-clock-user-idle-seconds
)
939 (defun org-resolve-clocks-if-idle ()
940 "Resolve all currently open org-mode clocks.
941 This is performed after `org-clock-idle-time' minutes, to check
942 if the user really wants to stay clocked in after being idle for
944 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
946 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
947 (org-clock-user-idle-start
948 (time-subtract (current-time)
949 (seconds-to-time org-clock-user-idle-seconds
)))
950 (org-clock-resolving-clocks-due-to-idleness t
))
951 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
953 (cons org-clock-marker
954 org-clock-start-time
)
957 (format "Clocked in & idle for %.1f mins"
959 (time-subtract (current-time)
960 org-clock-user-idle-start
))
962 org-clock-user-idle-start
)))))
964 (defun org-clock-in (&optional select start-time
)
965 "Start the clock on the current item.
966 If necessary, clock-out of the currently active clock.
967 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
968 recently clocked tasks to
969 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
970 clock into the current task and mark
971 is as the default task, a special task that will always be offered in
972 the clocking selection, associated with the letter `d'."
974 (setq org-clock-notification-was-shown nil
)
976 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
978 ts selected-task target-pos
(msg-extra "")
979 (leftover (and (not org-clock-resolving-clocks
)
980 org-clock-leftover-time
)))
981 (when (and org-clock-auto-clock-resolution
982 (or (not interrupting
)
983 (eq t org-clock-auto-clock-resolution
))
984 (not org-clock-clocking-in
)
985 (not org-clock-resolving-clocks
))
986 (setq org-clock-leftover-time nil
)
987 (let ((org-clock-clocking-in t
))
988 (org-resolve-clocks))) ; check if any clocks are dangling
989 (when (equal select
'(4))
990 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
992 (setq selected-task
(copy-marker selected-task
))
995 ;; We are interrupting the clocking of a different task.
996 ;; Save a marker to this task, so that we can go back.
997 ;; First check if we are trying to clock into the same task!
998 (when (save-excursion
999 (unless selected-task
1000 (org-back-to-heading t
))
1001 (and (equal (marker-buffer org-clock-hd-marker
)
1003 (marker-buffer selected-task
)
1005 (= (marker-position org-clock-hd-marker
)
1007 (marker-position selected-task
)
1009 (message "Clock continues in \"%s\"" org-clock-heading
)
1011 (move-marker org-clock-interrupted-task
1012 (marker-position org-clock-marker
)
1013 (marker-buffer org-clock-marker
))
1014 (let ((org-clock-clocking-in t
))
1017 (when (equal select
'(16))
1018 ;; Mark as default clocking task
1019 (org-clock-mark-default-task))
1021 ;; Clock in at which position?
1023 (if (and (eobp) (not (org-on-heading-p)))
1026 (run-hooks 'org-clock-in-prepare-hook
)
1028 (when (and selected-task
(marker-buffer selected-task
))
1029 ;; There is a selected task, move to the correct buffer
1030 ;; and set the new target position.
1031 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
1032 (setq target-pos
(marker-position selected-task
))
1033 (move-marker selected-task nil
))
1037 (goto-char target-pos
)
1038 (org-back-to-heading t
)
1039 (or interrupting
(move-marker org-clock-interrupted-task nil
))
1040 (org-clock-history-push)
1041 (org-clock-set-current)
1042 (cond ((functionp org-clock-in-switch-to-state
)
1043 (looking-at org-complex-heading-regexp
)
1044 (let ((newstate (funcall org-clock-in-switch-to-state
1046 (if newstate
(org-todo newstate
))))
1047 ((and org-clock-in-switch-to-state
1048 (not (looking-at (concat outline-regexp
"[ \t]*"
1049 org-clock-in-switch-to-state
1051 (org-todo org-clock-in-switch-to-state
)))
1052 (setq org-clock-heading-for-remember
1053 (and (looking-at org-complex-heading-regexp
)
1055 (org-trim (buffer-substring (match-end 1)
1057 (setq org-clock-heading
1058 (cond ((and org-clock-heading-function
1059 (functionp org-clock-heading-function
))
1060 (funcall org-clock-heading-function
))
1061 ((looking-at org-complex-heading-regexp
)
1062 (replace-regexp-in-string
1063 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1066 (setq org-clock-heading
(org-propertize org-clock-heading
1068 (org-clock-find-position org-clock-in-resume
)
1070 ((and org-clock-in-resume
1072 (concat "^[ \t]* " org-clock-string
1073 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1074 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1075 (message "Matched %s" (match-string 1))
1076 (setq ts
(concat "[" (match-string 1) "]"))
1077 (goto-char (match-end 1))
1078 (setq org-clock-start-time
1080 (org-parse-time-string (match-string 1))))
1081 (setq org-clock-effort
(org-get-effort))
1082 (setq org-clock-total-time
(org-clock-sum-current-item
1083 (org-clock-get-sum-start))))
1084 ((eq org-clock-in-resume
'auto-restart
)
1085 ;; called from org-clock-load during startup,
1086 ;; do not interrupt, but warn!
1087 (message "Cannot restart clock because task does not contain unfinished clock")
1092 (insert-before-markers "\n")
1094 (org-indent-line-function)
1095 (when (and (save-excursion
1098 (beginning-of-line 1)
1099 (org-indent-line-to (- (org-get-indentation) 2)))
1100 (insert org-clock-string
" ")
1101 (setq org-clock-effort
(org-get-effort))
1102 (setq org-clock-total-time
(org-clock-sum-current-item
1103 (org-clock-get-sum-start)))
1104 (setq org-clock-start-time
1108 "You stopped another clock %d mins ago; start this one from then? "
1109 (/ (- (org-float-time (current-time))
1110 (org-float-time leftover
)) 60)))
1114 (setq ts
(org-insert-time-stamp org-clock-start-time
1115 'with-hm
'inactive
))))
1116 (move-marker org-clock-marker
(point) (buffer-base-buffer))
1117 (move-marker org-clock-hd-marker
1118 (save-excursion (org-back-to-heading t
) (point))
1119 (buffer-base-buffer))
1120 (setq org-clock-has-been-used t
)
1121 (or global-mode-string
(setq global-mode-string
'("")))
1122 (or (memq 'org-mode-line-string global-mode-string
)
1123 (setq global-mode-string
1124 (append global-mode-string
'(org-mode-line-string))))
1125 (org-clock-update-mode-line)
1126 (when org-clock-mode-line-timer
1127 (cancel-timer org-clock-mode-line-timer
)
1128 (setq org-clock-mode-line-timer nil
))
1129 (setq org-clock-mode-line-timer
1130 (run-with-timer org-clock-update-period
1131 org-clock-update-period
1132 'org-clock-update-mode-line
))
1133 (when org-clock-idle-timer
1134 (cancel-timer org-clock-idle-timer
)
1135 (setq org-clock-idle-timer nil
))
1136 (setq org-clock-idle-timer
1137 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
1138 (message "Clock starts at %s - %s" ts msg-extra
)
1139 (run-hooks 'org-clock-in-hook
)))))))
1141 (defvar org-clock-current-task nil
1142 "Task currently clocked in.")
1143 (defun org-clock-set-current ()
1144 "Set `org-clock-current-task' to the task currently clocked in."
1145 (setq org-clock-current-task
(nth 4 (org-heading-components))))
1147 (defun org-clock-delete-current ()
1148 "Reset `org-clock-current-task' to nil."
1149 (setq org-clock-current-task nil
))
1151 (defun org-clock-mark-default-task ()
1152 "Mark current task as default task."
1155 (org-back-to-heading t
)
1156 (move-marker org-clock-default-task
(point))))
1159 (defun org-clock-get-sum-start ()
1160 "Return the time from which clock times should be counted.
1161 This is for the currently running clock as it is displayed
1162 in the mode line. This function looks at the properties
1163 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1164 corresponding variable `org-clock-modeline-total' and then
1165 decides which time to use."
1166 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
1167 (symbol-name org-clock-modeline-total
)))
1168 (lr (org-entry-get nil
"LAST_REPEAT")))
1170 ((equal cmt
"current")
1171 (setq msg-extra
"showing time in current clock instance")
1173 ((equal cmt
"today")
1174 (setq msg-extra
"showing today's task time.")
1175 (let* ((dt (decode-time (current-time))))
1176 (setq dt
(append (list 0 0 0) (nthcdr 3 dt
)))
1177 (if org-extend-today-until
1178 (setf (nth 2 dt
) org-extend-today-until
))
1179 (apply 'encode-time dt
)))
1180 ((or (equal cmt
"all")
1181 (and (or (not cmt
) (equal cmt
"auto"))
1183 (setq msg-extra
"showing entire task time.")
1185 ((or (equal cmt
"repeat")
1186 (and (or (not cmt
) (equal cmt
"auto"))
1188 (setq msg-extra
"showing task time since last repeat.")
1191 (org-time-string-to-time lr
)))
1194 (defun org-clock-find-position (find-unclosed)
1195 "Find the location where the next clock line should be inserted.
1196 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1197 line and position cursor in that line."
1198 (org-back-to-heading t
)
1200 (let ((beg (save-excursion
1201 (beginning-of-line 2)
1202 (or (bolp) (newline))
1204 (end (progn (outline-next-heading) (point)))
1205 (re (concat "^[ \t]*" org-clock-string
))
1207 (drawer (if (stringp org-clock-into-drawer
)
1208 org-clock-into-drawer
"LOGBOOK"))
1209 first last ind-last
)
1211 (when (and find-unclosed
1213 (concat "^[ \t]* " org-clock-string
1214 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1215 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1217 (beginning-of-line 1)
1219 (when (eobp) (newline) (setq end
(max (point) end
)))
1220 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
1221 ;; we seem to have a CLOCK drawer, so go there.
1222 (beginning-of-line 2)
1223 (or org-log-states-order-reversed
1224 (and (re-search-forward org-property-end-re nil t
)
1225 (goto-char (match-beginning 0))))
1227 ;; Lets count the CLOCK lines
1229 (while (re-search-forward re end t
)
1230 (setq first
(or first
(match-beginning 0))
1231 last
(match-beginning 0)
1233 (when (and (integerp org-clock-into-drawer
)
1235 (>= (1+ cnt
) org-clock-into-drawer
))
1236 ;; Wrap current entries into a new drawer
1238 (setq ind-last
(org-get-indentation))
1239 (beginning-of-line 2)
1240 (if (and (>= (org-get-indentation) ind-last
)
1244 (beginning-of-line 0)
1245 (org-indent-line-to ind-last
)
1247 (insert ":" drawer
":\n")
1248 (beginning-of-line 0)
1249 (org-indent-line-function)
1251 (beginning-of-line 2)
1252 (or org-log-states-order-reversed
1253 (and (re-search-forward org-property-end-re nil t
)
1254 (goto-char (match-beginning 0))))
1258 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1259 (not (equal (match-string 1) org-clock-string
)))
1260 ;; Planning info, skip to after it
1261 (beginning-of-line 2)
1262 (or (bolp) (newline)))
1263 (when (or (eq org-clock-into-drawer t
)
1264 (stringp org-clock-into-drawer
)
1265 (and (integerp org-clock-into-drawer
)
1266 (< org-clock-into-drawer
2)))
1267 (insert ":" drawer
":\n:END:\n")
1268 (beginning-of-line -
1)
1269 (org-indent-line-function)
1271 (beginning-of-line 2)
1272 (org-indent-line-function)
1274 (or org-log-states-order-reversed
1275 (and (re-search-forward org-property-end-re nil t
)
1276 (goto-char (match-beginning 0))))))))
1278 (defun org-clock-out (&optional fail-quietly at-time
)
1279 "Stop the currently running clock.
1280 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1283 (when (not (org-clocking-p))
1284 (setq global-mode-string
1285 (delq 'org-mode-line-string global-mode-string
))
1286 (force-mode-line-update)
1287 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
1288 (let (ts te s h m remove
)
1289 (save-excursion ; Do not replace this with `with-current-buffer'.
1290 (with-no-warnings (set-buffer (org-clocking-buffer)))
1293 (goto-char org-clock-marker
)
1294 (beginning-of-line 1)
1295 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1296 (equal (match-string 1) org-clock-string
))
1297 (setq ts
(match-string 2))
1298 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1299 (goto-char (match-end 0))
1300 (delete-region (point) (point-at-eol))
1302 (setq te
(org-insert-time-stamp (or at-time
(current-time))
1303 'with-hm
'inactive
))
1304 (setq s
(- (org-float-time (apply 'encode-time
(org-parse-time-string te
)))
1305 (org-float-time (apply 'encode-time
(org-parse-time-string ts
))))
1306 h
(floor (/ s
3600))
1310 (insert " => " (format "%2d:%02d" h m
))
1311 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
1313 (beginning-of-line 1)
1314 (delete-region (point) (point-at-eol))
1315 (and (looking-at "\n") (> (point-max) (1+ (point)))
1317 (move-marker org-clock-marker nil
)
1318 (move-marker org-clock-hd-marker nil
)
1319 (when org-log-note-clock-out
1320 (org-add-log-setup 'clock-out nil nil nil nil
1321 (concat "# Task: " (org-get-heading t
) "\n\n")))
1322 (when org-clock-mode-line-timer
1323 (cancel-timer org-clock-mode-line-timer
)
1324 (setq org-clock-mode-line-timer nil
))
1325 (when org-clock-idle-timer
1326 (cancel-timer org-clock-idle-timer
)
1327 (setq org-clock-idle-timer nil
))
1328 (setq global-mode-string
1329 (delq 'org-mode-line-string global-mode-string
))
1330 (when org-clock-out-switch-to-state
1332 (org-back-to-heading t
)
1333 (let ((org-inhibit-logging t
)
1334 (org-clock-out-when-done nil
))
1336 ((functionp org-clock-out-switch-to-state
)
1337 (looking-at org-complex-heading-regexp
)
1338 (let ((newstate (funcall org-clock-out-switch-to-state
1340 (if newstate
(org-todo newstate
))))
1341 ((and org-clock-out-switch-to-state
1342 (not (looking-at (concat outline-regexp
"[ \t]*"
1343 org-clock-out-switch-to-state
1345 (org-todo org-clock-out-switch-to-state
))))))
1346 (force-mode-line-update)
1347 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
1348 (if remove
" => LINE REMOVED" ""))
1349 (run-hooks 'org-clock-out-hook
)
1350 (org-clock-delete-current))))))
1352 (defun org-clock-cancel ()
1353 "Cancel the running clock by removing the start timestamp."
1355 (when (not (org-clocking-p))
1356 (setq global-mode-string
1357 (delq 'org-mode-line-string global-mode-string
))
1358 (force-mode-line-update)
1359 (error "No active clock"))
1360 (save-excursion ; Do not replace this with `with-current-buffer'.
1361 (with-no-warnings (set-buffer (org-clocking-buffer)))
1362 (goto-char org-clock-marker
)
1363 (delete-region (1- (point-at-bol)) (point-at-eol))
1364 ;; Just in case, remove any empty LOGBOOK left over
1365 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1366 (move-marker org-clock-marker nil
)
1367 (move-marker org-clock-hd-marker nil
)
1368 (setq global-mode-string
1369 (delq 'org-mode-line-string global-mode-string
))
1370 (force-mode-line-update)
1371 (message "Clock canceled")
1372 (run-hooks 'org-clock-cancel-hook
))
1374 (defun org-clock-goto (&optional select
)
1375 "Go to the currently clocked-in entry, or to the most recently clocked one.
1376 With prefix arg SELECT, offer recently clocked tasks for selection."
1381 (or (org-clock-select-task "Select task to go to: ")
1382 (error "No task selected")))
1383 ((org-clocking-p) org-clock-marker
)
1384 ((and org-clock-goto-may-find-recent-task
1385 (car org-clock-history
)
1386 (marker-buffer (car org-clock-history
)))
1388 (car org-clock-history
))
1389 (t (error "No active or recent clock task")))))
1390 (switch-to-buffer (marker-buffer m
))
1391 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1394 (org-back-to-heading t
)
1395 (org-cycle-hide-drawers 'children
)
1399 (message "No running clock, this is the most recently clocked task"))
1400 (run-hooks 'org-clock-goto-hook
)))
1402 (defvar org-clock-file-total-minutes nil
1403 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1404 (make-variable-buffer-local 'org-clock-file-total-minutes
)
1406 (defun org-clock-sum (&optional tstart tend headline-filter
)
1407 "Sum the times for each subtree.
1408 Puts the resulting times in minutes as a text property on each headline.
1409 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1410 zero-arg function that, if specified, is called for each headline in the time
1411 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1412 nil are excluded from the clock summation."
1414 (let* ((bmp (buffer-modified-p))
1415 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1417 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1419 (ltimes (make-vector lmax
0))
1424 (if (stringp tstart
) (setq tstart
(org-time-string-to-seconds tstart
)))
1425 (if (stringp tend
) (setq tend
(org-time-string-to-seconds tend
)))
1426 (if (consp tstart
) (setq tstart
(org-float-time tstart
)))
1427 (if (consp tend
) (setq tend
(org-float-time tend
)))
1428 (remove-text-properties (point-min) (point-max)
1429 '(:org-clock-minutes t
1430 :org-clock-force-headline-inclusion t
))
1432 (goto-char (point-max))
1433 (while (re-search-backward re nil t
)
1437 (setq ts
(match-string 2)
1440 (apply 'encode-time
(org-parse-time-string ts
)))
1442 (apply 'encode-time
(org-parse-time-string te
)))
1443 ts
(if tstart
(max ts tstart
) ts
)
1444 te
(if tend
(min te tend
) te
)
1446 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
1449 (setq t1
(+ t1
(string-to-number (match-string 5))
1450 (* 60 (string-to-number (match-string 4))))))
1452 ;; Add the currently clocking item time to the total
1453 (when (and org-clock-report-include-clocking-task
1454 (equal (org-clocking-buffer) (current-buffer))
1455 (equal (marker-position org-clock-hd-marker
) (point))
1458 (>= (org-float-time org-clock-start-time
) tstart
)
1459 (<= (org-float-time org-clock-start-time
) tend
))
1460 (let ((time (floor (- (org-float-time)
1461 (org-float-time org-clock-start-time
)) 60)))
1462 (setq t1
(+ t1 time
))))
1463 (let* ((headline-forced
1464 (get-text-property (point)
1465 :org-clock-force-headline-inclusion
))
1467 (or (null headline-filter
)
1469 (save-match-data (funcall headline-filter
))))))
1470 (setq level
(- (match-end 1) (match-beginning 1)))
1471 (when (or (> t1
0) (> (aref ltimes level
) 0))
1472 (when (or headline-included headline-forced
)
1473 (if headline-included
1474 (loop for l from
0 to level do
1475 (aset ltimes l
(+ (aref ltimes l
) t1
))))
1476 (setq time
(aref ltimes level
))
1477 (goto-char (match-beginning 0))
1478 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)
1483 (> (funcall outline-level
) 1)
1484 (outline-up-heading 1 t
)
1486 (point) (point-at-eol)
1487 :org-clock-force-headline-inclusion t
))))))
1489 (loop for l from level to
(1- lmax
) do
1490 (aset ltimes l
0)))))))
1491 (setq org-clock-file-total-minutes
(aref ltimes
0)))
1492 (set-buffer-modified-p bmp
)))
1494 (defun org-clock-sum-current-item (&optional tstart
)
1495 "Return time, clocked on current item in total."
1498 (org-narrow-to-subtree)
1499 (org-clock-sum tstart
)
1500 org-clock-file-total-minutes
)))
1502 (defun org-clock-display (&optional total-only
)
1503 "Show subtree times in the entire buffer.
1504 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1507 (org-clock-remove-overlays)
1512 (goto-char (point-min))
1513 (while (or (and (equal (setq p
(point)) (point-min))
1514 (get-text-property p
:org-clock-minutes
))
1515 (setq p
(next-single-property-change
1516 (point) :org-clock-minutes
)))
1518 (when (setq time
(get-text-property p
:org-clock-minutes
))
1519 (org-clock-put-overlay time
(funcall outline-level
))))
1520 (setq h
(/ org-clock-file-total-minutes
60)
1521 m
(- org-clock-file-total-minutes
(* 60 h
)))
1522 ;; Arrange to remove the overlays upon next change.
1523 (when org-remove-highlights-with-change
1524 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
1526 (if org-time-clocksum-use-fractional
1527 (message (concat "Total file time: " org-time-clocksum-fractional-format
1528 " (%d hours and %d minutes)")
1529 (/ (+ (* h
60.0) m
) 60.0) h m
)
1530 (message (concat "Total file time: " org-time-clocksum-format
1531 " (%d hours and %d minutes)") h m h m
))))
1533 (defvar org-clock-overlays nil
)
1534 (make-variable-buffer-local 'org-clock-overlays
)
1536 (defun org-clock-put-overlay (time &optional level
)
1537 "Put an overlays on the current line, displaying TIME.
1538 If LEVEL is given, prefix time with a corresponding number of stars.
1539 This creates a new overlay and stores it in `org-clock-overlays', so that it
1540 will be easy to remove."
1541 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
1542 (l (if level
(org-get-valid-level level
0) 0))
1543 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1544 org-time-clocksum-fractional-format
1545 org-time-clocksum-format
) "%s"))
1548 (org-move-to-column c
)
1549 (unless (eolp) (skip-chars-backward "^ \t"))
1550 (skip-chars-backward " \t")
1551 (setq ov
(make-overlay (1- (point)) (point-at-eol))
1552 tx
(concat (buffer-substring (1- (point)) (point))
1553 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
1554 (org-add-props (if org-time-clocksum-use-fractional
1557 (/ (+ (* h
60.0) m
) 60.0)
1558 (make-string (- 16 l
) ?\
))
1560 (make-string l ?
*) h m
1561 (make-string (- 16 l
) ?\
)))
1562 (list 'face
'org-clock-overlay
))
1564 (if (not (featurep 'xemacs
))
1565 (overlay-put ov
'display tx
)
1566 (overlay-put ov
'invisible t
)
1567 (overlay-put ov
'end-glyph
(make-glyph tx
)))
1568 (push ov org-clock-overlays
)))
1570 (defun org-clock-remove-overlays (&optional beg end noremove
)
1571 "Remove the occur highlights from the buffer.
1572 BEG and END are ignored. If NOREMOVE is nil, remove this function
1573 from the `before-change-functions' in the current buffer."
1575 (unless org-inhibit-highlight-removal
1576 (mapc 'delete-overlay org-clock-overlays
)
1577 (setq org-clock-overlays nil
)
1579 (remove-hook 'before-change-functions
1580 'org-clock-remove-overlays
'local
))))
1582 (defvar state
) ;; dynamically scoped into this function
1583 (defun org-clock-out-if-current ()
1584 "Clock out if the current entry contains the running clock.
1585 This is used to stop the clock after a TODO entry is marked DONE,
1586 and is only done if the variable `org-clock-out-when-done' is not nil."
1587 (when (and org-clock-out-when-done
1588 (or (and (eq t org-clock-out-when-done
)
1589 (member state org-done-keywords
))
1590 (and (listp org-clock-out-when-done
)
1591 (member state org-clock-out-when-done
)))
1592 (equal (or (buffer-base-buffer (org-clocking-buffer))
1593 (org-clocking-buffer))
1594 (or (buffer-base-buffer (current-buffer))
1596 (< (point) org-clock-marker
)
1597 (> (save-excursion (outline-next-heading) (point))
1599 ;; Clock out, but don't accept a logging message for this.
1600 (let ((org-log-note-clock-out nil
)
1601 (org-clock-out-switch-to-state nil
))
1604 (add-hook 'org-after-todo-state-change-hook
1605 'org-clock-out-if-current
)
1608 (defun org-get-clocktable (&rest props
)
1609 "Get a formatted clocktable with parameters according to PROPS.
1610 The table is created in a temporary buffer, fully formatted and
1611 fontified, and then returned."
1613 (setq props
(plist-put props
:name
"clocktable"))
1614 (unless (plist-member props
:maxlevel
)
1615 (setq props
(plist-put props
:maxlevel
2)))
1616 (unless (plist-member props
:scope
)
1617 (setq props
(plist-put props
:scope
'agenda
)))
1620 (org-create-dblock props
)
1622 (font-lock-fontify-buffer)
1624 (buffer-substring (point) (progn
1625 (re-search-forward "^[ \t]*#\\+END" nil t
)
1628 (defun org-clock-report (&optional arg
)
1629 "Create a table containing a report about clocked time.
1630 If the cursor is inside an existing clocktable block, then the table
1631 will be updated. If not, a new clocktable will be inserted.
1632 When called with a prefix argument, move to the first clock table in the
1633 buffer and update it."
1635 (org-clock-remove-overlays)
1637 (org-find-dblock "clocktable")
1639 (if (org-in-clocktable-p)
1640 (goto-char (org-in-clocktable-p))
1641 (org-create-dblock (append (list :name
"clocktable")
1642 org-clock-clocktable-default-properties
)))
1643 (org-update-dblock))
1645 (defun org-in-clocktable-p ()
1646 "Check if the cursor is in a clocktable."
1647 (let ((pos (point)) start
)
1650 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t
)
1651 (setq start
(match-beginning 0))
1652 (re-search-forward "^[ \t]*#\\+END:.*" nil t
)
1653 (>= (match-end 0) pos
)
1656 (defun org-day-of-week (day month year
)
1657 "Returns the day of the week as an integer."
1661 (format "%d-%02d-%02dT00:00:00" year month day
)))))
1663 (defun org-quarter-to-date (quarter year
)
1664 "Get the date (week day year) of the first day of a given quarter."
1668 (setq startday
(org-day-of-week 1 1 year
))
1671 (list 52 7 (- year
1)))
1673 (list 52 6 (- year
1)))
1675 (list 1 startday year
))
1677 (list 53 startday
(- year
1)))
1681 (setq startday
(org-day-of-week 1 4 year
))
1684 (list 13 startday year
))
1686 (list 14 startday year
))
1688 (list 13 startday year
))
1692 (setq startday
(org-day-of-week 1 7 year
))
1695 (list 26 startday year
))
1697 (list 27 startday year
))
1699 (list 26 startday year
))
1703 (setq startday
(org-day-of-week 1 10 year
))
1706 (list 39 startday year
))
1708 (list 40 startday year
))
1710 (list 39 startday year
)))))))
1712 (defun org-clock-special-range (key &optional time as-strings
)
1713 "Return two times bordering a special time range.
1714 Key is a symbol specifying the range and can be one of `today', `yesterday',
1715 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1716 A week starts Monday 0:00 and ends Sunday 24:00.
1717 The range is determined relative to TIME. TIME defaults to the current time.
1718 The return value is a cons cell with two internal times like the ones
1719 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1720 the returned times will be formatted strings."
1721 (if (integerp key
) (setq key
(intern (number-to-string key
))))
1722 (let* ((tm (decode-time (or time
(current-time))))
1723 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
1724 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
1726 (skey (symbol-name key
))
1728 (q (cond ((>= (nth 4 tm
) 10) 4)
1729 ((>= (nth 4 tm
) 7) 3)
1730 ((>= (nth 4 tm
) 4) 2)
1731 ((>= (nth 4 tm
) 1) 1)))
1732 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1733 interval tmp shiftedy shiftedm shiftedq
)
1735 ((string-match "^[0-9]+$" skey
)
1736 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
1737 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1738 (setq y
(string-to-number (match-string 1 skey
))
1739 month
(string-to-number (match-string 2 skey
))
1741 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
1743 (setq y
(string-to-number (match-string 1 skey
))
1744 w
(string-to-number (match-string 2 skey
)))
1745 (setq date
(calendar-gregorian-from-absolute
1746 (calendar-absolute-from-iso (list w
1 y
))))
1747 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1750 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey
)
1752 (setq y
(string-to-number (match-string 1 skey
)))
1753 (setq q
(string-to-number (match-string 2 skey
)))
1754 (setq date
(calendar-gregorian-from-absolute
1755 (calendar-absolute-from-iso (org-quarter-to-date q y
))))
1756 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1759 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1760 (setq y
(string-to-number (match-string 1 skey
))
1761 month
(string-to-number (match-string 2 skey
))
1762 d
(string-to-number (match-string 3 skey
))
1764 ((string-match "\\([-+][0-9]+\\)$" skey
)
1765 (setq shift
(string-to-number (match-string 1 skey
))
1766 key
(intern (substring skey
0 (match-beginning 1))))
1767 (if(and (memq key
'(quarter thisq
)) (> shift
0))
1768 (error "Looking forward with quarters isn't implemented.")
1772 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
1773 ((eq key
'lastweek
) (setq key
'week shift -
1))
1774 ((eq key
'lastmonth
) (setq key
'month shift -
1))
1775 ((eq key
'lastyear
) (setq key
'year shift -
1))
1776 ((eq key
'lastq
) (setq key
'quarter shift -
1))))
1778 ((memq key
'(day today
))
1779 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
1780 ((memq key
'(week thisweek
))
1781 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
1782 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
1783 ((memq key
'(month thismonth
))
1784 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
1785 ((memq key
'(quarter thisq
))
1786 ; compute if this shift remains in this year
1787 ; if not, compute how many years and quarters we have to shift (via floor*)
1788 ; and compute the shifted years, months and quarters
1790 ((< (+ (- q
1) shift
) 0) ; shift not in this year
1791 (setq interval
(* -
1 (+ (- q
1) shift
)))
1792 ; set tmp to ((years to shift) (quarters to shift))
1793 (setq tmp
(org-floor* interval
4))
1794 ; due to the use of floor, 0 quarters actually means 4
1795 (if (= 0 (nth 1 tmp
))
1796 (setq shiftedy
(- y
(nth 0 tmp
))
1799 (setq shiftedy
(- y
(+ 1 (nth 0 tmp
)))
1800 shiftedm
(- 13 (* 3 (nth 1 tmp
)))
1801 shiftedq
(- 5 (nth 1 tmp
))))
1802 (setq d
1 h
0 m
0 d1
1 month shiftedm month1
(+ 3 shiftedm
) h1
0 m1
0 y shiftedy
))
1803 ((> (+ q shift
) 0) ; shift is whitin this year
1804 (setq shiftedq
(+ q shift
))
1806 (setq d
1 h
0 m
0 d1
1 month
(+ 1 (* 3 (- (+ q shift
) 1))) month1
(+ 4 (* 3 (- (+ q shift
) 1))) h1
0 m1
0))))
1807 ((memq key
'(year thisyear
))
1808 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
1809 (t (error "No such time block %s" key
)))
1810 (setq ts
(encode-time s m h d month y
)
1811 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
1812 (or d1 d
) (or month1 month
) (or y1 y
)))
1813 (setq fm
(cdr org-time-stamp-formats
))
1815 ((memq key
'(day today
))
1816 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
1817 ((memq key
'(week thisweek
))
1818 (setq txt
(format-time-string "week %G-W%V" ts
)))
1819 ((memq key
'(month thismonth
))
1820 (setq txt
(format-time-string "%B %Y" ts
)))
1821 ((memq key
'(year thisyear
))
1822 (setq txt
(format-time-string "the year %Y" ts
)))
1823 ((memq key
'(quarter thisq
))
1824 (setq txt
(concatenate 'string
(org-count-quarter shiftedq
) " quarter of " (number-to-string shiftedy
))))
1827 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
1830 (defun org-count-quarter (n)
1837 (defun org-clocktable-shift (dir n
)
1838 "Try to shift the :block date of the clocktable at point.
1839 Point must be in the #+BEGIN: line of a clocktable, or this function
1840 will throw an error.
1841 DIR is a direction, a symbol `left', `right', `up', or `down'.
1842 Both `left' and `down' shift the block toward the past, `up' and `right'
1843 push it toward the future.
1844 N is the number of shift steps to take. The size of the step depends on
1845 the currently selected interval size."
1846 (setq n
(prefix-numeric-value n
))
1847 (and (memq dir
'(left down
)) (setq n
(- n
)))
1849 (goto-char (point-at-bol))
1850 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1851 (error "Line needs a :block definition before this command works")
1852 (let* ((b (match-beginning 1)) (e (match-end 1))
1853 (s (match-string 1))
1854 block shift ins y mw d date wp m
)
1856 ((equal s
"yesterday") (setq s
"today-1"))
1857 ((equal s
"lastweek") (setq s
"thisweek-1"))
1858 ((equal s
"lastmonth") (setq s
"thismonth-1"))
1859 ((equal s
"lastyear") (setq s
"thisyear-1"))
1860 ((equal s
"lastq") (setq s
"thisq-1")))
1863 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s
)
1864 (setq block
(match-string 1 s
)
1865 shift
(if (match-end 2)
1866 (string-to-number (match-string 2 s
))
1868 (setq shift
(+ shift n
))
1869 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
1870 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
1871 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1872 (setq y
(string-to-number (match-string 1 s
))
1873 wp
(and (match-end 3) (match-string 3 s
))
1874 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
1875 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
1877 (d (setq ins
(format-time-string
1879 (encode-time 0 0 0 (+ d n
) m y
))))
1880 ((and wp
(string-match "w\\|W" wp
) mw
(> (length wp
) 0))
1882 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
1883 (setq ins
(format-time-string
1885 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1886 ((and wp
(string-match "q\\|Q" wp
) mw
(> (length wp
) 0))
1888 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
1893 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
1898 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (org-quarter-to-date (+ mw n
) y
))))
1899 (setq ins
(format-time-string
1900 (concatenate 'string
(number-to-string y
) "-Q" (number-to-string (+ mw n
)))
1901 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1903 (setq ins
(format-time-string
1905 (encode-time 0 0 0 1 (+ mw n
) y
))))
1907 (setq ins
(number-to-string (+ y n
))))))
1908 (t (error "Cannot shift clocktable block")))
1912 (delete-region (point) (+ (point) (- e b
)))
1913 (beginning-of-line 1)
1917 (defun org-dblock-write:clocktable
(params)
1918 "Write the standard clocktable."
1919 (setq params
(org-combine-plists org-clocktable-defaults params
))
1921 (let* ((scope (plist-get params
:scope
))
1922 (block (plist-get params
:block
))
1923 (ts (plist-get params
:tstart
))
1924 (te (plist-get params
:tend
))
1925 (link (plist-get params
:link
))
1926 (maxlevel (or (plist-get params
:maxlevel
) 3))
1927 (step (plist-get params
:step
))
1928 (timestamp (plist-get params
:timestamp
))
1929 (formatter (or (plist-get params
:formatter
)
1930 org-clock-clocktable-formatter
1931 'org-clocktable-write-default
))
1932 cc range-text ipos pos one-file-with-archives
1933 scope-is-list tbls level
)
1935 ;; Check if we need to do steps
1937 ;; Get the range text for the header
1938 (setq cc
(org-clock-special-range block nil t
)
1939 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1941 ;; Write many tables, in steps
1942 (unless (or block
(and ts te
))
1943 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1944 (org-clocktable-steps params
)
1947 (setq ipos
(point)) ; remember the insertion position
1949 ;; Get the right scope
1952 ((and scope
(listp scope
) (symbolp (car scope
)))
1953 (setq scope
(eval scope
)))
1955 (setq scope
(org-agenda-files t
)))
1956 ((eq scope
'agenda-with-archives
)
1957 (setq scope
(org-agenda-files t
))
1958 (setq scope
(org-add-archive-files scope
)))
1959 ((eq scope
'file-with-archives
)
1960 (setq scope
(org-add-archive-files (list (buffer-file-name)))
1961 one-file-with-archives t
)))
1962 (setq scope-is-list
(and scope
(listp scope
)))
1964 ;; we collect from several files
1965 (let* ((files scope
)
1967 (org-prepare-agenda-buffers files
)
1968 (while (setq file
(pop files
))
1969 (with-current-buffer (find-buffer-visiting file
)
1972 (push (org-clock-get-table-data file params
) tbls
))))))
1973 ;; Just from the current file
1975 ;; get the right range into the restriction
1976 (org-prepare-agenda-buffers (list (buffer-file-name)))
1978 ((not scope
)) ; use the restriction as it is now
1979 ((eq scope
'file
) (widen))
1980 ((eq scope
'subtree
) (org-narrow-to-subtree))
1982 (while (org-up-heading-safe))
1983 (org-narrow-to-subtree))
1984 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
1985 (symbol-name scope
)))
1986 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
1988 (while (org-up-heading-safe)
1989 (looking-at outline-regexp
)
1990 (if (<= (org-reduced-level (funcall outline-level
)) level
)
1991 (throw 'exit nil
))))
1992 (org-narrow-to-subtree)))
1993 ;; do the table, with no file name.
1994 (push (org-clock-get-table-data nil params
) tbls
)))
1996 ;; OK, at this point we tbls as a list of tables, one per file
1997 (setq tbls
(nreverse tbls
))
1999 (setq params
(plist-put params
:multifile scope-is-list
))
2000 (setq params
(plist-put params
:one-file-with-archives
2001 one-file-with-archives
))
2003 (funcall formatter ipos tbls params
))))
2005 (defun org-clocktable-write-default (ipos tables params
)
2006 "Write out a clock table at position IPOS in the current buffer.
2007 TABLES is a list of tables with clocking data as produced by
2008 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2009 from the dynamic block defintion."
2010 ;; This function looks quite complicated, mainly because there are a lot
2011 ;; of options which can add or remove columns. I have massively commented
2012 ;; function, to I hope it is understandable. If someone want to write
2013 ;; there own special formatter, this maybe much easier because there can
2014 ;; be a fixed format with a well-defined number of columns...
2015 (let* ((hlchars '((1 .
"*") (2 .
"/")))
2016 (multifile (plist-get params
:multifile
))
2017 (block (plist-get params
:block
))
2018 (ts (plist-get params
:tstart
))
2019 (te (plist-get params
:tend
))
2020 (header (plist-get params
:header
))
2021 (narrow (plist-get params
:narrow
))
2022 (link (plist-get params
:link
))
2023 (maxlevel (or (plist-get params
:maxlevel
) 3))
2024 (emph (plist-get params
:emphasize
))
2025 (level-p (plist-get params
:level
))
2026 (timestamp (plist-get params
:timestamp
))
2027 (ntcol (max 1 (or (plist-get params
:tcolumns
) 100)))
2028 (rm-file-column (plist-get params
:one-file-with-archives
))
2029 (indent (plist-get params
:indent
))
2030 range-text total-time tbl level hlc formula pcol
2031 file-time entries entry headline
2032 recalc content narrow-cut-p tcol
)
2034 ;; Implement abbreviations
2035 (when (plist-get params
:compact
)
2036 (setq level nil indent t narrow
(or narrow
'40!) ntcol
1))
2038 ;; Some consistency test for parameters
2039 (unless (integerp ntcol
)
2040 (setq params
(plist-put params
:tcolumns
(setq ntcol
100))))
2042 (when (and narrow
(integerp narrow
) link
)
2043 ;; We cannot have both integer narrow and link
2045 "Using hard narrowing in clocktable to allow for links")
2046 (setq narrow
(intern (format "%d!" narrow
))))
2051 ((and (symbolp narrow
)
2052 (string-match "\\`[0-9]+!\\'" (symbol-name narrow
)))
2053 (setq narrow-cut-p t
2054 narrow
(string-to-number (substring (symbol-name narrow
)
2057 (error "Invalid value %s of :narrow property in clock table"
2061 ;; Get the range text for the header
2062 (setq range-text
(nth 2 (org-clock-special-range block nil t
))))
2064 ;; Compute the total time
2065 (setq total-time
(apply '+ (mapcar 'cadr tables
)))
2067 ;; Now we need to output this tsuff
2070 ;; Insert the text *before* the actual table
2071 (insert-before-markers
2073 ;; Format the standard header
2075 "Clock summary at ["
2077 (format-time-string (cdr org-time-stamp-formats
))
2080 (if block
(concat ", for " range-text
".") "")
2083 ;; Insert the narrowing line
2084 (when (and narrow
(integerp narrow
) (not narrow-cut-p
))
2085 (insert-before-markers
2086 "|" ; table line starter
2087 (if multifile
"|" "") ; file column, maybe
2088 (if level-p
"|" "") ; level column, maybe
2089 (if timestamp
"|" "") ; timestamp column, maybe
2090 (format "<%d>| |\n" narrow
))) ; headline and time columns
2092 ;; Insert the table header line
2093 (insert-before-markers
2094 "|" ; table line starter
2095 (if multifile
"File|" "") ; file column, maybe
2096 (if level-p
"L|" "") ; level column, maybe
2097 (if timestamp
"Timestamp|" "") ; timestamp column, maybe
2098 "Headline|Time|\n") ; headline and time columns
2100 ;; Insert the total time in the table
2101 (insert-before-markers
2103 "|" ; table line starter
2104 (if multifile
"| ALL " "") ; file column, maybe
2105 (if level-p
"|" "") ; level column, maybe
2106 (if timestamp
"|" "") ; timestamp column, maybe
2107 "*Total time*| " ; instead of a headline
2109 (org-minutes-to-hh:mm-string
(or total-time
0)) ; the time
2110 "*|\n") ; close line
2112 ;; Now iterate over the tables and insert the data
2113 ;; but only if any time has been collected
2114 (when (and total-time
(> total-time
0))
2116 (while (setq tbl
(pop tables
))
2117 ;; now tbl is the table resulting from one file.
2118 (setq file-time
(nth 1 tbl
))
2119 (when (or (and file-time
(> file-time
0))
2120 (not (plist-get params
:fileskip0
)))
2121 (insert-before-markers "|-\n") ; a hline because a new file starts
2122 ;; First the file time, if we have multiple files
2124 ;; Summarize the time colleted from this file
2125 (insert-before-markers
2126 (format "| %s %s | %s*File time* | *%s*|\n"
2127 (file-name-nondirectory (car tbl
))
2128 (if level-p
"| " "") ; level column, maybe
2129 (if timestamp
"| " "") ; timestamp column, maybe
2130 (org-minutes-to-hh:mm-string
(nth 1 tbl
))))) ; the time
2132 ;; Get the list of node entries and iterate over it
2133 (setq entries
(nth 2 tbl
))
2134 (while (setq entry
(pop entries
))
2135 (setq level
(car entry
)
2136 headline
(nth 1 entry
)
2137 hlc
(if emph
(or (cdr (assoc level hlchars
)) "") ""))
2139 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2144 (format "[[%s][%s]]"
2145 (match-string 1 headline
)
2146 (org-shorten-string (match-string 3 headline
)
2148 (setq headline
(org-shorten-string headline narrow
))))
2149 (insert-before-markers
2150 "|" ; start the table line
2151 (if multifile
"|" "") ; free space for file name column?
2152 (if level-p
(format "%d|" (car entry
)) "") ; level, maybe
2153 (if timestamp
(concat (nth 2 entry
) "|") "") ; timestamp, maybe
2154 (if indent
(org-clocktable-indent-string level
) "") ; indentation
2155 hlc headline hlc
"|" ; headline
2156 (make-string (min (1- ntcol
) (or (- level
1))) ?|
)
2157 ; empty fields for higher levels
2158 hlc
(org-minutes-to-hh:mm-string
(nth 3 entry
)) hlc
; time
2161 (backward-delete-char 1)
2162 (if (setq formula
(plist-get params
:formula
))
2165 ;; compute the column where the % numbers need to go
2170 (min maxlevel
(or ntcol
100))))
2171 ;; compute the column where the total time is
2175 (if timestamp
1 0)))
2178 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2179 pcol
; the column where the % numbers should go
2180 (if (and narrow
(not narrow-cut-p
)) 3 2) ; row of the total time
2181 tcol
; column of the total time
2182 tcol
(1- pcol
) ; range of columns where times can be found
2186 (insert "\n#+TBLFM: " formula
)
2188 (t (error "invalid formula in clocktable")))
2189 ;; Should we rescue an old formula?
2190 (when (stringp (setq content
(plist-get params
:content
)))
2191 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content
)
2193 (insert "\n" (match-string 1 (plist-get params
:content
)))
2194 (beginning-of-line 0))))
2195 ;; Back to beginning, align the table, recalculate if necessary
2197 (skip-chars-forward "^|")
2199 (when org-hide-emphasis-markers
2200 ;; we need to align a second time
2205 (if (and narrow
(not narrow-cut-p
)) (beginning-of-line 2))
2206 (org-table-goto-column pcol nil
'force
)
2208 (org-table-recalculate 'all
))
2209 (when rm-file-column
2210 ;; The file column is actually not wanted
2212 (org-table-delete-column))
2215 (defun org-clocktable-indent-string (level)
2220 (setq level
(1- level
)
2221 str
(concat str
"___")))
2224 (defun org-clocktable-steps (params)
2225 "Step through the range to make a number of clock tables."
2226 (let* ((p1 (copy-sequence params
))
2227 (ts (plist-get p1
:tstart
))
2228 (te (plist-get p1
:tend
))
2229 (step0 (plist-get p1
:step
))
2230 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
2231 (stepskip0 (plist-get p1
:stepskip0
))
2232 (block (plist-get p1
:block
))
2233 cc range-text step-time
)
2235 (setq cc
(org-clock-special-range block nil t
)
2236 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
2239 ;; If ts is a number, it's an absolute day number from org-agenda.
2240 (destructuring-bind (month day year
) (calendar-gregorian-from-absolute ts
)
2241 (setq ts
(org-float-time (encode-time 0 0 0 day month year
)))))
2243 (setq ts
(org-float-time
2244 (apply 'encode-time
(org-parse-time-string ts
))))))
2248 (destructuring-bind (month day year
) (calendar-gregorian-from-absolute te
)
2249 (setq te
(org-float-time (encode-time 0 0 0 day month year
)))))
2251 (setq te
(org-float-time
2252 (apply 'encode-time
(org-parse-time-string te
))))))
2253 (setq p1
(plist-put p1
:header
""))
2254 (setq p1
(plist-put p1
:step nil
))
2255 (setq p1
(plist-put p1
:block nil
))
2257 (or (bolp) (insert "\n"))
2258 (setq p1
(plist-put p1
:tstart
(format-time-string
2259 (org-time-stamp-format nil t
)
2260 (seconds-to-time ts
))))
2261 (setq p1
(plist-put p1
:tend
(format-time-string
2262 (org-time-stamp-format nil t
)
2263 (seconds-to-time (setq ts
(+ ts step
))))))
2264 (insert "\n" (if (eq step0
'day
) "Daily report: "
2265 "Weekly report starting on: ")
2266 (plist-get p1
:tstart
) "\n")
2267 (setq step-time
(org-dblock-write:clocktable p1
))
2268 (re-search-forward "^[ \t]*#\\+END:")
2269 (when (and (equal step-time
0) stepskip0
)
2270 ;; Remove the empty table
2271 (delete-region (point-at-bol)
2273 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2278 (defun org-clock-get-table-data (file params
)
2279 "Get the clocktable data for file FILE, with parameters PARAMS.
2280 FILE is only for identification - this function assumes that
2281 the correct buffer is current, and that the wanted restriction is
2283 The return value will be a list with the file name and the total
2284 file time (in minutes) as 1st and 2nd elements. The third element
2285 of this list will be a list of headline entries. Each entry has the
2286 following structure:
2288 (LEVEL HEADLINE TIMESTAMP TIME)
2290 LEVEL: The level of the headline, as an integer. This will be
2291 the reduced leve, so 1,2,3,... even if only odd levels
2293 HEADLINE: The text of the headline. Depending on PARAMS, this may
2294 already be formatted like a link.
2295 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2296 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2298 TIME: The sum of all time spend in this tree, in minutes. This time
2299 will of cause be restricted to the time block and tags match
2300 specified in PARAMS."
2301 (let* ((maxlevel (or (plist-get params
:maxlevel
) 3))
2302 (timestamp (plist-get params
:timestamp
))
2303 (ts (plist-get params
:tstart
))
2304 (te (plist-get params
:tend
))
2305 (block (plist-get params
:block
))
2306 (link (plist-get params
:link
))
2307 (tags (plist-get params
:tags
))
2308 (matcher (if tags
(cdr (org-make-tags-matcher tags
))))
2309 cc range-text st p time level hdl props tsp tbl
)
2311 (setq org-clock-file-total-minutes nil
)
2313 (setq cc
(org-clock-special-range block nil t
)
2314 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
2315 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
2316 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
2317 (when (and ts
(listp ts
))
2318 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
2319 (when (and te
(listp te
))
2320 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
2321 ;; Now the times are strings we can parse.
2322 (if ts
(setq ts
(org-float-time
2323 (apply 'encode-time
(org-parse-time-string ts
)))))
2324 (if te
(setq te
(org-float-time
2325 (apply 'encode-time
(org-parse-time-string te
)))))
2327 (org-clock-sum ts te
2328 (unless (null matcher
)
2330 (let ((tags-list (org-get-tags-at)))
2332 (goto-char (point-min))
2334 (while (or (and (bobp) (prog1 st
(setq st nil
))
2335 (get-text-property (point) :org-clock-minutes
)
2336 (setq p
(point-min)))
2337 (setq p
(next-single-property-change
2338 (point) :org-clock-minutes
)))
2340 (when (setq time
(get-text-property p
:org-clock-minutes
))
2342 (beginning-of-line 1)
2343 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2344 (setq level
(org-reduced-level
2345 (- (match-end 1) (match-beginning 1))))
2346 (<= level maxlevel
))
2347 (setq hdl
(if (not link
)
2349 (org-make-link-string
2350 (format "file:%s::%s"
2353 (org-make-org-heading-search-string
2357 (setq props
(org-entry-properties (point)))
2358 (or (cdr (assoc "SCHEDULED" props
))
2359 (cdr (assoc "DEADLINE" props
))
2360 (cdr (assoc "TIMESTAMP" props
))
2361 (cdr (assoc "TIMESTAMP_IA" props
)))))
2362 (when (> time
0) (push (list level hdl tsp time
) tbl
))))))
2363 (setq tbl
(nreverse tbl
))
2364 (list file org-clock-file-total-minutes tbl
))))
2366 (defun org-clock-time%
(total &rest strings
)
2367 "Compute a time fraction in percent.
2368 TOTAL s a time string like 10:21 specifying the total times.
2369 STRINGS is a list of strings that should be checked for a time.
2370 The first string that does have a time will be used.
2371 This function is made for clock tables."
2372 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2376 (if (not (string-match re total
))
2378 (setq tot
(+ (string-to-number (match-string 2 total
))
2379 (* 60 (string-to-number (match-string 1 total
)))))
2380 (if (= tot
0.
) (throw 'exit
0.
)))
2381 (while (setq s
(pop strings
))
2382 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
2384 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
2385 (* 60 (string-to-number
2386 (match-string 1 s
)))))
2390 (defvar org-clock-loaded nil
2391 "Was the clock file loaded?")
2393 (defun org-clock-save ()
2394 "Persist various clock-related data to disk.
2395 The details of what will be saved are regulated by the variable
2396 `org-clock-persist'."
2397 (when (and org-clock-persist
2398 (or org-clock-loaded
2399 org-clock-has-been-used
2400 (not (file-exists-p org-clock-persist-file
))))
2402 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
2404 (delete-region (point-min) (point-max))
2406 (insert (format ";; org-persist.el - %s at %s\n"
2407 system-name
(format-time-string
2408 (cdr org-time-stamp-formats
))))
2409 (if (and (memq org-clock-persist
'(t clock
))
2410 (setq b
(org-clocking-buffer))
2411 (setq b
(or (buffer-base-buffer b
) b
))
2413 (buffer-file-name b
)
2414 (or (not org-clock-persist-query-save
)
2415 (y-or-n-p (concat "Save current clock ("
2416 (substring-no-properties
2419 (insert "(setq resume-clock '(\""
2420 (buffer-file-name (org-clocking-buffer))
2421 "\" . " (int-to-string (marker-position org-clock-marker
))
2423 ;; Store clocked task history. Tasks are stored reversed to make
2425 (when (and (memq org-clock-persist
'(t history
))
2428 "(setq stored-clock-history '("
2431 (when (and (setq b
(marker-buffer m
))
2432 (setq b
(or (buffer-base-buffer b
) b
))
2434 (buffer-file-name b
))
2435 (concat "(\"" (buffer-file-name b
)
2436 "\" . " (int-to-string (marker-position m
))
2438 (reverse org-clock-history
) " ") "))\n"))
2440 (kill-buffer (current-buffer)))))))
2442 (defun org-clock-load ()
2443 "Load clock-related data from disk, maybe resuming a stored clock."
2444 (when (and org-clock-persist
(not org-clock-loaded
))
2445 (let ((filename (expand-file-name org-clock-persist-file
))
2446 (org-clock-in-resume 'auto-restart
)
2447 resume-clock stored-clock-history
)
2448 (if (not (file-readable-p filename
))
2449 (message "Not restoring clock data; %s not found"
2450 org-clock-persist-file
)
2451 (message "%s" "Restoring clock data")
2452 (setq org-clock-loaded t
)
2453 (load-file filename
)
2455 (when stored-clock-history
2456 (save-window-excursion
2457 (mapc (lambda (task)
2458 (if (file-exists-p (car task
))
2459 (org-clock-history-push (cdr task
)
2460 (find-file (car task
)))))
2461 stored-clock-history
)))
2463 (when (and resume-clock org-clock-persist
2464 (file-exists-p (car resume-clock
))
2465 (or (not org-clock-persist-query-resume
)
2469 (with-current-buffer (find-file (car resume-clock
))
2471 (goto-char (cdr resume-clock
))
2472 (org-back-to-heading t
)
2473 (and (looking-at org-complex-heading-regexp
)
2476 (when (file-exists-p (car resume-clock
))
2477 (with-current-buffer (find-file (car resume-clock
))
2478 (goto-char (cdr resume-clock
))
2479 (let ((org-clock-auto-clock-resolution nil
))
2481 (if (org-invisible-p)
2482 (org-show-context))))))))))
2485 (defun org-clock-persistence-insinuate ()
2486 "Set up hooks for clock persistence."
2487 (add-hook 'org-mode-hook
'org-clock-load
)
2488 (add-hook 'kill-emacs-hook
'org-clock-save
))
2490 ;; Suggested bindings
2491 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
2493 (provide 'org-clock
)
2496 ;;; org-clock.el ends here