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