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