Standardize case of "GTK+" in a few manuals
[emacs.git] / lisp / org / org-clock.el
blob434f6a1d5f6a00e527c98454cc984f7b1f30129e
1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the time clocking code for Org-mode
29 (require 'org)
30 (require 'org-exp)
31 ;;; Code:
33 (eval-when-compile
34 (require 'cl))
36 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
37 (declare-function notifications-notify "notifications" (&rest params))
38 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
39 (defvar org-time-stamp-formats)
40 (defvar org-ts-what)
42 (defgroup org-clock nil
43 "Options concerning clocking working time in Org-mode."
44 :tag "Org Clock"
45 :group 'org-progress)
47 (defcustom org-clock-into-drawer org-log-into-drawer
48 "Should clocking info be wrapped into a drawer?
49 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
50 If necessary, the drawer will be created.
51 When nil, the drawer will not be created, but used when present.
52 When an integer and the number of clocking entries in an item
53 reaches or exceeds this number, a drawer will be created.
54 When a string, it names the drawer to be used.
56 The default for this variable is the value of `org-log-into-drawer',
57 which see."
58 :group 'org-todo
59 :group 'org-clock
60 :type '(choice
61 (const :tag "Always" t)
62 (const :tag "Only when drawer exists" nil)
63 (integer :tag "When at least N clock entries")
64 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
65 (string :tag "Into Drawer named...")))
67 (defun org-clock-into-drawer ()
68 "Return the value of `org-clock-into-drawer', but let properties overrule.
69 If the current entry has or inherits a CLOCK_INTO_DRAWER
70 property, it will be used instead of the default value; otherwise
71 if the current entry has or inherits a LOG_INTO_DRAWER property,
72 it will be used instead of the default value.
73 The default is the value of the customizable variable `org-clock-into-drawer',
74 which see."
75 (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit))
76 (q (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
77 (cond
78 ((or (not (or p q)) (equal p "nil") (equal q "nil")) org-clock-into-drawer)
79 ((or (equal p "t") (equal q "t")) "LOGBOOK")
80 ((not p) q)
81 (t p))))
83 (defcustom org-clock-out-when-done t
84 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
85 DONE here means any DONE-like state.
86 A nil value means clock will keep running until stopped explicitly with
87 `C-c C-x C-o', or until the clock is started in a different item.
88 Instead of t, this can also be a list of TODO states that should trigger
89 clocking out."
90 :group 'org-clock
91 :type '(choice
92 (const :tag "No" nil)
93 (const :tag "Yes, when done" t)
94 (repeat :tag "State list"
95 (string :tag "TODO keyword"))))
97 (defcustom org-clock-out-remove-zero-time-clocks nil
98 "Non-nil means remove the clock line when the resulting time is zero."
99 :group 'org-clock
100 :type 'boolean)
102 (defcustom org-clock-in-switch-to-state nil
103 "Set task to a special todo state while clocking it.
104 The value should be the state to which the entry should be
105 switched. If the value is a function, it must take one
106 parameter (the current TODO state of the item) and return the
107 state to switch it to."
108 :group 'org-clock
109 :group 'org-todo
110 :type '(choice
111 (const :tag "Don't force a state" nil)
112 (string :tag "State")
113 (symbol :tag "Function")))
115 (defcustom org-clock-out-switch-to-state nil
116 "Set task to a special todo state after clocking out.
117 The value should be the state to which the entry should be
118 switched. If the value is a function, it must take one
119 parameter (the current TODO state of the item) and return the
120 state to switch it to."
121 :group 'org-clock
122 :group 'org-todo
123 :type '(choice
124 (const :tag "Don't force a state" nil)
125 (string :tag "State")
126 (symbol :tag "Function")))
128 (defcustom org-clock-history-length 5
129 "Number of clock tasks to remember in history."
130 :group 'org-clock
131 :type 'integer)
133 (defcustom org-clock-goto-may-find-recent-task t
134 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
135 :group 'org-clock
136 :type 'boolean)
138 (defcustom org-clock-heading-function nil
139 "When non-nil, should be a function to create `org-clock-heading'.
140 This is the string shown in the mode line when a clock is running.
141 The function is called with point at the beginning of the headline."
142 :group 'org-clock
143 :type 'function)
145 (defcustom org-clock-string-limit 0
146 "Maximum length of clock strings in the modeline. 0 means no limit."
147 :group 'org-clock
148 :type 'integer)
150 (defcustom org-clock-in-resume nil
151 "If non-nil, resume clock when clocking into task with open clock.
152 When clocking into a task with a clock entry which has not been closed,
153 the clock can be resumed from that point."
154 :group 'org-clock
155 :type 'boolean)
157 (defcustom org-clock-persist nil
158 "When non-nil, save the running clock when Emacs is closed.
159 The clock is resumed when Emacs restarts.
160 When this is t, both the running clock, and the entire clock
161 history are saved. When this is the symbol `clock', only the
162 running clock is saved.
164 When Emacs restarts with saved clock information, the file containing the
165 running clock as well as all files mentioned in the clock history will
166 be visited.
167 All this depends on running `org-clock-persistence-insinuate' in .emacs"
168 :group 'org-clock
169 :type '(choice
170 (const :tag "Just the running clock" clock)
171 (const :tag "Just the history" history)
172 (const :tag "Clock and history" t)
173 (const :tag "No persistence" nil)))
175 (defcustom org-clock-persist-file (convert-standard-filename
176 "~/.emacs.d/org-clock-save.el")
177 "File to save clock data to."
178 :group 'org-clock
179 :type 'string)
181 (defcustom org-clock-persist-query-save nil
182 "When non-nil, ask before saving the current clock on exit."
183 :group 'org-clock
184 :type 'boolean)
186 (defcustom org-clock-persist-query-resume t
187 "When non-nil, ask before resuming any stored clock during load."
188 :group 'org-clock
189 :type 'boolean)
191 (defcustom org-clock-sound nil
192 "Sound that will used for notifications.
193 Possible values:
195 nil no sound played.
196 t standard Emacs beep
197 file name play this sound file. If not possible, fall back to beep"
198 :group 'org-clock
199 :type '(choice
200 (const :tag "No sound" nil)
201 (const :tag "Standard beep" t)
202 (file :tag "Play sound file")))
204 (defcustom org-clock-modeline-total 'auto
205 "Default setting for the time included for the modeline clock.
206 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
207 Allowed values are:
209 current Only the time in the current instance of the clock
210 today All time clocked into this task today
211 repeat All time clocked into this task since last repeat
212 all All time ever recorded for this task
213 auto Automatically, either `all', or `repeat' for repeating tasks"
214 :group 'org-clock
215 :type '(choice
216 (const :tag "Current clock" current)
217 (const :tag "Today's task time" today)
218 (const :tag "Since last repeat" repeat)
219 (const :tag "All task time" all)
220 (const :tag "Automatically, `all' or since `repeat'" auto)))
222 (defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
223 (defcustom org-clock-task-overrun-text nil
224 "The extra modeline text that should indicate that the clock is overrun.
225 The can be nil to indicate that instead of adding text, the clock time
226 should get a different face (`org-mode-line-clock-overrun').
227 When this is a string, it is prepended to the clock string as an indication,
228 also using the face `org-mode-line-clock-overrun'."
229 :group 'org-clock
230 :version "24.1"
231 :type '(choice
232 (const :tag "Just mark the time string" nil)
233 (string :tag "Text to prepend")))
235 (defcustom org-show-notification-handler nil
236 "Function or program to send notification with.
237 The function or program will be called with the notification
238 string as argument."
239 :group 'org-clock
240 :type '(choice
241 (string :tag "Program")
242 (function :tag "Function")))
244 (defgroup org-clocktable nil
245 "Options concerning the clock table in Org-mode."
246 :tag "Org Clock Table"
247 :group 'org-clock)
249 (defcustom org-clocktable-defaults
250 `(list
251 :maxlevel 2
252 :lang ,org-export-default-language
253 :scope 'file
254 :block nil
255 :tstart nil
256 :tend nil
257 :step nil
258 :stepskip0 nil
259 :fileskip0 nil
260 :tags nil
261 :emphasize nil
262 :link nil
263 :narrow '40!
264 :indent t
265 :formula nil
266 :timestamp nil
267 :level nil
268 :tcolumns nil
269 :formatter nil)
270 "Default properties for clock tables."
271 :group 'org-clock
272 :version "24.1"
273 :type 'plist)
275 (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
276 "Function to turn clocking data into a table.
277 For more information, see `org-clocktable-write-default'."
278 :group 'org-clocktable
279 :version "24.1"
280 :type 'function)
282 ;; FIXME: translate es and nl last string "Clock summary at"
283 (defcustom org-clock-clocktable-language-setup
284 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
285 ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
286 ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à")
287 ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at"))
288 "Terms used in clocktable, translated to different languages."
289 :group 'org-clocktable
290 :version "24.1"
291 :type 'alist)
293 (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
294 "Default properties for new clocktables.
295 These will be inserted into the BEGIN line, to make it easy for users to
296 play with them."
297 :group 'org-clocktable
298 :type 'plist)
300 (defcustom org-clock-idle-time nil
301 "When non-nil, resolve open clocks if the user is idle more than X minutes."
302 :group 'org-clock
303 :type '(choice
304 (const :tag "Never" nil)
305 (integer :tag "After N minutes")))
307 (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
308 "When to automatically resolve open clocks found in Org buffers."
309 :group 'org-clock
310 :type '(choice
311 (const :tag "Never" nil)
312 (const :tag "Always" t)
313 (const :tag "When no clock is running" when-no-clock-is-running)))
315 (defcustom org-clock-report-include-clocking-task nil
316 "When non-nil, include the current clocking task time in clock reports."
317 :group 'org-clock
318 :version "24.1"
319 :type 'boolean)
321 (defcustom org-clock-resolve-expert nil
322 "Non-nil means do not show the splash buffer with the clock resolver."
323 :group 'org-clock
324 :version "24.1"
325 :type 'boolean)
327 (defvar org-clock-in-prepare-hook nil
328 "Hook run when preparing the clock.
329 This hook is run before anything happens to the task that
330 you want to clock in. For example, you can use this hook
331 to add an effort property.")
332 (defvar org-clock-in-hook nil
333 "Hook run when starting the clock.")
334 (defvar org-clock-out-hook nil
335 "Hook run when stopping the current clock.")
337 (defvar org-clock-cancel-hook nil
338 "Hook run when cancelling the current clock.")
339 (defvar org-clock-goto-hook nil
340 "Hook run when selecting the currently clocked-in entry.")
341 (defvar org-clock-has-been-used nil
342 "Has the clock been used during the current Emacs session?")
344 ;;; The clock for measuring work time.
346 (defvar org-mode-line-string "")
347 (put 'org-mode-line-string 'risky-local-variable t)
349 (defvar org-clock-mode-line-timer nil)
350 (defvar org-clock-idle-timer nil)
351 (defvar org-clock-heading) ; defined in org.el
352 (defvar org-clock-heading-for-remember "")
353 (defvar org-clock-start-time "")
355 (defvar org-clock-leftover-time nil
356 "If non-nil, user cancelled a clock; this is when leftover time started.")
358 (defvar org-clock-effort ""
359 "Effort estimate of the currently clocking task.")
361 (defvar org-clock-total-time nil
362 "Holds total time, spent previously on currently clocked item.
363 This does not include the time in the currently running clock.")
365 (defvar org-clock-history nil
366 "List of marker pointing to recent clocked tasks.")
368 (defvar org-clock-default-task (make-marker)
369 "Marker pointing to the default task that should clock time.
370 The clock can be made to switch to this task after clocking out
371 of a different task.")
373 (defvar org-clock-interrupted-task (make-marker)
374 "Marker pointing to the task that has been interrupted by the current clock.")
376 (defvar org-clock-mode-line-map (make-sparse-keymap))
377 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
378 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
380 (defun org-clock-menu ()
381 (interactive)
382 (popup-menu
383 '("Clock"
384 ["Clock out" org-clock-out t]
385 ["Change effort estimate" org-clock-modify-effort-estimate t]
386 ["Go to clock entry" org-clock-goto t]
387 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
389 (defun org-clock-history-push (&optional pos buffer)
390 "Push a marker to the clock history."
391 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
392 (let ((m (move-marker (make-marker)
393 (or pos (point)) (org-base-buffer
394 (or buffer (current-buffer)))))
395 n l)
396 (while (setq n (member m org-clock-history))
397 (move-marker (car n) nil))
398 (setq org-clock-history
399 (delq nil
400 (mapcar (lambda (x) (if (marker-buffer x) x nil))
401 org-clock-history)))
402 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
403 (setq org-clock-history
404 (nreverse
405 (nthcdr (- l org-clock-history-length -1)
406 (nreverse org-clock-history)))))
407 (push m org-clock-history)))
409 (defun org-clock-save-markers-for-cut-and-paste (beg end)
410 "Save relative positions of markers in region."
411 (org-check-and-save-marker org-clock-marker beg end)
412 (org-check-and-save-marker org-clock-hd-marker beg end)
413 (org-check-and-save-marker org-clock-default-task beg end)
414 (org-check-and-save-marker org-clock-interrupted-task beg end)
415 (mapc (lambda (m) (org-check-and-save-marker m beg end))
416 org-clock-history))
418 (defun org-clocking-buffer ()
419 "Return the clocking buffer if we are currently clocking a task or nil."
420 (marker-buffer org-clock-marker))
422 (defun org-clocking-p ()
423 "Return t when clocking a task."
424 (not (equal (org-clocking-buffer) nil)))
426 (defvar org-clock-before-select-task-hook nil
427 "Hook called in task selection just before prompting the user.")
429 (defun org-clock-select-task (&optional prompt)
430 "Select a task that recently was associated with clocking."
431 (interactive)
432 (let (sel-list rpl (i 0) s)
433 (save-window-excursion
434 (org-switch-to-buffer-other-window
435 (get-buffer-create "*Clock Task Select*"))
436 (erase-buffer)
437 (when (marker-buffer org-clock-default-task)
438 (insert (org-add-props "Default Task\n" nil 'face 'bold))
439 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
440 (push s sel-list))
441 (when (marker-buffer org-clock-interrupted-task)
442 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
443 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
444 (push s sel-list))
445 (when (org-clocking-p)
446 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
447 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
448 (push s sel-list))
449 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
450 (mapc
451 (lambda (m)
452 (when (marker-buffer m)
453 (setq i (1+ i)
454 s (org-clock-insert-selection-line
455 (if (< i 10)
456 (+ i ?0)
457 (+ i (- ?A 10))) m))
458 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
459 (push s sel-list)))
460 org-clock-history)
461 (run-hooks 'org-clock-before-select-task-hook)
462 (org-fit-window-to-buffer)
463 (message (or prompt "Select task for clocking:"))
464 (setq rpl (read-char-exclusive))
465 (cond
466 ((eq rpl ?q) nil)
467 ((eq rpl ?x) nil)
468 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
469 (t (error "Invalid task choice %c" rpl))))))
471 (defun org-clock-insert-selection-line (i marker)
472 "Insert a line for the clock selection menu.
473 And return a cons cell with the selection character integer and the marker
474 pointing to it."
475 (when (marker-buffer marker)
476 (let (file cat task heading prefix)
477 (with-current-buffer (org-base-buffer (marker-buffer marker))
478 (save-excursion
479 (save-restriction
480 (widen)
481 (ignore-errors
482 (goto-char marker)
483 (setq file (buffer-file-name (marker-buffer marker))
484 cat (org-get-category)
485 heading (org-get-heading 'notags)
486 prefix (save-excursion
487 (org-back-to-heading t)
488 (looking-at org-outline-regexp)
489 (match-string 0))
490 task (substring
491 (org-fontify-like-in-org-mode
492 (concat prefix heading)
493 org-odd-levels-only)
494 (length prefix)))))))
495 (when (and cat task)
496 (insert (format "[%c] %-15s %s\n" i cat task))
497 (cons i marker)))))
499 (defvar org-clock-task-overrun nil
500 "Internal flag indicating if the clock has overrun the planned time.")
501 (defvar org-clock-update-period 60
502 "Number of seconds between mode line clock string updates.")
504 (defun org-clock-get-clock-string ()
505 "Form a clock-string, that will be shown in the mode line.
506 If an effort estimate was defined for the current item, use
507 01:30/01:50 format (clocked/estimated).
508 If not, show simply the clocked time like 01:50."
509 (let* ((clocked-time (org-clock-get-clocked-time))
510 (h (floor clocked-time 60))
511 (m (- clocked-time (* 60 h))))
512 (if org-clock-effort
513 (let* ((effort-in-minutes
514 (org-duration-string-to-minutes org-clock-effort))
515 (effort-h (floor effort-in-minutes 60))
516 (effort-m (- effort-in-minutes (* effort-h 60)))
517 (work-done-str
518 (org-propertize
519 (format org-time-clocksum-format h m)
520 'face (if (and org-clock-task-overrun (not org-clock-task-overrun-text))
521 'org-mode-line-clock-overrun 'org-mode-line-clock)))
522 (effort-str (format org-time-clocksum-format effort-h effort-m))
523 (clockstr (org-propertize
524 (concat "[%s/" effort-str
525 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
526 'face 'org-mode-line-clock)))
527 (format clockstr work-done-str))
528 (org-propertize (format
529 (concat "[" org-time-clocksum-format " (%s)]")
530 h m org-clock-heading)
531 'face 'org-mode-line-clock))))
533 (defun org-clock-update-mode-line ()
534 (if org-clock-effort
535 (org-clock-notify-once-if-expired)
536 (setq org-clock-task-overrun nil))
537 (setq org-mode-line-string
538 (org-propertize
539 (let ((clock-string (org-clock-get-clock-string))
540 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
541 (if (and (> org-clock-string-limit 0)
542 (> (length clock-string) org-clock-string-limit))
543 (org-propertize
544 (substring clock-string 0 org-clock-string-limit)
545 'help-echo (concat help-text ": " org-clock-heading))
546 (org-propertize clock-string 'help-echo help-text)))
547 'local-map org-clock-mode-line-map
548 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
550 (if (and org-clock-task-overrun org-clock-task-overrun-text)
551 (setq org-mode-line-string
552 (concat (org-propertize
553 org-clock-task-overrun-text
554 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
555 (force-mode-line-update))
557 (defun org-clock-get-clocked-time ()
558 "Get the clocked time for the current item in minutes.
559 The time returned includes the time spent on this task in
560 previous clocking intervals."
561 (let ((currently-clocked-time
562 (floor (- (org-float-time)
563 (org-float-time org-clock-start-time)) 60)))
564 (+ currently-clocked-time (or org-clock-total-time 0))))
566 (defun org-clock-modify-effort-estimate (&optional value)
567 "Add to or set the effort estimate of the item currently being clocked.
568 VALUE can be a number of minutes, or a string with format hh:mm or mm.
569 When the string starts with a + or a - sign, the current value of the effort
570 property will be changed by that amount.
571 This will update the \"Effort\" property of currently clocked item, and
572 the mode line."
573 (interactive)
574 (when (org-clock-is-active)
575 (let ((current org-clock-effort) sign)
576 (unless value
577 ;; Prompt user for a value or a change
578 (setq value
579 (read-string
580 (format "Set effort (hh:mm or mm%s): "
581 (if current
582 (format ", prefix + to add to %s" org-clock-effort)
583 "")))))
584 (when (stringp value)
585 ;; A string. See if it is a delta
586 (setq sign (string-to-char value))
587 (if (member sign '(?- ?+))
588 (setq current (org-duration-string-to-minutes current)
589 value (substring value 1))
590 (setq current 0))
591 (setq value (org-duration-string-to-minutes value))
592 (if (equal ?- sign)
593 (setq value (- current value))
594 (if (equal ?+ sign) (setq value (+ current value)))))
595 (setq value (max 0 value)
596 org-clock-effort (org-minutes-to-hh:mm-string value))
597 (org-entry-put org-clock-marker "Effort" org-clock-effort)
598 (org-clock-update-mode-line)
599 (message "Effort is now %s" org-clock-effort))))
601 (defvar org-clock-notification-was-shown nil
602 "Shows if we have shown notification already.")
604 (defun org-clock-notify-once-if-expired ()
605 "Show notification if we spent more time than we estimated before.
606 Notification is shown only once."
607 (when (org-clocking-p)
608 (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort))
609 (clocked-time (org-clock-get-clocked-time)))
610 (if (setq org-clock-task-overrun
611 (if (or (null effort-in-minutes) (zerop effort-in-minutes))
613 (>= clocked-time effort-in-minutes)))
614 (unless org-clock-notification-was-shown
615 (setq org-clock-notification-was-shown t)
616 (org-notify
617 (format "Task '%s' should be finished by now. (%s)"
618 org-clock-heading org-clock-effort) t))
619 (setq org-clock-notification-was-shown nil)))))
621 (defun org-notify (notification &optional play-sound)
622 "Send a NOTIFICATION and maybe PLAY-SOUND."
623 (org-show-notification notification)
624 (if play-sound (org-clock-play-sound)))
626 (defun org-show-notification (notification)
627 "Show notification.
628 Use `org-show-notification-handler' if defined,
629 use libnotify if available, or fall back on a message."
630 (cond ((functionp org-show-notification-handler)
631 (funcall org-show-notification-handler notification))
632 ((stringp org-show-notification-handler)
633 (start-process "emacs-timer-notification" nil
634 org-show-notification-handler notification))
635 ((featurep 'notifications)
636 (require 'notifications)
637 (notifications-notify
638 :title "Org-mode message"
639 :body notification
640 ;; FIXME how to link to the Org icon?
641 ;; :app-icon "~/.emacs.d/icons/mail.png"
642 :urgency 'low))
643 ((org-program-exists "notify-send")
644 (start-process "emacs-timer-notification" nil
645 "notify-send" notification))
646 ;; Maybe the handler will send a message, so only use message as
647 ;; a fall back option
648 (t (message "%s" notification))))
650 (defun org-clock-play-sound ()
651 "Play sound as configured by `org-clock-sound'.
652 Use alsa's aplay tool if available."
653 (cond
654 ((not org-clock-sound))
655 ((eq org-clock-sound t) (beep t) (beep t))
656 ((stringp org-clock-sound)
657 (let ((file (expand-file-name org-clock-sound)))
658 (if (file-exists-p file)
659 (if (org-program-exists "aplay")
660 (start-process "org-clock-play-notification" nil
661 "aplay" file)
662 (condition-case nil
663 (play-sound-file file)
664 (error (beep t) (beep t)))))))))
666 (defun org-program-exists (program-name)
667 "Checks whenever we can locate program and launch it."
668 (if (member system-type '(gnu/linux darwin))
669 (= 0 (call-process "which" nil nil nil program-name))))
671 (defvar org-clock-mode-line-entry nil
672 "Information for the modeline about the running clock.")
674 (defun org-find-open-clocks (file)
675 "Search through the given file and find all open clocks."
676 (let ((buf (or (get-file-buffer file)
677 (find-file-noselect file)))
678 clocks)
679 (with-current-buffer buf
680 (save-excursion
681 (goto-char (point-min))
682 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
683 (push (cons (copy-marker (match-end 1) t)
684 (org-time-string-to-time (match-string 1))) clocks))))
685 clocks))
687 (defsubst org-is-active-clock (clock)
688 "Return t if CLOCK is the currently active clock."
689 (and (org-clock-is-active)
690 (= org-clock-marker (car clock))))
692 (defmacro org-with-clock-position (clock &rest forms)
693 "Evaluate FORMS with CLOCK as the current active clock."
694 `(with-current-buffer (marker-buffer (car ,clock))
695 (save-excursion
696 (save-restriction
697 (widen)
698 (goto-char (car ,clock))
699 (beginning-of-line)
700 ,@forms))))
701 (def-edebug-spec org-with-clock-position (form body))
702 (put 'org-with-clock-position 'lisp-indent-function 1)
704 (defmacro org-with-clock (clock &rest forms)
705 "Evaluate FORMS with CLOCK as the current active clock.
706 This macro also protects the current active clock from being altered."
707 `(org-with-clock-position ,clock
708 (let ((org-clock-start-time (cdr ,clock))
709 (org-clock-total-time)
710 (org-clock-history)
711 (org-clock-effort)
712 (org-clock-marker (car ,clock))
713 (org-clock-hd-marker (save-excursion
714 (outline-back-to-heading t)
715 (point-marker))))
716 ,@forms)))
717 (def-edebug-spec org-with-clock (form body))
718 (put 'org-with-clock 'lisp-indent-function 1)
720 (defsubst org-clock-clock-in (clock &optional resume start-time)
721 "Clock in to the clock located by CLOCK.
722 If necessary, clock-out of the currently active clock."
723 (org-with-clock-position clock
724 (let ((org-clock-in-resume (or resume org-clock-in-resume)))
725 (org-clock-in nil start-time))))
727 (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
728 "Clock out of the clock located by CLOCK."
729 (let ((temp (copy-marker (car clock)
730 (marker-insertion-type (car clock)))))
731 (if (org-is-active-clock clock)
732 (org-clock-out fail-quietly at-time)
733 (org-with-clock clock
734 (org-clock-out fail-quietly at-time)))
735 (setcar clock temp)))
737 (defsubst org-clock-clock-cancel (clock)
738 "Cancel the clock located by CLOCK."
739 (let ((temp (copy-marker (car clock)
740 (marker-insertion-type (car clock)))))
741 (if (org-is-active-clock clock)
742 (org-clock-cancel)
743 (org-with-clock clock
744 (org-clock-cancel)))
745 (setcar clock temp)))
747 (defvar org-clock-clocking-in nil)
748 (defvar org-clock-resolving-clocks nil)
749 (defvar org-clock-resolving-clocks-due-to-idleness nil)
751 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
752 &optional close-p restart-p fail-quietly)
753 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
754 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
755 (let ((org-clock-resolving-clocks t))
756 (cond
757 ((null resolve-to)
758 (org-clock-clock-cancel clock)
759 (if (and restart-p (not org-clock-clocking-in))
760 (org-clock-clock-in clock)))
762 ((eq resolve-to 'now)
763 (if restart-p
764 (error "RESTART-P is not valid here"))
765 (if (or close-p org-clock-clocking-in)
766 (org-clock-clock-out clock fail-quietly)
767 (unless (org-is-active-clock clock)
768 (org-clock-clock-in clock t))))
770 ((not (time-less-p resolve-to (current-time)))
771 (error "RESOLVE-TO must refer to a time in the past"))
774 (if restart-p
775 (error "RESTART-P is not valid here"))
776 (org-clock-clock-out clock fail-quietly (or clock-out-time
777 resolve-to))
778 (unless org-clock-clocking-in
779 (if close-p
780 (setq org-clock-leftover-time (and (null clock-out-time)
781 resolve-to))
782 (org-clock-clock-in clock nil (and clock-out-time
783 resolve-to))))))))
785 (defun org-clock-jump-to-current-clock (&optional effective-clock)
786 (interactive)
787 (let ((org-clock-into-drawer (org-clock-into-drawer))
788 (clock (or effective-clock (cons org-clock-marker
789 org-clock-start-time))))
790 (unless (marker-buffer (car clock))
791 (error "No clock is currently running"))
792 (org-with-clock clock (org-clock-goto))
793 (with-current-buffer (marker-buffer (car clock))
794 (goto-char (car clock))
795 (if org-clock-into-drawer
796 (let ((logbook
797 (if (stringp org-clock-into-drawer)
798 (concat ":" org-clock-into-drawer ":")
799 ":LOGBOOK:")))
800 (ignore-errors
801 (outline-flag-region
802 (save-excursion
803 (outline-back-to-heading t)
804 (search-forward logbook)
805 (goto-char (match-beginning 0)))
806 (save-excursion
807 (outline-back-to-heading t)
808 (search-forward logbook)
809 (search-forward ":END:")
810 (goto-char (match-end 0)))
811 nil)))))))
813 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
814 "Resolve an open org-mode clock.
815 An open clock was found, with `dangling' possibly being non-nil.
816 If this function was invoked with a prefix argument, non-dangling
817 open clocks are ignored. The given clock requires some sort of
818 user intervention to resolve it, either because a clock was left
819 dangling or due to an idle timeout. The clock resolution can
820 either be:
822 (a) deleted, the user doesn't care about the clock
823 (b) restarted from the current time (if no other clock is open)
824 (c) closed, giving the clock X minutes
825 (d) closed and then restarted
826 (e) resumed, as if the user had never left
828 The format of clock is (CONS MARKER START-TIME), where MARKER
829 identifies the buffer and position the clock is open at (and
830 thus, the heading it's under), and START-TIME is when the clock
831 was started."
832 (assert clock)
833 (let* ((ch
834 (save-window-excursion
835 (save-excursion
836 (unless org-clock-resolving-clocks-due-to-idleness
837 (org-clock-jump-to-current-clock clock))
838 (unless org-clock-resolve-expert
839 (with-output-to-temp-buffer "*Org Clock*"
840 (princ "Select a Clock Resolution Command:
842 i/q/C-g Ignore this question; the same as keeping all the idle time.
844 k/K Keep X minutes of the idle time (default is all). If this
845 amount is less than the default, you will be clocked out
846 that many minutes after the time that idling began, and then
847 clocked back in at the present time.
848 g/G Indicate that you \"got back\" X minutes ago. This is quite
849 different from 'k': it clocks you out from the beginning of
850 the idle period and clock you back in X minutes ago.
851 s/S Subtract the idle time from the current clock. This is the
852 same as keeping 0 minutes.
853 C Cancel the open timer altogether. It will be as though you
854 never clocked in.
855 j/J Jump to the current clock, to make manual adjustments.
857 For all these options, using uppercase makes your final state
858 to be CLOCKED OUT.")))
859 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
860 (let (char-pressed)
861 (when (featurep 'xemacs)
862 (message (concat (funcall prompt-fn clock)
863 " [jkKgGsScCiq]? "))
864 (setq char-pressed (read-char-exclusive)))
865 (while (or (null char-pressed)
866 (and (not (memq char-pressed
867 '(?k ?K ?g ?G ?s ?S ?C
868 ?j ?J ?i ?q)))
869 (or (ding) t)))
870 (setq char-pressed
871 (read-char (concat (funcall prompt-fn clock)
872 " [jkKgGSscCiq]? ")
873 nil 45)))
874 (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
875 (default
876 (floor (/ (org-float-time
877 (time-subtract (current-time) last-valid)) 60)))
878 (keep
879 (and (memq ch '(?k ?K))
880 (read-number "Keep how many minutes? " default)))
881 (gotback
882 (and (memq ch '(?g ?G))
883 (read-number "Got back how many minutes ago? " default)))
884 (subtractp (memq ch '(?s ?S)))
885 (barely-started-p (< (- (org-float-time last-valid)
886 (org-float-time (cdr clock))) 45))
887 (start-over (and subtractp barely-started-p)))
888 (cond
889 ((memq ch '(?j ?J))
890 (if (eq ch ?J)
891 (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
892 (org-clock-jump-to-current-clock clock))
893 ((or (null ch)
894 (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
895 (message ""))
897 (org-clock-resolve-clock
898 clock (cond
899 ((or (eq ch ?C)
900 ;; If the time on the clock was less than a minute before
901 ;; the user went away, and they've ask to subtract all the
902 ;; time...
903 start-over)
904 nil)
905 ((or subtractp
906 (and gotback (= gotback 0)))
907 last-valid)
908 ((or (and keep (= keep default))
909 (and gotback (= gotback default)))
910 'now)
911 (keep
912 (time-add last-valid (seconds-to-time (* 60 keep))))
913 (gotback
914 (time-subtract (current-time)
915 (seconds-to-time (* 60 gotback))))
917 (error "Unexpected, please report this as a bug")))
918 (and gotback last-valid)
919 (memq ch '(?K ?G ?S))
920 (and start-over
921 (not (memq ch '(?K ?G ?S ?C))))
922 fail-quietly)))))
924 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
925 "Resolve all currently open org-mode clocks.
926 If `only-dangling-p' is non-nil, only ask to resolve dangling
927 \(i.e., not currently open and valid) clocks."
928 (interactive "P")
929 (unless org-clock-resolving-clocks
930 (let ((org-clock-resolving-clocks t))
931 (dolist (file (org-files-list))
932 (let ((clocks (org-find-open-clocks file)))
933 (dolist (clock clocks)
934 (let ((dangling (or (not (org-clock-is-active))
935 (/= (car clock) org-clock-marker))))
936 (if (or (not only-dangling-p) dangling)
937 (org-clock-resolve
938 clock
939 (or prompt-fn
940 (function
941 (lambda (clock)
942 (format
943 "Dangling clock started %d mins ago"
944 (floor
945 (/ (- (org-float-time (current-time))
946 (org-float-time (cdr clock))) 60))))))
947 (or last-valid
948 (cdr clock)))))))))))
950 (defun org-emacs-idle-seconds ()
951 "Return the current Emacs idle time in seconds, or nil if not idle."
952 (let ((idle-time (current-idle-time)))
953 (if idle-time
954 (org-float-time idle-time)
955 0)))
957 (defun org-mac-idle-seconds ()
958 "Return the current Mac idle time in seconds."
959 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
961 (defun org-x11-idle-seconds ()
962 "Return the current X11 idle time in seconds."
963 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
965 (defun org-user-idle-seconds ()
966 "Return the number of seconds the user has been idle for.
967 This routine returns a floating point number."
968 (cond
969 ((eq system-type 'darwin)
970 (org-mac-idle-seconds))
971 ((eq window-system 'x)
972 (org-x11-idle-seconds))
974 (org-emacs-idle-seconds))))
976 (defvar org-clock-user-idle-seconds)
978 (defun org-resolve-clocks-if-idle ()
979 "Resolve all currently open org-mode clocks.
980 This is performed after `org-clock-idle-time' minutes, to check
981 if the user really wants to stay clocked in after being idle for
982 so long."
983 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
984 org-clock-marker)
985 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
986 (org-clock-user-idle-start
987 (time-subtract (current-time)
988 (seconds-to-time org-clock-user-idle-seconds)))
989 (org-clock-resolving-clocks-due-to-idleness t))
990 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
991 (org-clock-resolve
992 (cons org-clock-marker
993 org-clock-start-time)
994 (function
995 (lambda (clock)
996 (format "Clocked in & idle for %.1f mins"
997 (/ (org-float-time
998 (time-subtract (current-time)
999 org-clock-user-idle-start))
1000 60.0))))
1001 org-clock-user-idle-start)))))
1003 (defvar org-clock-current-task nil
1004 "Task currently clocked in.")
1005 (defun org-clock-set-current ()
1006 "Set `org-clock-current-task' to the task currently clocked in."
1007 (setq org-clock-current-task (nth 4 (org-heading-components))))
1009 (defun org-clock-delete-current ()
1010 "Reset `org-clock-current-task' to nil."
1011 (setq org-clock-current-task nil))
1013 (defun org-clock-in (&optional select start-time)
1014 "Start the clock on the current item.
1015 If necessary, clock-out of the currently active clock.
1016 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
1017 recently clocked tasks to
1018 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
1019 clock into the current task and mark
1020 is as the default task, a special task that will always be offered in
1021 the clocking selection, associated with the letter `d'."
1022 (interactive "P")
1023 (setq org-clock-notification-was-shown nil)
1024 (catch 'abort
1025 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
1026 (org-clocking-p)))
1027 ts selected-task target-pos (msg-extra "")
1028 (leftover (and (not org-clock-resolving-clocks)
1029 org-clock-leftover-time)))
1031 (when (and org-clock-auto-clock-resolution
1032 (or (not interrupting)
1033 (eq t org-clock-auto-clock-resolution))
1034 (not org-clock-clocking-in)
1035 (not org-clock-resolving-clocks))
1036 (setq org-clock-leftover-time nil)
1037 (let ((org-clock-clocking-in t))
1038 (org-resolve-clocks))) ; check if any clocks are dangling
1040 (when (equal select '(4))
1041 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1042 (if selected-task
1043 (setq selected-task (copy-marker selected-task))
1044 (error "Abort")))
1046 (when (equal select '(16))
1047 ;; Mark as default clocking task
1048 (org-clock-mark-default-task))
1050 (when interrupting
1051 ;; We are interrupting the clocking of a different task.
1052 ;; Save a marker to this task, so that we can go back.
1053 ;; First check if we are trying to clock into the same task!
1054 (when (save-excursion
1055 (unless selected-task
1056 (org-back-to-heading t))
1057 (and (equal (marker-buffer org-clock-hd-marker)
1058 (if selected-task
1059 (marker-buffer selected-task)
1060 (current-buffer)))
1061 (= (marker-position org-clock-hd-marker)
1062 (if selected-task
1063 (marker-position selected-task)
1064 (point)))
1065 (equal org-clock-current-task (nth 4 (org-heading-components)))))
1066 (message "Clock continues in \"%s\"" org-clock-heading)
1067 (throw 'abort nil))
1068 (move-marker org-clock-interrupted-task
1069 (marker-position org-clock-marker)
1070 (marker-buffer org-clock-marker))
1071 (let ((org-clock-clocking-in t))
1072 (org-clock-out t)))
1074 ;; Clock in at which position?
1075 (setq target-pos
1076 (if (and (eobp) (not (org-at-heading-p)))
1077 (point-at-bol 0)
1078 (point)))
1079 (run-hooks 'org-clock-in-prepare-hook)
1080 (save-excursion
1081 (when (and selected-task (marker-buffer selected-task))
1082 ;; There is a selected task, move to the correct buffer
1083 ;; and set the new target position.
1084 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1085 (setq target-pos (marker-position selected-task))
1086 (move-marker selected-task nil))
1087 (save-excursion
1088 (save-restriction
1089 (widen)
1090 (goto-char target-pos)
1091 (org-back-to-heading t)
1092 (or interrupting (move-marker org-clock-interrupted-task nil))
1093 (org-clock-history-push)
1094 (org-clock-set-current)
1095 (cond ((functionp org-clock-in-switch-to-state)
1096 (looking-at org-complex-heading-regexp)
1097 (let ((newstate (funcall org-clock-in-switch-to-state
1098 (match-string 2))))
1099 (if newstate (org-todo newstate))))
1100 ((and org-clock-in-switch-to-state
1101 (not (looking-at (concat org-outline-regexp "[ \t]*"
1102 org-clock-in-switch-to-state
1103 "\\>"))))
1104 (org-todo org-clock-in-switch-to-state)))
1105 (setq org-clock-heading-for-remember
1106 (and (looking-at org-complex-heading-regexp)
1107 (match-end 4)
1108 (org-trim (buffer-substring (match-end 1)
1109 (match-end 4)))))
1110 (setq org-clock-heading
1111 (cond ((and org-clock-heading-function
1112 (functionp org-clock-heading-function))
1113 (funcall org-clock-heading-function))
1114 ((looking-at org-complex-heading-regexp)
1115 (replace-regexp-in-string
1116 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1117 (match-string 4)))
1118 (t "???")))
1119 (setq org-clock-heading (org-propertize org-clock-heading
1120 'face nil))
1121 (org-clock-find-position org-clock-in-resume)
1122 (cond
1123 ((and org-clock-in-resume
1124 (looking-at
1125 (concat "^[ \t]*" org-clock-string
1126 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1127 " *\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1128 (message "Matched %s" (match-string 1))
1129 (setq ts (concat "[" (match-string 1) "]"))
1130 (goto-char (match-end 1))
1131 (setq org-clock-start-time
1132 (apply 'encode-time
1133 (org-parse-time-string (match-string 1))))
1134 (setq org-clock-effort (org-get-effort))
1135 (setq org-clock-total-time (org-clock-sum-current-item
1136 (org-clock-get-sum-start))))
1137 ((eq org-clock-in-resume 'auto-restart)
1138 ;; called from org-clock-load during startup,
1139 ;; do not interrupt, but warn!
1140 (message "Cannot restart clock because task does not contain unfinished clock")
1141 (ding)
1142 (sit-for 2)
1143 (throw 'abort nil))
1145 (insert-before-markers "\n")
1146 (backward-char 1)
1147 (org-indent-line-function)
1148 (when (and (save-excursion
1149 (end-of-line 0)
1150 (org-in-item-p)))
1151 (beginning-of-line 1)
1152 (org-indent-line-to (- (org-get-indentation) 2)))
1153 (insert org-clock-string " ")
1154 (setq org-clock-effort (org-get-effort))
1155 (setq org-clock-total-time (org-clock-sum-current-item
1156 (org-clock-get-sum-start)))
1157 (setq org-clock-start-time
1158 (or (and leftover
1159 (y-or-n-p
1160 (format
1161 "You stopped another clock %d mins ago; start this one from then? "
1162 (/ (- (org-float-time (current-time))
1163 (org-float-time leftover)) 60)))
1164 leftover)
1165 start-time
1166 (current-time)))
1167 (setq ts (org-insert-time-stamp org-clock-start-time
1168 'with-hm 'inactive))))
1169 (move-marker org-clock-marker (point) (buffer-base-buffer))
1170 (move-marker org-clock-hd-marker
1171 (save-excursion (org-back-to-heading t) (point))
1172 (buffer-base-buffer))
1173 (setq org-clock-has-been-used t)
1174 (or global-mode-string (setq global-mode-string '("")))
1175 (or (memq 'org-mode-line-string global-mode-string)
1176 (setq global-mode-string
1177 (append global-mode-string '(org-mode-line-string))))
1178 (org-clock-update-mode-line)
1179 (when org-clock-mode-line-timer
1180 (cancel-timer org-clock-mode-line-timer)
1181 (setq org-clock-mode-line-timer nil))
1182 (setq org-clock-mode-line-timer
1183 (run-with-timer org-clock-update-period
1184 org-clock-update-period
1185 'org-clock-update-mode-line))
1186 (when org-clock-idle-timer
1187 (cancel-timer org-clock-idle-timer)
1188 (setq org-clock-idle-timer nil))
1189 (setq org-clock-idle-timer
1190 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1191 (message "Clock starts at %s - %s" ts msg-extra)
1192 (run-hooks 'org-clock-in-hook)))))))
1194 (defun org-clock-mark-default-task ()
1195 "Mark current task as default task."
1196 (interactive)
1197 (save-excursion
1198 (org-back-to-heading t)
1199 (move-marker org-clock-default-task (point))))
1201 (defvar msg-extra)
1202 (defun org-clock-get-sum-start ()
1203 "Return the time from which clock times should be counted.
1204 This is for the currently running clock as it is displayed
1205 in the mode line. This function looks at the properties
1206 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1207 corresponding variable `org-clock-modeline-total' and then
1208 decides which time to use."
1209 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1210 (symbol-name org-clock-modeline-total)))
1211 (lr (org-entry-get nil "LAST_REPEAT")))
1212 (cond
1213 ((equal cmt "current")
1214 (setq msg-extra "showing time in current clock instance")
1215 (current-time))
1216 ((equal cmt "today")
1217 (setq msg-extra "showing today's task time.")
1218 (let* ((dt (decode-time (current-time))))
1219 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1220 (if org-extend-today-until
1221 (setf (nth 2 dt) org-extend-today-until))
1222 (apply 'encode-time dt)))
1223 ((or (equal cmt "all")
1224 (and (or (not cmt) (equal cmt "auto"))
1225 (not lr)))
1226 (setq msg-extra "showing entire task time.")
1227 nil)
1228 ((or (equal cmt "repeat")
1229 (and (or (not cmt) (equal cmt "auto"))
1230 lr))
1231 (setq msg-extra "showing task time since last repeat.")
1232 (if (not lr)
1234 (org-time-string-to-time lr)))
1235 (t nil))))
1237 (defun org-clock-find-position (find-unclosed)
1238 "Find the location where the next clock line should be inserted.
1239 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1240 line and position cursor in that line."
1241 (org-back-to-heading t)
1242 (catch 'exit
1243 (let* ((org-clock-into-drawer (org-clock-into-drawer))
1244 (beg (save-excursion
1245 (beginning-of-line 2)
1246 (or (bolp) (newline))
1247 (point)))
1248 (end (progn (outline-next-heading) (point)))
1249 (re (concat "^[ \t]*" org-clock-string))
1250 (cnt 0)
1251 (drawer (if (stringp org-clock-into-drawer)
1252 org-clock-into-drawer "LOGBOOK"))
1253 first last ind-last)
1254 (goto-char beg)
1255 (when (and find-unclosed
1256 (re-search-forward
1257 (concat "^[ \t]*" org-clock-string
1258 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1259 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1260 end t))
1261 (beginning-of-line 1)
1262 (throw 'exit t))
1263 (when (eobp) (newline) (setq end (max (point) end)))
1264 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1265 ;; we seem to have a CLOCK drawer, so go there.
1266 (beginning-of-line 2)
1267 (or org-log-states-order-reversed
1268 (and (re-search-forward org-property-end-re nil t)
1269 (goto-char (match-beginning 0))))
1270 (throw 'exit t))
1271 ;; Lets count the CLOCK lines
1272 (goto-char beg)
1273 (while (re-search-forward re end t)
1274 (setq first (or first (match-beginning 0))
1275 last (match-beginning 0)
1276 cnt (1+ cnt)))
1277 (when (and (integerp org-clock-into-drawer)
1278 last
1279 (>= (1+ cnt) org-clock-into-drawer))
1280 ;; Wrap current entries into a new drawer
1281 (goto-char last)
1282 (setq ind-last (org-get-indentation))
1283 (beginning-of-line 2)
1284 (if (and (>= (org-get-indentation) ind-last)
1285 (org-at-item-p))
1286 (when (and (>= (org-get-indentation) ind-last)
1287 (org-at-item-p))
1288 (let ((struct (org-list-struct)))
1289 (goto-char (org-list-get-bottom-point struct)))))
1290 (insert ":END:\n")
1291 (beginning-of-line 0)
1292 (org-indent-line-to ind-last)
1293 (goto-char first)
1294 (insert ":" drawer ":\n")
1295 (beginning-of-line 0)
1296 (org-indent-line-function)
1297 (org-flag-drawer t)
1298 (beginning-of-line 2)
1299 (or org-log-states-order-reversed
1300 (and (re-search-forward org-property-end-re nil t)
1301 (goto-char (match-beginning 0))))
1302 (throw 'exit nil))
1304 (goto-char beg)
1305 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1306 (not (equal (match-string 1) org-clock-string)))
1307 ;; Planning info, skip to after it
1308 (beginning-of-line 2)
1309 (or (bolp) (newline)))
1310 (when (or (eq org-clock-into-drawer t)
1311 (stringp org-clock-into-drawer)
1312 (and (integerp org-clock-into-drawer)
1313 (< org-clock-into-drawer 2)))
1314 (insert ":" drawer ":\n:END:\n")
1315 (beginning-of-line -1)
1316 (org-indent-line-function)
1317 (org-flag-drawer t)
1318 (beginning-of-line 2)
1319 (org-indent-line-function)
1320 (beginning-of-line)
1321 (or org-log-states-order-reversed
1322 (and (re-search-forward org-property-end-re nil t)
1323 (goto-char (match-beginning 0))))))))
1325 (defun org-clock-out (&optional fail-quietly at-time)
1326 "Stop the currently running clock.
1327 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1328 (interactive)
1329 (catch 'exit
1330 (when (not (org-clocking-p))
1331 (setq global-mode-string
1332 (delq 'org-mode-line-string global-mode-string))
1333 (force-mode-line-update)
1334 (if fail-quietly (throw 'exit t) (error "No active clock")))
1335 (let (ts te s h m remove)
1336 (save-excursion ; Do not replace this with `with-current-buffer'.
1337 (with-no-warnings (set-buffer (org-clocking-buffer)))
1338 (save-restriction
1339 (widen)
1340 (goto-char org-clock-marker)
1341 (beginning-of-line 1)
1342 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1343 (equal (match-string 1) org-clock-string))
1344 (setq ts (match-string 2))
1345 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1346 (goto-char (match-end 0))
1347 (delete-region (point) (point-at-eol))
1348 (insert "--")
1349 (setq te (org-insert-time-stamp (or at-time (current-time))
1350 'with-hm 'inactive))
1351 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1352 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1353 h (floor (/ s 3600))
1354 s (- s (* 3600 h))
1355 m (floor (/ s 60))
1356 s (- s (* 60 s)))
1357 (insert " => " (format "%2d:%02d" h m))
1358 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1359 (= (+ h m) 0)))
1360 (beginning-of-line 1)
1361 (delete-region (point) (point-at-eol))
1362 (and (looking-at "\n") (> (point-max) (1+ (point)))
1363 (delete-char 1)))
1364 (move-marker org-clock-marker nil)
1365 (move-marker org-clock-hd-marker nil)
1366 (when org-log-note-clock-out
1367 (org-add-log-setup 'clock-out nil nil nil nil
1368 (concat "# Task: " (org-get-heading t) "\n\n")))
1369 (when org-clock-mode-line-timer
1370 (cancel-timer org-clock-mode-line-timer)
1371 (setq org-clock-mode-line-timer nil))
1372 (when org-clock-idle-timer
1373 (cancel-timer org-clock-idle-timer)
1374 (setq org-clock-idle-timer nil))
1375 (setq global-mode-string
1376 (delq 'org-mode-line-string global-mode-string))
1377 (when org-clock-out-switch-to-state
1378 (save-excursion
1379 (org-back-to-heading t)
1380 (let ((org-inhibit-logging t)
1381 (org-clock-out-when-done nil))
1382 (cond
1383 ((functionp org-clock-out-switch-to-state)
1384 (looking-at org-complex-heading-regexp)
1385 (let ((newstate (funcall org-clock-out-switch-to-state
1386 (match-string 2))))
1387 (if newstate (org-todo newstate))))
1388 ((and org-clock-out-switch-to-state
1389 (not (looking-at (concat org-outline-regexp "[ \t]*"
1390 org-clock-out-switch-to-state
1391 "\\>"))))
1392 (org-todo org-clock-out-switch-to-state))))))
1393 (force-mode-line-update)
1394 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1395 (if remove " => LINE REMOVED" ""))
1396 (run-hooks 'org-clock-out-hook)
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 org-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 org-state org-done-keywords))
1711 (and (listp org-clock-out-when-done)
1712 (member org-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 todo-only
2445 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2446 cc range-text st p time level hdl props tsp tbl)
2448 (setq org-clock-file-total-minutes nil)
2449 (when block
2450 (setq cc (org-clock-special-range block nil t)
2451 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2452 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2453 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2454 (when (and ts (listp ts))
2455 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2456 (when (and te (listp te))
2457 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2458 ;; Now the times are strings we can parse.
2459 (if ts (setq ts (org-float-time
2460 (apply 'encode-time (org-parse-time-string ts)))))
2461 (if te (setq te (org-float-time
2462 (apply 'encode-time (org-parse-time-string te)))))
2463 (save-excursion
2464 (org-clock-sum ts te
2465 (unless (null matcher)
2466 (lambda ()
2467 (let ((tags-list (org-get-tags-at)))
2468 (eval matcher)))))
2469 (goto-char (point-min))
2470 (setq st t)
2471 (while (or (and (bobp) (prog1 st (setq st nil))
2472 (get-text-property (point) :org-clock-minutes)
2473 (setq p (point-min)))
2474 (setq p (next-single-property-change
2475 (point) :org-clock-minutes)))
2476 (goto-char p)
2477 (when (setq time (get-text-property p :org-clock-minutes))
2478 (save-excursion
2479 (beginning-of-line 1)
2480 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2481 (setq level (org-reduced-level
2482 (- (match-end 1) (match-beginning 1))))
2483 (<= level maxlevel))
2484 (setq hdl (if (not link)
2485 (match-string 2)
2486 (org-make-link-string
2487 (format "file:%s::%s"
2488 (buffer-file-name)
2489 (save-match-data
2490 (org-make-org-heading-search-string
2491 (match-string 2))))
2492 (match-string 2)))
2493 tsp (when timestamp
2494 (setq props (org-entry-properties (point)))
2495 (or (cdr (assoc "SCHEDULED" props))
2496 (cdr (assoc "DEADLINE" props))
2497 (cdr (assoc "TIMESTAMP" props))
2498 (cdr (assoc "TIMESTAMP_IA" props))))
2499 props (when properties
2500 (remove nil
2501 (mapcar
2502 (lambda (p)
2503 (when (org-entry-get (point) p inherit-property-p)
2504 (cons p (org-entry-get (point) p inherit-property-p))))
2505 properties))))
2506 (when (> time 0) (push (list level hdl tsp time props) tbl))))))
2507 (setq tbl (nreverse tbl))
2508 (list file org-clock-file-total-minutes tbl))))
2510 (defun org-clock-time% (total &rest strings)
2511 "Compute a time fraction in percent.
2512 TOTAL s a time string like 10:21 specifying the total times.
2513 STRINGS is a list of strings that should be checked for a time.
2514 The first string that does have a time will be used.
2515 This function is made for clock tables."
2516 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2517 tot s)
2518 (save-match-data
2519 (catch 'exit
2520 (if (not (string-match re total))
2521 (throw 'exit 0.)
2522 (setq tot (+ (string-to-number (match-string 2 total))
2523 (* 60 (string-to-number (match-string 1 total)))))
2524 (if (= tot 0.) (throw 'exit 0.)))
2525 (while (setq s (pop strings))
2526 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2527 (throw 'exit
2528 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2529 (* 60 (string-to-number
2530 (match-string 1 s)))))
2531 tot))))
2532 0))))
2534 ;; Saving and loading the clock
2536 (defvar org-clock-loaded nil
2537 "Was the clock file loaded?")
2539 (defun org-clock-save ()
2540 "Persist various clock-related data to disk.
2541 The details of what will be saved are regulated by the variable
2542 `org-clock-persist'."
2543 (when (and org-clock-persist
2544 (or org-clock-loaded
2545 org-clock-has-been-used
2546 (not (file-exists-p org-clock-persist-file))))
2547 (let (b)
2548 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2549 (progn
2550 (delete-region (point-min) (point-max))
2551 ;;Store clock
2552 (insert (format ";; org-persist.el - %s at %s\n"
2553 system-name (format-time-string
2554 (cdr org-time-stamp-formats))))
2555 (if (and (memq org-clock-persist '(t clock))
2556 (setq b (org-clocking-buffer))
2557 (setq b (or (buffer-base-buffer b) b))
2558 (buffer-live-p b)
2559 (buffer-file-name b)
2560 (or (not org-clock-persist-query-save)
2561 (y-or-n-p (concat "Save current clock ("
2562 (substring-no-properties
2563 org-clock-heading)
2564 ") "))))
2565 (insert "(setq resume-clock '(\""
2566 (buffer-file-name (org-clocking-buffer))
2567 "\" . " (int-to-string (marker-position org-clock-marker))
2568 "))\n"))
2569 ;; Store clocked task history. Tasks are stored reversed to make
2570 ;; reading simpler
2571 (when (and (memq org-clock-persist '(t history))
2572 org-clock-history)
2573 (insert
2574 "(setq stored-clock-history '("
2575 (mapconcat
2576 (lambda (m)
2577 (when (and (setq b (marker-buffer m))
2578 (setq b (or (buffer-base-buffer b) b))
2579 (buffer-live-p b)
2580 (buffer-file-name b))
2581 (concat "(\"" (buffer-file-name b)
2582 "\" . " (int-to-string (marker-position m))
2583 ")")))
2584 (reverse org-clock-history) " ") "))\n"))
2585 (save-buffer)
2586 (kill-buffer (current-buffer)))))))
2588 (defun org-clock-load ()
2589 "Load clock-related data from disk, maybe resuming a stored clock."
2590 (when (and org-clock-persist (not org-clock-loaded))
2591 (let ((filename (expand-file-name org-clock-persist-file))
2592 (org-clock-in-resume 'auto-restart)
2593 resume-clock stored-clock-history)
2594 (if (not (file-readable-p filename))
2595 (message "Not restoring clock data; %s not found"
2596 org-clock-persist-file)
2597 (message "%s" "Restoring clock data")
2598 (setq org-clock-loaded t)
2599 (load-file filename)
2600 ;; load history
2601 (when stored-clock-history
2602 (save-window-excursion
2603 (mapc (lambda (task)
2604 (if (file-exists-p (car task))
2605 (org-clock-history-push (cdr task)
2606 (find-file (car task)))))
2607 stored-clock-history)))
2608 ;; resume clock
2609 (when (and resume-clock org-clock-persist
2610 (file-exists-p (car resume-clock))
2611 (or (not org-clock-persist-query-resume)
2612 (y-or-n-p
2613 (concat
2614 "Resume clock ("
2615 (with-current-buffer (find-file (car resume-clock))
2616 (save-excursion
2617 (goto-char (cdr resume-clock))
2618 (org-back-to-heading t)
2619 (and (looking-at org-complex-heading-regexp)
2620 (match-string 4))))
2621 ") "))))
2622 (when (file-exists-p (car resume-clock))
2623 (with-current-buffer (find-file (car resume-clock))
2624 (goto-char (cdr resume-clock))
2625 (let ((org-clock-auto-clock-resolution nil))
2626 (org-clock-in)
2627 (if (outline-invisible-p)
2628 (org-show-context))))))))))
2630 ;;;###autoload
2631 (defun org-clock-persistence-insinuate ()
2632 "Set up hooks for clock persistence."
2633 (add-hook 'org-mode-hook 'org-clock-load)
2634 (add-hook 'kill-emacs-hook 'org-clock-save))
2636 ;; Suggested bindings
2637 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2639 (provide 'org-clock)
2641 ;;; org-clock.el ends here