doc: more explicit about the mechanism through which interactive evaluation of code...
[org-mode/org-jambu.git] / lisp / org-clock.el
blobabab70c2533be2ffa878255c08056aa87009b1fd
1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
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 (defvar org-clock-current-task nil
980 "Task currently clocked in.")
981 (defun org-clock-set-current ()
982 "Set `org-clock-current-task' to the task currently clocked in."
983 (setq org-clock-current-task (nth 4 (org-heading-components))))
985 (defun org-clock-delete-current ()
986 "Reset `org-clock-current-task' to nil."
987 (setq org-clock-current-task nil))
989 (defun org-clock-in (&optional select start-time)
990 "Start the clock on the current item.
991 If necessary, clock-out of the currently active clock.
992 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
993 recently clocked tasks to
994 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
995 clock into the current task and mark
996 is as the default task, a special task that will always be offered in
997 the clocking selection, associated with the letter `d'."
998 (interactive "P")
999 (setq org-clock-notification-was-shown nil)
1000 (catch 'abort
1001 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
1002 (org-clocking-p)))
1003 ts selected-task target-pos (msg-extra "")
1004 (leftover (and (not org-clock-resolving-clocks)
1005 org-clock-leftover-time)))
1007 (when (and org-clock-auto-clock-resolution
1008 (or (not interrupting)
1009 (eq t org-clock-auto-clock-resolution))
1010 (not org-clock-clocking-in)
1011 (not org-clock-resolving-clocks))
1012 (setq org-clock-leftover-time nil)
1013 (let ((org-clock-clocking-in t))
1014 (org-resolve-clocks))) ; check if any clocks are dangling
1016 (when (equal select '(4))
1017 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1018 (if selected-task
1019 (setq selected-task (copy-marker selected-task))
1020 (error "Abort")))
1022 (when (equal select '(16))
1023 ;; Mark as default clocking task
1024 (org-clock-mark-default-task))
1026 (when interrupting
1027 ;; We are interrupting the clocking of a different task.
1028 ;; Save a marker to this task, so that we can go back.
1029 ;; First check if we are trying to clock into the same task!
1030 (when (save-excursion
1031 (unless selected-task
1032 (org-back-to-heading t))
1033 (and (equal (marker-buffer org-clock-hd-marker)
1034 (if selected-task
1035 (marker-buffer selected-task)
1036 (current-buffer)))
1037 (= (marker-position org-clock-hd-marker)
1038 (if selected-task
1039 (marker-position selected-task)
1040 (point)))
1041 (equal org-clock-current-task (nth 4 (org-heading-components)))))
1042 (message "Clock continues in \"%s\"" org-clock-heading)
1043 (throw 'abort nil))
1044 (move-marker org-clock-interrupted-task
1045 (marker-position org-clock-marker)
1046 (marker-buffer org-clock-marker))
1047 (let ((org-clock-clocking-in t))
1048 (org-clock-out t)))
1050 ;; Clock in at which position?
1051 (setq target-pos
1052 (if (and (eobp) (not (org-on-heading-p)))
1053 (point-at-bol 0)
1054 (point)))
1055 (run-hooks 'org-clock-in-prepare-hook)
1056 (save-excursion
1057 (when (and selected-task (marker-buffer selected-task))
1058 ;; There is a selected task, move to the correct buffer
1059 ;; and set the new target position.
1060 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1061 (setq target-pos (marker-position selected-task))
1062 (move-marker selected-task nil))
1063 (save-excursion
1064 (save-restriction
1065 (widen)
1066 (goto-char target-pos)
1067 (org-back-to-heading t)
1068 (or interrupting (move-marker org-clock-interrupted-task nil))
1069 (org-clock-history-push)
1070 (org-clock-set-current)
1071 (cond ((functionp org-clock-in-switch-to-state)
1072 (looking-at org-complex-heading-regexp)
1073 (let ((newstate (funcall org-clock-in-switch-to-state
1074 (match-string 2))))
1075 (if newstate (org-todo newstate))))
1076 ((and org-clock-in-switch-to-state
1077 (not (looking-at (concat outline-regexp "[ \t]*"
1078 org-clock-in-switch-to-state
1079 "\\>"))))
1080 (org-todo org-clock-in-switch-to-state)))
1081 (setq org-clock-heading-for-remember
1082 (and (looking-at org-complex-heading-regexp)
1083 (match-end 4)
1084 (org-trim (buffer-substring (match-end 1)
1085 (match-end 4)))))
1086 (setq org-clock-heading
1087 (cond ((and org-clock-heading-function
1088 (functionp org-clock-heading-function))
1089 (funcall org-clock-heading-function))
1090 ((looking-at org-complex-heading-regexp)
1091 (replace-regexp-in-string
1092 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1093 (match-string 4)))
1094 (t "???")))
1095 (setq org-clock-heading (org-propertize org-clock-heading
1096 'face nil))
1097 (org-clock-find-position org-clock-in-resume)
1098 (cond
1099 ((and org-clock-in-resume
1100 (looking-at
1101 (concat "^[ \t]* " org-clock-string
1102 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1103 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1104 (message "Matched %s" (match-string 1))
1105 (setq ts (concat "[" (match-string 1) "]"))
1106 (goto-char (match-end 1))
1107 (setq org-clock-start-time
1108 (apply 'encode-time
1109 (org-parse-time-string (match-string 1))))
1110 (setq org-clock-effort (org-get-effort))
1111 (setq org-clock-total-time (org-clock-sum-current-item
1112 (org-clock-get-sum-start))))
1113 ((eq org-clock-in-resume 'auto-restart)
1114 ;; called from org-clock-load during startup,
1115 ;; do not interrupt, but warn!
1116 (message "Cannot restart clock because task does not contain unfinished clock")
1117 (ding)
1118 (sit-for 2)
1119 (throw 'abort nil))
1121 (insert-before-markers "\n")
1122 (backward-char 1)
1123 (org-indent-line-function)
1124 (when (and (save-excursion
1125 (end-of-line 0)
1126 (org-in-item-p)))
1127 (beginning-of-line 1)
1128 (org-indent-line-to (- (org-get-indentation) 2)))
1129 (insert org-clock-string " ")
1130 (setq org-clock-effort (org-get-effort))
1131 (setq org-clock-total-time (org-clock-sum-current-item
1132 (org-clock-get-sum-start)))
1133 (setq org-clock-start-time
1134 (or (and leftover
1135 (y-or-n-p
1136 (format
1137 "You stopped another clock %d mins ago; start this one from then? "
1138 (/ (- (org-float-time (current-time))
1139 (org-float-time leftover)) 60)))
1140 leftover)
1141 start-time
1142 (current-time)))
1143 (setq ts (org-insert-time-stamp org-clock-start-time
1144 'with-hm 'inactive))))
1145 (move-marker org-clock-marker (point) (buffer-base-buffer))
1146 (move-marker org-clock-hd-marker
1147 (save-excursion (org-back-to-heading t) (point))
1148 (buffer-base-buffer))
1149 (setq org-clock-has-been-used t)
1150 (or global-mode-string (setq global-mode-string '("")))
1151 (or (memq 'org-mode-line-string global-mode-string)
1152 (setq global-mode-string
1153 (append global-mode-string '(org-mode-line-string))))
1154 (org-clock-update-mode-line)
1155 (when org-clock-mode-line-timer
1156 (cancel-timer org-clock-mode-line-timer)
1157 (setq org-clock-mode-line-timer nil))
1158 (setq org-clock-mode-line-timer
1159 (run-with-timer org-clock-update-period
1160 org-clock-update-period
1161 'org-clock-update-mode-line))
1162 (when org-clock-idle-timer
1163 (cancel-timer org-clock-idle-timer)
1164 (setq org-clock-idle-timer nil))
1165 (setq org-clock-idle-timer
1166 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1167 (message "Clock starts at %s - %s" ts msg-extra)
1168 (run-hooks 'org-clock-in-hook)))))))
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. The scope
1656 of the new clock will be subtree when called from within a subtree, and
1657 file elsewhere.
1659 When called with a prefix argument, move to the first clock table in the
1660 buffer and update it."
1661 (interactive "P")
1662 (org-clock-remove-overlays)
1663 (when arg
1664 (org-find-dblock "clocktable")
1665 (org-show-entry))
1666 (if (org-in-clocktable-p)
1667 (goto-char (org-in-clocktable-p))
1668 (let ((props (if (ignore-errors
1669 (save-excursion (org-back-to-heading)))
1670 (list :name "clocktable" :scope 'subtree)
1671 (list :name "clocktable"))))
1672 (org-create-dblock
1673 (org-combine-plists org-clock-clocktable-default-properties props))))
1674 (org-update-dblock))
1676 (defun org-in-clocktable-p ()
1677 "Check if the cursor is in a clocktable."
1678 (let ((pos (point)) start)
1679 (save-excursion
1680 (end-of-line 1)
1681 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
1682 (setq start (match-beginning 0))
1683 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
1684 (>= (match-end 0) pos)
1685 start))))
1687 (defun org-day-of-week (day month year)
1688 "Returns the day of the week as an integer."
1689 (nth 6
1690 (decode-time
1691 (date-to-time
1692 (format "%d-%02d-%02dT00:00:00" year month day)))))
1694 (defun org-quarter-to-date (quarter year)
1695 "Get the date (week day year) of the first day of a given quarter."
1696 (let (startday)
1697 (cond
1698 ((= quarter 1)
1699 (setq startday (org-day-of-week 1 1 year))
1700 (cond
1701 ((= startday 0)
1702 (list 52 7 (- year 1)))
1703 ((= startday 6)
1704 (list 52 6 (- year 1)))
1705 ((<= startday 4)
1706 (list 1 startday year))
1707 ((> startday 4)
1708 (list 53 startday (- year 1)))
1711 ((= quarter 2)
1712 (setq startday (org-day-of-week 1 4 year))
1713 (cond
1714 ((= startday 0)
1715 (list 13 startday year))
1716 ((< startday 4)
1717 (list 14 startday year))
1718 ((>= startday 4)
1719 (list 13 startday year))
1722 ((= quarter 3)
1723 (setq startday (org-day-of-week 1 7 year))
1724 (cond
1725 ((= startday 0)
1726 (list 26 startday year))
1727 ((< startday 4)
1728 (list 27 startday year))
1729 ((>= startday 4)
1730 (list 26 startday year))
1733 ((= quarter 4)
1734 (setq startday (org-day-of-week 1 10 year))
1735 (cond
1736 ((= startday 0)
1737 (list 39 startday year))
1738 ((<= startday 4)
1739 (list 40 startday year))
1740 ((> startday 4)
1741 (list 39 startday year)))))))
1743 (defun org-clock-special-range (key &optional time as-strings)
1744 "Return two times bordering a special time range.
1745 Key is a symbol specifying the range and can be one of `today', `yesterday',
1746 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1747 A week starts Monday 0:00 and ends Sunday 24:00.
1748 The range is determined relative to TIME. TIME defaults to the current time.
1749 The return value is a cons cell with two internal times like the ones
1750 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1751 the returned times will be formatted strings."
1752 (if (integerp key) (setq key (intern (number-to-string key))))
1753 (let* ((tm (decode-time (or time (current-time))))
1754 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1755 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1756 (dow (nth 6 tm))
1757 (skey (symbol-name key))
1758 (shift 0)
1759 (q (cond ((>= (nth 4 tm) 10) 4)
1760 ((>= (nth 4 tm) 7) 3)
1761 ((>= (nth 4 tm) 4) 2)
1762 ((>= (nth 4 tm) 1) 1)))
1763 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1764 interval tmp shiftedy shiftedm shiftedq)
1765 (cond
1766 ((string-match "^[0-9]+$" skey)
1767 (setq y (string-to-number skey) m 1 d 1 key 'year))
1768 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1769 (setq y (string-to-number (match-string 1 skey))
1770 month (string-to-number (match-string 2 skey))
1771 d 1 key 'month))
1772 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1773 (require 'cal-iso)
1774 (setq y (string-to-number (match-string 1 skey))
1775 w (string-to-number (match-string 2 skey)))
1776 (setq date (calendar-gregorian-from-absolute
1777 (calendar-absolute-from-iso (list w 1 y))))
1778 (setq d (nth 1 date) month (car date) y (nth 2 date)
1779 dow 1
1780 key 'week))
1781 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
1782 (require 'cal-iso)
1783 (setq y (string-to-number (match-string 1 skey)))
1784 (setq q (string-to-number (match-string 2 skey)))
1785 (setq date (calendar-gregorian-from-absolute
1786 (calendar-absolute-from-iso (org-quarter-to-date q y))))
1787 (setq d (nth 1 date) month (car date) y (nth 2 date)
1788 dow 1
1789 key 'quarter))
1790 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1791 (setq y (string-to-number (match-string 1 skey))
1792 month (string-to-number (match-string 2 skey))
1793 d (string-to-number (match-string 3 skey))
1794 key 'day))
1795 ((string-match "\\([-+][0-9]+\\)$" skey)
1796 (setq shift (string-to-number (match-string 1 skey))
1797 key (intern (substring skey 0 (match-beginning 1))))
1798 (if(and (memq key '(quarter thisq)) (> shift 0))
1799 (error "Looking forward with quarters isn't implemented.")
1800 ())))
1802 (when (= shift 0)
1803 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1804 ((eq key 'lastweek) (setq key 'week shift -1))
1805 ((eq key 'lastmonth) (setq key 'month shift -1))
1806 ((eq key 'lastyear) (setq key 'year shift -1))
1807 ((eq key 'lastq) (setq key 'quarter shift -1))))
1808 (cond
1809 ((memq key '(day today))
1810 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1811 ((memq key '(week thisweek))
1812 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1813 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1814 ((memq key '(month thismonth))
1815 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1816 ((memq key '(quarter thisq))
1817 ; compute if this shift remains in this year
1818 ; if not, compute how many years and quarters we have to shift (via floor*)
1819 ; and compute the shifted years, months and quarters
1820 (cond
1821 ((< (+ (- q 1) shift) 0) ; shift not in this year
1822 (setq interval (* -1 (+ (- q 1) shift)))
1823 ; set tmp to ((years to shift) (quarters to shift))
1824 (setq tmp (org-floor* interval 4))
1825 ; due to the use of floor, 0 quarters actually means 4
1826 (if (= 0 (nth 1 tmp))
1827 (setq shiftedy (- y (nth 0 tmp))
1828 shiftedm 1
1829 shiftedq 1)
1830 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
1831 shiftedm (- 13 (* 3 (nth 1 tmp)))
1832 shiftedq (- 5 (nth 1 tmp))))
1833 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
1834 ((> (+ q shift) 0) ; shift is whitin this year
1835 (setq shiftedq (+ q shift))
1836 (setq shiftedy y)
1837 (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))))
1838 ((memq key '(year thisyear))
1839 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1840 (t (error "No such time block %s" key)))
1841 (setq ts (encode-time s m h d month y)
1842 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1843 (or d1 d) (or month1 month) (or y1 y)))
1844 (setq fm (cdr org-time-stamp-formats))
1845 (cond
1846 ((memq key '(day today))
1847 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1848 ((memq key '(week thisweek))
1849 (setq txt (format-time-string "week %G-W%V" ts)))
1850 ((memq key '(month thismonth))
1851 (setq txt (format-time-string "%B %Y" ts)))
1852 ((memq key '(year thisyear))
1853 (setq txt (format-time-string "the year %Y" ts)))
1854 ((memq key '(quarter thisq))
1855 (setq txt (concatenate 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
1857 (if as-strings
1858 (list (format-time-string fm ts) (format-time-string fm te) txt)
1859 (list ts te txt))))
1861 (defun org-count-quarter (n)
1862 (cond
1863 ((= n 1) "1st")
1864 ((= n 2) "2nd")
1865 ((= n 3) "3rd")
1866 ((= n 4) "4th")))
1868 (defun org-clocktable-shift (dir n)
1869 "Try to shift the :block date of the clocktable at point.
1870 Point must be in the #+BEGIN: line of a clocktable, or this function
1871 will throw an error.
1872 DIR is a direction, a symbol `left', `right', `up', or `down'.
1873 Both `left' and `down' shift the block toward the past, `up' and `right'
1874 push it toward the future.
1875 N is the number of shift steps to take. The size of the step depends on
1876 the currently selected interval size."
1877 (setq n (prefix-numeric-value n))
1878 (and (memq dir '(left down)) (setq n (- n)))
1879 (save-excursion
1880 (goto-char (point-at-bol))
1881 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1882 (error "Line needs a :block definition before this command works")
1883 (let* ((b (match-beginning 1)) (e (match-end 1))
1884 (s (match-string 1))
1885 block shift ins y mw d date wp m)
1886 (cond
1887 ((equal s "yesterday") (setq s "today-1"))
1888 ((equal s "lastweek") (setq s "thisweek-1"))
1889 ((equal s "lastmonth") (setq s "thismonth-1"))
1890 ((equal s "lastyear") (setq s "thisyear-1"))
1891 ((equal s "lastq") (setq s "thisq-1")))
1893 (cond
1894 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
1895 (setq block (match-string 1 s)
1896 shift (if (match-end 2)
1897 (string-to-number (match-string 2 s))
1899 (setq shift (+ shift n))
1900 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1901 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1902 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1903 (setq y (string-to-number (match-string 1 s))
1904 wp (and (match-end 3) (match-string 3 s))
1905 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1906 d (and (match-end 6) (string-to-number (match-string 6 s))))
1907 (cond
1908 (d (setq ins (format-time-string
1909 "%Y-%m-%d"
1910 (encode-time 0 0 0 (+ d n) m y))))
1911 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
1912 (require 'cal-iso)
1913 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1914 (setq ins (format-time-string
1915 "%G-W%V"
1916 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1917 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
1918 (require 'cal-iso)
1919 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
1920 (if (> (+ mw n) 4)
1921 (setq mw 0
1922 y (+ 1 y))
1924 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
1925 (if (= (+ mw n) 0)
1926 (setq mw 5
1927 y (- y 1))
1929 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
1930 (setq ins (format-time-string
1931 (concatenate 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
1932 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1934 (setq ins (format-time-string
1935 "%Y-%m"
1936 (encode-time 0 0 0 1 (+ mw n) y))))
1938 (setq ins (number-to-string (+ y n))))))
1939 (t (error "Cannot shift clocktable block")))
1940 (when ins
1941 (goto-char b)
1942 (insert ins)
1943 (delete-region (point) (+ (point) (- e b)))
1944 (beginning-of-line 1)
1945 (org-update-dblock)
1946 t)))))
1948 (defun org-dblock-write:clocktable (params)
1949 "Write the standard clocktable."
1950 (setq params (org-combine-plists org-clocktable-defaults params))
1951 (catch 'exit
1952 (let* ((scope (plist-get params :scope))
1953 (block (plist-get params :block))
1954 (ts (plist-get params :tstart))
1955 (te (plist-get params :tend))
1956 (link (plist-get params :link))
1957 (maxlevel (or (plist-get params :maxlevel) 3))
1958 (step (plist-get params :step))
1959 (timestamp (plist-get params :timestamp))
1960 (formatter (or (plist-get params :formatter)
1961 org-clock-clocktable-formatter
1962 'org-clocktable-write-default))
1963 cc range-text ipos pos one-file-with-archives
1964 scope-is-list tbls level)
1966 ;; Check if we need to do steps
1967 (when block
1968 ;; Get the range text for the header
1969 (setq cc (org-clock-special-range block nil t)
1970 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1971 (when step
1972 ;; Write many tables, in steps
1973 (unless (or block (and ts te))
1974 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1975 (org-clocktable-steps params)
1976 (throw 'exit nil))
1978 (setq ipos (point)) ; remember the insertion position
1980 ;; Get the right scope
1981 (setq pos (point))
1982 (cond
1983 ((and scope (listp scope) (symbolp (car scope)))
1984 (setq scope (eval scope)))
1985 ((eq scope 'agenda)
1986 (setq scope (org-agenda-files t)))
1987 ((eq scope 'agenda-with-archives)
1988 (setq scope (org-agenda-files t))
1989 (setq scope (org-add-archive-files scope)))
1990 ((eq scope 'file-with-archives)
1991 (setq scope (org-add-archive-files (list (buffer-file-name)))
1992 one-file-with-archives t)))
1993 (setq scope-is-list (and scope (listp scope)))
1994 (if scope-is-list
1995 ;; we collect from several files
1996 (let* ((files scope)
1997 file)
1998 (org-prepare-agenda-buffers files)
1999 (while (setq file (pop files))
2000 (with-current-buffer (find-buffer-visiting file)
2001 (save-excursion
2002 (save-restriction
2003 (push (org-clock-get-table-data file params) tbls))))))
2004 ;; Just from the current file
2005 (save-restriction
2006 ;; get the right range into the restriction
2007 (org-prepare-agenda-buffers (list (buffer-file-name)))
2008 (cond
2009 ((not scope)) ; use the restriction as it is now
2010 ((eq scope 'file) (widen))
2011 ((eq scope 'subtree) (org-narrow-to-subtree))
2012 ((eq scope 'tree)
2013 (while (org-up-heading-safe))
2014 (org-narrow-to-subtree))
2015 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
2016 (symbol-name scope)))
2017 (setq level (string-to-number (match-string 1 (symbol-name scope))))
2018 (catch 'exit
2019 (while (org-up-heading-safe)
2020 (looking-at outline-regexp)
2021 (if (<= (org-reduced-level (funcall outline-level)) level)
2022 (throw 'exit nil))))
2023 (org-narrow-to-subtree)))
2024 ;; do the table, with no file name.
2025 (push (org-clock-get-table-data nil params) tbls)))
2027 ;; OK, at this point we tbls as a list of tables, one per file
2028 (setq tbls (nreverse tbls))
2030 (setq params (plist-put params :multifile scope-is-list))
2031 (setq params (plist-put params :one-file-with-archives
2032 one-file-with-archives))
2034 (funcall formatter ipos tbls params))))
2036 (defun org-clocktable-write-default (ipos tables params)
2037 "Write out a clock table at position IPOS in the current buffer.
2038 TABLES is a list of tables with clocking data as produced by
2039 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2040 from the dynamic block defintion."
2041 ;; This function looks quite complicated, mainly because there are a
2042 ;; lot of options which can add or remove columns. I have massively
2043 ;; commented this function, the I hope it is understandable. If
2044 ;; someone wants to write their own special formatter, this maybe
2045 ;; much easier because there can be a fixed format with a
2046 ;; well-defined number of columns...
2047 (let* ((hlchars '((1 . "*") (2 . "/")))
2048 (lwords (assoc (or (plist-get params :lang)
2049 org-export-default-language)
2050 org-clock-clocktable-language-setup))
2051 (multifile (plist-get params :multifile))
2052 (block (plist-get params :block))
2053 (ts (plist-get params :tstart))
2054 (te (plist-get params :tend))
2055 (header (plist-get params :header))
2056 (narrow (plist-get params :narrow))
2057 (link (plist-get params :link))
2058 (maxlevel (or (plist-get params :maxlevel) 3))
2059 (emph (plist-get params :emphasize))
2060 (level-p (plist-get params :level))
2061 (timestamp (plist-get params :timestamp))
2062 (properties (plist-get params :properties))
2063 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2064 (rm-file-column (plist-get params :one-file-with-archives))
2065 (indent (plist-get params :indent))
2066 range-text total-time tbl level hlc formula pcol
2067 file-time entries entry headline
2068 recalc content narrow-cut-p tcol)
2070 ;; Implement abbreviations
2071 (when (plist-get params :compact)
2072 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2074 ;; Some consistency test for parameters
2075 (unless (integerp ntcol)
2076 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2078 (when (and narrow (integerp narrow) link)
2079 ;; We cannot have both integer narrow and link
2080 (message
2081 "Using hard narrowing in clocktable to allow for links")
2082 (setq narrow (intern (format "%d!" narrow))))
2084 (when narrow
2085 (cond
2086 ((integerp narrow))
2087 ((and (symbolp narrow)
2088 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2089 (setq narrow-cut-p t
2090 narrow (string-to-number (substring (symbol-name narrow)
2091 0 -1))))
2093 (error "Invalid value %s of :narrow property in clock table"
2094 narrow))))
2096 (when block
2097 ;; Get the range text for the header
2098 (setq range-text (nth 2 (org-clock-special-range block nil t))))
2100 ;; Compute the total time
2101 (setq total-time (apply '+ (mapcar 'cadr tables)))
2103 ;; Now we need to output this tsuff
2104 (goto-char ipos)
2106 ;; Insert the text *before* the actual table
2107 (insert-before-markers
2108 (or header
2109 ;; Format the standard header
2110 (concat
2111 (nth 9 lwords) " ["
2112 (substring
2113 (format-time-string (cdr org-time-stamp-formats))
2114 1 -1)
2116 (if block (concat ", for " range-text ".") "")
2117 "\n\n")))
2119 ;; Insert the narrowing line
2120 (when (and narrow (integerp narrow) (not narrow-cut-p))
2121 (insert-before-markers
2122 "|" ; table line starter
2123 (if multifile "|" "") ; file column, maybe
2124 (if level-p "|" "") ; level column, maybe
2125 (if timestamp "|" "") ; timestamp column, maybe
2126 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2127 (format "<%d>| |\n" narrow))) ; headline and time columns
2129 ;; Insert the table header line
2130 (insert-before-markers
2131 "|" ; table line starter
2132 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2133 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2134 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2135 (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
2136 (concat (nth 4 lwords) "|"
2137 (nth 5 lwords) "|\n")) ; headline and time columns
2139 ;; Insert the total time in the table
2140 (insert-before-markers
2141 "|-\n" ; a hline
2142 "|" ; table line starter
2143 (if multifile (concat "| " (nth 6 lwords) " ") "")
2144 ; file column, maybe
2145 (if level-p "|" "") ; level column, maybe
2146 (if timestamp "|" "") ; timestamp column, maybe
2147 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2148 (concat "*" (nth 7 lwords) "*| ") ; instead of a headline
2150 (org-minutes-to-hh:mm-string (or total-time 0)) ; the time
2151 "*|\n") ; close line
2153 ;; Now iterate over the tables and insert the data
2154 ;; but only if any time has been collected
2155 (when (and total-time (> total-time 0))
2157 (while (setq tbl (pop tables))
2158 ;; now tbl is the table resulting from one file.
2159 (setq file-time (nth 1 tbl))
2160 (when (or (and file-time (> file-time 0))
2161 (not (plist-get params :fileskip0)))
2162 (insert-before-markers "|-\n") ; a hline because a new file starts
2163 ;; First the file time, if we have multiple files
2164 (when multifile
2165 ;; Summarize the time collected from this file
2166 (insert-before-markers
2167 (format (concat "| %s %s | %s%s*" (nth 8 lwords) "* | *%s*|\n")
2168 (file-name-nondirectory (car tbl))
2169 (if level-p "| " "") ; level column, maybe
2170 (if timestamp "| " "") ; timestamp column, maybe
2171 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2172 (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
2174 ;; Get the list of node entries and iterate over it
2175 (setq entries (nth 2 tbl))
2176 (while (setq entry (pop entries))
2177 (setq level (car entry)
2178 headline (nth 1 entry)
2179 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2180 (when narrow-cut-p
2181 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2182 "\\'")
2183 headline)
2184 (match-end 3))
2185 (setq headline
2186 (format "[[%s][%s]]"
2187 (match-string 1 headline)
2188 (org-shorten-string (match-string 3 headline)
2189 narrow)))
2190 (setq headline (org-shorten-string headline narrow))))
2191 (insert-before-markers
2192 "|" ; start the table line
2193 (if multifile "|" "") ; free space for file name column?
2194 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2195 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2196 (if properties
2197 (concat
2198 (mapconcat
2199 (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
2200 properties "|") "|") "") ;properties columns, maybe
2201 (if indent (org-clocktable-indent-string level) "") ; indentation
2202 hlc headline hlc "|" ; headline
2203 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2204 ; empty fields for higher levels
2205 hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
2206 "|\n" ; close line
2207 )))))
2208 (backward-delete-char 1)
2209 (if (setq formula (plist-get params :formula))
2210 (cond
2211 ((eq formula '%)
2212 ;; compute the column where the % numbers need to go
2213 (setq pcol (+ 2
2214 (if multifile 1 0)
2215 (if level-p 1 0)
2216 (if timestamp 1 0)
2217 (min maxlevel (or ntcol 100))))
2218 ;; compute the column where the total time is
2219 (setq tcol (+ 2
2220 (if multifile 1 0)
2221 (if level-p 1 0)
2222 (if timestamp 1 0)))
2223 (insert
2224 (format
2225 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2226 pcol ; the column where the % numbers should go
2227 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2228 tcol ; column of the total time
2229 tcol (1- pcol) ; range of columns where times can be found
2231 (setq recalc t))
2232 ((stringp formula)
2233 (insert "\n#+TBLFM: " formula)
2234 (setq recalc t))
2235 (t (error "invalid formula in clocktable")))
2236 ;; Should we rescue an old formula?
2237 (when (stringp (setq content (plist-get params :content)))
2238 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
2239 (setq recalc t)
2240 (insert "\n" (match-string 1 (plist-get params :content)))
2241 (beginning-of-line 0))))
2242 ;; Back to beginning, align the table, recalculate if necessary
2243 (goto-char ipos)
2244 (skip-chars-forward "^|")
2245 (org-table-align)
2246 (when org-hide-emphasis-markers
2247 ;; we need to align a second time
2248 (org-table-align))
2249 (when recalc
2250 (if (eq formula '%)
2251 (save-excursion
2252 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2253 (org-table-goto-column pcol nil 'force)
2254 (insert "%")))
2255 (org-table-recalculate 'all))
2256 (when rm-file-column
2257 ;; The file column is actually not wanted
2258 (forward-char 1)
2259 (org-table-delete-column))
2260 total-time))
2262 (defun org-clocktable-indent-string (level)
2263 (if (= level 1)
2265 (let ((str "\\__"))
2266 (while (> level 2)
2267 (setq level (1- level)
2268 str (concat str "___")))
2269 (concat str " "))))
2271 (defun org-clocktable-steps (params)
2272 "Step through the range to make a number of clock tables."
2273 (let* ((p1 (copy-sequence params))
2274 (ts (plist-get p1 :tstart))
2275 (te (plist-get p1 :tend))
2276 (step0 (plist-get p1 :step))
2277 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2278 (stepskip0 (plist-get p1 :stepskip0))
2279 (block (plist-get p1 :block))
2280 cc range-text step-time)
2281 (when block
2282 (setq cc (org-clock-special-range block nil t)
2283 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2284 (cond
2285 ((numberp ts)
2286 ;; If ts is a number, it's an absolute day number from org-agenda.
2287 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2288 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2290 (setq ts (org-float-time
2291 (apply 'encode-time (org-parse-time-string ts))))))
2292 (cond
2293 ((numberp te)
2294 ;; Likewise for te.
2295 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2296 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2298 (setq te (org-float-time
2299 (apply 'encode-time (org-parse-time-string te))))))
2300 (setq p1 (plist-put p1 :header ""))
2301 (setq p1 (plist-put p1 :step nil))
2302 (setq p1 (plist-put p1 :block nil))
2303 (while (< ts te)
2304 (or (bolp) (insert "\n"))
2305 (setq p1 (plist-put p1 :tstart (format-time-string
2306 (org-time-stamp-format nil t)
2307 (seconds-to-time ts))))
2308 (setq p1 (plist-put p1 :tend (format-time-string
2309 (org-time-stamp-format nil t)
2310 (seconds-to-time (setq ts (+ ts step))))))
2311 (insert "\n" (if (eq step0 'day) "Daily report: "
2312 "Weekly report starting on: ")
2313 (plist-get p1 :tstart) "\n")
2314 (setq step-time (org-dblock-write:clocktable p1))
2315 (re-search-forward "^[ \t]*#\\+END:")
2316 (when (and (equal step-time 0) stepskip0)
2317 ;; Remove the empty table
2318 (delete-region (point-at-bol)
2319 (save-excursion
2320 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2321 nil t)
2322 (point))))
2323 (end-of-line 0))))
2325 (defun org-clock-get-table-data (file params)
2326 "Get the clocktable data for file FILE, with parameters PARAMS.
2327 FILE is only for identification - this function assumes that
2328 the correct buffer is current, and that the wanted restriction is
2329 in place.
2330 The return value will be a list with the file name and the total
2331 file time (in minutes) as 1st and 2nd elements. The third element
2332 of this list will be a list of headline entries. Each entry has the
2333 following structure:
2335 (LEVEL HEADLINE TIMESTAMP TIME)
2337 LEVEL: The level of the headline, as an integer. This will be
2338 the reduced leve, so 1,2,3,... even if only odd levels
2339 are being used.
2340 HEADLINE: The text of the headline. Depending on PARAMS, this may
2341 already be formatted like a link.
2342 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2343 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2344 in this sequence.
2345 TIME: The sum of all time spend in this tree, in minutes. This time
2346 will of cause be restricted to the time block and tags match
2347 specified in PARAMS."
2348 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2349 (timestamp (plist-get params :timestamp))
2350 (ts (plist-get params :tstart))
2351 (te (plist-get params :tend))
2352 (block (plist-get params :block))
2353 (link (plist-get params :link))
2354 (tags (plist-get params :tags))
2355 (properties (plist-get params :properties))
2356 (inherit-property-p (plist-get params :inherit-props))
2357 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2358 cc range-text st p time level hdl props tsp tbl)
2360 (setq org-clock-file-total-minutes nil)
2361 (when block
2362 (setq cc (org-clock-special-range block nil t)
2363 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2364 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2365 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2366 (when (and ts (listp ts))
2367 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2368 (when (and te (listp te))
2369 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2370 ;; Now the times are strings we can parse.
2371 (if ts (setq ts (org-float-time
2372 (apply 'encode-time (org-parse-time-string ts)))))
2373 (if te (setq te (org-float-time
2374 (apply 'encode-time (org-parse-time-string te)))))
2375 (save-excursion
2376 (org-clock-sum ts te
2377 (unless (null matcher)
2378 (lambda ()
2379 (let ((tags-list (org-get-tags-at)))
2380 (eval matcher)))))
2381 (goto-char (point-min))
2382 (setq st t)
2383 (while (or (and (bobp) (prog1 st (setq st nil))
2384 (get-text-property (point) :org-clock-minutes)
2385 (setq p (point-min)))
2386 (setq p (next-single-property-change
2387 (point) :org-clock-minutes)))
2388 (goto-char p)
2389 (when (setq time (get-text-property p :org-clock-minutes))
2390 (save-excursion
2391 (beginning-of-line 1)
2392 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2393 (setq level (org-reduced-level
2394 (- (match-end 1) (match-beginning 1))))
2395 (<= level maxlevel))
2396 (setq hdl (if (not link)
2397 (match-string 2)
2398 (org-make-link-string
2399 (format "file:%s::%s"
2400 (buffer-file-name)
2401 (save-match-data
2402 (org-make-org-heading-search-string
2403 (match-string 2))))
2404 (match-string 2)))
2405 tsp (when timestamp
2406 (setq props (org-entry-properties (point)))
2407 (or (cdr (assoc "SCHEDULED" props))
2408 (cdr (assoc "DEADLINE" props))
2409 (cdr (assoc "TIMESTAMP" props))
2410 (cdr (assoc "TIMESTAMP_IA" props))))
2411 props (when properties
2412 (remove nil
2413 (mapcar
2414 (lambda (p)
2415 (when (org-entry-get (point) p inherit-property-p)
2416 (cons p (org-entry-get (point) p inherit-property-p))))
2417 properties))))
2418 (when (> time 0) (push (list level hdl tsp time props) tbl))))))
2419 (setq tbl (nreverse tbl))
2420 (list file org-clock-file-total-minutes tbl))))
2422 (defun org-clock-time% (total &rest strings)
2423 "Compute a time fraction in percent.
2424 TOTAL s a time string like 10:21 specifying the total times.
2425 STRINGS is a list of strings that should be checked for a time.
2426 The first string that does have a time will be used.
2427 This function is made for clock tables."
2428 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2429 tot s)
2430 (save-match-data
2431 (catch 'exit
2432 (if (not (string-match re total))
2433 (throw 'exit 0.)
2434 (setq tot (+ (string-to-number (match-string 2 total))
2435 (* 60 (string-to-number (match-string 1 total)))))
2436 (if (= tot 0.) (throw 'exit 0.)))
2437 (while (setq s (pop strings))
2438 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2439 (throw 'exit
2440 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2441 (* 60 (string-to-number
2442 (match-string 1 s)))))
2443 tot))))
2444 0))))
2446 ;; Saving and loading the clock
2448 (defvar org-clock-loaded nil
2449 "Was the clock file loaded?")
2451 (defun org-clock-save ()
2452 "Persist various clock-related data to disk.
2453 The details of what will be saved are regulated by the variable
2454 `org-clock-persist'."
2455 (when (and org-clock-persist
2456 (or org-clock-loaded
2457 org-clock-has-been-used
2458 (not (file-exists-p org-clock-persist-file))))
2459 (let (b)
2460 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2461 (progn
2462 (delete-region (point-min) (point-max))
2463 ;;Store clock
2464 (insert (format ";; org-persist.el - %s at %s\n"
2465 system-name (format-time-string
2466 (cdr org-time-stamp-formats))))
2467 (if (and (memq org-clock-persist '(t clock))
2468 (setq b (org-clocking-buffer))
2469 (setq b (or (buffer-base-buffer b) b))
2470 (buffer-live-p b)
2471 (buffer-file-name b)
2472 (or (not org-clock-persist-query-save)
2473 (y-or-n-p (concat "Save current clock ("
2474 (substring-no-properties
2475 org-clock-heading)
2476 ") "))))
2477 (insert "(setq resume-clock '(\""
2478 (buffer-file-name (org-clocking-buffer))
2479 "\" . " (int-to-string (marker-position org-clock-marker))
2480 "))\n"))
2481 ;; Store clocked task history. Tasks are stored reversed to make
2482 ;; reading simpler
2483 (when (and (memq org-clock-persist '(t history))
2484 org-clock-history)
2485 (insert
2486 "(setq stored-clock-history '("
2487 (mapconcat
2488 (lambda (m)
2489 (when (and (setq b (marker-buffer m))
2490 (setq b (or (buffer-base-buffer b) b))
2491 (buffer-live-p b)
2492 (buffer-file-name b))
2493 (concat "(\"" (buffer-file-name b)
2494 "\" . " (int-to-string (marker-position m))
2495 ")")))
2496 (reverse org-clock-history) " ") "))\n"))
2497 (save-buffer)
2498 (kill-buffer (current-buffer)))))))
2500 (defun org-clock-load ()
2501 "Load clock-related data from disk, maybe resuming a stored clock."
2502 (when (and org-clock-persist (not org-clock-loaded))
2503 (let ((filename (expand-file-name org-clock-persist-file))
2504 (org-clock-in-resume 'auto-restart)
2505 resume-clock stored-clock-history)
2506 (if (not (file-readable-p filename))
2507 (message "Not restoring clock data; %s not found"
2508 org-clock-persist-file)
2509 (message "%s" "Restoring clock data")
2510 (setq org-clock-loaded t)
2511 (load-file filename)
2512 ;; load history
2513 (when stored-clock-history
2514 (save-window-excursion
2515 (mapc (lambda (task)
2516 (if (file-exists-p (car task))
2517 (org-clock-history-push (cdr task)
2518 (find-file (car task)))))
2519 stored-clock-history)))
2520 ;; resume clock
2521 (when (and resume-clock org-clock-persist
2522 (file-exists-p (car resume-clock))
2523 (or (not org-clock-persist-query-resume)
2524 (y-or-n-p
2525 (concat
2526 "Resume clock ("
2527 (with-current-buffer (find-file (car resume-clock))
2528 (save-excursion
2529 (goto-char (cdr resume-clock))
2530 (org-back-to-heading t)
2531 (and (looking-at org-complex-heading-regexp)
2532 (match-string 4))))
2533 ") "))))
2534 (when (file-exists-p (car resume-clock))
2535 (with-current-buffer (find-file (car resume-clock))
2536 (goto-char (cdr resume-clock))
2537 (let ((org-clock-auto-clock-resolution nil))
2538 (org-clock-in)
2539 (if (outline-invisible-p)
2540 (org-show-context))))))))))
2542 ;;;###autoload
2543 (defun org-clock-persistence-insinuate ()
2544 "Set up hooks for clock persistence."
2545 (add-hook 'org-mode-hook 'org-clock-load)
2546 (add-hook 'kill-emacs-hook 'org-clock-save))
2548 ;; Suggested bindings
2549 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2551 (provide 'org-clock)
2553 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2555 ;;; org-clock.el ends here