Add version tag "24.1" for options introduced since Emacs 23.4 (and <= 24.1)
[org-mode.git] / lisp / org-clock.el
blob92066082df55f1296d89a4b8612fcb55865bc790
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 (unless (org-clocking-p)
1397 (org-clock-delete-current)))))))
1399 (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
1401 (defun org-clock-remove-empty-clock-drawer nil
1402 "Remove empty clock drawer in the current subtree."
1403 (let* ((olid (or (org-entry-get (point) "LOG_INTO_DRAWER")
1404 org-log-into-drawer))
1405 (clock-drawer (if (eq t olid) "LOGBOOK" olid))
1406 (end (save-excursion (org-end-of-subtree t t))))
1407 (when clock-drawer
1408 (save-excursion
1409 (org-back-to-heading t)
1410 (while (search-forward clock-drawer end t)
1411 (goto-char (match-beginning 0))
1412 (org-remove-empty-drawer-at clock-drawer (point))
1413 (forward-line 1))))))
1415 (defun org-at-clock-log-p nil
1416 "Is the cursor on the clock log line?"
1417 (save-excursion
1418 (move-beginning-of-line 1)
1419 (looking-at "^[ \t]*CLOCK:")))
1421 (defun org-clock-timestamps-up nil
1422 "Increase CLOCK timestamps at cursor."
1423 (interactive)
1424 (org-clock-timestamps-change 'up))
1426 (defun org-clock-timestamps-down nil
1427 "Increase CLOCK timestamps at cursor."
1428 (interactive)
1429 (org-clock-timestamps-change 'down))
1431 (defun org-clock-timestamps-change (updown)
1432 "Change CLOCK timestamps synchronously at cursor.
1433 UPDOWN tells whether to change 'up or 'down."
1434 (setq org-ts-what nil)
1435 (when (org-at-timestamp-p t)
1436 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1437 'org-timestamp-down))
1438 ts1 begts1 ts2 begts2 updatets1 tdiff)
1439 (save-excursion
1440 (move-beginning-of-line 1)
1441 (re-search-forward org-ts-regexp3 nil t)
1442 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1443 (when (re-search-forward org-ts-regexp3 nil t)
1444 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1445 ;; Are we on the second timestamp?
1446 (if (<= begts2 (point)) (setq updatets1 t))
1447 (if (not ts2)
1448 ;; fall back on org-timestamp-up if there is only one
1449 (funcall tschange)
1450 ;; setq this so that (boundp 'org-ts-what is non-nil)
1451 (funcall tschange)
1452 (let ((ts (if updatets1 ts2 ts1))
1453 (begts (if updatets1 begts1 begts2)))
1454 (setq tdiff
1455 (subtract-time
1456 (org-time-string-to-time org-last-changed-timestamp)
1457 (org-time-string-to-time ts)))
1458 (save-excursion
1459 (goto-char begts)
1460 (org-timestamp-change
1461 (round (/ (org-float-time tdiff)
1462 (cond ((eq org-ts-what 'minute) 60)
1463 ((eq org-ts-what 'hour) 3600)
1464 ((eq org-ts-what 'day) (* 24 3600))
1465 ((eq org-ts-what 'month) (* 24 3600 31))
1466 ((eq org-ts-what 'year) (* 24 3600 365.2)))))
1467 org-ts-what 'updown)))))))
1469 (defun org-clock-cancel ()
1470 "Cancel the running clock by removing the start timestamp."
1471 (interactive)
1472 (when (not (org-clocking-p))
1473 (setq global-mode-string
1474 (delq 'org-mode-line-string global-mode-string))
1475 (force-mode-line-update)
1476 (error "No active clock"))
1477 (save-excursion ; Do not replace this with `with-current-buffer'.
1478 (with-no-warnings (set-buffer (org-clocking-buffer)))
1479 (goto-char org-clock-marker)
1480 (delete-region (1- (point-at-bol)) (point-at-eol))
1481 ;; Just in case, remove any empty LOGBOOK left over
1482 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1483 (move-marker org-clock-marker nil)
1484 (move-marker org-clock-hd-marker nil)
1485 (setq global-mode-string
1486 (delq 'org-mode-line-string global-mode-string))
1487 (force-mode-line-update)
1488 (message "Clock canceled")
1489 (run-hooks 'org-clock-cancel-hook))
1491 (defun org-clock-goto (&optional select)
1492 "Go to the currently clocked-in entry, or to the most recently clocked one.
1493 With prefix arg SELECT, offer recently clocked tasks for selection."
1494 (interactive "@P")
1495 (let* ((recent nil)
1496 (m (cond
1497 (select
1498 (or (org-clock-select-task "Select task to go to: ")
1499 (error "No task selected")))
1500 ((org-clocking-p) org-clock-marker)
1501 ((and org-clock-goto-may-find-recent-task
1502 (car org-clock-history)
1503 (marker-buffer (car org-clock-history)))
1504 (setq recent t)
1505 (car org-clock-history))
1506 (t (error "No active or recent clock task")))))
1507 (org-pop-to-buffer-same-window (marker-buffer m))
1508 (if (or (< m (point-min)) (> m (point-max))) (widen))
1509 (goto-char m)
1510 (org-show-entry)
1511 (org-back-to-heading t)
1512 (org-cycle-hide-drawers 'children)
1513 (recenter)
1514 (org-reveal)
1515 (if recent
1516 (message "No running clock, this is the most recently clocked task"))
1517 (run-hooks 'org-clock-goto-hook)))
1519 (defvar org-clock-file-total-minutes nil
1520 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1521 (make-variable-buffer-local 'org-clock-file-total-minutes)
1523 (defun org-clock-sum (&optional tstart tend headline-filter)
1524 "Sum the times for each subtree.
1525 Puts the resulting times in minutes as a text property on each headline.
1526 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1527 zero-arg function that, if specified, is called for each headline in the time
1528 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1529 nil are excluded from the clock summation."
1530 (interactive)
1531 (let* ((bmp (buffer-modified-p))
1532 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1533 org-clock-string
1534 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1535 (lmax 30)
1536 (ltimes (make-vector lmax 0))
1537 (t1 0)
1538 (level 0)
1539 ts te dt
1540 time)
1541 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1542 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1543 (if (consp tstart) (setq tstart (org-float-time tstart)))
1544 (if (consp tend) (setq tend (org-float-time tend)))
1545 (remove-text-properties (point-min) (point-max)
1546 '(:org-clock-minutes t
1547 :org-clock-force-headline-inclusion t))
1548 (save-excursion
1549 (goto-char (point-max))
1550 (while (re-search-backward re nil t)
1551 (cond
1552 ((match-end 2)
1553 ;; Two time stamps
1554 (setq ts (match-string 2)
1555 te (match-string 3)
1556 ts (org-float-time
1557 (apply 'encode-time (org-parse-time-string ts)))
1558 te (org-float-time
1559 (apply 'encode-time (org-parse-time-string te)))
1560 ts (if tstart (max ts tstart) ts)
1561 te (if tend (min te tend) te)
1562 dt (- te ts)
1563 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1564 ((match-end 4)
1565 ;; A naked time
1566 (setq t1 (+ t1 (string-to-number (match-string 5))
1567 (* 60 (string-to-number (match-string 4))))))
1568 (t ;; A headline
1569 ;; Add the currently clocking item time to the total
1570 (when (and org-clock-report-include-clocking-task
1571 (equal (org-clocking-buffer) (current-buffer))
1572 (equal (marker-position org-clock-hd-marker) (point))
1573 tstart
1574 tend
1575 (>= (org-float-time org-clock-start-time) tstart)
1576 (<= (org-float-time org-clock-start-time) tend))
1577 (let ((time (floor (- (org-float-time)
1578 (org-float-time org-clock-start-time)) 60)))
1579 (setq t1 (+ t1 time))))
1580 (let* ((headline-forced
1581 (get-text-property (point)
1582 :org-clock-force-headline-inclusion))
1583 (headline-included
1584 (or (null headline-filter)
1585 (save-excursion
1586 (save-match-data (funcall headline-filter))))))
1587 (setq level (- (match-end 1) (match-beginning 1)))
1588 (when (or (> t1 0) (> (aref ltimes level) 0))
1589 (when (or headline-included headline-forced)
1590 (if headline-included
1591 (loop for l from 0 to level do
1592 (aset ltimes l (+ (aref ltimes l) t1))))
1593 (setq time (aref ltimes level))
1594 (goto-char (match-beginning 0))
1595 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1596 (if headline-filter
1597 (save-excursion
1598 (save-match-data
1599 (while
1600 (> (funcall outline-level) 1)
1601 (outline-up-heading 1 t)
1602 (put-text-property
1603 (point) (point-at-eol)
1604 :org-clock-force-headline-inclusion t))))))
1605 (setq t1 0)
1606 (loop for l from level to (1- lmax) do
1607 (aset ltimes l 0)))))))
1608 (setq org-clock-file-total-minutes (aref ltimes 0)))
1609 (set-buffer-modified-p bmp)))
1611 (defun org-clock-sum-current-item (&optional tstart)
1612 "Return time, clocked on current item in total."
1613 (save-excursion
1614 (save-restriction
1615 (org-narrow-to-subtree)
1616 (org-clock-sum tstart)
1617 org-clock-file-total-minutes)))
1619 (defun org-clock-display (&optional total-only)
1620 "Show subtree times in the entire buffer.
1621 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1622 in the echo area.
1624 Use \\[org-clock-remove-overlays] to remove the subtree times."
1625 (interactive)
1626 (org-clock-remove-overlays)
1627 (let (time h m p)
1628 (org-clock-sum)
1629 (unless total-only
1630 (save-excursion
1631 (goto-char (point-min))
1632 (while (or (and (equal (setq p (point)) (point-min))
1633 (get-text-property p :org-clock-minutes))
1634 (setq p (next-single-property-change
1635 (point) :org-clock-minutes)))
1636 (goto-char p)
1637 (when (setq time (get-text-property p :org-clock-minutes))
1638 (org-clock-put-overlay time (funcall outline-level))))
1639 (setq h (/ org-clock-file-total-minutes 60)
1640 m (- org-clock-file-total-minutes (* 60 h)))
1641 ;; Arrange to remove the overlays upon next change.
1642 (when org-remove-highlights-with-change
1643 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1644 nil 'local))))
1645 (if org-time-clocksum-use-fractional
1646 (message (concat "Total file time: " org-time-clocksum-fractional-format
1647 " (%d hours and %d minutes)")
1648 (/ (+ (* h 60.0) m) 60.0) h m)
1649 (message (concat "Total file time: " org-time-clocksum-format
1650 " (%d hours and %d minutes)") h m h m))))
1652 (defvar org-clock-overlays nil)
1653 (make-variable-buffer-local 'org-clock-overlays)
1655 (defun org-clock-put-overlay (time &optional level)
1656 "Put an overlays on the current line, displaying TIME.
1657 If LEVEL is given, prefix time with a corresponding number of stars.
1658 This creates a new overlay and stores it in `org-clock-overlays', so that it
1659 will be easy to remove."
1660 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1661 (l (if level (org-get-valid-level level 0) 0))
1662 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1663 org-time-clocksum-fractional-format
1664 org-time-clocksum-format) "%s"))
1665 (off 0)
1666 ov tx)
1667 (org-move-to-column c)
1668 (unless (eolp) (skip-chars-backward "^ \t"))
1669 (skip-chars-backward " \t")
1670 (setq ov (make-overlay (1- (point)) (point-at-eol))
1671 tx (concat (buffer-substring (1- (point)) (point))
1672 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1673 (org-add-props (if org-time-clocksum-use-fractional
1674 (format fmt
1675 (make-string l ?*)
1676 (/ (+ (* h 60.0) m) 60.0)
1677 (make-string (- 16 l) ?\ ))
1678 (format fmt
1679 (make-string l ?*) h m
1680 (make-string (- 16 l) ?\ )))
1681 (list 'face 'org-clock-overlay))
1682 ""))
1683 (if (not (featurep 'xemacs))
1684 (overlay-put ov 'display tx)
1685 (overlay-put ov 'invisible t)
1686 (overlay-put ov 'end-glyph (make-glyph tx)))
1687 (push ov org-clock-overlays)))
1689 (defun org-clock-remove-overlays (&optional beg end noremove)
1690 "Remove the occur highlights from the buffer.
1691 BEG and END are ignored. If NOREMOVE is nil, remove this function
1692 from the `before-change-functions' in the current buffer."
1693 (interactive)
1694 (unless org-inhibit-highlight-removal
1695 (mapc 'delete-overlay org-clock-overlays)
1696 (setq org-clock-overlays nil)
1697 (unless noremove
1698 (remove-hook 'before-change-functions
1699 'org-clock-remove-overlays 'local))))
1701 (defvar state) ;; dynamically scoped into this function
1702 (defun org-clock-out-if-current ()
1703 "Clock out if the current entry contains the running clock.
1704 This is used to stop the clock after a TODO entry is marked DONE,
1705 and is only done if the variable `org-clock-out-when-done' is not nil."
1706 (when (and (org-clocking-p)
1707 org-clock-out-when-done
1708 (marker-buffer org-clock-marker)
1709 (or (and (eq t org-clock-out-when-done)
1710 (member state org-done-keywords))
1711 (and (listp org-clock-out-when-done)
1712 (member state org-clock-out-when-done)))
1713 (equal (or (buffer-base-buffer (org-clocking-buffer))
1714 (org-clocking-buffer))
1715 (or (buffer-base-buffer (current-buffer))
1716 (current-buffer)))
1717 (< (point) org-clock-marker)
1718 (> (save-excursion (outline-next-heading) (point))
1719 org-clock-marker))
1720 ;; Clock out, but don't accept a logging message for this.
1721 (let ((org-log-note-clock-out nil)
1722 (org-clock-out-switch-to-state nil))
1723 (org-clock-out))))
1725 (add-hook 'org-after-todo-state-change-hook
1726 'org-clock-out-if-current)
1728 ;;;###autoload
1729 (defun org-get-clocktable (&rest props)
1730 "Get a formatted clocktable with parameters according to PROPS.
1731 The table is created in a temporary buffer, fully formatted and
1732 fontified, and then returned."
1733 ;; Set the defaults
1734 (setq props (plist-put props :name "clocktable"))
1735 (unless (plist-member props :maxlevel)
1736 (setq props (plist-put props :maxlevel 2)))
1737 (unless (plist-member props :scope)
1738 (setq props (plist-put props :scope 'agenda)))
1739 (with-temp-buffer
1740 (org-mode)
1741 (org-create-dblock props)
1742 (org-update-dblock)
1743 (font-lock-fontify-buffer)
1744 (forward-line 2)
1745 (buffer-substring (point) (progn
1746 (re-search-forward "^[ \t]*#\\+END" nil t)
1747 (point-at-bol)))))
1749 (defun org-clock-report (&optional arg)
1750 "Create a table containing a report about clocked time.
1751 If the cursor is inside an existing clocktable block, then the table
1752 will be updated. If not, a new clocktable will be inserted. The scope
1753 of the new clock will be subtree when called from within a subtree, and
1754 file elsewhere.
1756 When called with a prefix argument, move to the first clock table in the
1757 buffer and update it."
1758 (interactive "P")
1759 (org-clock-remove-overlays)
1760 (when arg
1761 (org-find-dblock "clocktable")
1762 (org-show-entry))
1763 (if (org-in-clocktable-p)
1764 (goto-char (org-in-clocktable-p))
1765 (let ((props (if (ignore-errors
1766 (save-excursion (org-back-to-heading)))
1767 (list :name "clocktable" :scope 'subtree)
1768 (list :name "clocktable"))))
1769 (org-create-dblock
1770 (org-combine-plists org-clock-clocktable-default-properties props))))
1771 (org-update-dblock))
1773 (defun org-day-of-week (day month year)
1774 "Returns the day of the week as an integer."
1775 (nth 6
1776 (decode-time
1777 (date-to-time
1778 (format "%d-%02d-%02dT00:00:00" year month day)))))
1780 (defun org-quarter-to-date (quarter year)
1781 "Get the date (week day year) of the first day of a given quarter."
1782 (let (startday)
1783 (cond
1784 ((= quarter 1)
1785 (setq startday (org-day-of-week 1 1 year))
1786 (cond
1787 ((= startday 0)
1788 (list 52 7 (- year 1)))
1789 ((= startday 6)
1790 (list 52 6 (- year 1)))
1791 ((<= startday 4)
1792 (list 1 startday year))
1793 ((> startday 4)
1794 (list 53 startday (- year 1)))
1797 ((= quarter 2)
1798 (setq startday (org-day-of-week 1 4 year))
1799 (cond
1800 ((= startday 0)
1801 (list 13 startday year))
1802 ((< startday 4)
1803 (list 14 startday year))
1804 ((>= startday 4)
1805 (list 13 startday year))
1808 ((= quarter 3)
1809 (setq startday (org-day-of-week 1 7 year))
1810 (cond
1811 ((= startday 0)
1812 (list 26 startday year))
1813 ((< startday 4)
1814 (list 27 startday year))
1815 ((>= startday 4)
1816 (list 26 startday year))
1819 ((= quarter 4)
1820 (setq startday (org-day-of-week 1 10 year))
1821 (cond
1822 ((= startday 0)
1823 (list 39 startday year))
1824 ((<= startday 4)
1825 (list 40 startday year))
1826 ((> startday 4)
1827 (list 39 startday year)))))))
1829 (defun org-clock-special-range (key &optional time as-strings)
1830 "Return two times bordering a special time range.
1831 Key is a symbol specifying the range and can be one of `today', `yesterday',
1832 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1833 A week starts Monday 0:00 and ends Sunday 24:00.
1834 The range is determined relative to TIME. TIME defaults to the current time.
1835 The return value is a cons cell with two internal times like the ones
1836 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1837 the returned times will be formatted strings."
1838 (if (integerp key) (setq key (intern (number-to-string key))))
1839 (let* ((tm (decode-time (or time (current-time))))
1840 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1841 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1842 (dow (nth 6 tm))
1843 (skey (symbol-name key))
1844 (shift 0)
1845 (q (cond ((>= (nth 4 tm) 10) 4)
1846 ((>= (nth 4 tm) 7) 3)
1847 ((>= (nth 4 tm) 4) 2)
1848 ((>= (nth 4 tm) 1) 1)))
1849 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1850 interval tmp shiftedy shiftedm shiftedq)
1851 (cond
1852 ((string-match "^[0-9]+$" skey)
1853 (setq y (string-to-number skey) m 1 d 1 key 'year))
1854 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1855 (setq y (string-to-number (match-string 1 skey))
1856 month (string-to-number (match-string 2 skey))
1857 d 1 key 'month))
1858 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1859 (require 'cal-iso)
1860 (setq y (string-to-number (match-string 1 skey))
1861 w (string-to-number (match-string 2 skey)))
1862 (setq date (calendar-gregorian-from-absolute
1863 (calendar-absolute-from-iso (list w 1 y))))
1864 (setq d (nth 1 date) month (car date) y (nth 2 date)
1865 dow 1
1866 key 'week))
1867 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
1868 (require 'cal-iso)
1869 (setq y (string-to-number (match-string 1 skey)))
1870 (setq q (string-to-number (match-string 2 skey)))
1871 (setq date (calendar-gregorian-from-absolute
1872 (calendar-absolute-from-iso (org-quarter-to-date q y))))
1873 (setq d (nth 1 date) month (car date) y (nth 2 date)
1874 dow 1
1875 key 'quarter))
1876 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1877 (setq y (string-to-number (match-string 1 skey))
1878 month (string-to-number (match-string 2 skey))
1879 d (string-to-number (match-string 3 skey))
1880 key 'day))
1881 ((string-match "\\([-+][0-9]+\\)$" skey)
1882 (setq shift (string-to-number (match-string 1 skey))
1883 key (intern (substring skey 0 (match-beginning 1))))
1884 (if(and (memq key '(quarter thisq)) (> shift 0))
1885 (error "Looking forward with quarters isn't implemented.")
1886 ())))
1888 (when (= shift 0)
1889 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1890 ((eq key 'lastweek) (setq key 'week shift -1))
1891 ((eq key 'lastmonth) (setq key 'month shift -1))
1892 ((eq key 'lastyear) (setq key 'year shift -1))
1893 ((eq key 'lastq) (setq key 'quarter shift -1))))
1894 (cond
1895 ((memq key '(day today))
1896 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1897 ((memq key '(week thisweek))
1898 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1899 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1900 ((memq key '(month thismonth))
1901 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1902 ((memq key '(quarter thisq))
1903 ; compute if this shift remains in this year
1904 ; if not, compute how many years and quarters we have to shift (via floor*)
1905 ; and compute the shifted years, months and quarters
1906 (cond
1907 ((< (+ (- q 1) shift) 0) ; shift not in this year
1908 (setq interval (* -1 (+ (- q 1) shift)))
1909 ; set tmp to ((years to shift) (quarters to shift))
1910 (setq tmp (org-floor* interval 4))
1911 ; due to the use of floor, 0 quarters actually means 4
1912 (if (= 0 (nth 1 tmp))
1913 (setq shiftedy (- y (nth 0 tmp))
1914 shiftedm 1
1915 shiftedq 1)
1916 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
1917 shiftedm (- 13 (* 3 (nth 1 tmp)))
1918 shiftedq (- 5 (nth 1 tmp))))
1919 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
1920 ((> (+ q shift) 0) ; shift is within this year
1921 (setq shiftedq (+ q shift))
1922 (setq shiftedy y)
1923 (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))))
1924 ((memq key '(year thisyear))
1925 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1926 (t (error "No such time block %s" key)))
1927 (setq ts (encode-time s m h d month y)
1928 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1929 (or d1 d) (or month1 month) (or y1 y)))
1930 (setq fm (cdr org-time-stamp-formats))
1931 (cond
1932 ((memq key '(day today))
1933 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1934 ((memq key '(week thisweek))
1935 (setq txt (format-time-string "week %G-W%V" ts)))
1936 ((memq key '(month thismonth))
1937 (setq txt (format-time-string "%B %Y" ts)))
1938 ((memq key '(year thisyear))
1939 (setq txt (format-time-string "the year %Y" ts)))
1940 ((memq key '(quarter thisq))
1941 (setq txt (concatenate 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
1943 (if as-strings
1944 (list (format-time-string fm ts) (format-time-string fm te) txt)
1945 (list ts te txt))))
1947 (defun org-count-quarter (n)
1948 (cond
1949 ((= n 1) "1st")
1950 ((= n 2) "2nd")
1951 ((= n 3) "3rd")
1952 ((= n 4) "4th")))
1954 (defun org-clocktable-shift (dir n)
1955 "Try to shift the :block date of the clocktable at point.
1956 Point must be in the #+BEGIN: line of a clocktable, or this function
1957 will throw an error.
1958 DIR is a direction, a symbol `left', `right', `up', or `down'.
1959 Both `left' and `down' shift the block toward the past, `up' and `right'
1960 push it toward the future.
1961 N is the number of shift steps to take. The size of the step depends on
1962 the currently selected interval size."
1963 (setq n (prefix-numeric-value n))
1964 (and (memq dir '(left down)) (setq n (- n)))
1965 (save-excursion
1966 (goto-char (point-at-bol))
1967 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1968 (error "Line needs a :block definition before this command works")
1969 (let* ((b (match-beginning 1)) (e (match-end 1))
1970 (s (match-string 1))
1971 block shift ins y mw d date wp m)
1972 (cond
1973 ((equal s "yesterday") (setq s "today-1"))
1974 ((equal s "lastweek") (setq s "thisweek-1"))
1975 ((equal s "lastmonth") (setq s "thismonth-1"))
1976 ((equal s "lastyear") (setq s "thisyear-1"))
1977 ((equal s "lastq") (setq s "thisq-1")))
1979 (cond
1980 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
1981 (setq block (match-string 1 s)
1982 shift (if (match-end 2)
1983 (string-to-number (match-string 2 s))
1985 (setq shift (+ shift n))
1986 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1987 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1988 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1989 (setq y (string-to-number (match-string 1 s))
1990 wp (and (match-end 3) (match-string 3 s))
1991 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1992 d (and (match-end 6) (string-to-number (match-string 6 s))))
1993 (cond
1994 (d (setq ins (format-time-string
1995 "%Y-%m-%d"
1996 (encode-time 0 0 0 (+ d n) m y))))
1997 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
1998 (require 'cal-iso)
1999 (setq date (calendar-gregorian-from-absolute
2000 (calendar-absolute-from-iso (list (+ mw n) 1 y))))
2001 (setq ins (format-time-string
2002 "%G-W%V"
2003 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2004 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2005 (require 'cal-iso)
2006 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2007 (if (> (+ mw n) 4)
2008 (setq mw 0
2009 y (+ 1 y))
2011 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2012 (if (= (+ mw n) 0)
2013 (setq mw 5
2014 y (- y 1))
2016 (setq date (calendar-gregorian-from-absolute
2017 (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
2018 (setq ins (format-time-string
2019 (concatenate 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
2020 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2022 (setq ins (format-time-string
2023 "%Y-%m"
2024 (encode-time 0 0 0 1 (+ mw n) y))))
2026 (setq ins (number-to-string (+ y n))))))
2027 (t (error "Cannot shift clocktable block")))
2028 (when ins
2029 (goto-char b)
2030 (insert ins)
2031 (delete-region (point) (+ (point) (- e b)))
2032 (beginning-of-line 1)
2033 (org-update-dblock)
2034 t)))))
2036 (defun org-dblock-write:clocktable (params)
2037 "Write the standard clocktable."
2038 (setq params (org-combine-plists org-clocktable-defaults params))
2039 (catch 'exit
2040 (let* ((scope (plist-get params :scope))
2041 (block (plist-get params :block))
2042 (ts (plist-get params :tstart))
2043 (te (plist-get params :tend))
2044 (link (plist-get params :link))
2045 (maxlevel (or (plist-get params :maxlevel) 3))
2046 (step (plist-get params :step))
2047 (timestamp (plist-get params :timestamp))
2048 (formatter (or (plist-get params :formatter)
2049 org-clock-clocktable-formatter
2050 'org-clocktable-write-default))
2051 cc range-text ipos pos one-file-with-archives
2052 scope-is-list tbls level)
2053 ;; Check if we need to do steps
2054 (when block
2055 ;; Get the range text for the header
2056 (setq cc (org-clock-special-range block nil t)
2057 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2058 (when step
2059 ;; Write many tables, in steps
2060 (unless (or block (and ts te))
2061 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2062 (org-clocktable-steps params)
2063 (throw 'exit nil))
2065 (setq ipos (point)) ; remember the insertion position
2067 ;; Get the right scope
2068 (setq pos (point))
2069 (cond
2070 ((and scope (listp scope) (symbolp (car scope)))
2071 (setq scope (eval scope)))
2072 ((eq scope 'agenda)
2073 (setq scope (org-agenda-files t)))
2074 ((eq scope 'agenda-with-archives)
2075 (setq scope (org-agenda-files t))
2076 (setq scope (org-add-archive-files scope)))
2077 ((eq scope 'file-with-archives)
2078 (setq scope (org-add-archive-files (list (buffer-file-name)))
2079 one-file-with-archives t)))
2080 (setq scope-is-list (and scope (listp scope)))
2081 (if scope-is-list
2082 ;; we collect from several files
2083 (let* ((files scope)
2084 file)
2085 (org-prepare-agenda-buffers files)
2086 (while (setq file (pop files))
2087 (with-current-buffer (find-buffer-visiting file)
2088 (save-excursion
2089 (save-restriction
2090 (push (org-clock-get-table-data file params) tbls))))))
2091 ;; Just from the current file
2092 (save-restriction
2093 ;; get the right range into the restriction
2094 (org-prepare-agenda-buffers (list (buffer-file-name)))
2095 (cond
2096 ((not scope)) ; use the restriction as it is now
2097 ((eq scope 'file) (widen))
2098 ((eq scope 'subtree) (org-narrow-to-subtree))
2099 ((eq scope 'tree)
2100 (while (org-up-heading-safe))
2101 (org-narrow-to-subtree))
2102 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
2103 (symbol-name scope)))
2104 (setq level (string-to-number (match-string 1 (symbol-name scope))))
2105 (catch 'exit
2106 (while (org-up-heading-safe)
2107 (looking-at org-outline-regexp)
2108 (if (<= (org-reduced-level (funcall outline-level)) level)
2109 (throw 'exit nil))))
2110 (org-narrow-to-subtree)))
2111 ;; do the table, with no file name.
2112 (push (org-clock-get-table-data nil params) tbls)))
2114 ;; OK, at this point we tbls as a list of tables, one per file
2115 (setq tbls (nreverse tbls))
2117 (setq params (plist-put params :multifile scope-is-list))
2118 (setq params (plist-put params :one-file-with-archives
2119 one-file-with-archives))
2121 (funcall formatter ipos tbls params))))
2123 (defun org-clocktable-write-default (ipos tables params)
2124 "Write out a clock table at position IPOS in the current buffer.
2125 TABLES is a list of tables with clocking data as produced by
2126 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2127 from the dynamic block definition."
2128 ;; This function looks quite complicated, mainly because there are a
2129 ;; lot of options which can add or remove columns. I have massively
2130 ;; commented this function, the I hope it is understandable. If
2131 ;; someone wants to write their own special formatter, this maybe
2132 ;; much easier because there can be a fixed format with a
2133 ;; well-defined number of columns...
2134 (let* ((hlchars '((1 . "*") (2 . "/")))
2135 (lwords (assoc (or (plist-get params :lang)
2136 org-export-default-language)
2137 org-clock-clocktable-language-setup))
2138 (multifile (plist-get params :multifile))
2139 (block (plist-get params :block))
2140 (ts (plist-get params :tstart))
2141 (te (plist-get params :tend))
2142 (header (plist-get params :header))
2143 (narrow (plist-get params :narrow))
2144 (link (plist-get params :link))
2145 (maxlevel (or (plist-get params :maxlevel) 3))
2146 (emph (plist-get params :emphasize))
2147 (level-p (plist-get params :level))
2148 (timestamp (plist-get params :timestamp))
2149 (properties (plist-get params :properties))
2150 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2151 (rm-file-column (plist-get params :one-file-with-archives))
2152 (indent (plist-get params :indent))
2153 range-text total-time tbl level hlc formula pcol
2154 file-time entries entry headline
2155 recalc content narrow-cut-p tcol)
2157 ;; Implement abbreviations
2158 (when (plist-get params :compact)
2159 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2161 ;; Some consistency test for parameters
2162 (unless (integerp ntcol)
2163 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2165 (when (and narrow (integerp narrow) link)
2166 ;; We cannot have both integer narrow and link
2167 (message
2168 "Using hard narrowing in clocktable to allow for links")
2169 (setq narrow (intern (format "%d!" narrow))))
2171 (when narrow
2172 (cond
2173 ((integerp narrow))
2174 ((and (symbolp narrow)
2175 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2176 (setq narrow-cut-p t
2177 narrow (string-to-number (substring (symbol-name narrow)
2178 0 -1))))
2180 (error "Invalid value %s of :narrow property in clock table"
2181 narrow))))
2183 (when block
2184 ;; Get the range text for the header
2185 (setq range-text (nth 2 (org-clock-special-range block nil t))))
2187 ;; Compute the total time
2188 (setq total-time (apply '+ (mapcar 'cadr tables)))
2190 ;; Now we need to output this tsuff
2191 (goto-char ipos)
2193 ;; Insert the text *before* the actual table
2194 (insert-before-markers
2195 (or header
2196 ;; Format the standard header
2197 (concat
2198 (nth 9 lwords) " ["
2199 (substring
2200 (format-time-string (cdr org-time-stamp-formats))
2201 1 -1)
2203 (if block (concat ", for " range-text ".") "")
2204 "\n\n")))
2206 ;; Insert the narrowing line
2207 (when (and narrow (integerp narrow) (not narrow-cut-p))
2208 (insert-before-markers
2209 "|" ; table line starter
2210 (if multifile "|" "") ; file column, maybe
2211 (if level-p "|" "") ; level column, maybe
2212 (if timestamp "|" "") ; timestamp column, maybe
2213 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2214 (format "<%d>| |\n" narrow))) ; headline and time columns
2216 ;; Insert the table header line
2217 (insert-before-markers
2218 "|" ; table line starter
2219 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2220 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2221 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2222 (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
2223 (concat (nth 4 lwords) "|"
2224 (nth 5 lwords) "|\n")) ; headline and time columns
2226 ;; Insert the total time in the table
2227 (insert-before-markers
2228 "|-\n" ; a hline
2229 "|" ; table line starter
2230 (if multifile (concat "| " (nth 6 lwords) " ") "")
2231 ; file column, maybe
2232 (if level-p "|" "") ; level column, maybe
2233 (if timestamp "|" "") ; timestamp column, maybe
2234 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2235 (concat "*" (nth 7 lwords) "*| ") ; instead of a headline
2237 (org-minutes-to-hh:mm-string (or total-time 0)) ; the time
2238 "*|\n") ; close line
2240 ;; Now iterate over the tables and insert the data
2241 ;; but only if any time has been collected
2242 (when (and total-time (> total-time 0))
2244 (while (setq tbl (pop tables))
2245 ;; now tbl is the table resulting from one file.
2246 (setq file-time (nth 1 tbl))
2247 (when (or (and file-time (> file-time 0))
2248 (not (plist-get params :fileskip0)))
2249 (insert-before-markers "|-\n") ; a hline because a new file starts
2250 ;; First the file time, if we have multiple files
2251 (when multifile
2252 ;; Summarize the time collected from this file
2253 (insert-before-markers
2254 (format (concat "| %s %s | %s%s*" (nth 8 lwords) "* | *%s*|\n")
2255 (file-name-nondirectory (car tbl))
2256 (if level-p "| " "") ; level column, maybe
2257 (if timestamp "| " "") ; timestamp column, maybe
2258 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2259 (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
2261 ;; Get the list of node entries and iterate over it
2262 (setq entries (nth 2 tbl))
2263 (while (setq entry (pop entries))
2264 (setq level (car entry)
2265 headline (nth 1 entry)
2266 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2267 (when narrow-cut-p
2268 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2269 "\\'")
2270 headline)
2271 (match-end 3))
2272 (setq headline
2273 (format "[[%s][%s]]"
2274 (match-string 1 headline)
2275 (org-shorten-string (match-string 3 headline)
2276 narrow)))
2277 (setq headline (org-shorten-string headline narrow))))
2278 (insert-before-markers
2279 "|" ; start the table line
2280 (if multifile "|" "") ; free space for file name column?
2281 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2282 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2283 (if properties
2284 (concat
2285 (mapconcat
2286 (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
2287 properties "|") "|") "") ;properties columns, maybe
2288 (if indent (org-clocktable-indent-string level) "") ; indentation
2289 hlc headline hlc "|" ; headline
2290 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2291 ; empty fields for higher levels
2292 hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
2293 "|\n" ; close line
2294 )))))
2295 (backward-delete-char 1)
2296 (if (setq formula (plist-get params :formula))
2297 (cond
2298 ((eq formula '%)
2299 ;; compute the column where the % numbers need to go
2300 (setq pcol (+ 2
2301 (if multifile 1 0)
2302 (if level-p 1 0)
2303 (if timestamp 1 0)
2304 (min maxlevel (or ntcol 100))))
2305 ;; compute the column where the total time is
2306 (setq tcol (+ 2
2307 (if multifile 1 0)
2308 (if level-p 1 0)
2309 (if timestamp 1 0)))
2310 (insert
2311 (format
2312 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2313 pcol ; the column where the % numbers should go
2314 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2315 tcol ; column of the total time
2316 tcol (1- pcol) ; range of columns where times can be found
2318 (setq recalc t))
2319 ((stringp formula)
2320 (insert "\n#+TBLFM: " formula)
2321 (setq recalc t))
2322 (t (error "invalid formula in clocktable")))
2323 ;; Should we rescue an old formula?
2324 (when (stringp (setq content (plist-get params :content)))
2325 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
2326 (setq recalc t)
2327 (insert "\n" (match-string 1 (plist-get params :content)))
2328 (beginning-of-line 0))))
2329 ;; Back to beginning, align the table, recalculate if necessary
2330 (goto-char ipos)
2331 (skip-chars-forward "^|")
2332 (org-table-align)
2333 (when org-hide-emphasis-markers
2334 ;; we need to align a second time
2335 (org-table-align))
2336 (when recalc
2337 (if (eq formula '%)
2338 (save-excursion
2339 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2340 (org-table-goto-column pcol nil 'force)
2341 (insert "%")))
2342 (org-table-recalculate 'all))
2343 (when rm-file-column
2344 ;; The file column is actually not wanted
2345 (forward-char 1)
2346 (org-table-delete-column))
2347 total-time))
2349 (defun org-clocktable-indent-string (level)
2350 (if (= level 1)
2352 (let ((str "\\__"))
2353 (while (> level 2)
2354 (setq level (1- level)
2355 str (concat str "___")))
2356 (concat str " "))))
2358 (defun org-clocktable-steps (params)
2359 "Step through the range to make a number of clock tables."
2360 (let* ((p1 (copy-sequence params))
2361 (ts (plist-get p1 :tstart))
2362 (te (plist-get p1 :tend))
2363 (step0 (plist-get p1 :step))
2364 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2365 (stepskip0 (plist-get p1 :stepskip0))
2366 (block (plist-get p1 :block))
2367 cc range-text step-time)
2368 (when block
2369 (setq cc (org-clock-special-range block nil t)
2370 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2371 (cond
2372 ((numberp ts)
2373 ;; If ts is a number, it's an absolute day number from org-agenda.
2374 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2375 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2377 (setq ts (org-float-time
2378 (apply 'encode-time (org-parse-time-string ts))))))
2379 (cond
2380 ((numberp te)
2381 ;; Likewise for te.
2382 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2383 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2385 (setq te (org-float-time
2386 (apply 'encode-time (org-parse-time-string te))))))
2387 (setq p1 (plist-put p1 :header ""))
2388 (setq p1 (plist-put p1 :step nil))
2389 (setq p1 (plist-put p1 :block nil))
2390 (while (< ts te)
2391 (or (bolp) (insert "\n"))
2392 (setq p1 (plist-put p1 :tstart (format-time-string
2393 (org-time-stamp-format nil t)
2394 (seconds-to-time ts))))
2395 (setq p1 (plist-put p1 :tend (format-time-string
2396 (org-time-stamp-format nil t)
2397 (seconds-to-time (setq ts (+ ts step))))))
2398 (insert "\n" (if (eq step0 'day) "Daily report: "
2399 "Weekly report starting on: ")
2400 (plist-get p1 :tstart) "\n")
2401 (setq step-time (org-dblock-write:clocktable p1))
2402 (re-search-forward "^[ \t]*#\\+END:")
2403 (when (and (equal step-time 0) stepskip0)
2404 ;; Remove the empty table
2405 (delete-region (point-at-bol)
2406 (save-excursion
2407 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2408 nil t)
2409 (point))))
2410 (end-of-line 0))))
2412 (defun org-clock-get-table-data (file params)
2413 "Get the clocktable data for file FILE, with parameters PARAMS.
2414 FILE is only for identification - this function assumes that
2415 the correct buffer is current, and that the wanted restriction is
2416 in place.
2417 The return value will be a list with the file name and the total
2418 file time (in minutes) as 1st and 2nd elements. The third element
2419 of this list will be a list of headline entries. Each entry has the
2420 following structure:
2422 (LEVEL HEADLINE TIMESTAMP TIME)
2424 LEVEL: The level of the headline, as an integer. This will be
2425 the reduced leve, so 1,2,3,... even if only odd levels
2426 are being used.
2427 HEADLINE: The text of the headline. Depending on PARAMS, this may
2428 already be formatted like a link.
2429 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2430 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2431 in this sequence.
2432 TIME: The sum of all time spend in this tree, in minutes. This time
2433 will of cause be restricted to the time block and tags match
2434 specified in PARAMS."
2435 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2436 (timestamp (plist-get params :timestamp))
2437 (ts (plist-get params :tstart))
2438 (te (plist-get params :tend))
2439 (block (plist-get params :block))
2440 (link (plist-get params :link))
2441 (tags (plist-get params :tags))
2442 (properties (plist-get params :properties))
2443 (inherit-property-p (plist-get params :inherit-props))
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