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