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