1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the time clocking code for Org-mode
38 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
39 (declare-function notifications-notify
"notifications" (&rest params
))
40 (defvar org-time-stamp-formats
)
42 (defgroup org-clock nil
43 "Options concerning clocking working time in Org-mode."
47 (defcustom org-clock-into-drawer org-log-into-drawer
48 "Should clocking info be wrapped into a drawer?
49 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
50 If necessary, the drawer will be created.
51 When nil, the drawer will not be created, but used when present.
52 When an integer and the number of clocking entries in an item
53 reaches or exceeds this number, a drawer will be created.
54 When a string, it names the drawer to be used.
56 The default for this variable is the value of `org-log-into-drawer',
61 (const :tag
"Always" t
)
62 (const :tag
"Only when drawer exists" nil
)
63 (integer :tag
"When at least N clock entries")
64 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
65 (string :tag
"Into Drawer named...")))
67 (defcustom org-clock-out-when-done t
68 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
69 DONE here means any DONE-like state.
70 A nil value means clock will keep running until stopped explicitly with
71 `C-c C-x C-o', or until the clock is started in a different item.
72 Instead of t, this can also be a list of TODO states that should trigger
77 (const :tag
"Yes, when done" t
)
78 (repeat :tag
"State list"
79 (string :tag
"TODO keyword"))))
81 (defcustom org-clock-out-remove-zero-time-clocks nil
82 "Non-nil means remove the clock line when the resulting time is zero."
86 (defcustom org-clock-in-switch-to-state nil
87 "Set task to a special todo state while clocking it.
88 The value should be the state to which the entry should be
89 switched. If the value is a function, it must take one
90 parameter (the current TODO state of the item) and return the
91 state to switch it to."
95 (const :tag
"Don't force a state" nil
)
97 (symbol :tag
"Function")))
99 (defcustom org-clock-out-switch-to-state nil
100 "Set task to a special todo state after clocking out.
101 The value should be the state to which the entry should be
102 switched. If the value is a function, it must take one
103 parameter (the current TODO state of the item) and return the
104 state to switch it to."
108 (const :tag
"Don't force a state" nil
)
109 (string :tag
"State")
110 (symbol :tag
"Function")))
112 (defcustom org-clock-history-length
5
113 "Number of clock tasks to remember in history."
117 (defcustom org-clock-goto-may-find-recent-task t
118 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
122 (defcustom org-clock-heading-function nil
123 "When non-nil, should be a function to create `org-clock-heading'.
124 This is the string shown in the mode line when a clock is running.
125 The function is called with point at the beginning of the headline."
129 (defcustom org-clock-string-limit
0
130 "Maximum length of clock strings in the modeline. 0 means no limit."
134 (defcustom org-clock-in-resume nil
135 "If non-nil, resume clock when clocking into task with open clock.
136 When clocking into a task with a clock entry which has not been closed,
137 the clock can be resumed from that point."
141 (defcustom org-clock-persist nil
142 "When non-nil, save the running clock when Emacs is closed.
143 The clock is resumed when Emacs restarts.
144 When this is t, both the running clock, and the entire clock
145 history are saved. When this is the symbol `clock', only the
146 running clock is saved.
148 When Emacs restarts with saved clock information, the file containing the
149 running clock as well as all files mentioned in the clock history will
151 All this depends on running `org-clock-persistence-insinuate' in .emacs"
154 (const :tag
"Just the running clock" clock
)
155 (const :tag
"Just the history" history
)
156 (const :tag
"Clock and history" t
)
157 (const :tag
"No persistence" nil
)))
159 (defcustom org-clock-persist-file
(convert-standard-filename
160 "~/.emacs.d/org-clock-save.el")
161 "File to save clock data to."
165 (defcustom org-clock-persist-query-save nil
166 "When non-nil, ask before saving the current clock on exit."
170 (defcustom org-clock-persist-query-resume t
171 "When non-nil, ask before resuming any stored clock during load."
175 (defcustom org-clock-sound nil
176 "Sound that will used for notifications.
180 t standard Emacs beep
181 file name play this sound file. If not possible, fall back to beep"
184 (const :tag
"No sound" nil
)
185 (const :tag
"Standard beep" t
)
186 (file :tag
"Play sound file")))
188 (defcustom org-clock-modeline-total
'auto
189 "Default setting for the time included for the modeline clock.
190 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
193 current Only the time in the current instance of the clock
194 today All time clocked into this task today
195 repeat All time clocked into this task since last repeat
196 all All time ever recorded for this task
197 auto Automatically, either `all', or `repeat' for repeating tasks"
200 (const :tag
"Current clock" current
)
201 (const :tag
"Today's task time" today
)
202 (const :tag
"Since last repeat" repeat
)
203 (const :tag
"All task time" all
)
204 (const :tag
"Automatically, `all' or since `repeat'" auto
)))
206 (defcustom org-task-overrun-text nil
207 "The extra modeline text that should indicate that the clock is overrun.
208 The can be nil to indicate that instead of adding text, the clock time
209 should get a different face (`org-mode-line-clock-overrun').
210 When this is a string, it is prepended to the clock string as an indication,
211 also using the face `org-mode-line-clock-overrun'."
214 (const :tag
"Just mark the time string" nil
)
215 (string :tag
"Text to prepend")))
217 (defcustom org-show-notification-handler nil
218 "Function or program to send notification with.
219 The function or program will be called with the notification
223 (string :tag
"Program")
224 (function :tag
"Function")))
226 (defgroup org-clocktable nil
227 "Options concerning the clock table in Org-mode."
228 :tag
"Org Clock Table"
231 (defcustom org-clocktable-defaults
234 :lang
,org-export-default-language
252 "Default properties for clock tables."
256 (defcustom org-clock-clocktable-formatter
'org-clocktable-write-default
257 "Function to turn clocking data into a table.
258 For more information, see `org-clocktable-write-default'."
259 :group
'org-clocktable
262 (defcustom org-clock-clocktable-language-setup
263 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time")
264 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo")
265 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier")
266 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd"))
267 "Terms used in clocktable, translated to different languages."
268 :group
'org-clocktable
271 (defcustom org-clock-clocktable-default-properties
'(:maxlevel
2 :scope file
)
272 "Default properties for new clocktables.
273 These will be inserted into the BEGIN line, to make it easy for users to
275 :group
'org-clocktable
278 (defcustom org-clock-idle-time nil
279 "When non-nil, resolve open clocks if the user is idle more than X minutes."
282 (const :tag
"Never" nil
)
283 (integer :tag
"After N minutes")))
285 (defcustom org-clock-auto-clock-resolution
'when-no-clock-is-running
286 "When to automatically resolve open clocks found in Org buffers."
289 (const :tag
"Never" nil
)
290 (const :tag
"Always" t
)
291 (const :tag
"When no clock is running" when-no-clock-is-running
)))
293 (defcustom org-clock-report-include-clocking-task nil
294 "When non-nil, include the current clocking task time in clock reports."
298 (defcustom org-clock-resolve-expert nil
299 "Non-nil means do not show the splash buffer with the clock resolver."
303 (defvar org-clock-in-prepare-hook nil
304 "Hook run when preparing the clock.
305 This hook is run before anything happens to the task that
306 you want to clock in. For example, you can use this hook
307 to add an effort property.")
308 (defvar org-clock-in-hook nil
309 "Hook run when starting the clock.")
310 (defvar org-clock-out-hook nil
311 "Hook run when stopping the current clock.")
313 (defvar org-clock-cancel-hook nil
314 "Hook run when cancelling the current clock.")
315 (defvar org-clock-goto-hook nil
316 "Hook run when selecting the currently clocked-in entry.")
317 (defvar org-clock-has-been-used nil
318 "Has the clock been used during the current Emacs session?")
320 ;;; The clock for measuring work time.
322 (defvar org-mode-line-string
"")
323 (put 'org-mode-line-string
'risky-local-variable t
)
325 (defvar org-clock-mode-line-timer nil
)
326 (defvar org-clock-idle-timer nil
)
327 (defvar org-clock-heading
) ; defined in org.el
328 (defvar org-clock-heading-for-remember
"")
329 (defvar org-clock-start-time
"")
331 (defvar org-clock-leftover-time nil
332 "If non-nil, user cancelled a clock; this is when leftover time started.")
334 (defvar org-clock-effort
""
335 "Effort estimate of the currently clocking task.")
337 (defvar org-clock-total-time nil
338 "Holds total time, spent previously on currently clocked item.
339 This does not include the time in the currently running clock.")
341 (defvar org-clock-history nil
342 "List of marker pointing to recent clocked tasks.")
344 (defvar org-clock-default-task
(make-marker)
345 "Marker pointing to the default task that should clock time.
346 The clock can be made to switch to this task after clocking out
347 of a different task.")
349 (defvar org-clock-interrupted-task
(make-marker)
350 "Marker pointing to the task that has been interrupted by the current clock.")
352 (defvar org-clock-mode-line-map
(make-sparse-keymap))
353 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
354 (define-key org-clock-mode-line-map
[mode-line mouse-1
] 'org-clock-menu
)
356 (defun org-clock-menu ()
360 ["Clock out" org-clock-out t
]
361 ["Change effort estimate" org-clock-modify-effort-estimate t
]
362 ["Go to clock entry" org-clock-goto t
]
363 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t
:keys
"C-u C-c C-x C-i"])))
365 (defun org-clock-history-push (&optional pos buffer
)
366 "Push a marker to the clock history."
367 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
368 (let ((m (move-marker (make-marker)
369 (or pos
(point)) (org-base-buffer
370 (or buffer
(current-buffer)))))
372 (while (setq n
(member m org-clock-history
))
373 (move-marker (car n
) nil
))
374 (setq org-clock-history
376 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
378 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
379 (setq org-clock-history
381 (nthcdr (- l org-clock-history-length -
1)
382 (nreverse org-clock-history
)))))
383 (push m org-clock-history
)))
385 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
386 "Save relative positions of markers in region."
387 (org-check-and-save-marker org-clock-marker beg end
)
388 (org-check-and-save-marker org-clock-hd-marker beg end
)
389 (org-check-and-save-marker org-clock-default-task beg end
)
390 (org-check-and-save-marker org-clock-interrupted-task beg end
)
391 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
394 (defun org-clocking-buffer ()
395 "Return the clocking buffer if we are currently clocking a task or nil."
396 (marker-buffer org-clock-marker
))
398 (defun org-clocking-p ()
399 "Return t when clocking a task."
400 (not (equal (org-clocking-buffer) nil
)))
402 (defvar org-clock-before-select-task-hook nil
403 "Hook called in task selection just before prompting the user.")
405 (defun org-clock-select-task (&optional prompt
)
406 "Select a task that recently was associated with clocking."
408 (let (sel-list rpl
(i 0) s
)
409 (save-window-excursion
410 (org-switch-to-buffer-other-window
411 (get-buffer-create "*Clock Task Select*"))
413 (when (marker-buffer org-clock-default-task
)
414 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
415 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
417 (when (marker-buffer org-clock-interrupted-task
)
418 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
419 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
421 (when (org-clocking-p)
422 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
423 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
425 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
428 (when (marker-buffer m
)
430 s
(org-clock-insert-selection-line
434 (if (fboundp 'int-to-char
) (setf (car s
) (int-to-char (car s
))))
437 (run-hooks 'org-clock-before-select-task-hook
)
438 (org-fit-window-to-buffer)
439 (message (or prompt
"Select task for clocking:"))
440 (setq rpl
(read-char-exclusive))
444 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
445 (t (error "Invalid task choice %c" rpl
))))))
447 (defun org-clock-insert-selection-line (i marker
)
448 "Insert a line for the clock selection menu.
449 And return a cons cell with the selection character integer and the marker
451 (when (marker-buffer marker
)
452 (let (file cat task heading prefix
)
453 (with-current-buffer (org-base-buffer (marker-buffer marker
))
459 (setq file
(buffer-file-name (marker-buffer marker
))
460 cat
(org-get-category)
461 heading
(org-get-heading 'notags
)
462 prefix
(save-excursion
463 (org-back-to-heading t
)
467 (org-fontify-like-in-org-mode
468 (concat prefix heading
)
470 (length prefix
)))))))
472 (insert (format "[%c] %-15s %s\n" i cat task
))
475 (defvar org-task-overrun nil
476 "Internal flag indicating if the clock has overrun the planned time.")
477 (defvar org-clock-update-period
60
478 "Number of seconds between mode line clock string updates.")
480 (defun org-clock-get-clock-string ()
481 "Form a clock-string, that will be shown in the mode line.
482 If an effort estimate was defined for the current item, use
483 01:30/01:50 format (clocked/estimated).
484 If not, show simply the clocked time like 01:50."
485 (let* ((clocked-time (org-clock-get-clocked-time))
486 (h (floor clocked-time
60))
487 (m (- clocked-time
(* 60 h
))))
489 (let* ((effort-in-minutes
490 (org-duration-string-to-minutes org-clock-effort
))
491 (effort-h (floor effort-in-minutes
60))
492 (effort-m (- effort-in-minutes
(* effort-h
60)))
495 (format org-time-clocksum-format h m
)
496 'face
(if (and org-task-overrun
(not org-task-overrun-text
))
497 'org-mode-line-clock-overrun
'org-mode-line-clock
)))
498 (effort-str (format org-time-clocksum-format effort-h effort-m
))
499 (clockstr (org-propertize
500 (concat "[%s/" effort-str
501 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading
) ")")
502 'face
'org-mode-line-clock
)))
503 (format clockstr work-done-str
))
504 (org-propertize (format
505 (concat "[" org-time-clocksum-format
" (%s)]")
506 h m org-clock-heading
)
507 'face
'org-mode-line-clock
))))
509 (defun org-clock-update-mode-line ()
511 (org-clock-notify-once-if-expired)
512 (setq org-task-overrun nil
))
513 (setq org-mode-line-string
515 (let ((clock-string (org-clock-get-clock-string))
516 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
517 (if (and (> org-clock-string-limit
0)
518 (> (length clock-string
) org-clock-string-limit
))
520 (substring clock-string
0 org-clock-string-limit
)
521 'help-echo
(concat help-text
": " org-clock-heading
))
522 (org-propertize clock-string
'help-echo help-text
)))
523 'local-map org-clock-mode-line-map
524 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)
526 (if (and org-task-overrun org-task-overrun-text
)
527 (setq org-mode-line-string
528 (concat (org-propertize
529 org-task-overrun-text
530 'face
'org-mode-line-clock-overrun
) org-mode-line-string
)))
531 (force-mode-line-update))
533 (defun org-clock-get-clocked-time ()
534 "Get the clocked time for the current item in minutes.
535 The time returned includes the time spent on this task in
536 previous clocking intervals."
537 (let ((currently-clocked-time
538 (floor (- (org-float-time)
539 (org-float-time org-clock-start-time
)) 60)))
540 (+ currently-clocked-time
(or org-clock-total-time
0))))
542 (defun org-clock-modify-effort-estimate (&optional value
)
543 "Add to or set the effort estimate of the item currently being clocked.
544 VALUE can be a number of minutes, or a string with format hh:mm or mm.
545 When the string starts with a + or a - sign, the current value of the effort
546 property will be changed by that amount.
547 This will update the \"Effort\" property of currently clocked item, and
550 (when (org-clock-is-active)
551 (let ((current org-clock-effort
) sign
)
553 ;; Prompt user for a value or a change
556 (format "Set effort (hh:mm or mm%s): "
558 (format ", prefix + to add to %s" org-clock-effort
)
560 (when (stringp value
)
561 ;; A string. See if it is a delta
562 (setq sign
(string-to-char value
))
563 (if (member sign
'(?- ?
+))
564 (setq current
(org-duration-string-to-minutes current
)
565 value
(substring value
1))
567 (setq value
(org-duration-string-to-minutes value
))
569 (setq value
(- current value
))
570 (if (equal ?
+ sign
) (setq value
(+ current value
)))))
571 (setq value
(max 0 value
)
572 org-clock-effort
(org-minutes-to-hh:mm-string value
))
573 (org-entry-put org-clock-marker
"Effort" org-clock-effort
)
574 (org-clock-update-mode-line)
575 (message "Effort is now %s" org-clock-effort
))))
577 (defvar org-clock-notification-was-shown nil
578 "Shows if we have shown notification already.")
580 (defun org-clock-notify-once-if-expired ()
581 "Show notification if we spent more time than we estimated before.
582 Notification is shown only once."
583 (when (org-clocking-p)
584 (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort
))
585 (clocked-time (org-clock-get-clocked-time)))
586 (if (setq org-task-overrun
587 (if (or (null effort-in-minutes
) (zerop effort-in-minutes
))
589 (>= clocked-time effort-in-minutes
)))
590 (unless org-clock-notification-was-shown
591 (setq org-clock-notification-was-shown t
)
593 (format "Task '%s' should be finished by now. (%s)"
594 org-clock-heading org-clock-effort
) t
))
595 (setq org-clock-notification-was-shown nil
)))))
597 (defun org-notify (notification &optional play-sound
)
598 "Send a NOTIFICATION and maybe PLAY-SOUND."
599 (org-show-notification notification
)
600 (if play-sound
(org-clock-play-sound)))
602 (defun org-show-notification (notification)
604 Use `org-show-notification-handler' if defined,
605 use libnotify if available, or fall back on a message."
606 (cond ((functionp org-show-notification-handler
)
607 (funcall org-show-notification-handler notification
))
608 ((stringp org-show-notification-handler
)
609 (start-process "emacs-timer-notification" nil
610 org-show-notification-handler notification
))
611 ((featurep 'notifications
)
612 (require 'notifications
)
613 (notifications-notify
614 :title
"Org-mode message"
616 ;; FIXME how to link to the Org icon?
617 ;; :app-icon "~/.emacs.d/icons/mail.png"
619 ((org-program-exists "notify-send")
620 (start-process "emacs-timer-notification" nil
621 "notify-send" notification
))
622 ;; Maybe the handler will send a message, so only use message as
623 ;; a fall back option
624 (t (message "%s" notification
))))
626 (defun org-clock-play-sound ()
627 "Play sound as configured by `org-clock-sound'.
628 Use alsa's aplay tool if available."
630 ((not org-clock-sound
))
631 ((eq org-clock-sound t
) (beep t
) (beep t
))
632 ((stringp org-clock-sound
)
633 (let ((file (expand-file-name org-clock-sound
)))
634 (if (file-exists-p file
)
635 (if (org-program-exists "aplay")
636 (start-process "org-clock-play-notification" nil
639 (play-sound-file file
)
640 (error (beep t
) (beep t
)))))))))
642 (defun org-program-exists (program-name)
643 "Checks whenever we can locate program and launch it."
644 (if (eq system-type
'gnu
/linux
)
645 (= 0 (call-process "which" nil nil nil program-name
))))
647 (defvar org-clock-mode-line-entry nil
648 "Information for the modeline about the running clock.")
650 (defun org-find-open-clocks (file)
651 "Search through the given file and find all open clocks."
652 (let ((buf (or (get-file-buffer file
)
653 (find-file-noselect file
)))
655 (with-current-buffer buf
657 (goto-char (point-min))
658 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t
)
659 (push (cons (copy-marker (match-end 1) t
)
660 (org-time-string-to-time (match-string 1))) clocks
))))
663 (defsubst org-is-active-clock
(clock)
664 "Return t if CLOCK is the currently active clock."
665 (and (org-clock-is-active)
666 (= org-clock-marker
(car clock
))))
668 (defmacro org-with-clock-position
(clock &rest forms
)
669 "Evaluate FORMS with CLOCK as the current active clock."
670 `(with-current-buffer (marker-buffer (car ,clock
))
674 (goto-char (car ,clock
))
678 (put 'org-with-clock-position
'lisp-indent-function
1)
680 (defmacro org-with-clock
(clock &rest forms
)
681 "Evaluate FORMS with CLOCK as the current active clock.
682 This macro also protects the current active clock from being altered."
683 `(org-with-clock-position ,clock
684 (let ((org-clock-start-time (cdr ,clock
))
685 (org-clock-total-time)
688 (org-clock-marker (car ,clock
))
689 (org-clock-hd-marker (save-excursion
690 (outline-back-to-heading t
)
694 (put 'org-with-clock
'lisp-indent-function
1)
696 (defsubst org-clock-clock-in
(clock &optional resume start-time
)
697 "Clock in to the clock located by CLOCK.
698 If necessary, clock-out of the currently active clock."
699 (org-with-clock-position clock
700 (let ((org-clock-in-resume (or resume org-clock-in-resume
)))
701 (org-clock-in nil start-time
))))
703 (defsubst org-clock-clock-out
(clock &optional fail-quietly at-time
)
704 "Clock out of the clock located by CLOCK."
705 (let ((temp (copy-marker (car clock
)
706 (marker-insertion-type (car clock
)))))
707 (if (org-is-active-clock clock
)
708 (org-clock-out fail-quietly at-time
)
709 (org-with-clock clock
710 (org-clock-out fail-quietly at-time
)))
711 (setcar clock temp
)))
713 (defsubst org-clock-clock-cancel
(clock)
714 "Cancel the clock located by CLOCK."
715 (let ((temp (copy-marker (car clock
)
716 (marker-insertion-type (car clock
)))))
717 (if (org-is-active-clock clock
)
719 (org-with-clock clock
721 (setcar clock temp
)))
723 (defvar org-clock-clocking-in nil
)
724 (defvar org-clock-resolving-clocks nil
)
725 (defvar org-clock-resolving-clocks-due-to-idleness nil
)
727 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
728 &optional close-p restart-p fail-quietly
)
729 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
730 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
731 (let ((org-clock-resolving-clocks t
))
734 (org-clock-clock-cancel clock
)
735 (if (and restart-p
(not org-clock-clocking-in
))
736 (org-clock-clock-in clock
)))
738 ((eq resolve-to
'now
)
740 (error "RESTART-P is not valid here"))
741 (if (or close-p org-clock-clocking-in
)
742 (org-clock-clock-out clock fail-quietly
)
743 (unless (org-is-active-clock clock
)
744 (org-clock-clock-in clock t
))))
746 ((not (time-less-p resolve-to
(current-time)))
747 (error "RESOLVE-TO must refer to a time in the past"))
751 (error "RESTART-P is not valid here"))
752 (org-clock-clock-out clock fail-quietly
(or clock-out-time
754 (unless org-clock-clocking-in
756 (setq org-clock-leftover-time
(and (null clock-out-time
)
758 (org-clock-clock-in clock nil
(and clock-out-time
761 (defun org-clock-jump-to-current-clock (&optional effective-clock
)
763 (let ((clock (or effective-clock
(cons org-clock-marker
764 org-clock-start-time
))))
765 (unless (marker-buffer (car clock
))
766 (error "No clock is currently running"))
767 (org-with-clock clock
(org-clock-goto))
768 (with-current-buffer (marker-buffer (car clock
))
769 (goto-char (car clock
))
770 (if org-clock-into-drawer
772 (if (stringp org-clock-into-drawer
)
773 (concat ":" org-clock-into-drawer
":")
778 (outline-back-to-heading t
)
779 (search-forward logbook
)
780 (goto-char (match-beginning 0)))
782 (outline-back-to-heading t
)
783 (search-forward logbook
)
784 (search-forward ":END:")
785 (goto-char (match-end 0)))
788 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly
)
789 "Resolve an open org-mode clock.
790 An open clock was found, with `dangling' possibly being non-nil.
791 If this function was invoked with a prefix argument, non-dangling
792 open clocks are ignored. The given clock requires some sort of
793 user intervention to resolve it, either because a clock was left
794 dangling or due to an idle timeout. The clock resolution can
797 (a) deleted, the user doesn't care about the clock
798 (b) restarted from the current time (if no other clock is open)
799 (c) closed, giving the clock X minutes
800 (d) closed and then restarted
801 (e) resumed, as if the user had never left
803 The format of clock is (CONS MARKER START-TIME), where MARKER
804 identifies the buffer and position the clock is open at (and
805 thus, the heading it's under), and START-TIME is when the clock
809 (save-window-excursion
811 (unless org-clock-resolving-clocks-due-to-idleness
812 (org-clock-jump-to-current-clock clock
))
813 (unless org-clock-resolve-expert
814 (with-output-to-temp-buffer "*Org Clock*"
815 (princ "Select a Clock Resolution Command:
817 i/q/C-g Ignore this question; the same as keeping all the idle time.
819 k/K Keep X minutes of the idle time (default is all). If this
820 amount is less than the default, you will be clocked out
821 that many minutes after the time that idling began, and then
822 clocked back in at the present time.
823 g/G Indicate that you \"got back\" X minutes ago. This is quite
824 different from 'k': it clocks you out from the beginning of
825 the idle period and clock you back in X minutes ago.
826 s/S Subtract the idle time from the current clock. This is the
827 same as keeping 0 minutes.
828 C Cancel the open timer altogether. It will be as though you
830 j/J Jump to the current clock, to make manual adjustments.
832 For all these options, using uppercase makes your final state
833 to be CLOCKED OUT.")))
834 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
836 (when (featurep 'xemacs
)
837 (message (concat (funcall prompt-fn clock
)
839 (setq char-pressed
(read-char-exclusive)))
840 (while (or (null char-pressed
)
841 (and (not (memq char-pressed
842 '(?k ?K ?g ?G ?s ?S ?C
846 (read-char (concat (funcall prompt-fn clock
)
849 (and (not (memq char-pressed
'(?i ?q
))) char-pressed
)))))
851 (floor (/ (org-float-time
852 (time-subtract (current-time) last-valid
)) 60)))
854 (and (memq ch
'(?k ?K
))
855 (read-number "Keep how many minutes? " default
)))
857 (and (memq ch
'(?g ?G
))
858 (read-number "Got back how many minutes ago? " default
)))
859 (subtractp (memq ch
'(?s ?S
)))
860 (barely-started-p (< (- (org-float-time last-valid
)
861 (org-float-time (cdr clock
))) 45))
862 (start-over (and subtractp barely-started-p
)))
866 (org-clock-resolve-clock clock
'now nil t nil fail-quietly
))
867 (org-clock-jump-to-current-clock clock
))
869 (not (memq ch
'(?k ?K ?g ?G ?s ?S ?C
))))
872 (org-clock-resolve-clock
875 ;; If the time on the clock was less than a minute before
876 ;; the user went away, and they've ask to subtract all the
881 (and gotback
(= gotback
0)))
883 ((or (and keep
(= keep default
))
884 (and gotback
(= gotback default
)))
887 (time-add last-valid
(seconds-to-time (* 60 keep
))))
889 (time-subtract (current-time)
890 (seconds-to-time (* 60 gotback
))))
892 (error "Unexpected, please report this as a bug")))
893 (and gotback last-valid
)
894 (memq ch
'(?K ?G ?S
))
896 (not (memq ch
'(?K ?G ?S ?C
))))
899 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid
)
900 "Resolve all currently open org-mode clocks.
901 If `only-dangling-p' is non-nil, only ask to resolve dangling
902 \(i.e., not currently open and valid) clocks."
904 (unless org-clock-resolving-clocks
905 (let ((org-clock-resolving-clocks t
))
906 (dolist (file (org-files-list))
907 (let ((clocks (org-find-open-clocks file
)))
908 (dolist (clock clocks
)
909 (let ((dangling (or (not (org-clock-is-active))
910 (/= (car clock
) org-clock-marker
))))
911 (if (or (not only-dangling-p
) dangling
)
918 "Dangling clock started %d mins ago"
920 (/ (- (org-float-time (current-time))
921 (org-float-time (cdr clock
))) 60))))))
923 (cdr clock
)))))))))))
925 (defun org-emacs-idle-seconds ()
926 "Return the current Emacs idle time in seconds, or nil if not idle."
927 (let ((idle-time (current-idle-time)))
929 (org-float-time idle-time
)
932 (defun org-mac-idle-seconds ()
933 "Return the current Mac idle time in seconds."
934 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
936 (defun org-x11-idle-seconds ()
937 "Return the current X11 idle time in seconds."
938 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
940 (defun org-user-idle-seconds ()
941 "Return the number of seconds the user has been idle for.
942 This routine returns a floating point number."
944 ((eq system-type
'darwin
)
945 (org-mac-idle-seconds))
946 ((eq window-system
'x
)
947 (org-x11-idle-seconds))
949 (org-emacs-idle-seconds))))
951 (defvar org-clock-user-idle-seconds
)
953 (defun org-resolve-clocks-if-idle ()
954 "Resolve all currently open org-mode clocks.
955 This is performed after `org-clock-idle-time' minutes, to check
956 if the user really wants to stay clocked in after being idle for
958 (when (and org-clock-idle-time
(not org-clock-resolving-clocks
)
960 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
961 (org-clock-user-idle-start
962 (time-subtract (current-time)
963 (seconds-to-time org-clock-user-idle-seconds
)))
964 (org-clock-resolving-clocks-due-to-idleness t
))
965 (if (> org-clock-user-idle-seconds
(* 60 org-clock-idle-time
))
967 (cons org-clock-marker
968 org-clock-start-time
)
971 (format "Clocked in & idle for %.1f mins"
973 (time-subtract (current-time)
974 org-clock-user-idle-start
))
976 org-clock-user-idle-start
)))))
978 (defun org-clock-in (&optional select start-time
)
979 "Start the clock on the current item.
980 If necessary, clock-out of the currently active clock.
981 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
982 recently clocked tasks to
983 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
984 clock into the current task and mark
985 is as the default task, a special task that will always be offered in
986 the clocking selection, associated with the letter `d'."
988 (setq org-clock-notification-was-shown nil
)
990 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness
)
992 ts selected-task target-pos
(msg-extra "")
993 (leftover (and (not org-clock-resolving-clocks
)
994 org-clock-leftover-time
)))
996 (when (and org-clock-auto-clock-resolution
997 (or (not interrupting
)
998 (eq t org-clock-auto-clock-resolution
))
999 (not org-clock-clocking-in
)
1000 (not org-clock-resolving-clocks
))
1001 (setq org-clock-leftover-time nil
)
1002 (let ((org-clock-clocking-in t
))
1003 (org-resolve-clocks))) ; check if any clocks are dangling
1005 (when (equal select
'(4))
1006 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
1008 (setq selected-task
(copy-marker selected-task
))
1011 (when (equal select
'(16))
1012 ;; Mark as default clocking task
1013 (org-clock-mark-default-task))
1016 ;; We are interrupting the clocking of a different task.
1017 ;; Save a marker to this task, so that we can go back.
1018 ;; First check if we are trying to clock into the same task!
1019 (when (save-excursion
1020 (unless selected-task
1021 (org-back-to-heading t
))
1022 (and (equal (marker-buffer org-clock-hd-marker
)
1024 (marker-buffer selected-task
)
1026 (= (marker-position org-clock-hd-marker
)
1028 (marker-position selected-task
)
1030 (equal org-clock-current-task
(nth 4 (org-heading-components)))))
1031 (message "Clock continues in \"%s\"" org-clock-heading
)
1033 (move-marker org-clock-interrupted-task
1034 (marker-position org-clock-marker
)
1035 (marker-buffer org-clock-marker
))
1036 (let ((org-clock-clocking-in t
))
1039 ;; Clock in at which position?
1041 (if (and (eobp) (not (org-on-heading-p)))
1044 (run-hooks 'org-clock-in-prepare-hook
)
1046 (when (and selected-task
(marker-buffer selected-task
))
1047 ;; There is a selected task, move to the correct buffer
1048 ;; and set the new target position.
1049 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
1050 (setq target-pos
(marker-position selected-task
))
1051 (move-marker selected-task nil
))
1055 (goto-char target-pos
)
1056 (org-back-to-heading t
)
1057 (or interrupting
(move-marker org-clock-interrupted-task nil
))
1058 (org-clock-history-push)
1059 (org-clock-set-current)
1060 (cond ((functionp org-clock-in-switch-to-state
)
1061 (looking-at org-complex-heading-regexp
)
1062 (let ((newstate (funcall org-clock-in-switch-to-state
1064 (if newstate
(org-todo newstate
))))
1065 ((and org-clock-in-switch-to-state
1066 (not (looking-at (concat outline-regexp
"[ \t]*"
1067 org-clock-in-switch-to-state
1069 (org-todo org-clock-in-switch-to-state
)))
1070 (setq org-clock-heading-for-remember
1071 (and (looking-at org-complex-heading-regexp
)
1073 (org-trim (buffer-substring (match-end 1)
1075 (setq org-clock-heading
1076 (cond ((and org-clock-heading-function
1077 (functionp org-clock-heading-function
))
1078 (funcall org-clock-heading-function
))
1079 ((looking-at org-complex-heading-regexp
)
1080 (replace-regexp-in-string
1081 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1084 (setq org-clock-heading
(org-propertize org-clock-heading
1086 (org-clock-find-position org-clock-in-resume
)
1088 ((and org-clock-in-resume
1090 (concat "^[ \t]* " org-clock-string
1091 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1092 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1093 (message "Matched %s" (match-string 1))
1094 (setq ts
(concat "[" (match-string 1) "]"))
1095 (goto-char (match-end 1))
1096 (setq org-clock-start-time
1098 (org-parse-time-string (match-string 1))))
1099 (setq org-clock-effort
(org-get-effort))
1100 (setq org-clock-total-time
(org-clock-sum-current-item
1101 (org-clock-get-sum-start))))
1102 ((eq org-clock-in-resume
'auto-restart
)
1103 ;; called from org-clock-load during startup,
1104 ;; do not interrupt, but warn!
1105 (message "Cannot restart clock because task does not contain unfinished clock")
1110 (insert-before-markers "\n")
1112 (org-indent-line-function)
1113 (when (and (save-excursion
1116 (beginning-of-line 1)
1117 (org-indent-line-to (- (org-get-indentation) 2)))
1118 (insert org-clock-string
" ")
1119 (setq org-clock-effort
(org-get-effort))
1120 (setq org-clock-total-time
(org-clock-sum-current-item
1121 (org-clock-get-sum-start)))
1122 (setq org-clock-start-time
1126 "You stopped another clock %d mins ago; start this one from then? "
1127 (/ (- (org-float-time (current-time))
1128 (org-float-time leftover
)) 60)))
1132 (setq ts
(org-insert-time-stamp org-clock-start-time
1133 'with-hm
'inactive
))))
1134 (move-marker org-clock-marker
(point) (buffer-base-buffer))
1135 (move-marker org-clock-hd-marker
1136 (save-excursion (org-back-to-heading t
) (point))
1137 (buffer-base-buffer))
1138 (setq org-clock-has-been-used t
)
1139 (or global-mode-string
(setq global-mode-string
'("")))
1140 (or (memq 'org-mode-line-string global-mode-string
)
1141 (setq global-mode-string
1142 (append global-mode-string
'(org-mode-line-string))))
1143 (org-clock-update-mode-line)
1144 (when org-clock-mode-line-timer
1145 (cancel-timer org-clock-mode-line-timer
)
1146 (setq org-clock-mode-line-timer nil
))
1147 (setq org-clock-mode-line-timer
1148 (run-with-timer org-clock-update-period
1149 org-clock-update-period
1150 'org-clock-update-mode-line
))
1151 (when org-clock-idle-timer
1152 (cancel-timer org-clock-idle-timer
)
1153 (setq org-clock-idle-timer nil
))
1154 (setq org-clock-idle-timer
1155 (run-with-timer 60 60 'org-resolve-clocks-if-idle
))
1156 (message "Clock starts at %s - %s" ts msg-extra
)
1157 (run-hooks 'org-clock-in-hook
)))))))
1159 (defvar org-clock-current-task nil
1160 "Task currently clocked in.")
1161 (defun org-clock-set-current ()
1162 "Set `org-clock-current-task' to the task currently clocked in."
1163 (setq org-clock-current-task
(nth 4 (org-heading-components))))
1165 (defun org-clock-delete-current ()
1166 "Reset `org-clock-current-task' to nil."
1167 (setq org-clock-current-task nil
))
1169 (defun org-clock-mark-default-task ()
1170 "Mark current task as default task."
1173 (org-back-to-heading t
)
1174 (move-marker org-clock-default-task
(point))))
1177 (defun org-clock-get-sum-start ()
1178 "Return the time from which clock times should be counted.
1179 This is for the currently running clock as it is displayed
1180 in the mode line. This function looks at the properties
1181 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1182 corresponding variable `org-clock-modeline-total' and then
1183 decides which time to use."
1184 (let ((cmt (or (org-entry-get nil
"CLOCK_MODELINE_TOTAL")
1185 (symbol-name org-clock-modeline-total
)))
1186 (lr (org-entry-get nil
"LAST_REPEAT")))
1188 ((equal cmt
"current")
1189 (setq msg-extra
"showing time in current clock instance")
1191 ((equal cmt
"today")
1192 (setq msg-extra
"showing today's task time.")
1193 (let* ((dt (decode-time (current-time))))
1194 (setq dt
(append (list 0 0 0) (nthcdr 3 dt
)))
1195 (if org-extend-today-until
1196 (setf (nth 2 dt
) org-extend-today-until
))
1197 (apply 'encode-time dt
)))
1198 ((or (equal cmt
"all")
1199 (and (or (not cmt
) (equal cmt
"auto"))
1201 (setq msg-extra
"showing entire task time.")
1203 ((or (equal cmt
"repeat")
1204 (and (or (not cmt
) (equal cmt
"auto"))
1206 (setq msg-extra
"showing task time since last repeat.")
1209 (org-time-string-to-time lr
)))
1212 (defun org-clock-find-position (find-unclosed)
1213 "Find the location where the next clock line should be inserted.
1214 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1215 line and position cursor in that line."
1216 (org-back-to-heading t
)
1218 (let ((beg (save-excursion
1219 (beginning-of-line 2)
1220 (or (bolp) (newline))
1222 (end (progn (outline-next-heading) (point)))
1223 (re (concat "^[ \t]*" org-clock-string
))
1225 (drawer (if (stringp org-clock-into-drawer
)
1226 org-clock-into-drawer
"LOGBOOK"))
1227 first last ind-last
)
1229 (when (and find-unclosed
1231 (concat "^[ \t]* " org-clock-string
1232 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1233 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1235 (beginning-of-line 1)
1237 (when (eobp) (newline) (setq end
(max (point) end
)))
1238 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
1239 ;; we seem to have a CLOCK drawer, so go there.
1240 (beginning-of-line 2)
1241 (or org-log-states-order-reversed
1242 (and (re-search-forward org-property-end-re nil t
)
1243 (goto-char (match-beginning 0))))
1245 ;; Lets count the CLOCK lines
1247 (while (re-search-forward re end t
)
1248 (setq first
(or first
(match-beginning 0))
1249 last
(match-beginning 0)
1251 (when (and (integerp org-clock-into-drawer
)
1253 (>= (1+ cnt
) org-clock-into-drawer
))
1254 ;; Wrap current entries into a new drawer
1256 (setq ind-last
(org-get-indentation))
1257 (beginning-of-line 2)
1258 (if (and (>= (org-get-indentation) ind-last
)
1260 (when (and (>= (org-get-indentation) ind-last
)
1262 (let ((struct (org-list-struct)))
1263 (goto-char (org-list-get-bottom-point struct
)))))
1265 (beginning-of-line 0)
1266 (org-indent-line-to ind-last
)
1268 (insert ":" drawer
":\n")
1269 (beginning-of-line 0)
1270 (org-indent-line-function)
1272 (beginning-of-line 2)
1273 (or org-log-states-order-reversed
1274 (and (re-search-forward org-property-end-re nil t
)
1275 (goto-char (match-beginning 0))))
1279 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1280 (not (equal (match-string 1) org-clock-string
)))
1281 ;; Planning info, skip to after it
1282 (beginning-of-line 2)
1283 (or (bolp) (newline)))
1284 (when (or (eq org-clock-into-drawer t
)
1285 (stringp org-clock-into-drawer
)
1286 (and (integerp org-clock-into-drawer
)
1287 (< org-clock-into-drawer
2)))
1288 (insert ":" drawer
":\n:END:\n")
1289 (beginning-of-line -
1)
1290 (org-indent-line-function)
1292 (beginning-of-line 2)
1293 (org-indent-line-function)
1295 (or org-log-states-order-reversed
1296 (and (re-search-forward org-property-end-re nil t
)
1297 (goto-char (match-beginning 0))))))))
1299 (defun org-clock-out (&optional fail-quietly at-time
)
1300 "Stop the currently running clock.
1301 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1304 (when (not (org-clocking-p))
1305 (setq global-mode-string
1306 (delq 'org-mode-line-string global-mode-string
))
1307 (force-mode-line-update)
1308 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
1309 (let (ts te s h m remove
)
1310 (save-excursion ; Do not replace this with `with-current-buffer'.
1311 (with-no-warnings (set-buffer (org-clocking-buffer)))
1314 (goto-char org-clock-marker
)
1315 (beginning-of-line 1)
1316 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
1317 (equal (match-string 1) org-clock-string
))
1318 (setq ts
(match-string 2))
1319 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
1320 (goto-char (match-end 0))
1321 (delete-region (point) (point-at-eol))
1323 (setq te
(org-insert-time-stamp (or at-time
(current-time))
1324 'with-hm
'inactive
))
1325 (setq s
(- (org-float-time (apply 'encode-time
(org-parse-time-string te
)))
1326 (org-float-time (apply 'encode-time
(org-parse-time-string ts
))))
1327 h
(floor (/ s
3600))
1331 (insert " => " (format "%2d:%02d" h m
))
1332 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
1334 (beginning-of-line 1)
1335 (delete-region (point) (point-at-eol))
1336 (and (looking-at "\n") (> (point-max) (1+ (point)))
1338 (move-marker org-clock-marker nil
)
1339 (move-marker org-clock-hd-marker nil
)
1340 (when org-log-note-clock-out
1341 (org-add-log-setup 'clock-out nil nil nil nil
1342 (concat "# Task: " (org-get-heading t
) "\n\n")))
1343 (when org-clock-mode-line-timer
1344 (cancel-timer org-clock-mode-line-timer
)
1345 (setq org-clock-mode-line-timer nil
))
1346 (when org-clock-idle-timer
1347 (cancel-timer org-clock-idle-timer
)
1348 (setq org-clock-idle-timer nil
))
1349 (setq global-mode-string
1350 (delq 'org-mode-line-string global-mode-string
))
1351 (when org-clock-out-switch-to-state
1353 (org-back-to-heading t
)
1354 (let ((org-inhibit-logging t
)
1355 (org-clock-out-when-done nil
))
1357 ((functionp org-clock-out-switch-to-state
)
1358 (looking-at org-complex-heading-regexp
)
1359 (let ((newstate (funcall org-clock-out-switch-to-state
1361 (if newstate
(org-todo newstate
))))
1362 ((and org-clock-out-switch-to-state
1363 (not (looking-at (concat outline-regexp
"[ \t]*"
1364 org-clock-out-switch-to-state
1366 (org-todo org-clock-out-switch-to-state
))))))
1367 (force-mode-line-update)
1368 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
1369 (if remove
" => LINE REMOVED" ""))
1370 (run-hooks 'org-clock-out-hook
)
1371 (org-clock-delete-current))))))
1373 (defun org-clock-cancel ()
1374 "Cancel the running clock by removing the start timestamp."
1376 (when (not (org-clocking-p))
1377 (setq global-mode-string
1378 (delq 'org-mode-line-string global-mode-string
))
1379 (force-mode-line-update)
1380 (error "No active clock"))
1381 (save-excursion ; Do not replace this with `with-current-buffer'.
1382 (with-no-warnings (set-buffer (org-clocking-buffer)))
1383 (goto-char org-clock-marker
)
1384 (delete-region (1- (point-at-bol)) (point-at-eol))
1385 ;; Just in case, remove any empty LOGBOOK left over
1386 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1387 (move-marker org-clock-marker nil
)
1388 (move-marker org-clock-hd-marker nil
)
1389 (setq global-mode-string
1390 (delq 'org-mode-line-string global-mode-string
))
1391 (force-mode-line-update)
1392 (message "Clock canceled")
1393 (run-hooks 'org-clock-cancel-hook
))
1395 (defun org-clock-goto (&optional select
)
1396 "Go to the currently clocked-in entry, or to the most recently clocked one.
1397 With prefix arg SELECT, offer recently clocked tasks for selection."
1402 (or (org-clock-select-task "Select task to go to: ")
1403 (error "No task selected")))
1404 ((org-clocking-p) org-clock-marker
)
1405 ((and org-clock-goto-may-find-recent-task
1406 (car org-clock-history
)
1407 (marker-buffer (car org-clock-history
)))
1409 (car org-clock-history
))
1410 (t (error "No active or recent clock task")))))
1411 (switch-to-buffer (marker-buffer m
))
1412 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
1415 (org-back-to-heading t
)
1416 (org-cycle-hide-drawers 'children
)
1420 (message "No running clock, this is the most recently clocked task"))
1421 (run-hooks 'org-clock-goto-hook
)))
1423 (defvar org-clock-file-total-minutes nil
1424 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1425 (make-variable-buffer-local 'org-clock-file-total-minutes
)
1427 (defun org-clock-sum (&optional tstart tend headline-filter
)
1428 "Sum the times for each subtree.
1429 Puts the resulting times in minutes as a text property on each headline.
1430 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1431 zero-arg function that, if specified, is called for each headline in the time
1432 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1433 nil are excluded from the clock summation."
1435 (let* ((bmp (buffer-modified-p))
1436 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1438 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1440 (ltimes (make-vector lmax
0))
1445 (if (stringp tstart
) (setq tstart
(org-time-string-to-seconds tstart
)))
1446 (if (stringp tend
) (setq tend
(org-time-string-to-seconds tend
)))
1447 (if (consp tstart
) (setq tstart
(org-float-time tstart
)))
1448 (if (consp tend
) (setq tend
(org-float-time tend
)))
1449 (remove-text-properties (point-min) (point-max)
1450 '(:org-clock-minutes t
1451 :org-clock-force-headline-inclusion t
))
1453 (goto-char (point-max))
1454 (while (re-search-backward re nil t
)
1458 (setq ts
(match-string 2)
1461 (apply 'encode-time
(org-parse-time-string ts
)))
1463 (apply 'encode-time
(org-parse-time-string te
)))
1464 ts
(if tstart
(max ts tstart
) ts
)
1465 te
(if tend
(min te tend
) te
)
1467 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
1470 (setq t1
(+ t1
(string-to-number (match-string 5))
1471 (* 60 (string-to-number (match-string 4))))))
1473 ;; Add the currently clocking item time to the total
1474 (when (and org-clock-report-include-clocking-task
1475 (equal (org-clocking-buffer) (current-buffer))
1476 (equal (marker-position org-clock-hd-marker
) (point))
1479 (>= (org-float-time org-clock-start-time
) tstart
)
1480 (<= (org-float-time org-clock-start-time
) tend
))
1481 (let ((time (floor (- (org-float-time)
1482 (org-float-time org-clock-start-time
)) 60)))
1483 (setq t1
(+ t1 time
))))
1484 (let* ((headline-forced
1485 (get-text-property (point)
1486 :org-clock-force-headline-inclusion
))
1488 (or (null headline-filter
)
1490 (save-match-data (funcall headline-filter
))))))
1491 (setq level
(- (match-end 1) (match-beginning 1)))
1492 (when (or (> t1
0) (> (aref ltimes level
) 0))
1493 (when (or headline-included headline-forced
)
1494 (if headline-included
1495 (loop for l from
0 to level do
1496 (aset ltimes l
(+ (aref ltimes l
) t1
))))
1497 (setq time
(aref ltimes level
))
1498 (goto-char (match-beginning 0))
1499 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)
1504 (> (funcall outline-level
) 1)
1505 (outline-up-heading 1 t
)
1507 (point) (point-at-eol)
1508 :org-clock-force-headline-inclusion t
))))))
1510 (loop for l from level to
(1- lmax
) do
1511 (aset ltimes l
0)))))))
1512 (setq org-clock-file-total-minutes
(aref ltimes
0)))
1513 (set-buffer-modified-p bmp
)))
1515 (defun org-clock-sum-current-item (&optional tstart
)
1516 "Return time, clocked on current item in total."
1519 (org-narrow-to-subtree)
1520 (org-clock-sum tstart
)
1521 org-clock-file-total-minutes
)))
1523 (defun org-clock-display (&optional total-only
)
1524 "Show subtree times in the entire buffer.
1525 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1528 Use \\[org-clock-remove-overlays] to remove the subtree times."
1530 (org-clock-remove-overlays)
1535 (goto-char (point-min))
1536 (while (or (and (equal (setq p
(point)) (point-min))
1537 (get-text-property p
:org-clock-minutes
))
1538 (setq p
(next-single-property-change
1539 (point) :org-clock-minutes
)))
1541 (when (setq time
(get-text-property p
:org-clock-minutes
))
1542 (org-clock-put-overlay time
(funcall outline-level
))))
1543 (setq h
(/ org-clock-file-total-minutes
60)
1544 m
(- org-clock-file-total-minutes
(* 60 h
)))
1545 ;; Arrange to remove the overlays upon next change.
1546 (when org-remove-highlights-with-change
1547 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
1549 (if org-time-clocksum-use-fractional
1550 (message (concat "Total file time: " org-time-clocksum-fractional-format
1551 " (%d hours and %d minutes)")
1552 (/ (+ (* h
60.0) m
) 60.0) h m
)
1553 (message (concat "Total file time: " org-time-clocksum-format
1554 " (%d hours and %d minutes)") h m h m
))))
1556 (defvar org-clock-overlays nil
)
1557 (make-variable-buffer-local 'org-clock-overlays
)
1559 (defun org-clock-put-overlay (time &optional level
)
1560 "Put an overlays on the current line, displaying TIME.
1561 If LEVEL is given, prefix time with a corresponding number of stars.
1562 This creates a new overlay and stores it in `org-clock-overlays', so that it
1563 will be easy to remove."
1564 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
1565 (l (if level
(org-get-valid-level level
0) 0))
1566 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1567 org-time-clocksum-fractional-format
1568 org-time-clocksum-format
) "%s"))
1571 (org-move-to-column c
)
1572 (unless (eolp) (skip-chars-backward "^ \t"))
1573 (skip-chars-backward " \t")
1574 (setq ov
(make-overlay (1- (point)) (point-at-eol))
1575 tx
(concat (buffer-substring (1- (point)) (point))
1576 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
1577 (org-add-props (if org-time-clocksum-use-fractional
1580 (/ (+ (* h
60.0) m
) 60.0)
1581 (make-string (- 16 l
) ?\
))
1583 (make-string l ?
*) h m
1584 (make-string (- 16 l
) ?\
)))
1585 (list 'face
'org-clock-overlay
))
1587 (if (not (featurep 'xemacs
))
1588 (overlay-put ov
'display tx
)
1589 (overlay-put ov
'invisible t
)
1590 (overlay-put ov
'end-glyph
(make-glyph tx
)))
1591 (push ov org-clock-overlays
)))
1593 (defun org-clock-remove-overlays (&optional beg end noremove
)
1594 "Remove the occur highlights from the buffer.
1595 BEG and END are ignored. If NOREMOVE is nil, remove this function
1596 from the `before-change-functions' in the current buffer."
1598 (unless org-inhibit-highlight-removal
1599 (mapc 'delete-overlay org-clock-overlays
)
1600 (setq org-clock-overlays nil
)
1602 (remove-hook 'before-change-functions
1603 'org-clock-remove-overlays
'local
))))
1605 (defvar state
) ;; dynamically scoped into this function
1606 (defun org-clock-out-if-current ()
1607 "Clock out if the current entry contains the running clock.
1608 This is used to stop the clock after a TODO entry is marked DONE,
1609 and is only done if the variable `org-clock-out-when-done' is not nil."
1610 (when (and org-clock-out-when-done
1611 (or (and (eq t org-clock-out-when-done
)
1612 (member state org-done-keywords
))
1613 (and (listp org-clock-out-when-done
)
1614 (member state org-clock-out-when-done
)))
1615 (equal (or (buffer-base-buffer (org-clocking-buffer))
1616 (org-clocking-buffer))
1617 (or (buffer-base-buffer (current-buffer))
1619 (< (point) org-clock-marker
)
1620 (> (save-excursion (outline-next-heading) (point))
1622 ;; Clock out, but don't accept a logging message for this.
1623 (let ((org-log-note-clock-out nil
)
1624 (org-clock-out-switch-to-state nil
))
1627 (add-hook 'org-after-todo-state-change-hook
1628 'org-clock-out-if-current
)
1631 (defun org-get-clocktable (&rest props
)
1632 "Get a formatted clocktable with parameters according to PROPS.
1633 The table is created in a temporary buffer, fully formatted and
1634 fontified, and then returned."
1636 (setq props
(plist-put props
:name
"clocktable"))
1637 (unless (plist-member props
:maxlevel
)
1638 (setq props
(plist-put props
:maxlevel
2)))
1639 (unless (plist-member props
:scope
)
1640 (setq props
(plist-put props
:scope
'agenda
)))
1643 (org-create-dblock props
)
1645 (font-lock-fontify-buffer)
1647 (buffer-substring (point) (progn
1648 (re-search-forward "^[ \t]*#\\+END" nil t
)
1651 (defun org-clock-report (&optional arg
)
1652 "Create a table containing a report about clocked time.
1653 If the cursor is inside an existing clocktable block, then the table
1654 will be updated. If not, a new clocktable will be inserted.
1655 When called with a prefix argument, move to the first clock table in the
1656 buffer and update it."
1658 (org-clock-remove-overlays)
1660 (org-find-dblock "clocktable")
1662 (if (org-in-clocktable-p)
1663 (goto-char (org-in-clocktable-p))
1664 (org-create-dblock (append (list :name
"clocktable")
1665 org-clock-clocktable-default-properties
)))
1666 (org-update-dblock))
1668 (defun org-in-clocktable-p ()
1669 "Check if the cursor is in a clocktable."
1670 (let ((pos (point)) start
)
1673 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t
)
1674 (setq start
(match-beginning 0))
1675 (re-search-forward "^[ \t]*#\\+END:.*" nil t
)
1676 (>= (match-end 0) pos
)
1679 (defun org-day-of-week (day month year
)
1680 "Returns the day of the week as an integer."
1684 (format "%d-%02d-%02dT00:00:00" year month day
)))))
1686 (defun org-quarter-to-date (quarter year
)
1687 "Get the date (week day year) of the first day of a given quarter."
1691 (setq startday
(org-day-of-week 1 1 year
))
1694 (list 52 7 (- year
1)))
1696 (list 52 6 (- year
1)))
1698 (list 1 startday year
))
1700 (list 53 startday
(- year
1)))
1704 (setq startday
(org-day-of-week 1 4 year
))
1707 (list 13 startday year
))
1709 (list 14 startday year
))
1711 (list 13 startday year
))
1715 (setq startday
(org-day-of-week 1 7 year
))
1718 (list 26 startday year
))
1720 (list 27 startday year
))
1722 (list 26 startday year
))
1726 (setq startday
(org-day-of-week 1 10 year
))
1729 (list 39 startday year
))
1731 (list 40 startday year
))
1733 (list 39 startday year
)))))))
1735 (defun org-clock-special-range (key &optional time as-strings
)
1736 "Return two times bordering a special time range.
1737 Key is a symbol specifying the range and can be one of `today', `yesterday',
1738 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1739 A week starts Monday 0:00 and ends Sunday 24:00.
1740 The range is determined relative to TIME. TIME defaults to the current time.
1741 The return value is a cons cell with two internal times like the ones
1742 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1743 the returned times will be formatted strings."
1744 (if (integerp key
) (setq key
(intern (number-to-string key
))))
1745 (let* ((tm (decode-time (or time
(current-time))))
1746 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
1747 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
1749 (skey (symbol-name key
))
1751 (q (cond ((>= (nth 4 tm
) 10) 4)
1752 ((>= (nth 4 tm
) 7) 3)
1753 ((>= (nth 4 tm
) 4) 2)
1754 ((>= (nth 4 tm
) 1) 1)))
1755 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1756 interval tmp shiftedy shiftedm shiftedq
)
1758 ((string-match "^[0-9]+$" skey
)
1759 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
1760 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1761 (setq y
(string-to-number (match-string 1 skey
))
1762 month
(string-to-number (match-string 2 skey
))
1764 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
1766 (setq y
(string-to-number (match-string 1 skey
))
1767 w
(string-to-number (match-string 2 skey
)))
1768 (setq date
(calendar-gregorian-from-absolute
1769 (calendar-absolute-from-iso (list w
1 y
))))
1770 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1773 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey
)
1775 (setq y
(string-to-number (match-string 1 skey
)))
1776 (setq q
(string-to-number (match-string 2 skey
)))
1777 (setq date
(calendar-gregorian-from-absolute
1778 (calendar-absolute-from-iso (org-quarter-to-date q y
))))
1779 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
1782 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
1783 (setq y
(string-to-number (match-string 1 skey
))
1784 month
(string-to-number (match-string 2 skey
))
1785 d
(string-to-number (match-string 3 skey
))
1787 ((string-match "\\([-+][0-9]+\\)$" skey
)
1788 (setq shift
(string-to-number (match-string 1 skey
))
1789 key
(intern (substring skey
0 (match-beginning 1))))
1790 (if(and (memq key
'(quarter thisq
)) (> shift
0))
1791 (error "Looking forward with quarters isn't implemented.")
1795 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
1796 ((eq key
'lastweek
) (setq key
'week shift -
1))
1797 ((eq key
'lastmonth
) (setq key
'month shift -
1))
1798 ((eq key
'lastyear
) (setq key
'year shift -
1))
1799 ((eq key
'lastq
) (setq key
'quarter shift -
1))))
1801 ((memq key
'(day today
))
1802 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
1803 ((memq key
'(week thisweek
))
1804 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
1805 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
1806 ((memq key
'(month thismonth
))
1807 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
1808 ((memq key
'(quarter thisq
))
1809 ; compute if this shift remains in this year
1810 ; if not, compute how many years and quarters we have to shift (via floor*)
1811 ; and compute the shifted years, months and quarters
1813 ((< (+ (- q
1) shift
) 0) ; shift not in this year
1814 (setq interval
(* -
1 (+ (- q
1) shift
)))
1815 ; set tmp to ((years to shift) (quarters to shift))
1816 (setq tmp
(org-floor* interval
4))
1817 ; due to the use of floor, 0 quarters actually means 4
1818 (if (= 0 (nth 1 tmp
))
1819 (setq shiftedy
(- y
(nth 0 tmp
))
1822 (setq shiftedy
(- y
(+ 1 (nth 0 tmp
)))
1823 shiftedm
(- 13 (* 3 (nth 1 tmp
)))
1824 shiftedq
(- 5 (nth 1 tmp
))))
1825 (setq d
1 h
0 m
0 d1
1 month shiftedm month1
(+ 3 shiftedm
) h1
0 m1
0 y shiftedy
))
1826 ((> (+ q shift
) 0) ; shift is whitin this year
1827 (setq shiftedq
(+ q shift
))
1829 (setq d
1 h
0 m
0 d1
1 month
(+ 1 (* 3 (- (+ q shift
) 1))) month1
(+ 4 (* 3 (- (+ q shift
) 1))) h1
0 m1
0))))
1830 ((memq key
'(year thisyear
))
1831 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
1832 (t (error "No such time block %s" key
)))
1833 (setq ts
(encode-time s m h d month y
)
1834 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
1835 (or d1 d
) (or month1 month
) (or y1 y
)))
1836 (setq fm
(cdr org-time-stamp-formats
))
1838 ((memq key
'(day today
))
1839 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
1840 ((memq key
'(week thisweek
))
1841 (setq txt
(format-time-string "week %G-W%V" ts
)))
1842 ((memq key
'(month thismonth
))
1843 (setq txt
(format-time-string "%B %Y" ts
)))
1844 ((memq key
'(year thisyear
))
1845 (setq txt
(format-time-string "the year %Y" ts
)))
1846 ((memq key
'(quarter thisq
))
1847 (setq txt
(concatenate 'string
(org-count-quarter shiftedq
) " quarter of " (number-to-string shiftedy
))))
1850 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
1853 (defun org-count-quarter (n)
1860 (defun org-clocktable-shift (dir n
)
1861 "Try to shift the :block date of the clocktable at point.
1862 Point must be in the #+BEGIN: line of a clocktable, or this function
1863 will throw an error.
1864 DIR is a direction, a symbol `left', `right', `up', or `down'.
1865 Both `left' and `down' shift the block toward the past, `up' and `right'
1866 push it toward the future.
1867 N is the number of shift steps to take. The size of the step depends on
1868 the currently selected interval size."
1869 (setq n
(prefix-numeric-value n
))
1870 (and (memq dir
'(left down
)) (setq n
(- n
)))
1872 (goto-char (point-at-bol))
1873 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1874 (error "Line needs a :block definition before this command works")
1875 (let* ((b (match-beginning 1)) (e (match-end 1))
1876 (s (match-string 1))
1877 block shift ins y mw d date wp m
)
1879 ((equal s
"yesterday") (setq s
"today-1"))
1880 ((equal s
"lastweek") (setq s
"thisweek-1"))
1881 ((equal s
"lastmonth") (setq s
"thismonth-1"))
1882 ((equal s
"lastyear") (setq s
"thisyear-1"))
1883 ((equal s
"lastq") (setq s
"thisq-1")))
1886 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s
)
1887 (setq block
(match-string 1 s
)
1888 shift
(if (match-end 2)
1889 (string-to-number (match-string 2 s
))
1891 (setq shift
(+ shift n
))
1892 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
1893 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
1894 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1895 (setq y
(string-to-number (match-string 1 s
))
1896 wp
(and (match-end 3) (match-string 3 s
))
1897 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
1898 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
1900 (d (setq ins
(format-time-string
1902 (encode-time 0 0 0 (+ d n
) m y
))))
1903 ((and wp
(string-match "w\\|W" wp
) mw
(> (length wp
) 0))
1905 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
1906 (setq ins
(format-time-string
1908 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1909 ((and wp
(string-match "q\\|Q" wp
) mw
(> (length wp
) 0))
1911 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
1916 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
1921 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (org-quarter-to-date (+ mw n
) y
))))
1922 (setq ins
(format-time-string
1923 (concatenate 'string
(number-to-string y
) "-Q" (number-to-string (+ mw n
)))
1924 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
1926 (setq ins
(format-time-string
1928 (encode-time 0 0 0 1 (+ mw n
) y
))))
1930 (setq ins
(number-to-string (+ y n
))))))
1931 (t (error "Cannot shift clocktable block")))
1935 (delete-region (point) (+ (point) (- e b
)))
1936 (beginning-of-line 1)
1940 (defun org-dblock-write:clocktable
(params)
1941 "Write the standard clocktable."
1942 (setq params
(org-combine-plists org-clocktable-defaults params
))
1944 (let* ((scope (plist-get params
:scope
))
1945 (block (plist-get params
:block
))
1946 (ts (plist-get params
:tstart
))
1947 (te (plist-get params
:tend
))
1948 (link (plist-get params
:link
))
1949 (maxlevel (or (plist-get params
:maxlevel
) 3))
1950 (step (plist-get params
:step
))
1951 (timestamp (plist-get params
:timestamp
))
1952 (formatter (or (plist-get params
:formatter
)
1953 org-clock-clocktable-formatter
1954 'org-clocktable-write-default
))
1955 cc range-text ipos pos one-file-with-archives
1956 scope-is-list tbls level
)
1958 ;; Check if we need to do steps
1960 ;; Get the range text for the header
1961 (setq cc
(org-clock-special-range block nil t
)
1962 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1964 ;; Write many tables, in steps
1965 (unless (or block
(and ts te
))
1966 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1967 (org-clocktable-steps params
)
1970 (setq ipos
(point)) ; remember the insertion position
1972 ;; Get the right scope
1975 ((and scope
(listp scope
) (symbolp (car scope
)))
1976 (setq scope
(eval scope
)))
1978 (setq scope
(org-agenda-files t
)))
1979 ((eq scope
'agenda-with-archives
)
1980 (setq scope
(org-agenda-files t
))
1981 (setq scope
(org-add-archive-files scope
)))
1982 ((eq scope
'file-with-archives
)
1983 (setq scope
(org-add-archive-files (list (buffer-file-name)))
1984 one-file-with-archives t
)))
1985 (setq scope-is-list
(and scope
(listp scope
)))
1987 ;; we collect from several files
1988 (let* ((files scope
)
1990 (org-prepare-agenda-buffers files
)
1991 (while (setq file
(pop files
))
1992 (with-current-buffer (find-buffer-visiting file
)
1995 (push (org-clock-get-table-data file params
) tbls
))))))
1996 ;; Just from the current file
1998 ;; get the right range into the restriction
1999 (org-prepare-agenda-buffers (list (buffer-file-name)))
2001 ((not scope
)) ; use the restriction as it is now
2002 ((eq scope
'file
) (widen))
2003 ((eq scope
'subtree
) (org-narrow-to-subtree))
2005 (while (org-up-heading-safe))
2006 (org-narrow-to-subtree))
2007 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
2008 (symbol-name scope
)))
2009 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
2011 (while (org-up-heading-safe)
2012 (looking-at outline-regexp
)
2013 (if (<= (org-reduced-level (funcall outline-level
)) level
)
2014 (throw 'exit nil
))))
2015 (org-narrow-to-subtree)))
2016 ;; do the table, with no file name.
2017 (push (org-clock-get-table-data nil params
) tbls
)))
2019 ;; OK, at this point we tbls as a list of tables, one per file
2020 (setq tbls
(nreverse tbls
))
2022 (setq params
(plist-put params
:multifile scope-is-list
))
2023 (setq params
(plist-put params
:one-file-with-archives
2024 one-file-with-archives
))
2026 (funcall formatter ipos tbls params
))))
2028 (defun org-clocktable-write-default (ipos tables params
)
2029 "Write out a clock table at position IPOS in the current buffer.
2030 TABLES is a list of tables with clocking data as produced by
2031 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2032 from the dynamic block defintion."
2033 ;; This function looks quite complicated, mainly because there are a
2034 ;; lot of options which can add or remove columns. I have massively
2035 ;; commented this function, the I hope it is understandable. If
2036 ;; someone wants to write their own special formatter, this maybe
2037 ;; much easier because there can be a fixed format with a
2038 ;; well-defined number of columns...
2039 (let* ((hlchars '((1 .
"*") (2 .
"/")))
2040 (lwords (assoc (or (plist-get params
:lang
)
2041 org-export-default-language
)
2042 org-clock-clocktable-language-setup
))
2043 (multifile (plist-get params
:multifile
))
2044 (block (plist-get params
:block
))
2045 (ts (plist-get params
:tstart
))
2046 (te (plist-get params
:tend
))
2047 (header (plist-get params
:header
))
2048 (narrow (plist-get params
:narrow
))
2049 (link (plist-get params
:link
))
2050 (maxlevel (or (plist-get params
:maxlevel
) 3))
2051 (emph (plist-get params
:emphasize
))
2052 (level-p (plist-get params
:level
))
2053 (timestamp (plist-get params
:timestamp
))
2054 (ntcol (max 1 (or (plist-get params
:tcolumns
) 100)))
2055 (rm-file-column (plist-get params
:one-file-with-archives
))
2056 (indent (plist-get params
:indent
))
2057 range-text total-time tbl level hlc formula pcol
2058 file-time entries entry headline
2059 recalc content narrow-cut-p tcol
)
2061 ;; Implement abbreviations
2062 (when (plist-get params
:compact
)
2063 (setq level nil indent t narrow
(or narrow
'40!) ntcol
1))
2065 ;; Some consistency test for parameters
2066 (unless (integerp ntcol
)
2067 (setq params
(plist-put params
:tcolumns
(setq ntcol
100))))
2069 (when (and narrow
(integerp narrow
) link
)
2070 ;; We cannot have both integer narrow and link
2072 "Using hard narrowing in clocktable to allow for links")
2073 (setq narrow
(intern (format "%d!" narrow
))))
2078 ((and (symbolp narrow
)
2079 (string-match "\\`[0-9]+!\\'" (symbol-name narrow
)))
2080 (setq narrow-cut-p t
2081 narrow
(string-to-number (substring (symbol-name narrow
)
2084 (error "Invalid value %s of :narrow property in clock table"
2088 ;; Get the range text for the header
2089 (setq range-text
(nth 2 (org-clock-special-range block nil t
))))
2091 ;; Compute the total time
2092 (setq total-time
(apply '+ (mapcar 'cadr tables
)))
2094 ;; Now we need to output this tsuff
2097 ;; Insert the text *before* the actual table
2098 (insert-before-markers
2100 ;; Format the standard header
2102 "Clock summary at ["
2104 (format-time-string (cdr org-time-stamp-formats
))
2107 (if block
(concat ", for " range-text
".") "")
2110 ;; Insert the narrowing line
2111 (when (and narrow
(integerp narrow
) (not narrow-cut-p
))
2112 (insert-before-markers
2113 "|" ; table line starter
2114 (if multifile
"|" "") ; file column, maybe
2115 (if level-p
"|" "") ; level column, maybe
2116 (if timestamp
"|" "") ; timestamp column, maybe
2117 (format "<%d>| |\n" narrow
))) ; headline and time columns
2119 ;; Insert the table header line
2120 (insert-before-markers
2121 "|" ; table line starter
2122 (if multifile
(concat (nth 1 lwords
) "|") "") ; file column, maybe
2123 (if level-p
(concat (nth 2 lwords
) "|") "") ; level column, maybe
2124 (if timestamp
(concat (nth 3 lwords
) "|") "") ; timestamp column, maybe
2125 (concat (nth 4 lwords
) "|"
2126 (nth 5 lwords
) "|\n")) ; headline and time columns
2128 ;; Insert the total time in the table
2129 (insert-before-markers
2131 "|" ; table line starter
2132 (if multifile
(concat "| " (nth 6 lwords
) " ") "")
2133 ; file column, maybe
2134 (if level-p
"|" "") ; level column, maybe
2135 (if timestamp
"|" "") ; timestamp column, maybe
2136 (concat "*" (nth 7 lwords
) "*| ") ; instead of a headline
2138 (org-minutes-to-hh:mm-string
(or total-time
0)) ; the time
2139 "*|\n") ; close line
2141 ;; Now iterate over the tables and insert the data
2142 ;; but only if any time has been collected
2143 (when (and total-time
(> total-time
0))
2145 (while (setq tbl
(pop tables
))
2146 ;; now tbl is the table resulting from one file.
2147 (setq file-time
(nth 1 tbl
))
2148 (when (or (and file-time
(> file-time
0))
2149 (not (plist-get params
:fileskip0
)))
2150 (insert-before-markers "|-\n") ; a hline because a new file starts
2151 ;; First the file time, if we have multiple files
2153 ;; Summarize the time colleted from this file
2154 (insert-before-markers
2155 (format (concat "| %s %s | %s*" (nth 8 lwords
) "* | *%s*|\n")
2156 (file-name-nondirectory (car tbl
))
2157 (if level-p
"| " "") ; level column, maybe
2158 (if timestamp
"| " "") ; timestamp column, maybe
2159 (org-minutes-to-hh:mm-string
(nth 1 tbl
))))) ; the time
2161 ;; Get the list of node entries and iterate over it
2162 (setq entries
(nth 2 tbl
))
2163 (while (setq entry
(pop entries
))
2164 (setq level
(car entry
)
2165 headline
(nth 1 entry
)
2166 hlc
(if emph
(or (cdr (assoc level hlchars
)) "") ""))
2168 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2173 (format "[[%s][%s]]"
2174 (match-string 1 headline
)
2175 (org-shorten-string (match-string 3 headline
)
2177 (setq headline
(org-shorten-string headline narrow
))))
2178 (insert-before-markers
2179 "|" ; start the table line
2180 (if multifile
"|" "") ; free space for file name column?
2181 (if level-p
(format "%d|" (car entry
)) "") ; level, maybe
2182 (if timestamp
(concat (nth 2 entry
) "|") "") ; timestamp, maybe
2183 (if indent
(org-clocktable-indent-string level
) "") ; indentation
2184 hlc headline hlc
"|" ; headline
2185 (make-string (min (1- ntcol
) (or (- level
1))) ?|
)
2186 ; empty fields for higher levels
2187 hlc
(org-minutes-to-hh:mm-string
(nth 3 entry
)) hlc
; time
2190 (backward-delete-char 1)
2191 (if (setq formula
(plist-get params
:formula
))
2194 ;; compute the column where the % numbers need to go
2199 (min maxlevel
(or ntcol
100))))
2200 ;; compute the column where the total time is
2204 (if timestamp
1 0)))
2207 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2208 pcol
; the column where the % numbers should go
2209 (if (and narrow
(not narrow-cut-p
)) 3 2) ; row of the total time
2210 tcol
; column of the total time
2211 tcol
(1- pcol
) ; range of columns where times can be found
2215 (insert "\n#+TBLFM: " formula
)
2217 (t (error "invalid formula in clocktable")))
2218 ;; Should we rescue an old formula?
2219 (when (stringp (setq content
(plist-get params
:content
)))
2220 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content
)
2222 (insert "\n" (match-string 1 (plist-get params
:content
)))
2223 (beginning-of-line 0))))
2224 ;; Back to beginning, align the table, recalculate if necessary
2226 (skip-chars-forward "^|")
2228 (when org-hide-emphasis-markers
2229 ;; we need to align a second time
2234 (if (and narrow
(not narrow-cut-p
)) (beginning-of-line 2))
2235 (org-table-goto-column pcol nil
'force
)
2237 (org-table-recalculate 'all
))
2238 (when rm-file-column
2239 ;; The file column is actually not wanted
2241 (org-table-delete-column))
2244 (defun org-clocktable-indent-string (level)
2249 (setq level
(1- level
)
2250 str
(concat str
"___")))
2253 (defun org-clocktable-steps (params)
2254 "Step through the range to make a number of clock tables."
2255 (let* ((p1 (copy-sequence params
))
2256 (ts (plist-get p1
:tstart
))
2257 (te (plist-get p1
:tend
))
2258 (step0 (plist-get p1
:step
))
2259 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
2260 (stepskip0 (plist-get p1
:stepskip0
))
2261 (block (plist-get p1
:block
))
2262 cc range-text step-time
)
2264 (setq cc
(org-clock-special-range block nil t
)
2265 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
2268 ;; If ts is a number, it's an absolute day number from org-agenda.
2269 (destructuring-bind (month day year
) (calendar-gregorian-from-absolute ts
)
2270 (setq ts
(org-float-time (encode-time 0 0 0 day month year
)))))
2272 (setq ts
(org-float-time
2273 (apply 'encode-time
(org-parse-time-string ts
))))))
2277 (destructuring-bind (month day year
) (calendar-gregorian-from-absolute te
)
2278 (setq te
(org-float-time (encode-time 0 0 0 day month year
)))))
2280 (setq te
(org-float-time
2281 (apply 'encode-time
(org-parse-time-string te
))))))
2282 (setq p1
(plist-put p1
:header
""))
2283 (setq p1
(plist-put p1
:step nil
))
2284 (setq p1
(plist-put p1
:block nil
))
2286 (or (bolp) (insert "\n"))
2287 (setq p1
(plist-put p1
:tstart
(format-time-string
2288 (org-time-stamp-format nil t
)
2289 (seconds-to-time ts
))))
2290 (setq p1
(plist-put p1
:tend
(format-time-string
2291 (org-time-stamp-format nil t
)
2292 (seconds-to-time (setq ts
(+ ts step
))))))
2293 (insert "\n" (if (eq step0
'day
) "Daily report: "
2294 "Weekly report starting on: ")
2295 (plist-get p1
:tstart
) "\n")
2296 (setq step-time
(org-dblock-write:clocktable p1
))
2297 (re-search-forward "^[ \t]*#\\+END:")
2298 (when (and (equal step-time
0) stepskip0
)
2299 ;; Remove the empty table
2300 (delete-region (point-at-bol)
2302 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2307 (defun org-clock-get-table-data (file params
)
2308 "Get the clocktable data for file FILE, with parameters PARAMS.
2309 FILE is only for identification - this function assumes that
2310 the correct buffer is current, and that the wanted restriction is
2312 The return value will be a list with the file name and the total
2313 file time (in minutes) as 1st and 2nd elements. The third element
2314 of this list will be a list of headline entries. Each entry has the
2315 following structure:
2317 (LEVEL HEADLINE TIMESTAMP TIME)
2319 LEVEL: The level of the headline, as an integer. This will be
2320 the reduced leve, so 1,2,3,... even if only odd levels
2322 HEADLINE: The text of the headline. Depending on PARAMS, this may
2323 already be formatted like a link.
2324 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2325 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2327 TIME: The sum of all time spend in this tree, in minutes. This time
2328 will of cause be restricted to the time block and tags match
2329 specified in PARAMS."
2330 (let* ((maxlevel (or (plist-get params
:maxlevel
) 3))
2331 (timestamp (plist-get params
:timestamp
))
2332 (ts (plist-get params
:tstart
))
2333 (te (plist-get params
:tend
))
2334 (block (plist-get params
:block
))
2335 (link (plist-get params
:link
))
2336 (tags (plist-get params
:tags
))
2337 (matcher (if tags
(cdr (org-make-tags-matcher tags
))))
2338 cc range-text st p time level hdl props tsp tbl
)
2340 (setq org-clock-file-total-minutes nil
)
2342 (setq cc
(org-clock-special-range block nil t
)
2343 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
2344 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
2345 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
2346 (when (and ts
(listp ts
))
2347 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
2348 (when (and te
(listp te
))
2349 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
2350 ;; Now the times are strings we can parse.
2351 (if ts
(setq ts
(org-float-time
2352 (apply 'encode-time
(org-parse-time-string ts
)))))
2353 (if te
(setq te
(org-float-time
2354 (apply 'encode-time
(org-parse-time-string te
)))))
2356 (org-clock-sum ts te
2357 (unless (null matcher
)
2359 (let ((tags-list (org-get-tags-at)))
2361 (goto-char (point-min))
2363 (while (or (and (bobp) (prog1 st
(setq st nil
))
2364 (get-text-property (point) :org-clock-minutes
)
2365 (setq p
(point-min)))
2366 (setq p
(next-single-property-change
2367 (point) :org-clock-minutes
)))
2369 (when (setq time
(get-text-property p
:org-clock-minutes
))
2371 (beginning-of-line 1)
2372 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2373 (setq level
(org-reduced-level
2374 (- (match-end 1) (match-beginning 1))))
2375 (<= level maxlevel
))
2376 (setq hdl
(if (not link
)
2378 (org-make-link-string
2379 (format "file:%s::%s"
2382 (org-make-org-heading-search-string
2386 (setq props
(org-entry-properties (point)))
2387 (or (cdr (assoc "SCHEDULED" props
))
2388 (cdr (assoc "DEADLINE" props
))
2389 (cdr (assoc "TIMESTAMP" props
))
2390 (cdr (assoc "TIMESTAMP_IA" props
)))))
2391 (when (> time
0) (push (list level hdl tsp time
) tbl
))))))
2392 (setq tbl
(nreverse tbl
))
2393 (list file org-clock-file-total-minutes tbl
))))
2395 (defun org-clock-time%
(total &rest strings
)
2396 "Compute a time fraction in percent.
2397 TOTAL s a time string like 10:21 specifying the total times.
2398 STRINGS is a list of strings that should be checked for a time.
2399 The first string that does have a time will be used.
2400 This function is made for clock tables."
2401 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2405 (if (not (string-match re total
))
2407 (setq tot
(+ (string-to-number (match-string 2 total
))
2408 (* 60 (string-to-number (match-string 1 total
)))))
2409 (if (= tot
0.
) (throw 'exit
0.
)))
2410 (while (setq s
(pop strings
))
2411 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
2413 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
2414 (* 60 (string-to-number
2415 (match-string 1 s
)))))
2419 (defvar org-clock-loaded nil
2420 "Was the clock file loaded?")
2422 (defun org-clock-save ()
2423 "Persist various clock-related data to disk.
2424 The details of what will be saved are regulated by the variable
2425 `org-clock-persist'."
2426 (when (and org-clock-persist
2427 (or org-clock-loaded
2428 org-clock-has-been-used
2429 (not (file-exists-p org-clock-persist-file
))))
2431 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
2433 (delete-region (point-min) (point-max))
2435 (insert (format ";; org-persist.el - %s at %s\n"
2436 system-name
(format-time-string
2437 (cdr org-time-stamp-formats
))))
2438 (if (and (memq org-clock-persist
'(t clock
))
2439 (setq b
(org-clocking-buffer))
2440 (setq b
(or (buffer-base-buffer b
) b
))
2442 (buffer-file-name b
)
2443 (or (not org-clock-persist-query-save
)
2444 (y-or-n-p (concat "Save current clock ("
2445 (substring-no-properties
2448 (insert "(setq resume-clock '(\""
2449 (buffer-file-name (org-clocking-buffer))
2450 "\" . " (int-to-string (marker-position org-clock-marker
))
2452 ;; Store clocked task history. Tasks are stored reversed to make
2454 (when (and (memq org-clock-persist
'(t history
))
2457 "(setq stored-clock-history '("
2460 (when (and (setq b
(marker-buffer m
))
2461 (setq b
(or (buffer-base-buffer b
) b
))
2463 (buffer-file-name b
))
2464 (concat "(\"" (buffer-file-name b
)
2465 "\" . " (int-to-string (marker-position m
))
2467 (reverse org-clock-history
) " ") "))\n"))
2469 (kill-buffer (current-buffer)))))))
2471 (defun org-clock-load ()
2472 "Load clock-related data from disk, maybe resuming a stored clock."
2473 (when (and org-clock-persist
(not org-clock-loaded
))
2474 (let ((filename (expand-file-name org-clock-persist-file
))
2475 (org-clock-in-resume 'auto-restart
)
2476 resume-clock stored-clock-history
)
2477 (if (not (file-readable-p filename
))
2478 (message "Not restoring clock data; %s not found"
2479 org-clock-persist-file
)
2480 (message "%s" "Restoring clock data")
2481 (setq org-clock-loaded t
)
2482 (load-file filename
)
2484 (when stored-clock-history
2485 (save-window-excursion
2486 (mapc (lambda (task)
2487 (if (file-exists-p (car task
))
2488 (org-clock-history-push (cdr task
)
2489 (find-file (car task
)))))
2490 stored-clock-history
)))
2492 (when (and resume-clock org-clock-persist
2493 (file-exists-p (car resume-clock
))
2494 (or (not org-clock-persist-query-resume
)
2498 (with-current-buffer (find-file (car resume-clock
))
2500 (goto-char (cdr resume-clock
))
2501 (org-back-to-heading t
)
2502 (and (looking-at org-complex-heading-regexp
)
2505 (when (file-exists-p (car resume-clock
))
2506 (with-current-buffer (find-file (car resume-clock
))
2507 (goto-char (cdr resume-clock
))
2508 (let ((org-clock-auto-clock-resolution nil
))
2510 (if (outline-invisible-p)
2511 (org-show-context))))))))))
2514 (defun org-clock-persistence-insinuate ()
2515 "Set up hooks for clock persistence."
2516 (add-hook 'org-mode-hook
'org-clock-load
)
2517 (add-hook 'kill-emacs-hook
'org-clock-save
))
2519 ;; Suggested bindings
2520 (org-defkey org-mode-map
"\C-c\C-x\C-e" 'org-clock-modify-effort-estimate
)
2522 (provide 'org-clock
)
2524 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2526 ;;; org-clock.el ends here