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")))
216 (defcustom org-clock-auto-clock-resolution t
217 "When non-nil, do not resolve open clocks on clock-in."
221 (defvar org-clock-in-prepare-hook nil
222 "Hook run when preparing the clock.
223 This hook is run before anything happens to the task that
224 you want to clock in. For example, you can use this hook
225 to add an effort property.")
226 (defvar org-clock-in-hook nil
227 "Hook run when starting the clock.")
228 (defvar org-clock-out-hook nil
229 "Hook run when stopping the current clock.")
231 (defvar org-clock-cancel-hook nil
232 "Hook run when cancelling the current clock.")
233 (defvar org-clock-goto-hook nil
234 "Hook run when selecting the currently clocked-in entry.")
236 ;;; The clock for measuring work time.
238 (defvar org-mode-line-string
"")
239 (put 'org-mode-line-string
'risky-local-variable t
)
241 (defvar org-clock-mode-line-timer nil
)
242 (defvar org-clock-idle-timer nil
)
243 (defvar org-clock-heading
"")
244 (defvar org-clock-heading-for-remember
"")
245 (defvar org-clock-start-time
"")
247 (defvar org-clock-left-over-time nil
248 "If non-nil, user cancelled a clock; this is when leftover time started.")
250 (defvar org-clock-effort
""
251 "Effort estimate of the currently clocking task")
253 (defvar org-clock-total-time nil
254 "Holds total time, spent previously on currently clocked item.
255 This does not include the time in the currently running clock.")
257 (defvar org-clock-history nil
258 "List of marker pointing to recent clocked tasks.")
260 (defvar org-clock-default-task
(make-marker)
261 "Marker pointing to the default task that should clock time.
262 The clock can be made to switch to this task after clocking out
263 of a different task.")
265 (defvar org-clock-interrupted-task
(make-marker)
266 "Marker pointing to the task that has been interrupted by the current clock.")
268 (defvar org-clock-mode-line-map
(make-sparse-keymap))
269 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
270 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
272 (defun org-clock-menu ()
276 ["Clock out" org-clock-out t
]
277 ["Change effort estimate" org-clock-modify-effort-estimate t
]
278 ["Go to clock entry" org-clock-goto t
]
279 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
281 (defun org-clock-history-push (&optional pos buffer
)
282 "Push a marker to the clock history."
283 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
284 (let ((m (move-marker (make-marker) (or pos
(point)) buffer
)) n l
)
285 (while (setq n
(member m org-clock-history
))
286 (move-marker (car n
) nil
))
287 (setq org-clock-history
289 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
291 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
292 (setq org-clock-history
294 (nthcdr (- l org-clock-history-length -
1)
295 (nreverse org-clock-history
)))))
296 (push m org-clock-history
)))
298 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
299 "Save relative positions of markers in region."
300 (org-check-and-save-marker org-clock-marker beg end
)
301 (org-check-and-save-marker org-clock-hd-marker beg end
)
302 (org-check-and-save-marker org-clock-default-task beg end
)
303 (org-check-and-save-marker org-clock-interrupted-task beg end
)
304 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
307 (defun org-clock-select-task (&optional prompt
)
308 "Select a task that recently was associated with clocking."
310 (let (sel-list rpl
(i 0) s
)
311 (save-window-excursion
312 (org-switch-to-buffer-other-window
313 (get-buffer-create "*Clock Task Select*"))
315 (when (marker-buffer org-clock-default-task
)
316 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
317 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
319 (when (marker-buffer org-clock-interrupted-task
)
320 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
321 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
323 (when (marker-buffer org-clock-marker
)
324 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
325 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
327 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
330 (when (marker-buffer m
)
332 s
(org-clock-insert-selection-line
338 (org-fit-window-to-buffer)
339 (message (or prompt
"Select task for clocking:"))
340 (setq rpl
(read-char-exclusive))
344 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
345 (t (error "Invalid task choice %c" rpl
))))))
347 (defun org-clock-insert-selection-line (i marker
)
348 "Insert a line for the clock selection menu.
349 And return a cons cell with the selection character integer and the marker
351 (when (marker-buffer marker
)
352 (let (file cat task heading prefix
)
353 (with-current-buffer (org-base-buffer (marker-buffer marker
))
358 (setq file
(buffer-file-name (marker-buffer marker
))
359 cat
(or (org-get-category)
360 (progn (org-refresh-category-properties)
362 heading
(org-get-heading 'notags
)
363 prefix
(save-excursion
364 (org-back-to-heading t
)
368 (org-fontify-like-in-org-mode
369 (concat prefix heading
)
373 (insert (format "[%c] %-15s %s\n" i cat task
))
376 (defun org-clock-get-clock-string ()
377 "Form a clock-string, that will be show in the mode line.
378 If an effort estimate was defined for current item, use
379 01:30/01:50 format (clocked/estimated).
380 If not, show simply the clocked time like 01:50."
381 (let* ((clocked-time (org-clock-get-clocked-time))
382 (h (floor clocked-time
60))
383 (m (- clocked-time
(* 60 h
))))
384 (if (and org-clock-effort
)
385 (let* ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort
))
386 (effort-h (floor effort-in-minutes
60))
387 (effort-m (- effort-in-minutes
(* effort-h
60))))
388 (format (concat "-[" org-time-clocksum-format
"/" org-time-clocksum-format
" (%s)]")
389 h m effort-h effort-m org-clock-heading
))
390 (format (concat "-[" org-time-clocksum-format
" (%s)]")
391 h m org-clock-heading
))))
393 (defun org-clock-update-mode-line ()
394 (setq org-mode-line-string
396 (let ((clock-string (org-clock-get-clock-string))
397 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
398 (if (and (> org-clock-string-limit
0)
399 (> (length clock-string
) org-clock-string-limit
))
400 (org-propertize (substring clock-string
0 org-clock-string-limit
)
401 'help-echo
(concat help-text
": " org-clock-heading
))
402 (org-propertize clock-string
'help-echo help-text
)))
403 'local-map org-clock-mode-line-map
404 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)
405 'face
'org-mode-line-clock
))
406 (if org-clock-effort
(org-clock-notify-once-if-expired))
407 (force-mode-line-update))
409 (defun org-clock-get-clocked-time ()
410 "Get the clocked time for the current item in minutes.
411 The time returned includes the time spent on this task in
412 previous clocking intervals."
413 (let ((currently-clocked-time
414 (floor (- (org-float-time)
415 (org-float-time org-clock-start-time
)) 60)))
416 (+ currently-clocked-time
(or org-clock-total-time
0))))
418 (defun org-clock-modify-effort-estimate (&optional value
)
419 "Add to or set the effort estimate of the item currently being clocked.
420 VALUE can be a number of minutes, or a string with forat hh:mm or mm.
421 WHen the strig starts with a + or a - sign, the current value of the effort
422 property will be changed by that amount.
423 This will update the \"Effort\" property of currently clocked item, and
426 (when (org-clock-is-active)
427 (let ((current org-clock-effort
) sign
)
429 ;; Prompt user for a value or a change
432 (format "Set effort (hh:mm or mm%s): "
434 (format ", prefix + to add to %s" org-clock-effort
)
436 (when (stringp value
)
437 ;; A string. See if it is a delta
438 (setq sign
(string-to-char value
))
439 (if (member sign
'(?- ?
+))
440 (setq current
(org-hh:mm-string-to-minutes
(substring current
1)))
442 (setq value
(org-hh:mm-string-to-minutes value
))
444 (setq value
(- current value
))
445 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
446 (setq value
(max 0 value
)
447 org-clock-effort
(org-minutes-to-hh:mm-string value
))
448 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
449 (org-clock-update-mode-line)
450 (message "Effort is now %s" org-clock-effort
))))
452 (defvar org-clock-notification-was-shown nil
453 "Shows if we have shown notification already.")
455 (defun org-clock-notify-once-if-expired ()
456 "Show notification if we spent more time than we estimated before.
457 Notification is shown only once."
458 (when (marker-buffer org-clock-marker
)
459 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort
))
460 (clocked-time (org-clock-get-clocked-time)))
461 (if (>= clocked-time effort-in-minutes
)
462 (unless org-clock-notification-was-shown
463 (setq org-clock-notification-was-shown t
)
465 (format "Task '%s' should be finished by now. (%s)"
466 org-clock-heading org-clock-effort
) t
))
467 (setq org-clock-notification-was-shown nil
)))))
469 (defun org-notify (notification &optional play-sound
)
470 "Send a NOTIFICATION and maybe PLAY-SOUND."
471 (org-show-notification notification
)
472 (if play-sound
(org-clock-play-sound)))
474 (defun org-show-notification (notification)
476 Use `org-show-notification-handler' if defined,
477 use libnotify if available, or fall back on a message."
478 (cond ((functionp org-show-notification-handler
)
479 (funcall org-show-notification-handler notification
))
480 ((stringp org-show-notification-handler
)
481 (start-process "emacs-timer-notification" nil
482 org-show-notification-handler notification
))
483 ((org-program-exists "notify-send")
484 (start-process "emacs-timer-notification" nil
485 "notify-send" notification
))
486 ;; Maybe the handler will send a message, so only use message as
487 ;; a fall back option
488 (t (message notification
))))
490 (defun org-clock-play-sound ()
491 "Play sound as configured by `org-clock-sound'.
492 Use alsa's aplay tool if available."
494 ((not org-clock-sound
))
495 ((eq org-clock-sound t
) (beep t
) (beep t
))
496 ((stringp org-clock-sound
)
497 (if (file-exists-p org-clock-sound
)
498 (if (org-program-exists "aplay")
499 (start-process "org-clock-play-notification" nil
500 "aplay" org-clock-sound
)
502 (play-sound-file org-clock-sound
)
503 (error (beep t
) (beep t
))))))))
505 (defun org-program-exists (program-name)
506 "Checks whenever we can locate program and launch it."
507 (if (eq system-type
'gnu
/linux
)
508 (= 0 (call-process "which" nil nil nil program-name
))))
510 (defvar org-clock-mode-line-entry nil
511 "Information for the modeline about the running clock.")
513 (defun org-find-open-clocks (file)
514 "Search through the given file and find all open clocks."
515 (let ((buf (or (get-file-buffer file
)
516 (find-file-noselect file
)))
518 (with-current-buffer buf
520 (goto-char (point-min))
521 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t
)
522 (push (cons (copy-marker (1- (match-end 1)) t
)
523 (org-time-string-to-time (match-string 1))) clocks
))))
526 (defsubst org-is-active-clock
(clock)
527 "Return t if CLOCK is the currently active clock."
528 (and (org-clock-is-active)
529 (= org-clock-marker
(car clock
))))
531 (defmacro org-with-clock-position
(clock &rest forms
)
532 "Evaluate FORMS with CLOCK as the current active clock."
533 `(with-current-buffer (marker-buffer (car ,clock
))
537 (goto-char (car ,clock
))
541 (put 'org-with-clock-position
'lisp-indent-function
1)
543 (defmacro org-with-clock
(clock &rest forms
)
544 "Evaluate FORMS with CLOCK as the current active clock.
545 This macro also protects the current active clock from being altered."
546 `(org-with-clock-position ,clock
547 (let ((org-clock-start-time (cdr ,clock
))
548 (org-clock-total-time)
551 (org-clock-marker (car ,clock
))
552 (org-clock-hd-marker (save-excursion
553 (outline-back-to-heading t
)
557 (put 'org-with-clock
'lisp-indent-function
1)
559 (defsubst org-clock-clock-in
(clock &optional resume
)
560 "Clock in to the clock located by CLOCK.
561 If necessary, clock-out of the currently active clock."
562 (org-with-clock-position clock
563 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
566 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
567 "Clock out of the clock located by CLOCK."
568 (let ((temp (copy-marker (car clock
)
569 (marker-insertion-type (car clock
)))))
570 (if (org-is-active-clock clock
)
571 (org-clock-out fail-quietly at-time
)
572 (org-with-clock clock
573 (org-clock-out fail-quietly at-time
)))
574 (setcar clock temp
)))
576 (defsubst org-clock-clock-cancel
(clock)
577 "Cancel the clock located by CLOCK."
578 (let ((temp (copy-marker (car clock
)
579 (marker-insertion-type (car clock
)))))
580 (if (org-is-active-clock clock
)
582 (org-with-clock clock
584 (setcar clock temp
)))
586 (defvar org-clock-clocking-in nil
)
587 (defvar org-clock-resolving-clocks nil
)
588 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
590 (defun org-clock-resolve-clock (clock resolve-to
&optional close-p
591 restart-p fail-quietly
)
592 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
593 `CLOCK' is a cons cell of the form (MARKER START-TIME).
594 This routine can do one of many things:
596 if `RESOLVE-TO' is nil
597 if `CLOSE-P' is non-nil, give an error
598 if this clock is the active clock, cancel it
599 else delete the clock line (as if it never happened)
600 if `RESTART-P' is non-nil, start a new clock
602 else if `RESOLVE-TO' is the symbol `now'
603 if `RESTART-P' is non-nil, give an error
604 if `CLOSE-P' is non-nil, clock out the entry and
605 if this clock is the active clock, stop it
606 else if this clock is the active clock, do nothing
607 else if there is no active clock, resume this clock
608 else ask to cancel the active clock, and if so,
609 resume this clock after cancelling it
611 else if `RESOLVE-TO' is some date in the future
612 give an error about `RESOLVE-TO' being invalid
614 else if `RESOLVE-TO' is some date in the past
615 if `RESTART-P' is non-nil, give an error
616 if `CLOSE-P' is non-nil, enter a closing time and
617 if this clock is the active clock, stop it
618 else if this clock is the active clock, enter a
619 closing time, stop the current clock, then
620 start a new clock for the same item
621 else just enter a closing time for this clock
622 and then start a new clock for the same item"
623 (let ((org-clock-resolving-clocks t
))
626 (org-clock-clock-cancel clock
)
627 (if (and restart-p
(not org-clock-clocking-in
))
628 (org-clock-clock-in clock
)))
630 ((eq resolve-to
'now
)
632 (error "RESTART-P is not valid here"))
633 (if (or close-p org-clock-clocking-in
)
634 (org-clock-clock-out clock fail-quietly
)
635 (unless (org-is-active-clock clock
)
636 (org-clock-clock-in clock t
))))
638 ((not (time-less-p resolve-to
(current-time)))
639 (error "RESOLVE-TO must refer to a time in the past"))
643 (error "RESTART-P is not valid here"))
644 (org-clock-clock-out clock fail-quietly resolve-to
)
645 (unless org-clock-clocking-in
647 (setq org-clock-left-over-time resolve-to
)
648 (org-clock-clock-in clock
)))))))
650 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
651 "Resolve an open org-mode clock.
652 An open clock was found, with `dangling' possibly being non-nil.
653 If this function was invoked with a prefix argument, non-dangling
654 open clocks are ignored. The given clock requires some sort of
655 user intervention to resolve it, either because a clock was left
656 dangling or due to an idle timeout. The clock resolution can
659 (a) deleted, the user doesn't care about the clock
660 (b) restarted from the current time (if no other clock is open)
661 (c) closed, giving the clock X minutes
662 (d) closed and then restarted
663 (e) resumed, as if the user had never left
665 The format of clock is (CONS MARKER START-TIME), where MARKER
666 identifies the buffer and position the clock is open at (and
667 thus, the heading it's under), and START-TIME is when the clock
671 (save-window-excursion
673 (unless org-clock-resolving-clocks-due-to-idleness
674 (org-with-clock clock
676 (with-current-buffer (marker-buffer (car clock
))
677 (goto-char (car clock
))
678 (if org-clock-into-drawer
680 (outline-flag-region (save-excursion
681 (outline-back-to-heading t
)
682 (search-forward ":LOGBOOK:")
683 (goto-char (match-beginning 0)))
685 (outline-back-to-heading t
)
686 (search-forward ":LOGBOOK:")
687 (search-forward ":END:")
688 (goto-char (match-end 0)))
691 (while (null char-pressed
)
693 (read-char (concat (funcall prompt-fn clock
)
694 " [(kK)eep (sS)ubtract (C)ancel]? ")
697 (default (floor (/ (org-float-time
698 (time-subtract (current-time) last-valid
)) 60)))
699 (keep (and (memq ch
'(?k ?K
))
700 (read-number "Keep how many minutes? " default
)))
701 (subtractp (memq ch
'(?s ?S
)))
702 (barely-started-p (< (- (org-float-time last-valid
)
703 (org-float-time (cdr clock
))) 45))
704 (start-over (and subtractp barely-started-p
)))
706 (not (memq ch
'(?k ?K ?s ?S ?C
))))
708 (org-clock-resolve-clock
711 ;; If the time on the clock was less than a minute before
712 ;; the user went away, and they've ask to subtract all the
721 (time-add last-valid
(seconds-to-time (* 60 keep
)))))
724 (not (memq ch
'(?K ?S ?C
))))
727 (defun org-resolve-clocks (&optional also-non-dangling-p prompt-fn last-valid
)
728 "Resolve all currently open org-mode clocks.
729 If `also-non-dangling-p' is non-nil, also ask to resolve
730 non-dangling (i.e., currently open and valid) clocks."
732 (unless org-clock-resolving-clocks
733 (let ((org-clock-resolving-clocks t
))
734 (dolist (file (org-files-list))
735 (let ((clocks (org-find-open-clocks file
)))
736 (dolist (clock clocks
)
737 (let ((dangling (or (not (org-clock-is-active))
738 (/= (car clock
) org-clock-marker
))))
739 (unless (and (not dangling
) (not also-non-dangling-p
))
746 "Dangling clock started %d mins ago"
748 (/ (- (org-float-time (current-time))
749 (org-float-time (cdr clock
))) 60))))))
751 (cdr clock
)))))))))))
753 (defun org-emacs-idle-seconds ()
754 "Return the current Emacs idle time in seconds, or nil if not idle."
755 (let ((idle-time (current-idle-time)))
757 (org-float-time idle-time
)
760 (defun org-mac-idle-seconds ()
761 "Return the current Mac idle time in seconds"
762 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
764 (defun org-x11-idle-seconds ()
765 "Return the current X11 idle time in seconds"
766 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
768 (defun org-user-idle-seconds ()
769 "Return the number of seconds the user has been idle for.
770 This routine returns a floating point number."
771 (if (or (eq system-type
'darwin
) (eq window-system
'x
))
772 (let ((emacs-idle (org-emacs-idle-seconds)))
773 ;; If Emacs has been idle for longer than the user's
774 ;; `org-clock-idle-time' value, check whether the whole system has
775 ;; really been idle for that long.
776 (if (> emacs-idle
(* 60 org-clock-idle-time
))
777 (min emacs-idle
(if (eq system-type
'darwin
)
778 (org-mac-idle-seconds)
779 (org-x11-idle-seconds)))
781 (org-emacs-idle-seconds)))
783 (defvar org-clock-user-idle-seconds
)
785 (defun org-resolve-clocks-if-idle ()
786 "Resolve all currently open org-mode clocks.
787 This is performed after `org-clock-idle-time' minutes, to check
788 if the user really wants to stay clocked in after being idle for
790 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
792 (let ((org-clock-user-idle-seconds (org-user-idle-seconds))
793 (org-clock-resolving-clocks-due-to-idleness t
))
794 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
796 (cons org-clock-marker
797 org-clock-start-time
)
800 (format "Clocked in & idle for %d mins"
801 (/ org-clock-user-idle-seconds
60))))
802 (time-subtract (current-time)
803 (seconds-to-time org-clock-user-idle-seconds
)))))))
805 (defun org-clock-in (&optional select
)
806 "Start the clock on the current item.
807 If necessary, clock-out of the currently active clock.
808 With prefix arg SELECT, offer a list of recently clocked tasks to
809 clock into. When SELECT is `C-u C-u', clock into the current task and mark
810 is as the default task, a special task that will always be offered in
811 the clocking selection, associated with the letter `d'."
813 (setq org-clock-notification-was-shown nil
)
815 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
816 (marker-buffer org-clock-marker
)))
817 ts selected-task target-pos
(msg-extra "")
818 (left-over (and (not org-clock-resolving-clocks
)
819 org-clock-left-over-time
)))
820 (unless (or interrupting
821 org-clock-clocking-in
822 org-clock-resolving-clocks
823 (not org-clock-auto-clock-resolution
))
824 (setq org-clock-left-over-time nil
)
825 (let ((org-clock-clocking-in t
))
826 (org-resolve-clocks))) ; check if any clocks are dangling
827 (when (equal select
'(4))
828 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
830 (setq selected-task
(copy-marker selected-task
))
833 ;; We are interrupting the clocking of a different task.
834 ;; Save a marker to this task, so that we can go back.
835 (move-marker org-clock-interrupted-task
836 (marker-position org-clock-marker
)
837 (marker-buffer org-clock-marker
))
840 (when (equal select
'(16))
841 ;; Mark as default clocking task
842 (org-clock-mark-default-task))
844 ;; Clock in at which position?
846 (if (and (eobp) (not (org-on-heading-p)))
849 (run-hooks 'org-clock-in-prepare-hook
)
851 (when (and selected-task
(marker-buffer selected-task
))
852 ;; There is a selected task, move to the correct buffer
853 ;; and set the new target position.
854 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
855 (setq target-pos
(marker-position selected-task
))
856 (move-marker selected-task nil
))
860 (goto-char target-pos
)
861 (org-back-to-heading t
)
862 (or interrupting
(move-marker org-clock-interrupted-task nil
))
863 (org-clock-history-push)
864 (cond ((functionp org-clock-in-switch-to-state
)
865 (looking-at org-complex-heading-regexp
)
866 (let ((newstate (funcall org-clock-in-switch-to-state
868 (if newstate
(org-todo newstate
))))
869 ((and org-clock-in-switch-to-state
870 (not (looking-at (concat outline-regexp
"[ \t]*"
871 org-clock-in-switch-to-state
873 (org-todo org-clock-in-switch-to-state
)))
874 (setq org-clock-heading-for-remember
875 (and (looking-at org-complex-heading-regexp
)
877 (org-trim (buffer-substring (match-end 1)
879 (setq org-clock-heading
880 (cond ((and org-clock-heading-function
881 (functionp org-clock-heading-function
))
882 (funcall org-clock-heading-function
))
883 ((looking-at org-complex-heading-regexp
)
886 (setq org-clock-heading
(org-propertize org-clock-heading
888 (org-clock-find-position org-clock-in-resume
)
890 ((and org-clock-in-resume
892 (concat "^[ \t]* " org-clock-string
893 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
894 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
895 (message "Matched %s" (match-string 1))
896 (setq ts
(concat "[" (match-string 1) "]"))
897 (goto-char (match-end 1))
898 (setq org-clock-start-time
900 (org-parse-time-string (match-string 1))))
901 (setq org-clock-effort
(org-get-effort))
902 (setq org-clock-total-time
(org-clock-sum-current-item
903 (org-clock-get-sum-start))))
904 ((eq org-clock-in-resume
'auto-restart
)
905 ;; called from org-clock-load during startup,
906 ;; do not interrupt, but warn!
907 (message "Cannot restart clock because task does not contain unfinished clock")
912 (insert-before-markers "\n")
914 (org-indent-line-function)
915 (when (and (save-excursion
918 (beginning-of-line 1)
919 (org-indent-line-to (- (org-get-indentation) 2)))
920 (insert org-clock-string
" ")
921 (setq org-clock-effort
(org-get-effort))
922 (setq org-clock-total-time
(org-clock-sum-current-item
923 (org-clock-get-sum-start)))
924 (setq org-clock-start-time
928 "You stopped another clock %d mins ago; start this one from then? "
929 (/ (- (org-float-time (current-time))
930 (org-float-time left-over
)) 60)))
933 (setq ts
(org-insert-time-stamp org-clock-start-time
934 'with-hm
'inactive
))))
935 (move-marker org-clock-marker
(point) (buffer-base-buffer))
936 (move-marker org-clock-hd-marker
937 (save-excursion (org-back-to-heading t
) (point))
938 (buffer-base-buffer))
939 (or global-mode-string
(setq global-mode-string
'("")))
940 (or (memq 'org-mode-line-string global-mode-string
)
941 (setq global-mode-string
942 (append global-mode-string
'(org-mode-line-string))))
943 (org-clock-update-mode-line)
944 (when org-clock-mode-line-timer
945 (cancel-timer org-clock-mode-line-timer
)
946 (setq org-clock-mode-line-timer nil
))
947 (setq org-clock-mode-line-timer
948 (run-with-timer 60 60 'org-clock-update-mode-line
))
949 (when org-clock-idle-timer
950 (cancel-timer org-clock-idle-timer
)
951 (setq org-clock-idle-timer nil
))
952 (setq org-clock-idle-timer
953 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
954 (message "Clock starts at %s - %s" ts msg-extra
)
955 (run-hooks 'org-clock-in-hook
)))))))
957 (defun org-clock-mark-default-task ()
958 "Mark current task as default task."
961 (org-back-to-heading t
)
962 (move-marker org-clock-default-task
(point))))
965 (defun org-clock-get-sum-start ()
966 "Return the time from which clock times should be counted.
967 This is for the currently running clock as it is displayed
968 in the mode line. This function looks at the properties
969 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
970 corresponding variable `org-clock-modeline-total' and then
971 decides which time to use."
972 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
973 (symbol-name org-clock-modeline-total
)))
974 (lr (org-entry-get nil
"LAST_REPEAT")))
976 ((equal cmt
"current")
977 (setq msg-extra
"showing time in current clock instance")
980 (setq msg-extra
"showing today's task time.")
981 (let* ((dt (decode-time (current-time))))
982 (setq dt
(append (list 0 0 0) (nthcdr 3 dt
)))
983 (if org-extend-today-until
984 (setf (nth 2 dt
) org-extend-today-until
))
985 (apply 'encode-time dt
)))
986 ((or (equal cmt
"all")
987 (and (or (not cmt
) (equal cmt
"auto"))
989 (setq msg-extra
"showing entire task time.")
991 ((or (equal cmt
"repeat")
992 (and (or (not cmt
) (equal cmt
"auto"))
994 (setq msg-extra
"showing task time since last repeat.")
997 (org-time-string-to-time lr
)))
1000 (defun org-clock-find-position (find-unclosed)
1001 "Find the location where the next clock line should be inserted.
1002 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1003 line and position cursor in that line."
1004 (org-back-to-heading t
)
1006 (let ((beg (save-excursion
1007 (beginning-of-line 2)
1008 (or (bolp) (newline))
1010 (end (progn (outline-next-heading) (point)))
1011 (re (concat "^[ \t]*" org-clock-string
))
1013 (drawer (if (stringp org-clock-into-drawer
)
1014 org-clock-into-drawer
"LOGBOOK"))
1015 first last ind-last
)
1017 (when (and find-unclosed
1019 (concat "^[ \t]* " org-clock-string
1020 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1021 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1023 (beginning-of-line 1)
1025 (when (eobp) (newline) (setq end
(max (point) end
)))
1026 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
1027 ;; we seem to have a CLOCK drawer, so go there.
1028 (beginning-of-line 2)
1029 (or org-log-states-order-reversed
1030 (and (re-search-forward org-property-end-re nil t
)
1031 (goto-char (match-beginning 0))))
1033 ;; Lets count the CLOCK lines
1035 (while (re-search-forward re end t
)
1036 (setq first
(or first
(match-beginning 0))
1037 last
(match-beginning 0)
1039 (when (and (integerp org-clock-into-drawer
)
1041 (>= (1+ cnt
) org-clock-into-drawer
))
1042 ;; Wrap current entries into a new drawer
1044 (setq ind-last
(org-get-indentation))
1045 (beginning-of-line 2)
1046 (if (and (>= (org-get-indentation) ind-last
)
1050 (beginning-of-line 0)
1051 (org-indent-line-to ind-last
)
1053 (insert ":" drawer
":\n")
1054 (beginning-of-line 0)
1055 (org-indent-line-function)
1057 (beginning-of-line 2)
1058 (or org-log-states-order-reversed
1059 (and (re-search-forward org-property-end-re nil t
)
1060 (goto-char (match-beginning 0))))
1064 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1065 (not (equal (match-string 1) org-clock-string
)))
1066 ;; Planning info, skip to after it
1067 (beginning-of-line 2)
1068 (or (bolp) (newline)))
1069 (when (or (eq org-clock-into-drawer t
)
1070 (stringp org-clock-into-drawer
)
1071 (and (integerp org-clock-into-drawer
)
1072 (< org-clock-into-drawer
2)))
1073 (insert ":" drawer
":\n:END:\n")
1074 (beginning-of-line -
1)
1075 (org-indent-line-function)
1077 (beginning-of-line 2)
1078 (org-indent-line-function)
1080 (or org-log-states-order-reversed
1081 (and (re-search-forward org-property-end-re nil t
)
1082 (goto-char (match-beginning 0))))))))
1084 (defun org-clock-out (&optional fail-quietly at-time
)
1085 "Stop the currently running clock.
1086 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1089 (if (not (marker-buffer org-clock-marker
))
1090 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
1091 (let (ts te s h m remove
)
1093 (set-buffer (marker-buffer org-clock-marker
))
1096 (goto-char org-clock-marker
)
1097 (beginning-of-line 1)
1098 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1099 (equal (match-string 1) org-clock-string
))
1100 (setq ts
(match-string 2))
1101 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1102 (goto-char (match-end 0))
1103 (delete-region (point) (point-at-eol))
1105 (setq te
(org-insert-time-stamp (or at-time
(current-time))
1106 'with-hm
'inactive
))
1107 (setq s
(- (org-float-time (apply 'encode-time
(org-parse-time-string te
)))
1108 (org-float-time (apply 'encode-time
(org-parse-time-string ts
))))
1109 h
(floor (/ s
3600))
1113 (insert " => " (format "%2d:%02d" h m
))
1114 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
1116 (beginning-of-line 1)
1117 (delete-region (point) (point-at-eol))
1118 (and (looking-at "\n") (> (point-max) (1+ (point)))
1120 (move-marker org-clock-marker nil
)
1121 (move-marker org-clock-hd-marker nil
)
1122 (when org-log-note-clock-out
1123 (org-add-log-setup 'clock-out nil nil nil nil
1124 (concat "# Task: " (org-get-heading t
) "\n\n")))
1125 (when org-clock-mode-line-timer
1126 (cancel-timer org-clock-mode-line-timer
)
1127 (setq org-clock-mode-line-timer nil
))
1128 (when org-clock-idle-timer
1129 (cancel-timer org-clock-idle-timer
)
1130 (setq org-clock-idle-timer nil
))
1131 (setq global-mode-string
1132 (delq 'org-mode-line-string global-mode-string
))
1133 (when org-clock-out-switch-to-state
1135 (org-back-to-heading t
)
1136 (let ((org-inhibit-logging t
))
1138 ((functionp org-clock-out-switch-to-state
)
1139 (looking-at org-complex-heading-regexp
)
1140 (let ((newstate (funcall org-clock-out-switch-to-state
1142 (if newstate
(org-todo newstate
))))
1143 ((and org-clock-out-switch-to-state
1144 (not (looking-at (concat outline-regexp
"[ \t]*"
1145 org-clock-out-switch-to-state
1147 (org-todo org-clock-out-switch-to-state
))))))
1148 (force-mode-line-update)
1149 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
1150 (if remove
" => LINE REMOVED" ""))
1151 (run-hooks 'org-clock-out-hook
))))))
1153 (defun org-clock-cancel ()
1154 "Cancel the running clock be removing the start timestamp."
1156 (if (not (marker-buffer org-clock-marker
))
1157 (error "No active clock"))
1159 (set-buffer (marker-buffer org-clock-marker
))
1160 (goto-char org-clock-marker
)
1161 (delete-region (1- (point-at-bol)) (point-at-eol))
1162 ;; Just in case, remove any empty LOGBOOK left over
1163 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1164 (move-marker org-clock-marker nil
)
1165 (move-marker org-clock-hd-marker nil
)
1166 (setq global-mode-string
1167 (delq 'org-mode-line-string global-mode-string
))
1168 (force-mode-line-update)
1169 (message "Clock canceled")
1170 (run-hooks 'org-clock-cancel-hook
))
1172 (defun org-clock-goto (&optional select
)
1173 "Go to the currently clocked-in entry, or to the most recently clocked one.
1174 With prefix arg SELECT, offer recently clocked tasks for selection."
1179 (or (org-clock-select-task "Select task to go to: ")
1180 (error "No task selected")))
1181 ((marker-buffer org-clock-marker
) org-clock-marker
)
1182 ((and org-clock-goto-may-find-recent-task
1183 (car org-clock-history
)
1184 (marker-buffer (car org-clock-history
)))
1186 (car org-clock-history
))
1187 (t (error "No active or recent clock task")))))
1188 (switch-to-buffer (marker-buffer m
))
1189 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1192 (org-back-to-heading t
)
1193 (org-cycle-hide-drawers 'children
)
1196 (message "No running clock, this is the most recently clocked task"))
1197 (run-hooks 'org-clock-goto-hook
)))
1199 (defvar org-clock-file-total-minutes nil
1200 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1201 (make-variable-buffer-local 'org-clock-file-total-minutes
)
1203 (defun org-clock-sum (&optional tstart tend
)
1204 "Sum the times for each subtree.
1205 Puts the resulting times in minutes as a text property on each headline.
1206 TSTART and TEND can mark a time range to be considered."
1208 (let* ((bmp (buffer-modified-p))
1209 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1211 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1213 (ltimes (make-vector lmax
0))
1218 (if (stringp tstart
) (setq tstart
(org-time-string-to-seconds tstart
)))
1219 (if (stringp tend
) (setq tend
(org-time-string-to-seconds tend
)))
1220 (if (consp tstart
) (setq tstart
(org-float-time tstart
)))
1221 (if (consp tend
) (setq tend
(org-float-time tend
)))
1222 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
1224 (goto-char (point-max))
1225 (while (re-search-backward re nil t
)
1229 (setq ts
(match-string 2)
1232 (apply 'encode-time
(org-parse-time-string ts
)))
1234 (apply 'encode-time
(org-parse-time-string te
)))
1235 ts
(if tstart
(max ts tstart
) ts
)
1236 te
(if tend
(min te tend
) te
)
1238 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
1241 (setq t1
(+ t1
(string-to-number (match-string 5))
1242 (* 60 (string-to-number (match-string 4))))))
1244 (setq level
(- (match-end 1) (match-beginning 1)))
1245 (when (or (> t1
0) (> (aref ltimes level
) 0))
1246 (loop for l from
0 to level do
1247 (aset ltimes l
(+ (aref ltimes l
) t1
)))
1248 (setq t1
0 time
(aref ltimes level
))
1249 (loop for l from level to
(1- lmax
) do
1251 (goto-char (match-beginning 0))
1252 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
1253 (setq org-clock-file-total-minutes
(aref ltimes
0)))
1254 (set-buffer-modified-p bmp
)))
1256 (defun org-clock-sum-current-item (&optional tstart
)
1257 "Returns time, clocked on current item in total"
1260 (org-narrow-to-subtree)
1261 (org-clock-sum tstart
)
1262 org-clock-file-total-minutes
)))
1264 (defun org-clock-display (&optional total-only
)
1265 "Show subtree times in the entire buffer.
1266 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1269 (org-clock-remove-overlays)
1274 (goto-char (point-min))
1275 (while (or (and (equal (setq p
(point)) (point-min))
1276 (get-text-property p
:org-clock-minutes
))
1277 (setq p
(next-single-property-change
1278 (point) :org-clock-minutes
)))
1280 (when (setq time
(get-text-property p
:org-clock-minutes
))
1281 (org-clock-put-overlay time
(funcall outline-level
))))
1282 (setq h
(/ org-clock-file-total-minutes
60)
1283 m
(- org-clock-file-total-minutes
(* 60 h
)))
1284 ;; Arrange to remove the overlays upon next change.
1285 (when org-remove-highlights-with-change
1286 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
1288 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
1290 (defvar org-clock-overlays nil
)
1291 (make-variable-buffer-local 'org-clock-overlays
)
1293 (defun org-clock-put-overlay (time &optional level
)
1294 "Put an overlays on the current line, displaying TIME.
1295 If LEVEL is given, prefix time with a corresponding number of stars.
1296 This creates a new overlay and stores it in `org-clock-overlays', so that it
1297 will be easy to remove."
1298 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
1299 (l (if level
(org-get-valid-level level
0) 0))
1300 (fmt (concat "%s " org-time-clocksum-format
"%s"))
1303 (org-move-to-column c
)
1304 (unless (eolp) (skip-chars-backward "^ \t"))
1305 (skip-chars-backward " \t")
1306 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
1307 tx
(concat (buffer-substring (1- (point)) (point))
1308 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
1309 (org-add-props (format fmt
1310 (make-string l ?
*) h m
1311 (make-string (- 16 l
) ?\
))
1312 (list 'face
'org-clock-overlay
))
1314 (if (not (featurep 'xemacs
))
1315 (org-overlay-put ov
'display tx
)
1316 (org-overlay-put ov
'invisible t
)
1317 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
1318 (push ov org-clock-overlays
)))
1320 (defun org-clock-remove-overlays (&optional beg end noremove
)
1321 "Remove the occur highlights from the buffer.
1322 BEG and END are ignored. If NOREMOVE is nil, remove this function
1323 from the `before-change-functions' in the current buffer."
1325 (unless org-inhibit-highlight-removal
1326 (mapc 'org-delete-overlay org-clock-overlays
)
1327 (setq org-clock-overlays nil
)
1329 (remove-hook 'before-change-functions
1330 'org-clock-remove-overlays
'local
))))
1332 (defvar state
) ;; dynamically scoped into this function
1333 (defun org-clock-out-if-current ()
1334 "Clock out if the current entry contains the running clock.
1335 This is used to stop the clock after a TODO entry is marked DONE,
1336 and is only done if the variable `org-clock-out-when-done' is not nil."
1337 (when (and org-clock-out-when-done
1338 (member state org-done-keywords
)
1339 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker
))
1340 (marker-buffer org-clock-marker
))
1341 (or (buffer-base-buffer (current-buffer))
1343 (< (point) org-clock-marker
)
1344 (> (save-excursion (outline-next-heading) (point))
1346 ;; Clock out, but don't accept a logging message for this.
1347 (let ((org-log-note-clock-out nil
))
1350 (add-hook 'org-after-todo-state-change-hook
1351 'org-clock-out-if-current
)
1354 (defun org-get-clocktable (&rest props
)
1355 "Get a formatted clocktable with parameters according to PROPS.
1356 The table is created in a temporary buffer, fully formatted and
1357 fontified, and then returned."
1359 (setq props
(plist-put props
:name
"clocktable"))
1360 (unless (plist-member props
:maxlevel
)
1361 (setq props
(plist-put props
:maxlevel
2)))
1362 (unless (plist-member props
:scope
)
1363 (setq props
(plist-put props
:scope
'agenda
)))
1366 (org-create-dblock props
)
1368 (font-lock-fontify-buffer)
1370 (buffer-substring (point) (progn
1371 (re-search-forward "^#\\+END" nil t
)
1374 (defun org-clock-report (&optional arg
)
1375 "Create a table containing a report about clocked time.
1376 If the cursor is inside an existing clocktable block, then the table
1377 will be updated. If not, a new clocktable will be inserted.
1378 When called with a prefix argument, move to the first clock table in the
1379 buffer and update it."
1381 (org-clock-remove-overlays)
1383 (org-find-dblock "clocktable")
1385 (if (org-in-clocktable-p)
1386 (goto-char (org-in-clocktable-p))
1387 (org-create-dblock (append (list :name
"clocktable")
1388 org-clock-clocktable-default-properties
)))
1389 (org-update-dblock))
1391 (defun org-in-clocktable-p ()
1392 "Check if the cursor is in a clocktable."
1393 (let ((pos (point)) start
)
1396 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
1397 (setq start
(match-beginning 0))
1398 (re-search-forward "^#\\+END:.*" nil t
)
1399 (>= (match-end 0) pos
)
1402 (defun org-clock-special-range (key &optional time as-strings
)
1403 "Return two times bordering a special time range.
1404 Key is a symbol specifying the range and can be one of `today', `yesterday',
1405 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1406 A week starts Monday 0:00 and ends Sunday 24:00.
1407 The range is determined relative to TIME. TIME defaults to the current time.
1408 The return value is a cons cell with two internal times like the ones
1409 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1410 the returned times will be formatted strings."
1411 (if (integerp key
) (setq key
(intern (number-to-string key
))))
1412 (let* ((tm (decode-time (or time
(current-time))))
1413 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
1414 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
1416 (skey (symbol-name key
))
1418 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
1420 ((string-match "^[0-9]+$" skey
)
1421 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
1422 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1423 (setq y
(string-to-number (match-string 1 skey
))
1424 month
(string-to-number (match-string 2 skey
))
1426 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
1428 (setq y
(string-to-number (match-string 1 skey
))
1429 w
(string-to-number (match-string 2 skey
)))
1430 (setq date
(calendar-gregorian-from-absolute
1431 (calendar-absolute-from-iso (list w
1 y
))))
1432 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1435 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1436 (setq y
(string-to-number (match-string 1 skey
))
1437 month
(string-to-number (match-string 2 skey
))
1438 d
(string-to-number (match-string 3 skey
))
1440 ((string-match "\\([-+][0-9]+\\)$" skey
)
1441 (setq shift
(string-to-number (match-string 1 skey
))
1442 key
(intern (substring skey
0 (match-beginning 1))))))
1444 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
1445 ((eq key
'lastweek
) (setq key
'week shift -
1))
1446 ((eq key
'lastmonth
) (setq key
'month shift -
1))
1447 ((eq key
'lastyear
) (setq key
'year shift -
1))))
1449 ((memq key
'(day today
))
1450 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
1451 ((memq key
'(week thisweek
))
1452 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
1453 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
1454 ((memq key
'(month thismonth
))
1455 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
1456 ((memq key
'(year thisyear
))
1457 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
1458 (t (error "No such time block %s" key
)))
1459 (setq ts
(encode-time s m h d month y
)
1460 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
1461 (or d1 d
) (or month1 month
) (or y1 y
)))
1462 (setq fm
(cdr org-time-stamp-formats
))
1464 ((memq key
'(day today
))
1465 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
1466 ((memq key
'(week thisweek
))
1467 (setq txt
(format-time-string "week %G-W%V" ts
)))
1468 ((memq key
'(month thismonth
))
1469 (setq txt
(format-time-string "%B %Y" ts
)))
1470 ((memq key
'(year thisyear
))
1471 (setq txt
(format-time-string "the year %Y" ts
))))
1473 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
1476 (defun org-clocktable-shift (dir n
)
1477 "Try to shift the :block date of the clocktable at point.
1478 Point must be in the #+BEGIN: line of a clocktable, or this function
1479 will throw an error.
1480 DIR is a direction, a symbol `left', `right', `up', or `down'.
1481 Both `left' and `down' shift the block toward the past, `up' and `right'
1482 push it toward the future.
1483 N is the number of shift steps to take. The size of the step depends on
1484 the currently selected interval size."
1485 (setq n
(prefix-numeric-value n
))
1486 (and (memq dir
'(left down
)) (setq n
(- n
)))
1488 (goto-char (point-at-bol))
1489 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1490 (error "Line needs a :block definition before this command works")
1491 (let* ((b (match-beginning 1)) (e (match-end 1))
1492 (s (match-string 1))
1493 block shift ins y mw d date wp m
)
1495 ((equal s
"yesterday") (setq s
"today-1"))
1496 ((equal s
"lastweek") (setq s
"thisweek-1"))
1497 ((equal s
"lastmonth") (setq s
"thismonth-1"))
1498 ((equal s
"lastyear") (setq s
"thisyear-1")))
1500 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
1501 (setq block
(match-string 1 s
)
1502 shift
(if (match-end 2)
1503 (string-to-number (match-string 2 s
))
1505 (setq shift
(+ shift n
))
1506 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
1507 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
1508 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1509 (setq y
(string-to-number (match-string 1 s
))
1510 wp
(and (match-end 3) (match-string 3 s
))
1511 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
1512 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
1514 (d (setq ins
(format-time-string
1516 (encode-time 0 0 0 (+ d n
) m y
))))
1517 ((and wp mw
(> (length wp
) 0))
1519 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
1520 (setq ins
(format-time-string
1522 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1524 (setq ins
(format-time-string
1526 (encode-time 0 0 0 1 (+ mw n
) y
))))
1528 (setq ins
(number-to-string (+ y n
))))))
1529 (t (error "Cannot shift clocktable block")))
1533 (delete-region (point) (+ (point) (- e b
)))
1534 (beginning-of-line 1)
1538 (defun org-dblock-write:clocktable
(params)
1539 "Write the standard clocktable."
1541 (let* ((hlchars '((1 .
"*") (2 .
"/")))
1544 (scope (plist-get params
:scope
))
1545 (tostring (plist-get params
:tostring
))
1546 (multifile (plist-get params
:multifile
))
1547 (header (plist-get params
:header
))
1548 (maxlevel (or (plist-get params
:maxlevel
) 3))
1549 (step (plist-get params
:step
))
1550 (emph (plist-get params
:emphasize
))
1551 (timestamp (plist-get params
:timestamp
))
1552 (ts (plist-get params
:tstart
))
1553 (te (plist-get params
:tend
))
1554 (block (plist-get params
:block
))
1555 (link (plist-get params
:link
))
1556 ipos time p level hlc hdl tsp props content recalc formula pcol
1557 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st
)
1558 (setq org-clock-file-total-minutes nil
)
1560 (unless (or block
(and ts te
))
1561 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1562 (org-clocktable-steps params
)
1565 (setq cc
(org-clock-special-range block nil t
)
1566 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1567 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
1568 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
1569 (when (and ts
(listp ts
))
1570 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
1571 (when (and te
(listp te
))
1572 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
1573 ;; Now the times are strings we can parse.
1574 (if ts
(setq ts
(org-float-time
1575 (apply 'encode-time
(org-parse-time-string ts
)))))
1576 (if te
(setq te
(org-float-time
1577 (apply 'encode-time
(org-parse-time-string te
)))))
1578 (move-marker ins
(point))
1581 ;; Get the right scope
1584 ((and scope
(listp scope
) (symbolp (car scope
)))
1585 (setq scope
(eval scope
)))
1587 (setq scope
(org-agenda-files t
)))
1588 ((eq scope
'agenda-with-archives
)
1589 (setq scope
(org-agenda-files t
))
1590 (setq scope
(org-add-archive-files scope
)))
1591 ((eq scope
'file-with-archives
)
1592 (setq scope
(org-add-archive-files (list (buffer-file-name)))
1594 (setq scope-is-list
(and scope
(listp scope
)))
1598 ((eq scope
'file
) (widen))
1599 ((eq scope
'subtree
) (org-narrow-to-subtree))
1601 (while (org-up-heading-safe))
1602 (org-narrow-to-subtree))
1603 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
1604 (symbol-name scope
)))
1605 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
1607 (while (org-up-heading-safe)
1608 (looking-at outline-regexp
)
1609 (if (<= (org-reduced-level (funcall outline-level
)) level
)
1610 (throw 'exit nil
))))
1611 (org-narrow-to-subtree))
1613 (let* ((files scope
)
1615 (p1 (copy-sequence params
))
1617 (setq p1
(plist-put p1
:tostring t
))
1618 (setq p1
(plist-put p1
:multifile t
))
1619 (setq p1
(plist-put p1
:scope
'file
))
1620 (org-prepare-agenda-buffers files
)
1621 (while (setq file
(pop files
))
1622 (with-current-buffer (find-buffer-visiting file
)
1623 (setq tbl1
(org-dblock-write:clocktable p1
))
1625 (push (org-clocktable-add-file
1627 (concat "| |*File time*|*"
1628 (org-minutes-to-hh:mm-string
1629 org-clock-file-total-minutes
)
1632 (setq total-time
(+ (or total-time
0)
1633 org-clock-file-total-minutes
))))))))
1636 (unless scope-is-list
1637 (org-clock-sum ts te
)
1638 (goto-char (point-min))
1640 (while (or (and (bobp) (prog1 st
(setq st nil
))
1641 (get-text-property (point) :org-clock-minutes
)
1642 (setq p
(point-min)))
1643 (setq p
(next-single-property-change (point) :org-clock-minutes
)))
1645 (when (setq time
(get-text-property p
:org-clock-minutes
))
1647 (beginning-of-line 1)
1648 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1649 (setq level
(org-reduced-level
1650 (- (match-end 1) (match-beginning 1))))
1651 (<= level maxlevel
))
1652 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
1655 (org-make-link-string
1656 (format "file:%s::%s"
1659 (org-make-org-heading-search-string
1663 (setq props
(org-entry-properties (point)))
1664 (or (cdr (assoc "SCHEDULED" props
))
1665 (cdr (assoc "TIMESTAMP" props
))
1666 (cdr (assoc "DEADLINE" props
))
1667 (cdr (assoc "TIMESTAMP_IA" props
)))))
1668 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
1670 "| " (int-to-string level
) "|"
1671 (if timestamp
(concat tsp
"|") "")
1673 (make-string (1- level
) ?|
)
1674 hlc
(org-minutes-to-hh:mm-string time
) hlc
1676 (setq tbl
(nreverse tbl
))
1678 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
1680 (insert-before-markers
1683 "Clock summary at ["
1685 (format-time-string (cdr org-time-stamp-formats
))
1688 (if block
(concat ", for " range-text
".") "")
1690 (if scope-is-list
"|File" "")
1691 "|L|" (if timestamp
"Timestamp|" "") "Headline|Time|\n")
1692 (setq total-time
(or total-time org-clock-file-total-minutes
))
1693 (insert-before-markers
1695 (if scope-is-list
"|" "")
1696 (if timestamp
"|Timestamp|" "|")
1698 (org-minutes-to-hh:mm-string
(or total-time
0))
1700 (setq tbl
(delq nil tbl
))
1701 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
1702 (equal (substring (car tbl
) 0 2) "|-"))
1704 (insert-before-markers (mapconcat
1705 'identity
(delq nil tbl
)
1706 (if scope-is-list
"\n|-\n" "\n")))
1707 (backward-delete-char 1)
1708 (if (setq formula
(plist-get params
:formula
))
1711 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
1714 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1717 (+ 3 (if scope-is-list
1 0))
1718 (+ (if scope-is-list
1 0) 3)
1722 (insert "\n#+TBLFM: " formula
)
1724 (t (error "invalid formula in clocktable")))
1725 ;; Should we rescue an old formula?
1726 (when (stringp (setq content
(plist-get params
:content
)))
1727 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content
)
1729 (insert "\n" (match-string 1 (plist-get params
:content
)))
1730 (beginning-of-line 0))))
1732 (skip-chars-forward "^|")
1736 (save-excursion (org-table-goto-column pcol nil
'force
)
1738 (org-table-recalculate 'all
))
1739 (when rm-file-column
1741 (org-table-delete-column)))))))
1743 (defun org-clocktable-steps (params)
1744 (let* ((p1 (copy-sequence params
))
1745 (ts (plist-get p1
:tstart
))
1746 (te (plist-get p1
:tend
))
1747 (step0 (plist-get p1
:step
))
1748 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1749 (block (plist-get p1
:block
))
1752 (setq cc
(org-clock-special-range block nil t
)
1753 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1754 (if ts
(setq ts
(org-float-time
1755 (apply 'encode-time
(org-parse-time-string ts
)))))
1756 (if te
(setq te
(org-float-time
1757 (apply 'encode-time
(org-parse-time-string te
)))))
1758 (setq p1
(plist-put p1
:header
""))
1759 (setq p1
(plist-put p1
:step nil
))
1760 (setq p1
(plist-put p1
:block nil
))
1762 (or (bolp) (insert "\n"))
1763 (setq p1
(plist-put p1
:tstart
(format-time-string
1764 (org-time-stamp-format nil t
)
1765 (seconds-to-time ts
))))
1766 (setq p1
(plist-put p1
:tend
(format-time-string
1767 (org-time-stamp-format nil t
)
1768 (seconds-to-time (setq ts
(+ ts step
))))))
1769 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1770 (plist-get p1
:tstart
) "\n")
1771 (org-dblock-write:clocktable p1
)
1772 (re-search-forward "#\\+END:")
1775 (defun org-clocktable-add-file (file table
)
1777 (let ((lines (org-split-string table
"\n"))
1778 (ff (file-name-nondirectory file
)))
1779 (mapconcat 'identity
1781 (if (string-match org-table-dataline-regexp x
)
1787 (defun org-clock-time%
(total &rest strings
)
1788 "Compute a time fraction in percent.
1789 TOTAL s a time string like 10:21 specifying the total times.
1790 STRINGS is a list of strings that should be checked for a time.
1791 The first string that does have a time will be used.
1792 This function is made for clock tables."
1793 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1797 (if (not (string-match re total
))
1799 (setq tot
(+ (string-to-number (match-string 2 total
))
1800 (* 60 (string-to-number (match-string 1 total
)))))
1801 (if (= tot
0.
) (throw 'exit
0.
)))
1802 (while (setq s
(pop strings
))
1803 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1805 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1806 (* 60 (string-to-number (match-string 1 s
)))))
1810 (defun org-clock-save ()
1811 "Persist various clock-related data to disk.
1812 The details of what will be saved are regulated by the variable
1813 `org-clock-persist'."
1814 (when org-clock-persist
1816 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1818 (delete-region (point-min) (point-max))
1820 (insert (format ";; org-persist.el - %s at %s\n"
1821 system-name
(format-time-string
1822 (cdr org-time-stamp-formats
))))
1823 (if (and (setq b
(marker-buffer org-clock-marker
))
1824 (setq b
(or (buffer-base-buffer b
) b
))
1826 (buffer-file-name b
)
1827 (or (not org-clock-persist-query-save
)
1828 (y-or-n-p (concat "Save current clock ("
1829 (substring-no-properties org-clock-heading
)
1831 (insert "(setq resume-clock '(\""
1832 (buffer-file-name (marker-buffer org-clock-marker
))
1833 "\" . " (int-to-string (marker-position org-clock-marker
))
1835 ;; Store clocked task history. Tasks are stored reversed to make
1837 (when (and org-clock-history
(eq org-clock-persist t
))
1839 "(setq stored-clock-history '("
1842 (when (and (setq b
(marker-buffer m
))
1843 (setq b
(or (buffer-base-buffer b
) b
))
1845 (buffer-file-name b
))
1846 (concat "(\"" (buffer-file-name b
)
1847 "\" . " (int-to-string (marker-position m
))
1849 (reverse org-clock-history
) " ") "))\n"))
1851 (kill-buffer (current-buffer)))))))
1853 (defvar org-clock-loaded nil
1854 "Was the clock file loaded?")
1856 (defun org-clock-load ()
1857 "Load clock-related data from disk, maybe resuming a stored clock."
1858 (when (and org-clock-persist
(not org-clock-loaded
))
1859 (let ((filename (expand-file-name org-clock-persist-file
))
1860 (org-clock-in-resume 'auto-restart
)
1861 resume-clock stored-clock-history
)
1862 (if (not (file-readable-p filename
))
1863 (message "Not restoring clock data; %s not found"
1864 org-clock-persist-file
)
1865 (message "%s" "Restoring clock data")
1866 (setq org-clock-loaded t
)
1867 (load-file filename
)
1869 (when stored-clock-history
1870 (save-window-excursion
1871 (mapc (lambda (task)
1872 (if (file-exists-p (car task
))
1873 (org-clock-history-push (cdr task
)
1874 (find-file (car task
)))))
1875 stored-clock-history
)))
1877 (when (and resume-clock org-clock-persist
1878 (file-exists-p (car resume-clock
))
1879 (or (not org-clock-persist-query-resume
)
1883 (with-current-buffer (find-file (car resume-clock
))
1885 (goto-char (cdr resume-clock
))
1886 (org-back-to-heading t
)
1887 (and (looking-at org-complex-heading-regexp
)
1890 (when (file-exists-p (car resume-clock
))
1891 (with-current-buffer (find-file (car resume-clock
))
1892 (goto-char (cdr resume-clock
))
1894 (if (org-invisible-p)
1895 (org-show-context)))))))))
1898 (defun org-clock-persistence-insinuate ()
1899 "Set up hooks for clock persistence"
1900 (add-hook 'org-mode-hook
'org-clock-load
)
1901 (add-hook 'kill-emacs-hook
'org-clock-save
))
1903 ;; Suggested bindings
1904 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
1906 (provide 'org-clock
)
1908 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1910 ;;; org-clock.el ends here