Release 6.35b
[org-mode/org-tableheadings.git] / lisp / org-clock.el
blob77b748613f9fd26b152ca8877b798ef56f2e8d04
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.35b
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 (defcustom org-clock-report-include-clocking-task nil
244 "When non-nil, include the current clocking task time in clock reports."
245 :group 'org-clock
246 :type 'boolean)
248 (defvar org-clock-in-prepare-hook nil
249 "Hook run when preparing the clock.
250 This hook is run before anything happens to the task that
251 you want to clock in. For example, you can use this hook
252 to add an effort property.")
253 (defvar org-clock-in-hook nil
254 "Hook run when starting the clock.")
255 (defvar org-clock-out-hook nil
256 "Hook run when stopping the current clock.")
258 (defvar org-clock-cancel-hook nil
259 "Hook run when cancelling the current clock.")
260 (defvar org-clock-goto-hook nil
261 "Hook run when selecting the currently clocked-in entry.")
262 (defvar org-clock-has-been-used nil
263 "Has the clock been used during the current Emacs session?")
265 ;;; The clock for measuring work time.
267 (defvar org-mode-line-string "")
268 (put 'org-mode-line-string 'risky-local-variable t)
270 (defvar org-clock-mode-line-timer nil)
271 (defvar org-clock-idle-timer nil)
272 (defvar org-clock-heading) ; defined in org.el
273 (defvar org-clock-heading-for-remember "")
274 (defvar org-clock-start-time "")
276 (defvar org-clock-leftover-time nil
277 "If non-nil, user cancelled a clock; this is when leftover time started.")
279 (defvar org-clock-effort ""
280 "Effort estimate of the currently clocking task")
282 (defvar org-clock-total-time nil
283 "Holds total time, spent previously on currently clocked item.
284 This does not include the time in the currently running clock.")
286 (defvar org-clock-history nil
287 "List of marker pointing to recent clocked tasks.")
289 (defvar org-clock-default-task (make-marker)
290 "Marker pointing to the default task that should clock time.
291 The clock can be made to switch to this task after clocking out
292 of a different task.")
294 (defvar org-clock-interrupted-task (make-marker)
295 "Marker pointing to the task that has been interrupted by the current clock.")
297 (defvar org-clock-mode-line-map (make-sparse-keymap))
298 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
299 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
301 (defun org-clock-menu ()
302 (interactive)
303 (popup-menu
304 '("Clock"
305 ["Clock out" org-clock-out t]
306 ["Change effort estimate" org-clock-modify-effort-estimate t]
307 ["Go to clock entry" org-clock-goto t]
308 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
310 (defun org-clock-history-push (&optional pos buffer)
311 "Push a marker to the clock history."
312 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
313 (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
314 (while (setq n (member m org-clock-history))
315 (move-marker (car n) nil))
316 (setq org-clock-history
317 (delq nil
318 (mapcar (lambda (x) (if (marker-buffer x) x nil))
319 org-clock-history)))
320 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
321 (setq org-clock-history
322 (nreverse
323 (nthcdr (- l org-clock-history-length -1)
324 (nreverse org-clock-history)))))
325 (push m org-clock-history)))
327 (defun org-clock-save-markers-for-cut-and-paste (beg end)
328 "Save relative positions of markers in region."
329 (org-check-and-save-marker org-clock-marker beg end)
330 (org-check-and-save-marker org-clock-hd-marker beg end)
331 (org-check-and-save-marker org-clock-default-task beg end)
332 (org-check-and-save-marker org-clock-interrupted-task beg end)
333 (mapc (lambda (m) (org-check-and-save-marker m beg end))
334 org-clock-history))
336 (defun org-clocking-buffer ()
337 "Returns clocking buffer if we are currently clocking a task or nil"
338 (marker-buffer org-clock-marker))
340 (defun org-clocking-p ()
341 "Returns t when clocking a task"
342 (not (equal (org-clocking-buffer) nil)))
344 (defun org-clock-select-task (&optional prompt)
345 "Select a task that recently was associated with clocking."
346 (interactive)
347 (let (sel-list rpl (i 0) s)
348 (save-window-excursion
349 (org-switch-to-buffer-other-window
350 (get-buffer-create "*Clock Task Select*"))
351 (erase-buffer)
352 (when (marker-buffer org-clock-default-task)
353 (insert (org-add-props "Default Task\n" nil 'face 'bold))
354 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
355 (push s sel-list))
356 (when (marker-buffer org-clock-interrupted-task)
357 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
358 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
359 (push s sel-list))
360 (when (org-clocking-p)
361 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
362 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
363 (push s sel-list))
364 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
365 (mapc
366 (lambda (m)
367 (when (marker-buffer m)
368 (setq i (1+ i)
369 s (org-clock-insert-selection-line
370 (if (< i 10)
371 (+ i ?0)
372 (+ i (- ?A 10))) m))
373 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
374 (push s sel-list)))
375 org-clock-history)
376 (org-fit-window-to-buffer)
377 (message (or prompt "Select task for clocking:"))
378 (setq rpl (read-char-exclusive))
379 (cond
380 ((eq rpl ?q) nil)
381 ((eq rpl ?x) nil)
382 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
383 (t (error "Invalid task choice %c" rpl))))))
385 (defun org-clock-insert-selection-line (i marker)
386 "Insert a line for the clock selection menu.
387 And return a cons cell with the selection character integer and the marker
388 pointing to it."
389 (when (marker-buffer marker)
390 (let (file cat task heading prefix)
391 (with-current-buffer (org-base-buffer (marker-buffer marker))
392 (save-excursion
393 (save-restriction
394 (widen)
395 (ignore-errors
396 (goto-char marker)
397 (setq file (buffer-file-name (marker-buffer marker))
398 cat (or (org-get-category)
399 (progn (org-refresh-category-properties)
400 (org-get-category)))
401 heading (org-get-heading 'notags)
402 prefix (save-excursion
403 (org-back-to-heading t)
404 (looking-at "\\*+ ")
405 (match-string 0))
406 task (substring
407 (org-fontify-like-in-org-mode
408 (concat prefix heading)
409 org-odd-levels-only)
410 (length prefix)))))))
411 (when (and cat task)
412 (insert (format "[%c] %-15s %s\n" i cat task))
413 (cons i marker)))))
415 (defvar org-task-overrun nil
416 "Internal flag indicating if the clock has overrun the planned time.")
417 (defvar org-clock-update-period 60
418 "Number of seconds between mode line clock string updates.")
420 (defun org-clock-get-clock-string ()
421 "Form a clock-string, that will be shown in the mode line.
422 If an effort estimate was defined for the current item, use
423 01:30/01:50 format (clocked/estimated).
424 If not, show simply the clocked time like 01:50."
425 (let* ((clocked-time (org-clock-get-clocked-time))
426 (h (floor clocked-time 60))
427 (m (- clocked-time (* 60 h))))
428 (if org-clock-effort
429 (let* ((effort-in-minutes
430 (org-hh:mm-string-to-minutes org-clock-effort))
431 (effort-h (floor effort-in-minutes 60))
432 (effort-m (- effort-in-minutes (* effort-h 60)))
433 (work-done-str
434 (org-propertize
435 (format org-time-clocksum-format h m)
436 'face (if (and org-task-overrun (not org-task-overrun-text))
437 'org-mode-line-clock-overrun 'org-mode-line-clock)))
438 (effort-str (format org-time-clocksum-format effort-h effort-m))
439 (clockstr (org-propertize
440 (concat "[%s/" effort-str
441 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
442 'face 'org-mode-line-clock)))
443 (format clockstr work-done-str))
444 (org-propertize (format
445 (concat "[" org-time-clocksum-format " (%s)]")
446 h m org-clock-heading)
447 'face 'org-mode-line-clock))))
449 (defun org-clock-update-mode-line ()
450 (if org-clock-effort
451 (org-clock-notify-once-if-expired)
452 (setq org-task-overrun nil))
453 (setq org-mode-line-string
454 (org-propertize
455 (let ((clock-string (org-clock-get-clock-string))
456 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
457 (if (and (> org-clock-string-limit 0)
458 (> (length clock-string) org-clock-string-limit))
459 (org-propertize
460 (substring clock-string 0 org-clock-string-limit)
461 'help-echo (concat help-text ": " org-clock-heading))
462 (org-propertize clock-string 'help-echo help-text)))
463 'local-map org-clock-mode-line-map
464 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
466 (if (and org-task-overrun org-task-overrun-text)
467 (setq org-mode-line-string
468 (concat (org-propertize
469 org-task-overrun-text
470 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
471 (force-mode-line-update))
473 (defun org-clock-get-clocked-time ()
474 "Get the clocked time for the current item in minutes.
475 The time returned includes the time spent on this task in
476 previous clocking intervals."
477 (let ((currently-clocked-time
478 (floor (- (org-float-time)
479 (org-float-time org-clock-start-time)) 60)))
480 (+ currently-clocked-time (or org-clock-total-time 0))))
482 (defun org-clock-modify-effort-estimate (&optional value)
483 "Add to or set the effort estimate of the item currently being clocked.
484 VALUE can be a number of minutes, or a string with format hh:mm or mm.
485 When the string starts with a + or a - sign, the current value of the effort
486 property will be changed by that amount.
487 This will update the \"Effort\" property of currently clocked item, and
488 the mode line."
489 (interactive)
490 (when (org-clock-is-active)
491 (let ((current org-clock-effort) sign)
492 (unless value
493 ;; Prompt user for a value or a change
494 (setq value
495 (read-string
496 (format "Set effort (hh:mm or mm%s): "
497 (if current
498 (format ", prefix + to add to %s" org-clock-effort)
499 "")))))
500 (when (stringp value)
501 ;; A string. See if it is a delta
502 (setq sign (string-to-char value))
503 (if (member sign '(?- ?+))
504 (setq current (org-hh:mm-string-to-minutes (substring current 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 (if (featurep 'xemacs)
764 (progn
765 (message (concat (funcall prompt-fn clock)
766 " [(kK)eep (sS)ubtract (C)ancel]? "))
767 (setq char-pressed (read-char-exclusive)))
768 (while (or (null char-pressed)
769 (and (not (memq char-pressed '(?k ?K ?s ?S ?C ?i)))
770 (or (ding) t)))
771 (setq char-pressed
772 (read-char (concat (funcall prompt-fn clock)
773 " [(kK)p (sS)ub (C)ncl (i)gn]? ")
774 nil 45)))
775 (and (not (eq char-pressed ?i)) char-pressed))))))
776 (default (floor (/ (org-float-time
777 (time-subtract (current-time) last-valid)) 60)))
778 (keep (and (memq ch '(?k ?K))
779 (read-number "Keep how many minutes? " default)))
780 (subtractp (memq ch '(?s ?S)))
781 (barely-started-p (< (- (org-float-time last-valid)
782 (org-float-time (cdr clock))) 45))
783 (start-over (and subtractp barely-started-p)))
784 (if (or (null ch)
785 (not (memq ch '(?k ?K ?s ?S ?C))))
786 (message "")
787 (org-clock-resolve-clock
788 clock (cond
789 ((or (eq ch ?C)
790 ;; If the time on the clock was less than a minute before
791 ;; the user went away, and they've ask to subtract all the
792 ;; time...
793 start-over)
794 nil)
795 (subtractp
796 last-valid)
797 ((= keep default)
798 'now)
800 (time-add last-valid (seconds-to-time (* 60 keep)))))
801 (memq ch '(?K ?S))
802 (and start-over
803 (not (memq ch '(?K ?S ?C))))
804 fail-quietly))))
806 (defun org-resolve-clocks (&optional also-non-dangling-p prompt-fn last-valid)
807 "Resolve all currently open org-mode clocks.
808 If `also-non-dangling-p' is non-nil, also ask to resolve
809 non-dangling (i.e., currently open and valid) clocks."
810 (interactive "P")
811 (unless org-clock-resolving-clocks
812 (let ((org-clock-resolving-clocks t))
813 (dolist (file (org-files-list))
814 (let ((clocks (org-find-open-clocks file)))
815 (dolist (clock clocks)
816 (let ((dangling (or (not (org-clock-is-active))
817 (/= (car clock) org-clock-marker))))
818 (unless (and (not dangling) (not also-non-dangling-p))
819 (org-clock-resolve
820 clock
821 (or prompt-fn
822 (function
823 (lambda (clock)
824 (format
825 "Dangling clock started %d mins ago"
826 (floor
827 (/ (- (org-float-time (current-time))
828 (org-float-time (cdr clock))) 60))))))
829 (or last-valid
830 (cdr clock)))))))))))
832 (defun org-emacs-idle-seconds ()
833 "Return the current Emacs idle time in seconds, or nil if not idle."
834 (let ((idle-time (current-idle-time)))
835 (if idle-time
836 (org-float-time idle-time)
837 0)))
839 (defun org-mac-idle-seconds ()
840 "Return the current Mac idle time in seconds"
841 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
843 (defun org-x11-idle-seconds ()
844 "Return the current X11 idle time in seconds"
845 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
847 (defun org-user-idle-seconds ()
848 "Return the number of seconds the user has been idle for.
849 This routine returns a floating point number."
850 (cond
851 ((eq system-type 'darwin)
852 (org-mac-idle-seconds))
853 ((eq window-system 'x)
854 (org-x11-idle-seconds))
856 (org-emacs-idle-seconds))))
858 (defvar org-clock-user-idle-seconds)
860 (defun org-resolve-clocks-if-idle ()
861 "Resolve all currently open org-mode clocks.
862 This is performed after `org-clock-idle-time' minutes, to check
863 if the user really wants to stay clocked in after being idle for
864 so long."
865 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
866 org-clock-marker)
867 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
868 (org-clock-user-idle-start
869 (time-subtract (current-time)
870 (seconds-to-time org-clock-user-idle-seconds)))
871 (org-clock-resolving-clocks-due-to-idleness t))
872 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
873 (org-clock-resolve
874 (cons org-clock-marker
875 org-clock-start-time)
876 (function
877 (lambda (clock)
878 (format "Clocked in & idle for %.1f mins"
879 (/ (org-float-time
880 (time-subtract (current-time)
881 org-clock-user-idle-start))
882 60.0))))
883 org-clock-user-idle-start)))))
885 (defun org-clock-in (&optional select)
886 "Start the clock on the current item.
887 If necessary, clock-out of the currently active clock.
888 With prefix arg SELECT, offer a list of recently clocked tasks to
889 clock into. When SELECT is `C-u C-u', clock into the current task and mark
890 is as the default task, a special task that will always be offered in
891 the clocking selection, associated with the letter `d'."
892 (interactive "P")
893 (setq org-clock-notification-was-shown nil)
894 (catch 'abort
895 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
896 (org-clocking-p)))
897 ts selected-task target-pos (msg-extra "")
898 (leftover (and (not org-clock-resolving-clocks)
899 org-clock-leftover-time)))
900 (when (and org-clock-auto-clock-resolution
901 (or (not interrupting)
902 (eq t org-clock-auto-clock-resolution))
903 (not org-clock-clocking-in)
904 (not org-clock-resolving-clocks))
905 (setq org-clock-leftover-time nil)
906 (let ((org-clock-clocking-in t))
907 (org-resolve-clocks))) ; check if any clocks are dangling
908 (when (equal select '(4))
909 (setq selected-task (org-clock-select-task "Clock-in on task: "))
910 (if selected-task
911 (setq selected-task (copy-marker selected-task))
912 (error "Abort")))
913 (when interrupting
914 ;; We are interrupting the clocking of a different task.
915 ;; Save a marker to this task, so that we can go back.
916 ;; First check if we are trying to clock into the same task!
917 (if (save-excursion
918 (unless selected-task
919 (org-back-to-heading t))
920 (and (equal (marker-buffer org-clock-hd-marker)
921 (if selected-task
922 (marker-buffer selected-task)
923 (current-buffer)))
924 (= (marker-position org-clock-hd-marker)
925 (if selected-task
926 (marker-position selected-task)
927 (point)))))
928 (message "Clock continues in \"%s\"" org-clock-heading)
929 (progn
930 (move-marker org-clock-interrupted-task
931 (marker-position org-clock-marker)
932 (org-clocking-buffer))
933 (org-clock-out t))))
935 (when (equal select '(16))
936 ;; Mark as default clocking task
937 (org-clock-mark-default-task))
939 ;; Clock in at which position?
940 (setq target-pos
941 (if (and (eobp) (not (org-on-heading-p)))
942 (point-at-bol 0)
943 (point)))
944 (run-hooks 'org-clock-in-prepare-hook)
945 (save-excursion
946 (when (and selected-task (marker-buffer selected-task))
947 ;; There is a selected task, move to the correct buffer
948 ;; and set the new target position.
949 (set-buffer (org-base-buffer (marker-buffer selected-task)))
950 (setq target-pos (marker-position selected-task))
951 (move-marker selected-task nil))
952 (save-excursion
953 (save-restriction
954 (widen)
955 (goto-char target-pos)
956 (org-back-to-heading t)
957 (or interrupting (move-marker org-clock-interrupted-task nil))
958 (org-clock-history-push)
959 (org-clock-set-current)
960 (cond ((functionp org-clock-in-switch-to-state)
961 (looking-at org-complex-heading-regexp)
962 (let ((newstate (funcall org-clock-in-switch-to-state
963 (match-string 2))))
964 (if newstate (org-todo newstate))))
965 ((and org-clock-in-switch-to-state
966 (not (looking-at (concat outline-regexp "[ \t]*"
967 org-clock-in-switch-to-state
968 "\\>"))))
969 (org-todo org-clock-in-switch-to-state)))
970 (setq org-clock-heading-for-remember
971 (and (looking-at org-complex-heading-regexp)
972 (match-end 4)
973 (org-trim (buffer-substring (match-end 1)
974 (match-end 4)))))
975 (setq org-clock-heading
976 (cond ((and org-clock-heading-function
977 (functionp org-clock-heading-function))
978 (funcall org-clock-heading-function))
979 ((looking-at org-complex-heading-regexp)
980 (replace-regexp-in-string
981 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
982 (match-string 4)))
983 (t "???")))
984 (setq org-clock-heading (org-propertize org-clock-heading
985 'face nil))
986 (org-clock-find-position org-clock-in-resume)
987 (cond
988 ((and org-clock-in-resume
989 (looking-at
990 (concat "^[ \t]* " org-clock-string
991 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
992 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
993 (message "Matched %s" (match-string 1))
994 (setq ts (concat "[" (match-string 1) "]"))
995 (goto-char (match-end 1))
996 (setq org-clock-start-time
997 (apply 'encode-time
998 (org-parse-time-string (match-string 1))))
999 (setq org-clock-effort (org-get-effort))
1000 (setq org-clock-total-time (org-clock-sum-current-item
1001 (org-clock-get-sum-start))))
1002 ((eq org-clock-in-resume 'auto-restart)
1003 ;; called from org-clock-load during startup,
1004 ;; do not interrupt, but warn!
1005 (message "Cannot restart clock because task does not contain unfinished clock")
1006 (ding)
1007 (sit-for 2)
1008 (throw 'abort nil))
1010 (insert-before-markers "\n")
1011 (backward-char 1)
1012 (org-indent-line-function)
1013 (when (and (save-excursion
1014 (end-of-line 0)
1015 (org-in-item-p)))
1016 (beginning-of-line 1)
1017 (org-indent-line-to (- (org-get-indentation) 2)))
1018 (insert org-clock-string " ")
1019 (setq org-clock-effort (org-get-effort))
1020 (setq org-clock-total-time (org-clock-sum-current-item
1021 (org-clock-get-sum-start)))
1022 (setq org-clock-start-time
1023 (or (and leftover
1024 (y-or-n-p
1025 (format
1026 "You stopped another clock %d mins ago; start this one from then? "
1027 (/ (- (org-float-time (current-time))
1028 (org-float-time leftover)) 60)))
1029 leftover)
1030 (current-time)))
1031 (setq ts (org-insert-time-stamp org-clock-start-time
1032 'with-hm 'inactive))))
1033 (move-marker org-clock-marker (point) (buffer-base-buffer))
1034 (move-marker org-clock-hd-marker
1035 (save-excursion (org-back-to-heading t) (point))
1036 (buffer-base-buffer))
1037 (setq org-clock-has-been-used t)
1038 (or global-mode-string (setq global-mode-string '("")))
1039 (or (memq 'org-mode-line-string global-mode-string)
1040 (setq global-mode-string
1041 (append global-mode-string '(org-mode-line-string))))
1042 (org-clock-update-mode-line)
1043 (when org-clock-mode-line-timer
1044 (cancel-timer org-clock-mode-line-timer)
1045 (setq org-clock-mode-line-timer nil))
1046 (setq org-clock-mode-line-timer
1047 (run-with-timer org-clock-update-period
1048 org-clock-update-period
1049 'org-clock-update-mode-line))
1050 (when org-clock-idle-timer
1051 (cancel-timer org-clock-idle-timer)
1052 (setq org-clock-idle-timer nil))
1053 (setq org-clock-idle-timer
1054 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1055 (message "Clock starts at %s - %s" ts msg-extra)
1056 (run-hooks 'org-clock-in-hook)))))))
1058 (defvar org-clock-current-task nil
1059 "Task currently clocked in.")
1060 (defun org-clock-set-current ()
1061 "Set `org-clock-current-task' to the task currently clocked in."
1062 (setq org-clock-current-task (org-get-heading)))
1063 (defun org-clock-delete-current ()
1064 "Reset `org-clock-current-task' to nil."
1065 (setq org-clock-current-task nil))
1067 (defun org-clock-mark-default-task ()
1068 "Mark current task as default task."
1069 (interactive)
1070 (save-excursion
1071 (org-back-to-heading t)
1072 (move-marker org-clock-default-task (point))))
1074 (defvar msg-extra)
1075 (defun org-clock-get-sum-start ()
1076 "Return the time from which clock times should be counted.
1077 This is for the currently running clock as it is displayed
1078 in the mode line. This function looks at the properties
1079 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1080 corresponding variable `org-clock-modeline-total' and then
1081 decides which time to use."
1082 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1083 (symbol-name org-clock-modeline-total)))
1084 (lr (org-entry-get nil "LAST_REPEAT")))
1085 (cond
1086 ((equal cmt "current")
1087 (setq msg-extra "showing time in current clock instance")
1088 (current-time))
1089 ((equal cmt "today")
1090 (setq msg-extra "showing today's task time.")
1091 (let* ((dt (decode-time (current-time))))
1092 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1093 (if org-extend-today-until
1094 (setf (nth 2 dt) org-extend-today-until))
1095 (apply 'encode-time dt)))
1096 ((or (equal cmt "all")
1097 (and (or (not cmt) (equal cmt "auto"))
1098 (not lr)))
1099 (setq msg-extra "showing entire task time.")
1100 nil)
1101 ((or (equal cmt "repeat")
1102 (and (or (not cmt) (equal cmt "auto"))
1103 lr))
1104 (setq msg-extra "showing task time since last repeat.")
1105 (if (not lr)
1107 (org-time-string-to-time lr)))
1108 (t nil))))
1110 (defun org-clock-find-position (find-unclosed)
1111 "Find the location where the next clock line should be inserted.
1112 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1113 line and position cursor in that line."
1114 (org-back-to-heading t)
1115 (catch 'exit
1116 (let ((beg (save-excursion
1117 (beginning-of-line 2)
1118 (or (bolp) (newline))
1119 (point)))
1120 (end (progn (outline-next-heading) (point)))
1121 (re (concat "^[ \t]*" org-clock-string))
1122 (cnt 0)
1123 (drawer (if (stringp org-clock-into-drawer)
1124 org-clock-into-drawer "LOGBOOK"))
1125 first last ind-last)
1126 (goto-char beg)
1127 (when (and find-unclosed
1128 (re-search-forward
1129 (concat "^[ \t]* " org-clock-string
1130 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1131 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1132 end t))
1133 (beginning-of-line 1)
1134 (throw 'exit t))
1135 (when (eobp) (newline) (setq end (max (point) end)))
1136 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1137 ;; we seem to have a CLOCK drawer, so go there.
1138 (beginning-of-line 2)
1139 (or org-log-states-order-reversed
1140 (and (re-search-forward org-property-end-re nil t)
1141 (goto-char (match-beginning 0))))
1142 (throw 'exit t))
1143 ;; Lets count the CLOCK lines
1144 (goto-char beg)
1145 (while (re-search-forward re end t)
1146 (setq first (or first (match-beginning 0))
1147 last (match-beginning 0)
1148 cnt (1+ cnt)))
1149 (when (and (integerp org-clock-into-drawer)
1150 last
1151 (>= (1+ cnt) org-clock-into-drawer))
1152 ;; Wrap current entries into a new drawer
1153 (goto-char last)
1154 (setq ind-last (org-get-indentation))
1155 (beginning-of-line 2)
1156 (if (and (>= (org-get-indentation) ind-last)
1157 (org-at-item-p))
1158 (org-end-of-item))
1159 (insert ":END:\n")
1160 (beginning-of-line 0)
1161 (org-indent-line-to ind-last)
1162 (goto-char first)
1163 (insert ":" drawer ":\n")
1164 (beginning-of-line 0)
1165 (org-indent-line-function)
1166 (org-flag-drawer t)
1167 (beginning-of-line 2)
1168 (or org-log-states-order-reversed
1169 (and (re-search-forward org-property-end-re nil t)
1170 (goto-char (match-beginning 0))))
1171 (throw 'exit nil))
1173 (goto-char beg)
1174 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1175 (not (equal (match-string 1) org-clock-string)))
1176 ;; Planning info, skip to after it
1177 (beginning-of-line 2)
1178 (or (bolp) (newline)))
1179 (when (or (eq org-clock-into-drawer t)
1180 (stringp org-clock-into-drawer)
1181 (and (integerp org-clock-into-drawer)
1182 (< org-clock-into-drawer 2)))
1183 (insert ":" drawer ":\n:END:\n")
1184 (beginning-of-line -1)
1185 (org-indent-line-function)
1186 (org-flag-drawer t)
1187 (beginning-of-line 2)
1188 (org-indent-line-function)
1189 (beginning-of-line)
1190 (or org-log-states-order-reversed
1191 (and (re-search-forward org-property-end-re nil t)
1192 (goto-char (match-beginning 0))))))))
1194 (defun org-clock-out (&optional fail-quietly at-time)
1195 "Stop the currently running clock.
1196 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1197 (interactive)
1198 (catch 'exit
1199 (if (not (org-clocking-p))
1200 (if fail-quietly (throw 'exit t) (error "No active clock")))
1201 (let (ts te s h m remove)
1202 (save-excursion
1203 (set-buffer (org-clocking-buffer))
1204 (save-restriction
1205 (widen)
1206 (goto-char org-clock-marker)
1207 (beginning-of-line 1)
1208 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1209 (equal (match-string 1) org-clock-string))
1210 (setq ts (match-string 2))
1211 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1212 (goto-char (match-end 0))
1213 (delete-region (point) (point-at-eol))
1214 (insert "--")
1215 (setq te (org-insert-time-stamp (or at-time (current-time))
1216 'with-hm 'inactive))
1217 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1218 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1219 h (floor (/ s 3600))
1220 s (- s (* 3600 h))
1221 m (floor (/ s 60))
1222 s (- s (* 60 s)))
1223 (insert " => " (format "%2d:%02d" h m))
1224 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1225 (= (+ h m) 0)))
1226 (beginning-of-line 1)
1227 (delete-region (point) (point-at-eol))
1228 (and (looking-at "\n") (> (point-max) (1+ (point)))
1229 (delete-char 1)))
1230 (move-marker org-clock-marker nil)
1231 (move-marker org-clock-hd-marker nil)
1232 (when org-log-note-clock-out
1233 (org-add-log-setup 'clock-out nil nil nil nil
1234 (concat "# Task: " (org-get-heading t) "\n\n")))
1235 (when org-clock-mode-line-timer
1236 (cancel-timer org-clock-mode-line-timer)
1237 (setq org-clock-mode-line-timer nil))
1238 (when org-clock-idle-timer
1239 (cancel-timer org-clock-idle-timer)
1240 (setq org-clock-idle-timer nil))
1241 (setq global-mode-string
1242 (delq 'org-mode-line-string global-mode-string))
1243 (when org-clock-out-switch-to-state
1244 (save-excursion
1245 (org-back-to-heading t)
1246 (let ((org-inhibit-logging t)
1247 (org-clock-out-when-done nil))
1248 (cond
1249 ((functionp org-clock-out-switch-to-state)
1250 (looking-at org-complex-heading-regexp)
1251 (let ((newstate (funcall org-clock-out-switch-to-state
1252 (match-string 2))))
1253 (if newstate (org-todo newstate))))
1254 ((and org-clock-out-switch-to-state
1255 (not (looking-at (concat outline-regexp "[ \t]*"
1256 org-clock-out-switch-to-state
1257 "\\>"))))
1258 (org-todo org-clock-out-switch-to-state))))))
1259 (force-mode-line-update)
1260 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1261 (if remove " => LINE REMOVED" ""))
1262 (run-hooks 'org-clock-out-hook)
1263 (org-clock-delete-current))))))
1265 (defun org-clock-cancel ()
1266 "Cancel the running clock be removing the start timestamp."
1267 (interactive)
1268 (if (not (org-clocking-p))
1269 (error "No active clock"))
1270 (save-excursion
1271 (set-buffer (org-clocking-buffer))
1272 (goto-char org-clock-marker)
1273 (delete-region (1- (point-at-bol)) (point-at-eol))
1274 ;; Just in case, remove any empty LOGBOOK left over
1275 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1276 (move-marker org-clock-marker nil)
1277 (move-marker org-clock-hd-marker nil)
1278 (setq global-mode-string
1279 (delq 'org-mode-line-string global-mode-string))
1280 (force-mode-line-update)
1281 (message "Clock canceled")
1282 (run-hooks 'org-clock-cancel-hook))
1284 (defun org-clock-goto (&optional select)
1285 "Go to the currently clocked-in entry, or to the most recently clocked one.
1286 With prefix arg SELECT, offer recently clocked tasks for selection."
1287 (interactive "@P")
1288 (let* ((recent nil)
1289 (m (cond
1290 (select
1291 (or (org-clock-select-task "Select task to go to: ")
1292 (error "No task selected")))
1293 ((org-clocking-p) org-clock-marker)
1294 ((and org-clock-goto-may-find-recent-task
1295 (car org-clock-history)
1296 (marker-buffer (car org-clock-history)))
1297 (setq recent t)
1298 (car org-clock-history))
1299 (t (error "No active or recent clock task")))))
1300 (switch-to-buffer (marker-buffer m))
1301 (if (or (< m (point-min)) (> m (point-max))) (widen))
1302 (goto-char m)
1303 (org-show-entry)
1304 (org-back-to-heading t)
1305 (org-cycle-hide-drawers 'children)
1306 (recenter)
1307 (org-reveal)
1308 (if recent
1309 (message "No running clock, this is the most recently clocked task"))
1310 (run-hooks 'org-clock-goto-hook)))
1312 (defvar org-clock-file-total-minutes nil
1313 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1314 (make-variable-buffer-local 'org-clock-file-total-minutes)
1316 (defun org-clock-sum (&optional tstart tend)
1317 "Sum the times for each subtree.
1318 Puts the resulting times in minutes as a text property on each headline.
1319 TSTART and TEND can mark a time range to be considered."
1320 (interactive)
1321 (let* ((bmp (buffer-modified-p))
1322 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1323 org-clock-string
1324 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1325 (lmax 30)
1326 (ltimes (make-vector lmax 0))
1327 (t1 0)
1328 (level 0)
1329 ts te dt
1330 time)
1331 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1332 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1333 (if (consp tstart) (setq tstart (org-float-time tstart)))
1334 (if (consp tend) (setq tend (org-float-time tend)))
1335 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
1336 (save-excursion
1337 (goto-char (point-max))
1338 (while (re-search-backward re nil t)
1339 (cond
1340 ((match-end 2)
1341 ;; Two time stamps
1342 (setq ts (match-string 2)
1343 te (match-string 3)
1344 ts (org-float-time
1345 (apply 'encode-time (org-parse-time-string ts)))
1346 te (org-float-time
1347 (apply 'encode-time (org-parse-time-string te)))
1348 ts (if tstart (max ts tstart) ts)
1349 te (if tend (min te tend) te)
1350 dt (- te ts)
1351 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1352 ((match-end 4)
1353 ;; A naked time
1354 (setq t1 (+ t1 (string-to-number (match-string 5))
1355 (* 60 (string-to-number (match-string 4))))))
1356 (t ;; A headline
1357 ;; Add the currently clocking item time to the total
1358 (when (and org-clock-report-include-clocking-task
1359 (equal (org-clocking-buffer) (current-buffer))
1360 (equal (marker-position org-clock-hd-marker) (point)))
1361 (let ((time (floor (- (org-float-time)
1362 (org-float-time org-clock-start-time)) 60)))
1363 (setq t1 (+ t1 time))))
1364 (setq level (- (match-end 1) (match-beginning 1)))
1365 (when (or (> t1 0) (> (aref ltimes level) 0))
1366 (loop for l from 0 to level do
1367 (aset ltimes l (+ (aref ltimes l) t1)))
1368 (setq t1 0 time (aref ltimes level))
1369 (loop for l from level to (1- lmax) do
1370 (aset ltimes l 0))
1371 (goto-char (match-beginning 0))
1372 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
1373 (setq org-clock-file-total-minutes (aref ltimes 0)))
1374 (set-buffer-modified-p bmp)))
1376 (defun org-clock-sum-current-item (&optional tstart)
1377 "Returns time, clocked on current item in total"
1378 (save-excursion
1379 (save-restriction
1380 (org-narrow-to-subtree)
1381 (org-clock-sum tstart)
1382 org-clock-file-total-minutes)))
1384 (defun org-clock-display (&optional total-only)
1385 "Show subtree times in the entire buffer.
1386 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1387 in the echo area."
1388 (interactive)
1389 (org-clock-remove-overlays)
1390 (let (time h m p)
1391 (org-clock-sum)
1392 (unless total-only
1393 (save-excursion
1394 (goto-char (point-min))
1395 (while (or (and (equal (setq p (point)) (point-min))
1396 (get-text-property p :org-clock-minutes))
1397 (setq p (next-single-property-change
1398 (point) :org-clock-minutes)))
1399 (goto-char p)
1400 (when (setq time (get-text-property p :org-clock-minutes))
1401 (org-clock-put-overlay time (funcall outline-level))))
1402 (setq h (/ org-clock-file-total-minutes 60)
1403 m (- org-clock-file-total-minutes (* 60 h)))
1404 ;; Arrange to remove the overlays upon next change.
1405 (when org-remove-highlights-with-change
1406 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1407 nil 'local))))
1408 (if org-time-clocksum-use-fractional
1409 (message (concat "Total file time: " org-time-clocksum-fractional-format
1410 " (%d hours and %d minutes)")
1411 (/ (+ (* h 60.0) m) 60.0) h m)
1412 (message (concat "Total file time: " org-time-clocksum-format
1413 " (%d hours and %d minutes)") h m h m))))
1415 (defvar org-clock-overlays nil)
1416 (make-variable-buffer-local 'org-clock-overlays)
1418 (defun org-clock-put-overlay (time &optional level)
1419 "Put an overlays on the current line, displaying TIME.
1420 If LEVEL is given, prefix time with a corresponding number of stars.
1421 This creates a new overlay and stores it in `org-clock-overlays', so that it
1422 will be easy to remove."
1423 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1424 (l (if level (org-get-valid-level level 0) 0))
1425 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1426 org-time-clocksum-fractional-format
1427 org-time-clocksum-format) "%s"))
1428 (off 0)
1429 ov tx)
1430 (org-move-to-column c)
1431 (unless (eolp) (skip-chars-backward "^ \t"))
1432 (skip-chars-backward " \t")
1433 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
1434 tx (concat (buffer-substring (1- (point)) (point))
1435 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1436 (org-add-props (if org-time-clocksum-use-fractional
1437 (format fmt
1438 (make-string l ?*)
1439 (/ (+ (* h 60.0) m) 60.0)
1440 (make-string (- 16 l) ?\ ))
1441 (format fmt
1442 (make-string l ?*) h m
1443 (make-string (- 16 l) ?\ )))
1444 (list 'face 'org-clock-overlay))
1445 ""))
1446 (if (not (featurep 'xemacs))
1447 (org-overlay-put ov 'display tx)
1448 (org-overlay-put ov 'invisible t)
1449 (org-overlay-put ov 'end-glyph (make-glyph tx)))
1450 (push ov org-clock-overlays)))
1452 (defun org-clock-remove-overlays (&optional beg end noremove)
1453 "Remove the occur highlights from the buffer.
1454 BEG and END are ignored. If NOREMOVE is nil, remove this function
1455 from the `before-change-functions' in the current buffer."
1456 (interactive)
1457 (unless org-inhibit-highlight-removal
1458 (mapc 'org-delete-overlay org-clock-overlays)
1459 (setq org-clock-overlays nil)
1460 (unless noremove
1461 (remove-hook 'before-change-functions
1462 'org-clock-remove-overlays 'local))))
1464 (defvar state) ;; dynamically scoped into this function
1465 (defun org-clock-out-if-current ()
1466 "Clock out if the current entry contains the running clock.
1467 This is used to stop the clock after a TODO entry is marked DONE,
1468 and is only done if the variable `org-clock-out-when-done' is not nil."
1469 (when (and org-clock-out-when-done
1470 (or (and (eq t org-clock-out-when-done)
1471 (member state org-done-keywords))
1472 (and (listp org-clock-out-when-done)
1473 (member state org-clock-out-when-done)))
1474 (equal (or (buffer-base-buffer (org-clocking-buffer))
1475 (org-clocking-buffer))
1476 (or (buffer-base-buffer (current-buffer))
1477 (current-buffer)))
1478 (< (point) org-clock-marker)
1479 (> (save-excursion (outline-next-heading) (point))
1480 org-clock-marker))
1481 ;; Clock out, but don't accept a logging message for this.
1482 (let ((org-log-note-clock-out nil)
1483 (org-clock-out-switch-to-state nil))
1484 (org-clock-out))))
1486 (add-hook 'org-after-todo-state-change-hook
1487 'org-clock-out-if-current)
1489 ;;;###autoload
1490 (defun org-get-clocktable (&rest props)
1491 "Get a formatted clocktable with parameters according to PROPS.
1492 The table is created in a temporary buffer, fully formatted and
1493 fontified, and then returned."
1494 ;; Set the defaults
1495 (setq props (plist-put props :name "clocktable"))
1496 (unless (plist-member props :maxlevel)
1497 (setq props (plist-put props :maxlevel 2)))
1498 (unless (plist-member props :scope)
1499 (setq props (plist-put props :scope 'agenda)))
1500 (with-temp-buffer
1501 (org-mode)
1502 (org-create-dblock props)
1503 (org-update-dblock)
1504 (font-lock-fontify-buffer)
1505 (forward-line 2)
1506 (buffer-substring (point) (progn
1507 (re-search-forward "^#\\+END" nil t)
1508 (point-at-bol)))))
1510 (defun org-clock-report (&optional arg)
1511 "Create a table containing a report about clocked time.
1512 If the cursor is inside an existing clocktable block, then the table
1513 will be updated. If not, a new clocktable will be inserted.
1514 When called with a prefix argument, move to the first clock table in the
1515 buffer and update it."
1516 (interactive "P")
1517 (org-clock-remove-overlays)
1518 (when arg
1519 (org-find-dblock "clocktable")
1520 (org-show-entry))
1521 (if (org-in-clocktable-p)
1522 (goto-char (org-in-clocktable-p))
1523 (org-create-dblock (append (list :name "clocktable")
1524 org-clock-clocktable-default-properties)))
1525 (org-update-dblock))
1527 (defun org-in-clocktable-p ()
1528 "Check if the cursor is in a clocktable."
1529 (let ((pos (point)) start)
1530 (save-excursion
1531 (end-of-line 1)
1532 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
1533 (setq start (match-beginning 0))
1534 (re-search-forward "^#\\+END:.*" nil t)
1535 (>= (match-end 0) pos)
1536 start))))
1538 (defun org-clock-special-range (key &optional time as-strings)
1539 "Return two times bordering a special time range.
1540 Key is a symbol specifying the range and can be one of `today', `yesterday',
1541 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1542 A week starts Monday 0:00 and ends Sunday 24:00.
1543 The range is determined relative to TIME. TIME defaults to the current time.
1544 The return value is a cons cell with two internal times like the ones
1545 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1546 the returned times will be formatted strings."
1547 (if (integerp key) (setq key (intern (number-to-string key))))
1548 (let* ((tm (decode-time (or time (current-time))))
1549 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1550 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1551 (dow (nth 6 tm))
1552 (skey (symbol-name key))
1553 (shift 0)
1554 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
1555 (cond
1556 ((string-match "^[0-9]+$" skey)
1557 (setq y (string-to-number skey) m 1 d 1 key 'year))
1558 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1559 (setq y (string-to-number (match-string 1 skey))
1560 month (string-to-number (match-string 2 skey))
1561 d 1 key 'month))
1562 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1563 (require 'cal-iso)
1564 (setq y (string-to-number (match-string 1 skey))
1565 w (string-to-number (match-string 2 skey)))
1566 (setq date (calendar-gregorian-from-absolute
1567 (calendar-absolute-from-iso (list w 1 y))))
1568 (setq d (nth 1 date) month (car date) y (nth 2 date)
1569 dow 1
1570 key 'week))
1571 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1572 (setq y (string-to-number (match-string 1 skey))
1573 month (string-to-number (match-string 2 skey))
1574 d (string-to-number (match-string 3 skey))
1575 key 'day))
1576 ((string-match "\\([-+][0-9]+\\)$" skey)
1577 (setq shift (string-to-number (match-string 1 skey))
1578 key (intern (substring skey 0 (match-beginning 1))))))
1579 (when (= shift 0)
1580 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1581 ((eq key 'lastweek) (setq key 'week shift -1))
1582 ((eq key 'lastmonth) (setq key 'month shift -1))
1583 ((eq key 'lastyear) (setq key 'year shift -1))))
1584 (cond
1585 ((memq key '(day today))
1586 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1587 ((memq key '(week thisweek))
1588 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1589 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1590 ((memq key '(month thismonth))
1591 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1592 ((memq key '(year thisyear))
1593 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1594 (t (error "No such time block %s" key)))
1595 (setq ts (encode-time s m h d month y)
1596 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1597 (or d1 d) (or month1 month) (or y1 y)))
1598 (setq fm (cdr org-time-stamp-formats))
1599 (cond
1600 ((memq key '(day today))
1601 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1602 ((memq key '(week thisweek))
1603 (setq txt (format-time-string "week %G-W%V" ts)))
1604 ((memq key '(month thismonth))
1605 (setq txt (format-time-string "%B %Y" ts)))
1606 ((memq key '(year thisyear))
1607 (setq txt (format-time-string "the year %Y" ts))))
1608 (if as-strings
1609 (list (format-time-string fm ts) (format-time-string fm te) txt)
1610 (list ts te txt))))
1612 (defun org-clocktable-shift (dir n)
1613 "Try to shift the :block date of the clocktable at point.
1614 Point must be in the #+BEGIN: line of a clocktable, or this function
1615 will throw an error.
1616 DIR is a direction, a symbol `left', `right', `up', or `down'.
1617 Both `left' and `down' shift the block toward the past, `up' and `right'
1618 push it toward the future.
1619 N is the number of shift steps to take. The size of the step depends on
1620 the currently selected interval size."
1621 (setq n (prefix-numeric-value n))
1622 (and (memq dir '(left down)) (setq n (- n)))
1623 (save-excursion
1624 (goto-char (point-at-bol))
1625 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1626 (error "Line needs a :block definition before this command works")
1627 (let* ((b (match-beginning 1)) (e (match-end 1))
1628 (s (match-string 1))
1629 block shift ins y mw d date wp m)
1630 (cond
1631 ((equal s "yesterday") (setq s "today-1"))
1632 ((equal s "lastweek") (setq s "thisweek-1"))
1633 ((equal s "lastmonth") (setq s "thismonth-1"))
1634 ((equal s "lastyear") (setq s "thisyear-1")))
1635 (cond
1636 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
1637 (setq block (match-string 1 s)
1638 shift (if (match-end 2)
1639 (string-to-number (match-string 2 s))
1641 (setq shift (+ shift n))
1642 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1643 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1644 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1645 (setq y (string-to-number (match-string 1 s))
1646 wp (and (match-end 3) (match-string 3 s))
1647 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1648 d (and (match-end 6) (string-to-number (match-string 6 s))))
1649 (cond
1650 (d (setq ins (format-time-string
1651 "%Y-%m-%d"
1652 (encode-time 0 0 0 (+ d n) m y))))
1653 ((and wp mw (> (length wp) 0))
1654 (require 'cal-iso)
1655 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1656 (setq ins (format-time-string
1657 "%G-W%V"
1658 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1660 (setq ins (format-time-string
1661 "%Y-%m"
1662 (encode-time 0 0 0 1 (+ mw n) y))))
1664 (setq ins (number-to-string (+ y n))))))
1665 (t (error "Cannot shift clocktable block")))
1666 (when ins
1667 (goto-char b)
1668 (insert ins)
1669 (delete-region (point) (+ (point) (- e b)))
1670 (beginning-of-line 1)
1671 (org-update-dblock)
1672 t)))))
1674 (defun org-dblock-write:clocktable (params)
1675 "Write the standard clocktable."
1676 (catch 'exit
1677 (let* ((hlchars '((1 . "*") (2 . "/")))
1678 (ins (make-marker))
1679 (total-time nil)
1680 (scope (plist-get params :scope))
1681 (tostring (plist-get params :tostring))
1682 (multifile (plist-get params :multifile))
1683 (header (plist-get params :header))
1684 (maxlevel (or (plist-get params :maxlevel) 3))
1685 (step (plist-get params :step))
1686 (emph (plist-get params :emphasize))
1687 (timestamp (plist-get params :timestamp))
1688 (ts (plist-get params :tstart))
1689 (te (plist-get params :tend))
1690 (block (plist-get params :block))
1691 (link (plist-get params :link))
1692 ipos time p level hlc hdl tsp props content recalc formula pcol
1693 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
1694 (setq org-clock-file-total-minutes nil)
1695 (when step
1696 (unless (or block (and ts te))
1697 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1698 (org-clocktable-steps params)
1699 (throw 'exit nil))
1700 (when block
1701 (setq cc (org-clock-special-range block nil t)
1702 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1703 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
1704 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
1705 (when (and ts (listp ts))
1706 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
1707 (when (and te (listp te))
1708 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
1709 ;; Now the times are strings we can parse.
1710 (if ts (setq ts (org-float-time
1711 (apply 'encode-time (org-parse-time-string ts)))))
1712 (if te (setq te (org-float-time
1713 (apply 'encode-time (org-parse-time-string te)))))
1714 (move-marker ins (point))
1715 (setq ipos (point))
1717 ;; Get the right scope
1718 (setq pos (point))
1719 (cond
1720 ((and scope (listp scope) (symbolp (car scope)))
1721 (setq scope (eval scope)))
1722 ((eq scope 'agenda)
1723 (setq scope (org-agenda-files t)))
1724 ((eq scope 'agenda-with-archives)
1725 (setq scope (org-agenda-files t))
1726 (setq scope (org-add-archive-files scope)))
1727 ((eq scope 'file-with-archives)
1728 (setq scope (org-add-archive-files (list (buffer-file-name)))
1729 rm-file-column t)))
1730 (setq scope-is-list (and scope (listp scope)))
1731 (save-restriction
1732 (cond
1733 ((not scope))
1734 ((eq scope 'file) (widen))
1735 ((eq scope 'subtree) (org-narrow-to-subtree))
1736 ((eq scope 'tree)
1737 (while (org-up-heading-safe))
1738 (org-narrow-to-subtree))
1739 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1740 (symbol-name scope)))
1741 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1742 (catch 'exit
1743 (while (org-up-heading-safe)
1744 (looking-at outline-regexp)
1745 (if (<= (org-reduced-level (funcall outline-level)) level)
1746 (throw 'exit nil))))
1747 (org-narrow-to-subtree))
1748 (scope-is-list
1749 (let* ((files scope)
1750 (scope 'agenda)
1751 (p1 (copy-sequence params))
1752 file)
1753 (setq p1 (plist-put p1 :tostring t))
1754 (setq p1 (plist-put p1 :multifile t))
1755 (setq p1 (plist-put p1 :scope 'file))
1756 (org-prepare-agenda-buffers files)
1757 (while (setq file (pop files))
1758 (with-current-buffer (find-buffer-visiting file)
1759 (setq tbl1 (org-dblock-write:clocktable p1))
1760 (when tbl1
1761 (push (org-clocktable-add-file
1762 file
1763 (concat "| |*File time*|*"
1764 (org-minutes-to-hh:mm-string
1765 org-clock-file-total-minutes)
1766 "*|\n"
1767 tbl1)) tbl)
1768 (setq total-time (+ (or total-time 0)
1769 org-clock-file-total-minutes))))))))
1770 (goto-char pos)
1772 (unless scope-is-list
1773 (org-clock-sum ts te)
1774 (goto-char (point-min))
1775 (setq st t)
1776 (while (or (and (bobp) (prog1 st (setq st nil))
1777 (get-text-property (point) :org-clock-minutes)
1778 (setq p (point-min)))
1779 (setq p (next-single-property-change (point) :org-clock-minutes)))
1780 (goto-char p)
1781 (when (setq time (get-text-property p :org-clock-minutes))
1782 (save-excursion
1783 (beginning-of-line 1)
1784 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1785 (setq level (org-reduced-level
1786 (- (match-end 1) (match-beginning 1))))
1787 (<= level maxlevel))
1788 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
1789 hdl (if (not link)
1790 (match-string 2)
1791 (org-make-link-string
1792 (format "file:%s::%s"
1793 (buffer-file-name)
1794 (save-match-data
1795 (org-make-org-heading-search-string
1796 (match-string 2))))
1797 (match-string 2)))
1798 tsp (when timestamp
1799 (setq props (org-entry-properties (point)))
1800 (or (cdr (assoc "SCHEDULED" props))
1801 (cdr (assoc "TIMESTAMP" props))
1802 (cdr (assoc "DEADLINE" props))
1803 (cdr (assoc "TIMESTAMP_IA" props)))))
1804 (if (and (not multifile) (= level 1)) (push "|-" tbl))
1805 (push (concat
1806 "| " (int-to-string level) "|"
1807 (if timestamp (concat tsp "|") "")
1808 hlc hdl hlc " |"
1809 (make-string (1- level) ?|)
1810 hlc (org-minutes-to-hh:mm-string time) hlc
1811 " |") tbl))))))
1812 (setq tbl (nreverse tbl))
1813 (if tostring
1814 (if tbl (mapconcat 'identity tbl "\n") nil)
1815 (goto-char ins)
1816 (insert-before-markers
1817 (or header
1818 (concat
1819 "Clock summary at ["
1820 (substring
1821 (format-time-string (cdr org-time-stamp-formats))
1822 1 -1)
1824 (if block (concat ", for " range-text ".") "")
1825 "\n\n"))
1826 (if scope-is-list "|File" "")
1827 "|L|" (if timestamp "Timestamp|" "") "Headline|Time|\n")
1828 (setq total-time (or total-time org-clock-file-total-minutes))
1829 (insert-before-markers
1830 "|-\n|"
1831 (if scope-is-list "|" "")
1832 (if timestamp "|Timestamp|" "|")
1833 "*Total time*| *"
1834 (org-minutes-to-hh:mm-string (or total-time 0))
1835 "*|\n|-\n")
1836 (setq tbl (delq nil tbl))
1837 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
1838 (equal (substring (car tbl) 0 2) "|-"))
1839 (pop tbl))
1840 (insert-before-markers (mapconcat
1841 'identity (delq nil tbl)
1842 (if scope-is-list "\n|-\n" "\n")))
1843 (backward-delete-char 1)
1844 (if (setq formula (plist-get params :formula))
1845 (cond
1846 ((eq formula '%)
1847 (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
1848 (insert
1849 (format
1850 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1851 pcol
1853 (+ 3 (if scope-is-list 1 0))
1854 (+ (if scope-is-list 1 0) 3)
1855 (1- pcol)))
1856 (setq recalc t))
1857 ((stringp formula)
1858 (insert "\n#+TBLFM: " formula)
1859 (setq recalc t))
1860 (t (error "invalid formula in clocktable")))
1861 ;; Should we rescue an old formula?
1862 (when (stringp (setq content (plist-get params :content)))
1863 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
1864 (setq recalc t)
1865 (insert "\n" (match-string 1 (plist-get params :content)))
1866 (beginning-of-line 0))))
1867 (goto-char ipos)
1868 (skip-chars-forward "^|")
1869 (org-table-align)
1870 (when recalc
1871 (if (eq formula '%)
1872 (save-excursion (org-table-goto-column pcol nil 'force)
1873 (insert "%")))
1874 (org-table-recalculate 'all))
1875 (when rm-file-column
1876 (forward-char 1)
1877 (org-table-delete-column)))))))
1879 (defun org-clocktable-steps (params)
1880 (let* ((p1 (copy-sequence params))
1881 (ts (plist-get p1 :tstart))
1882 (te (plist-get p1 :tend))
1883 (step0 (plist-get p1 :step))
1884 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
1885 (block (plist-get p1 :block))
1886 cc range-text)
1887 (when block
1888 (setq cc (org-clock-special-range block nil t)
1889 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1890 (if ts (setq ts (org-float-time
1891 (apply 'encode-time (org-parse-time-string ts)))))
1892 (if te (setq te (org-float-time
1893 (apply 'encode-time (org-parse-time-string te)))))
1894 (setq p1 (plist-put p1 :header ""))
1895 (setq p1 (plist-put p1 :step nil))
1896 (setq p1 (plist-put p1 :block nil))
1897 (while (< ts te)
1898 (or (bolp) (insert "\n"))
1899 (setq p1 (plist-put p1 :tstart (format-time-string
1900 (org-time-stamp-format nil t)
1901 (seconds-to-time ts))))
1902 (setq p1 (plist-put p1 :tend (format-time-string
1903 (org-time-stamp-format nil t)
1904 (seconds-to-time (setq ts (+ ts step))))))
1905 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
1906 (plist-get p1 :tstart) "\n")
1907 (org-dblock-write:clocktable p1)
1908 (re-search-forward "#\\+END:")
1909 (end-of-line 0))))
1911 (defun org-clocktable-add-file (file table)
1912 (if table
1913 (let ((lines (org-split-string table "\n"))
1914 (ff (file-name-nondirectory file)))
1915 (mapconcat 'identity
1916 (mapcar (lambda (x)
1917 (if (string-match org-table-dataline-regexp x)
1918 (concat "|" ff x)
1920 lines)
1921 "\n"))))
1923 (defun org-clock-time% (total &rest strings)
1924 "Compute a time fraction in percent.
1925 TOTAL s a time string like 10:21 specifying the total times.
1926 STRINGS is a list of strings that should be checked for a time.
1927 The first string that does have a time will be used.
1928 This function is made for clock tables."
1929 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1930 tot s)
1931 (save-match-data
1932 (catch 'exit
1933 (if (not (string-match re total))
1934 (throw 'exit 0.)
1935 (setq tot (+ (string-to-number (match-string 2 total))
1936 (* 60 (string-to-number (match-string 1 total)))))
1937 (if (= tot 0.) (throw 'exit 0.)))
1938 (while (setq s (pop strings))
1939 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
1940 (throw 'exit
1941 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
1942 (* 60 (string-to-number (match-string 1 s)))))
1943 tot))))
1944 0))))
1946 (defvar org-clock-loaded nil
1947 "Was the clock file loaded?")
1949 (defun org-clock-save ()
1950 "Persist various clock-related data to disk.
1951 The details of what will be saved are regulated by the variable
1952 `org-clock-persist'."
1953 (when (and org-clock-persist
1954 (or org-clock-loaded
1955 org-clock-has-been-used
1956 (not (file-exists-p org-clock-persist-file))))
1957 (let (b)
1958 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
1959 (progn
1960 (delete-region (point-min) (point-max))
1961 ;;Store clock
1962 (insert (format ";; org-persist.el - %s at %s\n"
1963 system-name (format-time-string
1964 (cdr org-time-stamp-formats))))
1965 (if (and (memq org-clock-persist '(t clock))
1966 (setq b (org-clocking-buffer))
1967 (setq b (or (buffer-base-buffer b) b))
1968 (buffer-live-p b)
1969 (buffer-file-name b)
1970 (or (not org-clock-persist-query-save)
1971 (y-or-n-p (concat "Save current clock ("
1972 (substring-no-properties org-clock-heading)
1973 ") "))))
1974 (insert "(setq resume-clock '(\""
1975 (buffer-file-name (org-clocking-buffer))
1976 "\" . " (int-to-string (marker-position org-clock-marker))
1977 "))\n"))
1978 ;; Store clocked task history. Tasks are stored reversed to make
1979 ;; reading simpler
1980 (when (and (memq org-clock-persist '(t history))
1981 org-clock-history)
1982 (insert
1983 "(setq stored-clock-history '("
1984 (mapconcat
1985 (lambda (m)
1986 (when (and (setq b (marker-buffer m))
1987 (setq b (or (buffer-base-buffer b) b))
1988 (buffer-live-p b)
1989 (buffer-file-name b))
1990 (concat "(\"" (buffer-file-name b)
1991 "\" . " (int-to-string (marker-position m))
1992 ")")))
1993 (reverse org-clock-history) " ") "))\n"))
1994 (save-buffer)
1995 (kill-buffer (current-buffer)))))))
1997 (defun org-clock-load ()
1998 "Load clock-related data from disk, maybe resuming a stored clock."
1999 (when (and org-clock-persist (not org-clock-loaded))
2000 (let ((filename (expand-file-name org-clock-persist-file))
2001 (org-clock-in-resume 'auto-restart)
2002 resume-clock stored-clock-history)
2003 (if (not (file-readable-p filename))
2004 (message "Not restoring clock data; %s not found"
2005 org-clock-persist-file)
2006 (message "%s" "Restoring clock data")
2007 (setq org-clock-loaded t)
2008 (load-file filename)
2009 ;; load history
2010 (when stored-clock-history
2011 (save-window-excursion
2012 (mapc (lambda (task)
2013 (if (file-exists-p (car task))
2014 (org-clock-history-push (cdr task)
2015 (find-file (car task)))))
2016 stored-clock-history)))
2017 ;; resume clock
2018 (when (and resume-clock org-clock-persist
2019 (file-exists-p (car resume-clock))
2020 (or (not org-clock-persist-query-resume)
2021 (y-or-n-p
2022 (concat
2023 "Resume clock ("
2024 (with-current-buffer (find-file (car resume-clock))
2025 (save-excursion
2026 (goto-char (cdr resume-clock))
2027 (org-back-to-heading t)
2028 (and (looking-at org-complex-heading-regexp)
2029 (match-string 4))))
2030 ") "))))
2031 (when (file-exists-p (car resume-clock))
2032 (with-current-buffer (find-file (car resume-clock))
2033 (goto-char (cdr resume-clock))
2034 (let ((org-clock-auto-clock-resolution nil))
2035 (org-clock-in)
2036 (if (org-invisible-p)
2037 (org-show-context))))))))))
2039 ;;;###autoload
2040 (defun org-clock-persistence-insinuate ()
2041 "Set up hooks for clock persistence"
2042 (add-hook 'org-mode-hook 'org-clock-load)
2043 (add-hook 'kill-emacs-hook 'org-clock-save))
2045 ;; Suggested bindings
2046 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2048 (provide 'org-clock)
2050 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2052 ;;; org-clock.el ends here