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