replacing cl concatenate with concat
[org-mode.git] / lisp / org-clock.el
blob40e1556b4f53f50866dd7601e362795c06233cfb
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 ((and
1014 (eq window-system 'x)
1015 ;; Check that x11idle exists
1016 (eq (call-process-shell-command "command" nil nil nil "-v" "x11idle") 0)
1017 ;; Check that x11idle can retrieve the idle time
1018 (eq (call-process-shell-command "x11idle" nil nil nil ) 0))
1019 (org-x11-idle-seconds))
1021 (org-emacs-idle-seconds))))
1023 (defvar org-clock-user-idle-seconds)
1025 (defun org-resolve-clocks-if-idle ()
1026 "Resolve all currently open org-mode clocks.
1027 This is performed after `org-clock-idle-time' minutes, to check
1028 if the user really wants to stay clocked in after being idle for
1029 so long."
1030 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
1031 org-clock-marker)
1032 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
1033 (org-clock-user-idle-start
1034 (time-subtract (current-time)
1035 (seconds-to-time org-clock-user-idle-seconds)))
1036 (org-clock-resolving-clocks-due-to-idleness t))
1037 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
1038 (org-clock-resolve
1039 (cons org-clock-marker
1040 org-clock-start-time)
1041 (function
1042 (lambda (clock)
1043 (format "Clocked in & idle for %.1f mins"
1044 (/ (org-float-time
1045 (time-subtract (current-time)
1046 org-clock-user-idle-start))
1047 60.0))))
1048 org-clock-user-idle-start)))))
1050 (defvar org-clock-current-task nil
1051 "Task currently clocked in.")
1052 (defun org-clock-set-current ()
1053 "Set `org-clock-current-task' to the task currently clocked in."
1054 (setq org-clock-current-task (nth 4 (org-heading-components))))
1056 (defun org-clock-delete-current ()
1057 "Reset `org-clock-current-task' to nil."
1058 (setq org-clock-current-task nil))
1060 (defvar org-clock-out-time nil) ; store the time of the last clock-out
1061 (defun org-clock-in (&optional select start-time)
1062 "Start the clock on the current item.
1063 If necessary, clock-out of the currently active clock.
1064 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
1065 recently clocked tasks to
1066 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
1067 clock into the current task and mark
1068 it as the default task, a special task that will always be offered in
1069 the clocking selection, associated with the letter `d'.
1070 When SELECT is \\[universal-argument] \\[universal-argument] \\[universal-argument], \
1071 clock in by using the last clock-out time as the start time
1072 \(see `org-clock-continuously' to make this the default behavior.)"
1073 (interactive "P")
1074 (setq org-clock-notification-was-shown nil)
1075 (catch 'abort
1076 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
1077 (org-clocking-p)))
1078 ts selected-task target-pos (msg-extra "")
1079 (leftover (and (not org-clock-resolving-clocks)
1080 org-clock-leftover-time)))
1082 (when (and org-clock-auto-clock-resolution
1083 (or (not interrupting)
1084 (eq t org-clock-auto-clock-resolution))
1085 (not org-clock-clocking-in)
1086 (not org-clock-resolving-clocks))
1087 (setq org-clock-leftover-time nil)
1088 (let ((org-clock-clocking-in t))
1089 (org-resolve-clocks))) ; check if any clocks are dangling
1091 (when (equal select '(64))
1092 ;; Set start-time to `org-clock-out-time'
1093 (let ((org-clock-continuously t))
1094 (org-clock-in nil org-clock-out-time)))
1096 (when (equal select '(4))
1097 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1098 (if selected-task
1099 (setq selected-task (copy-marker selected-task))
1100 (error "Abort")))
1102 (when (equal select '(16))
1103 ;; Mark as default clocking task
1104 (org-clock-mark-default-task))
1106 (when interrupting
1107 ;; We are interrupting the clocking of a different task.
1108 ;; Save a marker to this task, so that we can go back.
1109 ;; First check if we are trying to clock into the same task!
1110 (when (save-excursion
1111 (unless selected-task
1112 (org-back-to-heading t))
1113 (and (equal (marker-buffer org-clock-hd-marker)
1114 (if selected-task
1115 (marker-buffer selected-task)
1116 (current-buffer)))
1117 (= (marker-position org-clock-hd-marker)
1118 (if selected-task
1119 (marker-position selected-task)
1120 (point)))
1121 (equal org-clock-current-task (nth 4 (org-heading-components)))))
1122 (message "Clock continues in \"%s\"" org-clock-heading)
1123 (throw 'abort nil))
1124 (move-marker org-clock-interrupted-task
1125 (marker-position org-clock-marker)
1126 (marker-buffer org-clock-marker))
1127 (let ((org-clock-clocking-in t))
1128 (org-clock-out t)))
1130 ;; Clock in at which position?
1131 (setq target-pos
1132 (if (and (eobp) (not (org-at-heading-p)))
1133 (point-at-bol 0)
1134 (point)))
1135 (run-hooks 'org-clock-in-prepare-hook)
1136 (save-excursion
1137 (when (and selected-task (marker-buffer selected-task))
1138 ;; There is a selected task, move to the correct buffer
1139 ;; and set the new target position.
1140 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1141 (setq target-pos (marker-position selected-task))
1142 (move-marker selected-task nil))
1143 (save-excursion
1144 (save-restriction
1145 (widen)
1146 (goto-char target-pos)
1147 (org-back-to-heading t)
1148 (or interrupting (move-marker org-clock-interrupted-task nil))
1149 (org-clock-history-push)
1150 (org-clock-set-current)
1151 (cond ((functionp org-clock-in-switch-to-state)
1152 (looking-at org-complex-heading-regexp)
1153 (let ((newstate (funcall org-clock-in-switch-to-state
1154 (match-string 2))))
1155 (if newstate (org-todo newstate))))
1156 ((and org-clock-in-switch-to-state
1157 (not (looking-at (concat org-outline-regexp "[ \t]*"
1158 org-clock-in-switch-to-state
1159 "\\>"))))
1160 (org-todo org-clock-in-switch-to-state)))
1161 (setq org-clock-heading-for-remember
1162 (and (looking-at org-complex-heading-regexp)
1163 (match-end 4)
1164 (org-trim (buffer-substring (match-end 1)
1165 (match-end 4)))))
1166 (setq org-clock-heading
1167 (cond ((and org-clock-heading-function
1168 (functionp org-clock-heading-function))
1169 (funcall org-clock-heading-function))
1170 ((looking-at org-complex-heading-regexp)
1171 (replace-regexp-in-string
1172 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1173 (match-string 4)))
1174 (t "???")))
1175 (setq org-clock-heading (org-propertize org-clock-heading
1176 'face nil))
1177 (org-clock-find-position org-clock-in-resume)
1178 (cond
1179 ((and org-clock-in-resume
1180 (looking-at
1181 (concat "^[ \t]*" org-clock-string
1182 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1183 " *\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1184 (message "Matched %s" (match-string 1))
1185 (setq ts (concat "[" (match-string 1) "]"))
1186 (goto-char (match-end 1))
1187 (setq org-clock-start-time
1188 (apply 'encode-time
1189 (org-parse-time-string (match-string 1))))
1190 (setq org-clock-effort (org-get-effort))
1191 (setq org-clock-total-time (org-clock-sum-current-item
1192 (org-clock-get-sum-start))))
1193 ((eq org-clock-in-resume 'auto-restart)
1194 ;; called from org-clock-load during startup,
1195 ;; do not interrupt, but warn!
1196 (message "Cannot restart clock because task does not contain unfinished clock")
1197 (ding)
1198 (sit-for 2)
1199 (throw 'abort nil))
1201 (insert-before-markers "\n")
1202 (backward-char 1)
1203 (org-indent-line)
1204 (when (and (save-excursion
1205 (end-of-line 0)
1206 (org-in-item-p)))
1207 (beginning-of-line 1)
1208 (org-indent-line-to (- (org-get-indentation) 2)))
1209 (insert org-clock-string " ")
1210 (setq org-clock-effort (org-get-effort))
1211 (setq org-clock-total-time (org-clock-sum-current-item
1212 (org-clock-get-sum-start)))
1213 (setq org-clock-start-time
1214 (or (and org-clock-continuously org-clock-out-time)
1215 (and leftover
1216 (y-or-n-p
1217 (format
1218 "You stopped another clock %d mins ago; start this one from then? "
1219 (/ (- (org-float-time (current-time))
1220 (org-float-time leftover)) 60)))
1221 leftover)
1222 start-time
1223 (current-time)))
1224 (setq ts (org-insert-time-stamp org-clock-start-time
1225 'with-hm 'inactive))))
1226 (move-marker org-clock-marker (point) (buffer-base-buffer))
1227 (move-marker org-clock-hd-marker
1228 (save-excursion (org-back-to-heading t) (point))
1229 (buffer-base-buffer))
1230 (setq org-clock-has-been-used t)
1231 ;; add to mode line
1232 (when (or (eq org-clock-clocked-in-display 'mode-line)
1233 (eq org-clock-clocked-in-display 'both))
1234 (or global-mode-string (setq global-mode-string '("")))
1235 (or (memq 'org-mode-line-string global-mode-string)
1236 (setq global-mode-string
1237 (append global-mode-string '(org-mode-line-string)))))
1238 ;; add to frame title
1239 (when (or (eq org-clock-clocked-in-display 'frame-title)
1240 (eq org-clock-clocked-in-display 'both))
1241 (setq frame-title-format org-clock-frame-title-format))
1242 (org-clock-update-mode-line)
1243 (when org-clock-mode-line-timer
1244 (cancel-timer org-clock-mode-line-timer)
1245 (setq org-clock-mode-line-timer nil))
1246 (when org-clock-clocked-in-display
1247 (setq org-clock-mode-line-timer
1248 (run-with-timer org-clock-update-period
1249 org-clock-update-period
1250 'org-clock-update-mode-line)))
1251 (when org-clock-idle-timer
1252 (cancel-timer org-clock-idle-timer)
1253 (setq org-clock-idle-timer nil))
1254 (setq org-clock-idle-timer
1255 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1256 (message "Clock starts at %s - %s" ts msg-extra)
1257 (run-hooks 'org-clock-in-hook)))))))
1259 ;;;###autoload
1260 (defun org-clock-in-last (&optional arg)
1261 "Clock in the last closed clocked item.
1262 When already clocking in, send an warning.
1263 With a universal prefix argument, select the task you want to
1264 clock in from the last clocked in tasks.
1265 With two universal prefix arguments, start clocking using the
1266 last clock-out time, if any."
1267 (interactive "P")
1268 (if (equal arg '(4)) (org-clock-in (org-clock-select-task))
1269 (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
1270 (or org-clock-out-time (current-time))
1271 (current-time))))
1272 (if (null org-clock-history)
1273 (message "No last clock")
1274 (org-clock-clock-in (list (car org-clock-history)) nil start-time)
1275 (message "Clocking back: %s (in %s)"
1276 org-clock-current-task
1277 (buffer-name (marker-buffer org-clock-marker)))))))
1279 (defun org-clock-mark-default-task ()
1280 "Mark current task as default task."
1281 (interactive)
1282 (save-excursion
1283 (org-back-to-heading t)
1284 (move-marker org-clock-default-task (point))))
1286 (defvar msg-extra)
1287 (defun org-clock-get-sum-start ()
1288 "Return the time from which clock times should be counted.
1289 This is for the currently running clock as it is displayed
1290 in the mode line. This function looks at the properties
1291 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1292 corresponding variable `org-clock-modeline-total' and then
1293 decides which time to use."
1294 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1295 (symbol-name org-clock-modeline-total)))
1296 (lr (org-entry-get nil "LAST_REPEAT")))
1297 (cond
1298 ((equal cmt "current")
1299 (setq msg-extra "showing time in current clock instance")
1300 (current-time))
1301 ((equal cmt "today")
1302 (setq msg-extra "showing today's task time.")
1303 (let* ((dt (decode-time (current-time))))
1304 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1305 (if org-extend-today-until
1306 (setf (nth 2 dt) org-extend-today-until))
1307 (apply 'encode-time dt)))
1308 ((or (equal cmt "all")
1309 (and (or (not cmt) (equal cmt "auto"))
1310 (not lr)))
1311 (setq msg-extra "showing entire task time.")
1312 nil)
1313 ((or (equal cmt "repeat")
1314 (and (or (not cmt) (equal cmt "auto"))
1315 lr))
1316 (setq msg-extra "showing task time since last repeat.")
1317 (if (not lr)
1319 (org-time-string-to-time lr)))
1320 (t nil))))
1322 (defun org-clock-find-position (find-unclosed)
1323 "Find the location where the next clock line should be inserted.
1324 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1325 line and position cursor in that line."
1326 (org-back-to-heading t)
1327 (catch 'exit
1328 (let* ((org-clock-into-drawer (org-clock-into-drawer))
1329 (beg (save-excursion
1330 (beginning-of-line 2)
1331 (or (bolp) (newline))
1332 (point)))
1333 (end (progn (outline-next-heading) (point)))
1334 (re (concat "^[ \t]*" org-clock-string))
1335 (cnt 0)
1336 (drawer (if (stringp org-clock-into-drawer)
1337 org-clock-into-drawer "LOGBOOK"))
1338 first last ind-last)
1339 (goto-char beg)
1340 (when (and find-unclosed
1341 (re-search-forward
1342 (concat "^[ \t]*" org-clock-string
1343 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1344 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1345 end t))
1346 (beginning-of-line 1)
1347 (throw 'exit t))
1348 (when (eobp) (newline) (setq end (max (point) end)))
1349 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1350 ;; we seem to have a CLOCK drawer, so go there.
1351 (beginning-of-line 2)
1352 (or org-log-states-order-reversed
1353 (and (re-search-forward org-property-end-re nil t)
1354 (goto-char (match-beginning 0))))
1355 (throw 'exit t))
1356 ;; Lets count the CLOCK lines
1357 (goto-char beg)
1358 (while (re-search-forward re end t)
1359 (setq first (or first (match-beginning 0))
1360 last (match-beginning 0)
1361 cnt (1+ cnt)))
1362 (when (and (integerp org-clock-into-drawer)
1363 last
1364 (>= (1+ cnt) org-clock-into-drawer))
1365 ;; Wrap current entries into a new drawer
1366 (goto-char last)
1367 (setq ind-last (org-get-indentation))
1368 (beginning-of-line 2)
1369 (if (and (>= (org-get-indentation) ind-last)
1370 (org-at-item-p))
1371 (when (and (>= (org-get-indentation) ind-last)
1372 (org-at-item-p))
1373 (let ((struct (org-list-struct)))
1374 (goto-char (org-list-get-bottom-point struct)))))
1375 (insert ":END:\n")
1376 (beginning-of-line 0)
1377 (org-indent-line-to ind-last)
1378 (goto-char first)
1379 (insert ":" drawer ":\n")
1380 (beginning-of-line 0)
1381 (org-indent-line)
1382 (org-flag-drawer t)
1383 (beginning-of-line 2)
1384 (or org-log-states-order-reversed
1385 (and (re-search-forward org-property-end-re nil t)
1386 (goto-char (match-beginning 0))))
1387 (throw 'exit nil))
1389 (goto-char beg)
1390 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1391 (not (equal (match-string 1) org-clock-string)))
1392 ;; Planning info, skip to after it
1393 (beginning-of-line 2)
1394 (or (bolp) (newline)))
1395 (when (or (eq org-clock-into-drawer t)
1396 (stringp org-clock-into-drawer)
1397 (and (integerp org-clock-into-drawer)
1398 (< org-clock-into-drawer 2)))
1399 (insert ":" drawer ":\n:END:\n")
1400 (beginning-of-line -1)
1401 (org-indent-line)
1402 (org-flag-drawer t)
1403 (beginning-of-line 2)
1404 (org-indent-line)
1405 (beginning-of-line)
1406 (or org-log-states-order-reversed
1407 (and (re-search-forward org-property-end-re nil t)
1408 (goto-char (match-beginning 0))))))))
1410 (defun org-clock-out (&optional fail-quietly at-time)
1411 "Stop the currently running clock.
1412 Throw an error if there is no running clock and FAIL-QUIETLY is nil."
1413 (interactive)
1414 (catch 'exit
1415 (when (not (org-clocking-p))
1416 (setq global-mode-string
1417 (delq 'org-mode-line-string global-mode-string))
1418 (setq frame-title-format org-frame-title-format-backup)
1419 (force-mode-line-update)
1420 (if fail-quietly (throw 'exit t) (error "No active clock")))
1421 (let ((now (current-time)) ts te s h m remove)
1422 (setq org-clock-out-time now)
1423 (save-excursion ; Do not replace this with `with-current-buffer'.
1424 (org-no-warnings (set-buffer (org-clocking-buffer)))
1425 (save-restriction
1426 (widen)
1427 (goto-char org-clock-marker)
1428 (beginning-of-line 1)
1429 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1430 (equal (match-string 1) org-clock-string))
1431 (setq ts (match-string 2))
1432 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1433 (goto-char (match-end 0))
1434 (delete-region (point) (point-at-eol))
1435 (insert "--")
1436 (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
1437 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1438 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1439 h (floor (/ s 3600))
1440 s (- s (* 3600 h))
1441 m (floor (/ s 60))
1442 s (- s (* 60 s)))
1443 (insert " => " (format "%2d:%02d" h m))
1444 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1445 (= (+ h m) 0)))
1446 (beginning-of-line 1)
1447 (delete-region (point) (point-at-eol))
1448 (and (looking-at "\n") (> (point-max) (1+ (point)))
1449 (delete-char 1)))
1450 (move-marker org-clock-marker nil)
1451 (move-marker org-clock-hd-marker nil)
1452 (when org-log-note-clock-out
1453 (org-add-log-setup 'clock-out nil nil nil nil
1454 (concat "# Task: " (org-get-heading t) "\n\n")))
1455 (when org-clock-mode-line-timer
1456 (cancel-timer org-clock-mode-line-timer)
1457 (setq org-clock-mode-line-timer nil))
1458 (when org-clock-idle-timer
1459 (cancel-timer org-clock-idle-timer)
1460 (setq org-clock-idle-timer nil))
1461 (setq global-mode-string
1462 (delq 'org-mode-line-string global-mode-string))
1463 (setq frame-title-format org-frame-title-format-backup)
1464 (when org-clock-out-switch-to-state
1465 (save-excursion
1466 (org-back-to-heading t)
1467 (let ((org-inhibit-logging t)
1468 (org-clock-out-when-done nil))
1469 (cond
1470 ((functionp org-clock-out-switch-to-state)
1471 (looking-at org-complex-heading-regexp)
1472 (let ((newstate (funcall org-clock-out-switch-to-state
1473 (match-string 2))))
1474 (if newstate (org-todo newstate))))
1475 ((and org-clock-out-switch-to-state
1476 (not (looking-at (concat org-outline-regexp "[ \t]*"
1477 org-clock-out-switch-to-state
1478 "\\>"))))
1479 (org-todo org-clock-out-switch-to-state))))))
1480 (force-mode-line-update)
1481 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1482 (if remove " => LINE REMOVED" ""))
1483 (run-hooks 'org-clock-out-hook)
1484 (unless (org-clocking-p)
1485 (org-clock-delete-current)))))))
1487 (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
1489 (defun org-clock-remove-empty-clock-drawer nil
1490 "Remove empty clock drawer in the current subtree."
1491 (let* ((olid (or (org-entry-get (point) "LOG_INTO_DRAWER")
1492 org-log-into-drawer))
1493 (clock-drawer (if (eq t olid) "LOGBOOK" olid))
1494 (end (save-excursion (org-end-of-subtree t t))))
1495 (when clock-drawer
1496 (save-excursion
1497 (org-back-to-heading t)
1498 (while (and (< (point) end)
1499 (search-forward clock-drawer end t))
1500 (goto-char (match-beginning 0))
1501 (org-remove-empty-drawer-at clock-drawer (point))
1502 (forward-line 1))))))
1504 (defun org-at-clock-log-p nil
1505 "Is the cursor on the clock log line?"
1506 (save-excursion
1507 (move-beginning-of-line 1)
1508 (looking-at "^[ \t]*CLOCK:")))
1510 (defun org-clock-timestamps-up nil
1511 "Increase CLOCK timestamps at cursor."
1512 (interactive)
1513 (org-clock-timestamps-change 'up))
1515 (defun org-clock-timestamps-down nil
1516 "Increase CLOCK timestamps at cursor."
1517 (interactive)
1518 (org-clock-timestamps-change 'down))
1520 (defun org-clock-timestamps-change (updown)
1521 "Change CLOCK timestamps synchronously at cursor.
1522 UPDOWN tells whether to change 'up or 'down."
1523 (setq org-ts-what nil)
1524 (when (org-at-timestamp-p t)
1525 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1526 'org-timestamp-down))
1527 ts1 begts1 ts2 begts2 updatets1 tdiff)
1528 (save-excursion
1529 (move-beginning-of-line 1)
1530 (re-search-forward org-ts-regexp3 nil t)
1531 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1532 (when (re-search-forward org-ts-regexp3 nil t)
1533 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1534 ;; Are we on the second timestamp?
1535 (if (<= begts2 (point)) (setq updatets1 t))
1536 (if (not ts2)
1537 ;; fall back on org-timestamp-up if there is only one
1538 (funcall tschange)
1539 ;; setq this so that (boundp 'org-ts-what is non-nil)
1540 (funcall tschange)
1541 (let ((ts (if updatets1 ts2 ts1))
1542 (begts (if updatets1 begts1 begts2)))
1543 (setq tdiff
1544 (subtract-time
1545 (org-time-string-to-time org-last-changed-timestamp)
1546 (org-time-string-to-time ts)))
1547 (save-excursion
1548 (goto-char begts)
1549 (org-timestamp-change
1550 (round (/ (org-float-time tdiff)
1551 (cond ((eq org-ts-what 'minute) 60)
1552 ((eq org-ts-what 'hour) 3600)
1553 ((eq org-ts-what 'day) (* 24 3600))
1554 ((eq org-ts-what 'month) (* 24 3600 31))
1555 ((eq org-ts-what 'year) (* 24 3600 365.2)))))
1556 org-ts-what 'updown)))))))
1558 (defun org-clock-cancel ()
1559 "Cancel the running clock by removing the start timestamp."
1560 (interactive)
1561 (when (not (org-clocking-p))
1562 (setq global-mode-string
1563 (delq 'org-mode-line-string global-mode-string))
1564 (setq frame-title-format org-frame-title-format-backup)
1565 (force-mode-line-update)
1566 (error "No active clock"))
1567 (save-excursion ; Do not replace this with `with-current-buffer'.
1568 (org-no-warnings (set-buffer (org-clocking-buffer)))
1569 (goto-char org-clock-marker)
1570 (if (looking-back (concat "^[ \t]*" org-clock-string ".*"))
1571 (progn (delete-region (1- (point-at-bol)) (point-at-eol))
1572 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1573 (message "Clock gone, cancel the timer anyway")
1574 (sit-for 2)))
1575 (move-marker org-clock-marker nil)
1576 (move-marker org-clock-hd-marker nil)
1577 (setq global-mode-string
1578 (delq 'org-mode-line-string global-mode-string))
1579 (setq frame-title-format org-frame-title-format-backup)
1580 (force-mode-line-update)
1581 (message "Clock canceled")
1582 (run-hooks 'org-clock-cancel-hook))
1584 (defun org-clock-goto (&optional select)
1585 "Go to the currently clocked-in entry, or to the most recently clocked one.
1586 With prefix arg SELECT, offer recently clocked tasks for selection."
1587 (interactive "@P")
1588 (let* ((recent nil)
1589 (m (cond
1590 (select
1591 (or (org-clock-select-task "Select task to go to: ")
1592 (error "No task selected")))
1593 ((org-clocking-p) org-clock-marker)
1594 ((and org-clock-goto-may-find-recent-task
1595 (car org-clock-history)
1596 (marker-buffer (car org-clock-history)))
1597 (setq recent t)
1598 (car org-clock-history))
1599 (t (error "No active or recent clock task")))))
1600 (org-pop-to-buffer-same-window (marker-buffer m))
1601 (if (or (< m (point-min)) (> m (point-max))) (widen))
1602 (goto-char m)
1603 (org-show-entry)
1604 (org-back-to-heading t)
1605 (org-cycle-hide-drawers 'children)
1606 (recenter)
1607 (org-reveal)
1608 (if recent
1609 (message "No running clock, this is the most recently clocked task"))
1610 (run-hooks 'org-clock-goto-hook)))
1612 (defvar org-clock-file-total-minutes nil
1613 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1614 (make-variable-buffer-local 'org-clock-file-total-minutes)
1616 (defun org-clock-sum (&optional tstart tend headline-filter)
1617 "Sum the times for each subtree.
1618 Puts the resulting times in minutes as a text property on each headline.
1619 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1620 zero-arg function that, if specified, is called for each headline in the time
1621 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1622 nil are excluded from the clock summation."
1623 (interactive)
1624 (let* ((bmp (buffer-modified-p))
1625 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1626 org-clock-string
1627 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1628 (lmax 30)
1629 (ltimes (make-vector lmax 0))
1630 (t1 0)
1631 (level 0)
1632 ts te dt
1633 time)
1634 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1635 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1636 (if (consp tstart) (setq tstart (org-float-time tstart)))
1637 (if (consp tend) (setq tend (org-float-time tend)))
1638 (remove-text-properties (point-min) (point-max)
1639 '(:org-clock-minutes t
1640 :org-clock-force-headline-inclusion t))
1641 (save-excursion
1642 (goto-char (point-max))
1643 (while (re-search-backward re nil t)
1644 (cond
1645 ((match-end 2)
1646 ;; Two time stamps
1647 (setq ts (match-string 2)
1648 te (match-string 3)
1649 ts (org-float-time
1650 (apply 'encode-time (org-parse-time-string ts)))
1651 te (org-float-time
1652 (apply 'encode-time (org-parse-time-string te)))
1653 ts (if tstart (max ts tstart) ts)
1654 te (if tend (min te tend) te)
1655 dt (- te ts)
1656 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1657 ((match-end 4)
1658 ;; A naked time
1659 (setq t1 (+ t1 (string-to-number (match-string 5))
1660 (* 60 (string-to-number (match-string 4))))))
1661 (t ;; A headline
1662 ;; Add the currently clocking item time to the total
1663 (when (and org-clock-report-include-clocking-task
1664 (equal (org-clocking-buffer) (current-buffer))
1665 (equal (marker-position org-clock-hd-marker) (point))
1666 tstart
1667 tend
1668 (>= (org-float-time org-clock-start-time) tstart)
1669 (<= (org-float-time org-clock-start-time) tend))
1670 (let ((time (floor (- (org-float-time)
1671 (org-float-time org-clock-start-time)) 60)))
1672 (setq t1 (+ t1 time))))
1673 (let* ((headline-forced
1674 (get-text-property (point)
1675 :org-clock-force-headline-inclusion))
1676 (headline-included
1677 (or (null headline-filter)
1678 (save-excursion
1679 (save-match-data (funcall headline-filter))))))
1680 (setq level (- (match-end 1) (match-beginning 1)))
1681 (when (or (> t1 0) (> (aref ltimes level) 0))
1682 (when (or headline-included headline-forced)
1683 (if headline-included
1684 (loop for l from 0 to level do
1685 (aset ltimes l (+ (aref ltimes l) t1))))
1686 (setq time (aref ltimes level))
1687 (goto-char (match-beginning 0))
1688 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1689 (if headline-filter
1690 (save-excursion
1691 (save-match-data
1692 (while
1693 (> (funcall outline-level) 1)
1694 (outline-up-heading 1 t)
1695 (put-text-property
1696 (point) (point-at-eol)
1697 :org-clock-force-headline-inclusion t))))))
1698 (setq t1 0)
1699 (loop for l from level to (1- lmax) do
1700 (aset ltimes l 0)))))))
1701 (setq org-clock-file-total-minutes (aref ltimes 0)))
1702 (set-buffer-modified-p bmp)))
1704 (defun org-clock-sum-current-item (&optional tstart)
1705 "Return time, clocked on current item in total."
1706 (save-excursion
1707 (save-restriction
1708 (org-narrow-to-subtree)
1709 (org-clock-sum tstart)
1710 org-clock-file-total-minutes)))
1712 (defun org-clock-display (&optional total-only)
1713 "Show subtree times in the entire buffer.
1714 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1715 in the echo area.
1717 Use \\[org-clock-remove-overlays] to remove the subtree times."
1718 (interactive)
1719 (org-clock-remove-overlays)
1720 (let (time h m p)
1721 (org-clock-sum)
1722 (unless total-only
1723 (save-excursion
1724 (goto-char (point-min))
1725 (while (or (and (equal (setq p (point)) (point-min))
1726 (get-text-property p :org-clock-minutes))
1727 (setq p (next-single-property-change
1728 (point) :org-clock-minutes)))
1729 (goto-char p)
1730 (when (setq time (get-text-property p :org-clock-minutes))
1731 (org-clock-put-overlay time (funcall outline-level))))
1732 (setq h (/ org-clock-file-total-minutes 60)
1733 m (- org-clock-file-total-minutes (* 60 h)))
1734 ;; Arrange to remove the overlays upon next change.
1735 (when org-remove-highlights-with-change
1736 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1737 nil 'local))))
1738 (if org-time-clocksum-use-fractional
1739 (message (concat "Total file time: " org-time-clocksum-fractional-format
1740 " (%d hours and %d minutes)")
1741 (/ (+ (* h 60.0) m) 60.0) h m)
1742 (message (concat "Total file time: " org-time-clocksum-format
1743 " (%d hours and %d minutes)") h m h m))))
1745 (defvar org-clock-overlays nil)
1746 (make-variable-buffer-local 'org-clock-overlays)
1748 (defun org-clock-put-overlay (time &optional level)
1749 "Put an overlays on the current line, displaying TIME.
1750 If LEVEL is given, prefix time with a corresponding number of stars.
1751 This creates a new overlay and stores it in `org-clock-overlays', so that it
1752 will be easy to remove."
1753 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1754 (l (if level (org-get-valid-level level 0) 0))
1755 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1756 org-time-clocksum-fractional-format
1757 org-time-clocksum-format) "%s"))
1758 (off 0)
1759 ov tx)
1760 (org-move-to-column c)
1761 (unless (eolp) (skip-chars-backward "^ \t"))
1762 (skip-chars-backward " \t")
1763 (setq ov (make-overlay (1- (point)) (point-at-eol))
1764 tx (concat (buffer-substring (1- (point)) (point))
1765 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1766 (org-add-props (if org-time-clocksum-use-fractional
1767 (format fmt
1768 (make-string l ?*)
1769 (/ (+ (* h 60.0) m) 60.0)
1770 (make-string (- 16 l) ?\ ))
1771 (format fmt
1772 (make-string l ?*) h m
1773 (make-string (- 16 l) ?\ )))
1774 (list 'face 'org-clock-overlay))
1775 ""))
1776 (if (not (featurep 'xemacs))
1777 (overlay-put ov 'display tx)
1778 (overlay-put ov 'invisible t)
1779 (overlay-put ov 'end-glyph (make-glyph tx)))
1780 (push ov org-clock-overlays)))
1782 (defun org-clock-remove-overlays (&optional beg end noremove)
1783 "Remove the occur highlights from the buffer.
1784 BEG and END are ignored. If NOREMOVE is nil, remove this function
1785 from the `before-change-functions' in the current buffer."
1786 (interactive)
1787 (unless org-inhibit-highlight-removal
1788 (mapc 'delete-overlay org-clock-overlays)
1789 (setq org-clock-overlays nil)
1790 (unless noremove
1791 (remove-hook 'before-change-functions
1792 'org-clock-remove-overlays 'local))))
1794 (defvar org-state) ;; dynamically scoped into this function
1795 (defun org-clock-out-if-current ()
1796 "Clock out if the current entry contains the running clock.
1797 This is used to stop the clock after a TODO entry is marked DONE,
1798 and is only done if the variable `org-clock-out-when-done' is not nil."
1799 (when (and (org-clocking-p)
1800 org-clock-out-when-done
1801 (marker-buffer org-clock-marker)
1802 (or (and (eq t org-clock-out-when-done)
1803 (member org-state org-done-keywords))
1804 (and (listp org-clock-out-when-done)
1805 (member org-state org-clock-out-when-done)))
1806 (equal (or (buffer-base-buffer (org-clocking-buffer))
1807 (org-clocking-buffer))
1808 (or (buffer-base-buffer (current-buffer))
1809 (current-buffer)))
1810 (< (point) org-clock-marker)
1811 (> (save-excursion (outline-next-heading) (point))
1812 org-clock-marker))
1813 ;; Clock out, but don't accept a logging message for this.
1814 (let ((org-log-note-clock-out nil)
1815 (org-clock-out-switch-to-state nil))
1816 (org-clock-out))))
1818 (add-hook 'org-after-todo-state-change-hook
1819 'org-clock-out-if-current)
1821 ;;;###autoload
1822 (defun org-get-clocktable (&rest props)
1823 "Get a formatted clocktable with parameters according to PROPS.
1824 The table is created in a temporary buffer, fully formatted and
1825 fontified, and then returned."
1826 ;; Set the defaults
1827 (setq props (plist-put props :name "clocktable"))
1828 (unless (plist-member props :maxlevel)
1829 (setq props (plist-put props :maxlevel 2)))
1830 (unless (plist-member props :scope)
1831 (setq props (plist-put props :scope 'agenda)))
1832 (with-temp-buffer
1833 (org-mode)
1834 (org-create-dblock props)
1835 (org-update-dblock)
1836 (font-lock-fontify-buffer)
1837 (forward-line 2)
1838 (buffer-substring (point) (progn
1839 (re-search-forward "^[ \t]*#\\+END" nil t)
1840 (point-at-bol)))))
1842 (defun org-clock-report (&optional arg)
1843 "Create a table containing a report about clocked time.
1844 If the cursor is inside an existing clocktable block, then the table
1845 will be updated. If not, a new clocktable will be inserted. The scope
1846 of the new clock will be subtree when called from within a subtree, and
1847 file elsewhere.
1849 When called with a prefix argument, move to the first clock table in the
1850 buffer and update it."
1851 (interactive "P")
1852 (org-clock-remove-overlays)
1853 (when arg
1854 (org-find-dblock "clocktable")
1855 (org-show-entry))
1856 (if (org-in-clocktable-p)
1857 (goto-char (org-in-clocktable-p))
1858 (let ((props (if (ignore-errors
1859 (save-excursion (org-back-to-heading)))
1860 (list :name "clocktable" :scope 'subtree)
1861 (list :name "clocktable"))))
1862 (org-create-dblock
1863 (org-combine-plists org-clock-clocktable-default-properties props))))
1864 (org-update-dblock))
1866 (defun org-day-of-week (day month year)
1867 "Returns the day of the week as an integer."
1868 (nth 6
1869 (decode-time
1870 (date-to-time
1871 (format "%d-%02d-%02dT00:00:00" year month day)))))
1873 (defun org-quarter-to-date (quarter year)
1874 "Get the date (week day year) of the first day of a given quarter."
1875 (let (startday)
1876 (cond
1877 ((= quarter 1)
1878 (setq startday (org-day-of-week 1 1 year))
1879 (cond
1880 ((= startday 0)
1881 (list 52 7 (- year 1)))
1882 ((= startday 6)
1883 (list 52 6 (- year 1)))
1884 ((<= startday 4)
1885 (list 1 startday year))
1886 ((> startday 4)
1887 (list 53 startday (- year 1)))
1890 ((= quarter 2)
1891 (setq startday (org-day-of-week 1 4 year))
1892 (cond
1893 ((= startday 0)
1894 (list 13 startday year))
1895 ((< startday 4)
1896 (list 14 startday year))
1897 ((>= startday 4)
1898 (list 13 startday year))
1901 ((= quarter 3)
1902 (setq startday (org-day-of-week 1 7 year))
1903 (cond
1904 ((= startday 0)
1905 (list 26 startday year))
1906 ((< startday 4)
1907 (list 27 startday year))
1908 ((>= startday 4)
1909 (list 26 startday year))
1912 ((= quarter 4)
1913 (setq startday (org-day-of-week 1 10 year))
1914 (cond
1915 ((= startday 0)
1916 (list 39 startday year))
1917 ((<= startday 4)
1918 (list 40 startday year))
1919 ((> startday 4)
1920 (list 39 startday year)))))))
1922 (defun org-clock-special-range (key &optional time as-strings)
1923 "Return two times bordering a special time range.
1924 Key is a symbol specifying the range and can be one of `today', `yesterday',
1925 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1926 A week starts Monday 0:00 and ends Sunday 24:00.
1927 The range is determined relative to TIME. TIME defaults to the current time.
1928 The return value is a cons cell with two internal times like the ones
1929 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1930 the returned times will be formatted strings."
1931 (if (integerp key) (setq key (intern (number-to-string key))))
1932 (let* ((tm (decode-time (or time (current-time))))
1933 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1934 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1935 (dow (nth 6 tm))
1936 (skey (symbol-name key))
1937 (shift 0)
1938 (q (cond ((>= (nth 4 tm) 10) 4)
1939 ((>= (nth 4 tm) 7) 3)
1940 ((>= (nth 4 tm) 4) 2)
1941 ((>= (nth 4 tm) 1) 1)))
1942 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1943 interval tmp shiftedy shiftedm shiftedq)
1944 (cond
1945 ((string-match "^[0-9]+$" skey)
1946 (setq y (string-to-number skey) m 1 d 1 key 'year))
1947 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1948 (setq y (string-to-number (match-string 1 skey))
1949 month (string-to-number (match-string 2 skey))
1950 d 1 key 'month))
1951 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1952 (require 'cal-iso)
1953 (setq y (string-to-number (match-string 1 skey))
1954 w (string-to-number (match-string 2 skey)))
1955 (setq date (calendar-gregorian-from-absolute
1956 (calendar-absolute-from-iso (list w 1 y))))
1957 (setq d (nth 1 date) month (car date) y (nth 2 date)
1958 dow 1
1959 key 'week))
1960 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
1961 (require 'cal-iso)
1962 (setq y (string-to-number (match-string 1 skey)))
1963 (setq q (string-to-number (match-string 2 skey)))
1964 (setq date (calendar-gregorian-from-absolute
1965 (calendar-absolute-from-iso (org-quarter-to-date q y))))
1966 (setq d (nth 1 date) month (car date) y (nth 2 date)
1967 dow 1
1968 key 'quarter))
1969 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1970 (setq y (string-to-number (match-string 1 skey))
1971 month (string-to-number (match-string 2 skey))
1972 d (string-to-number (match-string 3 skey))
1973 key 'day))
1974 ((string-match "\\([-+][0-9]+\\)$" skey)
1975 (setq shift (string-to-number (match-string 1 skey))
1976 key (intern (substring skey 0 (match-beginning 1))))
1977 (if(and (memq key '(quarter thisq)) (> shift 0))
1978 (error "Looking forward with quarters isn't implemented.")
1979 ())))
1981 (when (= shift 0)
1982 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1983 ((eq key 'lastweek) (setq key 'week shift -1))
1984 ((eq key 'lastmonth) (setq key 'month shift -1))
1985 ((eq key 'lastyear) (setq key 'year shift -1))
1986 ((eq key 'lastq) (setq key 'quarter shift -1))))
1987 (cond
1988 ((memq key '(day today))
1989 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1990 ((memq key '(week thisweek))
1991 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1992 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1993 ((memq key '(month thismonth))
1994 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1995 ((memq key '(quarter thisq))
1996 ; compute if this shift remains in this year
1997 ; if not, compute how many years and quarters we have to shift (via floor*)
1998 ; and compute the shifted years, months and quarters
1999 (cond
2000 ((< (+ (- q 1) shift) 0) ; shift not in this year
2001 (setq interval (* -1 (+ (- q 1) shift)))
2002 ; set tmp to ((years to shift) (quarters to shift))
2003 (setq tmp (org-floor* interval 4))
2004 ; due to the use of floor, 0 quarters actually means 4
2005 (if (= 0 (nth 1 tmp))
2006 (setq shiftedy (- y (nth 0 tmp))
2007 shiftedm 1
2008 shiftedq 1)
2009 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
2010 shiftedm (- 13 (* 3 (nth 1 tmp)))
2011 shiftedq (- 5 (nth 1 tmp))))
2012 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
2013 ((> (+ q shift) 0) ; shift is within this year
2014 (setq shiftedq (+ q shift))
2015 (setq shiftedy y)
2016 (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))))
2017 ((memq key '(year thisyear))
2018 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
2019 (t (error "No such time block %s" key)))
2020 (setq ts (encode-time s m h d month y)
2021 te (encode-time (or s1 s) (or m1 m) (or h1 h)
2022 (or d1 d) (or month1 month) (or y1 y)))
2023 (setq fm (cdr org-time-stamp-formats))
2024 (cond
2025 ((memq key '(day today))
2026 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
2027 ((memq key '(week thisweek))
2028 (setq txt (format-time-string "week %G-W%V" ts)))
2029 ((memq key '(month thismonth))
2030 (setq txt (format-time-string "%B %Y" ts)))
2031 ((memq key '(year thisyear))
2032 (setq txt (format-time-string "the year %Y" ts)))
2033 ((memq key '(quarter thisq))
2034 (setq txt (concat 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
2036 (if as-strings
2037 (list (format-time-string fm ts) (format-time-string fm te) txt)
2038 (list ts te txt))))
2040 (defun org-count-quarter (n)
2041 (cond
2042 ((= n 1) "1st")
2043 ((= n 2) "2nd")
2044 ((= n 3) "3rd")
2045 ((= n 4) "4th")))
2047 (defun org-clocktable-shift (dir n)
2048 "Try to shift the :block date of the clocktable at point.
2049 Point must be in the #+BEGIN: line of a clocktable, or this function
2050 will throw an error.
2051 DIR is a direction, a symbol `left', `right', `up', or `down'.
2052 Both `left' and `down' shift the block toward the past, `up' and `right'
2053 push it toward the future.
2054 N is the number of shift steps to take. The size of the step depends on
2055 the currently selected interval size."
2056 (setq n (prefix-numeric-value n))
2057 (and (memq dir '(left down)) (setq n (- n)))
2058 (save-excursion
2059 (goto-char (point-at-bol))
2060 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2061 (error "Line needs a :block definition before this command works")
2062 (let* ((b (match-beginning 1)) (e (match-end 1))
2063 (s (match-string 1))
2064 block shift ins y mw d date wp m)
2065 (cond
2066 ((equal s "yesterday") (setq s "today-1"))
2067 ((equal s "lastweek") (setq s "thisweek-1"))
2068 ((equal s "lastmonth") (setq s "thismonth-1"))
2069 ((equal s "lastyear") (setq s "thisyear-1"))
2070 ((equal s "lastq") (setq s "thisq-1")))
2072 (cond
2073 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
2074 (setq block (match-string 1 s)
2075 shift (if (match-end 2)
2076 (string-to-number (match-string 2 s))
2078 (setq shift (+ shift n))
2079 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
2080 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
2081 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2082 (setq y (string-to-number (match-string 1 s))
2083 wp (and (match-end 3) (match-string 3 s))
2084 mw (and (match-end 4) (string-to-number (match-string 4 s)))
2085 d (and (match-end 6) (string-to-number (match-string 6 s))))
2086 (cond
2087 (d (setq ins (format-time-string
2088 "%Y-%m-%d"
2089 (encode-time 0 0 0 (+ d n) m y))))
2090 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2091 (require 'cal-iso)
2092 (setq date (calendar-gregorian-from-absolute
2093 (calendar-absolute-from-iso (list (+ mw n) 1 y))))
2094 (setq ins (format-time-string
2095 "%G-W%V"
2096 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2097 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2098 (require 'cal-iso)
2099 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2100 (if (> (+ mw n) 4)
2101 (setq mw 0
2102 y (+ 1 y))
2104 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2105 (if (= (+ mw n) 0)
2106 (setq mw 5
2107 y (- y 1))
2109 (setq date (calendar-gregorian-from-absolute
2110 (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
2111 (setq ins (format-time-string
2112 (concat 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
2113 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2115 (setq ins (format-time-string
2116 "%Y-%m"
2117 (encode-time 0 0 0 1 (+ mw n) y))))
2119 (setq ins (number-to-string (+ y n))))))
2120 (t (error "Cannot shift clocktable block")))
2121 (when ins
2122 (goto-char b)
2123 (insert ins)
2124 (delete-region (point) (+ (point) (- e b)))
2125 (beginning-of-line 1)
2126 (org-update-dblock)
2127 t)))))
2129 (defun org-dblock-write:clocktable (params)
2130 "Write the standard clocktable."
2131 (setq params (org-combine-plists org-clocktable-defaults params))
2132 (catch 'exit
2133 (let* ((scope (plist-get params :scope))
2134 (block (plist-get params :block))
2135 (ts (plist-get params :tstart))
2136 (te (plist-get params :tend))
2137 (link (plist-get params :link))
2138 (maxlevel (or (plist-get params :maxlevel) 3))
2139 (step (plist-get params :step))
2140 (timestamp (plist-get params :timestamp))
2141 (formatter (or (plist-get params :formatter)
2142 org-clock-clocktable-formatter
2143 'org-clocktable-write-default))
2144 cc range-text ipos pos one-file-with-archives
2145 scope-is-list tbls level)
2146 ;; Check if we need to do steps
2147 (when block
2148 ;; Get the range text for the header
2149 (setq cc (org-clock-special-range block nil t)
2150 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2151 (when step
2152 ;; Write many tables, in steps
2153 (unless (or block (and ts te))
2154 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2155 (org-clocktable-steps params)
2156 (throw 'exit nil))
2158 (setq ipos (point)) ; remember the insertion position
2160 ;; Get the right scope
2161 (setq pos (point))
2162 (cond
2163 ((and scope (listp scope) (symbolp (car scope)))
2164 (setq scope (eval scope)))
2165 ((eq scope 'agenda)
2166 (setq scope (org-agenda-files t)))
2167 ((eq scope 'agenda-with-archives)
2168 (setq scope (org-agenda-files t))
2169 (setq scope (org-add-archive-files scope)))
2170 ((eq scope 'file-with-archives)
2171 (setq scope (org-add-archive-files (list (buffer-file-name)))
2172 one-file-with-archives t)))
2173 (setq scope-is-list (and scope (listp scope)))
2174 (if scope-is-list
2175 ;; we collect from several files
2176 (let* ((files scope)
2177 file)
2178 (org-prepare-agenda-buffers files)
2179 (while (setq file (pop files))
2180 (with-current-buffer (find-buffer-visiting file)
2181 (save-excursion
2182 (save-restriction
2183 (push (org-clock-get-table-data file params) tbls))))))
2184 ;; Just from the current file
2185 (save-restriction
2186 ;; get the right range into the restriction
2187 (org-prepare-agenda-buffers (list (buffer-file-name)))
2188 (cond
2189 ((not scope)) ; use the restriction as it is now
2190 ((eq scope 'file) (widen))
2191 ((eq scope 'subtree) (org-narrow-to-subtree))
2192 ((eq scope 'tree)
2193 (while (org-up-heading-safe))
2194 (org-narrow-to-subtree))
2195 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
2196 (symbol-name scope)))
2197 (setq level (string-to-number (match-string 1 (symbol-name scope))))
2198 (catch 'exit
2199 (while (org-up-heading-safe)
2200 (looking-at org-outline-regexp)
2201 (if (<= (org-reduced-level (funcall outline-level)) level)
2202 (throw 'exit nil))))
2203 (org-narrow-to-subtree)))
2204 ;; do the table, with no file name.
2205 (push (org-clock-get-table-data nil params) tbls)))
2207 ;; OK, at this point we tbls as a list of tables, one per file
2208 (setq tbls (nreverse tbls))
2210 (setq params (plist-put params :multifile scope-is-list))
2211 (setq params (plist-put params :one-file-with-archives
2212 one-file-with-archives))
2214 (funcall formatter ipos tbls params))))
2216 (defun org-clocktable-write-default (ipos tables params)
2217 "Write out a clock table at position IPOS in the current buffer.
2218 TABLES is a list of tables with clocking data as produced by
2219 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2220 from the dynamic block definition."
2221 ;; This function looks quite complicated, mainly because there are a
2222 ;; lot of options which can add or remove columns. I have massively
2223 ;; commented this function, the I hope it is understandable. If
2224 ;; someone wants to write their own special formatter, this maybe
2225 ;; much easier because there can be a fixed format with a
2226 ;; well-defined number of columns...
2227 (let* ((hlchars '((1 . "*") (2 . "/")))
2228 (lwords (assoc (or (plist-get params :lang)
2229 org-export-default-language)
2230 org-clock-clocktable-language-setup))
2231 (multifile (plist-get params :multifile))
2232 (block (plist-get params :block))
2233 (ts (plist-get params :tstart))
2234 (te (plist-get params :tend))
2235 (header (plist-get params :header))
2236 (narrow (plist-get params :narrow))
2237 (link (plist-get params :link))
2238 (maxlevel (or (plist-get params :maxlevel) 3))
2239 (emph (plist-get params :emphasize))
2240 (level-p (plist-get params :level))
2241 (timestamp (plist-get params :timestamp))
2242 (properties (plist-get params :properties))
2243 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2244 (rm-file-column (plist-get params :one-file-with-archives))
2245 (indent (plist-get params :indent))
2246 (case-fold-search t)
2247 range-text total-time tbl level hlc formula pcol
2248 file-time entries entry headline
2249 recalc content narrow-cut-p tcol)
2251 ;; Implement abbreviations
2252 (when (plist-get params :compact)
2253 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2255 ;; Some consistency test for parameters
2256 (unless (integerp ntcol)
2257 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2259 (when (and narrow (integerp narrow) link)
2260 ;; We cannot have both integer narrow and link
2261 (message
2262 "Using hard narrowing in clocktable to allow for links")
2263 (setq narrow (intern (format "%d!" narrow))))
2265 (when narrow
2266 (cond
2267 ((integerp narrow))
2268 ((and (symbolp narrow)
2269 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2270 (setq narrow-cut-p t
2271 narrow (string-to-number (substring (symbol-name narrow)
2272 0 -1))))
2274 (error "Invalid value %s of :narrow property in clock table"
2275 narrow))))
2277 (when block
2278 ;; Get the range text for the header
2279 (setq range-text (nth 2 (org-clock-special-range block nil t))))
2281 ;; Compute the total time
2282 (setq total-time (apply '+ (mapcar 'cadr tables)))
2284 ;; Now we need to output this tsuff
2285 (goto-char ipos)
2287 ;; Insert the text *before* the actual table
2288 (insert-before-markers
2289 (or header
2290 ;; Format the standard header
2291 (concat
2292 (nth 9 lwords) " ["
2293 (substring
2294 (format-time-string (cdr org-time-stamp-formats))
2295 1 -1)
2297 (if block (concat ", for " range-text ".") "")
2298 "\n\n")))
2300 ;; Insert the narrowing line
2301 (when (and narrow (integerp narrow) (not narrow-cut-p))
2302 (insert-before-markers
2303 "|" ; table line starter
2304 (if multifile "|" "") ; file column, maybe
2305 (if level-p "|" "") ; level column, maybe
2306 (if timestamp "|" "") ; timestamp column, maybe
2307 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2308 (format "<%d>| |\n" narrow))) ; headline and time columns
2310 ;; Insert the table header line
2311 (insert-before-markers
2312 "|" ; table line starter
2313 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2314 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2315 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2316 (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
2317 (concat (nth 4 lwords) "|"
2318 (nth 5 lwords) "|\n")) ; headline and time columns
2320 ;; Insert the total time in the table
2321 (insert-before-markers
2322 "|-\n" ; a hline
2323 "|" ; table line starter
2324 (if multifile (concat "| " (nth 6 lwords) " ") "")
2325 ; file column, maybe
2326 (if level-p "|" "") ; level column, maybe
2327 (if timestamp "|" "") ; timestamp column, maybe
2328 (if properties (make-string (length properties) ?|) "") ; properties columns, maybe
2329 (concat (format org-clock-total-time-cell-format (nth 7 lwords)) "| ") ; instead of a headline
2330 (format org-clock-total-time-cell-format
2331 (org-minutes-to-hh:mm-string (or total-time 0))) ; the time
2332 "|\n") ; close line
2334 ;; Now iterate over the tables and insert the data
2335 ;; but only if any time has been collected
2336 (when (and total-time (> total-time 0))
2338 (while (setq tbl (pop tables))
2339 ;; now tbl is the table resulting from one file.
2340 (setq file-time (nth 1 tbl))
2341 (when (or (and file-time (> file-time 0))
2342 (not (plist-get params :fileskip0)))
2343 (insert-before-markers "|-\n") ; a hline because a new file starts
2344 ;; First the file time, if we have multiple files
2345 (when multifile
2346 ;; Summarize the time collected from this file
2347 (insert-before-markers
2348 (format (concat "| %s %s | %s%s"
2349 (format org-clock-file-time-cell-format (nth 8 lwords))
2350 " | *%s*|\n")
2351 (file-name-nondirectory (car tbl))
2352 (if level-p "| " "") ; level column, maybe
2353 (if timestamp "| " "") ; timestamp column, maybe
2354 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2355 (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
2357 ;; Get the list of node entries and iterate over it
2358 (setq entries (nth 2 tbl))
2359 (while (setq entry (pop entries))
2360 (setq level (car entry)
2361 headline (nth 1 entry)
2362 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2363 (when narrow-cut-p
2364 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2365 "\\'")
2366 headline)
2367 (match-end 3))
2368 (setq headline
2369 (format "[[%s][%s]]"
2370 (match-string 1 headline)
2371 (org-shorten-string (match-string 3 headline)
2372 narrow)))
2373 (setq headline (org-shorten-string headline narrow))))
2374 (insert-before-markers
2375 "|" ; start the table line
2376 (if multifile "|" "") ; free space for file name column?
2377 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2378 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2379 (if properties
2380 (concat
2381 (mapconcat
2382 (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
2383 properties "|") "|") "") ;properties columns, maybe
2384 (if indent (org-clocktable-indent-string level) "") ; indentation
2385 hlc headline hlc "|" ; headline
2386 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2387 ; empty fields for higher levels
2388 hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
2389 "|\n" ; close line
2390 )))))
2391 ;; When exporting subtrees or regions the region might be
2392 ;; activated, so let's disable ̀delete-active-region'
2393 (let ((delete-active-region nil)) (backward-delete-char 1))
2394 (if (setq formula (plist-get params :formula))
2395 (cond
2396 ((eq formula '%)
2397 ;; compute the column where the % numbers need to go
2398 (setq pcol (+ 2
2399 (if multifile 1 0)
2400 (if level-p 1 0)
2401 (if timestamp 1 0)
2402 (min maxlevel (or ntcol 100))))
2403 ;; compute the column where the total time is
2404 (setq tcol (+ 2
2405 (if multifile 1 0)
2406 (if level-p 1 0)
2407 (if timestamp 1 0)))
2408 (insert
2409 (format
2410 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2411 pcol ; the column where the % numbers should go
2412 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2413 tcol ; column of the total time
2414 tcol (1- pcol) ; range of columns where times can be found
2416 (setq recalc t))
2417 ((stringp formula)
2418 (insert "\n#+TBLFM: " formula)
2419 (setq recalc t))
2420 (t (error "invalid formula in clocktable")))
2421 ;; Should we rescue an old formula?
2422 (when (stringp (setq content (plist-get params :content)))
2423 (when (string-match "^\\([ \t]*#\\+tblfm:.*\\)" content)
2424 (setq recalc t)
2425 (insert "\n" (match-string 1 (plist-get params :content)))
2426 (beginning-of-line 0))))
2427 ;; Back to beginning, align the table, recalculate if necessary
2428 (goto-char ipos)
2429 (skip-chars-forward "^|")
2430 (org-table-align)
2431 (when org-hide-emphasis-markers
2432 ;; we need to align a second time
2433 (org-table-align))
2434 (when recalc
2435 (if (eq formula '%)
2436 (save-excursion
2437 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2438 (org-table-goto-column pcol nil 'force)
2439 (insert "%")))
2440 (org-table-recalculate 'all))
2441 (when rm-file-column
2442 ;; The file column is actually not wanted
2443 (forward-char 1)
2444 (org-table-delete-column))
2445 total-time))
2447 (defun org-clocktable-indent-string (level)
2448 (if (= level 1)
2450 (let ((str "\\__"))
2451 (while (> level 2)
2452 (setq level (1- level)
2453 str (concat str "___")))
2454 (concat str " "))))
2456 (defun org-clocktable-steps (params)
2457 "Step through the range to make a number of clock tables."
2458 (let* ((p1 (copy-sequence params))
2459 (ts (plist-get p1 :tstart))
2460 (te (plist-get p1 :tend))
2461 (step0 (plist-get p1 :step))
2462 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2463 (stepskip0 (plist-get p1 :stepskip0))
2464 (block (plist-get p1 :block))
2465 cc range-text step-time)
2466 (when block
2467 (setq cc (org-clock-special-range block nil t)
2468 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2469 (cond
2470 ((numberp ts)
2471 ;; If ts is a number, it's an absolute day number from org-agenda.
2472 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2473 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2475 (setq ts (org-float-time
2476 (apply 'encode-time (org-parse-time-string ts))))))
2477 (cond
2478 ((numberp te)
2479 ;; Likewise for te.
2480 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2481 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2483 (setq te (org-float-time
2484 (apply 'encode-time (org-parse-time-string te))))))
2485 (setq p1 (plist-put p1 :header ""))
2486 (setq p1 (plist-put p1 :step nil))
2487 (setq p1 (plist-put p1 :block nil))
2488 (while (< ts te)
2489 (or (bolp) (insert "\n"))
2490 (setq p1 (plist-put p1 :tstart (format-time-string
2491 (org-time-stamp-format nil t)
2492 (seconds-to-time ts))))
2493 (setq p1 (plist-put p1 :tend (format-time-string
2494 (org-time-stamp-format nil t)
2495 (seconds-to-time (setq ts (+ ts step))))))
2496 (insert "\n" (if (eq step0 'day) "Daily report: "
2497 "Weekly report starting on: ")
2498 (plist-get p1 :tstart) "\n")
2499 (setq step-time (org-dblock-write:clocktable p1))
2500 (re-search-forward "^[ \t]*#\\+END:")
2501 (when (and (equal step-time 0) stepskip0)
2502 ;; Remove the empty table
2503 (delete-region (point-at-bol)
2504 (save-excursion
2505 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2506 nil t)
2507 (point))))
2508 (end-of-line 0))))
2510 (defun org-clock-get-table-data (file params)
2511 "Get the clocktable data for file FILE, with parameters PARAMS.
2512 FILE is only for identification - this function assumes that
2513 the correct buffer is current, and that the wanted restriction is
2514 in place.
2515 The return value will be a list with the file name and the total
2516 file time (in minutes) as 1st and 2nd elements. The third element
2517 of this list will be a list of headline entries. Each entry has the
2518 following structure:
2520 (LEVEL HEADLINE TIMESTAMP TIME)
2522 LEVEL: The level of the headline, as an integer. This will be
2523 the reduced leve, so 1,2,3,... even if only odd levels
2524 are being used.
2525 HEADLINE: The text of the headline. Depending on PARAMS, this may
2526 already be formatted like a link.
2527 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2528 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2529 in this sequence.
2530 TIME: The sum of all time spend in this tree, in minutes. This time
2531 will of cause be restricted to the time block and tags match
2532 specified in PARAMS."
2533 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2534 (timestamp (plist-get params :timestamp))
2535 (ts (plist-get params :tstart))
2536 (te (plist-get params :tend))
2537 (block (plist-get params :block))
2538 (link (plist-get params :link))
2539 (tags (plist-get params :tags))
2540 (properties (plist-get params :properties))
2541 (inherit-property-p (plist-get params :inherit-props))
2542 todo-only
2543 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2544 cc range-text st p time level hdl props tsp tbl)
2546 (setq org-clock-file-total-minutes nil)
2547 (when block
2548 (setq cc (org-clock-special-range block nil t)
2549 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2550 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2551 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2552 (when (and ts (listp ts))
2553 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2554 (when (and te (listp te))
2555 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2556 ;; Now the times are strings we can parse.
2557 (if ts (setq ts (org-float-time
2558 (apply 'encode-time (org-parse-time-string ts)))))
2559 (if te (setq te (org-float-time
2560 (apply 'encode-time (org-parse-time-string te)))))
2561 (save-excursion
2562 (org-clock-sum ts te
2563 (unless (null matcher)
2564 (lambda ()
2565 (let* ((tags-list (org-get-tags-at))
2566 (org-scanner-tags tags-list)
2567 (org-trust-scanner-tags t))
2568 (eval matcher)))))
2569 (goto-char (point-min))
2570 (setq st t)
2571 (while (or (and (bobp) (prog1 st (setq st nil))
2572 (get-text-property (point) :org-clock-minutes)
2573 (setq p (point-min)))
2574 (setq p (next-single-property-change
2575 (point) :org-clock-minutes)))
2576 (goto-char p)
2577 (when (setq time (get-text-property p :org-clock-minutes))
2578 (save-excursion
2579 (beginning-of-line 1)
2580 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2581 (setq level (org-reduced-level
2582 (- (match-end 1) (match-beginning 1))))
2583 (<= level maxlevel))
2584 (setq hdl (if (not link)
2585 (match-string 2)
2586 (org-make-link-string
2587 (format "file:%s::%s"
2588 (buffer-file-name)
2589 (save-match-data
2590 (org-make-org-heading-search-string
2591 (match-string 2))))
2592 (match-string 2)))
2593 tsp (when timestamp
2594 (setq props (org-entry-properties (point)))
2595 (or (cdr (assoc "SCHEDULED" props))
2596 (cdr (assoc "DEADLINE" props))
2597 (cdr (assoc "TIMESTAMP" props))
2598 (cdr (assoc "TIMESTAMP_IA" props))))
2599 props (when properties
2600 (remove nil
2601 (mapcar
2602 (lambda (p)
2603 (when (org-entry-get (point) p inherit-property-p)
2604 (cons p (org-entry-get (point) p inherit-property-p))))
2605 properties))))
2606 (when (> time 0) (push (list level hdl tsp time props) tbl))))))
2607 (setq tbl (nreverse tbl))
2608 (list file org-clock-file-total-minutes tbl))))
2610 (defun org-clock-time% (total &rest strings)
2611 "Compute a time fraction in percent.
2612 TOTAL s a time string like 10:21 specifying the total times.
2613 STRINGS is a list of strings that should be checked for a time.
2614 The first string that does have a time will be used.
2615 This function is made for clock tables."
2616 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2617 tot s)
2618 (save-match-data
2619 (catch 'exit
2620 (if (not (string-match re total))
2621 (throw 'exit 0.)
2622 (setq tot (+ (string-to-number (match-string 2 total))
2623 (* 60 (string-to-number (match-string 1 total)))))
2624 (if (= tot 0.) (throw 'exit 0.)))
2625 (while (setq s (pop strings))
2626 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2627 (throw 'exit
2628 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2629 (* 60 (string-to-number
2630 (match-string 1 s)))))
2631 tot))))
2632 0))))
2634 ;; Saving and loading the clock
2636 (defvar org-clock-loaded nil
2637 "Was the clock file loaded?")
2639 (defun org-clock-save ()
2640 "Persist various clock-related data to disk.
2641 The details of what will be saved are regulated by the variable
2642 `org-clock-persist'."
2643 (when (and org-clock-persist
2644 (or org-clock-loaded
2645 org-clock-has-been-used
2646 (not (file-exists-p org-clock-persist-file))))
2647 (let (b)
2648 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2649 (progn
2650 (delete-region (point-min) (point-max))
2651 ;;Store clock
2652 (insert (format ";; org-persist.el - %s at %s\n"
2653 system-name (format-time-string
2654 (cdr org-time-stamp-formats))))
2655 (if (and (memq org-clock-persist '(t clock))
2656 (setq b (org-clocking-buffer))
2657 (setq b (or (buffer-base-buffer b) b))
2658 (buffer-live-p b)
2659 (buffer-file-name b)
2660 (or (not org-clock-persist-query-save)
2661 (y-or-n-p (concat "Save current clock ("
2662 (substring-no-properties
2663 org-clock-heading)
2664 ") "))))
2665 (insert "(setq resume-clock '(\""
2666 (buffer-file-name (org-clocking-buffer))
2667 "\" . " (int-to-string (marker-position org-clock-marker))
2668 "))\n"))
2669 ;; Store clocked task history. Tasks are stored reversed to make
2670 ;; reading simpler
2671 (when (and (memq org-clock-persist '(t history))
2672 org-clock-history)
2673 (insert
2674 "(setq stored-clock-history '("
2675 (mapconcat
2676 (lambda (m)
2677 (when (and (setq b (marker-buffer m))
2678 (setq b (or (buffer-base-buffer b) b))
2679 (buffer-live-p b)
2680 (buffer-file-name b))
2681 (concat "(\"" (buffer-file-name b)
2682 "\" . " (int-to-string (marker-position m))
2683 ")")))
2684 (reverse org-clock-history) " ") "))\n"))
2685 (save-buffer)
2686 (kill-buffer (current-buffer)))))))
2688 (defun org-clock-load ()
2689 "Load clock-related data from disk, maybe resuming a stored clock."
2690 (when (and org-clock-persist (not org-clock-loaded))
2691 (let ((filename (expand-file-name org-clock-persist-file))
2692 (org-clock-in-resume 'auto-restart)
2693 resume-clock stored-clock-history)
2694 (if (not (file-readable-p filename))
2695 (message "Not restoring clock data; %s not found"
2696 org-clock-persist-file)
2697 (message "%s" "Restoring clock data")
2698 (setq org-clock-loaded t)
2699 (load-file filename)
2700 ;; load history
2701 (when stored-clock-history
2702 (save-window-excursion
2703 (mapc (lambda (task)
2704 (if (file-exists-p (car task))
2705 (org-clock-history-push (cdr task)
2706 (find-file (car task)))))
2707 stored-clock-history)))
2708 ;; resume clock
2709 (when (and resume-clock org-clock-persist
2710 (file-exists-p (car resume-clock))
2711 (or (not org-clock-persist-query-resume)
2712 (y-or-n-p
2713 (concat
2714 "Resume clock ("
2715 (with-current-buffer (find-file (car resume-clock))
2716 (save-excursion
2717 (goto-char (cdr resume-clock))
2718 (org-back-to-heading t)
2719 (and (looking-at org-complex-heading-regexp)
2720 (match-string 4))))
2721 ") "))))
2722 (when (file-exists-p (car resume-clock))
2723 (with-current-buffer (find-file (car resume-clock))
2724 (goto-char (cdr resume-clock))
2725 (let ((org-clock-auto-clock-resolution nil))
2726 (org-clock-in)
2727 (if (outline-invisible-p)
2728 (org-show-context))))))))))
2730 ;;;###autoload
2731 (defun org-clock-persistence-insinuate ()
2732 "Set up hooks for clock persistence."
2733 (add-hook 'org-mode-hook 'org-clock-load)
2734 (add-hook 'kill-emacs-hook 'org-clock-save))
2736 ;; Suggested bindings
2737 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2739 (provide 'org-clock)
2741 ;;; org-clock.el ends here