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