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