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