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