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