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