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