Release 7.01
[org-mode.git] / lisp / org-clock.el
blobf451cf807920d71f3c67f0c8c7e5d16a55dfd298
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
9 ;; Version: 7.01
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the time clocking code for Org-mode
31 (require 'org)
32 ;;; Code:
34 (eval-when-compile
35 (require 'cl))
37 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
38 (defvar org-time-stamp-formats)
40 (defgroup org-clock nil
41 "Options concerning clocking working time in Org-mode."
42 :tag "Org Clock"
43 :group 'org-progress)
45 (defcustom org-clock-into-drawer org-log-into-drawer
46 "Should clocking info be wrapped into a drawer?
47 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
48 If necessary, the drawer will be created.
49 When nil, the drawer will not be created, but used when present.
50 When an integer and the number of clocking entries in an item
51 reaches or exceeds this number, a drawer will be created.
52 When a string, it names the drawer to be used.
54 The default for this variable is the value of `org-log-into-drawer',
55 which see."
56 :group 'org-todo
57 :group 'org-clock
58 :type '(choice
59 (const :tag "Always" t)
60 (const :tag "Only when drawer exists" nil)
61 (integer :tag "When at least N clock entries")
62 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
63 (string :tag "Into Drawer named...")))
65 (defcustom org-clock-out-when-done t
66 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
67 DONE here means any DONE-like state.
68 A nil value means clock will keep running until stopped explicitly with
69 `C-c C-x C-o', or until the clock is started in a different item.
70 Instead of t, this can also be a list of TODO states that should trigger
71 clocking out."
72 :group 'org-clock
73 :type '(choice
74 (const :tag "No" nil)
75 (const :tag "Yes, when done" t)
76 (repeat :tag "State list"
77 (string :tag "TODO keyword"))))
79 (defcustom org-clock-out-remove-zero-time-clocks nil
80 "Non-nil means remove the clock line when the resulting time is zero."
81 :group 'org-clock
82 :type 'boolean)
84 (defcustom org-clock-in-switch-to-state nil
85 "Set task to a special todo state while clocking it.
86 The value should be the state to which the entry should be
87 switched. If the value is a function, it must take one
88 parameter (the current TODO state of the item) and return the
89 state to switch it to."
90 :group 'org-clock
91 :group 'org-todo
92 :type '(choice
93 (const :tag "Don't force a state" nil)
94 (string :tag "State")
95 (symbol :tag "Function")))
97 (defcustom org-clock-out-switch-to-state nil
98 "Set task to a special todo state after clocking out.
99 The value should be the state to which the entry should be
100 switched. If the value is a function, it must take one
101 parameter (the current TODO state of the item) and return the
102 state to switch it to."
103 :group 'org-clock
104 :group 'org-todo
105 :type '(choice
106 (const :tag "Don't force a state" nil)
107 (string :tag "State")
108 (symbol :tag "Function")))
110 (defcustom org-clock-history-length 5
111 "Number of clock tasks to remember in history."
112 :group 'org-clock
113 :type 'integer)
115 (defcustom org-clock-goto-may-find-recent-task t
116 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
117 :group 'org-clock
118 :type 'boolean)
120 (defcustom org-clock-heading-function nil
121 "When non-nil, should be a function to create `org-clock-heading'.
122 This is the string shown in the mode line when a clock is running.
123 The function is called with point at the beginning of the headline."
124 :group 'org-clock
125 :type 'function)
127 (defcustom org-clock-string-limit 0
128 "Maximum length of clock strings in the modeline. 0 means no limit."
129 :group 'org-clock
130 :type 'integer)
132 (defcustom org-clock-in-resume nil
133 "If non-nil, resume clock when clocking into task with open clock.
134 When clocking into a task with a clock entry which has not been closed,
135 the clock can be resumed from that point."
136 :group 'org-clock
137 :type 'boolean)
139 (defcustom org-clock-persist nil
140 "When non-nil, save the running clock when Emacs is closed.
141 The clock is resumed when Emacs restarts.
142 When this is t, both the running clock, and the entire clock
143 history are saved. When this is the symbol `clock', only the
144 running clock is saved.
146 When Emacs restarts with saved clock information, the file containing the
147 running clock as well as all files mentioned in the clock history will
148 be visited.
149 All this depends on running `org-clock-persistence-insinuate' in .emacs"
150 :group 'org-clock
151 :type '(choice
152 (const :tag "Just the running clock" clock)
153 (const :tag "Just the history" history)
154 (const :tag "Clock and history" t)
155 (const :tag "No persistence" nil)))
157 (defcustom org-clock-persist-file (convert-standard-filename
158 "~/.emacs.d/org-clock-save.el")
159 "File to save clock data to."
160 :group 'org-clock
161 :type 'string)
163 (defcustom org-clock-persist-query-save nil
164 "When non-nil, ask before saving the current clock on exit."
165 :group 'org-clock
166 :type 'boolean)
168 (defcustom org-clock-persist-query-resume t
169 "When non-nil, ask before resuming any stored clock during load."
170 :group 'org-clock
171 :type 'boolean)
173 (defcustom org-clock-sound nil
174 "Sound that will used for notifications.
175 Possible values:
177 nil no sound played.
178 t standard Emacs beep
179 file name play this sound file. If not possible, fall back to beep"
180 :group 'org-clock
181 :type '(choice
182 (const :tag "No sound" nil)
183 (const :tag "Standard beep" t)
184 (file :tag "Play sound file")))
186 (defcustom org-clock-modeline-total 'auto
187 "Default setting for the time included for the modeline clock.
188 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
189 Allowed values are:
191 current Only the time in the current instance of the clock
192 today All time clocked into this task today
193 repeat All time clocked into this task since last repeat
194 all All time ever recorded for this task
195 auto Automatically, either `all', or `repeat' for repeating tasks"
196 :group 'org-clock
197 :type '(choice
198 (const :tag "Current clock" current)
199 (const :tag "Today's task time" today)
200 (const :tag "Since last repeat" repeat)
201 (const :tag "All task time" all)
202 (const :tag "Automatically, `all' or since `repeat'" auto)))
204 (defcustom org-task-overrun-text nil
205 "The extra modeline text that should indicate that the clock is overrun.
206 The can be nil to indicate that instead of adding text, the clock time
207 should get a different face (`org-mode-line-clock-overrun').
208 When this is a string, it is prepended to the clock string as an indication,
209 also using the face `org-mode-line-clock-overrun'."
210 :group 'org-clock
211 :type '(choice
212 (const :tag "Just mark the time string" nil)
213 (string :tag "Text to prepend")))
215 (defcustom org-show-notification-handler nil
216 "Function or program to send notification with.
217 The function or program will be called with the notification
218 string as argument."
219 :group 'org-clock
220 :type '(choice
221 (string :tag "Program")
222 (function :tag "Function")))
224 (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
225 "Default properties for new clocktables."
226 :group 'org-clock
227 :type 'plist)
229 (defcustom org-clock-idle-time nil
230 "When non-nil, resolve open clocks if the user is idle more than X minutes."
231 :group 'org-clock
232 :type '(choice
233 (const :tag "Never" nil)
234 (integer :tag "After N minutes")))
236 (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
237 "When to automatically resolve open clocks found in Org buffers."
238 :group 'org-clock
239 :type '(choice
240 (const :tag "Never" nil)
241 (const :tag "Always" t)
242 (const :tag "When no clock is running" when-no-clock-is-running)))
244 (defcustom org-clock-report-include-clocking-task nil
245 "When non-nil, include the current clocking task time in clock reports."
246 :group 'org-clock
247 :type 'boolean)
249 (defcustom org-clock-resolve-expert nil
250 "Non-nil means do not show the splash buffer with the clock resolver."
251 :group 'org-clock
252 :type 'boolean)
254 (defvar org-clock-in-prepare-hook nil
255 "Hook run when preparing the clock.
256 This hook is run before anything happens to the task that
257 you want to clock in. For example, you can use this hook
258 to add an effort property.")
259 (defvar org-clock-in-hook nil
260 "Hook run when starting the clock.")
261 (defvar org-clock-out-hook nil
262 "Hook run when stopping the current clock.")
264 (defvar org-clock-cancel-hook nil
265 "Hook run when cancelling the current clock.")
266 (defvar org-clock-goto-hook nil
267 "Hook run when selecting the currently clocked-in entry.")
268 (defvar org-clock-has-been-used nil
269 "Has the clock been used during the current Emacs session?")
271 ;;; The clock for measuring work time.
273 (defvar org-mode-line-string "")
274 (put 'org-mode-line-string 'risky-local-variable t)
276 (defvar org-clock-mode-line-timer nil)
277 (defvar org-clock-idle-timer nil)
278 (defvar org-clock-heading) ; defined in org.el
279 (defvar org-clock-heading-for-remember "")
280 (defvar org-clock-start-time "")
282 (defvar org-clock-leftover-time nil
283 "If non-nil, user cancelled a clock; this is when leftover time started.")
285 (defvar org-clock-effort ""
286 "Effort estimate of the currently clocking task.")
288 (defvar org-clock-total-time nil
289 "Holds total time, spent previously on currently clocked item.
290 This does not include the time in the currently running clock.")
292 (defvar org-clock-history nil
293 "List of marker pointing to recent clocked tasks.")
295 (defvar org-clock-default-task (make-marker)
296 "Marker pointing to the default task that should clock time.
297 The clock can be made to switch to this task after clocking out
298 of a different task.")
300 (defvar org-clock-interrupted-task (make-marker)
301 "Marker pointing to the task that has been interrupted by the current clock.")
303 (defvar org-clock-mode-line-map (make-sparse-keymap))
304 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
305 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
307 (defun org-clock-menu ()
308 (interactive)
309 (popup-menu
310 '("Clock"
311 ["Clock out" org-clock-out t]
312 ["Change effort estimate" org-clock-modify-effort-estimate t]
313 ["Go to clock entry" org-clock-goto t]
314 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
316 (defun org-clock-history-push (&optional pos buffer)
317 "Push a marker to the clock history."
318 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
319 (let ((m (move-marker (make-marker)
320 (or pos (point)) (org-base-buffer
321 (or buffer (current-buffer)))))
322 n l)
323 (while (setq n (member m org-clock-history))
324 (move-marker (car n) nil))
325 (setq org-clock-history
326 (delq nil
327 (mapcar (lambda (x) (if (marker-buffer x) x nil))
328 org-clock-history)))
329 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
330 (setq org-clock-history
331 (nreverse
332 (nthcdr (- l org-clock-history-length -1)
333 (nreverse org-clock-history)))))
334 (push m org-clock-history)))
336 (defun org-clock-save-markers-for-cut-and-paste (beg end)
337 "Save relative positions of markers in region."
338 (org-check-and-save-marker org-clock-marker beg end)
339 (org-check-and-save-marker org-clock-hd-marker beg end)
340 (org-check-and-save-marker org-clock-default-task beg end)
341 (org-check-and-save-marker org-clock-interrupted-task beg end)
342 (mapc (lambda (m) (org-check-and-save-marker m beg end))
343 org-clock-history))
345 (defun org-clocking-buffer ()
346 "Return the clocking buffer if we are currently clocking a task or nil."
347 (marker-buffer org-clock-marker))
349 (defun org-clocking-p ()
350 "Return t when clocking a task."
351 (not (equal (org-clocking-buffer) nil)))
353 (defun org-clock-select-task (&optional prompt)
354 "Select a task that recently was associated with clocking."
355 (interactive)
356 (let (sel-list rpl (i 0) s)
357 (save-window-excursion
358 (org-switch-to-buffer-other-window
359 (get-buffer-create "*Clock Task Select*"))
360 (erase-buffer)
361 (when (marker-buffer org-clock-default-task)
362 (insert (org-add-props "Default Task\n" nil 'face 'bold))
363 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
364 (push s sel-list))
365 (when (marker-buffer org-clock-interrupted-task)
366 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
367 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
368 (push s sel-list))
369 (when (org-clocking-p)
370 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
371 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
372 (push s sel-list))
373 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
374 (mapc
375 (lambda (m)
376 (when (marker-buffer m)
377 (setq i (1+ i)
378 s (org-clock-insert-selection-line
379 (if (< i 10)
380 (+ i ?0)
381 (+ i (- ?A 10))) m))
382 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
383 (push s sel-list)))
384 org-clock-history)
385 (org-fit-window-to-buffer)
386 (message (or prompt "Select task for clocking:"))
387 (setq rpl (read-char-exclusive))
388 (cond
389 ((eq rpl ?q) nil)
390 ((eq rpl ?x) nil)
391 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
392 (t (error "Invalid task choice %c" rpl))))))
394 (defun org-clock-insert-selection-line (i marker)
395 "Insert a line for the clock selection menu.
396 And return a cons cell with the selection character integer and the marker
397 pointing to it."
398 (when (marker-buffer marker)
399 (let (file cat task heading prefix)
400 (with-current-buffer (org-base-buffer (marker-buffer marker))
401 (save-excursion
402 (save-restriction
403 (widen)
404 (ignore-errors
405 (goto-char marker)
406 (setq file (buffer-file-name (marker-buffer marker))
407 cat (or (org-get-category)
408 (progn (org-refresh-category-properties)
409 (org-get-category)))
410 heading (org-get-heading 'notags)
411 prefix (save-excursion
412 (org-back-to-heading t)
413 (looking-at "\\*+ ")
414 (match-string 0))
415 task (substring
416 (org-fontify-like-in-org-mode
417 (concat prefix heading)
418 org-odd-levels-only)
419 (length prefix)))))))
420 (when (and cat task)
421 (insert (format "[%c] %-15s %s\n" i cat task))
422 (cons i marker)))))
424 (defvar org-task-overrun nil
425 "Internal flag indicating if the clock has overrun the planned time.")
426 (defvar org-clock-update-period 60
427 "Number of seconds between mode line clock string updates.")
429 (defun org-clock-get-clock-string ()
430 "Form a clock-string, that will be shown in the mode line.
431 If an effort estimate was defined for the current item, use
432 01:30/01:50 format (clocked/estimated).
433 If not, show simply the clocked time like 01:50."
434 (let* ((clocked-time (org-clock-get-clocked-time))
435 (h (floor clocked-time 60))
436 (m (- clocked-time (* 60 h))))
437 (if org-clock-effort
438 (let* ((effort-in-minutes
439 (org-hh:mm-string-to-minutes org-clock-effort))
440 (effort-h (floor effort-in-minutes 60))
441 (effort-m (- effort-in-minutes (* effort-h 60)))
442 (work-done-str
443 (org-propertize
444 (format org-time-clocksum-format h m)
445 'face (if (and org-task-overrun (not org-task-overrun-text))
446 'org-mode-line-clock-overrun 'org-mode-line-clock)))
447 (effort-str (format org-time-clocksum-format effort-h effort-m))
448 (clockstr (org-propertize
449 (concat "[%s/" effort-str
450 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
451 'face 'org-mode-line-clock)))
452 (format clockstr work-done-str))
453 (org-propertize (format
454 (concat "[" org-time-clocksum-format " (%s)]")
455 h m org-clock-heading)
456 'face 'org-mode-line-clock))))
458 (defun org-clock-update-mode-line ()
459 (if org-clock-effort
460 (org-clock-notify-once-if-expired)
461 (setq org-task-overrun nil))
462 (setq org-mode-line-string
463 (org-propertize
464 (let ((clock-string (org-clock-get-clock-string))
465 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
466 (if (and (> org-clock-string-limit 0)
467 (> (length clock-string) org-clock-string-limit))
468 (org-propertize
469 (substring clock-string 0 org-clock-string-limit)
470 'help-echo (concat help-text ": " org-clock-heading))
471 (org-propertize clock-string 'help-echo help-text)))
472 'local-map org-clock-mode-line-map
473 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
475 (if (and org-task-overrun org-task-overrun-text)
476 (setq org-mode-line-string
477 (concat (org-propertize
478 org-task-overrun-text
479 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
480 (force-mode-line-update))
482 (defun org-clock-get-clocked-time ()
483 "Get the clocked time for the current item in minutes.
484 The time returned includes the time spent on this task in
485 previous clocking intervals."
486 (let ((currently-clocked-time
487 (floor (- (org-float-time)
488 (org-float-time org-clock-start-time)) 60)))
489 (+ currently-clocked-time (or org-clock-total-time 0))))
491 (defun org-clock-modify-effort-estimate (&optional value)
492 "Add to or set the effort estimate of the item currently being clocked.
493 VALUE can be a number of minutes, or a string with format hh:mm or mm.
494 When the string starts with a + or a - sign, the current value of the effort
495 property will be changed by that amount.
496 This will update the \"Effort\" property of currently clocked item, and
497 the mode line."
498 (interactive)
499 (when (org-clock-is-active)
500 (let ((current org-clock-effort) sign)
501 (unless value
502 ;; Prompt user for a value or a change
503 (setq value
504 (read-string
505 (format "Set effort (hh:mm or mm%s): "
506 (if current
507 (format ", prefix + to add to %s" org-clock-effort)
508 "")))))
509 (when (stringp value)
510 ;; A string. See if it is a delta
511 (setq sign (string-to-char value))
512 (if (member sign '(?- ?+))
513 (setq current (org-hh:mm-string-to-minutes current)
514 value (substring value 1))
515 (setq current 0))
516 (setq value (org-hh:mm-string-to-minutes value))
517 (if (equal ?- sign)
518 (setq value (- current value))
519 (if (equal ?+ sign) (setq value (+ current value)))))
520 (setq value (max 0 value)
521 org-clock-effort (org-minutes-to-hh:mm-string value))
522 (org-entry-put org-clock-marker "Effort" org-clock-effort)
523 (org-clock-update-mode-line)
524 (message "Effort is now %s" org-clock-effort))))
526 (defvar org-clock-notification-was-shown nil
527 "Shows if we have shown notification already.")
529 (defun org-clock-notify-once-if-expired ()
530 "Show notification if we spent more time than we estimated before.
531 Notification is shown only once."
532 (when (org-clocking-p)
533 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
534 (clocked-time (org-clock-get-clocked-time)))
535 (if (setq org-task-overrun
536 (if (or (null effort-in-minutes) (zerop effort-in-minutes))
538 (>= clocked-time effort-in-minutes)))
539 (unless org-clock-notification-was-shown
540 (setq org-clock-notification-was-shown t)
541 (org-notify
542 (format "Task '%s' should be finished by now. (%s)"
543 org-clock-heading org-clock-effort) t))
544 (setq org-clock-notification-was-shown nil)))))
546 (defun org-notify (notification &optional play-sound)
547 "Send a NOTIFICATION and maybe PLAY-SOUND."
548 (org-show-notification notification)
549 (if play-sound (org-clock-play-sound)))
551 (defun org-show-notification (notification)
552 "Show notification.
553 Use `org-show-notification-handler' if defined,
554 use libnotify if available, or fall back on a message."
555 (cond ((functionp org-show-notification-handler)
556 (funcall org-show-notification-handler notification))
557 ((stringp org-show-notification-handler)
558 (start-process "emacs-timer-notification" nil
559 org-show-notification-handler notification))
560 ((org-program-exists "notify-send")
561 (start-process "emacs-timer-notification" nil
562 "notify-send" notification))
563 ;; Maybe the handler will send a message, so only use message as
564 ;; a fall back option
565 (t (message "%s" notification))))
567 (defun org-clock-play-sound ()
568 "Play sound as configured by `org-clock-sound'.
569 Use alsa's aplay tool if available."
570 (cond
571 ((not org-clock-sound))
572 ((eq org-clock-sound t) (beep t) (beep t))
573 ((stringp org-clock-sound)
574 (let ((file (expand-file-name org-clock-sound)))
575 (if (file-exists-p file)
576 (if (org-program-exists "aplay")
577 (start-process "org-clock-play-notification" nil
578 "aplay" file)
579 (condition-case nil
580 (play-sound-file file)
581 (error (beep t) (beep t)))))))))
583 (defun org-program-exists (program-name)
584 "Checks whenever we can locate program and launch it."
585 (if (eq system-type 'gnu/linux)
586 (= 0 (call-process "which" nil nil nil program-name))))
588 (defvar org-clock-mode-line-entry nil
589 "Information for the modeline about the running clock.")
591 (defun org-find-open-clocks (file)
592 "Search through the given file and find all open clocks."
593 (let ((buf (or (get-file-buffer file)
594 (find-file-noselect file)))
595 clocks)
596 (with-current-buffer buf
597 (save-excursion
598 (goto-char (point-min))
599 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
600 (push (cons (copy-marker (match-end 1) t)
601 (org-time-string-to-time (match-string 1))) clocks))))
602 clocks))
604 (defsubst org-is-active-clock (clock)
605 "Return t if CLOCK is the currently active clock."
606 (and (org-clock-is-active)
607 (= org-clock-marker (car clock))))
609 (defmacro org-with-clock-position (clock &rest forms)
610 "Evaluate FORMS with CLOCK as the current active clock."
611 `(with-current-buffer (marker-buffer (car ,clock))
612 (save-excursion
613 (save-restriction
614 (widen)
615 (goto-char (car ,clock))
616 (beginning-of-line)
617 ,@forms))))
619 (put 'org-with-clock-position 'lisp-indent-function 1)
621 (defmacro org-with-clock (clock &rest forms)
622 "Evaluate FORMS with CLOCK as the current active clock.
623 This macro also protects the current active clock from being altered."
624 `(org-with-clock-position ,clock
625 (let ((org-clock-start-time (cdr ,clock))
626 (org-clock-total-time)
627 (org-clock-history)
628 (org-clock-effort)
629 (org-clock-marker (car ,clock))
630 (org-clock-hd-marker (save-excursion
631 (outline-back-to-heading t)
632 (point-marker))))
633 ,@forms)))
635 (put 'org-with-clock 'lisp-indent-function 1)
637 (defsubst org-clock-clock-in (clock &optional resume start-time)
638 "Clock in to the clock located by CLOCK.
639 If necessary, clock-out of the currently active clock."
640 (org-with-clock-position clock
641 (let ((org-clock-in-resume (or resume org-clock-in-resume)))
642 (org-clock-in nil start-time))))
644 (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
645 "Clock out of the clock located by CLOCK."
646 (let ((temp (copy-marker (car clock)
647 (marker-insertion-type (car clock)))))
648 (if (org-is-active-clock clock)
649 (org-clock-out fail-quietly at-time)
650 (org-with-clock clock
651 (org-clock-out fail-quietly at-time)))
652 (setcar clock temp)))
654 (defsubst org-clock-clock-cancel (clock)
655 "Cancel the clock located by CLOCK."
656 (let ((temp (copy-marker (car clock)
657 (marker-insertion-type (car clock)))))
658 (if (org-is-active-clock clock)
659 (org-clock-cancel)
660 (org-with-clock clock
661 (org-clock-cancel)))
662 (setcar clock temp)))
664 (defvar org-clock-clocking-in nil)
665 (defvar org-clock-resolving-clocks nil)
666 (defvar org-clock-resolving-clocks-due-to-idleness nil)
668 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
669 &optional close-p restart-p fail-quietly)
670 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
671 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
672 (let ((org-clock-resolving-clocks t))
673 (cond
674 ((null resolve-to)
675 (org-clock-clock-cancel clock)
676 (if (and restart-p (not org-clock-clocking-in))
677 (org-clock-clock-in clock)))
679 ((eq resolve-to 'now)
680 (if restart-p
681 (error "RESTART-P is not valid here"))
682 (if (or close-p org-clock-clocking-in)
683 (org-clock-clock-out clock fail-quietly)
684 (unless (org-is-active-clock clock)
685 (org-clock-clock-in clock t))))
687 ((not (time-less-p resolve-to (current-time)))
688 (error "RESOLVE-TO must refer to a time in the past"))
691 (if restart-p
692 (error "RESTART-P is not valid here"))
693 (org-clock-clock-out clock fail-quietly (or clock-out-time
694 resolve-to))
695 (unless org-clock-clocking-in
696 (if close-p
697 (setq org-clock-leftover-time (and (null clock-out-time)
698 resolve-to))
699 (org-clock-clock-in clock nil (and clock-out-time
700 resolve-to))))))))
702 (defun org-clock-jump-to-current-clock (&optional effective-clock)
703 (interactive)
704 (let ((clock (or effective-clock (cons org-clock-marker
705 org-clock-start-time))))
706 (unless (marker-buffer (car clock))
707 (error "No clock is currently running"))
708 (org-with-clock clock (org-clock-goto))
709 (with-current-buffer (marker-buffer (car clock))
710 (goto-char (car clock))
711 (if org-clock-into-drawer
712 (let ((logbook
713 (if (stringp org-clock-into-drawer)
714 (concat ":" org-clock-into-drawer ":")
715 ":LOGBOOK:")))
716 (ignore-errors
717 (outline-flag-region
718 (save-excursion
719 (outline-back-to-heading t)
720 (search-forward logbook)
721 (goto-char (match-beginning 0)))
722 (save-excursion
723 (outline-back-to-heading t)
724 (search-forward logbook)
725 (search-forward ":END:")
726 (goto-char (match-end 0)))
727 nil)))))))
729 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
730 "Resolve an open org-mode clock.
731 An open clock was found, with `dangling' possibly being non-nil.
732 If this function was invoked with a prefix argument, non-dangling
733 open clocks are ignored. The given clock requires some sort of
734 user intervention to resolve it, either because a clock was left
735 dangling or due to an idle timeout. The clock resolution can
736 either be:
738 (a) deleted, the user doesn't care about the clock
739 (b) restarted from the current time (if no other clock is open)
740 (c) closed, giving the clock X minutes
741 (d) closed and then restarted
742 (e) resumed, as if the user had never left
744 The format of clock is (CONS MARKER START-TIME), where MARKER
745 identifies the buffer and position the clock is open at (and
746 thus, the heading it's under), and START-TIME is when the clock
747 was started."
748 (assert clock)
749 (let* ((ch
750 (save-window-excursion
751 (save-excursion
752 (unless org-clock-resolving-clocks-due-to-idleness
753 (org-clock-jump-to-current-clock clock))
754 (unless org-clock-resolve-expert
755 (with-output-to-temp-buffer "*Org Clock*"
756 (princ "Select a Clock Resolution Command:
758 i/q/C-g Ignore this question; the same as keeping all the idle time.
760 k/K Keep X minutes of the idle time (default is all). If this
761 amount is less than the default, you will be clocked out
762 that many minutes after the time that idling began, and then
763 clocked back in at the present time.
764 g/G Indicate that you \"got back\" X minutes ago. This is quite
765 different from 'k': it clocks you out from the beginning of
766 the idle period and clock you back in X minutes ago.
767 s/S Subtract the idle time from the current clock. This is the
768 same as keeping 0 minutes.
769 C Cancel the open timer altogether. It will be as though you
770 never clocked in.
771 j/J Jump to the current clock, to make manual adjustments.
773 For all these options, using uppercase makes your final state
774 to be CLOCKED OUT.")))
775 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
776 (let (char-pressed)
777 (when (featurep 'xemacs)
778 (message (concat (funcall prompt-fn clock)
779 " [jkKgGsScCiq]? "))
780 (setq char-pressed (read-char-exclusive)))
781 (while (or (null char-pressed)
782 (and (not (memq char-pressed
783 '(?k ?K ?g ?G ?s ?S ?C
784 ?j ?J ?i ?q)))
785 (or (ding) t)))
786 (setq char-pressed
787 (read-char (concat (funcall prompt-fn clock)
788 " [jkKgGSscCiq]? ")
789 nil 45)))
790 (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
791 (default
792 (floor (/ (org-float-time
793 (time-subtract (current-time) last-valid)) 60)))
794 (keep
795 (and (memq ch '(?k ?K))
796 (read-number "Keep how many minutes? " default)))
797 (gotback
798 (and (memq ch '(?g ?G))
799 (read-number "Got back how many minutes ago? " default)))
800 (subtractp (memq ch '(?s ?S)))
801 (barely-started-p (< (- (org-float-time last-valid)
802 (org-float-time (cdr clock))) 45))
803 (start-over (and subtractp barely-started-p)))
804 (cond
805 ((memq ch '(?j ?J))
806 (if (eq ch ?J)
807 (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
808 (org-clock-jump-to-current-clock clock))
809 ((or (null ch)
810 (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
811 (message ""))
813 (org-clock-resolve-clock
814 clock (cond
815 ((or (eq ch ?C)
816 ;; If the time on the clock was less than a minute before
817 ;; the user went away, and they've ask to subtract all the
818 ;; time...
819 start-over)
820 nil)
821 ((or subtractp
822 (and gotback (= gotback 0)))
823 last-valid)
824 ((or (and keep (= keep default))
825 (and gotback (= gotback default)))
826 'now)
827 (keep
828 (time-add last-valid (seconds-to-time (* 60 keep))))
829 (gotback
830 (time-subtract (current-time)
831 (seconds-to-time (* 60 gotback))))
833 (error "Unexpected, please report this as a bug")))
834 (and gotback last-valid)
835 (memq ch '(?K ?G ?S))
836 (and start-over
837 (not (memq ch '(?K ?G ?S ?C))))
838 fail-quietly)))))
840 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
841 "Resolve all currently open org-mode clocks.
842 If `only-dangling-p' is non-nil, only ask to resolve dangling
843 \(i.e., not currently open and valid) clocks."
844 (interactive "P")
845 (unless org-clock-resolving-clocks
846 (let ((org-clock-resolving-clocks t))
847 (dolist (file (org-files-list))
848 (let ((clocks (org-find-open-clocks file)))
849 (dolist (clock clocks)
850 (let ((dangling (or (not (org-clock-is-active))
851 (/= (car clock) org-clock-marker))))
852 (if (or (not only-dangling-p) dangling)
853 (org-clock-resolve
854 clock
855 (or prompt-fn
856 (function
857 (lambda (clock)
858 (format
859 "Dangling clock started %d mins ago"
860 (floor
861 (/ (- (org-float-time (current-time))
862 (org-float-time (cdr clock))) 60))))))
863 (or last-valid
864 (cdr clock)))))))))))
866 (defun org-emacs-idle-seconds ()
867 "Return the current Emacs idle time in seconds, or nil if not idle."
868 (let ((idle-time (current-idle-time)))
869 (if idle-time
870 (org-float-time idle-time)
871 0)))
873 (defun org-mac-idle-seconds ()
874 "Return the current Mac idle time in seconds."
875 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
877 (defun org-x11-idle-seconds ()
878 "Return the current X11 idle time in seconds."
879 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
881 (defun org-user-idle-seconds ()
882 "Return the number of seconds the user has been idle for.
883 This routine returns a floating point number."
884 (cond
885 ((eq system-type 'darwin)
886 (org-mac-idle-seconds))
887 ((eq window-system 'x)
888 (org-x11-idle-seconds))
890 (org-emacs-idle-seconds))))
892 (defvar org-clock-user-idle-seconds)
894 (defun org-resolve-clocks-if-idle ()
895 "Resolve all currently open org-mode clocks.
896 This is performed after `org-clock-idle-time' minutes, to check
897 if the user really wants to stay clocked in after being idle for
898 so long."
899 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
900 org-clock-marker)
901 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
902 (org-clock-user-idle-start
903 (time-subtract (current-time)
904 (seconds-to-time org-clock-user-idle-seconds)))
905 (org-clock-resolving-clocks-due-to-idleness t))
906 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
907 (org-clock-resolve
908 (cons org-clock-marker
909 org-clock-start-time)
910 (function
911 (lambda (clock)
912 (format "Clocked in & idle for %.1f mins"
913 (/ (org-float-time
914 (time-subtract (current-time)
915 org-clock-user-idle-start))
916 60.0))))
917 org-clock-user-idle-start)))))
919 (defun org-clock-in (&optional select start-time)
920 "Start the clock on the current item.
921 If necessary, clock-out of the currently active clock.
922 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
923 recently clocked tasks to
924 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
925 clock into the current task and mark
926 is as the default task, a special task that will always be offered in
927 the clocking selection, associated with the letter `d'."
928 (interactive "P")
929 (setq org-clock-notification-was-shown nil)
930 (catch 'abort
931 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
932 (org-clocking-p)))
933 ts selected-task target-pos (msg-extra "")
934 (leftover (and (not org-clock-resolving-clocks)
935 org-clock-leftover-time)))
936 (when (and org-clock-auto-clock-resolution
937 (or (not interrupting)
938 (eq t org-clock-auto-clock-resolution))
939 (not org-clock-clocking-in)
940 (not org-clock-resolving-clocks))
941 (setq org-clock-leftover-time nil)
942 (let ((org-clock-clocking-in t))
943 (org-resolve-clocks))) ; check if any clocks are dangling
944 (when (equal select '(4))
945 (setq selected-task (org-clock-select-task "Clock-in on task: "))
946 (if selected-task
947 (setq selected-task (copy-marker selected-task))
948 (error "Abort")))
949 (when interrupting
950 ;; We are interrupting the clocking of a different task.
951 ;; Save a marker to this task, so that we can go back.
952 ;; First check if we are trying to clock into the same task!
953 (if (save-excursion
954 (unless selected-task
955 (org-back-to-heading t))
956 (and (equal (marker-buffer org-clock-hd-marker)
957 (if selected-task
958 (marker-buffer selected-task)
959 (current-buffer)))
960 (= (marker-position org-clock-hd-marker)
961 (if selected-task
962 (marker-position selected-task)
963 (point)))))
964 (message "Clock continues in \"%s\"" org-clock-heading)
965 (progn
966 (move-marker org-clock-interrupted-task
967 (marker-position org-clock-marker)
968 (org-clocking-buffer))
969 (let ((org-clock-clocking-in t))
970 (org-clock-out t)))))
972 (when (equal select '(16))
973 ;; Mark as default clocking task
974 (org-clock-mark-default-task))
976 ;; Clock in at which position?
977 (setq target-pos
978 (if (and (eobp) (not (org-on-heading-p)))
979 (point-at-bol 0)
980 (point)))
981 (run-hooks 'org-clock-in-prepare-hook)
982 (save-excursion
983 (when (and selected-task (marker-buffer selected-task))
984 ;; There is a selected task, move to the correct buffer
985 ;; and set the new target position.
986 (set-buffer (org-base-buffer (marker-buffer selected-task)))
987 (setq target-pos (marker-position selected-task))
988 (move-marker selected-task nil))
989 (save-excursion
990 (save-restriction
991 (widen)
992 (goto-char target-pos)
993 (org-back-to-heading t)
994 (or interrupting (move-marker org-clock-interrupted-task nil))
995 (org-clock-history-push)
996 (org-clock-set-current)
997 (cond ((functionp org-clock-in-switch-to-state)
998 (looking-at org-complex-heading-regexp)
999 (let ((newstate (funcall org-clock-in-switch-to-state
1000 (match-string 2))))
1001 (if newstate (org-todo newstate))))
1002 ((and org-clock-in-switch-to-state
1003 (not (looking-at (concat outline-regexp "[ \t]*"
1004 org-clock-in-switch-to-state
1005 "\\>"))))
1006 (org-todo org-clock-in-switch-to-state)))
1007 (setq org-clock-heading-for-remember
1008 (and (looking-at org-complex-heading-regexp)
1009 (match-end 4)
1010 (org-trim (buffer-substring (match-end 1)
1011 (match-end 4)))))
1012 (setq org-clock-heading
1013 (cond ((and org-clock-heading-function
1014 (functionp org-clock-heading-function))
1015 (funcall org-clock-heading-function))
1016 ((looking-at org-complex-heading-regexp)
1017 (replace-regexp-in-string
1018 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1019 (match-string 4)))
1020 (t "???")))
1021 (setq org-clock-heading (org-propertize org-clock-heading
1022 'face nil))
1023 (org-clock-find-position org-clock-in-resume)
1024 (cond
1025 ((and org-clock-in-resume
1026 (looking-at
1027 (concat "^[ \t]* " org-clock-string
1028 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1029 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1030 (message "Matched %s" (match-string 1))
1031 (setq ts (concat "[" (match-string 1) "]"))
1032 (goto-char (match-end 1))
1033 (setq org-clock-start-time
1034 (apply 'encode-time
1035 (org-parse-time-string (match-string 1))))
1036 (setq org-clock-effort (org-get-effort))
1037 (setq org-clock-total-time (org-clock-sum-current-item
1038 (org-clock-get-sum-start))))
1039 ((eq org-clock-in-resume 'auto-restart)
1040 ;; called from org-clock-load during startup,
1041 ;; do not interrupt, but warn!
1042 (message "Cannot restart clock because task does not contain unfinished clock")
1043 (ding)
1044 (sit-for 2)
1045 (throw 'abort nil))
1047 (insert-before-markers "\n")
1048 (backward-char 1)
1049 (org-indent-line-function)
1050 (when (and (save-excursion
1051 (end-of-line 0)
1052 (org-in-item-p)))
1053 (beginning-of-line 1)
1054 (org-indent-line-to (- (org-get-indentation) 2)))
1055 (insert org-clock-string " ")
1056 (setq org-clock-effort (org-get-effort))
1057 (setq org-clock-total-time (org-clock-sum-current-item
1058 (org-clock-get-sum-start)))
1059 (setq org-clock-start-time
1060 (or (and leftover
1061 (y-or-n-p
1062 (format
1063 "You stopped another clock %d mins ago; start this one from then? "
1064 (/ (- (org-float-time (current-time))
1065 (org-float-time leftover)) 60)))
1066 leftover)
1067 start-time
1068 (current-time)))
1069 (setq ts (org-insert-time-stamp org-clock-start-time
1070 'with-hm 'inactive))))
1071 (move-marker org-clock-marker (point) (buffer-base-buffer))
1072 (move-marker org-clock-hd-marker
1073 (save-excursion (org-back-to-heading t) (point))
1074 (buffer-base-buffer))
1075 (setq org-clock-has-been-used t)
1076 (or global-mode-string (setq global-mode-string '("")))
1077 (or (memq 'org-mode-line-string global-mode-string)
1078 (setq global-mode-string
1079 (append global-mode-string '(org-mode-line-string))))
1080 (org-clock-update-mode-line)
1081 (when org-clock-mode-line-timer
1082 (cancel-timer org-clock-mode-line-timer)
1083 (setq org-clock-mode-line-timer nil))
1084 (setq org-clock-mode-line-timer
1085 (run-with-timer org-clock-update-period
1086 org-clock-update-period
1087 'org-clock-update-mode-line))
1088 (when org-clock-idle-timer
1089 (cancel-timer org-clock-idle-timer)
1090 (setq org-clock-idle-timer nil))
1091 (setq org-clock-idle-timer
1092 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1093 (message "Clock starts at %s - %s" ts msg-extra)
1094 (run-hooks 'org-clock-in-hook)))))))
1096 (defvar org-clock-current-task nil
1097 "Task currently clocked in.")
1098 (defun org-clock-set-current ()
1099 "Set `org-clock-current-task' to the task currently clocked in."
1100 (setq org-clock-current-task (nth 4 (org-heading-components))))
1101 (defun org-clock-delete-current ()
1102 "Reset `org-clock-current-task' to nil."
1103 (setq org-clock-current-task nil))
1105 (defun org-clock-mark-default-task ()
1106 "Mark current task as default task."
1107 (interactive)
1108 (save-excursion
1109 (org-back-to-heading t)
1110 (move-marker org-clock-default-task (point))))
1112 (defvar msg-extra)
1113 (defun org-clock-get-sum-start ()
1114 "Return the time from which clock times should be counted.
1115 This is for the currently running clock as it is displayed
1116 in the mode line. This function looks at the properties
1117 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1118 corresponding variable `org-clock-modeline-total' and then
1119 decides which time to use."
1120 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1121 (symbol-name org-clock-modeline-total)))
1122 (lr (org-entry-get nil "LAST_REPEAT")))
1123 (cond
1124 ((equal cmt "current")
1125 (setq msg-extra "showing time in current clock instance")
1126 (current-time))
1127 ((equal cmt "today")
1128 (setq msg-extra "showing today's task time.")
1129 (let* ((dt (decode-time (current-time))))
1130 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1131 (if org-extend-today-until
1132 (setf (nth 2 dt) org-extend-today-until))
1133 (apply 'encode-time dt)))
1134 ((or (equal cmt "all")
1135 (and (or (not cmt) (equal cmt "auto"))
1136 (not lr)))
1137 (setq msg-extra "showing entire task time.")
1138 nil)
1139 ((or (equal cmt "repeat")
1140 (and (or (not cmt) (equal cmt "auto"))
1141 lr))
1142 (setq msg-extra "showing task time since last repeat.")
1143 (if (not lr)
1145 (org-time-string-to-time lr)))
1146 (t nil))))
1148 (defun org-clock-find-position (find-unclosed)
1149 "Find the location where the next clock line should be inserted.
1150 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1151 line and position cursor in that line."
1152 (org-back-to-heading t)
1153 (catch 'exit
1154 (let ((beg (save-excursion
1155 (beginning-of-line 2)
1156 (or (bolp) (newline))
1157 (point)))
1158 (end (progn (outline-next-heading) (point)))
1159 (re (concat "^[ \t]*" org-clock-string))
1160 (cnt 0)
1161 (drawer (if (stringp org-clock-into-drawer)
1162 org-clock-into-drawer "LOGBOOK"))
1163 first last ind-last)
1164 (goto-char beg)
1165 (when (and find-unclosed
1166 (re-search-forward
1167 (concat "^[ \t]* " org-clock-string
1168 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1169 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1170 end t))
1171 (beginning-of-line 1)
1172 (throw 'exit t))
1173 (when (eobp) (newline) (setq end (max (point) end)))
1174 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1175 ;; we seem to have a CLOCK drawer, so go there.
1176 (beginning-of-line 2)
1177 (or org-log-states-order-reversed
1178 (and (re-search-forward org-property-end-re nil t)
1179 (goto-char (match-beginning 0))))
1180 (throw 'exit t))
1181 ;; Lets count the CLOCK lines
1182 (goto-char beg)
1183 (while (re-search-forward re end t)
1184 (setq first (or first (match-beginning 0))
1185 last (match-beginning 0)
1186 cnt (1+ cnt)))
1187 (when (and (integerp org-clock-into-drawer)
1188 last
1189 (>= (1+ cnt) org-clock-into-drawer))
1190 ;; Wrap current entries into a new drawer
1191 (goto-char last)
1192 (setq ind-last (org-get-indentation))
1193 (beginning-of-line 2)
1194 (if (and (>= (org-get-indentation) ind-last)
1195 (org-at-item-p))
1196 (org-end-of-item))
1197 (insert ":END:\n")
1198 (beginning-of-line 0)
1199 (org-indent-line-to ind-last)
1200 (goto-char first)
1201 (insert ":" drawer ":\n")
1202 (beginning-of-line 0)
1203 (org-indent-line-function)
1204 (org-flag-drawer t)
1205 (beginning-of-line 2)
1206 (or org-log-states-order-reversed
1207 (and (re-search-forward org-property-end-re nil t)
1208 (goto-char (match-beginning 0))))
1209 (throw 'exit nil))
1211 (goto-char beg)
1212 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1213 (not (equal (match-string 1) org-clock-string)))
1214 ;; Planning info, skip to after it
1215 (beginning-of-line 2)
1216 (or (bolp) (newline)))
1217 (when (or (eq org-clock-into-drawer t)
1218 (stringp org-clock-into-drawer)
1219 (and (integerp org-clock-into-drawer)
1220 (< org-clock-into-drawer 2)))
1221 (insert ":" drawer ":\n:END:\n")
1222 (beginning-of-line -1)
1223 (org-indent-line-function)
1224 (org-flag-drawer t)
1225 (beginning-of-line 2)
1226 (org-indent-line-function)
1227 (beginning-of-line)
1228 (or org-log-states-order-reversed
1229 (and (re-search-forward org-property-end-re nil t)
1230 (goto-char (match-beginning 0))))))))
1232 (defun org-clock-out (&optional fail-quietly at-time)
1233 "Stop the currently running clock.
1234 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1235 (interactive)
1236 (catch 'exit
1237 (when (not (org-clocking-p))
1238 (setq global-mode-string
1239 (delq 'org-mode-line-string global-mode-string))
1240 (force-mode-line-update)
1241 (if fail-quietly (throw 'exit t) (error "No active clock")))
1242 (let (ts te s h m remove)
1243 (save-excursion ; Do not replace this with `with-current-buffer'.
1244 (with-no-warnings (set-buffer (org-clocking-buffer)))
1245 (save-restriction
1246 (widen)
1247 (goto-char org-clock-marker)
1248 (beginning-of-line 1)
1249 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1250 (equal (match-string 1) org-clock-string))
1251 (setq ts (match-string 2))
1252 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1253 (goto-char (match-end 0))
1254 (delete-region (point) (point-at-eol))
1255 (insert "--")
1256 (setq te (org-insert-time-stamp (or at-time (current-time))
1257 'with-hm 'inactive))
1258 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1259 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1260 h (floor (/ s 3600))
1261 s (- s (* 3600 h))
1262 m (floor (/ s 60))
1263 s (- s (* 60 s)))
1264 (insert " => " (format "%2d:%02d" h m))
1265 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1266 (= (+ h m) 0)))
1267 (beginning-of-line 1)
1268 (delete-region (point) (point-at-eol))
1269 (and (looking-at "\n") (> (point-max) (1+ (point)))
1270 (delete-char 1)))
1271 (move-marker org-clock-marker nil)
1272 (move-marker org-clock-hd-marker nil)
1273 (when org-log-note-clock-out
1274 (org-add-log-setup 'clock-out nil nil nil nil
1275 (concat "# Task: " (org-get-heading t) "\n\n")))
1276 (when org-clock-mode-line-timer
1277 (cancel-timer org-clock-mode-line-timer)
1278 (setq org-clock-mode-line-timer nil))
1279 (when org-clock-idle-timer
1280 (cancel-timer org-clock-idle-timer)
1281 (setq org-clock-idle-timer nil))
1282 (setq global-mode-string
1283 (delq 'org-mode-line-string global-mode-string))
1284 (when org-clock-out-switch-to-state
1285 (save-excursion
1286 (org-back-to-heading t)
1287 (let ((org-inhibit-logging t)
1288 (org-clock-out-when-done nil))
1289 (cond
1290 ((functionp org-clock-out-switch-to-state)
1291 (looking-at org-complex-heading-regexp)
1292 (let ((newstate (funcall org-clock-out-switch-to-state
1293 (match-string 2))))
1294 (if newstate (org-todo newstate))))
1295 ((and org-clock-out-switch-to-state
1296 (not (looking-at (concat outline-regexp "[ \t]*"
1297 org-clock-out-switch-to-state
1298 "\\>"))))
1299 (org-todo org-clock-out-switch-to-state))))))
1300 (force-mode-line-update)
1301 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1302 (if remove " => LINE REMOVED" ""))
1303 (run-hooks 'org-clock-out-hook)
1304 (org-clock-delete-current))))))
1306 (defun org-clock-cancel ()
1307 "Cancel the running clock by removing the start timestamp."
1308 (interactive)
1309 (when (not (org-clocking-p))
1310 (setq global-mode-string
1311 (delq 'org-mode-line-string global-mode-string))
1312 (force-mode-line-update)
1313 (error "No active clock"))
1314 (save-excursion ; Do not replace this with `with-current-buffer'.
1315 (with-no-warnings (set-buffer (org-clocking-buffer)))
1316 (goto-char org-clock-marker)
1317 (delete-region (1- (point-at-bol)) (point-at-eol))
1318 ;; Just in case, remove any empty LOGBOOK left over
1319 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1320 (move-marker org-clock-marker nil)
1321 (move-marker org-clock-hd-marker nil)
1322 (setq global-mode-string
1323 (delq 'org-mode-line-string global-mode-string))
1324 (force-mode-line-update)
1325 (message "Clock canceled")
1326 (run-hooks 'org-clock-cancel-hook))
1328 (defun org-clock-goto (&optional select)
1329 "Go to the currently clocked-in entry, or to the most recently clocked one.
1330 With prefix arg SELECT, offer recently clocked tasks for selection."
1331 (interactive "@P")
1332 (let* ((recent nil)
1333 (m (cond
1334 (select
1335 (or (org-clock-select-task "Select task to go to: ")
1336 (error "No task selected")))
1337 ((org-clocking-p) org-clock-marker)
1338 ((and org-clock-goto-may-find-recent-task
1339 (car org-clock-history)
1340 (marker-buffer (car org-clock-history)))
1341 (setq recent t)
1342 (car org-clock-history))
1343 (t (error "No active or recent clock task")))))
1344 (switch-to-buffer (marker-buffer m))
1345 (if (or (< m (point-min)) (> m (point-max))) (widen))
1346 (goto-char m)
1347 (org-show-entry)
1348 (org-back-to-heading t)
1349 (org-cycle-hide-drawers 'children)
1350 (recenter)
1351 (org-reveal)
1352 (if recent
1353 (message "No running clock, this is the most recently clocked task"))
1354 (run-hooks 'org-clock-goto-hook)))
1356 (defvar org-clock-file-total-minutes nil
1357 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1358 (make-variable-buffer-local 'org-clock-file-total-minutes)
1360 (defun org-clock-sum (&optional tstart tend headline-filter)
1361 "Sum the times for each subtree.
1362 Puts the resulting times in minutes as a text property on each headline.
1363 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1364 zero-arg function that, if specified, is called for each headline in the time
1365 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1366 nil are excluded from the clock summation."
1367 (interactive)
1368 (let* ((bmp (buffer-modified-p))
1369 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1370 org-clock-string
1371 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1372 (lmax 30)
1373 (ltimes (make-vector lmax 0))
1374 (t1 0)
1375 (level 0)
1376 ts te dt
1377 time)
1378 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1379 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1380 (if (consp tstart) (setq tstart (org-float-time tstart)))
1381 (if (consp tend) (setq tend (org-float-time tend)))
1382 (remove-text-properties (point-min) (point-max)
1383 '(:org-clock-minutes t
1384 :org-clock-force-headline-inclusion t))
1385 (save-excursion
1386 (goto-char (point-max))
1387 (while (re-search-backward re nil t)
1388 (cond
1389 ((match-end 2)
1390 ;; Two time stamps
1391 (setq ts (match-string 2)
1392 te (match-string 3)
1393 ts (org-float-time
1394 (apply 'encode-time (org-parse-time-string ts)))
1395 te (org-float-time
1396 (apply 'encode-time (org-parse-time-string te)))
1397 ts (if tstart (max ts tstart) ts)
1398 te (if tend (min te tend) te)
1399 dt (- te ts)
1400 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1401 ((match-end 4)
1402 ;; A naked time
1403 (setq t1 (+ t1 (string-to-number (match-string 5))
1404 (* 60 (string-to-number (match-string 4))))))
1405 (t ;; A headline
1406 ;; Add the currently clocking item time to the total
1407 (when (and org-clock-report-include-clocking-task
1408 (equal (org-clocking-buffer) (current-buffer))
1409 (equal (marker-position org-clock-hd-marker) (point))
1410 tstart
1411 tend
1412 (>= (org-float-time org-clock-start-time) tstart)
1413 (<= (org-float-time org-clock-start-time) tend))
1414 (let ((time (floor (- (org-float-time)
1415 (org-float-time org-clock-start-time)) 60)))
1416 (setq t1 (+ t1 time))))
1417 (let* ((headline-forced
1418 (get-text-property (point)
1419 :org-clock-force-headline-inclusion))
1420 (headline-included
1421 (or (null headline-filter)
1422 (save-excursion
1423 (save-match-data (funcall headline-filter))))))
1424 (setq level (- (match-end 1) (match-beginning 1)))
1425 (when (or (> t1 0) (> (aref ltimes level) 0))
1426 (when (or headline-included headline-forced)
1427 (if headline-included
1428 (loop for l from 0 to level do
1429 (aset ltimes l (+ (aref ltimes l) t1))))
1430 (setq time (aref ltimes level))
1431 (goto-char (match-beginning 0))
1432 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1433 (if headline-filter
1434 (save-excursion
1435 (save-match-data
1436 (while
1437 (> (funcall outline-level) 1)
1438 (outline-up-heading 1 t)
1439 (put-text-property
1440 (point) (point-at-eol)
1441 :org-clock-force-headline-inclusion t))))))
1442 (setq t1 0)
1443 (loop for l from level to (1- lmax) do
1444 (aset ltimes l 0)))))))
1445 (setq org-clock-file-total-minutes (aref ltimes 0)))
1446 (set-buffer-modified-p bmp)))
1448 (defun org-clock-sum-current-item (&optional tstart)
1449 "Return time, clocked on current item in total."
1450 (save-excursion
1451 (save-restriction
1452 (org-narrow-to-subtree)
1453 (org-clock-sum tstart)
1454 org-clock-file-total-minutes)))
1456 (defun org-clock-display (&optional total-only)
1457 "Show subtree times in the entire buffer.
1458 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1459 in the echo area."
1460 (interactive)
1461 (org-clock-remove-overlays)
1462 (let (time h m p)
1463 (org-clock-sum)
1464 (unless total-only
1465 (save-excursion
1466 (goto-char (point-min))
1467 (while (or (and (equal (setq p (point)) (point-min))
1468 (get-text-property p :org-clock-minutes))
1469 (setq p (next-single-property-change
1470 (point) :org-clock-minutes)))
1471 (goto-char p)
1472 (when (setq time (get-text-property p :org-clock-minutes))
1473 (org-clock-put-overlay time (funcall outline-level))))
1474 (setq h (/ org-clock-file-total-minutes 60)
1475 m (- org-clock-file-total-minutes (* 60 h)))
1476 ;; Arrange to remove the overlays upon next change.
1477 (when org-remove-highlights-with-change
1478 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1479 nil 'local))))
1480 (if org-time-clocksum-use-fractional
1481 (message (concat "Total file time: " org-time-clocksum-fractional-format
1482 " (%d hours and %d minutes)")
1483 (/ (+ (* h 60.0) m) 60.0) h m)
1484 (message (concat "Total file time: " org-time-clocksum-format
1485 " (%d hours and %d minutes)") h m h m))))
1487 (defvar org-clock-overlays nil)
1488 (make-variable-buffer-local 'org-clock-overlays)
1490 (defun org-clock-put-overlay (time &optional level)
1491 "Put an overlays on the current line, displaying TIME.
1492 If LEVEL is given, prefix time with a corresponding number of stars.
1493 This creates a new overlay and stores it in `org-clock-overlays', so that it
1494 will be easy to remove."
1495 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1496 (l (if level (org-get-valid-level level 0) 0))
1497 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1498 org-time-clocksum-fractional-format
1499 org-time-clocksum-format) "%s"))
1500 (off 0)
1501 ov tx)
1502 (org-move-to-column c)
1503 (unless (eolp) (skip-chars-backward "^ \t"))
1504 (skip-chars-backward " \t")
1505 (setq ov (make-overlay (1- (point)) (point-at-eol))
1506 tx (concat (buffer-substring (1- (point)) (point))
1507 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1508 (org-add-props (if org-time-clocksum-use-fractional
1509 (format fmt
1510 (make-string l ?*)
1511 (/ (+ (* h 60.0) m) 60.0)
1512 (make-string (- 16 l) ?\ ))
1513 (format fmt
1514 (make-string l ?*) h m
1515 (make-string (- 16 l) ?\ )))
1516 (list 'face 'org-clock-overlay))
1517 ""))
1518 (if (not (featurep 'xemacs))
1519 (overlay-put ov 'display tx)
1520 (overlay-put ov 'invisible t)
1521 (overlay-put ov 'end-glyph (make-glyph tx)))
1522 (push ov org-clock-overlays)))
1524 (defun org-clock-remove-overlays (&optional beg end noremove)
1525 "Remove the occur highlights from the buffer.
1526 BEG and END are ignored. If NOREMOVE is nil, remove this function
1527 from the `before-change-functions' in the current buffer."
1528 (interactive)
1529 (unless org-inhibit-highlight-removal
1530 (mapc 'delete-overlay org-clock-overlays)
1531 (setq org-clock-overlays nil)
1532 (unless noremove
1533 (remove-hook 'before-change-functions
1534 'org-clock-remove-overlays 'local))))
1536 (defvar state) ;; dynamically scoped into this function
1537 (defun org-clock-out-if-current ()
1538 "Clock out if the current entry contains the running clock.
1539 This is used to stop the clock after a TODO entry is marked DONE,
1540 and is only done if the variable `org-clock-out-when-done' is not nil."
1541 (when (and org-clock-out-when-done
1542 (or (and (eq t org-clock-out-when-done)
1543 (member state org-done-keywords))
1544 (and (listp org-clock-out-when-done)
1545 (member state org-clock-out-when-done)))
1546 (equal (or (buffer-base-buffer (org-clocking-buffer))
1547 (org-clocking-buffer))
1548 (or (buffer-base-buffer (current-buffer))
1549 (current-buffer)))
1550 (< (point) org-clock-marker)
1551 (> (save-excursion (outline-next-heading) (point))
1552 org-clock-marker))
1553 ;; Clock out, but don't accept a logging message for this.
1554 (let ((org-log-note-clock-out nil)
1555 (org-clock-out-switch-to-state nil))
1556 (org-clock-out))))
1558 (add-hook 'org-after-todo-state-change-hook
1559 'org-clock-out-if-current)
1561 ;;;###autoload
1562 (defun org-get-clocktable (&rest props)
1563 "Get a formatted clocktable with parameters according to PROPS.
1564 The table is created in a temporary buffer, fully formatted and
1565 fontified, and then returned."
1566 ;; Set the defaults
1567 (setq props (plist-put props :name "clocktable"))
1568 (unless (plist-member props :maxlevel)
1569 (setq props (plist-put props :maxlevel 2)))
1570 (unless (plist-member props :scope)
1571 (setq props (plist-put props :scope 'agenda)))
1572 (with-temp-buffer
1573 (org-mode)
1574 (org-create-dblock props)
1575 (org-update-dblock)
1576 (font-lock-fontify-buffer)
1577 (forward-line 2)
1578 (buffer-substring (point) (progn
1579 (re-search-forward "^#\\+END" nil t)
1580 (point-at-bol)))))
1582 (defun org-clock-report (&optional arg)
1583 "Create a table containing a report about clocked time.
1584 If the cursor is inside an existing clocktable block, then the table
1585 will be updated. If not, a new clocktable will be inserted.
1586 When called with a prefix argument, move to the first clock table in the
1587 buffer and update it."
1588 (interactive "P")
1589 (org-clock-remove-overlays)
1590 (when arg
1591 (org-find-dblock "clocktable")
1592 (org-show-entry))
1593 (if (org-in-clocktable-p)
1594 (goto-char (org-in-clocktable-p))
1595 (org-create-dblock (append (list :name "clocktable")
1596 org-clock-clocktable-default-properties)))
1597 (org-update-dblock))
1599 (defun org-in-clocktable-p ()
1600 "Check if the cursor is in a clocktable."
1601 (let ((pos (point)) start)
1602 (save-excursion
1603 (end-of-line 1)
1604 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
1605 (setq start (match-beginning 0))
1606 (re-search-forward "^#\\+END:.*" nil t)
1607 (>= (match-end 0) pos)
1608 start))))
1610 (defun org-clock-special-range (key &optional time as-strings)
1611 "Return two times bordering a special time range.
1612 Key is a symbol specifying the range and can be one of `today', `yesterday',
1613 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1614 A week starts Monday 0:00 and ends Sunday 24:00.
1615 The range is determined relative to TIME. TIME defaults to the current time.
1616 The return value is a cons cell with two internal times like the ones
1617 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1618 the returned times will be formatted strings."
1619 (if (integerp key) (setq key (intern (number-to-string key))))
1620 (let* ((tm (decode-time (or time (current-time))))
1621 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1622 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1623 (dow (nth 6 tm))
1624 (skey (symbol-name key))
1625 (shift 0)
1626 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
1627 (cond
1628 ((string-match "^[0-9]+$" skey)
1629 (setq y (string-to-number skey) m 1 d 1 key 'year))
1630 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1631 (setq y (string-to-number (match-string 1 skey))
1632 month (string-to-number (match-string 2 skey))
1633 d 1 key 'month))
1634 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1635 (require 'cal-iso)
1636 (setq y (string-to-number (match-string 1 skey))
1637 w (string-to-number (match-string 2 skey)))
1638 (setq date (calendar-gregorian-from-absolute
1639 (calendar-absolute-from-iso (list w 1 y))))
1640 (setq d (nth 1 date) month (car date) y (nth 2 date)
1641 dow 1
1642 key 'week))
1643 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1644 (setq y (string-to-number (match-string 1 skey))
1645 month (string-to-number (match-string 2 skey))
1646 d (string-to-number (match-string 3 skey))
1647 key 'day))
1648 ((string-match "\\([-+][0-9]+\\)$" skey)
1649 (setq shift (string-to-number (match-string 1 skey))
1650 key (intern (substring skey 0 (match-beginning 1))))))
1651 (when (= shift 0)
1652 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1653 ((eq key 'lastweek) (setq key 'week shift -1))
1654 ((eq key 'lastmonth) (setq key 'month shift -1))
1655 ((eq key 'lastyear) (setq key 'year shift -1))))
1656 (cond
1657 ((memq key '(day today))
1658 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1659 ((memq key '(week thisweek))
1660 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1661 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1662 ((memq key '(month thismonth))
1663 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1664 ((memq key '(year thisyear))
1665 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1666 (t (error "No such time block %s" key)))
1667 (setq ts (encode-time s m h d month y)
1668 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1669 (or d1 d) (or month1 month) (or y1 y)))
1670 (setq fm (cdr org-time-stamp-formats))
1671 (cond
1672 ((memq key '(day today))
1673 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1674 ((memq key '(week thisweek))
1675 (setq txt (format-time-string "week %G-W%V" ts)))
1676 ((memq key '(month thismonth))
1677 (setq txt (format-time-string "%B %Y" ts)))
1678 ((memq key '(year thisyear))
1679 (setq txt (format-time-string "the year %Y" ts))))
1680 (if as-strings
1681 (list (format-time-string fm ts) (format-time-string fm te) txt)
1682 (list ts te txt))))
1684 (defun org-clocktable-shift (dir n)
1685 "Try to shift the :block date of the clocktable at point.
1686 Point must be in the #+BEGIN: line of a clocktable, or this function
1687 will throw an error.
1688 DIR is a direction, a symbol `left', `right', `up', or `down'.
1689 Both `left' and `down' shift the block toward the past, `up' and `right'
1690 push it toward the future.
1691 N is the number of shift steps to take. The size of the step depends on
1692 the currently selected interval size."
1693 (setq n (prefix-numeric-value n))
1694 (and (memq dir '(left down)) (setq n (- n)))
1695 (save-excursion
1696 (goto-char (point-at-bol))
1697 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1698 (error "Line needs a :block definition before this command works")
1699 (let* ((b (match-beginning 1)) (e (match-end 1))
1700 (s (match-string 1))
1701 block shift ins y mw d date wp m)
1702 (cond
1703 ((equal s "yesterday") (setq s "today-1"))
1704 ((equal s "lastweek") (setq s "thisweek-1"))
1705 ((equal s "lastmonth") (setq s "thismonth-1"))
1706 ((equal s "lastyear") (setq s "thisyear-1")))
1707 (cond
1708 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
1709 (setq block (match-string 1 s)
1710 shift (if (match-end 2)
1711 (string-to-number (match-string 2 s))
1713 (setq shift (+ shift n))
1714 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1715 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1716 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1717 (setq y (string-to-number (match-string 1 s))
1718 wp (and (match-end 3) (match-string 3 s))
1719 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1720 d (and (match-end 6) (string-to-number (match-string 6 s))))
1721 (cond
1722 (d (setq ins (format-time-string
1723 "%Y-%m-%d"
1724 (encode-time 0 0 0 (+ d n) m y))))
1725 ((and wp mw (> (length wp) 0))
1726 (require 'cal-iso)
1727 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1728 (setq ins (format-time-string
1729 "%G-W%V"
1730 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1732 (setq ins (format-time-string
1733 "%Y-%m"
1734 (encode-time 0 0 0 1 (+ mw n) y))))
1736 (setq ins (number-to-string (+ y n))))))
1737 (t (error "Cannot shift clocktable block")))
1738 (when ins
1739 (goto-char b)
1740 (insert ins)
1741 (delete-region (point) (+ (point) (- e b)))
1742 (beginning-of-line 1)
1743 (org-update-dblock)
1744 t)))))
1746 (defun org-dblock-write:clocktable (params)
1747 "Write the standard clocktable."
1748 (catch 'exit
1749 (let* ((hlchars '((1 . "*") (2 . "/")))
1750 (ins (make-marker))
1751 (total-time nil)
1752 (scope (plist-get params :scope))
1753 (tostring (plist-get params :tostring))
1754 (multifile (plist-get params :multifile))
1755 (header (plist-get params :header))
1756 (maxlevel (or (plist-get params :maxlevel) 3))
1757 (step (plist-get params :step))
1758 (emph (plist-get params :emphasize))
1759 (timestamp (plist-get params :timestamp))
1760 (ts (plist-get params :tstart))
1761 (te (plist-get params :tend))
1762 (block (plist-get params :block))
1763 (link (plist-get params :link))
1764 (tags (plist-get params :tags))
1765 (matcher (if tags (cdr (org-make-tags-matcher tags))))
1766 ipos time p level hlc hdl tsp props content recalc formula pcol
1767 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
1768 (setq org-clock-file-total-minutes nil)
1769 (when step
1770 (unless (or block (and ts te))
1771 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1772 (org-clocktable-steps params)
1773 (throw 'exit nil))
1774 (when block
1775 (setq cc (org-clock-special-range block nil t)
1776 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1777 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
1778 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
1779 (when (and ts (listp ts))
1780 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
1781 (when (and te (listp te))
1782 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
1783 ;; Now the times are strings we can parse.
1784 (if ts (setq ts (org-float-time
1785 (apply 'encode-time (org-parse-time-string ts)))))
1786 (if te (setq te (org-float-time
1787 (apply 'encode-time (org-parse-time-string te)))))
1788 (move-marker ins (point))
1789 (setq ipos (point))
1791 ;; Get the right scope
1792 (setq pos (point))
1793 (cond
1794 ((and scope (listp scope) (symbolp (car scope)))
1795 (setq scope (eval scope)))
1796 ((eq scope 'agenda)
1797 (setq scope (org-agenda-files t)))
1798 ((eq scope 'agenda-with-archives)
1799 (setq scope (org-agenda-files t))
1800 (setq scope (org-add-archive-files scope)))
1801 ((eq scope 'file-with-archives)
1802 (setq scope (org-add-archive-files (list (buffer-file-name)))
1803 rm-file-column t)))
1804 (setq scope-is-list (and scope (listp scope)))
1805 (save-restriction
1806 (cond
1807 ((not scope))
1808 ((eq scope 'file) (widen))
1809 ((eq scope 'subtree) (org-narrow-to-subtree))
1810 ((eq scope 'tree)
1811 (while (org-up-heading-safe))
1812 (org-narrow-to-subtree))
1813 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1814 (symbol-name scope)))
1815 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1816 (catch 'exit
1817 (while (org-up-heading-safe)
1818 (looking-at outline-regexp)
1819 (if (<= (org-reduced-level (funcall outline-level)) level)
1820 (throw 'exit nil))))
1821 (org-narrow-to-subtree))
1822 (scope-is-list
1823 (let* ((files scope)
1824 (scope 'agenda)
1825 (p1 (copy-sequence params))
1826 file)
1827 (setq p1 (plist-put p1 :tostring t))
1828 (setq p1 (plist-put p1 :multifile t))
1829 (setq p1 (plist-put p1 :scope 'file))
1830 (org-prepare-agenda-buffers files)
1831 (while (setq file (pop files))
1832 (with-current-buffer (find-buffer-visiting file)
1833 (setq tbl1 (org-dblock-write:clocktable p1))
1834 (when tbl1
1835 (push (org-clocktable-add-file
1836 file
1837 (concat "| |*File time*|*"
1838 (org-minutes-to-hh:mm-string
1839 org-clock-file-total-minutes)
1840 "*|\n"
1841 tbl1)) tbl)
1842 (setq total-time (+ (or total-time 0)
1843 org-clock-file-total-minutes))))))))
1844 (goto-char pos)
1846 (unless scope-is-list
1847 (org-clock-sum ts te
1848 (unless (null matcher)
1849 (lambda ()
1850 (let ((tags-list
1851 (org-split-string
1852 (or (org-entry-get (point) "ALLTAGS") "")
1853 ":")))
1854 (eval matcher)))))
1855 (goto-char (point-min))
1856 (setq st t)
1857 (while (or (and (bobp) (prog1 st (setq st nil))
1858 (get-text-property (point) :org-clock-minutes)
1859 (setq p (point-min)))
1860 (setq p (next-single-property-change (point) :org-clock-minutes)))
1861 (goto-char p)
1862 (when (setq time (get-text-property p :org-clock-minutes))
1863 (save-excursion
1864 (beginning-of-line 1)
1865 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1866 (setq level (org-reduced-level
1867 (- (match-end 1) (match-beginning 1))))
1868 (<= level maxlevel))
1869 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
1870 hdl (if (not link)
1871 (match-string 2)
1872 (org-make-link-string
1873 (format "file:%s::%s"
1874 (buffer-file-name)
1875 (save-match-data
1876 (org-make-org-heading-search-string
1877 (match-string 2))))
1878 (match-string 2)))
1879 tsp (when timestamp
1880 (setq props (org-entry-properties (point)))
1881 (or (cdr (assoc "SCHEDULED" props))
1882 (cdr (assoc "TIMESTAMP" props))
1883 (cdr (assoc "DEADLINE" props))
1884 (cdr (assoc "TIMESTAMP_IA" props)))))
1885 (if (and (not multifile) (= level 1)) (push "|-" tbl))
1886 (push (concat
1887 "| " (int-to-string level) "|"
1888 (if timestamp (concat tsp "|") "")
1889 hlc hdl hlc " |"
1890 (make-string (1- level) ?|)
1891 hlc (org-minutes-to-hh:mm-string time) hlc
1892 " |") tbl))))))
1893 (setq tbl (nreverse tbl))
1894 (if tostring
1895 (if tbl (mapconcat 'identity tbl "\n") nil)
1896 (goto-char ins)
1897 (insert-before-markers
1898 (or header
1899 (concat
1900 "Clock summary at ["
1901 (substring
1902 (format-time-string (cdr org-time-stamp-formats))
1903 1 -1)
1905 (if block (concat ", for " range-text ".") "")
1906 "\n\n"))
1907 (if scope-is-list "|File" "")
1908 "|L|" (if timestamp "Timestamp|" "") "Headline|Time|\n")
1909 (setq total-time (or total-time org-clock-file-total-minutes))
1910 (insert-before-markers
1911 "|-\n|"
1912 (if scope-is-list "|" "")
1913 (if timestamp "|Timestamp|" "|")
1914 "*Total time*| *"
1915 (org-minutes-to-hh:mm-string (or total-time 0))
1916 "*|\n|-\n")
1917 (setq tbl (delq nil tbl))
1918 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
1919 (equal (substring (car tbl) 0 2) "|-"))
1920 (pop tbl))
1921 (insert-before-markers (mapconcat
1922 'identity (delq nil tbl)
1923 (if scope-is-list "\n|-\n" "\n")))
1924 (backward-delete-char 1)
1925 (if (setq formula (plist-get params :formula))
1926 (cond
1927 ((eq formula '%)
1928 (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
1929 (insert
1930 (format
1931 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1932 pcol
1934 (+ 3 (if scope-is-list 1 0))
1935 (+ (if scope-is-list 1 0) 3)
1936 (1- pcol)))
1937 (setq recalc t))
1938 ((stringp formula)
1939 (insert "\n#+TBLFM: " formula)
1940 (setq recalc t))
1941 (t (error "invalid formula in clocktable")))
1942 ;; Should we rescue an old formula?
1943 (when (stringp (setq content (plist-get params :content)))
1944 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
1945 (setq recalc t)
1946 (insert "\n" (match-string 1 (plist-get params :content)))
1947 (beginning-of-line 0))))
1948 (goto-char ipos)
1949 (skip-chars-forward "^|")
1950 (org-table-align)
1951 (when recalc
1952 (if (eq formula '%)
1953 (save-excursion (org-table-goto-column pcol nil 'force)
1954 (insert "%")))
1955 (org-table-recalculate 'all))
1956 (when rm-file-column
1957 (forward-char 1)
1958 (org-table-delete-column))
1959 total-time)))))
1961 (defun org-clocktable-steps (params)
1962 (let* ((p1 (copy-sequence params))
1963 (ts (plist-get p1 :tstart))
1964 (te (plist-get p1 :tend))
1965 (step0 (plist-get p1 :step))
1966 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
1967 (stepskip0 (plist-get p1 :stepskip0))
1968 (block (plist-get p1 :block))
1969 cc range-text step-time)
1970 (when block
1971 (setq cc (org-clock-special-range block nil t)
1972 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1973 (if ts (setq ts (org-float-time
1974 (apply 'encode-time (org-parse-time-string ts)))))
1975 (if te (setq te (org-float-time
1976 (apply 'encode-time (org-parse-time-string te)))))
1977 (setq p1 (plist-put p1 :header ""))
1978 (setq p1 (plist-put p1 :step nil))
1979 (setq p1 (plist-put p1 :block nil))
1980 (while (< ts te)
1981 (or (bolp) (insert "\n"))
1982 (setq p1 (plist-put p1 :tstart (format-time-string
1983 (org-time-stamp-format nil t)
1984 (seconds-to-time ts))))
1985 (setq p1 (plist-put p1 :tend (format-time-string
1986 (org-time-stamp-format nil t)
1987 (seconds-to-time (setq ts (+ ts step))))))
1988 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
1989 (plist-get p1 :tstart) "\n")
1990 (setq step-time (org-dblock-write:clocktable p1))
1991 (re-search-forward "#\\+END:")
1992 (when (and (equal step-time 0) stepskip0)
1993 ;; Remove the empty table
1994 (delete-region (point-at-bol)
1995 (save-excursion
1996 (re-search-backward "^\\(Daily\\|Weekly\\) report" nil t)
1997 (point))))
1998 (end-of-line 0))))
2000 (defun org-clocktable-add-file (file table)
2001 (if table
2002 (let ((lines (org-split-string table "\n"))
2003 (ff (file-name-nondirectory file)))
2004 (mapconcat 'identity
2005 (mapcar (lambda (x)
2006 (if (string-match org-table-dataline-regexp x)
2007 (concat "|" ff x)
2009 lines)
2010 "\n"))))
2012 (defun org-clock-time% (total &rest strings)
2013 "Compute a time fraction in percent.
2014 TOTAL s a time string like 10:21 specifying the total times.
2015 STRINGS is a list of strings that should be checked for a time.
2016 The first string that does have a time will be used.
2017 This function is made for clock tables."
2018 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2019 tot s)
2020 (save-match-data
2021 (catch 'exit
2022 (if (not (string-match re total))
2023 (throw 'exit 0.)
2024 (setq tot (+ (string-to-number (match-string 2 total))
2025 (* 60 (string-to-number (match-string 1 total)))))
2026 (if (= tot 0.) (throw 'exit 0.)))
2027 (while (setq s (pop strings))
2028 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2029 (throw 'exit
2030 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2031 (* 60 (string-to-number (match-string 1 s)))))
2032 tot))))
2033 0))))
2035 (defvar org-clock-loaded nil
2036 "Was the clock file loaded?")
2038 (defun org-clock-save ()
2039 "Persist various clock-related data to disk.
2040 The details of what will be saved are regulated by the variable
2041 `org-clock-persist'."
2042 (when (and org-clock-persist
2043 (or org-clock-loaded
2044 org-clock-has-been-used
2045 (not (file-exists-p org-clock-persist-file))))
2046 (let (b)
2047 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2048 (progn
2049 (delete-region (point-min) (point-max))
2050 ;;Store clock
2051 (insert (format ";; org-persist.el - %s at %s\n"
2052 system-name (format-time-string
2053 (cdr org-time-stamp-formats))))
2054 (if (and (memq org-clock-persist '(t clock))
2055 (setq b (org-clocking-buffer))
2056 (setq b (or (buffer-base-buffer b) b))
2057 (buffer-live-p b)
2058 (buffer-file-name b)
2059 (or (not org-clock-persist-query-save)
2060 (y-or-n-p (concat "Save current clock ("
2061 (substring-no-properties org-clock-heading)
2062 ") "))))
2063 (insert "(setq resume-clock '(\""
2064 (buffer-file-name (org-clocking-buffer))
2065 "\" . " (int-to-string (marker-position org-clock-marker))
2066 "))\n"))
2067 ;; Store clocked task history. Tasks are stored reversed to make
2068 ;; reading simpler
2069 (when (and (memq org-clock-persist '(t history))
2070 org-clock-history)
2071 (insert
2072 "(setq stored-clock-history '("
2073 (mapconcat
2074 (lambda (m)
2075 (when (and (setq b (marker-buffer m))
2076 (setq b (or (buffer-base-buffer b) b))
2077 (buffer-live-p b)
2078 (buffer-file-name b))
2079 (concat "(\"" (buffer-file-name b)
2080 "\" . " (int-to-string (marker-position m))
2081 ")")))
2082 (reverse org-clock-history) " ") "))\n"))
2083 (save-buffer)
2084 (kill-buffer (current-buffer)))))))
2086 (defun org-clock-load ()
2087 "Load clock-related data from disk, maybe resuming a stored clock."
2088 (when (and org-clock-persist (not org-clock-loaded))
2089 (let ((filename (expand-file-name org-clock-persist-file))
2090 (org-clock-in-resume 'auto-restart)
2091 resume-clock stored-clock-history)
2092 (if (not (file-readable-p filename))
2093 (message "Not restoring clock data; %s not found"
2094 org-clock-persist-file)
2095 (message "%s" "Restoring clock data")
2096 (setq org-clock-loaded t)
2097 (load-file filename)
2098 ;; load history
2099 (when stored-clock-history
2100 (save-window-excursion
2101 (mapc (lambda (task)
2102 (if (file-exists-p (car task))
2103 (org-clock-history-push (cdr task)
2104 (find-file (car task)))))
2105 stored-clock-history)))
2106 ;; resume clock
2107 (when (and resume-clock org-clock-persist
2108 (file-exists-p (car resume-clock))
2109 (or (not org-clock-persist-query-resume)
2110 (y-or-n-p
2111 (concat
2112 "Resume clock ("
2113 (with-current-buffer (find-file (car resume-clock))
2114 (save-excursion
2115 (goto-char (cdr resume-clock))
2116 (org-back-to-heading t)
2117 (and (looking-at org-complex-heading-regexp)
2118 (match-string 4))))
2119 ") "))))
2120 (when (file-exists-p (car resume-clock))
2121 (with-current-buffer (find-file (car resume-clock))
2122 (goto-char (cdr resume-clock))
2123 (let ((org-clock-auto-clock-resolution nil))
2124 (org-clock-in)
2125 (if (org-invisible-p)
2126 (org-show-context))))))))))
2128 ;;;###autoload
2129 (defun org-clock-persistence-insinuate ()
2130 "Set up hooks for clock persistence."
2131 (add-hook 'org-mode-hook 'org-clock-load)
2132 (add-hook 'kill-emacs-hook 'org-clock-save))
2134 ;; Suggested bindings
2135 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2137 (provide 'org-clock)
2139 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2141 ;;; org-clock.el ends here