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