Bugfix in org-clock-set-current.
[org-mode.git] / lisp / org-clock.el
blob4fa0397aca45b0cb522a8629cf4bff865a3a3f3e
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.01trans
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))))
1102 (defun org-clock-delete-current ()
1103 "Reset `org-clock-current-task' to nil."
1104 (setq org-clock-current-task nil))
1106 (defun org-clock-mark-default-task ()
1107 "Mark current task as default task."
1108 (interactive)
1109 (save-excursion
1110 (org-back-to-heading t)
1111 (move-marker org-clock-default-task (point))))
1113 (defvar msg-extra)
1114 (defun org-clock-get-sum-start ()
1115 "Return the time from which clock times should be counted.
1116 This is for the currently running clock as it is displayed
1117 in the mode line. This function looks at the properties
1118 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1119 corresponding variable `org-clock-modeline-total' and then
1120 decides which time to use."
1121 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1122 (symbol-name org-clock-modeline-total)))
1123 (lr (org-entry-get nil "LAST_REPEAT")))
1124 (cond
1125 ((equal cmt "current")
1126 (setq msg-extra "showing time in current clock instance")
1127 (current-time))
1128 ((equal cmt "today")
1129 (setq msg-extra "showing today's task time.")
1130 (let* ((dt (decode-time (current-time))))
1131 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1132 (if org-extend-today-until
1133 (setf (nth 2 dt) org-extend-today-until))
1134 (apply 'encode-time dt)))
1135 ((or (equal cmt "all")
1136 (and (or (not cmt) (equal cmt "auto"))
1137 (not lr)))
1138 (setq msg-extra "showing entire task time.")
1139 nil)
1140 ((or (equal cmt "repeat")
1141 (and (or (not cmt) (equal cmt "auto"))
1142 lr))
1143 (setq msg-extra "showing task time since last repeat.")
1144 (if (not lr)
1146 (org-time-string-to-time lr)))
1147 (t nil))))
1149 (defun org-clock-find-position (find-unclosed)
1150 "Find the location where the next clock line should be inserted.
1151 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1152 line and position cursor in that line."
1153 (org-back-to-heading t)
1154 (catch 'exit
1155 (let ((beg (save-excursion
1156 (beginning-of-line 2)
1157 (or (bolp) (newline))
1158 (point)))
1159 (end (progn (outline-next-heading) (point)))
1160 (re (concat "^[ \t]*" org-clock-string))
1161 (cnt 0)
1162 (drawer (if (stringp org-clock-into-drawer)
1163 org-clock-into-drawer "LOGBOOK"))
1164 first last ind-last)
1165 (goto-char beg)
1166 (when (and find-unclosed
1167 (re-search-forward
1168 (concat "^[ \t]* " org-clock-string
1169 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1170 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1171 end t))
1172 (beginning-of-line 1)
1173 (throw 'exit t))
1174 (when (eobp) (newline) (setq end (max (point) end)))
1175 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1176 ;; we seem to have a CLOCK drawer, so go there.
1177 (beginning-of-line 2)
1178 (or org-log-states-order-reversed
1179 (and (re-search-forward org-property-end-re nil t)
1180 (goto-char (match-beginning 0))))
1181 (throw 'exit t))
1182 ;; Lets count the CLOCK lines
1183 (goto-char beg)
1184 (while (re-search-forward re end t)
1185 (setq first (or first (match-beginning 0))
1186 last (match-beginning 0)
1187 cnt (1+ cnt)))
1188 (when (and (integerp org-clock-into-drawer)
1189 last
1190 (>= (1+ cnt) org-clock-into-drawer))
1191 ;; Wrap current entries into a new drawer
1192 (goto-char last)
1193 (setq ind-last (org-get-indentation))
1194 (beginning-of-line 2)
1195 (if (and (>= (org-get-indentation) ind-last)
1196 (org-at-item-p))
1197 (org-end-of-item))
1198 (insert ":END:\n")
1199 (beginning-of-line 0)
1200 (org-indent-line-to ind-last)
1201 (goto-char first)
1202 (insert ":" drawer ":\n")
1203 (beginning-of-line 0)
1204 (org-indent-line-function)
1205 (org-flag-drawer t)
1206 (beginning-of-line 2)
1207 (or org-log-states-order-reversed
1208 (and (re-search-forward org-property-end-re nil t)
1209 (goto-char (match-beginning 0))))
1210 (throw 'exit nil))
1212 (goto-char beg)
1213 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1214 (not (equal (match-string 1) org-clock-string)))
1215 ;; Planning info, skip to after it
1216 (beginning-of-line 2)
1217 (or (bolp) (newline)))
1218 (when (or (eq org-clock-into-drawer t)
1219 (stringp org-clock-into-drawer)
1220 (and (integerp org-clock-into-drawer)
1221 (< org-clock-into-drawer 2)))
1222 (insert ":" drawer ":\n:END:\n")
1223 (beginning-of-line -1)
1224 (org-indent-line-function)
1225 (org-flag-drawer t)
1226 (beginning-of-line 2)
1227 (org-indent-line-function)
1228 (beginning-of-line)
1229 (or org-log-states-order-reversed
1230 (and (re-search-forward org-property-end-re nil t)
1231 (goto-char (match-beginning 0))))))))
1233 (defun org-clock-out (&optional fail-quietly at-time)
1234 "Stop the currently running clock.
1235 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1236 (interactive)
1237 (catch 'exit
1238 (when (not (org-clocking-p))
1239 (setq global-mode-string
1240 (delq 'org-mode-line-string global-mode-string))
1241 (force-mode-line-update)
1242 (if fail-quietly (throw 'exit t) (error "No active clock")))
1243 (let (ts te s h m remove)
1244 (save-excursion ; Do not replace this with `with-current-buffer'.
1245 (with-no-warnings (set-buffer (org-clocking-buffer)))
1246 (save-restriction
1247 (widen)
1248 (goto-char org-clock-marker)
1249 (beginning-of-line 1)
1250 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1251 (equal (match-string 1) org-clock-string))
1252 (setq ts (match-string 2))
1253 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1254 (goto-char (match-end 0))
1255 (delete-region (point) (point-at-eol))
1256 (insert "--")
1257 (setq te (org-insert-time-stamp (or at-time (current-time))
1258 'with-hm 'inactive))
1259 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1260 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1261 h (floor (/ s 3600))
1262 s (- s (* 3600 h))
1263 m (floor (/ s 60))
1264 s (- s (* 60 s)))
1265 (insert " => " (format "%2d:%02d" h m))
1266 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1267 (= (+ h m) 0)))
1268 (beginning-of-line 1)
1269 (delete-region (point) (point-at-eol))
1270 (and (looking-at "\n") (> (point-max) (1+ (point)))
1271 (delete-char 1)))
1272 (move-marker org-clock-marker nil)
1273 (move-marker org-clock-hd-marker nil)
1274 (when org-log-note-clock-out
1275 (org-add-log-setup 'clock-out nil nil nil nil
1276 (concat "# Task: " (org-get-heading t) "\n\n")))
1277 (when org-clock-mode-line-timer
1278 (cancel-timer org-clock-mode-line-timer)
1279 (setq org-clock-mode-line-timer nil))
1280 (when org-clock-idle-timer
1281 (cancel-timer org-clock-idle-timer)
1282 (setq org-clock-idle-timer nil))
1283 (setq global-mode-string
1284 (delq 'org-mode-line-string global-mode-string))
1285 (when org-clock-out-switch-to-state
1286 (save-excursion
1287 (org-back-to-heading t)
1288 (let ((org-inhibit-logging t)
1289 (org-clock-out-when-done nil))
1290 (cond
1291 ((functionp org-clock-out-switch-to-state)
1292 (looking-at org-complex-heading-regexp)
1293 (let ((newstate (funcall org-clock-out-switch-to-state
1294 (match-string 2))))
1295 (if newstate (org-todo newstate))))
1296 ((and org-clock-out-switch-to-state
1297 (not (looking-at (concat outline-regexp "[ \t]*"
1298 org-clock-out-switch-to-state
1299 "\\>"))))
1300 (org-todo org-clock-out-switch-to-state))))))
1301 (force-mode-line-update)
1302 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1303 (if remove " => LINE REMOVED" ""))
1304 (run-hooks 'org-clock-out-hook)
1305 (org-clock-delete-current))))))
1307 (defun org-clock-cancel ()
1308 "Cancel the running clock by removing the start timestamp."
1309 (interactive)
1310 (when (not (org-clocking-p))
1311 (setq global-mode-string
1312 (delq 'org-mode-line-string global-mode-string))
1313 (force-mode-line-update)
1314 (error "No active clock"))
1315 (save-excursion ; Do not replace this with `with-current-buffer'.
1316 (with-no-warnings (set-buffer (org-clocking-buffer)))
1317 (goto-char org-clock-marker)
1318 (delete-region (1- (point-at-bol)) (point-at-eol))
1319 ;; Just in case, remove any empty LOGBOOK left over
1320 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1321 (move-marker org-clock-marker nil)
1322 (move-marker org-clock-hd-marker nil)
1323 (setq global-mode-string
1324 (delq 'org-mode-line-string global-mode-string))
1325 (force-mode-line-update)
1326 (message "Clock canceled")
1327 (run-hooks 'org-clock-cancel-hook))
1329 (defun org-clock-goto (&optional select)
1330 "Go to the currently clocked-in entry, or to the most recently clocked one.
1331 With prefix arg SELECT, offer recently clocked tasks for selection."
1332 (interactive "@P")
1333 (let* ((recent nil)
1334 (m (cond
1335 (select
1336 (or (org-clock-select-task "Select task to go to: ")
1337 (error "No task selected")))
1338 ((org-clocking-p) org-clock-marker)
1339 ((and org-clock-goto-may-find-recent-task
1340 (car org-clock-history)
1341 (marker-buffer (car org-clock-history)))
1342 (setq recent t)
1343 (car org-clock-history))
1344 (t (error "No active or recent clock task")))))
1345 (switch-to-buffer (marker-buffer m))
1346 (if (or (< m (point-min)) (> m (point-max))) (widen))
1347 (goto-char m)
1348 (org-show-entry)
1349 (org-back-to-heading t)
1350 (org-cycle-hide-drawers 'children)
1351 (recenter)
1352 (org-reveal)
1353 (if recent
1354 (message "No running clock, this is the most recently clocked task"))
1355 (run-hooks 'org-clock-goto-hook)))
1357 (defvar org-clock-file-total-minutes nil
1358 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1359 (make-variable-buffer-local 'org-clock-file-total-minutes)
1361 (defun org-clock-sum (&optional tstart tend headline-filter)
1362 "Sum the times for each subtree.
1363 Puts the resulting times in minutes as a text property on each headline.
1364 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1365 zero-arg function that, if specified, is called for each headline in the time
1366 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1367 nil are excluded from the clock summation."
1368 (interactive)
1369 (let* ((bmp (buffer-modified-p))
1370 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1371 org-clock-string
1372 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1373 (lmax 30)
1374 (ltimes (make-vector lmax 0))
1375 (t1 0)
1376 (level 0)
1377 ts te dt
1378 time)
1379 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1380 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1381 (if (consp tstart) (setq tstart (org-float-time tstart)))
1382 (if (consp tend) (setq tend (org-float-time tend)))
1383 (remove-text-properties (point-min) (point-max)
1384 '(:org-clock-minutes t
1385 :org-clock-force-headline-inclusion t))
1386 (save-excursion
1387 (goto-char (point-max))
1388 (while (re-search-backward re nil t)
1389 (cond
1390 ((match-end 2)
1391 ;; Two time stamps
1392 (setq ts (match-string 2)
1393 te (match-string 3)
1394 ts (org-float-time
1395 (apply 'encode-time (org-parse-time-string ts)))
1396 te (org-float-time
1397 (apply 'encode-time (org-parse-time-string te)))
1398 ts (if tstart (max ts tstart) ts)
1399 te (if tend (min te tend) te)
1400 dt (- te ts)
1401 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1402 ((match-end 4)
1403 ;; A naked time
1404 (setq t1 (+ t1 (string-to-number (match-string 5))
1405 (* 60 (string-to-number (match-string 4))))))
1406 (t ;; A headline
1407 ;; Add the currently clocking item time to the total
1408 (when (and org-clock-report-include-clocking-task
1409 (equal (org-clocking-buffer) (current-buffer))
1410 (equal (marker-position org-clock-hd-marker) (point))
1411 tstart
1412 tend
1413 (>= (org-float-time org-clock-start-time) tstart)
1414 (<= (org-float-time org-clock-start-time) tend))
1415 (let ((time (floor (- (org-float-time)
1416 (org-float-time org-clock-start-time)) 60)))
1417 (setq t1 (+ t1 time))))
1418 (let* ((headline-forced
1419 (get-text-property (point)
1420 :org-clock-force-headline-inclusion))
1421 (headline-included
1422 (or (null headline-filter)
1423 (save-excursion
1424 (save-match-data (funcall headline-filter))))))
1425 (setq level (- (match-end 1) (match-beginning 1)))
1426 (when (or (> t1 0) (> (aref ltimes level) 0))
1427 (when (or headline-included headline-forced)
1428 (if headline-included
1429 (loop for l from 0 to level do
1430 (aset ltimes l (+ (aref ltimes l) t1))))
1431 (setq time (aref ltimes level))
1432 (goto-char (match-beginning 0))
1433 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1434 (if headline-filter
1435 (save-excursion
1436 (save-match-data
1437 (while
1438 (> (funcall outline-level) 1)
1439 (outline-up-heading 1 t)
1440 (put-text-property
1441 (point) (point-at-eol)
1442 :org-clock-force-headline-inclusion t))))))
1443 (setq t1 0)
1444 (loop for l from level to (1- lmax) do
1445 (aset ltimes l 0)))))))
1446 (setq org-clock-file-total-minutes (aref ltimes 0)))
1447 (set-buffer-modified-p bmp)))
1449 (defun org-clock-sum-current-item (&optional tstart)
1450 "Return time, clocked on current item in total."
1451 (save-excursion
1452 (save-restriction
1453 (org-narrow-to-subtree)
1454 (org-clock-sum tstart)
1455 org-clock-file-total-minutes)))
1457 (defun org-clock-display (&optional total-only)
1458 "Show subtree times in the entire buffer.
1459 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1460 in the echo area."
1461 (interactive)
1462 (org-clock-remove-overlays)
1463 (let (time h m p)
1464 (org-clock-sum)
1465 (unless total-only
1466 (save-excursion
1467 (goto-char (point-min))
1468 (while (or (and (equal (setq p (point)) (point-min))
1469 (get-text-property p :org-clock-minutes))
1470 (setq p (next-single-property-change
1471 (point) :org-clock-minutes)))
1472 (goto-char p)
1473 (when (setq time (get-text-property p :org-clock-minutes))
1474 (org-clock-put-overlay time (funcall outline-level))))
1475 (setq h (/ org-clock-file-total-minutes 60)
1476 m (- org-clock-file-total-minutes (* 60 h)))
1477 ;; Arrange to remove the overlays upon next change.
1478 (when org-remove-highlights-with-change
1479 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1480 nil 'local))))
1481 (if org-time-clocksum-use-fractional
1482 (message (concat "Total file time: " org-time-clocksum-fractional-format
1483 " (%d hours and %d minutes)")
1484 (/ (+ (* h 60.0) m) 60.0) h m)
1485 (message (concat "Total file time: " org-time-clocksum-format
1486 " (%d hours and %d minutes)") h m h m))))
1488 (defvar org-clock-overlays nil)
1489 (make-variable-buffer-local 'org-clock-overlays)
1491 (defun org-clock-put-overlay (time &optional level)
1492 "Put an overlays on the current line, displaying TIME.
1493 If LEVEL is given, prefix time with a corresponding number of stars.
1494 This creates a new overlay and stores it in `org-clock-overlays', so that it
1495 will be easy to remove."
1496 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1497 (l (if level (org-get-valid-level level 0) 0))
1498 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1499 org-time-clocksum-fractional-format
1500 org-time-clocksum-format) "%s"))
1501 (off 0)
1502 ov tx)
1503 (org-move-to-column c)
1504 (unless (eolp) (skip-chars-backward "^ \t"))
1505 (skip-chars-backward " \t")
1506 (setq ov (make-overlay (1- (point)) (point-at-eol))
1507 tx (concat (buffer-substring (1- (point)) (point))
1508 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1509 (org-add-props (if org-time-clocksum-use-fractional
1510 (format fmt
1511 (make-string l ?*)
1512 (/ (+ (* h 60.0) m) 60.0)
1513 (make-string (- 16 l) ?\ ))
1514 (format fmt
1515 (make-string l ?*) h m
1516 (make-string (- 16 l) ?\ )))
1517 (list 'face 'org-clock-overlay))
1518 ""))
1519 (if (not (featurep 'xemacs))
1520 (overlay-put ov 'display tx)
1521 (overlay-put ov 'invisible t)
1522 (overlay-put ov 'end-glyph (make-glyph tx)))
1523 (push ov org-clock-overlays)))
1525 (defun org-clock-remove-overlays (&optional beg end noremove)
1526 "Remove the occur highlights from the buffer.
1527 BEG and END are ignored. If NOREMOVE is nil, remove this function
1528 from the `before-change-functions' in the current buffer."
1529 (interactive)
1530 (unless org-inhibit-highlight-removal
1531 (mapc 'delete-overlay org-clock-overlays)
1532 (setq org-clock-overlays nil)
1533 (unless noremove
1534 (remove-hook 'before-change-functions
1535 'org-clock-remove-overlays 'local))))
1537 (defvar state) ;; dynamically scoped into this function
1538 (defun org-clock-out-if-current ()
1539 "Clock out if the current entry contains the running clock.
1540 This is used to stop the clock after a TODO entry is marked DONE,
1541 and is only done if the variable `org-clock-out-when-done' is not nil."
1542 (when (and org-clock-out-when-done
1543 (or (and (eq t org-clock-out-when-done)
1544 (member state org-done-keywords))
1545 (and (listp org-clock-out-when-done)
1546 (member state org-clock-out-when-done)))
1547 (equal (or (buffer-base-buffer (org-clocking-buffer))
1548 (org-clocking-buffer))
1549 (or (buffer-base-buffer (current-buffer))
1550 (current-buffer)))
1551 (< (point) org-clock-marker)
1552 (> (save-excursion (outline-next-heading) (point))
1553 org-clock-marker))
1554 ;; Clock out, but don't accept a logging message for this.
1555 (let ((org-log-note-clock-out nil)
1556 (org-clock-out-switch-to-state nil))
1557 (org-clock-out))))
1559 (add-hook 'org-after-todo-state-change-hook
1560 'org-clock-out-if-current)
1562 ;;;###autoload
1563 (defun org-get-clocktable (&rest props)
1564 "Get a formatted clocktable with parameters according to PROPS.
1565 The table is created in a temporary buffer, fully formatted and
1566 fontified, and then returned."
1567 ;; Set the defaults
1568 (setq props (plist-put props :name "clocktable"))
1569 (unless (plist-member props :maxlevel)
1570 (setq props (plist-put props :maxlevel 2)))
1571 (unless (plist-member props :scope)
1572 (setq props (plist-put props :scope 'agenda)))
1573 (with-temp-buffer
1574 (org-mode)
1575 (org-create-dblock props)
1576 (org-update-dblock)
1577 (font-lock-fontify-buffer)
1578 (forward-line 2)
1579 (buffer-substring (point) (progn
1580 (re-search-forward "^#\\+END" nil t)
1581 (point-at-bol)))))
1583 (defun org-clock-report (&optional arg)
1584 "Create a table containing a report about clocked time.
1585 If the cursor is inside an existing clocktable block, then the table
1586 will be updated. If not, a new clocktable will be inserted.
1587 When called with a prefix argument, move to the first clock table in the
1588 buffer and update it."
1589 (interactive "P")
1590 (org-clock-remove-overlays)
1591 (when arg
1592 (org-find-dblock "clocktable")
1593 (org-show-entry))
1594 (if (org-in-clocktable-p)
1595 (goto-char (org-in-clocktable-p))
1596 (org-create-dblock (append (list :name "clocktable")
1597 org-clock-clocktable-default-properties)))
1598 (org-update-dblock))
1600 (defun org-in-clocktable-p ()
1601 "Check if the cursor is in a clocktable."
1602 (let ((pos (point)) start)
1603 (save-excursion
1604 (end-of-line 1)
1605 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
1606 (setq start (match-beginning 0))
1607 (re-search-forward "^#\\+END:.*" nil t)
1608 (>= (match-end 0) pos)
1609 start))))
1611 (defun org-clock-special-range (key &optional time as-strings)
1612 "Return two times bordering a special time range.
1613 Key is a symbol specifying the range and can be one of `today', `yesterday',
1614 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1615 A week starts Monday 0:00 and ends Sunday 24:00.
1616 The range is determined relative to TIME. TIME defaults to the current time.
1617 The return value is a cons cell with two internal times like the ones
1618 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1619 the returned times will be formatted strings."
1620 (if (integerp key) (setq key (intern (number-to-string key))))
1621 (let* ((tm (decode-time (or time (current-time))))
1622 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1623 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1624 (dow (nth 6 tm))
1625 (skey (symbol-name key))
1626 (shift 0)
1627 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
1628 (cond
1629 ((string-match "^[0-9]+$" skey)
1630 (setq y (string-to-number skey) m 1 d 1 key 'year))
1631 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1632 (setq y (string-to-number (match-string 1 skey))
1633 month (string-to-number (match-string 2 skey))
1634 d 1 key 'month))
1635 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1636 (require 'cal-iso)
1637 (setq y (string-to-number (match-string 1 skey))
1638 w (string-to-number (match-string 2 skey)))
1639 (setq date (calendar-gregorian-from-absolute
1640 (calendar-absolute-from-iso (list w 1 y))))
1641 (setq d (nth 1 date) month (car date) y (nth 2 date)
1642 dow 1
1643 key 'week))
1644 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1645 (setq y (string-to-number (match-string 1 skey))
1646 month (string-to-number (match-string 2 skey))
1647 d (string-to-number (match-string 3 skey))
1648 key 'day))
1649 ((string-match "\\([-+][0-9]+\\)$" skey)
1650 (setq shift (string-to-number (match-string 1 skey))
1651 key (intern (substring skey 0 (match-beginning 1))))))
1652 (when (= shift 0)
1653 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1654 ((eq key 'lastweek) (setq key 'week shift -1))
1655 ((eq key 'lastmonth) (setq key 'month shift -1))
1656 ((eq key 'lastyear) (setq key 'year shift -1))))
1657 (cond
1658 ((memq key '(day today))
1659 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1660 ((memq key '(week thisweek))
1661 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1662 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1663 ((memq key '(month thismonth))
1664 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1665 ((memq key '(year thisyear))
1666 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1667 (t (error "No such time block %s" key)))
1668 (setq ts (encode-time s m h d month y)
1669 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1670 (or d1 d) (or month1 month) (or y1 y)))
1671 (setq fm (cdr org-time-stamp-formats))
1672 (cond
1673 ((memq key '(day today))
1674 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1675 ((memq key '(week thisweek))
1676 (setq txt (format-time-string "week %G-W%V" ts)))
1677 ((memq key '(month thismonth))
1678 (setq txt (format-time-string "%B %Y" ts)))
1679 ((memq key '(year thisyear))
1680 (setq txt (format-time-string "the year %Y" ts))))
1681 (if as-strings
1682 (list (format-time-string fm ts) (format-time-string fm te) txt)
1683 (list ts te txt))))
1685 (defun org-clocktable-shift (dir n)
1686 "Try to shift the :block date of the clocktable at point.
1687 Point must be in the #+BEGIN: line of a clocktable, or this function
1688 will throw an error.
1689 DIR is a direction, a symbol `left', `right', `up', or `down'.
1690 Both `left' and `down' shift the block toward the past, `up' and `right'
1691 push it toward the future.
1692 N is the number of shift steps to take. The size of the step depends on
1693 the currently selected interval size."
1694 (setq n (prefix-numeric-value n))
1695 (and (memq dir '(left down)) (setq n (- n)))
1696 (save-excursion
1697 (goto-char (point-at-bol))
1698 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1699 (error "Line needs a :block definition before this command works")
1700 (let* ((b (match-beginning 1)) (e (match-end 1))
1701 (s (match-string 1))
1702 block shift ins y mw d date wp m)
1703 (cond
1704 ((equal s "yesterday") (setq s "today-1"))
1705 ((equal s "lastweek") (setq s "thisweek-1"))
1706 ((equal s "lastmonth") (setq s "thismonth-1"))
1707 ((equal s "lastyear") (setq s "thisyear-1")))
1708 (cond
1709 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
1710 (setq block (match-string 1 s)
1711 shift (if (match-end 2)
1712 (string-to-number (match-string 2 s))
1714 (setq shift (+ shift n))
1715 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1716 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1717 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1718 (setq y (string-to-number (match-string 1 s))
1719 wp (and (match-end 3) (match-string 3 s))
1720 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1721 d (and (match-end 6) (string-to-number (match-string 6 s))))
1722 (cond
1723 (d (setq ins (format-time-string
1724 "%Y-%m-%d"
1725 (encode-time 0 0 0 (+ d n) m y))))
1726 ((and wp mw (> (length wp) 0))
1727 (require 'cal-iso)
1728 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1729 (setq ins (format-time-string
1730 "%G-W%V"
1731 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1733 (setq ins (format-time-string
1734 "%Y-%m"
1735 (encode-time 0 0 0 1 (+ mw n) y))))
1737 (setq ins (number-to-string (+ y n))))))
1738 (t (error "Cannot shift clocktable block")))
1739 (when ins
1740 (goto-char b)
1741 (insert ins)
1742 (delete-region (point) (+ (point) (- e b)))
1743 (beginning-of-line 1)
1744 (org-update-dblock)
1745 t)))))
1747 (defun org-dblock-write:clocktable (params)
1748 "Write the standard clocktable."
1749 (catch 'exit
1750 (let* ((hlchars '((1 . "*") (2 . "/")))
1751 (ins (make-marker))
1752 (total-time nil)
1753 (scope (plist-get params :scope))
1754 (tostring (plist-get params :tostring))
1755 (multifile (plist-get params :multifile))
1756 (header (plist-get params :header))
1757 (maxlevel (or (plist-get params :maxlevel) 3))
1758 (step (plist-get params :step))
1759 (emph (plist-get params :emphasize))
1760 (timestamp (plist-get params :timestamp))
1761 (ts (plist-get params :tstart))
1762 (te (plist-get params :tend))
1763 (block (plist-get params :block))
1764 (link (plist-get params :link))
1765 (tags (plist-get params :tags))
1766 (matcher (if tags (cdr (org-make-tags-matcher tags))))
1767 ipos time p level hlc hdl tsp props content recalc formula pcol
1768 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
1769 (setq org-clock-file-total-minutes nil)
1770 (when step
1771 (unless (or block (and ts te))
1772 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1773 (org-clocktable-steps params)
1774 (throw 'exit nil))
1775 (when block
1776 (setq cc (org-clock-special-range block nil t)
1777 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1778 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
1779 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
1780 (when (and ts (listp ts))
1781 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
1782 (when (and te (listp te))
1783 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
1784 ;; Now the times are strings we can parse.
1785 (if ts (setq ts (org-float-time
1786 (apply 'encode-time (org-parse-time-string ts)))))
1787 (if te (setq te (org-float-time
1788 (apply 'encode-time (org-parse-time-string te)))))
1789 (move-marker ins (point))
1790 (setq ipos (point))
1792 ;; Get the right scope
1793 (setq pos (point))
1794 (cond
1795 ((and scope (listp scope) (symbolp (car scope)))
1796 (setq scope (eval scope)))
1797 ((eq scope 'agenda)
1798 (setq scope (org-agenda-files t)))
1799 ((eq scope 'agenda-with-archives)
1800 (setq scope (org-agenda-files t))
1801 (setq scope (org-add-archive-files scope)))
1802 ((eq scope 'file-with-archives)
1803 (setq scope (org-add-archive-files (list (buffer-file-name)))
1804 rm-file-column t)))
1805 (setq scope-is-list (and scope (listp scope)))
1806 (save-restriction
1807 (cond
1808 ((not scope))
1809 ((eq scope 'file) (widen))
1810 ((eq scope 'subtree) (org-narrow-to-subtree))
1811 ((eq scope 'tree)
1812 (while (org-up-heading-safe))
1813 (org-narrow-to-subtree))
1814 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1815 (symbol-name scope)))
1816 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1817 (catch 'exit
1818 (while (org-up-heading-safe)
1819 (looking-at outline-regexp)
1820 (if (<= (org-reduced-level (funcall outline-level)) level)
1821 (throw 'exit nil))))
1822 (org-narrow-to-subtree))
1823 (scope-is-list
1824 (let* ((files scope)
1825 (scope 'agenda)
1826 (p1 (copy-sequence params))
1827 file)
1828 (setq p1 (plist-put p1 :tostring t))
1829 (setq p1 (plist-put p1 :multifile t))
1830 (setq p1 (plist-put p1 :scope 'file))
1831 (org-prepare-agenda-buffers files)
1832 (while (setq file (pop files))
1833 (with-current-buffer (find-buffer-visiting file)
1834 (setq tbl1 (org-dblock-write:clocktable p1))
1835 (when tbl1
1836 (push (org-clocktable-add-file
1837 file
1838 (concat "| |*File time*|*"
1839 (org-minutes-to-hh:mm-string
1840 org-clock-file-total-minutes)
1841 "*|\n"
1842 tbl1)) tbl)
1843 (setq total-time (+ (or total-time 0)
1844 org-clock-file-total-minutes))))))))
1845 (goto-char pos)
1847 (unless scope-is-list
1848 (org-clock-sum ts te
1849 (unless (null matcher)
1850 (lambda ()
1851 (let ((tags-list
1852 (org-split-string
1853 (or (org-entry-get (point) "ALLTAGS") "")
1854 ":")))
1855 (eval matcher)))))
1856 (goto-char (point-min))
1857 (setq st t)
1858 (while (or (and (bobp) (prog1 st (setq st nil))
1859 (get-text-property (point) :org-clock-minutes)
1860 (setq p (point-min)))
1861 (setq p (next-single-property-change (point) :org-clock-minutes)))
1862 (goto-char p)
1863 (when (setq time (get-text-property p :org-clock-minutes))
1864 (save-excursion
1865 (beginning-of-line 1)
1866 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1867 (setq level (org-reduced-level
1868 (- (match-end 1) (match-beginning 1))))
1869 (<= level maxlevel))
1870 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
1871 hdl (if (not link)
1872 (match-string 2)
1873 (org-make-link-string
1874 (format "file:%s::%s"
1875 (buffer-file-name)
1876 (save-match-data
1877 (org-make-org-heading-search-string
1878 (match-string 2))))
1879 (match-string 2)))
1880 tsp (when timestamp
1881 (setq props (org-entry-properties (point)))
1882 (or (cdr (assoc "SCHEDULED" props))
1883 (cdr (assoc "TIMESTAMP" props))
1884 (cdr (assoc "DEADLINE" props))
1885 (cdr (assoc "TIMESTAMP_IA" props)))))
1886 (if (and (not multifile) (= level 1)) (push "|-" tbl))
1887 (push (concat
1888 "| " (int-to-string level) "|"
1889 (if timestamp (concat tsp "|") "")
1890 hlc hdl hlc " |"
1891 (make-string (1- level) ?|)
1892 hlc (org-minutes-to-hh:mm-string time) hlc
1893 " |") tbl))))))
1894 (setq tbl (nreverse tbl))
1895 (if tostring
1896 (if tbl (mapconcat 'identity tbl "\n") nil)
1897 (goto-char ins)
1898 (insert-before-markers
1899 (or header
1900 (concat
1901 "Clock summary at ["
1902 (substring
1903 (format-time-string (cdr org-time-stamp-formats))
1904 1 -1)
1906 (if block (concat ", for " range-text ".") "")
1907 "\n\n"))
1908 (if scope-is-list "|File" "")
1909 "|L|" (if timestamp "Timestamp|" "") "Headline|Time|\n")
1910 (setq total-time (or total-time org-clock-file-total-minutes))
1911 (insert-before-markers
1912 "|-\n|"
1913 (if scope-is-list "|" "")
1914 (if timestamp "|Timestamp|" "|")
1915 "*Total time*| *"
1916 (org-minutes-to-hh:mm-string (or total-time 0))
1917 "*|\n|-\n")
1918 (setq tbl (delq nil tbl))
1919 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
1920 (equal (substring (car tbl) 0 2) "|-"))
1921 (pop tbl))
1922 (insert-before-markers (mapconcat
1923 'identity (delq nil tbl)
1924 (if scope-is-list "\n|-\n" "\n")))
1925 (backward-delete-char 1)
1926 (if (setq formula (plist-get params :formula))
1927 (cond
1928 ((eq formula '%)
1929 (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
1930 (insert
1931 (format
1932 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1933 pcol
1935 (+ 3 (if scope-is-list 1 0))
1936 (+ (if scope-is-list 1 0) 3)
1937 (1- pcol)))
1938 (setq recalc t))
1939 ((stringp formula)
1940 (insert "\n#+TBLFM: " formula)
1941 (setq recalc t))
1942 (t (error "invalid formula in clocktable")))
1943 ;; Should we rescue an old formula?
1944 (when (stringp (setq content (plist-get params :content)))
1945 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
1946 (setq recalc t)
1947 (insert "\n" (match-string 1 (plist-get params :content)))
1948 (beginning-of-line 0))))
1949 (goto-char ipos)
1950 (skip-chars-forward "^|")
1951 (org-table-align)
1952 (when recalc
1953 (if (eq formula '%)
1954 (save-excursion (org-table-goto-column pcol nil 'force)
1955 (insert "%")))
1956 (org-table-recalculate 'all))
1957 (when rm-file-column
1958 (forward-char 1)
1959 (org-table-delete-column))
1960 total-time)))))
1962 (defun org-clocktable-steps (params)
1963 (let* ((p1 (copy-sequence params))
1964 (ts (plist-get p1 :tstart))
1965 (te (plist-get p1 :tend))
1966 (step0 (plist-get p1 :step))
1967 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
1968 (stepskip0 (plist-get p1 :stepskip0))
1969 (block (plist-get p1 :block))
1970 cc range-text step-time)
1971 (when block
1972 (setq cc (org-clock-special-range block nil t)
1973 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1974 (if ts (setq ts (org-float-time
1975 (apply 'encode-time (org-parse-time-string ts)))))
1976 (if te (setq te (org-float-time
1977 (apply 'encode-time (org-parse-time-string te)))))
1978 (setq p1 (plist-put p1 :header ""))
1979 (setq p1 (plist-put p1 :step nil))
1980 (setq p1 (plist-put p1 :block nil))
1981 (while (< ts te)
1982 (or (bolp) (insert "\n"))
1983 (setq p1 (plist-put p1 :tstart (format-time-string
1984 (org-time-stamp-format nil t)
1985 (seconds-to-time ts))))
1986 (setq p1 (plist-put p1 :tend (format-time-string
1987 (org-time-stamp-format nil t)
1988 (seconds-to-time (setq ts (+ ts step))))))
1989 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
1990 (plist-get p1 :tstart) "\n")
1991 (setq step-time (org-dblock-write:clocktable p1))
1992 (re-search-forward "#\\+END:")
1993 (when (and (equal step-time 0) stepskip0)
1994 ;; Remove the empty table
1995 (delete-region (point-at-bol)
1996 (save-excursion
1997 (re-search-backward "^\\(Daily\\|Weekly\\) report" nil t)
1998 (point))))
1999 (end-of-line 0))))
2001 (defun org-clocktable-add-file (file table)
2002 (if table
2003 (let ((lines (org-split-string table "\n"))
2004 (ff (file-name-nondirectory file)))
2005 (mapconcat 'identity
2006 (mapcar (lambda (x)
2007 (if (string-match org-table-dataline-regexp x)
2008 (concat "|" ff x)
2010 lines)
2011 "\n"))))
2013 (defun org-clock-time% (total &rest strings)
2014 "Compute a time fraction in percent.
2015 TOTAL s a time string like 10:21 specifying the total times.
2016 STRINGS is a list of strings that should be checked for a time.
2017 The first string that does have a time will be used.
2018 This function is made for clock tables."
2019 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2020 tot s)
2021 (save-match-data
2022 (catch 'exit
2023 (if (not (string-match re total))
2024 (throw 'exit 0.)
2025 (setq tot (+ (string-to-number (match-string 2 total))
2026 (* 60 (string-to-number (match-string 1 total)))))
2027 (if (= tot 0.) (throw 'exit 0.)))
2028 (while (setq s (pop strings))
2029 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2030 (throw 'exit
2031 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2032 (* 60 (string-to-number (match-string 1 s)))))
2033 tot))))
2034 0))))
2036 (defvar org-clock-loaded nil
2037 "Was the clock file loaded?")
2039 (defun org-clock-save ()
2040 "Persist various clock-related data to disk.
2041 The details of what will be saved are regulated by the variable
2042 `org-clock-persist'."
2043 (when (and org-clock-persist
2044 (or org-clock-loaded
2045 org-clock-has-been-used
2046 (not (file-exists-p org-clock-persist-file))))
2047 (let (b)
2048 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2049 (progn
2050 (delete-region (point-min) (point-max))
2051 ;;Store clock
2052 (insert (format ";; org-persist.el - %s at %s\n"
2053 system-name (format-time-string
2054 (cdr org-time-stamp-formats))))
2055 (if (and (memq org-clock-persist '(t clock))
2056 (setq b (org-clocking-buffer))
2057 (setq b (or (buffer-base-buffer b) b))
2058 (buffer-live-p b)
2059 (buffer-file-name b)
2060 (or (not org-clock-persist-query-save)
2061 (y-or-n-p (concat "Save current clock ("
2062 (substring-no-properties org-clock-heading)
2063 ") "))))
2064 (insert "(setq resume-clock '(\""
2065 (buffer-file-name (org-clocking-buffer))
2066 "\" . " (int-to-string (marker-position org-clock-marker))
2067 "))\n"))
2068 ;; Store clocked task history. Tasks are stored reversed to make
2069 ;; reading simpler
2070 (when (and (memq org-clock-persist '(t history))
2071 org-clock-history)
2072 (insert
2073 "(setq stored-clock-history '("
2074 (mapconcat
2075 (lambda (m)
2076 (when (and (setq b (marker-buffer m))
2077 (setq b (or (buffer-base-buffer b) b))
2078 (buffer-live-p b)
2079 (buffer-file-name b))
2080 (concat "(\"" (buffer-file-name b)
2081 "\" . " (int-to-string (marker-position m))
2082 ")")))
2083 (reverse org-clock-history) " ") "))\n"))
2084 (save-buffer)
2085 (kill-buffer (current-buffer)))))))
2087 (defun org-clock-load ()
2088 "Load clock-related data from disk, maybe resuming a stored clock."
2089 (when (and org-clock-persist (not org-clock-loaded))
2090 (let ((filename (expand-file-name org-clock-persist-file))
2091 (org-clock-in-resume 'auto-restart)
2092 resume-clock stored-clock-history)
2093 (if (not (file-readable-p filename))
2094 (message "Not restoring clock data; %s not found"
2095 org-clock-persist-file)
2096 (message "%s" "Restoring clock data")
2097 (setq org-clock-loaded t)
2098 (load-file filename)
2099 ;; load history
2100 (when stored-clock-history
2101 (save-window-excursion
2102 (mapc (lambda (task)
2103 (if (file-exists-p (car task))
2104 (org-clock-history-push (cdr task)
2105 (find-file (car task)))))
2106 stored-clock-history)))
2107 ;; resume clock
2108 (when (and resume-clock org-clock-persist
2109 (file-exists-p (car resume-clock))
2110 (or (not org-clock-persist-query-resume)
2111 (y-or-n-p
2112 (concat
2113 "Resume clock ("
2114 (with-current-buffer (find-file (car resume-clock))
2115 (save-excursion
2116 (goto-char (cdr resume-clock))
2117 (org-back-to-heading t)
2118 (and (looking-at org-complex-heading-regexp)
2119 (match-string 4))))
2120 ") "))))
2121 (when (file-exists-p (car resume-clock))
2122 (with-current-buffer (find-file (car resume-clock))
2123 (goto-char (cdr resume-clock))
2124 (let ((org-clock-auto-clock-resolution nil))
2125 (org-clock-in)
2126 (if (org-invisible-p)
2127 (org-show-context))))))))))
2129 ;;;###autoload
2130 (defun org-clock-persistence-insinuate ()
2131 "Set up hooks for clock persistence."
2132 (add-hook 'org-mode-hook 'org-clock-load)
2133 (add-hook 'kill-emacs-hook 'org-clock-save))
2135 ;; Suggested bindings
2136 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2138 (provide 'org-clock)
2140 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2142 ;;; org-clock.el ends here