ox-latex: Remove non-existent TOC value
[org-mode.git] / lisp / org-clock.el
blob02924b824f1664e2d67d02e89eb40267bbcec0c7
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-at-clock-log-p nil
1571 "Is the cursor on the clock log line?"
1572 (save-excursion
1573 (move-beginning-of-line 1)
1574 (looking-at "^[ \t]*CLOCK:")))
1576 (defun org-clock-timestamps-up (&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 'up n))
1582 (defun org-clock-timestamps-down (&optional n)
1583 "Increase CLOCK timestamps at cursor.
1584 Optional argument N tells to change by that many units."
1585 (interactive "P")
1586 (org-clock-timestamps-change 'down n))
1588 (defun org-clock-timestamps-change (updown &optional n)
1589 "Change CLOCK timestamps synchronously at cursor.
1590 UPDOWN tells whether to change 'up or 'down.
1591 Optional argument N tells to change by that many units."
1592 (setq org-ts-what nil)
1593 (when (org-at-timestamp-p t)
1594 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1595 'org-timestamp-down))
1596 ts1 begts1 ts2 begts2 updatets1 tdiff)
1597 (save-excursion
1598 (move-beginning-of-line 1)
1599 (re-search-forward org-ts-regexp3 nil t)
1600 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1601 (when (re-search-forward org-ts-regexp3 nil t)
1602 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1603 ;; Are we on the second timestamp?
1604 (if (<= begts2 (point)) (setq updatets1 t))
1605 (if (not ts2)
1606 ;; fall back on org-timestamp-up if there is only one
1607 (funcall tschange n)
1608 ;; setq this so that (boundp 'org-ts-what is non-nil)
1609 (funcall tschange n)
1610 (let ((ts (if updatets1 ts2 ts1))
1611 (begts (if updatets1 begts1 begts2)))
1612 (setq tdiff
1613 (subtract-time
1614 (org-time-string-to-time org-last-changed-timestamp)
1615 (org-time-string-to-time ts)))
1616 (save-excursion
1617 (goto-char begts)
1618 (org-timestamp-change
1619 (round (/ (org-float-time tdiff)
1620 (cond ((eq org-ts-what 'minute) 60)
1621 ((eq org-ts-what 'hour) 3600)
1622 ((eq org-ts-what 'day) (* 24 3600))
1623 ((eq org-ts-what 'month) (* 24 3600 31))
1624 ((eq org-ts-what 'year) (* 24 3600 365.2)))))
1625 org-ts-what 'updown)))))))
1627 ;;;###autoload
1628 (defun org-clock-cancel ()
1629 "Cancel the running clock by removing the start timestamp."
1630 (interactive)
1631 (when (not (org-clocking-p))
1632 (setq global-mode-string
1633 (delq 'org-mode-line-string global-mode-string))
1634 (setq frame-title-format org-frame-title-format-backup)
1635 (force-mode-line-update)
1636 (error "No active clock"))
1637 (save-excursion ; Do not replace this with `with-current-buffer'.
1638 (org-no-warnings (set-buffer (org-clocking-buffer)))
1639 (goto-char org-clock-marker)
1640 (if (org-looking-back (concat "^[ \t]*" org-clock-string ".*"))
1641 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1642 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1643 (message "Clock gone, cancel the timer anyway")
1644 (sit-for 2)))
1645 (move-marker org-clock-marker nil)
1646 (move-marker org-clock-hd-marker nil)
1647 (setq global-mode-string
1648 (delq 'org-mode-line-string global-mode-string))
1649 (setq frame-title-format org-frame-title-format-backup)
1650 (force-mode-line-update)
1651 (message "Clock canceled")
1652 (run-hooks 'org-clock-cancel-hook))
1654 ;;;###autoload
1655 (defun org-clock-goto (&optional select)
1656 "Go to the currently clocked-in entry, or to the most recently clocked one.
1657 With prefix arg SELECT, offer recently clocked tasks for selection."
1658 (interactive "@P")
1659 (let* ((recent nil)
1660 (m (cond
1661 (select
1662 (or (org-clock-select-task "Select task to go to: ")
1663 (error "No task selected")))
1664 ((org-clocking-p) org-clock-marker)
1665 ((and org-clock-goto-may-find-recent-task
1666 (car org-clock-history)
1667 (marker-buffer (car org-clock-history)))
1668 (setq recent t)
1669 (car org-clock-history))
1670 (t (error "No active or recent clock task")))))
1671 (org-pop-to-buffer-same-window (marker-buffer m))
1672 (if (or (< m (point-min)) (> m (point-max))) (widen))
1673 (goto-char m)
1674 (org-show-entry)
1675 (org-back-to-heading t)
1676 (org-cycle-hide-drawers 'children)
1677 (recenter)
1678 (org-reveal)
1679 (if recent
1680 (message "No running clock, this is the most recently clocked task"))
1681 (run-hooks 'org-clock-goto-hook)))
1683 (defvar org-clock-file-total-minutes nil
1684 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1685 (make-variable-buffer-local 'org-clock-file-total-minutes)
1687 (defun org-clock-sum-today (&optional headline-filter)
1688 "Sum the times for each subtree for today."
1689 (interactive)
1690 (let ((range (org-clock-special-range 'today)))
1691 (org-clock-sum (car range) (cadr range) nil :org-clock-minutes-today)))
1693 ;;;###autoload
1694 (defun org-clock-sum (&optional tstart tend headline-filter propname)
1695 "Sum the times for each subtree.
1696 Puts the resulting times in minutes as a text property on each headline.
1697 TSTART and TEND can mark a time range to be considered.
1698 HEADLINE-FILTER is a zero-arg function that, if specified, is called for
1699 each headline in the time range with point at the headline. Headlines for
1700 which HEADLINE-FILTER returns nil are excluded from the clock summation.
1701 PROPNAME lets you set a custom text property instead of :org-clock-minutes."
1702 (interactive)
1703 (with-silent-modifications
1704 (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1705 org-clock-string
1706 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1707 (lmax 30)
1708 (ltimes (make-vector lmax 0))
1709 (t1 0)
1710 (level 0)
1711 ts te dt
1712 time)
1713 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1714 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1715 (if (consp tstart) (setq tstart (org-float-time tstart)))
1716 (if (consp tend) (setq tend (org-float-time tend)))
1717 (remove-text-properties (point-min) (point-max)
1718 `(,(or propname :org-clock-minutes) t
1719 :org-clock-force-headline-inclusion t))
1720 (save-excursion
1721 (goto-char (point-max))
1722 (while (re-search-backward re nil t)
1723 (cond
1724 ((match-end 2)
1725 ;; Two time stamps
1726 (setq ts (match-string 2)
1727 te (match-string 3)
1728 ts (org-float-time
1729 (apply 'encode-time (org-parse-time-string ts)))
1730 te (org-float-time
1731 (apply 'encode-time (org-parse-time-string te)))
1732 ts (if tstart (max ts tstart) ts)
1733 te (if tend (min te tend) te)
1734 dt (- te ts)
1735 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1736 ((match-end 4)
1737 ;; A naked time
1738 (setq t1 (+ t1 (string-to-number (match-string 5))
1739 (* 60 (string-to-number (match-string 4))))))
1740 (t ;; A headline
1741 ;; Add the currently clocking item time to the total
1742 (when (and org-clock-report-include-clocking-task
1743 (equal (org-clocking-buffer) (current-buffer))
1744 (equal (marker-position org-clock-hd-marker) (point))
1745 tstart
1746 tend
1747 (>= (org-float-time org-clock-start-time) tstart)
1748 (<= (org-float-time org-clock-start-time) tend))
1749 (let ((time (floor (- (org-float-time)
1750 (org-float-time org-clock-start-time)) 60)))
1751 (setq t1 (+ t1 time))))
1752 (let* ((headline-forced
1753 (get-text-property (point)
1754 :org-clock-force-headline-inclusion))
1755 (headline-included
1756 (or (null headline-filter)
1757 (save-excursion
1758 (save-match-data (funcall headline-filter))))))
1759 (setq level (- (match-end 1) (match-beginning 1)))
1760 (when (or (> t1 0) (> (aref ltimes level) 0))
1761 (when (or headline-included headline-forced)
1762 (if headline-included
1763 (loop for l from 0 to level do
1764 (aset ltimes l (+ (aref ltimes l) t1))))
1765 (setq time (aref ltimes level))
1766 (goto-char (match-beginning 0))
1767 (put-text-property (point) (point-at-eol)
1768 (or propname :org-clock-minutes) time)
1769 (if headline-filter
1770 (save-excursion
1771 (save-match-data
1772 (while
1773 (> (funcall outline-level) 1)
1774 (outline-up-heading 1 t)
1775 (put-text-property
1776 (point) (point-at-eol)
1777 :org-clock-force-headline-inclusion t))))))
1778 (setq t1 0)
1779 (loop for l from level to (1- lmax) do
1780 (aset ltimes l 0)))))))
1781 (setq org-clock-file-total-minutes (aref ltimes 0))))))
1783 (defun org-clock-sum-current-item (&optional tstart)
1784 "Return time, clocked on current item in total."
1785 (save-excursion
1786 (save-restriction
1787 (org-narrow-to-subtree)
1788 (org-clock-sum tstart)
1789 org-clock-file-total-minutes)))
1791 ;;;###autoload
1792 (defun org-clock-display (&optional total-only)
1793 "Show subtree times in the entire buffer.
1794 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1795 in the echo area.
1797 Use \\[org-clock-remove-overlays] to remove the subtree times."
1798 (interactive)
1799 (org-clock-remove-overlays)
1800 (let (time h m p)
1801 (org-clock-sum)
1802 (unless total-only
1803 (save-excursion
1804 (goto-char (point-min))
1805 (while (or (and (equal (setq p (point)) (point-min))
1806 (get-text-property p :org-clock-minutes))
1807 (setq p (next-single-property-change
1808 (point) :org-clock-minutes)))
1809 (goto-char p)
1810 (when (setq time (get-text-property p :org-clock-minutes))
1811 (org-clock-put-overlay time (funcall outline-level))))
1812 (setq h (/ org-clock-file-total-minutes 60)
1813 m (- org-clock-file-total-minutes (* 60 h)))
1814 ;; Arrange to remove the overlays upon next change.
1815 (when org-remove-highlights-with-change
1816 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1817 nil 'local))))
1818 (message (concat "Total file time: "
1819 (org-minutes-to-clocksum-string org-clock-file-total-minutes)
1820 " (%d hours and %d minutes)") h m)))
1822 (defvar org-clock-overlays nil)
1823 (make-variable-buffer-local 'org-clock-overlays)
1825 (defun org-clock-put-overlay (time &optional level)
1826 "Put an overlays on the current line, displaying TIME.
1827 If LEVEL is given, prefix time with a corresponding number of stars.
1828 This creates a new overlay and stores it in `org-clock-overlays', so that it
1829 will be easy to remove."
1830 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1831 (l (if level (org-get-valid-level level 0) 0))
1832 (off 0)
1833 ov tx)
1834 (org-move-to-column c)
1835 (unless (eolp) (skip-chars-backward "^ \t"))
1836 (skip-chars-backward " \t")
1837 (setq ov (make-overlay (point-at-bol) (point-at-eol))
1838 tx (concat (buffer-substring (point-at-bol) (point))
1839 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1840 (org-add-props (concat (make-string l ?*) " "
1841 (org-minutes-to-clocksum-string time)
1842 (make-string (- 16 l) ?\ ))
1843 (list 'face 'org-clock-overlay))
1844 ""))
1845 (if (not (featurep 'xemacs))
1846 (overlay-put ov 'display tx)
1847 (overlay-put ov 'invisible t)
1848 (overlay-put ov 'end-glyph (make-glyph tx)))
1849 (push ov org-clock-overlays)))
1851 (defun org-clock-remove-overlays (&optional beg end noremove)
1852 "Remove the occur highlights from the buffer.
1853 BEG and END are ignored. If NOREMOVE is nil, remove this function
1854 from the `before-change-functions' in the current buffer."
1855 (interactive)
1856 (unless org-inhibit-highlight-removal
1857 (mapc 'delete-overlay org-clock-overlays)
1858 (setq org-clock-overlays nil)
1859 (unless noremove
1860 (remove-hook 'before-change-functions
1861 'org-clock-remove-overlays 'local))))
1863 (defvar org-state) ;; dynamically scoped into this function
1864 (defun org-clock-out-if-current ()
1865 "Clock out if the current entry contains the running clock.
1866 This is used to stop the clock after a TODO entry is marked DONE,
1867 and is only done if the variable `org-clock-out-when-done' is not nil."
1868 (when (and (org-clocking-p)
1869 org-clock-out-when-done
1870 (marker-buffer org-clock-marker)
1871 (or (and (eq t org-clock-out-when-done)
1872 (member org-state org-done-keywords))
1873 (and (listp org-clock-out-when-done)
1874 (member org-state org-clock-out-when-done)))
1875 (equal (or (buffer-base-buffer (org-clocking-buffer))
1876 (org-clocking-buffer))
1877 (or (buffer-base-buffer (current-buffer))
1878 (current-buffer)))
1879 (< (point) org-clock-marker)
1880 (> (save-excursion (outline-next-heading) (point))
1881 org-clock-marker))
1882 ;; Clock out, but don't accept a logging message for this.
1883 (let ((org-log-note-clock-out nil)
1884 (org-clock-out-switch-to-state nil))
1885 (org-clock-out))))
1887 (add-hook 'org-after-todo-state-change-hook
1888 'org-clock-out-if-current)
1890 ;;;###autoload
1891 (defun org-clock-get-clocktable (&rest props)
1892 "Get a formatted clocktable with parameters according to PROPS.
1893 The table is created in a temporary buffer, fully formatted and
1894 fontified, and then returned."
1895 ;; Set the defaults
1896 (setq props (plist-put props :name "clocktable"))
1897 (unless (plist-member props :maxlevel)
1898 (setq props (plist-put props :maxlevel 2)))
1899 (unless (plist-member props :scope)
1900 (setq props (plist-put props :scope 'agenda)))
1901 (with-temp-buffer
1902 (org-mode)
1903 (org-create-dblock props)
1904 (org-update-dblock)
1905 (font-lock-fontify-buffer)
1906 (forward-line 2)
1907 (buffer-substring (point) (progn
1908 (re-search-forward "^[ \t]*#\\+END" nil t)
1909 (point-at-bol)))))
1911 ;;;###autoload
1912 (defun org-clock-report (&optional arg)
1913 "Create a table containing a report about clocked time.
1914 If the cursor is inside an existing clocktable block, then the table
1915 will be updated. If not, a new clocktable will be inserted. The scope
1916 of the new clock will be subtree when called from within a subtree, and
1917 file elsewhere.
1919 When called with a prefix argument, move to the first clock table in the
1920 buffer and update it."
1921 (interactive "P")
1922 (org-clock-remove-overlays)
1923 (when arg
1924 (org-find-dblock "clocktable")
1925 (org-show-entry))
1926 (if (org-in-clocktable-p)
1927 (goto-char (org-in-clocktable-p))
1928 (let ((props (if (ignore-errors
1929 (save-excursion (org-back-to-heading)))
1930 (list :name "clocktable" :scope 'subtree)
1931 (list :name "clocktable"))))
1932 (org-create-dblock
1933 (org-combine-plists org-clock-clocktable-default-properties props))))
1934 (org-update-dblock))
1936 (defun org-day-of-week (day month year)
1937 "Returns the day of the week as an integer."
1938 (nth 6
1939 (decode-time
1940 (date-to-time
1941 (format "%d-%02d-%02dT00:00:00" year month day)))))
1943 (defun org-quarter-to-date (quarter year)
1944 "Get the date (week day year) of the first day of a given quarter."
1945 (let (startday)
1946 (cond
1947 ((= quarter 1)
1948 (setq startday (org-day-of-week 1 1 year))
1949 (cond
1950 ((= startday 0)
1951 (list 52 7 (- year 1)))
1952 ((= startday 6)
1953 (list 52 6 (- year 1)))
1954 ((<= startday 4)
1955 (list 1 startday year))
1956 ((> startday 4)
1957 (list 53 startday (- year 1)))
1960 ((= quarter 2)
1961 (setq startday (org-day-of-week 1 4 year))
1962 (cond
1963 ((= startday 0)
1964 (list 13 startday year))
1965 ((< startday 4)
1966 (list 14 startday year))
1967 ((>= startday 4)
1968 (list 13 startday year))
1971 ((= quarter 3)
1972 (setq startday (org-day-of-week 1 7 year))
1973 (cond
1974 ((= startday 0)
1975 (list 26 startday year))
1976 ((< startday 4)
1977 (list 27 startday year))
1978 ((>= startday 4)
1979 (list 26 startday year))
1982 ((= quarter 4)
1983 (setq startday (org-day-of-week 1 10 year))
1984 (cond
1985 ((= startday 0)
1986 (list 39 startday year))
1987 ((<= startday 4)
1988 (list 40 startday year))
1989 ((> startday 4)
1990 (list 39 startday year)))))))
1992 (defun org-clock-special-range (key &optional time as-strings wstart)
1993 "Return two times bordering a special time range.
1994 Key is a symbol specifying the range and can be one of `today', `yesterday',
1995 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1996 By default, a week starts Monday 0:00 and ends Sunday 24:00.
1997 The range is determined relative to TIME. TIME defaults to the current time.
1998 The return value is a cons cell with two internal times like the ones
1999 returned by `current time' or `encode-time'. If AS-STRINGS is non-nil,
2000 the returned times will be formatted strings. If WSTART is non-nil,
2001 use this number to specify the starting day of a week (monday is 1)."
2002 (if (integerp key) (setq key (intern (number-to-string key))))
2003 (let* ((tm (decode-time (or time (current-time))))
2004 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
2005 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
2006 (dow (nth 6 tm))
2007 (ws (or wstart 1))
2008 (skey (symbol-name key))
2009 (shift 0)
2010 (q (cond ((>= (nth 4 tm) 10) 4)
2011 ((>= (nth 4 tm) 7) 3)
2012 ((>= (nth 4 tm) 4) 2)
2013 ((>= (nth 4 tm) 1) 1)))
2014 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
2015 interval tmp shiftedy shiftedm shiftedq)
2016 (cond
2017 ((string-match "^[0-9]+$" skey)
2018 (setq y (string-to-number skey) m 1 d 1 key 'year))
2019 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
2020 (setq y (string-to-number (match-string 1 skey))
2021 month (string-to-number (match-string 2 skey))
2022 d 1 key 'month))
2023 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
2024 (require 'cal-iso)
2025 (setq y (string-to-number (match-string 1 skey))
2026 w (string-to-number (match-string 2 skey)))
2027 (setq date (calendar-gregorian-from-absolute
2028 (calendar-absolute-from-iso (list w 1 y))))
2029 (setq d (nth 1 date) month (car date) y (nth 2 date)
2030 dow 1
2031 key 'week))
2032 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
2033 (require 'cal-iso)
2034 (setq y (string-to-number (match-string 1 skey)))
2035 (setq q (string-to-number (match-string 2 skey)))
2036 (setq date (calendar-gregorian-from-absolute
2037 (calendar-absolute-from-iso (org-quarter-to-date q y))))
2038 (setq d (nth 1 date) month (car date) y (nth 2 date)
2039 dow 1
2040 key 'quarter))
2041 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
2042 (setq y (string-to-number (match-string 1 skey))
2043 month (string-to-number (match-string 2 skey))
2044 d (string-to-number (match-string 3 skey))
2045 key 'day))
2046 ((string-match "\\([-+][0-9]+\\)$" skey)
2047 (setq shift (string-to-number (match-string 1 skey))
2048 key (intern (substring skey 0 (match-beginning 1))))
2049 (if (and (memq key '(quarter thisq)) (> shift 0))
2050 (error "Looking forward with quarters isn't implemented"))))
2052 (when (= shift 0)
2053 (cond ((eq key 'yesterday) (setq key 'today shift -1))
2054 ((eq key 'lastweek) (setq key 'week shift -1))
2055 ((eq key 'lastmonth) (setq key 'month shift -1))
2056 ((eq key 'lastyear) (setq key 'year shift -1))
2057 ((eq key 'lastq) (setq key 'quarter shift -1))))
2058 (cond
2059 ((memq key '(day today))
2060 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
2061 ((memq key '(week thisweek))
2062 (setq diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))
2063 m 0 h 0 d (- d diff) d1 (+ 7 d)))
2064 ((memq key '(month thismonth))
2065 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
2066 ((memq key '(quarter thisq))
2067 ; compute if this shift remains in this year
2068 ; if not, compute how many years and quarters we have to shift (via floor*)
2069 ; and compute the shifted years, months and quarters
2070 (cond
2071 ((< (+ (- q 1) shift) 0) ; shift not in this year
2072 (setq interval (* -1 (+ (- q 1) shift)))
2073 ; set tmp to ((years to shift) (quarters to shift))
2074 (setq tmp (org-floor* interval 4))
2075 ; due to the use of floor, 0 quarters actually means 4
2076 (if (= 0 (nth 1 tmp))
2077 (setq shiftedy (- y (nth 0 tmp))
2078 shiftedm 1
2079 shiftedq 1)
2080 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
2081 shiftedm (- 13 (* 3 (nth 1 tmp)))
2082 shiftedq (- 5 (nth 1 tmp))))
2083 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
2084 ((> (+ q shift) 0) ; shift is within this year
2085 (setq shiftedq (+ q shift))
2086 (setq shiftedy y)
2087 (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))))
2088 ((memq key '(year thisyear))
2089 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
2090 (t (error "No such time block %s" key)))
2091 (setq ts (encode-time s m h d month y)
2092 te (encode-time (or s1 s) (or m1 m) (or h1 h)
2093 (or d1 d) (or month1 month) (or y1 y)))
2094 (setq fm (cdr org-time-stamp-formats))
2095 (cond
2096 ((memq key '(day today))
2097 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
2098 ((memq key '(week thisweek))
2099 (setq txt (format-time-string "week %G-W%V" ts)))
2100 ((memq key '(month thismonth))
2101 (setq txt (format-time-string "%B %Y" ts)))
2102 ((memq key '(year thisyear))
2103 (setq txt (format-time-string "the year %Y" ts)))
2104 ((memq key '(quarter thisq))
2105 (setq txt (concat (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
2107 (if as-strings
2108 (list (format-time-string fm ts) (format-time-string fm te) txt)
2109 (list ts te txt))))
2111 (defun org-count-quarter (n)
2112 (cond
2113 ((= n 1) "1st")
2114 ((= n 2) "2nd")
2115 ((= n 3) "3rd")
2116 ((= n 4) "4th")))
2118 (defun org-clocktable-shift (dir n)
2119 "Try to shift the :block date of the clocktable at point.
2120 Point must be in the #+BEGIN: line of a clocktable, or this function
2121 will throw an error.
2122 DIR is a direction, a symbol `left', `right', `up', or `down'.
2123 Both `left' and `down' shift the block toward the past, `up' and `right'
2124 push it toward the future.
2125 N is the number of shift steps to take. The size of the step depends on
2126 the currently selected interval size."
2127 (setq n (prefix-numeric-value n))
2128 (and (memq dir '(left down)) (setq n (- n)))
2129 (save-excursion
2130 (goto-char (point-at-bol))
2131 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2132 (error "Line needs a :block definition before this command works")
2133 (let* ((b (match-beginning 1)) (e (match-end 1))
2134 (s (match-string 1))
2135 block shift ins y mw d date wp m)
2136 (cond
2137 ((equal s "yesterday") (setq s "today-1"))
2138 ((equal s "lastweek") (setq s "thisweek-1"))
2139 ((equal s "lastmonth") (setq s "thismonth-1"))
2140 ((equal s "lastyear") (setq s "thisyear-1"))
2141 ((equal s "lastq") (setq s "thisq-1")))
2143 (cond
2144 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
2145 (setq block (match-string 1 s)
2146 shift (if (match-end 2)
2147 (string-to-number (match-string 2 s))
2149 (setq shift (+ shift n))
2150 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
2151 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
2152 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2153 (setq y (string-to-number (match-string 1 s))
2154 wp (and (match-end 3) (match-string 3 s))
2155 mw (and (match-end 4) (string-to-number (match-string 4 s)))
2156 d (and (match-end 6) (string-to-number (match-string 6 s))))
2157 (cond
2158 (d (setq ins (format-time-string
2159 "%Y-%m-%d"
2160 (encode-time 0 0 0 (+ d n) m y))))
2161 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2162 (require 'cal-iso)
2163 (setq date (calendar-gregorian-from-absolute
2164 (calendar-absolute-from-iso (list (+ mw n) 1 y))))
2165 (setq ins (format-time-string
2166 "%G-W%V"
2167 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2168 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2169 (require 'cal-iso)
2170 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2171 (if (> (+ mw n) 4)
2172 (setq mw 0
2173 y (+ 1 y))
2175 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2176 (if (= (+ mw n) 0)
2177 (setq mw 5
2178 y (- y 1))
2180 (setq date (calendar-gregorian-from-absolute
2181 (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
2182 (setq ins (format-time-string
2183 (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
2184 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2186 (setq ins (format-time-string
2187 "%Y-%m"
2188 (encode-time 0 0 0 1 (+ mw n) y))))
2190 (setq ins (number-to-string (+ y n))))))
2191 (t (error "Cannot shift clocktable block")))
2192 (when ins
2193 (goto-char b)
2194 (insert ins)
2195 (delete-region (point) (+ (point) (- e b)))
2196 (beginning-of-line 1)
2197 (org-update-dblock)
2198 t)))))
2200 ;;;###autoload
2201 (defun org-dblock-write:clocktable (params)
2202 "Write the standard clocktable."
2203 (setq params (org-combine-plists org-clocktable-defaults params))
2204 (catch 'exit
2205 (let* ((scope (plist-get params :scope))
2206 (block (plist-get params :block))
2207 (ts (plist-get params :tstart))
2208 (te (plist-get params :tend))
2209 (link (plist-get params :link))
2210 (maxlevel (or (plist-get params :maxlevel) 3))
2211 (ws (plist-get params :wstart))
2212 (step (plist-get params :step))
2213 (timestamp (plist-get params :timestamp))
2214 (formatter (or (plist-get params :formatter)
2215 org-clock-clocktable-formatter
2216 'org-clocktable-write-default))
2217 cc range-text ipos pos one-file-with-archives
2218 scope-is-list tbls level)
2219 ;; Check if we need to do steps
2220 (when block
2221 ;; Get the range text for the header
2222 (setq cc (org-clock-special-range block nil t ws)
2223 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2224 (when step
2225 ;; Write many tables, in steps
2226 (unless (or block (and ts te))
2227 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2228 (org-clocktable-steps params)
2229 (throw 'exit nil))
2231 (setq ipos (point)) ; remember the insertion position
2233 ;; Get the right scope
2234 (setq pos (point))
2235 (cond
2236 ((and scope (listp scope) (symbolp (car scope)))
2237 (setq scope (eval scope)))
2238 ((eq scope 'agenda)
2239 (setq scope (org-agenda-files t)))
2240 ((eq scope 'agenda-with-archives)
2241 (setq scope (org-agenda-files t))
2242 (setq scope (org-add-archive-files scope)))
2243 ((eq scope 'file-with-archives)
2244 (setq scope (org-add-archive-files (list (buffer-file-name)))
2245 one-file-with-archives t)))
2246 (setq scope-is-list (and scope (listp scope)))
2247 (if scope-is-list
2248 ;; we collect from several files
2249 (let* ((files scope)
2250 file)
2251 (org-agenda-prepare-buffers files)
2252 (while (setq file (pop files))
2253 (with-current-buffer (find-buffer-visiting file)
2254 (save-excursion
2255 (save-restriction
2256 (push (org-clock-get-table-data file params) tbls))))))
2257 ;; Just from the current file
2258 (save-restriction
2259 ;; get the right range into the restriction
2260 (org-agenda-prepare-buffers (list (buffer-file-name)))
2261 (cond
2262 ((not scope)) ; use the restriction as it is now
2263 ((eq scope 'file) (widen))
2264 ((eq scope 'subtree) (org-narrow-to-subtree))
2265 ((eq scope 'tree)
2266 (while (org-up-heading-safe))
2267 (org-narrow-to-subtree))
2268 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
2269 (symbol-name scope)))
2270 (setq level (string-to-number (match-string 1 (symbol-name scope))))
2271 (catch 'exit
2272 (while (org-up-heading-safe)
2273 (looking-at org-outline-regexp)
2274 (if (<= (org-reduced-level (funcall outline-level)) level)
2275 (throw 'exit nil))))
2276 (org-narrow-to-subtree)))
2277 ;; do the table, with no file name.
2278 (push (org-clock-get-table-data nil params) tbls)))
2280 ;; OK, at this point we tbls as a list of tables, one per file
2281 (setq tbls (nreverse tbls))
2283 (setq params (plist-put params :multifile scope-is-list))
2284 (setq params (plist-put params :one-file-with-archives
2285 one-file-with-archives))
2287 (funcall formatter ipos tbls params))))
2289 (defun org-clocktable-write-default (ipos tables params)
2290 "Write out a clock table at position IPOS in the current buffer.
2291 TABLES is a list of tables with clocking data as produced by
2292 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2293 from the dynamic block definition."
2294 ;; This function looks quite complicated, mainly because there are a
2295 ;; lot of options which can add or remove columns. I have massively
2296 ;; commented this function, the I hope it is understandable. If
2297 ;; someone wants to write their own special formatter, this maybe
2298 ;; much easier because there can be a fixed format with a
2299 ;; well-defined number of columns...
2300 (let* ((hlchars '((1 . "*") (2 . "/")))
2301 (lwords (assoc (or (plist-get params :lang)
2302 (org-bound-and-true-p org-export-default-language)
2303 "en")
2304 org-clock-clocktable-language-setup))
2305 (multifile (plist-get params :multifile))
2306 (block (plist-get params :block))
2307 (ts (plist-get params :tstart))
2308 (te (plist-get params :tend))
2309 (header (plist-get params :header))
2310 (narrow (plist-get params :narrow))
2311 (ws (or (plist-get params :wstart) 1))
2312 (link (plist-get params :link))
2313 (maxlevel (or (plist-get params :maxlevel) 3))
2314 (emph (plist-get params :emphasize))
2315 (level-p (plist-get params :level))
2316 (org-time-clocksum-use-effort-durations
2317 (plist-get params :effort-durations))
2318 (timestamp (plist-get params :timestamp))
2319 (properties (plist-get params :properties))
2320 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2321 (rm-file-column (plist-get params :one-file-with-archives))
2322 (indent (plist-get params :indent))
2323 (case-fold-search t)
2324 range-text total-time tbl level hlc formula pcol
2325 file-time entries entry headline
2326 recalc content narrow-cut-p tcol)
2328 ;; Implement abbreviations
2329 (when (plist-get params :compact)
2330 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2332 ;; Some consistency test for parameters
2333 (unless (integerp ntcol)
2334 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2336 (when (and narrow (integerp narrow) link)
2337 ;; We cannot have both integer narrow and link
2338 (message
2339 "Using hard narrowing in clocktable to allow for links")
2340 (setq narrow (intern (format "%d!" narrow))))
2342 (when narrow
2343 (cond
2344 ((integerp narrow))
2345 ((and (symbolp narrow)
2346 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2347 (setq narrow-cut-p t
2348 narrow (string-to-number (substring (symbol-name narrow)
2349 0 -1))))
2351 (error "Invalid value %s of :narrow property in clock table"
2352 narrow))))
2354 (when block
2355 ;; Get the range text for the header
2356 (setq range-text (nth 2 (org-clock-special-range block nil t ws))))
2358 ;; Compute the total time
2359 (setq total-time (apply '+ (mapcar 'cadr tables)))
2361 ;; Now we need to output this tsuff
2362 (goto-char ipos)
2364 ;; Insert the text *before* the actual table
2365 (insert-before-markers
2366 (or header
2367 ;; Format the standard header
2368 (concat
2369 "#+CAPTION: "
2370 (nth 9 lwords) " ["
2371 (substring
2372 (format-time-string (cdr org-time-stamp-formats))
2373 1 -1)
2375 (if block (concat ", for " range-text ".") "")
2376 "\n")))
2378 ;; Insert the narrowing line
2379 (when (and narrow (integerp narrow) (not narrow-cut-p))
2380 (insert-before-markers
2381 "|" ; table line starter
2382 (if multifile "|" "") ; file column, maybe
2383 (if level-p "|" "") ; level column, maybe
2384 (if timestamp "|" "") ; timestamp column, maybe
2385 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2386 (format "<%d>| |\n" narrow))) ; headline and time columns
2388 ;; Insert the table header line
2389 (insert-before-markers
2390 "|" ; table line starter
2391 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2392 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2393 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2394 (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
2395 (concat (nth 4 lwords) "|"
2396 (nth 5 lwords) "|\n")) ; headline and time columns
2398 ;; Insert the total time in the table
2399 (insert-before-markers
2400 "|-\n" ; a hline
2401 "|" ; table line starter
2402 (if multifile (concat "| " (nth 6 lwords) " ") "")
2403 ; file column, maybe
2404 (if level-p "|" "") ; level column, maybe
2405 (if timestamp "|" "") ; timestamp column, maybe
2406 (if properties (make-string (length properties) ?|) "") ; properties columns, maybe
2407 (concat (format org-clock-total-time-cell-format (nth 7 lwords)) "| ") ; instead of a headline
2408 (format org-clock-total-time-cell-format
2409 (org-minutes-to-clocksum-string (or total-time 0))) ; the time
2410 "|\n") ; close line
2412 ;; Now iterate over the tables and insert the data
2413 ;; but only if any time has been collected
2414 (when (and total-time (> total-time 0))
2416 (while (setq tbl (pop tables))
2417 ;; now tbl is the table resulting from one file.
2418 (setq file-time (nth 1 tbl))
2419 (when (or (and file-time (> file-time 0))
2420 (not (plist-get params :fileskip0)))
2421 (insert-before-markers "|-\n") ; a hline because a new file starts
2422 ;; First the file time, if we have multiple files
2423 (when multifile
2424 ;; Summarize the time collected from this file
2425 (insert-before-markers
2426 (format (concat "| %s %s | %s%s"
2427 (format org-clock-file-time-cell-format (nth 8 lwords))
2428 " | *%s*|\n")
2429 (file-name-nondirectory (car tbl))
2430 (if level-p "| " "") ; level column, maybe
2431 (if timestamp "| " "") ; timestamp column, maybe
2432 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2433 (org-minutes-to-clocksum-string (nth 1 tbl))))) ; the time
2435 ;; Get the list of node entries and iterate over it
2436 (setq entries (nth 2 tbl))
2437 (while (setq entry (pop entries))
2438 (setq level (car entry)
2439 headline (nth 1 entry)
2440 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2441 (when narrow-cut-p
2442 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2443 "\\'")
2444 headline)
2445 (match-end 3))
2446 (setq headline
2447 (format "[[%s][%s]]"
2448 (match-string 1 headline)
2449 (org-shorten-string (match-string 3 headline)
2450 narrow)))
2451 (setq headline (org-shorten-string headline narrow))))
2452 (insert-before-markers
2453 "|" ; start the table line
2454 (if multifile "|" "") ; free space for file name column?
2455 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2456 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2457 (if properties
2458 (concat
2459 (mapconcat
2460 (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
2461 properties "|") "|") "") ;properties columns, maybe
2462 (if indent (org-clocktable-indent-string level) "") ; indentation
2463 hlc headline hlc "|" ; headline
2464 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2465 ; empty fields for higher levels
2466 hlc (org-minutes-to-clocksum-string (nth 3 entry)) hlc ; time
2467 "|\n" ; close line
2468 )))))
2469 ;; When exporting subtrees or regions the region might be
2470 ;; activated, so let's disable ̀delete-active-region'
2471 (let ((delete-active-region nil)) (backward-delete-char 1))
2472 (if (setq formula (plist-get params :formula))
2473 (cond
2474 ((eq formula '%)
2475 ;; compute the column where the % numbers need to go
2476 (setq pcol (+ 2
2477 (if multifile 1 0)
2478 (if level-p 1 0)
2479 (if timestamp 1 0)
2480 (min maxlevel (or ntcol 100))))
2481 ;; compute the column where the total time is
2482 (setq tcol (+ 2
2483 (if multifile 1 0)
2484 (if level-p 1 0)
2485 (if timestamp 1 0)))
2486 (insert
2487 (format
2488 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2489 pcol ; the column where the % numbers should go
2490 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2491 tcol ; column of the total time
2492 tcol (1- pcol) ; range of columns where times can be found
2494 (setq recalc t))
2495 ((stringp formula)
2496 (insert "\n#+TBLFM: " formula)
2497 (setq recalc t))
2498 (t (error "Invalid formula in clocktable")))
2499 ;; Should we rescue an old formula?
2500 (when (stringp (setq content (plist-get params :content)))
2501 (when (string-match "^\\([ \t]*#\\+tblfm:.*\\)" content)
2502 (setq recalc t)
2503 (insert "\n" (match-string 1 (plist-get params :content)))
2504 (beginning-of-line 0))))
2505 ;; Back to beginning, align the table, recalculate if necessary
2506 (goto-char ipos)
2507 (skip-chars-forward "^|")
2508 (org-table-align)
2509 (when org-hide-emphasis-markers
2510 ;; we need to align a second time
2511 (org-table-align))
2512 (when recalc
2513 (if (eq formula '%)
2514 (save-excursion
2515 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2516 (org-table-goto-column pcol nil 'force)
2517 (insert "%")))
2518 (org-table-recalculate 'all))
2519 (when rm-file-column
2520 ;; The file column is actually not wanted
2521 (forward-char 1)
2522 (org-table-delete-column))
2523 total-time))
2525 (defun org-clocktable-indent-string (level)
2526 (if (= level 1)
2528 (let ((str "\\__"))
2529 (while (> level 2)
2530 (setq level (1- level)
2531 str (concat str "___")))
2532 (concat str " "))))
2534 (defun org-clocktable-steps (params)
2535 "Step through the range to make a number of clock tables."
2536 (let* ((p1 (copy-sequence params))
2537 (ts (plist-get p1 :tstart))
2538 (te (plist-get p1 :tend))
2539 (ws (plist-get p1 :wstart))
2540 (step0 (plist-get p1 :step))
2541 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2542 (stepskip0 (plist-get p1 :stepskip0))
2543 (block (plist-get p1 :block))
2544 cc range-text step-time)
2545 (when block
2546 (setq cc (org-clock-special-range block nil t ws)
2547 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2548 (cond
2549 ((numberp ts)
2550 ;; If ts is a number, it's an absolute day number from org-agenda.
2551 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2552 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2554 (setq ts (org-float-time
2555 (apply 'encode-time (org-parse-time-string ts))))))
2556 (cond
2557 ((numberp te)
2558 ;; Likewise for te.
2559 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2560 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2562 (setq te (org-float-time
2563 (apply 'encode-time (org-parse-time-string te))))))
2564 (setq p1 (plist-put p1 :header ""))
2565 (setq p1 (plist-put p1 :step nil))
2566 (setq p1 (plist-put p1 :block nil))
2567 (while (< ts te)
2568 (or (bolp) (insert "\n"))
2569 (setq p1 (plist-put p1 :tstart (format-time-string
2570 (org-time-stamp-format nil t)
2571 (seconds-to-time ts))))
2572 (setq p1 (plist-put p1 :tend (format-time-string
2573 (org-time-stamp-format nil t)
2574 (seconds-to-time (setq ts (+ ts step))))))
2575 (insert "\n" (if (eq step0 'day) "Daily report: "
2576 "Weekly report starting on: ")
2577 (plist-get p1 :tstart) "\n")
2578 (setq step-time (org-dblock-write:clocktable p1))
2579 (re-search-forward "^[ \t]*#\\+END:")
2580 (when (and (equal step-time 0) stepskip0)
2581 ;; Remove the empty table
2582 (delete-region (point-at-bol)
2583 (save-excursion
2584 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2585 nil t)
2586 (point))))
2587 (end-of-line 0))))
2589 (defun org-clock-get-table-data (file params)
2590 "Get the clocktable data for file FILE, with parameters PARAMS.
2591 FILE is only for identification - this function assumes that
2592 the correct buffer is current, and that the wanted restriction is
2593 in place.
2594 The return value will be a list with the file name and the total
2595 file time (in minutes) as 1st and 2nd elements. The third element
2596 of this list will be a list of headline entries. Each entry has the
2597 following structure:
2599 (LEVEL HEADLINE TIMESTAMP TIME)
2601 LEVEL: The level of the headline, as an integer. This will be
2602 the reduced leve, so 1,2,3,... even if only odd levels
2603 are being used.
2604 HEADLINE: The text of the headline. Depending on PARAMS, this may
2605 already be formatted like a link.
2606 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2607 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2608 in this sequence.
2609 TIME: The sum of all time spend in this tree, in minutes. This time
2610 will of cause be restricted to the time block and tags match
2611 specified in PARAMS."
2612 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2613 (timestamp (plist-get params :timestamp))
2614 (ts (plist-get params :tstart))
2615 (te (plist-get params :tend))
2616 (ws (plist-get params :wstart))
2617 (block (plist-get params :block))
2618 (link (plist-get params :link))
2619 (tags (plist-get params :tags))
2620 (properties (plist-get params :properties))
2621 (inherit-property-p (plist-get params :inherit-props))
2622 todo-only
2623 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2624 cc range-text st p time level hdl props tsp tbl)
2626 (setq org-clock-file-total-minutes nil)
2627 (when block
2628 (setq cc (org-clock-special-range block nil t ws)
2629 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2630 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2631 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2632 (when (and ts (listp ts))
2633 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2634 (when (and te (listp te))
2635 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2636 ;; Now the times are strings we can parse.
2637 (if ts (setq ts (org-float-time
2638 (seconds-to-time (org-matcher-time ts)))))
2639 (if te (setq te (org-float-time
2640 (seconds-to-time (org-matcher-time te)))))
2641 (save-excursion
2642 (org-clock-sum ts te
2643 (unless (null matcher)
2644 (lambda ()
2645 (let* ((tags-list (org-get-tags-at))
2646 (org-scanner-tags tags-list)
2647 (org-trust-scanner-tags t))
2648 (eval matcher)))))
2649 (goto-char (point-min))
2650 (setq st t)
2651 (while (or (and (bobp) (prog1 st (setq st nil))
2652 (get-text-property (point) :org-clock-minutes)
2653 (setq p (point-min)))
2654 (setq p (next-single-property-change
2655 (point) :org-clock-minutes)))
2656 (goto-char p)
2657 (when (setq time (get-text-property p :org-clock-minutes))
2658 (save-excursion
2659 (beginning-of-line 1)
2660 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2661 (setq level (org-reduced-level
2662 (- (match-end 1) (match-beginning 1))))
2663 (<= level maxlevel))
2664 (setq hdl (if (not link)
2665 (match-string 2)
2666 (org-make-link-string
2667 (format "file:%s::%s"
2668 (buffer-file-name)
2669 (save-match-data
2670 (org-make-org-heading-search-string
2671 (match-string 2))))
2672 (match-string 2)))
2673 tsp (when timestamp
2674 (setq props (org-entry-properties (point)))
2675 (or (cdr (assoc "SCHEDULED" props))
2676 (cdr (assoc "DEADLINE" props))
2677 (cdr (assoc "TIMESTAMP" props))
2678 (cdr (assoc "TIMESTAMP_IA" props))))
2679 props (when properties
2680 (remove nil
2681 (mapcar
2682 (lambda (p)
2683 (when (org-entry-get (point) p inherit-property-p)
2684 (cons p (org-entry-get (point) p inherit-property-p))))
2685 properties))))
2686 (when (> time 0) (push (list level hdl tsp time props) tbl))))))
2687 (setq tbl (nreverse tbl))
2688 (list file org-clock-file-total-minutes tbl))))
2690 (defun org-clock-time% (total &rest strings)
2691 "Compute a time fraction in percent.
2692 TOTAL s a time string like 10:21 specifying the total times.
2693 STRINGS is a list of strings that should be checked for a time.
2694 The first string that does have a time will be used.
2695 This function is made for clock tables."
2696 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2697 tot s)
2698 (save-match-data
2699 (catch 'exit
2700 (if (not (string-match re total))
2701 (throw 'exit 0.)
2702 (setq tot (+ (string-to-number (match-string 2 total))
2703 (* 60 (string-to-number (match-string 1 total)))))
2704 (if (= tot 0.) (throw 'exit 0.)))
2705 (while (setq s (pop strings))
2706 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2707 (throw 'exit
2708 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2709 (* 60 (string-to-number
2710 (match-string 1 s)))))
2711 tot))))
2712 0))))
2714 ;; Saving and loading the clock
2716 (defvar org-clock-loaded nil
2717 "Was the clock file loaded?")
2719 (defun org-clock-update-time-maybe ()
2720 "If this is a CLOCK line, update it and return t.
2721 Otherwise, return nil."
2722 (interactive)
2723 (save-excursion
2724 (beginning-of-line 1)
2725 (skip-chars-forward " \t")
2726 (when (looking-at org-clock-string)
2727 (let ((re (concat "[ \t]*" org-clock-string
2728 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2729 "\\([ \t]*=>.*\\)?\\)?"))
2730 ts te h m s neg)
2731 (cond
2732 ((not (looking-at re))
2733 nil)
2734 ((not (match-end 2))
2735 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2736 (> org-clock-marker (point))
2737 (<= org-clock-marker (point-at-eol)))
2738 ;; The clock is running here
2739 (setq org-clock-start-time
2740 (apply 'encode-time
2741 (org-parse-time-string (match-string 1))))
2742 (org-clock-update-mode-line)))
2744 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2745 (end-of-line 1)
2746 (setq ts (match-string 1)
2747 te (match-string 3))
2748 (setq s (- (org-float-time
2749 (apply 'encode-time (org-parse-time-string te)))
2750 (org-float-time
2751 (apply 'encode-time (org-parse-time-string ts))))
2752 neg (< s 0)
2753 s (abs s)
2754 h (floor (/ s 3600))
2755 s (- s (* 3600 h))
2756 m (floor (/ s 60))
2757 s (- s (* 60 s)))
2758 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2759 t))))))
2761 (defun org-clock-save ()
2762 "Persist various clock-related data to disk.
2763 The details of what will be saved are regulated by the variable
2764 `org-clock-persist'."
2765 (when (and org-clock-persist
2766 (or org-clock-loaded
2767 org-clock-has-been-used
2768 (not (file-exists-p org-clock-persist-file))))
2769 (let (b)
2770 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2771 (progn
2772 (delete-region (point-min) (point-max))
2773 ;;Store clock
2774 (insert (format ";; org-persist.el - %s at %s\n"
2775 system-name (format-time-string
2776 (cdr org-time-stamp-formats))))
2777 (if (and (memq org-clock-persist '(t clock))
2778 (setq b (org-clocking-buffer))
2779 (setq b (or (buffer-base-buffer b) b))
2780 (buffer-live-p b)
2781 (buffer-file-name b)
2782 (or (not org-clock-persist-query-save)
2783 (y-or-n-p (concat "Save current clock ("
2784 org-clock-heading ") "))))
2785 (insert "(setq resume-clock '(\""
2786 (buffer-file-name (org-clocking-buffer))
2787 "\" . " (int-to-string (marker-position org-clock-marker))
2788 "))\n"))
2789 ;; Store clocked task history. Tasks are stored reversed to make
2790 ;; reading simpler
2791 (when (and (memq org-clock-persist '(t history))
2792 org-clock-history)
2793 (insert
2794 "(setq stored-clock-history '("
2795 (mapconcat
2796 (lambda (m)
2797 (when (and (setq b (marker-buffer m))
2798 (setq b (or (buffer-base-buffer b) b))
2799 (buffer-live-p b)
2800 (buffer-file-name b))
2801 (concat "(\"" (buffer-file-name b)
2802 "\" . " (int-to-string (marker-position m))
2803 ")")))
2804 (reverse org-clock-history) " ") "))\n"))
2805 (save-buffer)
2806 (kill-buffer (current-buffer)))))))
2808 (defun org-clock-load ()
2809 "Load clock-related data from disk, maybe resuming a stored clock."
2810 (when (and org-clock-persist (not org-clock-loaded))
2811 (let ((filename (expand-file-name org-clock-persist-file))
2812 (org-clock-in-resume 'auto-restart)
2813 resume-clock stored-clock-history)
2814 (if (not (file-readable-p filename))
2815 (message "Not restoring clock data; %s not found"
2816 org-clock-persist-file)
2817 (message "%s" "Restoring clock data")
2818 (setq org-clock-loaded t)
2819 (load-file filename)
2820 ;; load history
2821 (when stored-clock-history
2822 (save-window-excursion
2823 (mapc (lambda (task)
2824 (if (file-exists-p (car task))
2825 (org-clock-history-push (cdr task)
2826 (find-file (car task)))))
2827 stored-clock-history)))
2828 ;; resume clock
2829 (when (and resume-clock org-clock-persist
2830 (file-exists-p (car resume-clock))
2831 (or (not org-clock-persist-query-resume)
2832 (y-or-n-p
2833 (concat
2834 "Resume clock ("
2835 (with-current-buffer (find-file (car resume-clock))
2836 (save-excursion
2837 (goto-char (cdr resume-clock))
2838 (org-back-to-heading t)
2839 (and (looking-at org-complex-heading-regexp)
2840 (match-string 4))))
2841 ") "))))
2842 (when (file-exists-p (car resume-clock))
2843 (with-current-buffer (find-file (car resume-clock))
2844 (goto-char (cdr resume-clock))
2845 (let ((org-clock-auto-clock-resolution nil))
2846 (org-clock-in)
2847 (if (outline-invisible-p)
2848 (org-show-context))))))))))
2850 ;; Suggested bindings
2851 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2853 (provide 'org-clock)
2855 ;; Local variables:
2856 ;; generated-autoload-file: "org-loaddefs.el"
2857 ;; End:
2859 ;;; org-clock.el ends here