1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
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
36 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
37 (defvar org-time-stamp-formats
)
39 (defgroup org-clock nil
40 "Options concerning clocking working time in Org-mode."
44 (defcustom org-clock-into-drawer org-log-into-drawer
45 "Should clocking info be wrapped into a drawer?
46 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
47 If necessary, the drawer will be created.
48 When nil, the drawer will not be created, but used when present.
49 When an integer and the number of clocking entries in an item
50 reaches or exceeds this number, a drawer will be created.
51 When a string, it names the drawer to be used.
53 The default for this variable is the value of `org-log-into-drawer',
58 (const :tag
"Always" t
)
59 (const :tag
"Only when drawer exists" nil
)
60 (integer :tag
"When at least N clock entries")
61 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
62 (string :tag
"Into Drawer named...")))
64 (defcustom org-clock-out-when-done t
65 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
66 A nil value means, clock will keep running until stopped explicitly with
67 `C-c C-x C-o', or until the clock is started in a different item."
71 (defcustom org-clock-out-remove-zero-time-clocks nil
72 "Non-nil means, remove the clock line when the resulting time is zero."
76 (defcustom org-clock-in-switch-to-state nil
77 "Set task to a special todo state while clocking it.
78 The value should be the state to which the entry should be
79 switched. If the value is a function, it must take one
80 parameter (the current TODO state of the item) and return the
81 state to switch it to."
85 (const :tag
"Don't force a state" nil
)
87 (symbol :tag
"Function")))
89 (defcustom org-clock-out-switch-to-state nil
90 "Set task to a special todo state after clocking out.
91 The value should be the state to which the entry should be
92 switched. If the value is a function, it must take one
93 parameter (the current TODO state of the item) and return the
94 state to switch it to."
98 (const :tag
"Don't force a state" nil
)
100 (symbol :tag
"Function")))
102 (defcustom org-clock-history-length
5
103 "Number of clock tasks to remember in history."
107 (defcustom org-clock-goto-may-find-recent-task t
108 "Non-nil means, `org-clock-goto' can go to recent task if no active clock."
112 (defcustom org-clock-heading-function nil
113 "When non-nil, should be a function to create `org-clock-heading'.
114 This is the string shown in the mode line when a clock is running.
115 The function is called with point at the beginning of the headline."
119 (defcustom org-clock-string-limit
0
120 "Maximum length of clock strings in the modeline. 0 means no limit."
124 (defcustom org-clock-in-resume nil
125 "If non-nil, resume clock when clocking into task with open clock.
126 When clocking into a task with a clock entry which has not been closed,
127 the clock can be resumed from that point."
131 (defcustom org-clock-persist nil
132 "When non-nil, save the running clock when emacs is closed.
133 The clock is resumed when emacs restarts.
134 When this is t, both the running clock, and the entire clock
135 history are saved. When this is the symbol `clock', only the
136 running clock is saved.
138 When Emacs restarts with saved clock information, the file containing the
139 running clock as well as all files mentioned in the clock history will
141 All this depends on running `org-clock-persistence-insinuate' in .emacs"
144 (const :tag
"Just the running clock" clock
)
145 (const :tag
"Clock and history" t
)
146 (const :tag
"No persistence" nil
)))
148 (defcustom org-clock-persist-file
(convert-standard-filename
149 "~/.emacs.d/org-clock-save.el")
150 "File to save clock data to."
154 (defcustom org-clock-persist-query-save nil
155 "When non-nil, ask before saving the current clock on exit."
159 (defcustom org-clock-persist-query-resume t
160 "When non-nil, ask before resuming any stored clock during load."
164 (defcustom org-clock-sound nil
165 "Sound that will used for notifications.
169 t standard Emacs beep
170 file name play this sound file. If not possible, fall back to beep"
173 (const :tag
"No sound" nil
)
174 (const :tag
"Standard beep" t
)
175 (file :tag
"Play sound file")))
177 (defcustom org-clock-modeline-total
'auto
178 "Default setting for the time included for the modeline clock.
179 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
182 current Only the time in the current instance of the clock
183 today All time clocked inot this task today
184 repeat All time clocked into this task since last repeat
185 all All time ever recorded for this task
186 auto Automatically, either `all', or `repeat' for repeating tasks"
189 (const :tag
"Current clock" current
)
190 (const :tag
"Today's task time" today
)
191 (const :tag
"Since last repeat" repeat
)
192 (const :tag
"All task time" all
)
193 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
195 (defcustom org-show-notification-handler nil
196 "Function or program to send notification with.
197 The function or program will be called with the notification
201 (string :tag
"Program")
202 (function :tag
"Function")))
204 (defcustom org-clock-clocktable-default-properties
'(:maxlevel
2 :scope file
)
205 "Default properties for new clocktables."
209 (defcustom org-clock-idle-time nil
210 "When non-nil, resolve open clocks if the user is idle more than X minutes."
213 (const :tag
"Never" nil
)
214 (integer :tag
"After N minutes")))
217 (defvar org-clock-in-prepare-hook nil
218 "Hook run when preparing the clock.
219 This hook is run before anything happens to the task that
220 you want to clock in. For example, you can use this hook
221 to add an effort property.")
222 (defvar org-clock-in-hook nil
223 "Hook run when starting the clock.")
224 (defvar org-clock-out-hook nil
225 "Hook run when stopping the current clock.")
227 (defvar org-clock-cancel-hook nil
228 "Hook run when cancelling the current clock.")
229 (defvar org-clock-goto-hook nil
230 "Hook run when selecting the currently clocked-in entry.")
232 ;;; The clock for measuring work time.
234 (defvar org-mode-line-string
"")
235 (put 'org-mode-line-string
'risky-local-variable t
)
237 (defvar org-clock-mode-line-timer nil
)
238 (defvar org-clock-idle-timer nil
)
239 (defvar org-clock-heading
"")
240 (defvar org-clock-heading-for-remember
"")
241 (defvar org-clock-start-time
"")
243 (defvar org-clock-left-over-time nil
244 "If non-nil, user cancelled a clock; this is when leftover time started.")
246 (defvar org-clock-effort
""
247 "Effort estimate of the currently clocking task")
249 (defvar org-clock-total-time nil
250 "Holds total time, spent previously on currently clocked item.
251 This does not include the time in the currently running clock.")
253 (defvar org-clock-history nil
254 "List of marker pointing to recent clocked tasks.")
256 (defvar org-clock-default-task
(make-marker)
257 "Marker pointing to the default task that should clock time.
258 The clock can be made to switch to this task after clocking out
259 of a different task.")
261 (defvar org-clock-interrupted-task
(make-marker)
262 "Marker pointing to the task that has been interrupted by the current clock.")
264 (defvar org-clock-mode-line-map
(make-sparse-keymap))
265 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
266 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
268 (defun org-clock-menu ()
272 ["Clock out" org-clock-out t
]
273 ["Change effort estimate" org-clock-modify-effort-estimate t
]
274 ["Go to clock entry" org-clock-goto t
]
275 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
277 (defun org-clock-history-push (&optional pos buffer
)
278 "Push a marker to the clock history."
279 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
280 (let ((m (move-marker (make-marker) (or pos
(point)) buffer
)) n l
)
281 (while (setq n
(member m org-clock-history
))
282 (move-marker (car n
) nil
))
283 (setq org-clock-history
285 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
287 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
288 (setq org-clock-history
290 (nthcdr (- l org-clock-history-length -
1)
291 (nreverse org-clock-history
)))))
292 (push m org-clock-history
)))
294 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
295 "Save relative positions of markers in region."
296 (org-check-and-save-marker org-clock-marker beg end
)
297 (org-check-and-save-marker org-clock-hd-marker beg end
)
298 (org-check-and-save-marker org-clock-default-task beg end
)
299 (org-check-and-save-marker org-clock-interrupted-task beg end
)
300 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
303 (defun org-clock-select-task (&optional prompt
)
304 "Select a task that recently was associated with clocking."
306 (let (sel-list rpl
(i 0) s
)
307 (save-window-excursion
308 (org-switch-to-buffer-other-window
309 (get-buffer-create "*Clock Task Select*"))
311 (when (marker-buffer org-clock-default-task
)
312 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
313 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
315 (when (marker-buffer org-clock-interrupted-task
)
316 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
317 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
319 (when (marker-buffer org-clock-marker
)
320 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
321 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
323 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
326 (when (marker-buffer m
)
328 s
(org-clock-insert-selection-line
334 (org-fit-window-to-buffer)
335 (message (or prompt
"Select task for clocking:"))
336 (setq rpl
(read-char-exclusive))
340 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
341 (t (error "Invalid task choice %c" rpl
))))))
343 (defun org-clock-insert-selection-line (i marker
)
344 "Insert a line for the clock selection menu.
345 And return a cons cell with the selection character integer and the marker
347 (when (marker-buffer marker
)
348 (let (file cat task heading prefix
)
349 (with-current-buffer (org-base-buffer (marker-buffer marker
))
354 (setq file
(buffer-file-name (marker-buffer marker
))
355 cat
(or (org-get-category)
356 (progn (org-refresh-category-properties)
358 heading
(org-get-heading 'notags
)
359 prefix
(save-excursion
360 (org-back-to-heading t
)
364 (org-fontify-like-in-org-mode
365 (concat prefix heading
)
369 (insert (format "[%c] %-15s %s\n" i cat task
))
372 (defun org-clock-get-clock-string ()
373 "Form a clock-string, that will be show in the mode line.
374 If an effort estimate was defined for current item, use
375 01:30/01:50 format (clocked/estimated).
376 If not, show simply the clocked time like 01:50."
377 (let* ((clocked-time (org-clock-get-clocked-time))
378 (h (floor clocked-time
60))
379 (m (- clocked-time
(* 60 h
))))
380 (if (and org-clock-effort
)
381 (let* ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort
))
382 (effort-h (floor effort-in-minutes
60))
383 (effort-m (- effort-in-minutes
(* effort-h
60))))
384 (format (concat "-[" org-time-clocksum-format
"/" org-time-clocksum-format
" (%s)]")
385 h m effort-h effort-m org-clock-heading
))
386 (format (concat "-[" org-time-clocksum-format
" (%s)]")
387 h m org-clock-heading
))))
389 (defun org-clock-update-mode-line ()
390 (setq org-mode-line-string
392 (let ((clock-string (org-clock-get-clock-string))
393 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
394 (if (and (> org-clock-string-limit
0)
395 (> (length clock-string
) org-clock-string-limit
))
396 (org-propertize (substring clock-string
0 org-clock-string-limit
)
397 'help-echo
(concat help-text
": " org-clock-heading
))
398 (org-propertize clock-string
'help-echo help-text
)))
399 'local-map org-clock-mode-line-map
400 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)
401 'face
'org-mode-line-clock
))
402 (if org-clock-effort
(org-clock-notify-once-if-expired))
403 (force-mode-line-update))
405 (defun org-clock-get-clocked-time ()
406 "Get the clocked time for the current item in minutes.
407 The time returned includes the time spent on this task in
408 previous clocking intervals."
409 (let ((currently-clocked-time
410 (floor (- (org-float-time)
411 (org-float-time org-clock-start-time
)) 60)))
412 (+ currently-clocked-time
(or org-clock-total-time
0))))
414 (defun org-clock-modify-effort-estimate (&optional value
)
415 "Add to or set the effort estimate of the item currently being clocked.
416 VALUE can be a number of minutes, or a string with forat hh:mm or mm.
417 WHen the strig starts with a + or a - sign, the current value of the effort
418 property will be changed by that amount.
419 This will update the \"Effort\" property of currently clocked item, and
422 (when (org-clock-is-active)
423 (let ((current org-clock-effort
) sign
)
425 ;; Prompt user for a value or a change
428 (format "Set effort (hh:mm or mm%s): "
430 (format ", prefix + to add to %s" org-clock-effort
)
432 (when (stringp value
)
433 ;; A string. See if it is a delta
434 (setq sign
(string-to-char value
))
435 (if (member sign
'(?- ?
+))
436 (setq current
(org-hh:mm-string-to-minutes
(substring current
1)))
438 (setq value
(org-hh:mm-string-to-minutes value
))
440 (setq value
(- current value
))
441 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
442 (setq value
(max 0 value
)
443 org-clock-effort
(org-minutes-to-hh:mm-string value
))
444 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
445 (org-clock-update-mode-line)
446 (message "Effort is now %s" org-clock-effort
))))
448 (defvar org-clock-notification-was-shown nil
449 "Shows if we have shown notification already.")
451 (defun org-clock-notify-once-if-expired ()
452 "Show notification if we spent more time than we estimated before.
453 Notification is shown only once."
454 (when (marker-buffer org-clock-marker
)
455 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort
))
456 (clocked-time (org-clock-get-clocked-time)))
457 (if (>= clocked-time effort-in-minutes
)
458 (unless org-clock-notification-was-shown
459 (setq org-clock-notification-was-shown t
)
461 (format "Task '%s' should be finished by now. (%s)"
462 org-clock-heading org-clock-effort
) t
))
463 (setq org-clock-notification-was-shown nil
)))))
465 (defun org-notify (notification &optional play-sound
)
466 "Send a NOTIFICATION and maybe PLAY-SOUND."
467 (org-show-notification notification
)
468 (if play-sound
(org-clock-play-sound)))
470 (defun org-show-notification (notification)
472 Use `org-show-notification-handler' if defined,
473 use libnotify if available, or fall back on a message."
474 (cond ((functionp org-show-notification-handler
)
475 (funcall org-show-notification-handler notification
))
476 ((stringp org-show-notification-handler
)
477 (start-process "emacs-timer-notification" nil
478 org-show-notification-handler notification
))
479 ((org-program-exists "notify-send")
480 (start-process "emacs-timer-notification" nil
481 "notify-send" notification
))
482 ;; Maybe the handler will send a message, so only use message as
483 ;; a fall back option
484 (t (message notification
))))
486 (defun org-clock-play-sound ()
487 "Play sound as configured by `org-clock-sound'.
488 Use alsa's aplay tool if available."
490 ((not org-clock-sound
))
491 ((eq org-clock-sound t
) (beep t
) (beep t
))
492 ((stringp org-clock-sound
)
493 (if (file-exists-p org-clock-sound
)
494 (if (org-program-exists "aplay")
495 (start-process "org-clock-play-notification" nil
496 "aplay" org-clock-sound
)
498 (play-sound-file org-clock-sound
)
499 (error (beep t
) (beep t
))))))))
501 (defun org-program-exists (program-name)
502 "Checks whenever we can locate program and launch it."
503 (if (eq system-type
'gnu
/linux
)
504 (= 0 (call-process "which" nil nil nil program-name
))))
506 (defvar org-clock-mode-line-entry nil
507 "Information for the modeline about the running clock.")
509 (defun org-find-open-clocks (file)
510 "Search through the given file and find all open clocks."
511 (let ((buf (or (get-file-buffer file
)
512 (find-file-noselect file
)))
514 (with-current-buffer buf
516 (goto-char (point-min))
517 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t
)
518 (push (cons (copy-marker (1- (match-end 1)) t
)
519 (org-time-string-to-time (match-string 1))) clocks
))))
522 (defsubst org-is-active-clock
(clock)
523 "Return t if CLOCK is the currently active clock."
524 (and (org-clock-is-active)
525 (= org-clock-marker
(car clock
))))
527 (defmacro org-with-clock-position
(clock &rest forms
)
528 "Evaluate FORMS with CLOCK as the current active clock."
529 `(with-current-buffer (marker-buffer (car ,clock
))
533 (goto-char (car ,clock
))
537 (put 'org-with-clock-position
'lisp-indent-function
1)
539 (defmacro org-with-clock
(clock &rest forms
)
540 "Evaluate FORMS with CLOCK as the current active clock.
541 This macro also protects the current active clock from being altered."
542 `(org-with-clock-position ,clock
543 (let ((org-clock-start-time (cdr ,clock
))
544 (org-clock-total-time)
547 (org-clock-marker (car ,clock
))
548 (org-clock-hd-marker (save-excursion
549 (outline-back-to-heading t
)
553 (put 'org-with-clock
'lisp-indent-function
1)
555 (defsubst org-clock-clock-in
(clock &optional resume
)
556 "Clock in to the clock located by CLOCK.
557 If necessary, clock-out of the currently active clock."
558 (org-with-clock-position clock
559 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
562 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
563 "Clock out of the clock located by CLOCK."
564 (let ((temp (copy-marker (car clock
)
565 (marker-insertion-type (car clock
)))))
566 (if (org-is-active-clock clock
)
567 (org-clock-out fail-quietly at-time
)
568 (org-with-clock clock
569 (org-clock-out fail-quietly at-time
)))
570 (setcar clock temp
)))
572 (defsubst org-clock-clock-cancel
(clock)
573 "Cancel the clock located by CLOCK."
574 (let ((temp (copy-marker (car clock
)
575 (marker-insertion-type (car clock
)))))
576 (if (org-is-active-clock clock
)
578 (org-with-clock clock
580 (setcar clock temp
)))
582 (defvar org-clock-clocking-in nil
)
583 (defvar org-clock-resolving-clocks nil
)
584 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
586 (defun org-clock-resolve-clock (clock resolve-to
&optional close-p
587 restart-p fail-quietly
)
588 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
589 `CLOCK' is a cons cell of the form (MARKER START-TIME).
590 This routine can do one of many things:
592 if `RESOLVE-TO' is nil
593 if `CLOSE-P' is non-nil, give an error
594 if this clock is the active clock, cancel it
595 else delete the clock line (as if it never happened)
596 if `RESTART-P' is non-nil, start a new clock
598 else if `RESOLVE-TO' is the symbol `now'
599 if `RESTART-P' is non-nil, give an error
600 if `CLOSE-P' is non-nil, clock out the entry and
601 if this clock is the active clock, stop it
602 else if this clock is the active clock, do nothing
603 else if there is no active clock, resume this clock
604 else ask to cancel the active clock, and if so,
605 resume this clock after cancelling it
607 else if `RESOLVE-TO' is some date in the future
608 give an error about `RESOLVE-TO' being invalid
610 else if `RESOLVE-TO' is some date in the past
611 if `RESTART-P' is non-nil, give an error
612 if `CLOSE-P' is non-nil, enter a closing time and
613 if this clock is the active clock, stop it
614 else if this clock is the active clock, enter a
615 closing time, stop the current clock, then
616 start a new clock for the same item
617 else just enter a closing time for this clock
618 and then start a new clock for the same item"
619 (let ((org-clock-resolving-clocks t
))
622 (org-clock-clock-cancel clock
)
623 (if (and restart-p
(not org-clock-clocking-in
))
624 (org-clock-clock-in clock
)))
626 ((eq resolve-to
'now
)
628 (error "RESTART-P is not valid here"))
629 (if (or close-p org-clock-clocking-in
)
630 (org-clock-clock-out clock fail-quietly
)
631 (unless (org-is-active-clock clock
)
632 (org-clock-clock-in clock t
))))
634 ((not (time-less-p resolve-to
(current-time)))
635 (error "RESOLVE-TO must refer to a time in the past"))
639 (error "RESTART-P is not valid here"))
640 (org-clock-clock-out clock fail-quietly resolve-to
)
641 (unless org-clock-clocking-in
643 (setq org-clock-left-over-time last-valid
)
644 (org-clock-clock-in clock
)))))))
646 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
647 "Resolve an open org-mode clock.
648 An open clock was found, with `dangling' possibly being non-nil.
649 If this function was invoked with a prefix argument, non-dangling
650 open clocks are ignored. The given clock requires some sort of
651 user intervention to resolve it, either because a clock was left
652 dangling or due to an idle timeout. The clock resolution can
655 (a) deleted, the user doesn't care about the clock
656 (b) restarted from the current time (if no other clock is open)
657 (c) closed, giving the clock X minutes
658 (d) closed and then restarted
659 (e) resumed, as if the user had never left
661 The format of clock is (CONS MARKER START-TIME), where MARKER
662 identifies the buffer and position the clock is open at (and
663 thus, the heading it's under), and START-TIME is when the clock
667 (save-window-excursion
669 (unless org-clock-resolving-clocks-due-to-idleness
670 (org-with-clock clock
672 (with-current-buffer (marker-buffer (car clock
))
673 (goto-char (car clock
))
674 (if org-clock-into-drawer
676 (outline-flag-region (save-excursion
677 (outline-back-to-heading t
)
678 (search-forward ":LOGBOOK:")
679 (goto-char (match-beginning 0)))
681 (outline-back-to-heading t
)
682 (search-forward ":LOGBOOK:")
683 (search-forward ":END:")
684 (goto-char (match-end 0)))
687 (while (null char-pressed
)
689 (read-char (concat (funcall prompt-fn clock
)
690 " [(kK)eep (sS)ubtract (C)ancel]? ")
693 (default (floor (/ (org-float-time
694 (time-subtract (current-time) last-valid
)) 60)))
695 (keep (and (memq ch
'(?k ?K
))
696 (read-number "Keep how many minutes? " default
)))
697 (subtractp (memq ch
'(?s ?S
)))
698 (barely-started-p (< (- (org-float-time last-valid
)
699 (org-float-time (cdr clock
))) 45))
700 (start-over (and subtractp barely-started-p
)))
702 (not (memq ch
'(?k ?K ?s ?S ?C
))))
704 (org-clock-resolve-clock
707 ;; If the time on the clock was less than a minute before
708 ;; the user went away, and they've ask to subtract all the
717 (time-add last-valid
(seconds-to-time (* 60 keep
)))))
720 (not (memq ch
'(?K ?S ?C
))))
723 (defun org-resolve-clocks (&optional also-non-dangling-p prompt-fn last-valid
)
724 "Resolve all currently open org-mode clocks.
725 If `also-non-dangling-p' is non-nil, also ask to resolve
726 non-dangling (i.e., currently open and valid) clocks."
728 (unless org-clock-resolving-clocks
729 (let ((org-clock-resolving-clocks t
))
730 (dolist (file (org-files-list))
731 (let ((clocks (org-find-open-clocks file
)))
732 (dolist (clock clocks
)
733 (let ((dangling (or (not (org-clock-is-active))
734 (/= (car clock
) org-clock-marker
))))
735 (unless (and (not dangling
) (not also-non-dangling-p
))
742 "Dangling clock started %d mins ago"
744 (/ (- (org-float-time (current-time))
745 (org-float-time (cdr clock
))) 60))))))
747 (cdr clock
)))))))))))
749 (defun org-emacs-idle-seconds ()
750 "Return the current Emacs idle time in seconds, or nil if not idle."
751 (let ((idle-time (current-idle-time)))
753 (org-float-time idle-time
)
756 (defun org-mac-idle-seconds ()
757 "Return the current Mac idle time in seconds"
758 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
760 (defun org-user-idle-seconds ()
761 "Return the number of seconds the user has been idle for.
762 This routine returns a floating point number."
763 (if (eq system-type
'darwin
)
764 (let ((emacs-idle (org-emacs-idle-seconds)))
765 ;; If Emacs has been idle for longer than the user's
766 ;; `org-clock-idle-time' value, check whether the whole system has
767 ;; really been idle for that long.
768 (if (> emacs-idle
(* 60 org-clock-idle-time
))
769 (min emacs-idle
(org-mac-idle-seconds))
771 (org-emacs-idle-seconds)))
773 (defun org-resolve-clocks-if-idle ()
774 "Resolve all currently open org-mode clocks.
775 This is performed after `org-clock-idle-time' minutes, to check
776 if the user really wants to stay clocked in after being idle for
778 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
780 (let ((idle (org-user-idle-seconds))
781 (org-clock-resolving-clocks-due-to-idleness t
))
782 (if (> idle
(* 60 org-clock-idle-time
))
784 (cons org-clock-marker
785 org-clock-start-time
)
788 (format "Clocked in & idle for %d mins"
789 (/ (org-user-idle-seconds) 60))))
790 (time-subtract (current-time)
791 (seconds-to-time (org-user-idle-seconds))))))))
793 (defun org-clock-in (&optional select
)
794 "Start the clock on the current item.
795 If necessary, clock-out of the currently active clock.
796 With prefix arg SELECT, offer a list of recently clocked tasks to
797 clock into. When SELECT is `C-u C-u', clock into the current task and mark
798 is as the default task, a special task that will always be offered in
799 the clocking selection, associated with the letter `d'."
801 (setq org-clock-notification-was-shown nil
)
803 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
804 (marker-buffer org-clock-marker
)))
805 ts selected-task target-pos
(msg-extra "")
806 (left-over (and (not org-clock-resolving-clocks
)
807 org-clock-left-over-time
)))
808 (unless (or org-clock-clocking-in
809 org-clock-resolving-clocks
)
810 (setq org-clock-left-over-time nil
)
811 (let ((org-clock-clocking-in t
))
812 (org-resolve-clocks))) ; check if any clocks are dangling
813 (when (equal select
'(4))
814 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
816 (setq selected-task
(copy-marker selected-task
))
819 ;; We are interrupting the clocking of a different task.
820 ;; Save a marker to this task, so that we can go back.
821 (move-marker org-clock-interrupted-task
822 (marker-position org-clock-marker
)
823 (marker-buffer org-clock-marker
))
826 (when (equal select
'(16))
827 ;; Mark as default clocking task
828 (org-clock-mark-default-task))
830 ;; Clock in at which position?
832 (if (and (eobp) (not (org-on-heading-p)))
835 (run-hooks 'org-clock-in-prepare-hook
)
837 (when (and selected-task
(marker-buffer selected-task
))
838 ;; There is a selected task, move to the correct buffer
839 ;; and set the new target position.
840 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
841 (setq target-pos
(marker-position selected-task
))
842 (move-marker selected-task nil
))
846 (goto-char target-pos
)
847 (org-back-to-heading t
)
848 (or interrupting
(move-marker org-clock-interrupted-task nil
))
849 (org-clock-history-push)
850 (cond ((functionp org-clock-in-switch-to-state
)
851 (looking-at org-complex-heading-regexp
)
852 (let ((newstate (funcall org-clock-in-switch-to-state
854 (if newstate
(org-todo newstate
))))
855 ((and org-clock-in-switch-to-state
856 (not (looking-at (concat outline-regexp
"[ \t]*"
857 org-clock-in-switch-to-state
859 (org-todo org-clock-in-switch-to-state
)))
860 (setq org-clock-heading-for-remember
861 (and (looking-at org-complex-heading-regexp
)
863 (org-trim (buffer-substring (match-end 1)
865 (setq org-clock-heading
866 (cond ((and org-clock-heading-function
867 (functionp org-clock-heading-function
))
868 (funcall org-clock-heading-function
))
869 ((looking-at org-complex-heading-regexp
)
872 (setq org-clock-heading
(org-propertize org-clock-heading
874 (org-clock-find-position org-clock-in-resume
)
876 ((and org-clock-in-resume
878 (concat "^[ \t]* " org-clock-string
879 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
880 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
881 (message "Matched %s" (match-string 1))
882 (setq ts
(concat "[" (match-string 1) "]"))
883 (goto-char (match-end 1))
884 (setq org-clock-start-time
886 (org-parse-time-string (match-string 1))))
887 (setq org-clock-effort
(org-get-effort))
888 (setq org-clock-total-time
(org-clock-sum-current-item
889 (org-clock-get-sum-start))))
890 ((eq org-clock-in-resume
'auto-restart
)
891 ;; called from org-clock-load during startup,
892 ;; do not interrupt, but warn!
893 (message "Cannot restart clock because task does not contain unfinished clock")
898 (insert-before-markers "\n")
900 (org-indent-line-function)
901 (when (and (save-excursion
904 (beginning-of-line 1)
905 (org-indent-line-to (- (org-get-indentation) 2)))
906 (insert org-clock-string
" ")
907 (setq org-clock-effort
(org-get-effort))
908 (setq org-clock-total-time
(org-clock-sum-current-item
909 (org-clock-get-sum-start)))
910 (setq org-clock-start-time
914 "You stopped another clock %d mins ago; start this one from then? "
915 (/ (- (time-to-seconds (current-time))
916 (time-to-seconds left-over
)) 60)))
919 (setq ts
(org-insert-time-stamp org-clock-start-time
920 'with-hm
'inactive
))))
921 (move-marker org-clock-marker
(point) (buffer-base-buffer))
922 (move-marker org-clock-hd-marker
923 (save-excursion (org-back-to-heading t
) (point))
924 (buffer-base-buffer))
925 (or global-mode-string
(setq global-mode-string
'("")))
926 (or (memq 'org-mode-line-string global-mode-string
)
927 (setq global-mode-string
928 (append global-mode-string
'(org-mode-line-string))))
929 (org-clock-update-mode-line)
930 (when org-clock-mode-line-timer
931 (cancel-timer org-clock-mode-line-timer
)
932 (setq org-clock-mode-line-timer nil
))
933 (setq org-clock-mode-line-timer
934 (run-with-timer 60 60 'org-clock-update-mode-line
))
935 (when org-clock-idle-timer
936 (cancel-timer org-clock-idle-timer
)
937 (setq org-clock-idle-timer nil
))
938 (setq org-clock-idle-timer
939 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
940 (message "Clock starts at %s - %s" ts msg-extra
)
941 (run-hooks 'org-clock-in-hook
)))))))
943 (defun org-clock-mark-default-task ()
944 "Mark current task as default task."
947 (org-back-to-heading t
)
948 (move-marker org-clock-default-task
(point))))
951 (defun org-clock-get-sum-start ()
952 "Return the time from which clock times should be counted.
953 This is for the currently running clock as it is displayed
954 in the mode line. This function looks at the properties
955 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
956 corresponding variable `org-clock-modeline-total' and then
957 decides which time to use."
958 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
959 (symbol-name org-clock-modeline-total
)))
960 (lr (org-entry-get nil
"LAST_REPEAT")))
962 ((equal cmt
"current")
963 (setq msg-extra
"showing time in current clock instance")
966 (setq msg-extra
"showing today's task time.")
967 (let* ((dt (decode-time (current-time))))
968 (setq dt
(append (list 0 0 0) (nthcdr 3 dt
)))
969 (if org-extend-today-until
970 (setf (nth 2 dt
) org-extend-today-until
))
971 (apply 'encode-time dt
)))
972 ((or (equal cmt
"all")
973 (and (or (not cmt
) (equal cmt
"auto"))
975 (setq msg-extra
"showing entire task time.")
977 ((or (equal cmt
"repeat")
978 (and (or (not cmt
) (equal cmt
"auto"))
980 (setq msg-extra
"showing task time since last repeat.")
983 (org-time-string-to-time lr
)))
986 (defun org-clock-find-position (find-unclosed)
987 "Find the location where the next clock line should be inserted.
988 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
989 line and position cursor in that line."
990 (org-back-to-heading t
)
992 (let ((beg (save-excursion
993 (beginning-of-line 2)
994 (or (bolp) (newline))
996 (end (progn (outline-next-heading) (point)))
997 (re (concat "^[ \t]*" org-clock-string
))
999 (drawer (if (stringp org-clock-into-drawer
)
1000 org-clock-into-drawer
"LOGBOOK"))
1001 first last ind-last
)
1003 (when (and find-unclosed
1005 (concat "^[ \t]* " org-clock-string
1006 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1007 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1009 (beginning-of-line 1)
1011 (when (eobp) (newline) (setq end
(max (point) end
)))
1012 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
1013 ;; we seem to have a CLOCK drawer, so go there.
1014 (beginning-of-line 2)
1015 (or org-log-states-order-reversed
1016 (and (re-search-forward org-property-end-re nil t
)
1017 (goto-char (match-beginning 0))))
1019 ;; Lets count the CLOCK lines
1021 (while (re-search-forward re end t
)
1022 (setq first
(or first
(match-beginning 0))
1023 last
(match-beginning 0)
1025 (when (and (integerp org-clock-into-drawer
)
1027 (>= (1+ cnt
) org-clock-into-drawer
))
1028 ;; Wrap current entries into a new drawer
1030 (setq ind-last
(org-get-indentation))
1031 (beginning-of-line 2)
1032 (if (and (>= (org-get-indentation) ind-last
)
1036 (beginning-of-line 0)
1037 (org-indent-line-to ind-last
)
1039 (insert ":" drawer
":\n")
1040 (beginning-of-line 0)
1041 (org-indent-line-function)
1043 (beginning-of-line 2)
1044 (or org-log-states-order-reversed
1045 (and (re-search-forward org-property-end-re nil t
)
1046 (goto-char (match-beginning 0))))
1050 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1051 (not (equal (match-string 1) org-clock-string
)))
1052 ;; Planning info, skip to after it
1053 (beginning-of-line 2)
1054 (or (bolp) (newline)))
1055 (when (or (eq org-clock-into-drawer t
)
1056 (stringp org-clock-into-drawer
)
1057 (and (integerp org-clock-into-drawer
)
1058 (< org-clock-into-drawer
2)))
1059 (insert ":" drawer
":\n:END:\n")
1060 (beginning-of-line -
1)
1061 (org-indent-line-function)
1063 (beginning-of-line 2)
1064 (org-indent-line-function)
1066 (or org-log-states-order-reversed
1067 (and (re-search-forward org-property-end-re nil t
)
1068 (goto-char (match-beginning 0))))))))
1070 (defun org-clock-out (&optional fail-quietly at-time
)
1071 "Stop the currently running clock.
1072 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1075 (if (not (marker-buffer org-clock-marker
))
1076 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
1077 (let (ts te s h m remove
)
1079 (set-buffer (marker-buffer org-clock-marker
))
1082 (goto-char org-clock-marker
)
1083 (beginning-of-line 1)
1084 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1085 (equal (match-string 1) org-clock-string
))
1086 (setq ts
(match-string 2))
1087 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1088 (goto-char (match-end 0))
1089 (delete-region (point) (point-at-eol))
1091 (setq te
(org-insert-time-stamp (or at-time
(current-time))
1092 'with-hm
'inactive
))
1093 (setq s
(- (org-float-time (apply 'encode-time
(org-parse-time-string te
)))
1094 (org-float-time (apply 'encode-time
(org-parse-time-string ts
))))
1095 h
(floor (/ s
3600))
1099 (insert " => " (format "%2d:%02d" h m
))
1100 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
1102 (beginning-of-line 1)
1103 (delete-region (point) (point-at-eol))
1104 (and (looking-at "\n") (> (point-max) (1+ (point)))
1106 (move-marker org-clock-marker nil
)
1107 (move-marker org-clock-hd-marker nil
)
1108 (when org-log-note-clock-out
1109 (org-add-log-setup 'clock-out nil nil nil nil
1110 (concat "# Task: " (org-get-heading t
) "\n\n")))
1111 (when org-clock-mode-line-timer
1112 (cancel-timer org-clock-mode-line-timer
)
1113 (setq org-clock-mode-line-timer nil
))
1114 (when org-clock-idle-timer
1115 (cancel-timer org-clock-idle-timer
)
1116 (setq org-clock-idle-timer nil
))
1117 (setq global-mode-string
1118 (delq 'org-mode-line-string global-mode-string
))
1119 (when org-clock-out-switch-to-state
1121 (org-back-to-heading t
)
1122 (let ((org-inhibit-logging t
))
1124 ((functionp org-clock-out-switch-to-state
)
1125 (looking-at org-complex-heading-regexp
)
1126 (let ((newstate (funcall org-clock-out-switch-to-state
1128 (if newstate
(org-todo newstate
))))
1129 ((and org-clock-out-switch-to-state
1130 (not (looking-at (concat outline-regexp
"[ \t]*"
1131 org-clock-out-switch-to-state
1133 (org-todo org-clock-out-switch-to-state
))))))
1134 (force-mode-line-update)
1135 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
1136 (if remove
" => LINE REMOVED" ""))
1137 (run-hooks 'org-clock-out-hook
))))))
1139 (defun org-clock-cancel ()
1140 "Cancel the running clock be removing the start timestamp."
1142 (if (not (marker-buffer org-clock-marker
))
1143 (error "No active clock"))
1145 (set-buffer (marker-buffer org-clock-marker
))
1146 (goto-char org-clock-marker
)
1147 (delete-region (1- (point-at-bol)) (point-at-eol))
1148 ;; Just in case, remove any empty LOGBOOK left over
1149 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1150 (move-marker org-clock-marker nil
)
1151 (move-marker org-clock-hd-marker nil
)
1152 (setq global-mode-string
1153 (delq 'org-mode-line-string global-mode-string
))
1154 (force-mode-line-update)
1155 (message "Clock canceled")
1156 (run-hooks 'org-clock-cancel-hook
))
1158 (defun org-clock-goto (&optional select
)
1159 "Go to the currently clocked-in entry, or to the most recently clocked one.
1160 With prefix arg SELECT, offer recently clocked tasks for selection."
1165 (or (org-clock-select-task "Select task to go to: ")
1166 (error "No task selected")))
1167 ((marker-buffer org-clock-marker
) org-clock-marker
)
1168 ((and org-clock-goto-may-find-recent-task
1169 (car org-clock-history
)
1170 (marker-buffer (car org-clock-history
)))
1172 (car org-clock-history
))
1173 (t (error "No active or recent clock task")))))
1174 (switch-to-buffer (marker-buffer m
))
1175 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1178 (org-back-to-heading t
)
1179 (org-cycle-hide-drawers 'children
)
1182 (message "No running clock, this is the most recently clocked task"))
1183 (run-hooks 'org-clock-goto-hook
)))
1185 (defvar org-clock-file-total-minutes nil
1186 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1187 (make-variable-buffer-local 'org-clock-file-total-minutes
)
1189 (defun org-clock-sum (&optional tstart tend
)
1190 "Sum the times for each subtree.
1191 Puts the resulting times in minutes as a text property on each headline.
1192 TSTART and TEND can mark a time range to be considered."
1194 (let* ((bmp (buffer-modified-p))
1195 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1197 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1199 (ltimes (make-vector lmax
0))
1204 (if (stringp tstart
) (setq tstart
(org-time-string-to-seconds tstart
)))
1205 (if (stringp tend
) (setq tend
(org-time-string-to-seconds tend
)))
1206 (if (consp tstart
) (setq tstart
(org-float-time tstart
)))
1207 (if (consp tend
) (setq tend
(org-float-time tend
)))
1208 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
1210 (goto-char (point-max))
1211 (while (re-search-backward re nil t
)
1215 (setq ts
(match-string 2)
1218 (apply 'encode-time
(org-parse-time-string ts
)))
1220 (apply 'encode-time
(org-parse-time-string te
)))
1221 ts
(if tstart
(max ts tstart
) ts
)
1222 te
(if tend
(min te tend
) te
)
1224 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
1227 (setq t1
(+ t1
(string-to-number (match-string 5))
1228 (* 60 (string-to-number (match-string 4))))))
1230 (setq level
(- (match-end 1) (match-beginning 1)))
1231 (when (or (> t1
0) (> (aref ltimes level
) 0))
1232 (loop for l from
0 to level do
1233 (aset ltimes l
(+ (aref ltimes l
) t1
)))
1234 (setq t1
0 time
(aref ltimes level
))
1235 (loop for l from level to
(1- lmax
) do
1237 (goto-char (match-beginning 0))
1238 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
1239 (setq org-clock-file-total-minutes
(aref ltimes
0)))
1240 (set-buffer-modified-p bmp
)))
1242 (defun org-clock-sum-current-item (&optional tstart
)
1243 "Returns time, clocked on current item in total"
1246 (org-narrow-to-subtree)
1247 (org-clock-sum tstart
)
1248 org-clock-file-total-minutes
)))
1250 (defun org-clock-display (&optional total-only
)
1251 "Show subtree times in the entire buffer.
1252 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1255 (org-clock-remove-overlays)
1260 (goto-char (point-min))
1261 (while (or (and (equal (setq p
(point)) (point-min))
1262 (get-text-property p
:org-clock-minutes
))
1263 (setq p
(next-single-property-change
1264 (point) :org-clock-minutes
)))
1266 (when (setq time
(get-text-property p
:org-clock-minutes
))
1267 (org-clock-put-overlay time
(funcall outline-level
))))
1268 (setq h
(/ org-clock-file-total-minutes
60)
1269 m
(- org-clock-file-total-minutes
(* 60 h
)))
1270 ;; Arrange to remove the overlays upon next change.
1271 (when org-remove-highlights-with-change
1272 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
1274 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
1276 (defvar org-clock-overlays nil
)
1277 (make-variable-buffer-local 'org-clock-overlays
)
1279 (defun org-clock-put-overlay (time &optional level
)
1280 "Put an overlays on the current line, displaying TIME.
1281 If LEVEL is given, prefix time with a corresponding number of stars.
1282 This creates a new overlay and stores it in `org-clock-overlays', so that it
1283 will be easy to remove."
1284 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
1285 (l (if level
(org-get-valid-level level
0) 0))
1286 (fmt (concat "%s " org-time-clocksum-format
"%s"))
1289 (org-move-to-column c
)
1290 (unless (eolp) (skip-chars-backward "^ \t"))
1291 (skip-chars-backward " \t")
1292 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
1293 tx
(concat (buffer-substring (1- (point)) (point))
1294 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
1295 (org-add-props (format fmt
1296 (make-string l ?
*) h m
1297 (make-string (- 16 l
) ?\
))
1298 (list 'face
'org-clock-overlay
))
1300 (if (not (featurep 'xemacs
))
1301 (org-overlay-put ov
'display tx
)
1302 (org-overlay-put ov
'invisible t
)
1303 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
1304 (push ov org-clock-overlays
)))
1306 (defun org-clock-remove-overlays (&optional beg end noremove
)
1307 "Remove the occur highlights from the buffer.
1308 BEG and END are ignored. If NOREMOVE is nil, remove this function
1309 from the `before-change-functions' in the current buffer."
1311 (unless org-inhibit-highlight-removal
1312 (mapc 'org-delete-overlay org-clock-overlays
)
1313 (setq org-clock-overlays nil
)
1315 (remove-hook 'before-change-functions
1316 'org-clock-remove-overlays
'local
))))
1318 (defvar state
) ;; dynamically scoped into this function
1319 (defun org-clock-out-if-current ()
1320 "Clock out if the current entry contains the running clock.
1321 This is used to stop the clock after a TODO entry is marked DONE,
1322 and is only done if the variable `org-clock-out-when-done' is not nil."
1323 (when (and org-clock-out-when-done
1324 (member state org-done-keywords
)
1325 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker
))
1326 (marker-buffer org-clock-marker
))
1327 (or (buffer-base-buffer (current-buffer))
1329 (< (point) org-clock-marker
)
1330 (> (save-excursion (outline-next-heading) (point))
1332 ;; Clock out, but don't accept a logging message for this.
1333 (let ((org-log-note-clock-out nil
))
1336 (add-hook 'org-after-todo-state-change-hook
1337 'org-clock-out-if-current
)
1340 (defun org-get-clocktable (&rest props
)
1341 "Get a formatted clocktable with parameters according to PROPS.
1342 The table is created in a temporary buffer, fully formatted and
1343 fontified, and then returned."
1345 (setq props
(plist-put props
:name
"clocktable"))
1346 (unless (plist-member props
:maxlevel
)
1347 (setq props
(plist-put props
:maxlevel
2)))
1348 (unless (plist-member props
:scope
)
1349 (setq props
(plist-put props
:scope
'agenda
)))
1352 (org-create-dblock props
)
1354 (font-lock-fontify-buffer)
1356 (buffer-substring (point) (progn
1357 (re-search-forward "^#\\+END" nil t
)
1360 (defun org-clock-report (&optional arg
)
1361 "Create a table containing a report about clocked time.
1362 If the cursor is inside an existing clocktable block, then the table
1363 will be updated. If not, a new clocktable will be inserted.
1364 When called with a prefix argument, move to the first clock table in the
1365 buffer and update it."
1367 (org-clock-remove-overlays)
1369 (org-find-dblock "clocktable")
1371 (if (org-in-clocktable-p)
1372 (goto-char (org-in-clocktable-p))
1373 (org-create-dblock (append (list :name
"clocktable")
1374 org-clock-clocktable-default-properties
)))
1375 (org-update-dblock))
1377 (defun org-in-clocktable-p ()
1378 "Check if the cursor is in a clocktable."
1379 (let ((pos (point)) start
)
1382 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
1383 (setq start
(match-beginning 0))
1384 (re-search-forward "^#\\+END:.*" nil t
)
1385 (>= (match-end 0) pos
)
1388 (defun org-clock-special-range (key &optional time as-strings
)
1389 "Return two times bordering a special time range.
1390 Key is a symbol specifying the range and can be one of `today', `yesterday',
1391 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1392 A week starts Monday 0:00 and ends Sunday 24:00.
1393 The range is determined relative to TIME. TIME defaults to the current time.
1394 The return value is a cons cell with two internal times like the ones
1395 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1396 the returned times will be formatted strings."
1397 (if (integerp key
) (setq key
(intern (number-to-string key
))))
1398 (let* ((tm (decode-time (or time
(current-time))))
1399 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
1400 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
1402 (skey (symbol-name key
))
1404 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
1406 ((string-match "^[0-9]+$" skey
)
1407 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
1408 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1409 (setq y
(string-to-number (match-string 1 skey
))
1410 month
(string-to-number (match-string 2 skey
))
1412 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
1414 (setq y
(string-to-number (match-string 1 skey
))
1415 w
(string-to-number (match-string 2 skey
)))
1416 (setq date
(calendar-gregorian-from-absolute
1417 (calendar-absolute-from-iso (list w
1 y
))))
1418 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1421 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1422 (setq y
(string-to-number (match-string 1 skey
))
1423 month
(string-to-number (match-string 2 skey
))
1424 d
(string-to-number (match-string 3 skey
))
1426 ((string-match "\\([-+][0-9]+\\)$" skey
)
1427 (setq shift
(string-to-number (match-string 1 skey
))
1428 key
(intern (substring skey
0 (match-beginning 1))))))
1430 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
1431 ((eq key
'lastweek
) (setq key
'week shift -
1))
1432 ((eq key
'lastmonth
) (setq key
'month shift -
1))
1433 ((eq key
'lastyear
) (setq key
'year shift -
1))))
1435 ((memq key
'(day today
))
1436 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
1437 ((memq key
'(week thisweek
))
1438 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
1439 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
1440 ((memq key
'(month thismonth
))
1441 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
1442 ((memq key
'(year thisyear
))
1443 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
1444 (t (error "No such time block %s" key
)))
1445 (setq ts
(encode-time s m h d month y
)
1446 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
1447 (or d1 d
) (or month1 month
) (or y1 y
)))
1448 (setq fm
(cdr org-time-stamp-formats
))
1450 ((memq key
'(day today
))
1451 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
1452 ((memq key
'(week thisweek
))
1453 (setq txt
(format-time-string "week %G-W%V" ts
)))
1454 ((memq key
'(month thismonth
))
1455 (setq txt
(format-time-string "%B %Y" ts
)))
1456 ((memq key
'(year thisyear
))
1457 (setq txt
(format-time-string "the year %Y" ts
))))
1459 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
1462 (defun org-clocktable-shift (dir n
)
1463 "Try to shift the :block date of the clocktable at point.
1464 Point must be in the #+BEGIN: line of a clocktable, or this function
1465 will throw an error.
1466 DIR is a direction, a symbol `left', `right', `up', or `down'.
1467 Both `left' and `down' shift the block toward the past, `up' and `right'
1468 push it toward the future.
1469 N is the number of shift steps to take. The size of the step depends on
1470 the currently selected interval size."
1471 (setq n
(prefix-numeric-value n
))
1472 (and (memq dir
'(left down
)) (setq n
(- n
)))
1474 (goto-char (point-at-bol))
1475 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1476 (error "Line needs a :block definition before this command works")
1477 (let* ((b (match-beginning 1)) (e (match-end 1))
1478 (s (match-string 1))
1479 block shift ins y mw d date wp m
)
1481 ((equal s
"yesterday") (setq s
"today-1"))
1482 ((equal s
"lastweek") (setq s
"thisweek-1"))
1483 ((equal s
"lastmonth") (setq s
"thismonth-1"))
1484 ((equal s
"lastyear") (setq s
"thisyear-1")))
1486 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
1487 (setq block
(match-string 1 s
)
1488 shift
(if (match-end 2)
1489 (string-to-number (match-string 2 s
))
1491 (setq shift
(+ shift n
))
1492 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
1493 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
1494 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1495 (setq y
(string-to-number (match-string 1 s
))
1496 wp
(and (match-end 3) (match-string 3 s
))
1497 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
1498 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
1500 (d (setq ins
(format-time-string
1502 (encode-time 0 0 0 (+ d n
) m y
))))
1503 ((and wp mw
(> (length wp
) 0))
1505 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
1506 (setq ins
(format-time-string
1508 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1510 (setq ins
(format-time-string
1512 (encode-time 0 0 0 1 (+ mw n
) y
))))
1514 (setq ins
(number-to-string (+ y n
))))))
1515 (t (error "Cannot shift clocktable block")))
1519 (delete-region (point) (+ (point) (- e b
)))
1520 (beginning-of-line 1)
1524 (defun org-dblock-write:clocktable
(params)
1525 "Write the standard clocktable."
1527 (let* ((hlchars '((1 .
"*") (2 .
"/")))
1530 (scope (plist-get params
:scope
))
1531 (tostring (plist-get params
:tostring
))
1532 (multifile (plist-get params
:multifile
))
1533 (header (plist-get params
:header
))
1534 (maxlevel (or (plist-get params
:maxlevel
) 3))
1535 (step (plist-get params
:step
))
1536 (emph (plist-get params
:emphasize
))
1537 (timestamp (plist-get params
:timestamp
))
1538 (ts (plist-get params
:tstart
))
1539 (te (plist-get params
:tend
))
1540 (block (plist-get params
:block
))
1541 (link (plist-get params
:link
))
1542 ipos time p level hlc hdl tsp props content recalc formula pcol
1543 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st
)
1544 (setq org-clock-file-total-minutes nil
)
1546 (unless (or block
(and ts te
))
1547 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1548 (org-clocktable-steps params
)
1551 (setq cc
(org-clock-special-range block nil t
)
1552 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1553 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
1554 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
1555 (when (and ts
(listp ts
))
1556 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
1557 (when (and te
(listp te
))
1558 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
1559 ;; Now the times are strings we can parse.
1560 (if ts
(setq ts
(org-float-time
1561 (apply 'encode-time
(org-parse-time-string ts
)))))
1562 (if te
(setq te
(org-float-time
1563 (apply 'encode-time
(org-parse-time-string te
)))))
1564 (move-marker ins
(point))
1567 ;; Get the right scope
1570 ((and scope
(listp scope
) (symbolp (car scope
)))
1571 (setq scope
(eval scope
)))
1573 (setq scope
(org-agenda-files t
)))
1574 ((eq scope
'agenda-with-archives
)
1575 (setq scope
(org-agenda-files t
))
1576 (setq scope
(org-add-archive-files scope
)))
1577 ((eq scope
'file-with-archives
)
1578 (setq scope
(org-add-archive-files (list (buffer-file-name)))
1580 (setq scope-is-list
(and scope
(listp scope
)))
1584 ((eq scope
'file
) (widen))
1585 ((eq scope
'subtree
) (org-narrow-to-subtree))
1587 (while (org-up-heading-safe))
1588 (org-narrow-to-subtree))
1589 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
1590 (symbol-name scope
)))
1591 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
1593 (while (org-up-heading-safe)
1594 (looking-at outline-regexp
)
1595 (if (<= (org-reduced-level (funcall outline-level
)) level
)
1596 (throw 'exit nil
))))
1597 (org-narrow-to-subtree))
1599 (let* ((files scope
)
1601 (p1 (copy-sequence params
))
1603 (setq p1
(plist-put p1
:tostring t
))
1604 (setq p1
(plist-put p1
:multifile t
))
1605 (setq p1
(plist-put p1
:scope
'file
))
1606 (org-prepare-agenda-buffers files
)
1607 (while (setq file
(pop files
))
1608 (with-current-buffer (find-buffer-visiting file
)
1609 (setq tbl1
(org-dblock-write:clocktable p1
))
1611 (push (org-clocktable-add-file
1613 (concat "| |*File time*|*"
1614 (org-minutes-to-hh:mm-string
1615 org-clock-file-total-minutes
)
1618 (setq total-time
(+ (or total-time
0)
1619 org-clock-file-total-minutes
))))))))
1622 (unless scope-is-list
1623 (org-clock-sum ts te
)
1624 (goto-char (point-min))
1626 (while (or (and (bobp) (prog1 st
(setq st nil
))
1627 (get-text-property (point) :org-clock-minutes
)
1628 (setq p
(point-min)))
1629 (setq p
(next-single-property-change (point) :org-clock-minutes
)))
1631 (when (setq time
(get-text-property p
:org-clock-minutes
))
1633 (beginning-of-line 1)
1634 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1635 (setq level
(org-reduced-level
1636 (- (match-end 1) (match-beginning 1))))
1637 (<= level maxlevel
))
1638 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
1641 (org-make-link-string
1642 (format "file:%s::%s"
1645 (org-make-org-heading-search-string
1649 (setq props
(org-entry-properties (point)))
1650 (or (cdr (assoc "SCHEDULED" props
))
1651 (cdr (assoc "TIMESTAMP" props
))
1652 (cdr (assoc "DEADLINE" props
))
1653 (cdr (assoc "TIMESTAMP_IA" props
)))))
1654 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
1656 "| " (int-to-string level
) "|"
1657 (if timestamp
(concat tsp
"|") "")
1659 (make-string (1- level
) ?|
)
1660 hlc
(org-minutes-to-hh:mm-string time
) hlc
1662 (setq tbl
(nreverse tbl
))
1664 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
1666 (insert-before-markers
1669 "Clock summary at ["
1671 (format-time-string (cdr org-time-stamp-formats
))
1674 (if block
(concat ", for " range-text
".") "")
1676 (if scope-is-list
"|File" "")
1677 "|L|" (if timestamp
"Timestamp|" "") "Headline|Time|\n")
1678 (setq total-time
(or total-time org-clock-file-total-minutes
))
1679 (insert-before-markers
1681 (if scope-is-list
"|" "")
1682 (if timestamp
"|Timestamp|" "|")
1684 (org-minutes-to-hh:mm-string
(or total-time
0))
1686 (setq tbl
(delq nil tbl
))
1687 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
1688 (equal (substring (car tbl
) 0 2) "|-"))
1690 (insert-before-markers (mapconcat
1691 'identity
(delq nil tbl
)
1692 (if scope-is-list
"\n|-\n" "\n")))
1693 (backward-delete-char 1)
1694 (if (setq formula
(plist-get params
:formula
))
1697 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
1700 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1703 (+ 3 (if scope-is-list
1 0))
1704 (+ (if scope-is-list
1 0) 3)
1708 (insert "\n#+TBLFM: " formula
)
1710 (t (error "invalid formula in clocktable")))
1711 ;; Should we rescue an old formula?
1712 (when (stringp (setq content
(plist-get params
:content
)))
1713 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content
)
1715 (insert "\n" (match-string 1 (plist-get params
:content
)))
1716 (beginning-of-line 0))))
1718 (skip-chars-forward "^|")
1722 (save-excursion (org-table-goto-column pcol nil
'force
)
1724 (org-table-recalculate 'all
))
1725 (when rm-file-column
1727 (org-table-delete-column)))))))
1729 (defun org-clocktable-steps (params)
1730 (let* ((p1 (copy-sequence params
))
1731 (ts (plist-get p1
:tstart
))
1732 (te (plist-get p1
:tend
))
1733 (step0 (plist-get p1
:step
))
1734 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1735 (block (plist-get p1
:block
))
1738 (setq cc
(org-clock-special-range block nil t
)
1739 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1740 (if ts
(setq ts
(org-float-time
1741 (apply 'encode-time
(org-parse-time-string ts
)))))
1742 (if te
(setq te
(org-float-time
1743 (apply 'encode-time
(org-parse-time-string te
)))))
1744 (setq p1
(plist-put p1
:header
""))
1745 (setq p1
(plist-put p1
:step nil
))
1746 (setq p1
(plist-put p1
:block nil
))
1748 (or (bolp) (insert "\n"))
1749 (setq p1
(plist-put p1
:tstart
(format-time-string
1750 (org-time-stamp-format nil t
)
1751 (seconds-to-time ts
))))
1752 (setq p1
(plist-put p1
:tend
(format-time-string
1753 (org-time-stamp-format nil t
)
1754 (seconds-to-time (setq ts
(+ ts step
))))))
1755 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1756 (plist-get p1
:tstart
) "\n")
1757 (org-dblock-write:clocktable p1
)
1758 (re-search-forward "#\\+END:")
1761 (defun org-clocktable-add-file (file table
)
1763 (let ((lines (org-split-string table
"\n"))
1764 (ff (file-name-nondirectory file
)))
1765 (mapconcat 'identity
1767 (if (string-match org-table-dataline-regexp x
)
1773 (defun org-clock-time%
(total &rest strings
)
1774 "Compute a time fraction in percent.
1775 TOTAL s a time string like 10:21 specifying the total times.
1776 STRINGS is a list of strings that should be checked for a time.
1777 The first string that does have a time will be used.
1778 This function is made for clock tables."
1779 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1783 (if (not (string-match re total
))
1785 (setq tot
(+ (string-to-number (match-string 2 total
))
1786 (* 60 (string-to-number (match-string 1 total
)))))
1787 (if (= tot
0.
) (throw 'exit
0.
)))
1788 (while (setq s
(pop strings
))
1789 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1791 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1792 (* 60 (string-to-number (match-string 1 s
)))))
1796 (defun org-clock-save ()
1797 "Persist various clock-related data to disk.
1798 The details of what will be saved are regulated by the variable
1799 `org-clock-persist'."
1800 (when org-clock-persist
1802 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1804 (delete-region (point-min) (point-max))
1806 (insert (format ";; org-persist.el - %s at %s\n"
1807 system-name
(format-time-string
1808 (cdr org-time-stamp-formats
))))
1809 (if (and (setq b
(marker-buffer org-clock-marker
))
1810 (setq b
(or (buffer-base-buffer b
) b
))
1812 (buffer-file-name b
)
1813 (or (not org-clock-persist-query-save
)
1814 (y-or-n-p (concat "Save current clock ("
1815 (substring-no-properties org-clock-heading
)
1817 (insert "(setq resume-clock '(\""
1818 (buffer-file-name (marker-buffer org-clock-marker
))
1819 "\" . " (int-to-string (marker-position org-clock-marker
))
1821 ;; Store clocked task history. Tasks are stored reversed to make
1823 (when (and org-clock-history
(eq org-clock-persist t
))
1825 "(setq stored-clock-history '("
1828 (when (and (setq b
(marker-buffer m
))
1829 (setq b
(or (buffer-base-buffer b
) b
))
1831 (buffer-file-name b
))
1832 (concat "(\"" (buffer-file-name b
)
1833 "\" . " (int-to-string (marker-position m
))
1835 (reverse org-clock-history
) " ") "))\n"))
1837 (kill-buffer (current-buffer)))))))
1839 (defvar org-clock-loaded nil
1840 "Was the clock file loaded?")
1842 (defun org-clock-load ()
1843 "Load clock-related data from disk, maybe resuming a stored clock."
1844 (when (and org-clock-persist
(not org-clock-loaded
))
1845 (let ((filename (expand-file-name org-clock-persist-file
))
1846 (org-clock-in-resume 'auto-restart
)
1847 resume-clock stored-clock-history
)
1848 (if (not (file-readable-p filename
))
1849 (message "Not restoring clock data; %s not found"
1850 org-clock-persist-file
)
1851 (message "%s" "Restoring clock data")
1852 (setq org-clock-loaded t
)
1853 (load-file filename
)
1855 (when stored-clock-history
1856 (save-window-excursion
1857 (mapc (lambda (task)
1858 (if (file-exists-p (car task
))
1859 (org-clock-history-push (cdr task
)
1860 (find-file (car task
)))))
1861 stored-clock-history
)))
1863 (when (and resume-clock org-clock-persist
1864 (file-exists-p (car resume-clock
))
1865 (or (not org-clock-persist-query-resume
)
1869 (with-current-buffer (find-file (car resume-clock
))
1871 (goto-char (cdr resume-clock
))
1872 (org-back-to-heading t
)
1873 (and (looking-at org-complex-heading-regexp
)
1876 (when (file-exists-p (car resume-clock
))
1877 (with-current-buffer (find-file (car resume-clock
))
1878 (goto-char (cdr resume-clock
))
1880 (if (org-invisible-p)
1881 (org-show-context)))))))))
1884 (defun org-clock-persistence-insinuate ()
1885 "Set up hooks for clock persistence"
1886 (add-hook 'org-mode-hook
'org-clock-load
)
1887 (add-hook 'kill-emacs-hook
'org-clock-save
))
1889 ;; Suggested bindings
1890 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
1892 (provide 'org-clock
)
1894 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1896 ;;; org-clock.el ends here