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