Fix Org ChangeLog entries and remove arch-tag.
[bpt/emacs.git] / lisp / org / org-clock.el
1 ;;; org-clock.el --- The time clocking code for Org-mode
2
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 ;; Free Software Foundation, Inc.
5
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
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.
17
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.
22
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;;; Commentary:
28
29 ;; This file contains the time clocking code for Org-mode
30
31 (require 'org)
32 (require 'org-exp)
33 ;;; Code:
34
35 (eval-when-compile
36 (require 'cl))
37
38 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
39 (declare-function notifications-notify "notifications" (&rest params))
40 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
41 (defvar org-time-stamp-formats)
42 (defvar org-ts-what)
43
44 (defgroup org-clock nil
45 "Options concerning clocking working time in Org-mode."
46 :tag "Org Clock"
47 :group 'org-progress)
48
49 (defcustom org-clock-into-drawer org-log-into-drawer
50 "Should clocking info be wrapped into a drawer?
51 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
52 If necessary, the drawer will be created.
53 When nil, the drawer will not be created, but used when present.
54 When an integer and the number of clocking entries in an item
55 reaches or exceeds this number, a drawer will be created.
56 When a string, it names the drawer to be used.
57
58 The default for this variable is the value of `org-log-into-drawer',
59 which see."
60 :group 'org-todo
61 :group 'org-clock
62 :type '(choice
63 (const :tag "Always" t)
64 (const :tag "Only when drawer exists" nil)
65 (integer :tag "When at least N clock entries")
66 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
67 (string :tag "Into Drawer named...")))
68
69 (defun org-clock-into-drawer ()
70 "Return the value of `org-clock-into-drawer', but let properties overrule.
71 If the current entry has or inherits a CLOCK_INTO_DRAWER
72 property, it will be used instead of the default value; otherwise
73 if the current entry has or inherits a LOG_INTO_DRAWER property,
74 it will be used instead of the default value.
75 The default is the value of the customizable variable `org-clock-into-drawer',
76 which see."
77 (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit))
78 (q (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
79 (cond
80 ((or (not (or p q)) (equal p "nil") (equal q "nil")) org-clock-into-drawer)
81 ((or (equal p "t") (equal q "t")) "LOGBOOK")
82 ((not p) q)
83 (t p))))
84
85 (defcustom org-clock-out-when-done t
86 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
87 DONE here means any DONE-like state.
88 A nil value means clock will keep running until stopped explicitly with
89 `C-c C-x C-o', or until the clock is started in a different item.
90 Instead of t, this can also be a list of TODO states that should trigger
91 clocking out."
92 :group 'org-clock
93 :type '(choice
94 (const :tag "No" nil)
95 (const :tag "Yes, when done" t)
96 (repeat :tag "State list"
97 (string :tag "TODO keyword"))))
98
99 (defcustom org-clock-out-remove-zero-time-clocks nil
100 "Non-nil means remove the clock line when the resulting time is zero."
101 :group 'org-clock
102 :type 'boolean)
103
104 (defcustom org-clock-in-switch-to-state nil
105 "Set task to a special todo state while clocking it.
106 The value should be the state to which the entry should be
107 switched. If the value is a function, it must take one
108 parameter (the current TODO state of the item) and return the
109 state to switch it to."
110 :group 'org-clock
111 :group 'org-todo
112 :type '(choice
113 (const :tag "Don't force a state" nil)
114 (string :tag "State")
115 (symbol :tag "Function")))
116
117 (defcustom org-clock-out-switch-to-state nil
118 "Set task to a special todo state after clocking out.
119 The value should be the state to which the entry should be
120 switched. If the value is a function, it must take one
121 parameter (the current TODO state of the item) and return the
122 state to switch it to."
123 :group 'org-clock
124 :group 'org-todo
125 :type '(choice
126 (const :tag "Don't force a state" nil)
127 (string :tag "State")
128 (symbol :tag "Function")))
129
130 (defcustom org-clock-history-length 5
131 "Number of clock tasks to remember in history."
132 :group 'org-clock
133 :type 'integer)
134
135 (defcustom org-clock-goto-may-find-recent-task t
136 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
137 :group 'org-clock
138 :type 'boolean)
139
140 (defcustom org-clock-heading-function nil
141 "When non-nil, should be a function to create `org-clock-heading'.
142 This is the string shown in the mode line when a clock is running.
143 The function is called with point at the beginning of the headline."
144 :group 'org-clock
145 :type 'function)
146
147 (defcustom org-clock-string-limit 0
148 "Maximum length of clock strings in the modeline. 0 means no limit."
149 :group 'org-clock
150 :type 'integer)
151
152 (defcustom org-clock-in-resume nil
153 "If non-nil, resume clock when clocking into task with open clock.
154 When clocking into a task with a clock entry which has not been closed,
155 the clock can be resumed from that point."
156 :group 'org-clock
157 :type 'boolean)
158
159 (defcustom org-clock-persist nil
160 "When non-nil, save the running clock when Emacs is closed.
161 The clock is resumed when Emacs restarts.
162 When this is t, both the running clock, and the entire clock
163 history are saved. When this is the symbol `clock', only the
164 running clock is saved.
165
166 When Emacs restarts with saved clock information, the file containing the
167 running clock as well as all files mentioned in the clock history will
168 be visited.
169 All this depends on running `org-clock-persistence-insinuate' in .emacs"
170 :group 'org-clock
171 :type '(choice
172 (const :tag "Just the running clock" clock)
173 (const :tag "Just the history" history)
174 (const :tag "Clock and history" t)
175 (const :tag "No persistence" nil)))
176
177 (defcustom org-clock-persist-file (convert-standard-filename
178 "~/.emacs.d/org-clock-save.el")
179 "File to save clock data to."
180 :group 'org-clock
181 :type 'string)
182
183 (defcustom org-clock-persist-query-save nil
184 "When non-nil, ask before saving the current clock on exit."
185 :group 'org-clock
186 :type 'boolean)
187
188 (defcustom org-clock-persist-query-resume t
189 "When non-nil, ask before resuming any stored clock during load."
190 :group 'org-clock
191 :type 'boolean)
192
193 (defcustom org-clock-sound nil
194 "Sound that will used for notifications.
195 Possible values:
196
197 nil no sound played.
198 t standard Emacs beep
199 file name play this sound file. If not possible, fall back to beep"
200 :group 'org-clock
201 :type '(choice
202 (const :tag "No sound" nil)
203 (const :tag "Standard beep" t)
204 (file :tag "Play sound file")))
205
206 (defcustom org-clock-modeline-total 'auto
207 "Default setting for the time included for the modeline clock.
208 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
209 Allowed values are:
210
211 current Only the time in the current instance of the clock
212 today All time clocked into this task today
213 repeat All time clocked into this task since last repeat
214 all All time ever recorded for this task
215 auto Automatically, either `all', or `repeat' for repeating tasks"
216 :group 'org-clock
217 :type '(choice
218 (const :tag "Current clock" current)
219 (const :tag "Today's task time" today)
220 (const :tag "Since last repeat" repeat)
221 (const :tag "All task time" all)
222 (const :tag "Automatically, `all' or since `repeat'" auto)))
223
224 (defcustom org-task-overrun-text nil
225 "The extra modeline text that should indicate that the clock is overrun.
226 The can be nil to indicate that instead of adding text, the clock time
227 should get a different face (`org-mode-line-clock-overrun').
228 When this is a string, it is prepended to the clock string as an indication,
229 also using the face `org-mode-line-clock-overrun'."
230 :group 'org-clock
231 :type '(choice
232 (const :tag "Just mark the time string" nil)
233 (string :tag "Text to prepend")))
234
235 (defcustom org-show-notification-handler nil
236 "Function or program to send notification with.
237 The function or program will be called with the notification
238 string as argument."
239 :group 'org-clock
240 :type '(choice
241 (string :tag "Program")
242 (function :tag "Function")))
243
244 (defgroup org-clocktable nil
245 "Options concerning the clock table in Org-mode."
246 :tag "Org Clock Table"
247 :group 'org-clock)
248
249 (defcustom org-clocktable-defaults
250 `(list
251 :maxlevel 2
252 :lang ,org-export-default-language
253 :scope 'file
254 :block nil
255 :tstart nil
256 :tend nil
257 :step nil
258 :stepskip0 nil
259 :fileskip0 nil
260 :tags nil
261 :emphasize nil
262 :link nil
263 :narrow '40!
264 :indent t
265 :formula nil
266 :timestamp nil
267 :level nil
268 :tcolumns nil
269 :formatter nil)
270 "Default properties for clock tables."
271 :group 'org-clock
272 :type 'plist)
273
274 (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
275 "Function to turn clocking data into a table.
276 For more information, see `org-clocktable-write-default'."
277 :group 'org-clocktable
278 :type 'function)
279
280 ;; FIXME: translate es and nl last string "Clock summary at"
281 (defcustom org-clock-clocktable-language-setup
282 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
283 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
284 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à")
285 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at"))
286 "Terms used in clocktable, translated to different languages."
287 :group 'org-clocktable
288 :type 'alist)
289
290 (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
291 "Default properties for new clocktables.
292 These will be inserted into the BEGIN line, to make it easy for users to
293 play with them."
294 :group 'org-clocktable
295 :type 'plist)
296
297 (defcustom org-clock-idle-time nil
298 "When non-nil, resolve open clocks if the user is idle more than X minutes."
299 :group 'org-clock
300 :type '(choice
301 (const :tag "Never" nil)
302 (integer :tag "After N minutes")))
303
304 (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
305 "When to automatically resolve open clocks found in Org buffers."
306 :group 'org-clock
307 :type '(choice
308 (const :tag "Never" nil)
309 (const :tag "Always" t)
310 (const :tag "When no clock is running" when-no-clock-is-running)))
311
312 (defcustom org-clock-report-include-clocking-task nil
313 "When non-nil, include the current clocking task time in clock reports."
314 :group 'org-clock
315 :type 'boolean)
316
317 (defcustom org-clock-resolve-expert nil
318 "Non-nil means do not show the splash buffer with the clock resolver."
319 :group 'org-clock
320 :type 'boolean)
321
322 (defvar org-clock-in-prepare-hook nil
323 "Hook run when preparing the clock.
324 This hook is run before anything happens to the task that
325 you want to clock in. For example, you can use this hook
326 to add an effort property.")
327 (defvar org-clock-in-hook nil
328 "Hook run when starting the clock.")
329 (defvar org-clock-out-hook nil
330 "Hook run when stopping the current clock.")
331
332 (defvar org-clock-cancel-hook nil
333 "Hook run when cancelling the current clock.")
334 (defvar org-clock-goto-hook nil
335 "Hook run when selecting the currently clocked-in entry.")
336 (defvar org-clock-has-been-used nil
337 "Has the clock been used during the current Emacs session?")
338
339 ;;; The clock for measuring work time.
340
341 (defvar org-mode-line-string "")
342 (put 'org-mode-line-string 'risky-local-variable t)
343
344 (defvar org-clock-mode-line-timer nil)
345 (defvar org-clock-idle-timer nil)
346 (defvar org-clock-heading) ; defined in org.el
347 (defvar org-clock-heading-for-remember "")
348 (defvar org-clock-start-time "")
349
350 (defvar org-clock-leftover-time nil
351 "If non-nil, user cancelled a clock; this is when leftover time started.")
352
353 (defvar org-clock-effort ""
354 "Effort estimate of the currently clocking task.")
355
356 (defvar org-clock-total-time nil
357 "Holds total time, spent previously on currently clocked item.
358 This does not include the time in the currently running clock.")
359
360 (defvar org-clock-history nil
361 "List of marker pointing to recent clocked tasks.")
362
363 (defvar org-clock-default-task (make-marker)
364 "Marker pointing to the default task that should clock time.
365 The clock can be made to switch to this task after clocking out
366 of a different task.")
367
368 (defvar org-clock-interrupted-task (make-marker)
369 "Marker pointing to the task that has been interrupted by the current clock.")
370
371 (defvar org-clock-mode-line-map (make-sparse-keymap))
372 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
373 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
374
375 (defun org-clock-menu ()
376 (interactive)
377 (popup-menu
378 '("Clock"
379 ["Clock out" org-clock-out t]
380 ["Change effort estimate" org-clock-modify-effort-estimate t]
381 ["Go to clock entry" org-clock-goto t]
382 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
383
384 (defun org-clock-history-push (&optional pos buffer)
385 "Push a marker to the clock history."
386 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
387 (let ((m (move-marker (make-marker)
388 (or pos (point)) (org-base-buffer
389 (or buffer (current-buffer)))))
390 n l)
391 (while (setq n (member m org-clock-history))
392 (move-marker (car n) nil))
393 (setq org-clock-history
394 (delq nil
395 (mapcar (lambda (x) (if (marker-buffer x) x nil))
396 org-clock-history)))
397 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
398 (setq org-clock-history
399 (nreverse
400 (nthcdr (- l org-clock-history-length -1)
401 (nreverse org-clock-history)))))
402 (push m org-clock-history)))
403
404 (defun org-clock-save-markers-for-cut-and-paste (beg end)
405 "Save relative positions of markers in region."
406 (org-check-and-save-marker org-clock-marker beg end)
407 (org-check-and-save-marker org-clock-hd-marker beg end)
408 (org-check-and-save-marker org-clock-default-task beg end)
409 (org-check-and-save-marker org-clock-interrupted-task beg end)
410 (mapc (lambda (m) (org-check-and-save-marker m beg end))
411 org-clock-history))
412
413 (defun org-clocking-buffer ()
414 "Return the clocking buffer if we are currently clocking a task or nil."
415 (marker-buffer org-clock-marker))
416
417 (defun org-clocking-p ()
418 "Return t when clocking a task."
419 (not (equal (org-clocking-buffer) nil)))
420
421 (defvar org-clock-before-select-task-hook nil
422 "Hook called in task selection just before prompting the user.")
423
424 (defun org-clock-select-task (&optional prompt)
425 "Select a task that recently was associated with clocking."
426 (interactive)
427 (let (sel-list rpl (i 0) s)
428 (save-window-excursion
429 (org-switch-to-buffer-other-window
430 (get-buffer-create "*Clock Task Select*"))
431 (erase-buffer)
432 (when (marker-buffer org-clock-default-task)
433 (insert (org-add-props "Default Task\n" nil 'face 'bold))
434 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
435 (push s sel-list))
436 (when (marker-buffer org-clock-interrupted-task)
437 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
438 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
439 (push s sel-list))
440 (when (org-clocking-p)
441 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
442 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
443 (push s sel-list))
444 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
445 (mapc
446 (lambda (m)
447 (when (marker-buffer m)
448 (setq i (1+ i)
449 s (org-clock-insert-selection-line
450 (if (< i 10)
451 (+ i ?0)
452 (+ i (- ?A 10))) m))
453 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
454 (push s sel-list)))
455 org-clock-history)
456 (run-hooks 'org-clock-before-select-task-hook)
457 (org-fit-window-to-buffer)
458 (message (or prompt "Select task for clocking:"))
459 (setq rpl (read-char-exclusive))
460 (cond
461 ((eq rpl ?q) nil)
462 ((eq rpl ?x) nil)
463 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
464 (t (error "Invalid task choice %c" rpl))))))
465
466 (defun org-clock-insert-selection-line (i marker)
467 "Insert a line for the clock selection menu.
468 And return a cons cell with the selection character integer and the marker
469 pointing to it."
470 (when (marker-buffer marker)
471 (let (file cat task heading prefix)
472 (with-current-buffer (org-base-buffer (marker-buffer marker))
473 (save-excursion
474 (save-restriction
475 (widen)
476 (ignore-errors
477 (goto-char marker)
478 (setq file (buffer-file-name (marker-buffer marker))
479 cat (org-get-category)
480 heading (org-get-heading 'notags)
481 prefix (save-excursion
482 (org-back-to-heading t)
483 (looking-at org-outline-regexp)
484 (match-string 0))
485 task (substring
486 (org-fontify-like-in-org-mode
487 (concat prefix heading)
488 org-odd-levels-only)
489 (length prefix)))))))
490 (when (and cat task)
491 (insert (format "[%c] %-15s %s\n" i cat task))
492 (cons i marker)))))
493
494 (defvar org-task-overrun nil
495 "Internal flag indicating if the clock has overrun the planned time.")
496 (defvar org-clock-update-period 60
497 "Number of seconds between mode line clock string updates.")
498
499 (defun org-clock-get-clock-string ()
500 "Form a clock-string, that will be shown in the mode line.
501 If an effort estimate was defined for the current item, use
502 01:30/01:50 format (clocked/estimated).
503 If not, show simply the clocked time like 01:50."
504 (let* ((clocked-time (org-clock-get-clocked-time))
505 (h (floor clocked-time 60))
506 (m (- clocked-time (* 60 h))))
507 (if org-clock-effort
508 (let* ((effort-in-minutes
509 (org-duration-string-to-minutes org-clock-effort))
510 (effort-h (floor effort-in-minutes 60))
511 (effort-m (- effort-in-minutes (* effort-h 60)))
512 (work-done-str
513 (org-propertize
514 (format org-time-clocksum-format h m)
515 'face (if (and org-task-overrun (not org-task-overrun-text))
516 'org-mode-line-clock-overrun 'org-mode-line-clock)))
517 (effort-str (format org-time-clocksum-format effort-h effort-m))
518 (clockstr (org-propertize
519 (concat "[%s/" effort-str
520 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
521 'face 'org-mode-line-clock)))
522 (format clockstr work-done-str))
523 (org-propertize (format
524 (concat "[" org-time-clocksum-format " (%s)]")
525 h m org-clock-heading)
526 'face 'org-mode-line-clock))))
527
528 (defun org-clock-update-mode-line ()
529 (if org-clock-effort
530 (org-clock-notify-once-if-expired)
531 (setq org-task-overrun nil))
532 (setq org-mode-line-string
533 (org-propertize
534 (let ((clock-string (org-clock-get-clock-string))
535 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
536 (if (and (> org-clock-string-limit 0)
537 (> (length clock-string) org-clock-string-limit))
538 (org-propertize
539 (substring clock-string 0 org-clock-string-limit)
540 'help-echo (concat help-text ": " org-clock-heading))
541 (org-propertize clock-string 'help-echo help-text)))
542 'local-map org-clock-mode-line-map
543 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
544 ))
545 (if (and org-task-overrun org-task-overrun-text)
546 (setq org-mode-line-string
547 (concat (org-propertize
548 org-task-overrun-text
549 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
550 (force-mode-line-update))
551
552 (defun org-clock-get-clocked-time ()
553 "Get the clocked time for the current item in minutes.
554 The time returned includes the time spent on this task in
555 previous clocking intervals."
556 (let ((currently-clocked-time
557 (floor (- (org-float-time)
558 (org-float-time org-clock-start-time)) 60)))
559 (+ currently-clocked-time (or org-clock-total-time 0))))
560
561 (defun org-clock-modify-effort-estimate (&optional value)
562 "Add to or set the effort estimate of the item currently being clocked.
563 VALUE can be a number of minutes, or a string with format hh:mm or mm.
564 When the string starts with a + or a - sign, the current value of the effort
565 property will be changed by that amount.
566 This will update the \"Effort\" property of currently clocked item, and
567 the mode line."
568 (interactive)
569 (when (org-clock-is-active)
570 (let ((current org-clock-effort) sign)
571 (unless value
572 ;; Prompt user for a value or a change
573 (setq value
574 (read-string
575 (format "Set effort (hh:mm or mm%s): "
576 (if current
577 (format ", prefix + to add to %s" org-clock-effort)
578 "")))))
579 (when (stringp value)
580 ;; A string. See if it is a delta
581 (setq sign (string-to-char value))
582 (if (member sign '(?- ?+))
583 (setq current (org-duration-string-to-minutes current)
584 value (substring value 1))
585 (setq current 0))
586 (setq value (org-duration-string-to-minutes value))
587 (if (equal ?- sign)
588 (setq value (- current value))
589 (if (equal ?+ sign) (setq value (+ current value)))))
590 (setq value (max 0 value)
591 org-clock-effort (org-minutes-to-hh:mm-string value))
592 (org-entry-put org-clock-marker "Effort" org-clock-effort)
593 (org-clock-update-mode-line)
594 (message "Effort is now %s" org-clock-effort))))
595
596 (defvar org-clock-notification-was-shown nil
597 "Shows if we have shown notification already.")
598
599 (defun org-clock-notify-once-if-expired ()
600 "Show notification if we spent more time than we estimated before.
601 Notification is shown only once."
602 (when (org-clocking-p)
603 (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort))
604 (clocked-time (org-clock-get-clocked-time)))
605 (if (setq org-task-overrun
606 (if (or (null effort-in-minutes) (zerop effort-in-minutes))
607 nil
608 (>= clocked-time effort-in-minutes)))
609 (unless org-clock-notification-was-shown
610 (setq org-clock-notification-was-shown t)
611 (org-notify
612 (format "Task '%s' should be finished by now. (%s)"
613 org-clock-heading org-clock-effort) t))
614 (setq org-clock-notification-was-shown nil)))))
615
616 (defun org-notify (notification &optional play-sound)
617 "Send a NOTIFICATION and maybe PLAY-SOUND."
618 (org-show-notification notification)
619 (if play-sound (org-clock-play-sound)))
620
621 (defun org-show-notification (notification)
622 "Show notification.
623 Use `org-show-notification-handler' if defined,
624 use libnotify if available, or fall back on a message."
625 (cond ((functionp org-show-notification-handler)
626 (funcall org-show-notification-handler notification))
627 ((stringp org-show-notification-handler)
628 (start-process "emacs-timer-notification" nil
629 org-show-notification-handler notification))
630 ((featurep 'notifications)
631 (require 'notifications)
632 (notifications-notify
633 :title "Org-mode message"
634 :body notification
635 ;; FIXME how to link to the Org icon?
636 ;; :app-icon "~/.emacs.d/icons/mail.png"
637 :urgency 'low))
638 ((org-program-exists "notify-send")
639 (start-process "emacs-timer-notification" nil
640 "notify-send" notification))
641 ;; Maybe the handler will send a message, so only use message as
642 ;; a fall back option
643 (t (message "%s" notification))))
644
645 (defun org-clock-play-sound ()
646 "Play sound as configured by `org-clock-sound'.
647 Use alsa's aplay tool if available."
648 (cond
649 ((not org-clock-sound))
650 ((eq org-clock-sound t) (beep t) (beep t))
651 ((stringp org-clock-sound)
652 (let ((file (expand-file-name org-clock-sound)))
653 (if (file-exists-p file)
654 (if (org-program-exists "aplay")
655 (start-process "org-clock-play-notification" nil
656 "aplay" file)
657 (condition-case nil
658 (play-sound-file file)
659 (error (beep t) (beep t)))))))))
660
661 (defun org-program-exists (program-name)
662 "Checks whenever we can locate program and launch it."
663 (if (eq system-type 'gnu/linux)
664 (= 0 (call-process "which" nil nil nil program-name))))
665
666 (defvar org-clock-mode-line-entry nil
667 "Information for the modeline about the running clock.")
668
669 (defun org-find-open-clocks (file)
670 "Search through the given file and find all open clocks."
671 (let ((buf (or (get-file-buffer file)
672 (find-file-noselect file)))
673 clocks)
674 (with-current-buffer buf
675 (save-excursion
676 (goto-char (point-min))
677 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
678 (push (cons (copy-marker (match-end 1) t)
679 (org-time-string-to-time (match-string 1))) clocks))))
680 clocks))
681
682 (defsubst org-is-active-clock (clock)
683 "Return t if CLOCK is the currently active clock."
684 (and (org-clock-is-active)
685 (= org-clock-marker (car clock))))
686
687 (defmacro org-with-clock-position (clock &rest forms)
688 "Evaluate FORMS with CLOCK as the current active clock."
689 `(with-current-buffer (marker-buffer (car ,clock))
690 (save-excursion
691 (save-restriction
692 (widen)
693 (goto-char (car ,clock))
694 (beginning-of-line)
695 ,@forms))))
696
697 (put 'org-with-clock-position 'lisp-indent-function 1)
698
699 (defmacro org-with-clock (clock &rest forms)
700 "Evaluate FORMS with CLOCK as the current active clock.
701 This macro also protects the current active clock from being altered."
702 `(org-with-clock-position ,clock
703 (let ((org-clock-start-time (cdr ,clock))
704 (org-clock-total-time)
705 (org-clock-history)
706 (org-clock-effort)
707 (org-clock-marker (car ,clock))
708 (org-clock-hd-marker (save-excursion
709 (outline-back-to-heading t)
710 (point-marker))))
711 ,@forms)))
712
713 (put 'org-with-clock 'lisp-indent-function 1)
714
715 (defsubst org-clock-clock-in (clock &optional resume start-time)
716 "Clock in to the clock located by CLOCK.
717 If necessary, clock-out of the currently active clock."
718 (org-with-clock-position clock
719 (let ((org-clock-in-resume (or resume org-clock-in-resume)))
720 (org-clock-in nil start-time))))
721
722 (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
723 "Clock out of the clock located by CLOCK."
724 (let ((temp (copy-marker (car clock)
725 (marker-insertion-type (car clock)))))
726 (if (org-is-active-clock clock)
727 (org-clock-out fail-quietly at-time)
728 (org-with-clock clock
729 (org-clock-out fail-quietly at-time)))
730 (setcar clock temp)))
731
732 (defsubst org-clock-clock-cancel (clock)
733 "Cancel the clock located by CLOCK."
734 (let ((temp (copy-marker (car clock)
735 (marker-insertion-type (car clock)))))
736 (if (org-is-active-clock clock)
737 (org-clock-cancel)
738 (org-with-clock clock
739 (org-clock-cancel)))
740 (setcar clock temp)))
741
742 (defvar org-clock-clocking-in nil)
743 (defvar org-clock-resolving-clocks nil)
744 (defvar org-clock-resolving-clocks-due-to-idleness nil)
745
746 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
747 &optional close-p restart-p fail-quietly)
748 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
749 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
750 (let ((org-clock-resolving-clocks t))
751 (cond
752 ((null resolve-to)
753 (org-clock-clock-cancel clock)
754 (if (and restart-p (not org-clock-clocking-in))
755 (org-clock-clock-in clock)))
756
757 ((eq resolve-to 'now)
758 (if restart-p
759 (error "RESTART-P is not valid here"))
760 (if (or close-p org-clock-clocking-in)
761 (org-clock-clock-out clock fail-quietly)
762 (unless (org-is-active-clock clock)
763 (org-clock-clock-in clock t))))
764
765 ((not (time-less-p resolve-to (current-time)))
766 (error "RESOLVE-TO must refer to a time in the past"))
767
768 (t
769 (if restart-p
770 (error "RESTART-P is not valid here"))
771 (org-clock-clock-out clock fail-quietly (or clock-out-time
772 resolve-to))
773 (unless org-clock-clocking-in
774 (if close-p
775 (setq org-clock-leftover-time (and (null clock-out-time)
776 resolve-to))
777 (org-clock-clock-in clock nil (and clock-out-time
778 resolve-to))))))))
779
780 (defun org-clock-jump-to-current-clock (&optional effective-clock)
781 (interactive)
782 (let ((org-clock-into-drawer (org-clock-into-drawer))
783 (clock (or effective-clock (cons org-clock-marker
784 org-clock-start-time))))
785 (unless (marker-buffer (car clock))
786 (error "No clock is currently running"))
787 (org-with-clock clock (org-clock-goto))
788 (with-current-buffer (marker-buffer (car clock))
789 (goto-char (car clock))
790 (if org-clock-into-drawer
791 (let ((logbook
792 (if (stringp org-clock-into-drawer)
793 (concat ":" org-clock-into-drawer ":")
794 ":LOGBOOK:")))
795 (ignore-errors
796 (outline-flag-region
797 (save-excursion
798 (outline-back-to-heading t)
799 (search-forward logbook)
800 (goto-char (match-beginning 0)))
801 (save-excursion
802 (outline-back-to-heading t)
803 (search-forward logbook)
804 (search-forward ":END:")
805 (goto-char (match-end 0)))
806 nil)))))))
807
808 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
809 "Resolve an open org-mode clock.
810 An open clock was found, with `dangling' possibly being non-nil.
811 If this function was invoked with a prefix argument, non-dangling
812 open clocks are ignored. The given clock requires some sort of
813 user intervention to resolve it, either because a clock was left
814 dangling or due to an idle timeout. The clock resolution can
815 either be:
816
817 (a) deleted, the user doesn't care about the clock
818 (b) restarted from the current time (if no other clock is open)
819 (c) closed, giving the clock X minutes
820 (d) closed and then restarted
821 (e) resumed, as if the user had never left
822
823 The format of clock is (CONS MARKER START-TIME), where MARKER
824 identifies the buffer and position the clock is open at (and
825 thus, the heading it's under), and START-TIME is when the clock
826 was started."
827 (assert clock)
828 (let* ((ch
829 (save-window-excursion
830 (save-excursion
831 (unless org-clock-resolving-clocks-due-to-idleness
832 (org-clock-jump-to-current-clock clock))
833 (unless org-clock-resolve-expert
834 (with-output-to-temp-buffer "*Org Clock*"
835 (princ "Select a Clock Resolution Command:
836
837 i/q/C-g Ignore this question; the same as keeping all the idle time.
838
839 k/K Keep X minutes of the idle time (default is all). If this
840 amount is less than the default, you will be clocked out
841 that many minutes after the time that idling began, and then
842 clocked back in at the present time.
843 g/G Indicate that you \"got back\" X minutes ago. This is quite
844 different from 'k': it clocks you out from the beginning of
845 the idle period and clock you back in X minutes ago.
846 s/S Subtract the idle time from the current clock. This is the
847 same as keeping 0 minutes.
848 C Cancel the open timer altogether. It will be as though you
849 never clocked in.
850 j/J Jump to the current clock, to make manual adjustments.
851
852 For all these options, using uppercase makes your final state
853 to be CLOCKED OUT.")))
854 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
855 (let (char-pressed)
856 (when (featurep 'xemacs)
857 (message (concat (funcall prompt-fn clock)
858 " [jkKgGsScCiq]? "))
859 (setq char-pressed (read-char-exclusive)))
860 (while (or (null char-pressed)
861 (and (not (memq char-pressed
862 '(?k ?K ?g ?G ?s ?S ?C
863 ?j ?J ?i ?q)))
864 (or (ding) t)))
865 (setq char-pressed
866 (read-char (concat (funcall prompt-fn clock)
867 " [jkKgGSscCiq]? ")
868 nil 45)))
869 (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
870 (default
871 (floor (/ (org-float-time
872 (time-subtract (current-time) last-valid)) 60)))
873 (keep
874 (and (memq ch '(?k ?K))
875 (read-number "Keep how many minutes? " default)))
876 (gotback
877 (and (memq ch '(?g ?G))
878 (read-number "Got back how many minutes ago? " default)))
879 (subtractp (memq ch '(?s ?S)))
880 (barely-started-p (< (- (org-float-time last-valid)
881 (org-float-time (cdr clock))) 45))
882 (start-over (and subtractp barely-started-p)))
883 (cond
884 ((memq ch '(?j ?J))
885 (if (eq ch ?J)
886 (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
887 (org-clock-jump-to-current-clock clock))
888 ((or (null ch)
889 (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
890 (message ""))
891 (t
892 (org-clock-resolve-clock
893 clock (cond
894 ((or (eq ch ?C)
895 ;; If the time on the clock was less than a minute before
896 ;; the user went away, and they've ask to subtract all the
897 ;; time...
898 start-over)
899 nil)
900 ((or subtractp
901 (and gotback (= gotback 0)))
902 last-valid)
903 ((or (and keep (= keep default))
904 (and gotback (= gotback default)))
905 'now)
906 (keep
907 (time-add last-valid (seconds-to-time (* 60 keep))))
908 (gotback
909 (time-subtract (current-time)
910 (seconds-to-time (* 60 gotback))))
911 (t
912 (error "Unexpected, please report this as a bug")))
913 (and gotback last-valid)
914 (memq ch '(?K ?G ?S))
915 (and start-over
916 (not (memq ch '(?K ?G ?S ?C))))
917 fail-quietly)))))
918
919 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
920 "Resolve all currently open org-mode clocks.
921 If `only-dangling-p' is non-nil, only ask to resolve dangling
922 \(i.e., not currently open and valid) clocks."
923 (interactive "P")
924 (unless org-clock-resolving-clocks
925 (let ((org-clock-resolving-clocks t))
926 (dolist (file (org-files-list))
927 (let ((clocks (org-find-open-clocks file)))
928 (dolist (clock clocks)
929 (let ((dangling (or (not (org-clock-is-active))
930 (/= (car clock) org-clock-marker))))
931 (if (or (not only-dangling-p) dangling)
932 (org-clock-resolve
933 clock
934 (or prompt-fn
935 (function
936 (lambda (clock)
937 (format
938 "Dangling clock started %d mins ago"
939 (floor
940 (/ (- (org-float-time (current-time))
941 (org-float-time (cdr clock))) 60))))))
942 (or last-valid
943 (cdr clock)))))))))))
944
945 (defun org-emacs-idle-seconds ()
946 "Return the current Emacs idle time in seconds, or nil if not idle."
947 (let ((idle-time (current-idle-time)))
948 (if idle-time
949 (org-float-time idle-time)
950 0)))
951
952 (defun org-mac-idle-seconds ()
953 "Return the current Mac idle time in seconds."
954 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
955
956 (defun org-x11-idle-seconds ()
957 "Return the current X11 idle time in seconds."
958 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
959
960 (defun org-user-idle-seconds ()
961 "Return the number of seconds the user has been idle for.
962 This routine returns a floating point number."
963 (cond
964 ((eq system-type 'darwin)
965 (org-mac-idle-seconds))
966 ((eq window-system 'x)
967 (org-x11-idle-seconds))
968 (t
969 (org-emacs-idle-seconds))))
970
971 (defvar org-clock-user-idle-seconds)
972
973 (defun org-resolve-clocks-if-idle ()
974 "Resolve all currently open org-mode clocks.
975 This is performed after `org-clock-idle-time' minutes, to check
976 if the user really wants to stay clocked in after being idle for
977 so long."
978 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
979 org-clock-marker)
980 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
981 (org-clock-user-idle-start
982 (time-subtract (current-time)
983 (seconds-to-time org-clock-user-idle-seconds)))
984 (org-clock-resolving-clocks-due-to-idleness t))
985 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
986 (org-clock-resolve
987 (cons org-clock-marker
988 org-clock-start-time)
989 (function
990 (lambda (clock)
991 (format "Clocked in & idle for %.1f mins"
992 (/ (org-float-time
993 (time-subtract (current-time)
994 org-clock-user-idle-start))
995 60.0))))
996 org-clock-user-idle-start)))))
997
998 (defvar org-clock-current-task nil
999 "Task currently clocked in.")
1000 (defun org-clock-set-current ()
1001 "Set `org-clock-current-task' to the task currently clocked in."
1002 (setq org-clock-current-task (nth 4 (org-heading-components))))
1003
1004 (defun org-clock-delete-current ()
1005 "Reset `org-clock-current-task' to nil."
1006 (setq org-clock-current-task nil))
1007
1008 (defun org-clock-in (&optional select start-time)
1009 "Start the clock on the current item.
1010 If necessary, clock-out of the currently active clock.
1011 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
1012 recently clocked tasks to
1013 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
1014 clock into the current task and mark
1015 is as the default task, a special task that will always be offered in
1016 the clocking selection, associated with the letter `d'."
1017 (interactive "P")
1018 (setq org-clock-notification-was-shown nil)
1019 (catch 'abort
1020 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
1021 (org-clocking-p)))
1022 ts selected-task target-pos (msg-extra "")
1023 (leftover (and (not org-clock-resolving-clocks)
1024 org-clock-leftover-time)))
1025
1026 (when (and org-clock-auto-clock-resolution
1027 (or (not interrupting)
1028 (eq t org-clock-auto-clock-resolution))
1029 (not org-clock-clocking-in)
1030 (not org-clock-resolving-clocks))
1031 (setq org-clock-leftover-time nil)
1032 (let ((org-clock-clocking-in t))
1033 (org-resolve-clocks))) ; check if any clocks are dangling
1034
1035 (when (equal select '(4))
1036 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1037 (if selected-task
1038 (setq selected-task (copy-marker selected-task))
1039 (error "Abort")))
1040
1041 (when (equal select '(16))
1042 ;; Mark as default clocking task
1043 (org-clock-mark-default-task))
1044
1045 (when interrupting
1046 ;; We are interrupting the clocking of a different task.
1047 ;; Save a marker to this task, so that we can go back.
1048 ;; First check if we are trying to clock into the same task!
1049 (when (save-excursion
1050 (unless selected-task
1051 (org-back-to-heading t))
1052 (and (equal (marker-buffer org-clock-hd-marker)
1053 (if selected-task
1054 (marker-buffer selected-task)
1055 (current-buffer)))
1056 (= (marker-position org-clock-hd-marker)
1057 (if selected-task
1058 (marker-position selected-task)
1059 (point)))
1060 (equal org-clock-current-task (nth 4 (org-heading-components)))))
1061 (message "Clock continues in \"%s\"" org-clock-heading)
1062 (throw 'abort nil))
1063 (move-marker org-clock-interrupted-task
1064 (marker-position org-clock-marker)
1065 (marker-buffer org-clock-marker))
1066 (let ((org-clock-clocking-in t))
1067 (org-clock-out t)))
1068
1069 ;; Clock in at which position?
1070 (setq target-pos
1071 (if (and (eobp) (not (org-on-heading-p)))
1072 (point-at-bol 0)
1073 (point)))
1074 (run-hooks 'org-clock-in-prepare-hook)
1075 (save-excursion
1076 (when (and selected-task (marker-buffer selected-task))
1077 ;; There is a selected task, move to the correct buffer
1078 ;; and set the new target position.
1079 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1080 (setq target-pos (marker-position selected-task))
1081 (move-marker selected-task nil))
1082 (save-excursion
1083 (save-restriction
1084 (widen)
1085 (goto-char target-pos)
1086 (org-back-to-heading t)
1087 (or interrupting (move-marker org-clock-interrupted-task nil))
1088 (org-clock-history-push)
1089 (org-clock-set-current)
1090 (cond ((functionp org-clock-in-switch-to-state)
1091 (looking-at org-complex-heading-regexp)
1092 (let ((newstate (funcall org-clock-in-switch-to-state
1093 (match-string 2))))
1094 (if newstate (org-todo newstate))))
1095 ((and org-clock-in-switch-to-state
1096 (not (looking-at (concat org-outline-regexp "[ \t]*"
1097 org-clock-in-switch-to-state
1098 "\\>"))))
1099 (org-todo org-clock-in-switch-to-state)))
1100 (setq org-clock-heading-for-remember
1101 (and (looking-at org-complex-heading-regexp)
1102 (match-end 4)
1103 (org-trim (buffer-substring (match-end 1)
1104 (match-end 4)))))
1105 (setq org-clock-heading
1106 (cond ((and org-clock-heading-function
1107 (functionp org-clock-heading-function))
1108 (funcall org-clock-heading-function))
1109 ((looking-at org-complex-heading-regexp)
1110 (replace-regexp-in-string
1111 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1112 (match-string 4)))
1113 (t "???")))
1114 (setq org-clock-heading (org-propertize org-clock-heading
1115 'face nil))
1116 (org-clock-find-position org-clock-in-resume)
1117 (cond
1118 ((and org-clock-in-resume
1119 (looking-at
1120 (concat "^[ \t]* " org-clock-string
1121 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1122 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1123 (message "Matched %s" (match-string 1))
1124 (setq ts (concat "[" (match-string 1) "]"))
1125 (goto-char (match-end 1))
1126 (setq org-clock-start-time
1127 (apply 'encode-time
1128 (org-parse-time-string (match-string 1))))
1129 (setq org-clock-effort (org-get-effort))
1130 (setq org-clock-total-time (org-clock-sum-current-item
1131 (org-clock-get-sum-start))))
1132 ((eq org-clock-in-resume 'auto-restart)
1133 ;; called from org-clock-load during startup,
1134 ;; do not interrupt, but warn!
1135 (message "Cannot restart clock because task does not contain unfinished clock")
1136 (ding)
1137 (sit-for 2)
1138 (throw 'abort nil))
1139 (t
1140 (insert-before-markers "\n")
1141 (backward-char 1)
1142 (org-indent-line-function)
1143 (when (and (save-excursion
1144 (end-of-line 0)
1145 (org-in-item-p)))
1146 (beginning-of-line 1)
1147 (org-indent-line-to (- (org-get-indentation) 2)))
1148 (insert org-clock-string " ")
1149 (setq org-clock-effort (org-get-effort))
1150 (setq org-clock-total-time (org-clock-sum-current-item
1151 (org-clock-get-sum-start)))
1152 (setq org-clock-start-time
1153 (or (and leftover
1154 (y-or-n-p
1155 (format
1156 "You stopped another clock %d mins ago; start this one from then? "
1157 (/ (- (org-float-time (current-time))
1158 (org-float-time leftover)) 60)))
1159 leftover)
1160 start-time
1161 (current-time)))
1162 (setq ts (org-insert-time-stamp org-clock-start-time
1163 'with-hm 'inactive))))
1164 (move-marker org-clock-marker (point) (buffer-base-buffer))
1165 (move-marker org-clock-hd-marker
1166 (save-excursion (org-back-to-heading t) (point))
1167 (buffer-base-buffer))
1168 (setq org-clock-has-been-used t)
1169 (or global-mode-string (setq global-mode-string '("")))
1170 (or (memq 'org-mode-line-string global-mode-string)
1171 (setq global-mode-string
1172 (append global-mode-string '(org-mode-line-string))))
1173 (org-clock-update-mode-line)
1174 (when org-clock-mode-line-timer
1175 (cancel-timer org-clock-mode-line-timer)
1176 (setq org-clock-mode-line-timer nil))
1177 (setq org-clock-mode-line-timer
1178 (run-with-timer org-clock-update-period
1179 org-clock-update-period
1180 'org-clock-update-mode-line))
1181 (when org-clock-idle-timer
1182 (cancel-timer org-clock-idle-timer)
1183 (setq org-clock-idle-timer nil))
1184 (setq org-clock-idle-timer
1185 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1186 (message "Clock starts at %s - %s" ts msg-extra)
1187 (run-hooks 'org-clock-in-hook)))))))
1188
1189 (defun org-clock-mark-default-task ()
1190 "Mark current task as default task."
1191 (interactive)
1192 (save-excursion
1193 (org-back-to-heading t)
1194 (move-marker org-clock-default-task (point))))
1195
1196 (defvar msg-extra)
1197 (defun org-clock-get-sum-start ()
1198 "Return the time from which clock times should be counted.
1199 This is for the currently running clock as it is displayed
1200 in the mode line. This function looks at the properties
1201 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1202 corresponding variable `org-clock-modeline-total' and then
1203 decides which time to use."
1204 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1205 (symbol-name org-clock-modeline-total)))
1206 (lr (org-entry-get nil "LAST_REPEAT")))
1207 (cond
1208 ((equal cmt "current")
1209 (setq msg-extra "showing time in current clock instance")
1210 (current-time))
1211 ((equal cmt "today")
1212 (setq msg-extra "showing today's task time.")
1213 (let* ((dt (decode-time (current-time))))
1214 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1215 (if org-extend-today-until
1216 (setf (nth 2 dt) org-extend-today-until))
1217 (apply 'encode-time dt)))
1218 ((or (equal cmt "all")
1219 (and (or (not cmt) (equal cmt "auto"))
1220 (not lr)))
1221 (setq msg-extra "showing entire task time.")
1222 nil)
1223 ((or (equal cmt "repeat")
1224 (and (or (not cmt) (equal cmt "auto"))
1225 lr))
1226 (setq msg-extra "showing task time since last repeat.")
1227 (if (not lr)
1228 nil
1229 (org-time-string-to-time lr)))
1230 (t nil))))
1231
1232 (defun org-clock-find-position (find-unclosed)
1233 "Find the location where the next clock line should be inserted.
1234 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1235 line and position cursor in that line."
1236 (org-back-to-heading t)
1237 (catch 'exit
1238 (let* ((org-clock-into-drawer (org-clock-into-drawer))
1239 (beg (save-excursion
1240 (beginning-of-line 2)
1241 (or (bolp) (newline))
1242 (point)))
1243 (end (progn (outline-next-heading) (point)))
1244 (re (concat "^[ \t]*" org-clock-string))
1245 (cnt 0)
1246 (drawer (if (stringp org-clock-into-drawer)
1247 org-clock-into-drawer "LOGBOOK"))
1248 first last ind-last)
1249 (goto-char beg)
1250 (when (and find-unclosed
1251 (re-search-forward
1252 (concat "^[ \t]* " org-clock-string
1253 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1254 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1255 end t))
1256 (beginning-of-line 1)
1257 (throw 'exit t))
1258 (when (eobp) (newline) (setq end (max (point) end)))
1259 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1260 ;; we seem to have a CLOCK drawer, so go there.
1261 (beginning-of-line 2)
1262 (or org-log-states-order-reversed
1263 (and (re-search-forward org-property-end-re nil t)
1264 (goto-char (match-beginning 0))))
1265 (throw 'exit t))
1266 ;; Lets count the CLOCK lines
1267 (goto-char beg)
1268 (while (re-search-forward re end t)
1269 (setq first (or first (match-beginning 0))
1270 last (match-beginning 0)
1271 cnt (1+ cnt)))
1272 (when (and (integerp org-clock-into-drawer)
1273 last
1274 (>= (1+ cnt) org-clock-into-drawer))
1275 ;; Wrap current entries into a new drawer
1276 (goto-char last)
1277 (setq ind-last (org-get-indentation))
1278 (beginning-of-line 2)
1279 (if (and (>= (org-get-indentation) ind-last)
1280 (org-at-item-p))
1281 (when (and (>= (org-get-indentation) ind-last)
1282 (org-at-item-p))
1283 (let ((struct (org-list-struct)))
1284 (goto-char (org-list-get-bottom-point struct)))))
1285 (insert ":END:\n")
1286 (beginning-of-line 0)
1287 (org-indent-line-to ind-last)
1288 (goto-char first)
1289 (insert ":" drawer ":\n")
1290 (beginning-of-line 0)
1291 (org-indent-line-function)
1292 (org-flag-drawer t)
1293 (beginning-of-line 2)
1294 (or org-log-states-order-reversed
1295 (and (re-search-forward org-property-end-re nil t)
1296 (goto-char (match-beginning 0))))
1297 (throw 'exit nil))
1298
1299 (goto-char beg)
1300 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1301 (not (equal (match-string 1) org-clock-string)))
1302 ;; Planning info, skip to after it
1303 (beginning-of-line 2)
1304 (or (bolp) (newline)))
1305 (when (or (eq org-clock-into-drawer t)
1306 (stringp org-clock-into-drawer)
1307 (and (integerp org-clock-into-drawer)
1308 (< org-clock-into-drawer 2)))
1309 (insert ":" drawer ":\n:END:\n")
1310 (beginning-of-line -1)
1311 (org-indent-line-function)
1312 (org-flag-drawer t)
1313 (beginning-of-line 2)
1314 (org-indent-line-function)
1315 (beginning-of-line)
1316 (or org-log-states-order-reversed
1317 (and (re-search-forward org-property-end-re nil t)
1318 (goto-char (match-beginning 0))))))))
1319
1320 (defun org-clock-out (&optional fail-quietly at-time)
1321 "Stop the currently running clock.
1322 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1323 (interactive)
1324 (catch 'exit
1325 (when (not (org-clocking-p))
1326 (setq global-mode-string
1327 (delq 'org-mode-line-string global-mode-string))
1328 (force-mode-line-update)
1329 (if fail-quietly (throw 'exit t) (error "No active clock")))
1330 (let (ts te s h m remove)
1331 (save-excursion ; Do not replace this with `with-current-buffer'.
1332 (with-no-warnings (set-buffer (org-clocking-buffer)))
1333 (save-restriction
1334 (widen)
1335 (goto-char org-clock-marker)
1336 (beginning-of-line 1)
1337 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1338 (equal (match-string 1) org-clock-string))
1339 (setq ts (match-string 2))
1340 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1341 (goto-char (match-end 0))
1342 (delete-region (point) (point-at-eol))
1343 (insert "--")
1344 (setq te (org-insert-time-stamp (or at-time (current-time))
1345 'with-hm 'inactive))
1346 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1347 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1348 h (floor (/ s 3600))
1349 s (- s (* 3600 h))
1350 m (floor (/ s 60))
1351 s (- s (* 60 s)))
1352 (insert " => " (format "%2d:%02d" h m))
1353 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1354 (= (+ h m) 0)))
1355 (beginning-of-line 1)
1356 (delete-region (point) (point-at-eol))
1357 (and (looking-at "\n") (> (point-max) (1+ (point)))
1358 (delete-char 1)))
1359 (move-marker org-clock-marker nil)
1360 (move-marker org-clock-hd-marker nil)
1361 (when org-log-note-clock-out
1362 (org-add-log-setup 'clock-out nil nil nil nil
1363 (concat "# Task: " (org-get-heading t) "\n\n")))
1364 (when org-clock-mode-line-timer
1365 (cancel-timer org-clock-mode-line-timer)
1366 (setq org-clock-mode-line-timer nil))
1367 (when org-clock-idle-timer
1368 (cancel-timer org-clock-idle-timer)
1369 (setq org-clock-idle-timer nil))
1370 (setq global-mode-string
1371 (delq 'org-mode-line-string global-mode-string))
1372 (when org-clock-out-switch-to-state
1373 (save-excursion
1374 (org-back-to-heading t)
1375 (let ((org-inhibit-logging t)
1376 (org-clock-out-when-done nil))
1377 (cond
1378 ((functionp org-clock-out-switch-to-state)
1379 (looking-at org-complex-heading-regexp)
1380 (let ((newstate (funcall org-clock-out-switch-to-state
1381 (match-string 2))))
1382 (if newstate (org-todo newstate))))
1383 ((and org-clock-out-switch-to-state
1384 (not (looking-at (concat org-outline-regexp "[ \t]*"
1385 org-clock-out-switch-to-state
1386 "\\>"))))
1387 (org-todo org-clock-out-switch-to-state))))))
1388 (force-mode-line-update)
1389 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1390 (if remove " => LINE REMOVED" ""))
1391 (run-hooks 'org-clock-out-hook)
1392 (org-clock-delete-current))))))
1393
1394 (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
1395
1396 (defun org-clock-remove-empty-clock-drawer nil
1397 "Remove empty clock drawer in the current subtree."
1398 (let* ((olid (or (org-entry-get (point) "LOG_INTO_DRAWER")
1399 org-log-into-drawer))
1400 (clock-drawer (if (eq t olid) "LOGBOOK" olid))
1401 (end (save-excursion (org-end-of-subtree t t))))
1402 (when clock-drawer
1403 (save-excursion
1404 (org-back-to-heading t)
1405 (while (search-forward clock-drawer end t)
1406 (goto-char (match-beginning 0))
1407 (org-remove-empty-drawer-at clock-drawer (point))
1408 (forward-line 1))))))
1409
1410 (defun org-at-clock-log-p nil
1411 "Is the cursor on the clock log line?"
1412 (save-excursion
1413 (move-beginning-of-line 1)
1414 (looking-at "^[ \t]*CLOCK:")))
1415
1416 (defun org-clock-timestamps-up nil
1417 "Increase CLOCK timestamps at cursor."
1418 (interactive)
1419 (org-clock-timestamps-change 'up))
1420
1421 (defun org-clock-timestamps-down nil
1422 "Increase CLOCK timestamps at cursor."
1423 (interactive)
1424 (org-clock-timestamps-change 'down))
1425
1426 (defun org-clock-timestamps-change (updown)
1427 "Change CLOCK timestamps synchronously at cursor.
1428 UPDOWN tells whether to change 'up or 'down."
1429 (setq org-ts-what nil)
1430 (when (org-at-timestamp-p t)
1431 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1432 'org-timestamp-down))
1433 ts1 begts1 ts2 begts2 updatets1 tdiff)
1434 (save-excursion
1435 (move-beginning-of-line 1)
1436 (re-search-forward org-ts-regexp3 nil t)
1437 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1438 (when (re-search-forward org-ts-regexp3 nil t)
1439 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1440 ;; Are we on the second timestamp?
1441 (if (<= begts2 (point)) (setq updatets1 t))
1442 (if (not ts2)
1443 ;; fall back on org-timestamp-up if there is only one
1444 (funcall tschange)
1445 ;; setq this so that (boundp 'org-ts-what is non-nil)
1446 (funcall tschange)
1447 (let ((ts (if updatets1 ts2 ts1))
1448 (begts (if updatets1 begts1 begts2)))
1449 (setq tdiff
1450 (subtract-time
1451 (org-time-string-to-time org-last-changed-timestamp)
1452 (org-time-string-to-time ts)))
1453 (save-excursion
1454 (goto-char begts)
1455 (org-timestamp-change
1456 (round (/ (org-float-time tdiff)
1457 (cond ((eq org-ts-what 'minute) 60)
1458 ((eq org-ts-what 'hour) 3600)
1459 ((eq org-ts-what 'day) (* 24 3600))
1460 ((eq org-ts-what 'month) (* 24 3600 31))
1461 ((eq org-ts-what 'year) (* 24 3600 365.2)))))
1462 org-ts-what 'updown)))))))
1463
1464 (defun org-clock-cancel ()
1465 "Cancel the running clock by removing the start timestamp."
1466 (interactive)
1467 (when (not (org-clocking-p))
1468 (setq global-mode-string
1469 (delq 'org-mode-line-string global-mode-string))
1470 (force-mode-line-update)
1471 (error "No active clock"))
1472 (save-excursion ; Do not replace this with `with-current-buffer'.
1473 (with-no-warnings (set-buffer (org-clocking-buffer)))
1474 (goto-char org-clock-marker)
1475 (delete-region (1- (point-at-bol)) (point-at-eol))
1476 ;; Just in case, remove any empty LOGBOOK left over
1477 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1478 (move-marker org-clock-marker nil)
1479 (move-marker org-clock-hd-marker nil)
1480 (setq global-mode-string
1481 (delq 'org-mode-line-string global-mode-string))
1482 (force-mode-line-update)
1483 (message "Clock canceled")
1484 (run-hooks 'org-clock-cancel-hook))
1485
1486 (defun org-clock-goto (&optional select)
1487 "Go to the currently clocked-in entry, or to the most recently clocked one.
1488 With prefix arg SELECT, offer recently clocked tasks for selection."
1489 (interactive "@P")
1490 (let* ((recent nil)
1491 (m (cond
1492 (select
1493 (or (org-clock-select-task "Select task to go to: ")
1494 (error "No task selected")))
1495 ((org-clocking-p) org-clock-marker)
1496 ((and org-clock-goto-may-find-recent-task
1497 (car org-clock-history)
1498 (marker-buffer (car org-clock-history)))
1499 (setq recent t)
1500 (car org-clock-history))
1501 (t (error "No active or recent clock task")))))
1502 (org-pop-to-buffer-same-window (marker-buffer m))
1503 (if (or (< m (point-min)) (> m (point-max))) (widen))
1504 (goto-char m)
1505 (org-show-entry)
1506 (org-back-to-heading t)
1507 (org-cycle-hide-drawers 'children)
1508 (recenter)
1509 (org-reveal)
1510 (if recent
1511 (message "No running clock, this is the most recently clocked task"))
1512 (run-hooks 'org-clock-goto-hook)))
1513
1514 (defvar org-clock-file-total-minutes nil
1515 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1516 (make-variable-buffer-local 'org-clock-file-total-minutes)
1517
1518 (defun org-clock-sum (&optional tstart tend headline-filter)
1519 "Sum the times for each subtree.
1520 Puts the resulting times in minutes as a text property on each headline.
1521 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1522 zero-arg function that, if specified, is called for each headline in the time
1523 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1524 nil are excluded from the clock summation."
1525 (interactive)
1526 (let* ((bmp (buffer-modified-p))
1527 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1528 org-clock-string
1529 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1530 (lmax 30)
1531 (ltimes (make-vector lmax 0))
1532 (t1 0)
1533 (level 0)
1534 ts te dt
1535 time)
1536 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1537 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1538 (if (consp tstart) (setq tstart (org-float-time tstart)))
1539 (if (consp tend) (setq tend (org-float-time tend)))
1540 (remove-text-properties (point-min) (point-max)
1541 '(:org-clock-minutes t
1542 :org-clock-force-headline-inclusion t))
1543 (save-excursion
1544 (goto-char (point-max))
1545 (while (re-search-backward re nil t)
1546 (cond
1547 ((match-end 2)
1548 ;; Two time stamps
1549 (setq ts (match-string 2)
1550 te (match-string 3)
1551 ts (org-float-time
1552 (apply 'encode-time (org-parse-time-string ts)))
1553 te (org-float-time
1554 (apply 'encode-time (org-parse-time-string te)))
1555 ts (if tstart (max ts tstart) ts)
1556 te (if tend (min te tend) te)
1557 dt (- te ts)
1558 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1559 ((match-end 4)
1560 ;; A naked time
1561 (setq t1 (+ t1 (string-to-number (match-string 5))
1562 (* 60 (string-to-number (match-string 4))))))
1563 (t ;; A headline
1564 ;; Add the currently clocking item time to the total
1565 (when (and org-clock-report-include-clocking-task
1566 (equal (org-clocking-buffer) (current-buffer))
1567 (equal (marker-position org-clock-hd-marker) (point))
1568 tstart
1569 tend
1570 (>= (org-float-time org-clock-start-time) tstart)
1571 (<= (org-float-time org-clock-start-time) tend))
1572 (let ((time (floor (- (org-float-time)
1573 (org-float-time org-clock-start-time)) 60)))
1574 (setq t1 (+ t1 time))))
1575 (let* ((headline-forced
1576 (get-text-property (point)
1577 :org-clock-force-headline-inclusion))
1578 (headline-included
1579 (or (null headline-filter)
1580 (save-excursion
1581 (save-match-data (funcall headline-filter))))))
1582 (setq level (- (match-end 1) (match-beginning 1)))
1583 (when (or (> t1 0) (> (aref ltimes level) 0))
1584 (when (or headline-included headline-forced)
1585 (if headline-included
1586 (loop for l from 0 to level do
1587 (aset ltimes l (+ (aref ltimes l) t1))))
1588 (setq time (aref ltimes level))
1589 (goto-char (match-beginning 0))
1590 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1591 (if headline-filter
1592 (save-excursion
1593 (save-match-data
1594 (while
1595 (> (funcall outline-level) 1)
1596 (outline-up-heading 1 t)
1597 (put-text-property
1598 (point) (point-at-eol)
1599 :org-clock-force-headline-inclusion t))))))
1600 (setq t1 0)
1601 (loop for l from level to (1- lmax) do
1602 (aset ltimes l 0)))))))
1603 (setq org-clock-file-total-minutes (aref ltimes 0)))
1604 (set-buffer-modified-p bmp)))
1605
1606 (defun org-clock-sum-current-item (&optional tstart)
1607 "Return time, clocked on current item in total."
1608 (save-excursion
1609 (save-restriction
1610 (org-narrow-to-subtree)
1611 (org-clock-sum tstart)
1612 org-clock-file-total-minutes)))
1613
1614 (defun org-clock-display (&optional total-only)
1615 "Show subtree times in the entire buffer.
1616 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1617 in the echo area.
1618
1619 Use \\[org-clock-remove-overlays] to remove the subtree times."
1620 (interactive)
1621 (org-clock-remove-overlays)
1622 (let (time h m p)
1623 (org-clock-sum)
1624 (unless total-only
1625 (save-excursion
1626 (goto-char (point-min))
1627 (while (or (and (equal (setq p (point)) (point-min))
1628 (get-text-property p :org-clock-minutes))
1629 (setq p (next-single-property-change
1630 (point) :org-clock-minutes)))
1631 (goto-char p)
1632 (when (setq time (get-text-property p :org-clock-minutes))
1633 (org-clock-put-overlay time (funcall outline-level))))
1634 (setq h (/ org-clock-file-total-minutes 60)
1635 m (- org-clock-file-total-minutes (* 60 h)))
1636 ;; Arrange to remove the overlays upon next change.
1637 (when org-remove-highlights-with-change
1638 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1639 nil 'local))))
1640 (if org-time-clocksum-use-fractional
1641 (message (concat "Total file time: " org-time-clocksum-fractional-format
1642 " (%d hours and %d minutes)")
1643 (/ (+ (* h 60.0) m) 60.0) h m)
1644 (message (concat "Total file time: " org-time-clocksum-format
1645 " (%d hours and %d minutes)") h m h m))))
1646
1647 (defvar org-clock-overlays nil)
1648 (make-variable-buffer-local 'org-clock-overlays)
1649
1650 (defun org-clock-put-overlay (time &optional level)
1651 "Put an overlays on the current line, displaying TIME.
1652 If LEVEL is given, prefix time with a corresponding number of stars.
1653 This creates a new overlay and stores it in `org-clock-overlays', so that it
1654 will be easy to remove."
1655 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1656 (l (if level (org-get-valid-level level 0) 0))
1657 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1658 org-time-clocksum-fractional-format
1659 org-time-clocksum-format) "%s"))
1660 (off 0)
1661 ov tx)
1662 (org-move-to-column c)
1663 (unless (eolp) (skip-chars-backward "^ \t"))
1664 (skip-chars-backward " \t")
1665 (setq ov (make-overlay (1- (point)) (point-at-eol))
1666 tx (concat (buffer-substring (1- (point)) (point))
1667 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1668 (org-add-props (if org-time-clocksum-use-fractional
1669 (format fmt
1670 (make-string l ?*)
1671 (/ (+ (* h 60.0) m) 60.0)
1672 (make-string (- 16 l) ?\ ))
1673 (format fmt
1674 (make-string l ?*) h m
1675 (make-string (- 16 l) ?\ )))
1676 (list 'face 'org-clock-overlay))
1677 ""))
1678 (if (not (featurep 'xemacs))
1679 (overlay-put ov 'display tx)
1680 (overlay-put ov 'invisible t)
1681 (overlay-put ov 'end-glyph (make-glyph tx)))
1682 (push ov org-clock-overlays)))
1683
1684 (defun org-clock-remove-overlays (&optional beg end noremove)
1685 "Remove the occur highlights from the buffer.
1686 BEG and END are ignored. If NOREMOVE is nil, remove this function
1687 from the `before-change-functions' in the current buffer."
1688 (interactive)
1689 (unless org-inhibit-highlight-removal
1690 (mapc 'delete-overlay org-clock-overlays)
1691 (setq org-clock-overlays nil)
1692 (unless noremove
1693 (remove-hook 'before-change-functions
1694 'org-clock-remove-overlays 'local))))
1695
1696 (defvar state) ;; dynamically scoped into this function
1697 (defun org-clock-out-if-current ()
1698 "Clock out if the current entry contains the running clock.
1699 This is used to stop the clock after a TODO entry is marked DONE,
1700 and is only done if the variable `org-clock-out-when-done' is not nil."
1701 (when (and org-clock-out-when-done
1702 (or (and (eq t org-clock-out-when-done)
1703 (member state org-done-keywords))
1704 (and (listp org-clock-out-when-done)
1705 (member state org-clock-out-when-done)))
1706 (equal (or (buffer-base-buffer (org-clocking-buffer))
1707 (org-clocking-buffer))
1708 (or (buffer-base-buffer (current-buffer))
1709 (current-buffer)))
1710 (< (point) org-clock-marker)
1711 (> (save-excursion (outline-next-heading) (point))
1712 org-clock-marker))
1713 ;; Clock out, but don't accept a logging message for this.
1714 (let ((org-log-note-clock-out nil)
1715 (org-clock-out-switch-to-state nil))
1716 (org-clock-out))))
1717
1718 (add-hook 'org-after-todo-state-change-hook
1719 'org-clock-out-if-current)
1720
1721 ;;;###autoload
1722 (defun org-get-clocktable (&rest props)
1723 "Get a formatted clocktable with parameters according to PROPS.
1724 The table is created in a temporary buffer, fully formatted and
1725 fontified, and then returned."
1726 ;; Set the defaults
1727 (setq props (plist-put props :name "clocktable"))
1728 (unless (plist-member props :maxlevel)
1729 (setq props (plist-put props :maxlevel 2)))
1730 (unless (plist-member props :scope)
1731 (setq props (plist-put props :scope 'agenda)))
1732 (with-temp-buffer
1733 (org-mode)
1734 (org-create-dblock props)
1735 (org-update-dblock)
1736 (font-lock-fontify-buffer)
1737 (forward-line 2)
1738 (buffer-substring (point) (progn
1739 (re-search-forward "^[ \t]*#\\+END" nil t)
1740 (point-at-bol)))))
1741
1742 (defun org-clock-report (&optional arg)
1743 "Create a table containing a report about clocked time.
1744 If the cursor is inside an existing clocktable block, then the table
1745 will be updated. If not, a new clocktable will be inserted. The scope
1746 of the new clock will be subtree when called from within a subtree, and
1747 file elsewhere.
1748
1749 When called with a prefix argument, move to the first clock table in the
1750 buffer and update it."
1751 (interactive "P")
1752 (org-clock-remove-overlays)
1753 (when arg
1754 (org-find-dblock "clocktable")
1755 (org-show-entry))
1756 (if (org-in-clocktable-p)
1757 (goto-char (org-in-clocktable-p))
1758 (let ((props (if (ignore-errors
1759 (save-excursion (org-back-to-heading)))
1760 (list :name "clocktable" :scope 'subtree)
1761 (list :name "clocktable"))))
1762 (org-create-dblock
1763 (org-combine-plists org-clock-clocktable-default-properties props))))
1764 (org-update-dblock))
1765
1766 (defun org-in-clocktable-p ()
1767 "Check if the cursor is in a clocktable."
1768 (let ((pos (point)) start)
1769 (save-excursion
1770 (end-of-line 1)
1771 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
1772 (setq start (match-beginning 0))
1773 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
1774 (>= (match-end 0) pos)
1775 start))))
1776
1777 (defun org-day-of-week (day month year)
1778 "Returns the day of the week as an integer."
1779 (nth 6
1780 (decode-time
1781 (date-to-time
1782 (format "%d-%02d-%02dT00:00:00" year month day)))))
1783
1784 (defun org-quarter-to-date (quarter year)
1785 "Get the date (week day year) of the first day of a given quarter."
1786 (let (startday)
1787 (cond
1788 ((= quarter 1)
1789 (setq startday (org-day-of-week 1 1 year))
1790 (cond
1791 ((= startday 0)
1792 (list 52 7 (- year 1)))
1793 ((= startday 6)
1794 (list 52 6 (- year 1)))
1795 ((<= startday 4)
1796 (list 1 startday year))
1797 ((> startday 4)
1798 (list 53 startday (- year 1)))
1799 )
1800 )
1801 ((= quarter 2)
1802 (setq startday (org-day-of-week 1 4 year))
1803 (cond
1804 ((= startday 0)
1805 (list 13 startday year))
1806 ((< startday 4)
1807 (list 14 startday year))
1808 ((>= startday 4)
1809 (list 13 startday year))
1810 )
1811 )
1812 ((= quarter 3)
1813 (setq startday (org-day-of-week 1 7 year))
1814 (cond
1815 ((= startday 0)
1816 (list 26 startday year))
1817 ((< startday 4)
1818 (list 27 startday year))
1819 ((>= startday 4)
1820 (list 26 startday year))
1821 )
1822 )
1823 ((= quarter 4)
1824 (setq startday (org-day-of-week 1 10 year))
1825 (cond
1826 ((= startday 0)
1827 (list 39 startday year))
1828 ((<= startday 4)
1829 (list 40 startday year))
1830 ((> startday 4)
1831 (list 39 startday year)))))))
1832
1833 (defun org-clock-special-range (key &optional time as-strings)
1834 "Return two times bordering a special time range.
1835 Key is a symbol specifying the range and can be one of `today', `yesterday',
1836 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1837 A week starts Monday 0:00 and ends Sunday 24:00.
1838 The range is determined relative to TIME. TIME defaults to the current time.
1839 The return value is a cons cell with two internal times like the ones
1840 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1841 the returned times will be formatted strings."
1842 (if (integerp key) (setq key (intern (number-to-string key))))
1843 (let* ((tm (decode-time (or time (current-time))))
1844 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1845 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1846 (dow (nth 6 tm))
1847 (skey (symbol-name key))
1848 (shift 0)
1849 (q (cond ((>= (nth 4 tm) 10) 4)
1850 ((>= (nth 4 tm) 7) 3)
1851 ((>= (nth 4 tm) 4) 2)
1852 ((>= (nth 4 tm) 1) 1)))
1853 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1854 interval tmp shiftedy shiftedm shiftedq)
1855 (cond
1856 ((string-match "^[0-9]+$" skey)
1857 (setq y (string-to-number skey) m 1 d 1 key 'year))
1858 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1859 (setq y (string-to-number (match-string 1 skey))
1860 month (string-to-number (match-string 2 skey))
1861 d 1 key 'month))
1862 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1863 (require 'cal-iso)
1864 (setq y (string-to-number (match-string 1 skey))
1865 w (string-to-number (match-string 2 skey)))
1866 (setq date (calendar-gregorian-from-absolute
1867 (calendar-absolute-from-iso (list w 1 y))))
1868 (setq d (nth 1 date) month (car date) y (nth 2 date)
1869 dow 1
1870 key 'week))
1871 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
1872 (require 'cal-iso)
1873 (setq y (string-to-number (match-string 1 skey)))
1874 (setq q (string-to-number (match-string 2 skey)))
1875 (setq date (calendar-gregorian-from-absolute
1876 (calendar-absolute-from-iso (org-quarter-to-date q y))))
1877 (setq d (nth 1 date) month (car date) y (nth 2 date)
1878 dow 1
1879 key 'quarter))
1880 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1881 (setq y (string-to-number (match-string 1 skey))
1882 month (string-to-number (match-string 2 skey))
1883 d (string-to-number (match-string 3 skey))
1884 key 'day))
1885 ((string-match "\\([-+][0-9]+\\)$" skey)
1886 (setq shift (string-to-number (match-string 1 skey))
1887 key (intern (substring skey 0 (match-beginning 1))))
1888 (if(and (memq key '(quarter thisq)) (> shift 0))
1889 (error "Looking forward with quarters isn't implemented.")
1890 ())))
1891
1892 (when (= shift 0)
1893 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1894 ((eq key 'lastweek) (setq key 'week shift -1))
1895 ((eq key 'lastmonth) (setq key 'month shift -1))
1896 ((eq key 'lastyear) (setq key 'year shift -1))
1897 ((eq key 'lastq) (setq key 'quarter shift -1))))
1898 (cond
1899 ((memq key '(day today))
1900 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1901 ((memq key '(week thisweek))
1902 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1903 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1904 ((memq key '(month thismonth))
1905 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1906 ((memq key '(quarter thisq))
1907 ; compute if this shift remains in this year
1908 ; if not, compute how many years and quarters we have to shift (via floor*)
1909 ; and compute the shifted years, months and quarters
1910 (cond
1911 ((< (+ (- q 1) shift) 0) ; shift not in this year
1912 (setq interval (* -1 (+ (- q 1) shift)))
1913 ; set tmp to ((years to shift) (quarters to shift))
1914 (setq tmp (org-floor* interval 4))
1915 ; due to the use of floor, 0 quarters actually means 4
1916 (if (= 0 (nth 1 tmp))
1917 (setq shiftedy (- y (nth 0 tmp))
1918 shiftedm 1
1919 shiftedq 1)
1920 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
1921 shiftedm (- 13 (* 3 (nth 1 tmp)))
1922 shiftedq (- 5 (nth 1 tmp))))
1923 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
1924 ((> (+ q shift) 0) ; shift is whitin this year
1925 (setq shiftedq (+ q shift))
1926 (setq shiftedy y)
1927 (setq d 1 h 0 m 0 d1 1 month (+ 1 (* 3 (- (+ q shift) 1))) month1 (+ 4 (* 3 (- (+ q shift) 1))) h1 0 m1 0))))
1928 ((memq key '(year thisyear))
1929 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1930 (t (error "No such time block %s" key)))
1931 (setq ts (encode-time s m h d month y)
1932 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1933 (or d1 d) (or month1 month) (or y1 y)))
1934 (setq fm (cdr org-time-stamp-formats))
1935 (cond
1936 ((memq key '(day today))
1937 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1938 ((memq key '(week thisweek))
1939 (setq txt (format-time-string "week %G-W%V" ts)))
1940 ((memq key '(month thismonth))
1941 (setq txt (format-time-string "%B %Y" ts)))
1942 ((memq key '(year thisyear))
1943 (setq txt (format-time-string "the year %Y" ts)))
1944 ((memq key '(quarter thisq))
1945 (setq txt (concatenate 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
1946 )
1947 (if as-strings
1948 (list (format-time-string fm ts) (format-time-string fm te) txt)
1949 (list ts te txt))))
1950
1951 (defun org-count-quarter (n)
1952 (cond
1953 ((= n 1) "1st")
1954 ((= n 2) "2nd")
1955 ((= n 3) "3rd")
1956 ((= n 4) "4th")))
1957
1958 (defun org-clocktable-shift (dir n)
1959 "Try to shift the :block date of the clocktable at point.
1960 Point must be in the #+BEGIN: line of a clocktable, or this function
1961 will throw an error.
1962 DIR is a direction, a symbol `left', `right', `up', or `down'.
1963 Both `left' and `down' shift the block toward the past, `up' and `right'
1964 push it toward the future.
1965 N is the number of shift steps to take. The size of the step depends on
1966 the currently selected interval size."
1967 (setq n (prefix-numeric-value n))
1968 (and (memq dir '(left down)) (setq n (- n)))
1969 (save-excursion
1970 (goto-char (point-at-bol))
1971 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1972 (error "Line needs a :block definition before this command works")
1973 (let* ((b (match-beginning 1)) (e (match-end 1))
1974 (s (match-string 1))
1975 block shift ins y mw d date wp m)
1976 (cond
1977 ((equal s "yesterday") (setq s "today-1"))
1978 ((equal s "lastweek") (setq s "thisweek-1"))
1979 ((equal s "lastmonth") (setq s "thismonth-1"))
1980 ((equal s "lastyear") (setq s "thisyear-1"))
1981 ((equal s "lastq") (setq s "thisq-1")))
1982
1983 (cond
1984 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
1985 (setq block (match-string 1 s)
1986 shift (if (match-end 2)
1987 (string-to-number (match-string 2 s))
1988 0))
1989 (setq shift (+ shift n))
1990 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1991 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1992 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1993 (setq y (string-to-number (match-string 1 s))
1994 wp (and (match-end 3) (match-string 3 s))
1995 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1996 d (and (match-end 6) (string-to-number (match-string 6 s))))
1997 (cond
1998 (d (setq ins (format-time-string
1999 "%Y-%m-%d"
2000 (encode-time 0 0 0 (+ d n) m y))))
2001 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2002 (require 'cal-iso)
2003 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
2004 (setq ins (format-time-string
2005 "%G-W%V"
2006 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2007 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2008 (require 'cal-iso)
2009 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2010 (if (> (+ mw n) 4)
2011 (setq mw 0
2012 y (+ 1 y))
2013 ())
2014 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2015 (if (= (+ mw n) 0)
2016 (setq mw 5
2017 y (- y 1))
2018 ())
2019 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
2020 (setq ins (format-time-string
2021 (concatenate 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
2022 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2023 (mw
2024 (setq ins (format-time-string
2025 "%Y-%m"
2026 (encode-time 0 0 0 1 (+ mw n) y))))
2027 (y
2028 (setq ins (number-to-string (+ y n))))))
2029 (t (error "Cannot shift clocktable block")))
2030 (when ins
2031 (goto-char b)
2032 (insert ins)
2033 (delete-region (point) (+ (point) (- e b)))
2034 (beginning-of-line 1)
2035 (org-update-dblock)
2036 t)))))
2037
2038 (defun org-dblock-write:clocktable (params)
2039 "Write the standard clocktable."
2040 (setq params (org-combine-plists org-clocktable-defaults params))
2041 (catch 'exit
2042 (let* ((scope (plist-get params :scope))
2043 (block (plist-get params :block))
2044 (ts (plist-get params :tstart))
2045 (te (plist-get params :tend))
2046 (link (plist-get params :link))
2047 (maxlevel (or (plist-get params :maxlevel) 3))
2048 (step (plist-get params :step))
2049 (timestamp (plist-get params :timestamp))
2050 (formatter (or (plist-get params :formatter)
2051 org-clock-clocktable-formatter
2052 'org-clocktable-write-default))
2053 cc range-text ipos pos one-file-with-archives
2054 scope-is-list tbls level)
2055
2056 ;; Check if we need to do steps
2057 (when block
2058 ;; Get the range text for the header
2059 (setq cc (org-clock-special-range block nil t)
2060 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2061 (when step
2062 ;; Write many tables, in steps
2063 (unless (or block (and ts te))
2064 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2065 (org-clocktable-steps params)
2066 (throw 'exit nil))
2067
2068 (setq ipos (point)) ; remember the insertion position
2069
2070 ;; Get the right scope
2071 (setq pos (point))
2072 (cond
2073 ((and scope (listp scope) (symbolp (car scope)))
2074 (setq scope (eval scope)))
2075 ((eq scope 'agenda)
2076 (setq scope (org-agenda-files t)))
2077 ((eq scope 'agenda-with-archives)
2078 (setq scope (org-agenda-files t))
2079 (setq scope (org-add-archive-files scope)))
2080 ((eq scope 'file-with-archives)
2081 (setq scope (org-add-archive-files (list (buffer-file-name)))
2082 one-file-with-archives t)))
2083 (setq scope-is-list (and scope (listp scope)))
2084 (if scope-is-list
2085 ;; we collect from several files
2086 (let* ((files scope)
2087 file)
2088 (org-prepare-agenda-buffers files)
2089 (while (setq file (pop files))
2090 (with-current-buffer (find-buffer-visiting file)
2091 (save-excursion
2092 (save-restriction
2093 (push (org-clock-get-table-data file params) tbls))))))
2094 ;; Just from the current file
2095 (save-restriction
2096 ;; get the right range into the restriction
2097 (org-prepare-agenda-buffers (list (buffer-file-name)))
2098 (cond
2099 ((not scope)) ; use the restriction as it is now
2100 ((eq scope 'file) (widen))
2101 ((eq scope 'subtree) (org-narrow-to-subtree))
2102 ((eq scope 'tree)
2103 (while (org-up-heading-safe))
2104 (org-narrow-to-subtree))
2105 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
2106 (symbol-name scope)))
2107 (setq level (string-to-number (match-string 1 (symbol-name scope))))
2108 (catch 'exit
2109 (while (org-up-heading-safe)
2110 (looking-at org-outline-regexp)
2111 (if (<= (org-reduced-level (funcall outline-level)) level)
2112 (throw 'exit nil))))
2113 (org-narrow-to-subtree)))
2114 ;; do the table, with no file name.
2115 (push (org-clock-get-table-data nil params) tbls)))
2116
2117 ;; OK, at this point we tbls as a list of tables, one per file
2118 (setq tbls (nreverse tbls))
2119
2120 (setq params (plist-put params :multifile scope-is-list))
2121 (setq params (plist-put params :one-file-with-archives
2122 one-file-with-archives))
2123
2124 (funcall formatter ipos tbls params))))
2125
2126 (defun org-clocktable-write-default (ipos tables params)
2127 "Write out a clock table at position IPOS in the current buffer.
2128 TABLES is a list of tables with clocking data as produced by
2129 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2130 from the dynamic block defintion."
2131 ;; This function looks quite complicated, mainly because there are a
2132 ;; lot of options which can add or remove columns. I have massively
2133 ;; commented this function, the I hope it is understandable. If
2134 ;; someone wants to write their own special formatter, this maybe
2135 ;; much easier because there can be a fixed format with a
2136 ;; well-defined number of columns...
2137 (let* ((hlchars '((1 . "*") (2 . "/")))
2138 (lwords (assoc (or (plist-get params :lang)
2139 org-export-default-language)
2140 org-clock-clocktable-language-setup))
2141 (multifile (plist-get params :multifile))
2142 (block (plist-get params :block))
2143 (ts (plist-get params :tstart))
2144 (te (plist-get params :tend))
2145 (header (plist-get params :header))
2146 (narrow (plist-get params :narrow))
2147 (link (plist-get params :link))
2148 (maxlevel (or (plist-get params :maxlevel) 3))
2149 (emph (plist-get params :emphasize))
2150 (level-p (plist-get params :level))
2151 (timestamp (plist-get params :timestamp))
2152 (properties (plist-get params :properties))
2153 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2154 (rm-file-column (plist-get params :one-file-with-archives))
2155 (indent (plist-get params :indent))
2156 range-text total-time tbl level hlc formula pcol
2157 file-time entries entry headline
2158 recalc content narrow-cut-p tcol)
2159
2160 ;; Implement abbreviations
2161 (when (plist-get params :compact)
2162 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2163
2164 ;; Some consistency test for parameters
2165 (unless (integerp ntcol)
2166 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2167
2168 (when (and narrow (integerp narrow) link)
2169 ;; We cannot have both integer narrow and link
2170 (message
2171 "Using hard narrowing in clocktable to allow for links")
2172 (setq narrow (intern (format "%d!" narrow))))
2173
2174 (when narrow
2175 (cond
2176 ((integerp narrow))
2177 ((and (symbolp narrow)
2178 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2179 (setq narrow-cut-p t
2180 narrow (string-to-number (substring (symbol-name narrow)
2181 0 -1))))
2182 (t
2183 (error "Invalid value %s of :narrow property in clock table"
2184 narrow))))
2185
2186 (when block
2187 ;; Get the range text for the header
2188 (setq range-text (nth 2 (org-clock-special-range block nil t))))
2189
2190 ;; Compute the total time
2191 (setq total-time (apply '+ (mapcar 'cadr tables)))
2192
2193 ;; Now we need to output this tsuff
2194 (goto-char ipos)
2195
2196 ;; Insert the text *before* the actual table
2197 (insert-before-markers
2198 (or header
2199 ;; Format the standard header
2200 (concat
2201 (nth 9 lwords) " ["
2202 (substring
2203 (format-time-string (cdr org-time-stamp-formats))
2204 1 -1)
2205 "]"
2206 (if block (concat ", for " range-text ".") "")
2207 "\n\n")))
2208
2209 ;; Insert the narrowing line
2210 (when (and narrow (integerp narrow) (not narrow-cut-p))
2211 (insert-before-markers
2212 "|" ; table line starter
2213 (if multifile "|" "") ; file column, maybe
2214 (if level-p "|" "") ; level column, maybe
2215 (if timestamp "|" "") ; timestamp column, maybe
2216 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2217 (format "<%d>| |\n" narrow))) ; headline and time columns
2218
2219 ;; Insert the table header line
2220 (insert-before-markers
2221 "|" ; table line starter
2222 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2223 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2224 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2225 (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
2226 (concat (nth 4 lwords) "|"
2227 (nth 5 lwords) "|\n")) ; headline and time columns
2228
2229 ;; Insert the total time in the table
2230 (insert-before-markers
2231 "|-\n" ; a hline
2232 "|" ; table line starter
2233 (if multifile (concat "| " (nth 6 lwords) " ") "")
2234 ; file column, maybe
2235 (if level-p "|" "") ; level column, maybe
2236 (if timestamp "|" "") ; timestamp column, maybe
2237 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2238 (concat "*" (nth 7 lwords) "*| ") ; instead of a headline
2239 "*"
2240 (org-minutes-to-hh:mm-string (or total-time 0)) ; the time
2241 "*|\n") ; close line
2242
2243 ;; Now iterate over the tables and insert the data
2244 ;; but only if any time has been collected
2245 (when (and total-time (> total-time 0))
2246
2247 (while (setq tbl (pop tables))
2248 ;; now tbl is the table resulting from one file.
2249 (setq file-time (nth 1 tbl))
2250 (when (or (and file-time (> file-time 0))
2251 (not (plist-get params :fileskip0)))
2252 (insert-before-markers "|-\n") ; a hline because a new file starts
2253 ;; First the file time, if we have multiple files
2254 (when multifile
2255 ;; Summarize the time collected from this file
2256 (insert-before-markers
2257 (format (concat "| %s %s | %s%s*" (nth 8 lwords) "* | *%s*|\n")
2258 (file-name-nondirectory (car tbl))
2259 (if level-p "| " "") ; level column, maybe
2260 (if timestamp "| " "") ; timestamp column, maybe
2261 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2262 (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
2263
2264 ;; Get the list of node entries and iterate over it
2265 (setq entries (nth 2 tbl))
2266 (while (setq entry (pop entries))
2267 (setq level (car entry)
2268 headline (nth 1 entry)
2269 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2270 (when narrow-cut-p
2271 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2272 "\\'")
2273 headline)
2274 (match-end 3))
2275 (setq headline
2276 (format "[[%s][%s]]"
2277 (match-string 1 headline)
2278 (org-shorten-string (match-string 3 headline)
2279 narrow)))
2280 (setq headline (org-shorten-string headline narrow))))
2281 (insert-before-markers
2282 "|" ; start the table line
2283 (if multifile "|" "") ; free space for file name column?
2284 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2285 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2286 (if properties
2287 (concat
2288 (mapconcat
2289 (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
2290 properties "|") "|") "") ;properties columns, maybe
2291 (if indent (org-clocktable-indent-string level) "") ; indentation
2292 hlc headline hlc "|" ; headline
2293 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2294 ; empty fields for higher levels
2295 hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
2296 "|\n" ; close line
2297 )))))
2298 (backward-delete-char 1)
2299 (if (setq formula (plist-get params :formula))
2300 (cond
2301 ((eq formula '%)
2302 ;; compute the column where the % numbers need to go
2303 (setq pcol (+ 2
2304 (if multifile 1 0)
2305 (if level-p 1 0)
2306 (if timestamp 1 0)
2307 (min maxlevel (or ntcol 100))))
2308 ;; compute the column where the total time is
2309 (setq tcol (+ 2
2310 (if multifile 1 0)
2311 (if level-p 1 0)
2312 (if timestamp 1 0)))
2313 (insert
2314 (format
2315 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2316 pcol ; the column where the % numbers should go
2317 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2318 tcol ; column of the total time
2319 tcol (1- pcol) ; range of columns where times can be found
2320 ))
2321 (setq recalc t))
2322 ((stringp formula)
2323 (insert "\n#+TBLFM: " formula)
2324 (setq recalc t))
2325 (t (error "invalid formula in clocktable")))
2326 ;; Should we rescue an old formula?
2327 (when (stringp (setq content (plist-get params :content)))
2328 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
2329 (setq recalc t)
2330 (insert "\n" (match-string 1 (plist-get params :content)))
2331 (beginning-of-line 0))))
2332 ;; Back to beginning, align the table, recalculate if necessary
2333 (goto-char ipos)
2334 (skip-chars-forward "^|")
2335 (org-table-align)
2336 (when org-hide-emphasis-markers
2337 ;; we need to align a second time
2338 (org-table-align))
2339 (when recalc
2340 (if (eq formula '%)
2341 (save-excursion
2342 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2343 (org-table-goto-column pcol nil 'force)
2344 (insert "%")))
2345 (org-table-recalculate 'all))
2346 (when rm-file-column
2347 ;; The file column is actually not wanted
2348 (forward-char 1)
2349 (org-table-delete-column))
2350 total-time))
2351
2352 (defun org-clocktable-indent-string (level)
2353 (if (= level 1)
2354 ""
2355 (let ((str "\\__"))
2356 (while (> level 2)
2357 (setq level (1- level)
2358 str (concat str "___")))
2359 (concat str " "))))
2360
2361 (defun org-clocktable-steps (params)
2362 "Step through the range to make a number of clock tables."
2363 (let* ((p1 (copy-sequence params))
2364 (ts (plist-get p1 :tstart))
2365 (te (plist-get p1 :tend))
2366 (step0 (plist-get p1 :step))
2367 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2368 (stepskip0 (plist-get p1 :stepskip0))
2369 (block (plist-get p1 :block))
2370 cc range-text step-time)
2371 (when block
2372 (setq cc (org-clock-special-range block nil t)
2373 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2374 (cond
2375 ((numberp ts)
2376 ;; If ts is a number, it's an absolute day number from org-agenda.
2377 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2378 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2379 (ts
2380 (setq ts (org-float-time
2381 (apply 'encode-time (org-parse-time-string ts))))))
2382 (cond
2383 ((numberp te)
2384 ;; Likewise for te.
2385 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2386 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2387 (te
2388 (setq te (org-float-time
2389 (apply 'encode-time (org-parse-time-string te))))))
2390 (setq p1 (plist-put p1 :header ""))
2391 (setq p1 (plist-put p1 :step nil))
2392 (setq p1 (plist-put p1 :block nil))
2393 (while (< ts te)
2394 (or (bolp) (insert "\n"))
2395 (setq p1 (plist-put p1 :tstart (format-time-string
2396 (org-time-stamp-format nil t)
2397 (seconds-to-time ts))))
2398 (setq p1 (plist-put p1 :tend (format-time-string
2399 (org-time-stamp-format nil t)
2400 (seconds-to-time (setq ts (+ ts step))))))
2401 (insert "\n" (if (eq step0 'day) "Daily report: "
2402 "Weekly report starting on: ")
2403 (plist-get p1 :tstart) "\n")
2404 (setq step-time (org-dblock-write:clocktable p1))
2405 (re-search-forward "^[ \t]*#\\+END:")
2406 (when (and (equal step-time 0) stepskip0)
2407 ;; Remove the empty table
2408 (delete-region (point-at-bol)
2409 (save-excursion
2410 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2411 nil t)
2412 (point))))
2413 (end-of-line 0))))
2414
2415 (defun org-clock-get-table-data (file params)
2416 "Get the clocktable data for file FILE, with parameters PARAMS.
2417 FILE is only for identification - this function assumes that
2418 the correct buffer is current, and that the wanted restriction is
2419 in place.
2420 The return value will be a list with the file name and the total
2421 file time (in minutes) as 1st and 2nd elements. The third element
2422 of this list will be a list of headline entries. Each entry has the
2423 following structure:
2424
2425 (LEVEL HEADLINE TIMESTAMP TIME)
2426
2427 LEVEL: The level of the headline, as an integer. This will be
2428 the reduced leve, so 1,2,3,... even if only odd levels
2429 are being used.
2430 HEADLINE: The text of the headline. Depending on PARAMS, this may
2431 already be formatted like a link.
2432 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2433 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2434 in this sequence.
2435 TIME: The sum of all time spend in this tree, in minutes. This time
2436 will of cause be restricted to the time block and tags match
2437 specified in PARAMS."
2438 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2439 (timestamp (plist-get params :timestamp))
2440 (ts (plist-get params :tstart))
2441 (te (plist-get params :tend))
2442 (block (plist-get params :block))
2443 (link (plist-get params :link))
2444 (tags (plist-get params :tags))
2445 (properties (plist-get params :properties))
2446 (inherit-property-p (plist-get params :inherit-props))
2447 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2448 cc range-text st p time level hdl props tsp tbl)
2449
2450 (setq org-clock-file-total-minutes nil)
2451 (when block
2452 (setq cc (org-clock-special-range block nil t)
2453 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2454 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2455 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2456 (when (and ts (listp ts))
2457 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2458 (when (and te (listp te))
2459 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2460 ;; Now the times are strings we can parse.
2461 (if ts (setq ts (org-float-time
2462 (apply 'encode-time (org-parse-time-string ts)))))
2463 (if te (setq te (org-float-time
2464 (apply 'encode-time (org-parse-time-string te)))))
2465 (save-excursion
2466 (org-clock-sum ts te
2467 (unless (null matcher)
2468 (lambda ()
2469 (let ((tags-list (org-get-tags-at)))
2470 (eval matcher)))))
2471 (goto-char (point-min))
2472 (setq st t)
2473 (while (or (and (bobp) (prog1 st (setq st nil))
2474 (get-text-property (point) :org-clock-minutes)
2475 (setq p (point-min)))
2476 (setq p (next-single-property-change
2477 (point) :org-clock-minutes)))
2478 (goto-char p)
2479 (when (setq time (get-text-property p :org-clock-minutes))
2480 (save-excursion
2481 (beginning-of-line 1)
2482 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2483 (setq level (org-reduced-level
2484 (- (match-end 1) (match-beginning 1))))
2485 (<= level maxlevel))
2486 (setq hdl (if (not link)
2487 (match-string 2)
2488 (org-make-link-string
2489 (format "file:%s::%s"
2490 (buffer-file-name)
2491 (save-match-data
2492 (org-make-org-heading-search-string
2493 (match-string 2))))
2494 (match-string 2)))
2495 tsp (when timestamp
2496 (setq props (org-entry-properties (point)))
2497 (or (cdr (assoc "SCHEDULED" props))
2498 (cdr (assoc "DEADLINE" props))
2499 (cdr (assoc "TIMESTAMP" props))
2500 (cdr (assoc "TIMESTAMP_IA" props))))
2501 props (when properties
2502 (remove nil
2503 (mapcar
2504 (lambda (p)
2505 (when (org-entry-get (point) p inherit-property-p)
2506 (cons p (org-entry-get (point) p inherit-property-p))))
2507 properties))))
2508 (when (> time 0) (push (list level hdl tsp time props) tbl))))))
2509 (setq tbl (nreverse tbl))
2510 (list file org-clock-file-total-minutes tbl))))
2511
2512 (defun org-clock-time% (total &rest strings)
2513 "Compute a time fraction in percent.
2514 TOTAL s a time string like 10:21 specifying the total times.
2515 STRINGS is a list of strings that should be checked for a time.
2516 The first string that does have a time will be used.
2517 This function is made for clock tables."
2518 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2519 tot s)
2520 (save-match-data
2521 (catch 'exit
2522 (if (not (string-match re total))
2523 (throw 'exit 0.)
2524 (setq tot (+ (string-to-number (match-string 2 total))
2525 (* 60 (string-to-number (match-string 1 total)))))
2526 (if (= tot 0.) (throw 'exit 0.)))
2527 (while (setq s (pop strings))
2528 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2529 (throw 'exit
2530 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2531 (* 60 (string-to-number
2532 (match-string 1 s)))))
2533 tot))))
2534 0))))
2535
2536 ;; Saving and loading the clock
2537
2538 (defvar org-clock-loaded nil
2539 "Was the clock file loaded?")
2540
2541 (defun org-clock-save ()
2542 "Persist various clock-related data to disk.
2543 The details of what will be saved are regulated by the variable
2544 `org-clock-persist'."
2545 (when (and org-clock-persist
2546 (or org-clock-loaded
2547 org-clock-has-been-used
2548 (not (file-exists-p org-clock-persist-file))))
2549 (let (b)
2550 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2551 (progn
2552 (delete-region (point-min) (point-max))
2553 ;;Store clock
2554 (insert (format ";; org-persist.el - %s at %s\n"
2555 system-name (format-time-string
2556 (cdr org-time-stamp-formats))))
2557 (if (and (memq org-clock-persist '(t clock))
2558 (setq b (org-clocking-buffer))
2559 (setq b (or (buffer-base-buffer b) b))
2560 (buffer-live-p b)
2561 (buffer-file-name b)
2562 (or (not org-clock-persist-query-save)
2563 (y-or-n-p (concat "Save current clock ("
2564 (substring-no-properties
2565 org-clock-heading)
2566 ") "))))
2567 (insert "(setq resume-clock '(\""
2568 (buffer-file-name (org-clocking-buffer))
2569 "\" . " (int-to-string (marker-position org-clock-marker))
2570 "))\n"))
2571 ;; Store clocked task history. Tasks are stored reversed to make
2572 ;; reading simpler
2573 (when (and (memq org-clock-persist '(t history))
2574 org-clock-history)
2575 (insert
2576 "(setq stored-clock-history '("
2577 (mapconcat
2578 (lambda (m)
2579 (when (and (setq b (marker-buffer m))
2580 (setq b (or (buffer-base-buffer b) b))
2581 (buffer-live-p b)
2582 (buffer-file-name b))
2583 (concat "(\"" (buffer-file-name b)
2584 "\" . " (int-to-string (marker-position m))
2585 ")")))
2586 (reverse org-clock-history) " ") "))\n"))
2587 (save-buffer)
2588 (kill-buffer (current-buffer)))))))
2589
2590 (defun org-clock-load ()
2591 "Load clock-related data from disk, maybe resuming a stored clock."
2592 (when (and org-clock-persist (not org-clock-loaded))
2593 (let ((filename (expand-file-name org-clock-persist-file))
2594 (org-clock-in-resume 'auto-restart)
2595 resume-clock stored-clock-history)
2596 (if (not (file-readable-p filename))
2597 (message "Not restoring clock data; %s not found"
2598 org-clock-persist-file)
2599 (message "%s" "Restoring clock data")
2600 (setq org-clock-loaded t)
2601 (load-file filename)
2602 ;; load history
2603 (when stored-clock-history
2604 (save-window-excursion
2605 (mapc (lambda (task)
2606 (if (file-exists-p (car task))
2607 (org-clock-history-push (cdr task)
2608 (find-file (car task)))))
2609 stored-clock-history)))
2610 ;; resume clock
2611 (when (and resume-clock org-clock-persist
2612 (file-exists-p (car resume-clock))
2613 (or (not org-clock-persist-query-resume)
2614 (y-or-n-p
2615 (concat
2616 "Resume clock ("
2617 (with-current-buffer (find-file (car resume-clock))
2618 (save-excursion
2619 (goto-char (cdr resume-clock))
2620 (org-back-to-heading t)
2621 (and (looking-at org-complex-heading-regexp)
2622 (match-string 4))))
2623 ") "))))
2624 (when (file-exists-p (car resume-clock))
2625 (with-current-buffer (find-file (car resume-clock))
2626 (goto-char (cdr resume-clock))
2627 (let ((org-clock-auto-clock-resolution nil))
2628 (org-clock-in)
2629 (if (outline-invisible-p)
2630 (org-show-context))))))))))
2631
2632 ;;;###autoload
2633 (defun org-clock-persistence-insinuate ()
2634 "Set up hooks for clock persistence."
2635 (add-hook 'org-mode-hook 'org-clock-load)
2636 (add-hook 'kill-emacs-hook 'org-clock-save))
2637
2638 ;; Suggested bindings
2639 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2640
2641 (provide 'org-clock)
2642
2643
2644
2645 ;;; org-clock.el ends here
2646