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