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