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