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