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