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