Release 6.28e
[org-mode/org-tableheadings.git] / lisp / org-clock.el
blobeff1d946b76703debfca8c1c83246f807331ed51
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.28e
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the time clocking code for Org-mode
31 (require 'org)
32 (eval-when-compile
33 (require 'cl)
34 (require 'calendar))
36 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
37 (defvar org-time-stamp-formats)
39 (defgroup org-clock nil
40 "Options concerning clocking working time in Org-mode."
41 :tag "Org Clock"
42 :group 'org-progress)
44 (defcustom org-clock-into-drawer org-log-into-drawer
45 "Should clocking info be wrapped into a drawer?
46 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
47 If necessary, the drawer will be created.
48 When nil, the drawer will not be created, but used when present.
49 When an integer and the number of clocking entries in an item
50 reaches or exceeds this number, a drawer will be created.
51 When a string, it names the drawer to be used.
53 The default for this variable is the value of `org-log-into-drawer',
54 which see."
55 :group 'org-todo
56 :group 'org-clock
57 :type '(choice
58 (const :tag "Always" t)
59 (const :tag "Only when drawer exists" nil)
60 (integer :tag "When at least N clock entries")
61 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
62 (string :tag "Into Drawer named...")))
64 (defcustom org-clock-out-when-done t
65 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
66 A nil value means, clock will keep running until stopped explicitly with
67 `C-c C-x C-o', or until the clock is started in a different item."
68 :group 'org-clock
69 :type 'boolean)
71 (defcustom org-clock-out-remove-zero-time-clocks nil
72 "Non-nil means, remove the clock line when the resulting time is zero."
73 :group 'org-clock
74 :type 'boolean)
76 (defcustom org-clock-in-switch-to-state nil
77 "Set task to a special todo state while clocking it.
78 The value should be the state to which the entry should be
79 switched. If the value is a function, it must take one
80 parameter (the current TODO state of the item) and return the
81 state to switch it to."
82 :group 'org-clock
83 :group 'org-todo
84 :type '(choice
85 (const :tag "Don't force a state" nil)
86 (string :tag "State")
87 (symbol :tag "Function")))
89 (defcustom org-clock-out-switch-to-state nil
90 "Set task to a special todo state after clocking out.
91 The value should be the state to which the entry should be
92 switched. If the value is a function, it must take one
93 parameter (the current TODO state of the item) and return the
94 state to switch it to."
95 :group 'org-clock
96 :group 'org-todo
97 :type '(choice
98 (const :tag "Don't force a state" nil)
99 (string :tag "State")
100 (symbol :tag "Function")))
102 (defcustom org-clock-history-length 5
103 "Number of clock tasks to remember in history."
104 :group 'org-clock
105 :type 'integer)
107 (defcustom org-clock-goto-may-find-recent-task t
108 "Non-nil means, `org-clock-goto' can go to recent task if no active clock."
109 :group 'org-clock
110 :type 'boolean)
112 (defcustom org-clock-heading-function nil
113 "When non-nil, should be a function to create `org-clock-heading'.
114 This is the string shown in the mode line when a clock is running.
115 The function is called with point at the beginning of the headline."
116 :group 'org-clock
117 :type 'function)
119 (defcustom org-clock-string-limit 0
120 "Maximum length of clock strings in the modeline. 0 means no limit."
121 :group 'org-clock
122 :type 'integer)
124 (defcustom org-clock-in-resume nil
125 "If non-nil, resume clock when clocking into task with open clock.
126 When clocking into a task with a clock entry which has not been closed,
127 the clock can be resumed from that point."
128 :group 'org-clock
129 :type 'boolean)
131 (defcustom org-clock-persist nil
132 "When non-nil, save the running clock when emacs is closed.
133 The clock is resumed when emacs restarts.
134 When this is t, both the running clock, and the entire clock
135 history are saved. When this is the symbol `clock', only the
136 running clock is saved.
138 When Emacs restarts with saved clock information, the file containing the
139 running clock as well as all files mentioned in the clock history will
140 be visited.
141 All this depends on running `org-clock-persistence-insinuate' in .emacs"
142 :group 'org-clock
143 :type '(choice
144 (const :tag "Just the running clock" clock)
145 (const :tag "Clock and history" t)
146 (const :tag "No persistence" nil)))
148 (defcustom org-clock-persist-file (convert-standard-filename
149 "~/.emacs.d/org-clock-save.el")
150 "File to save clock data to."
151 :group 'org-clock
152 :type 'string)
154 (defcustom org-clock-persist-query-save nil
155 "When non-nil, ask before saving the current clock on exit."
156 :group 'org-clock
157 :type 'boolean)
159 (defcustom org-clock-persist-query-resume t
160 "When non-nil, ask before resuming any stored clock during load."
161 :group 'org-clock
162 :type 'boolean)
164 (defcustom org-clock-sound nil
165 "Sound that will used for notifications.
166 Possible values:
168 nil no sound played.
169 t standard Emacs beep
170 file name play this sound file. If not possible, fall back to beep"
171 :group 'org-clock
172 :type '(choice
173 (const :tag "No sound" nil)
174 (const :tag "Standard beep" t)
175 (file :tag "Play sound file")))
177 (defcustom org-clock-modeline-total 'auto
178 "Default setting for the time included for the modeline clock.
179 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
180 Allowed values are:
182 current Only the time in the current instance of the clock
183 today All time clocked inot this task today
184 repeat All time clocked into this task since last repeat
185 all All time ever recorded for this task
186 auto Automtically, either `all', or `repeat' for repeating tasks"
187 :group 'org-clock
188 :type '(choice
189 (const :tag "Current clock" current)
190 (const :tag "Today's task time" today)
191 (const :tag "Since last repeat" repeat)
192 (const :tag "All task time" all)
193 (const :tag "Automatically, `all' or since `repeat'" auto)))
195 (defvar org-clock-in-hook nil
196 "Hook run when starting the clock.")
197 (defvar org-clock-out-hook nil
198 "Hook run when stopping the current clock.")
200 (defvar org-clock-cancel-hook nil
201 "Hook run when cancelling the current clock.")
202 (defvar org-clock-goto-hook nil
203 "Hook run when selecting the currently clocked-in entry.")
205 ;;; The clock for measuring work time.
207 (defvar org-mode-line-string "")
208 (put 'org-mode-line-string 'risky-local-variable t)
210 (defvar org-clock-mode-line-timer nil)
211 (defvar org-clock-heading "")
212 (defvar org-clock-heading-for-remember "")
213 (defvar org-clock-start-time "")
215 (defvar org-clock-effort ""
216 "Effort estimate of the currently clocking task")
218 (defvar org-clock-total-time nil
219 "Holds total time, spent previously on currently clocked item.
220 This does not include the time in the currently running clock.")
222 (defvar org-clock-history nil
223 "List of marker pointing to recent clocked tasks.")
225 (defvar org-clock-default-task (make-marker)
226 "Marker pointing to the default task that should clock time.
227 The clock can be made to switch to this task after clocking out
228 of a different task.")
230 (defvar org-clock-interrupted-task (make-marker)
231 "Marker pointing to the task that has been interrupted by the current clock.")
233 (defvar org-clock-mode-line-map (make-sparse-keymap))
234 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
235 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
237 (defun org-clock-menu ()
238 (interactive)
239 (popup-menu
240 '("Clock"
241 ["Clock out" org-clock-out t]
242 ["Change effort estimate" org-clock-modify-effort-estimate t]
243 ["Go to clock entry" org-clock-goto t]
244 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
246 (defun org-clock-history-push (&optional pos buffer)
247 "Push a marker to the clock history."
248 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
249 (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
250 (while (setq n (member m org-clock-history))
251 (move-marker (car n) nil))
252 (setq org-clock-history
253 (delq nil
254 (mapcar (lambda (x) (if (marker-buffer x) x nil))
255 org-clock-history)))
256 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
257 (setq org-clock-history
258 (nreverse
259 (nthcdr (- l org-clock-history-length -1)
260 (nreverse org-clock-history)))))
261 (push m org-clock-history)))
263 (defun org-clock-save-markers-for-cut-and-paste (beg end)
264 "Save relative positions of markers in region."
265 (org-check-and-save-marker org-clock-marker beg end)
266 (org-check-and-save-marker org-clock-default-task beg end)
267 (org-check-and-save-marker org-clock-interrupted-task beg end)
268 (mapc (lambda (m) (org-check-and-save-marker m beg end))
269 org-clock-history))
271 (defun org-clock-select-task (&optional prompt)
272 "Select a task that recently was associated with clocking."
273 (interactive)
274 (let (sel-list rpl (i 0) s)
275 (save-window-excursion
276 (org-switch-to-buffer-other-window
277 (get-buffer-create "*Clock Task Select*"))
278 (erase-buffer)
279 (when (marker-buffer org-clock-default-task)
280 (insert (org-add-props "Default Task\n" nil 'face 'bold))
281 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
282 (push s sel-list))
283 (when (marker-buffer org-clock-interrupted-task)
284 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
285 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
286 (push s sel-list))
287 (when (marker-buffer org-clock-marker)
288 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
289 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
290 (push s sel-list))
291 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
292 (mapc
293 (lambda (m)
294 (when (marker-buffer m)
295 (setq i (1+ i)
296 s (org-clock-insert-selection-line
297 (if (< i 10)
298 (+ i ?0)
299 (+ i (- ?A 10))) m))
300 (push s sel-list)))
301 org-clock-history)
302 (org-fit-window-to-buffer)
303 (message (or prompt "Select task for clocking:"))
304 (setq rpl (read-char-exclusive))
305 (cond
306 ((eq rpl ?q) nil)
307 ((eq rpl ?x) nil)
308 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
309 (t (error "Invalid task choice %c" rpl))))))
311 (defun org-clock-insert-selection-line (i marker)
312 "Insert a line for the clock selection menu.
313 And return a cons cell with the selection character integer and the marker
314 pointing to it."
315 (when (marker-buffer marker)
316 (let (file cat task heading prefix)
317 (with-current-buffer (org-base-buffer (marker-buffer marker))
318 (save-excursion
319 (save-restriction
320 (widen)
321 (goto-char marker)
322 (setq file (buffer-file-name (marker-buffer marker))
323 cat (or (org-get-category)
324 (progn (org-refresh-category-properties)
325 (org-get-category)))
326 heading (org-get-heading 'notags)
327 prefix (save-excursion
328 (org-back-to-heading t)
329 (looking-at "\\*+ ")
330 (match-string 0))
331 task (substring
332 (org-fontify-like-in-org-mode
333 (concat prefix heading)
334 org-odd-levels-only)
335 (length prefix))))))
336 (when (and cat task)
337 (insert (format "[%c] %-15s %s\n" i cat task))
338 (cons i marker)))))
340 (defun org-clock-get-clock-string ()
341 "Form a clock-string, that will be show in the mode line.
342 If an effort estimate was defined for current item, use
343 01:30/01:50 format (clocked/estimated).
344 If not, show simply the clocked time like 01:50."
345 (let* ((clocked-time (org-clock-get-clocked-time))
346 (h (floor clocked-time 60))
347 (m (- clocked-time (* 60 h)))
349 (if (and org-clock-effort)
350 (let* ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
351 (effort-h (floor effort-in-minutes 60))
352 (effort-m (- effort-in-minutes (* effort-h 60)))
354 (format (concat "-[" org-time-clocksum-format "/" org-time-clocksum-format " (%s)]")
355 h m effort-h effort-m org-clock-heading)
357 (format (concat "-[" org-time-clocksum-format " (%s)]")
358 h m org-clock-heading))
361 (defun org-clock-update-mode-line ()
362 (setq org-mode-line-string
363 (org-propertize
364 (let ((clock-string (org-clock-get-clock-string))
365 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
366 (if (and (> org-clock-string-limit 0)
367 (> (length clock-string) org-clock-string-limit))
368 (org-propertize (substring clock-string 0 org-clock-string-limit)
369 'help-echo (concat help-text ": " org-clock-heading))
370 (org-propertize clock-string 'help-echo help-text)))
371 'local-map org-clock-mode-line-map
372 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
373 'face 'org-mode-line-clock))
374 (if org-clock-effort (org-clock-notify-once-if-expired))
375 (force-mode-line-update))
377 (defun org-clock-get-clocked-time ()
378 "Get the clocked time for the current item in minutes.
379 The time returned includes the the time spent on this task in
380 previous clocking intervals."
381 (let ((currently-clocked-time
382 (floor (- (time-to-seconds (current-time))
383 (time-to-seconds org-clock-start-time)) 60)))
384 (+ currently-clocked-time (or org-clock-total-time 0))))
386 (defun org-clock-modify-effort-estimate (&optional value)
387 "Add to or set the effort estimate of the item currently being clocked.
388 VALUE can be a number of minutes, or a string with forat hh:mm or mm.
389 WHen the strig starts with a + or a - sign, the current value of the effort
390 property will be changed by that amount.
391 This will update the \"Effort\" property of currently clocked item, and
392 the mode line."
393 (interactive)
394 (when (org-clock-is-active)
395 (let ((current org-clock-effort) sign)
396 (unless value
397 ;; Prompt user for a value or a change
398 (setq value
399 (read-string
400 (format "Set effort (hh:mm or mm%s): "
401 (if current
402 (format ", prefix + to add to %s" org-clock-effort)
403 "")))))
404 (when (stringp value)
405 ;; A string. See if it is a delta
406 (setq sign (string-to-char value))
407 (if (member sign '(?- ?+))
408 (setq current (org-hh:mm-string-to-minutes (substring current 1)))
409 (setq current 0))
410 (setq value (org-hh:mm-string-to-minutes value))
411 (if (equal ?- sign)
412 (setq value (- current value))
413 (if (equal ?+ sign) (setq value (+ current value)))))
414 (setq value (max 0 value)
415 org-clock-effort (org-minutes-to-hh:mm-string value))
416 (org-entry-put org-clock-marker "Effort" org-clock-effort)
417 (org-clock-update-mode-line))))
419 (defvar org-clock-notification-was-shown nil
420 "Shows if we have shown notification already.")
422 (defun org-clock-notify-once-if-expired ()
423 "Show notification if we spent more time then we estimated before.
424 Notification is shown only once."
425 (when (marker-buffer org-clock-marker)
426 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
427 (clocked-time (org-clock-get-clocked-time)))
428 (if (>= clocked-time effort-in-minutes)
429 (unless org-clock-notification-was-shown
430 (setq org-clock-notification-was-shown t)
431 (org-clock-play-sound)
432 (org-show-notification
433 (format "Task '%s' should be finished by now. (%s)"
434 org-clock-heading org-clock-effort)))
435 (setq org-clock-notification-was-shown nil)))))
437 (defun org-show-notification (notification)
438 "Show notification. Use libnotify, if available."
439 (if (org-program-exists "notify-send")
440 (start-process "emacs-timer-notification" nil "notify-send" notification))
441 ;; In any case, show in message area
442 (message notification))
444 (defun org-clock-play-sound ()
445 "Play sound as configured by `org-clock-sound'.
446 Use alsa's aplay tool if available."
447 (cond
448 ((not org-clock-sound))
449 ((eq org-clock-sound t) (beep t) (beep t))
450 ((stringp org-clock-sound)
451 (if (file-exists-p org-clock-sound)
452 (if (org-program-exists "aplay")
453 (start-process "org-clock-play-notification" nil
454 "aplay" org-clock-sound)
455 (condition-case nil
456 (play-sound-file org-clock-sound)
457 (error (beep t) (beep t))))))))
459 (defun org-program-exists (program-name)
460 "Checks whenever we can locate program and launch it."
461 (if (eq system-type 'gnu/linux)
462 (= 0 (call-process "which" nil nil nil program-name))
466 (defvar org-clock-mode-line-entry nil
467 "Information for the modeline about the running clock.")
469 (defun org-clock-in (&optional select)
470 "Start the clock on the current item.
471 If necessary, clock-out of the currently active clock.
472 With prefix arg SELECT, offer a list of recently clocked tasks to
473 clock into. When SELECT is `C-u C-u', clock into the current task and mark
474 is as the default task, a special task that will always be offered in
475 the clocking selection, associated with the letter `d'."
476 (interactive "P")
477 (setq org-clock-notification-was-shown nil)
478 (catch 'abort
479 (let ((interrupting (marker-buffer org-clock-marker))
480 ts selected-task target-pos (msg-extra ""))
481 (when (equal select '(4))
482 (setq selected-task (org-clock-select-task "Clock-in on task: "))
483 (if selected-task
484 (setq selected-task (copy-marker selected-task))
485 (error "Abort")))
486 (when interrupting
487 ;; We are interrupting the clocking of a different task.
488 ;; Save a marker to this task, so that we can go back.
489 (move-marker org-clock-interrupted-task
490 (marker-position org-clock-marker)
491 (marker-buffer org-clock-marker))
492 (org-clock-out t))
494 (when (equal select '(16))
495 ;; Mark as default clocking task
496 (org-clock-mark-default-task))
498 (setq target-pos (point)) ;; we want to clock in at this location
499 (save-excursion
500 (when (and selected-task (marker-buffer selected-task))
501 ;; There is a selected task, move to the correct buffer
502 ;; and set the new target position.
503 (set-buffer (org-base-buffer (marker-buffer selected-task)))
504 (setq target-pos (marker-position selected-task))
505 (move-marker selected-task nil))
506 (save-excursion
507 (save-restriction
508 (widen)
509 (goto-char target-pos)
510 (org-back-to-heading t)
511 (or interrupting (move-marker org-clock-interrupted-task nil))
512 (org-clock-history-push)
513 (cond ((functionp org-clock-in-switch-to-state)
514 (looking-at org-complex-heading-regexp)
515 (let ((newstate (funcall org-clock-in-switch-to-state
516 (match-string 2))))
517 (if newstate (org-todo newstate))))
518 ((and org-clock-in-switch-to-state
519 (not (looking-at (concat outline-regexp "[ \t]*"
520 org-clock-in-switch-to-state
521 "\\>"))))
522 (org-todo org-clock-in-switch-to-state)))
523 (setq org-clock-heading-for-remember
524 (and (looking-at org-complex-heading-regexp)
525 (match-end 4)
526 (org-trim (buffer-substring (match-end 1)
527 (match-end 4)))))
528 (setq org-clock-heading
529 (cond ((and org-clock-heading-function
530 (functionp org-clock-heading-function))
531 (funcall org-clock-heading-function))
532 ((looking-at org-complex-heading-regexp)
533 (match-string 4))
534 (t "???")))
535 (setq org-clock-heading (org-propertize org-clock-heading
536 'face nil))
537 (org-clock-find-position org-clock-in-resume)
538 (cond
539 ((and org-clock-in-resume
540 (looking-at
541 (concat "^[ \t]* " org-clock-string
542 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
543 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
544 (message "Matched %s" (match-string 1))
545 (setq ts (concat "[" (match-string 1) "]"))
546 (goto-char (match-end 1))
547 (setq org-clock-start-time
548 (apply 'encode-time
549 (org-parse-time-string (match-string 1))))
550 (setq org-clock-effort (org-get-effort))
551 (setq org-clock-total-time (org-clock-sum-current-item
552 (org-clock-get-sum-start))))
553 ((eq org-clock-in-resume 'auto-restart)
554 ;; called from org-clock-load during startup,
555 ;; do not interrupt, but warn!
556 (message "Cannot restart clock because task does not contain unfinished clock")
557 (ding)
558 (sit-for 2)
559 (throw 'abort nil))
561 (insert-before-markers "\n")
562 (backward-char 1)
563 (org-indent-line-function)
564 (when (and (save-excursion
565 (end-of-line 0)
566 (org-in-item-p)))
567 (beginning-of-line 1)
568 (org-indent-line-to (- (org-get-indentation) 2)))
569 (insert org-clock-string " ")
570 (setq org-clock-effort (org-get-effort))
571 (setq org-clock-total-time (org-clock-sum-current-item
572 (org-clock-get-sum-start)))
573 (setq org-clock-start-time (current-time))
574 (setq ts (org-insert-time-stamp org-clock-start-time
575 'with-hm 'inactive))))
576 (move-marker org-clock-marker (point) (buffer-base-buffer))
577 (or global-mode-string (setq global-mode-string '("")))
578 (or (memq 'org-mode-line-string global-mode-string)
579 (setq global-mode-string
580 (append global-mode-string '(org-mode-line-string))))
581 (org-clock-update-mode-line)
582 (setq org-clock-mode-line-timer
583 (run-with-timer 60 60 'org-clock-update-mode-line))
584 (message "Clock starts at %s - %s" ts msg-extra)
585 (run-hooks 'org-click-in-hook)))))))
587 (defun org-clock-mark-default-task ()
588 "Mark current task as default task."
589 (interactive)
590 (save-excursion
591 (org-back-to-heading t)
592 (move-marker org-clock-default-task (point))))
595 (defvar msg-extra)
596 (defun org-clock-get-sum-start ()
597 "Return the time from which clock times should be counted.
598 This is for the currently running clock as it is displayed
599 in the mode line. This function looks at the properties
600 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
601 corresponding variable `org-clock-modeline-total' and then
602 decides which time to use."
603 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
604 (symbol-name org-clock-modeline-total)))
605 (lr (org-entry-get nil "LAST_REPEAT")))
606 (cond
607 ((equal cmt "current")
608 (setq msg-extra "showing time in current clock instance")
609 (current-time))
610 ((equal cmt "today")
611 (setq msg-extra "showing today's task time.")
612 (let* ((dt (decode-time (current-time))))
613 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
614 (if org-extend-today-until
615 (setf (nth 2 dt) org-extend-today-until))
616 (apply 'encode-time dt)))
617 ((or (equal cmt "all")
618 (and (or (not cmt) (equal cmt "auto"))
619 (not lr)))
620 (setq msg-extra "showing entire task time.")
621 nil)
622 ((or (equal cmt "repeat")
623 (and (or (not cmt) (equal cmt "auto"))
624 lr))
625 (setq msg-extra "showing task time since last repeat.")
626 (if (not lr)
628 (org-time-string-to-time lr)))
629 (t nil))))
631 (defun org-clock-find-position (find-unclosed)
632 "Find the location where the next clock line should be inserted.
633 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
634 line and position cursor in that line."
635 (org-back-to-heading t)
636 (catch 'exit
637 (let ((beg (save-excursion
638 (beginning-of-line 2)
639 (or (bolp) (newline))
640 (point)))
641 (end (progn (outline-next-heading) (point)))
642 (re (concat "^[ \t]*" org-clock-string))
643 (cnt 0)
644 (drawer (if (stringp org-clock-into-drawer)
645 org-clock-into-drawer "LOGBOOK"))
646 first last ind-last)
647 (goto-char beg)
648 (when (and find-unclosed
649 (re-search-forward
650 (concat "^[ \t]* " org-clock-string
651 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
652 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
653 end t))
654 (beginning-of-line 1)
655 (throw 'exit t))
656 (when (eobp) (newline) (setq end (max (point) end)))
657 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
658 ;; we seem to have a CLOCK drawer, so go there.
659 (beginning-of-line 2)
660 (or org-log-states-order-reversed
661 (and (re-search-forward org-property-end-re nil t)
662 (goto-char (match-beginning 0))))
663 (throw 'exit t))
664 ;; Lets count the CLOCK lines
665 (goto-char beg)
666 (while (re-search-forward re end t)
667 (setq first (or first (match-beginning 0))
668 last (match-beginning 0)
669 cnt (1+ cnt)))
670 (when (and (integerp org-clock-into-drawer)
671 last
672 (>= (1+ cnt) org-clock-into-drawer))
673 ;; Wrap current entries into a new drawer
674 (goto-char last)
675 (setq ind-last (org-get-indentation))
676 (beginning-of-line 2)
677 (if (and (>= (org-get-indentation) ind-last)
678 (org-at-item-p))
679 (org-end-of-item))
680 (insert ":END:\n")
681 (beginning-of-line 0)
682 (org-indent-line-to ind-last)
683 (goto-char first)
684 (insert ":" drawer ":\n")
685 (beginning-of-line 0)
686 (org-indent-line-function)
687 (org-flag-drawer t)
688 (beginning-of-line 2)
689 (or org-log-states-order-reversed
690 (and (re-search-forward org-property-end-re nil t)
691 (goto-char (match-beginning 0))))
692 (throw 'exit nil))
694 (goto-char beg)
695 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
696 (not (equal (match-string 1) org-clock-string)))
697 ;; Planning info, skip to after it
698 (beginning-of-line 2)
699 (or (bolp) (newline)))
700 (when (or (eq org-clock-into-drawer t)
701 (stringp org-clock-into-drawer)
702 (and (integerp org-clock-into-drawer)
703 (< org-clock-into-drawer 2)))
704 (insert ":" drawer ":\n:END:\n")
705 (beginning-of-line -1)
706 (org-indent-line-function)
707 (org-flag-drawer t)
708 (beginning-of-line 2)
709 (org-indent-line-function)
710 (beginning-of-line)
711 (or org-log-states-order-reversed
712 (and (re-search-forward org-property-end-re nil t)
713 (goto-char (match-beginning 0))))))))
715 (defun org-clock-out (&optional fail-quietly)
716 "Stop the currently running clock.
717 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
718 (interactive)
719 (catch 'exit
720 (if (not (marker-buffer org-clock-marker))
721 (if fail-quietly (throw 'exit t) (error "No active clock")))
722 (let (ts te s h m remove)
723 (save-excursion
724 (set-buffer (marker-buffer org-clock-marker))
725 (save-restriction
726 (widen)
727 (goto-char org-clock-marker)
728 (beginning-of-line 1)
729 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
730 (equal (match-string 1) org-clock-string))
731 (setq ts (match-string 2))
732 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
733 (goto-char (match-end 0))
734 (delete-region (point) (point-at-eol))
735 (insert "--")
736 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
737 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
738 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
739 h (floor (/ s 3600))
740 s (- s (* 3600 h))
741 m (floor (/ s 60))
742 s (- s (* 60 s)))
743 (insert " => " (format "%2d:%02d" h m))
744 (when (setq remove (and org-clock-out-remove-zero-time-clocks
745 (= (+ h m) 0)))
746 (beginning-of-line 1)
747 (delete-region (point) (point-at-eol))
748 (and (looking-at "\n") (> (point-max) (1+ (point)))
749 (delete-char 1)))
750 (move-marker org-clock-marker nil)
751 (when org-log-note-clock-out
752 (org-add-log-setup 'clock-out nil nil nil nil
753 (concat "# Task: " (org-get-heading t) "\n\n")))
754 (when org-clock-mode-line-timer
755 (cancel-timer org-clock-mode-line-timer)
756 (setq org-clock-mode-line-timer nil))
757 (setq global-mode-string
758 (delq 'org-mode-line-string global-mode-string))
759 (when org-clock-out-switch-to-state
760 (save-excursion
761 (org-back-to-heading t)
762 (let ((org-inhibit-logging t))
763 (cond
764 ((functionp org-clock-out-switch-to-state)
765 (looking-at org-complex-heading-regexp)
766 (let ((newstate (funcall org-clock-out-switch-to-state
767 (match-string 2))))
768 (if newstate (org-todo newstate))))
769 ((and org-clock-out-switch-to-state
770 (not (looking-at (concat outline-regexp "[ \t]*"
771 org-clock-out-switch-to-state
772 "\\>"))))
773 (org-todo org-clock-out-switch-to-state))))))
774 (force-mode-line-update)
775 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
776 (if remove " => LINE REMOVED" ""))
777 (run-hooks 'org-clock-out-hook))))))
779 (defun org-clock-cancel ()
780 "Cancel the running clock be removing the start timestamp."
781 (interactive)
782 (if (not (marker-buffer org-clock-marker))
783 (error "No active clock"))
784 (save-excursion
785 (set-buffer (marker-buffer org-clock-marker))
786 (goto-char org-clock-marker)
787 (delete-region (1- (point-at-bol)) (point-at-eol)))
788 (setq global-mode-string
789 (delq 'org-mode-line-string global-mode-string))
790 (force-mode-line-update)
791 (message "Clock canceled")
792 (run-hooks 'org-clock-cancel-hook))
794 (defun org-clock-goto (&optional select)
795 "Go to the currently clocked-in entry, or to the most recently clocked one.
796 With prefix arg SELECT, offer recently clocked tasks for selection."
797 (interactive "@P")
798 (let* ((recent nil)
799 (m (cond
800 (select
801 (or (org-clock-select-task "Select task to go to: ")
802 (error "No task selected")))
803 ((marker-buffer org-clock-marker) org-clock-marker)
804 ((and org-clock-goto-may-find-recent-task
805 (car org-clock-history)
806 (marker-buffer (car org-clock-history)))
807 (setq recent t)
808 (car org-clock-history))
809 (t (error "No active or recent clock task")))))
810 (switch-to-buffer (marker-buffer m))
811 (if (or (< m (point-min)) (> m (point-max))) (widen))
812 (goto-char m)
813 (org-show-entry)
814 (org-back-to-heading)
815 (org-cycle-hide-drawers 'children)
816 (recenter)
817 (if recent
818 (message "No running clock, this is the most recently clocked task"))
819 (run-hooks 'org-clock-goto-hook)))
821 (defvar org-clock-file-total-minutes nil
822 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
823 (make-variable-buffer-local 'org-clock-file-total-minutes)
825 (defun org-clock-sum (&optional tstart tend)
826 "Sum the times for each subtree.
827 Puts the resulting times in minutes as a text property on each headline.
828 TSTART and TEND can mark a time range to be considered."
829 (interactive)
830 (let* ((bmp (buffer-modified-p))
831 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
832 org-clock-string
833 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
834 (lmax 30)
835 (ltimes (make-vector lmax 0))
836 (t1 0)
837 (level 0)
838 ts te dt
839 time)
840 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
841 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
842 (if (consp tstart) (setq tstart (time-to-seconds tstart)))
843 (if (consp tend) (setq tend (time-to-seconds tend)))
844 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
845 (save-excursion
846 (goto-char (point-max))
847 (while (re-search-backward re nil t)
848 (cond
849 ((match-end 2)
850 ;; Two time stamps
851 (setq ts (match-string 2)
852 te (match-string 3)
853 ts (time-to-seconds
854 (apply 'encode-time (org-parse-time-string ts)))
855 te (time-to-seconds
856 (apply 'encode-time (org-parse-time-string te)))
857 ts (if tstart (max ts tstart) ts)
858 te (if tend (min te tend) te)
859 dt (- te ts)
860 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
861 ((match-end 4)
862 ;; A naked time
863 (setq t1 (+ t1 (string-to-number (match-string 5))
864 (* 60 (string-to-number (match-string 4))))))
865 (t ;; A headline
866 (setq level (- (match-end 1) (match-beginning 1)))
867 (when (or (> t1 0) (> (aref ltimes level) 0))
868 (loop for l from 0 to level do
869 (aset ltimes l (+ (aref ltimes l) t1)))
870 (setq t1 0 time (aref ltimes level))
871 (loop for l from level to (1- lmax) do
872 (aset ltimes l 0))
873 (goto-char (match-beginning 0))
874 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
875 (setq org-clock-file-total-minutes (aref ltimes 0)))
876 (set-buffer-modified-p bmp)))
878 (defun org-clock-sum-current-item (&optional tstart)
879 "Returns time, clocked on current item in total"
880 (save-excursion
881 (save-restriction
882 (org-narrow-to-subtree)
883 (org-clock-sum tstart)
884 org-clock-file-total-minutes)))
886 (defun org-clock-display (&optional total-only)
887 "Show subtree times in the entire buffer.
888 If TOTAL-ONLY is non-nil, only show the total time for the entire file
889 in the echo area."
890 (interactive)
891 (org-clock-remove-overlays)
892 (let (time h m p)
893 (org-clock-sum)
894 (unless total-only
895 (save-excursion
896 (goto-char (point-min))
897 (while (or (and (equal (setq p (point)) (point-min))
898 (get-text-property p :org-clock-minutes))
899 (setq p (next-single-property-change
900 (point) :org-clock-minutes)))
901 (goto-char p)
902 (when (setq time (get-text-property p :org-clock-minutes))
903 (org-clock-put-overlay time (funcall outline-level))))
904 (setq h (/ org-clock-file-total-minutes 60)
905 m (- org-clock-file-total-minutes (* 60 h)))
906 ;; Arrange to remove the overlays upon next change.
907 (when org-remove-highlights-with-change
908 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
909 nil 'local))))
910 (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
912 (defvar org-clock-overlays nil)
913 (make-variable-buffer-local 'org-clock-overlays)
915 (defun org-clock-put-overlay (time &optional level)
916 "Put an overlays on the current line, displaying TIME.
917 If LEVEL is given, prefix time with a corresponding number of stars.
918 This creates a new overlay and stores it in `org-clock-overlays', so that it
919 will be easy to remove."
920 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
921 (l (if level (org-get-valid-level level 0) 0))
922 (fmt (concat "%s " org-time-clocksum-format "%s"))
923 (off 0)
924 ov tx)
925 (org-move-to-column c)
926 (unless (eolp) (skip-chars-backward "^ \t"))
927 (skip-chars-backward " \t")
928 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
929 tx (concat (buffer-substring (1- (point)) (point))
930 (make-string (+ off (max 0 (- c (current-column)))) ?.)
931 (org-add-props (format fmt
932 (make-string l ?*) h m
933 (make-string (- 16 l) ?\ ))
934 (list 'face 'org-clock-overlay))
935 ""))
936 (if (not (featurep 'xemacs))
937 (org-overlay-put ov 'display tx)
938 (org-overlay-put ov 'invisible t)
939 (org-overlay-put ov 'end-glyph (make-glyph tx)))
940 (push ov org-clock-overlays)))
942 (defun org-clock-remove-overlays (&optional beg end noremove)
943 "Remove the occur highlights from the buffer.
944 BEG and END are ignored. If NOREMOVE is nil, remove this function
945 from the `before-change-functions' in the current buffer."
946 (interactive)
947 (unless org-inhibit-highlight-removal
948 (mapc 'org-delete-overlay org-clock-overlays)
949 (setq org-clock-overlays nil)
950 (unless noremove
951 (remove-hook 'before-change-functions
952 'org-clock-remove-overlays 'local))))
954 (defvar state) ;; dynamically scoped into this function
955 (defun org-clock-out-if-current ()
956 "Clock out if the current entry contains the running clock.
957 This is used to stop the clock after a TODO entry is marked DONE,
958 and is only done if the variable `org-clock-out-when-done' is not nil."
959 (when (and org-clock-out-when-done
960 (member state org-done-keywords)
961 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker))
962 (marker-buffer org-clock-marker))
963 (or (buffer-base-buffer (current-buffer))
964 (current-buffer)))
965 (< (point) org-clock-marker)
966 (> (save-excursion (outline-next-heading) (point))
967 org-clock-marker))
968 ;; Clock out, but don't accept a logging message for this.
969 (let ((org-log-note-clock-out nil))
970 (org-clock-out))))
972 (add-hook 'org-after-todo-state-change-hook
973 'org-clock-out-if-current)
975 ;;;###autoload
976 (defun org-get-clocktable (&rest props)
977 "Get a formatted clocktable with parameters according to PROPS.
978 The table is created in a temporary buffer, fully formatted and
979 fontified, and then returned."
980 ;; Set the defaults
981 (setq props (plist-put props :name "clocktable"))
982 (unless (plist-member props :maxlevel)
983 (setq props (plist-put props :maxlevel 2)))
984 (unless (plist-member props :scope)
985 (setq props (plist-put props :scope 'agenda)))
986 (with-temp-buffer
987 (org-mode)
988 (org-create-dblock props)
989 (org-update-dblock)
990 (font-lock-fontify-buffer)
991 (forward-line 2)
992 (buffer-substring (point) (progn
993 (re-search-forward "^#\\+END" nil t)
994 (point-at-bol)))))
996 (defun org-clock-report (&optional arg)
997 "Create a table containing a report about clocked time.
998 If the cursor is inside an existing clocktable block, then the table
999 will be updated. If not, a new clocktable will be inserted.
1000 When called with a prefix argument, move to the first clock table in the
1001 buffer and update it."
1002 (interactive "P")
1003 (org-clock-remove-overlays)
1004 (when arg
1005 (org-find-dblock "clocktable")
1006 (org-show-entry))
1007 (if (org-in-clocktable-p)
1008 (goto-char (org-in-clocktable-p))
1009 (org-create-dblock (list :name "clocktable"
1010 :maxlevel 2 :scope 'file)))
1011 (org-update-dblock))
1013 (defun org-in-clocktable-p ()
1014 "Check if the cursor is in a clocktable."
1015 (let ((pos (point)) start)
1016 (save-excursion
1017 (end-of-line 1)
1018 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
1019 (setq start (match-beginning 0))
1020 (re-search-forward "^#\\+END:.*" nil t)
1021 (>= (match-end 0) pos)
1022 start))))
1024 (defun org-clock-special-range (key &optional time as-strings)
1025 "Return two times bordering a special time range.
1026 Key is a symbol specifying the range and can be one of `today', `yesterday',
1027 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1028 A week starts Monday 0:00 and ends Sunday 24:00.
1029 The range is determined relative to TIME. TIME defaults to the current time.
1030 The return value is a cons cell with two internal times like the ones
1031 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1032 the returned times will be formatted strings."
1033 (if (integerp key) (setq key (intern (number-to-string key))))
1034 (let* ((tm (decode-time (or time (current-time))))
1035 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1036 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1037 (dow (nth 6 tm))
1038 (skey (symbol-name key))
1039 (shift 0)
1040 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
1041 (cond
1042 ((string-match "^[0-9]+$" skey)
1043 (setq y (string-to-number skey) m 1 d 1 key 'year))
1044 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1045 (setq y (string-to-number (match-string 1 skey))
1046 month (string-to-number (match-string 2 skey))
1047 d 1 key 'month))
1048 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1049 (require 'cal-iso)
1050 (setq y (string-to-number (match-string 1 skey))
1051 w (string-to-number (match-string 2 skey)))
1052 (setq date (calendar-gregorian-from-absolute
1053 (calendar-absolute-from-iso (list w 1 y))))
1054 (setq d (nth 1 date) month (car date) y (nth 2 date)
1055 dow 1
1056 key 'week))
1057 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1058 (setq y (string-to-number (match-string 1 skey))
1059 month (string-to-number (match-string 2 skey))
1060 d (string-to-number (match-string 3 skey))
1061 key 'day))
1062 ((string-match "\\([-+][0-9]+\\)$" skey)
1063 (setq shift (string-to-number (match-string 1 skey))
1064 key (intern (substring skey 0 (match-beginning 1))))))
1065 (when (= shift 0)
1066 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1067 ((eq key 'lastweek) (setq key 'week shift -1))
1068 ((eq key 'lastmonth) (setq key 'month shift -1))
1069 ((eq key 'lastyear) (setq key 'year shift -1))))
1070 (cond
1071 ((memq key '(day today))
1072 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1073 ((memq key '(week thisweek))
1074 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1075 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1076 ((memq key '(month thismonth))
1077 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1078 ((memq key '(year thisyear))
1079 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1080 (t (error "No such time block %s" key)))
1081 (setq ts (encode-time s m h d month y)
1082 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1083 (or d1 d) (or month1 month) (or y1 y)))
1084 (setq fm (cdr org-time-stamp-formats))
1085 (cond
1086 ((memq key '(day today))
1087 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1088 ((memq key '(week thisweek))
1089 (setq txt (format-time-string "week %G-W%V" ts)))
1090 ((memq key '(month thismonth))
1091 (setq txt (format-time-string "%B %Y" ts)))
1092 ((memq key '(year thisyear))
1093 (setq txt (format-time-string "the year %Y" ts))))
1094 (if as-strings
1095 (list (format-time-string fm ts) (format-time-string fm te) txt)
1096 (list ts te txt))))
1098 (defun org-clocktable-shift (dir n)
1099 "Try to shift the :block date of the clocktable at point.
1100 Point must be in the #+BEGIN: line of a clocktable, or this function
1101 will throw an error.
1102 DIR is a direction, a symbol `left', `right', `up', or `down'.
1103 Both `left' and `down' shift the block toward the past, `up' and `right'
1104 push it toward the future.
1105 N is the number of shift steps to take. The size of the step depends on
1106 the currently selected interval size."
1107 (setq n (prefix-numeric-value n))
1108 (and (memq dir '(left down)) (setq n (- n)))
1109 (save-excursion
1110 (goto-char (point-at-bol))
1111 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1112 (error "Line needs a :block definition before this command works")
1113 (let* ((b (match-beginning 1)) (e (match-end 1))
1114 (s (match-string 1))
1115 block shift ins y mw d date wp m)
1116 (cond
1117 ((equal s "yesterday") (setq s "today-1"))
1118 ((equal s "lastweek") (setq s "thisweek-1"))
1119 ((equal s "lastmonth") (setq s "thismonth-1"))
1120 ((equal s "lastyear") (setq s "thisyear-1")))
1121 (cond
1122 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
1123 (setq block (match-string 1 s)
1124 shift (if (match-end 2)
1125 (string-to-number (match-string 2 s))
1127 (setq shift (+ shift n))
1128 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1129 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1130 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1131 (setq y (string-to-number (match-string 1 s))
1132 wp (and (match-end 3) (match-string 3 s))
1133 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1134 d (and (match-end 6) (string-to-number (match-string 6 s))))
1135 (cond
1136 (d (setq ins (format-time-string
1137 "%Y-%m-%d"
1138 (encode-time 0 0 0 (+ d n) m y))))
1139 ((and wp mw (> (length wp) 0))
1140 (require 'cal-iso)
1141 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1142 (setq ins (format-time-string
1143 "%G-W%V"
1144 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1146 (setq ins (format-time-string
1147 "%Y-%m"
1148 (encode-time 0 0 0 1 (+ mw n) y))))
1150 (setq ins (number-to-string (+ y n))))))
1151 (t (error "Cannot shift clocktable block")))
1152 (when ins
1153 (goto-char b)
1154 (insert ins)
1155 (delete-region (point) (+ (point) (- e b)))
1156 (beginning-of-line 1)
1157 (org-update-dblock)
1158 t)))))
1160 (defun org-dblock-write:clocktable (params)
1161 "Write the standard clocktable."
1162 (catch 'exit
1163 (let* ((hlchars '((1 . "*") (2 . "/")))
1164 (ins (make-marker))
1165 (total-time nil)
1166 (scope (plist-get params :scope))
1167 (tostring (plist-get params :tostring))
1168 (multifile (plist-get params :multifile))
1169 (header (plist-get params :header))
1170 (maxlevel (or (plist-get params :maxlevel) 3))
1171 (step (plist-get params :step))
1172 (emph (plist-get params :emphasize))
1173 (ts (plist-get params :tstart))
1174 (te (plist-get params :tend))
1175 (block (plist-get params :block))
1176 (link (plist-get params :link))
1177 ipos time p level hlc hdl content recalc formula pcol
1178 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
1179 (setq org-clock-file-total-minutes nil)
1180 (when step
1181 (unless (or block (and ts te))
1182 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1183 (org-clocktable-steps params)
1184 (throw 'exit nil))
1185 (when block
1186 (setq cc (org-clock-special-range block nil t)
1187 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1188 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
1189 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
1190 (when (and ts (listp ts))
1191 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
1192 (when (and te (listp te))
1193 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
1194 ;; Now the times are strings we can parse.
1195 (if ts (setq ts (time-to-seconds
1196 (apply 'encode-time (org-parse-time-string ts)))))
1197 (if te (setq te (time-to-seconds
1198 (apply 'encode-time (org-parse-time-string te)))))
1199 (move-marker ins (point))
1200 (setq ipos (point))
1202 ;; Get the right scope
1203 (setq pos (point))
1204 (cond
1205 ((and scope (listp scope) (symbolp (car scope)))
1206 (setq scope (eval scope)))
1207 ((eq scope 'agenda)
1208 (setq scope (org-agenda-files t)))
1209 ((eq scope 'agenda-with-archives)
1210 (setq scope (org-agenda-files t))
1211 (setq scope (org-add-archive-files scope)))
1212 ((eq scope 'file-with-archives)
1213 (setq scope (org-add-archive-files (list (buffer-file-name)))
1214 rm-file-column t)))
1215 (setq scope-is-list (and scope (listp scope)))
1216 (save-restriction
1217 (cond
1218 ((not scope))
1219 ((eq scope 'file) (widen))
1220 ((eq scope 'subtree) (org-narrow-to-subtree))
1221 ((eq scope 'tree)
1222 (while (org-up-heading-safe))
1223 (org-narrow-to-subtree))
1224 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1225 (symbol-name scope)))
1226 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1227 (catch 'exit
1228 (while (org-up-heading-safe)
1229 (looking-at outline-regexp)
1230 (if (<= (org-reduced-level (funcall outline-level)) level)
1231 (throw 'exit nil))))
1232 (org-narrow-to-subtree))
1233 (scope-is-list
1234 (let* ((files scope)
1235 (scope 'agenda)
1236 (p1 (copy-sequence params))
1237 file)
1238 (setq p1 (plist-put p1 :tostring t))
1239 (setq p1 (plist-put p1 :multifile t))
1240 (setq p1 (plist-put p1 :scope 'file))
1241 (org-prepare-agenda-buffers files)
1242 (while (setq file (pop files))
1243 (with-current-buffer (find-buffer-visiting file)
1244 (setq tbl1 (org-dblock-write:clocktable p1))
1245 (when tbl1
1246 (push (org-clocktable-add-file
1247 file
1248 (concat "| |*File time*|*"
1249 (org-minutes-to-hh:mm-string
1250 org-clock-file-total-minutes)
1251 "*|\n"
1252 tbl1)) tbl)
1253 (setq total-time (+ (or total-time 0)
1254 org-clock-file-total-minutes))))))))
1255 (goto-char pos)
1257 (unless scope-is-list
1258 (org-clock-sum ts te)
1259 (goto-char (point-min))
1260 (setq st t)
1261 (while (or (and (bobp) (prog1 st (setq st nil))
1262 (get-text-property (point) :org-clock-minutes)
1263 (setq p (point-min)))
1264 (setq p (next-single-property-change (point) :org-clock-minutes)))
1265 (goto-char p)
1266 (when (setq time (get-text-property p :org-clock-minutes))
1267 (save-excursion
1268 (beginning-of-line 1)
1269 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1270 (setq level (org-reduced-level
1271 (- (match-end 1) (match-beginning 1))))
1272 (<= level maxlevel))
1273 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
1274 hdl (if (not link)
1275 (match-string 2)
1276 (org-make-link-string
1277 (format "file:%s::%s"
1278 (buffer-file-name)
1279 (save-match-data
1280 (org-make-org-heading-search-string
1281 (match-string 2))))
1282 (match-string 2))))
1283 (if (and (not multifile) (= level 1)) (push "|-" tbl))
1284 (push (concat
1285 "| " (int-to-string level) "|" hlc hdl hlc " |"
1286 (make-string (1- level) ?|)
1287 hlc (org-minutes-to-hh:mm-string time) hlc
1288 " |") tbl))))))
1289 (setq tbl (nreverse tbl))
1290 (if tostring
1291 (if tbl (mapconcat 'identity tbl "\n") nil)
1292 (goto-char ins)
1293 (insert-before-markers
1294 (or header
1295 (concat
1296 "Clock summary at ["
1297 (substring
1298 (format-time-string (cdr org-time-stamp-formats))
1299 1 -1)
1301 (if block (concat ", for " range-text ".") "")
1302 "\n\n"))
1303 (if scope-is-list "|File" "")
1304 "|L|Headline|Time|\n")
1305 (setq total-time (or total-time org-clock-file-total-minutes))
1306 (insert-before-markers
1307 "|-\n|"
1308 (if scope-is-list "|" "")
1310 "*Total time*| *"
1311 (org-minutes-to-hh:mm-string (or total-time 0))
1312 "*|\n|-\n")
1313 (setq tbl (delq nil tbl))
1314 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
1315 (equal (substring (car tbl) 0 2) "|-"))
1316 (pop tbl))
1317 (insert-before-markers (mapconcat
1318 'identity (delq nil tbl)
1319 (if scope-is-list "\n|-\n" "\n")))
1320 (backward-delete-char 1)
1321 (if (setq formula (plist-get params :formula))
1322 (cond
1323 ((eq formula '%)
1324 (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
1325 (insert
1326 (format
1327 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1328 pcol
1330 (+ 3 (if scope-is-list 1 0))
1331 (+ (if scope-is-list 1 0) 3)
1332 (1- pcol)))
1333 (setq recalc t))
1334 ((stringp formula)
1335 (insert "\n#+TBLFM: " formula)
1336 (setq recalc t))
1337 (t (error "invalid formula in clocktable")))
1338 ;; Should we rescue an old formula?
1339 (when (stringp (setq content (plist-get params :content)))
1340 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
1341 (setq recalc t)
1342 (insert "\n" (match-string 1 (plist-get params :content)))
1343 (beginning-of-line 0))))
1344 (goto-char ipos)
1345 (skip-chars-forward "^|")
1346 (org-table-align)
1347 (when recalc
1348 (if (eq formula '%)
1349 (save-excursion (org-table-goto-column pcol nil 'force)
1350 (insert "%")))
1351 (org-table-recalculate 'all))
1352 (when rm-file-column
1353 (forward-char 1)
1354 (org-table-delete-column)))))))
1356 (defun org-clocktable-steps (params)
1357 (let* ((p1 (copy-sequence params))
1358 (ts (plist-get p1 :tstart))
1359 (te (plist-get p1 :tend))
1360 (step0 (plist-get p1 :step))
1361 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
1362 (block (plist-get p1 :block))
1363 cc range-text)
1364 (when block
1365 (setq cc (org-clock-special-range block nil t)
1366 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1367 (if ts (setq ts (time-to-seconds
1368 (apply 'encode-time (org-parse-time-string ts)))))
1369 (if te (setq te (time-to-seconds
1370 (apply 'encode-time (org-parse-time-string te)))))
1371 (setq p1 (plist-put p1 :header ""))
1372 (setq p1 (plist-put p1 :step nil))
1373 (setq p1 (plist-put p1 :block nil))
1374 (while (< ts te)
1375 (or (bolp) (insert "\n"))
1376 (setq p1 (plist-put p1 :tstart (format-time-string
1377 (org-time-stamp-format nil t)
1378 (seconds-to-time ts))))
1379 (setq p1 (plist-put p1 :tend (format-time-string
1380 (org-time-stamp-format nil t)
1381 (seconds-to-time (setq ts (+ ts step))))))
1382 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
1383 (plist-get p1 :tstart) "\n")
1384 (org-dblock-write:clocktable p1)
1385 (re-search-forward "#\\+END:")
1386 (end-of-line 0))))
1388 (defun org-clocktable-add-file (file table)
1389 (if table
1390 (let ((lines (org-split-string table "\n"))
1391 (ff (file-name-nondirectory file)))
1392 (mapconcat 'identity
1393 (mapcar (lambda (x)
1394 (if (string-match org-table-dataline-regexp x)
1395 (concat "|" ff x)
1397 lines)
1398 "\n"))))
1400 (defun org-clock-time% (total &rest strings)
1401 "Compute a time fraction in percent.
1402 TOTAL s a time string like 10:21 specifying the total times.
1403 STRINGS is a list of strings that should be checked for a time.
1404 The first string that does have a time will be used.
1405 This function is made for clock tables."
1406 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1407 tot s)
1408 (save-match-data
1409 (catch 'exit
1410 (if (not (string-match re total))
1411 (throw 'exit 0.)
1412 (setq tot (+ (string-to-number (match-string 2 total))
1413 (* 60 (string-to-number (match-string 1 total)))))
1414 (if (= tot 0.) (throw 'exit 0.)))
1415 (while (setq s (pop strings))
1416 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
1417 (throw 'exit
1418 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
1419 (* 60 (string-to-number (match-string 1 s)))))
1420 tot))))
1421 0))))
1423 (defun org-clock-save ()
1424 "Persist various clock-related data to disk.
1425 The details of what will be saved are regulated by the variable
1426 `org-clock-persist'."
1427 (when org-clock-persist
1428 (let (b)
1429 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
1430 (progn
1431 (delete-region (point-min) (point-max))
1432 ;;Store clock
1433 (insert (format ";; org-persist.el - %s at %s\n"
1434 system-name (format-time-string
1435 (cdr org-time-stamp-formats))))
1436 (if (and (setq b (marker-buffer org-clock-marker))
1437 (setq b (or (buffer-base-buffer b) b))
1438 (buffer-live-p b)
1439 (buffer-file-name b)
1440 (or (not org-clock-persist-query-save)
1441 (y-or-n-p (concat "Save current clock ("
1442 (substring-no-properties org-clock-heading)
1443 ") "))))
1444 (insert "(setq resume-clock '(\""
1445 (buffer-file-name (marker-buffer org-clock-marker))
1446 "\" . " (int-to-string (marker-position org-clock-marker))
1447 "))\n"))
1448 ;; Store clocked task history. Tasks are stored reversed to make
1449 ;; reading simpler
1450 (when (and org-clock-history (eq org-clock-persist t))
1451 (insert
1452 "(setq stored-clock-history '("
1453 (mapconcat
1454 (lambda (m)
1455 (when (and (setq b (marker-buffer m))
1456 (setq b (or (buffer-base-buffer b) b))
1457 (buffer-live-p b)
1458 (buffer-file-name b))
1459 (concat "(\"" (buffer-file-name b)
1460 "\" . " (int-to-string (marker-position m))
1461 ")")))
1462 (reverse org-clock-history) " ") "))\n"))
1463 (save-buffer)
1464 (kill-buffer (current-buffer)))))))
1466 (defvar org-clock-loaded nil
1467 "Was the clock file loaded?")
1469 (defun org-clock-load ()
1470 "Load clock-related data from disk, maybe resuming a stored clock."
1471 (when (and org-clock-persist (not org-clock-loaded))
1472 (let ((filename (expand-file-name org-clock-persist-file))
1473 (org-clock-in-resume 'auto-restart)
1474 resume-clock stored-clock-history)
1475 (if (not (file-readable-p filename))
1476 (message "Not restoring clock data; %s not found"
1477 org-clock-persist-file)
1478 (message "%s" "Restoring clock data")
1479 (setq org-clock-loaded t)
1480 (load-file filename)
1481 ;; load history
1482 (when stored-clock-history
1483 (save-window-excursion
1484 (mapc (lambda (task)
1485 (if (file-exists-p (car task))
1486 (org-clock-history-push (cdr task)
1487 (find-file (car task)))))
1488 stored-clock-history)))
1489 ;; resume clock
1490 (when (and resume-clock org-clock-persist
1491 (file-exists-p (car resume-clock))
1492 (or (not org-clock-persist-query-resume)
1493 (y-or-n-p
1494 (concat
1495 "Resume clock ("
1496 (with-current-buffer (find-file (car resume-clock))
1497 (save-excursion
1498 (goto-char (cdr resume-clock))
1499 (org-back-to-heading t)
1500 (and (looking-at org-complex-heading-regexp)
1501 (match-string 4))))
1502 ") "))))
1503 (when (file-exists-p (car resume-clock))
1504 (with-current-buffer (find-file (car resume-clock))
1505 (goto-char (cdr resume-clock))
1506 (org-clock-in)
1507 (if (org-invisible-p)
1508 (org-show-context)))))))))
1510 ;;;###autoload
1511 (defun org-clock-persistence-insinuate ()
1512 "Set up hooks for clock persistence"
1513 (add-hook 'org-mode-hook 'org-clock-load)
1514 (add-hook 'kill-emacs-hook 'org-clock-save))
1517 ;; Suggested bindings
1518 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
1520 (provide 'org-clock)
1522 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1524 ;;; org-clock.el ends here