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