Revert "Bugfix: don't exclude parentheses from org-plain-link-re."
[org-mode.git] / lisp / org-clock.el
blob48a0741eda71e394691e285743980bd476779b75
1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
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: 6.28trans
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 (eval-when-compile
33 (require 'cl)
34 (require 'calendar))
36 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
37 (defvar org-time-stamp-formats)
39 (defgroup org-clock nil
40 "Options concerning clocking working time in Org-mode."
41 :tag "Org Clock"
42 :group 'org-progress)
44 (defcustom org-clock-into-drawer org-log-into-drawer
45 "Should clocking info be wrapped into a drawer?
46 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
47 If necessary, the drawer will be created.
48 When nil, the drawer will not be created, but used when present.
49 When an integer and the number of clocking entries in an item
50 reaches or exceeds this number, a drawer will be created.
51 When a string, it names the drawer to be used.
53 The default for this variable is the value of `org-log-into-drawer',
54 which see."
55 :group 'org-todo
56 :group 'org-clock
57 :type '(choice
58 (const :tag "Always" t)
59 (const :tag "Only when drawer exists" nil)
60 (integer :tag "When at least N clock entries")
61 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
62 (string :tag "Into Drawer named...")))
64 (defcustom org-clock-out-when-done t
65 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
66 A nil value means, clock will keep running until stopped explicitly with
67 `C-c C-x C-o', or until the clock is started in a different item."
68 :group 'org-clock
69 :type 'boolean)
71 (defcustom org-clock-out-remove-zero-time-clocks nil
72 "Non-nil means, remove the clock line when the resulting time is zero."
73 :group 'org-clock
74 :type 'boolean)
76 (defcustom org-clock-in-switch-to-state nil
77 "Set task to a special todo state while clocking it.
78 The value should be the state to which the entry should be
79 switched. If the value is a function, it must take one
80 parameter (the current TODO state of the item) and return the
81 state to switch it to."
82 :group 'org-clock
83 :group 'org-todo
84 :type '(choice
85 (const :tag "Don't force a state" nil)
86 (string :tag "State")
87 (symbol :tag "Function")))
89 (defcustom org-clock-out-switch-to-state nil
90 "Set task to a special todo state after clocking out.
91 The value should be the state to which the entry should be
92 switched. If the value is a function, it must take one
93 parameter (the current TODO state of the item) and return the
94 state to switch it to."
95 :group 'org-clock
96 :group 'org-todo
97 :type '(choice
98 (const :tag "Don't force a state" nil)
99 (string :tag "State")
100 (symbol :tag "Function")))
102 (defcustom org-clock-history-length 5
103 "Number of clock tasks to remember in history."
104 :group 'org-clock
105 :type 'integer)
107 (defcustom org-clock-goto-may-find-recent-task t
108 "Non-nil means, `org-clock-goto' can go to recent task if no active clock."
109 :group 'org-clock
110 :type 'boolean)
112 (defcustom org-clock-heading-function nil
113 "When non-nil, should be a function to create `org-clock-heading'.
114 This is the string shown in the mode line when a clock is running.
115 The function is called with point at the beginning of the headline."
116 :group 'org-clock
117 :type 'function)
119 (defcustom org-clock-string-limit 0
120 "Maximum length of clock strings in the modeline. 0 means no limit."
121 :group 'org-clock
122 :type 'integer)
124 (defcustom org-clock-in-resume nil
125 "If non-nil, resume clock when clocking into task with open clock.
126 When clocking into a task with a clock entry which has not been closed,
127 the clock can be resumed from that point."
128 :group 'org-clock
129 :type 'boolean)
131 (defcustom org-clock-persist nil
132 "When non-nil, save the running clock when emacs is closed.
133 The clock is resumed when emacs restarts.
134 When this is t, both the running clock, and the entire clock
135 history are saved. When this is the symbol `clock', only the
136 running clock is saved.
138 When Emacs restarts with saved clock information, the file containing the
139 running clock as well as all files mentioned in the clock history will
140 be visited.
141 All this depends on running `org-clock-persistence-insinuate' in .emacs"
142 :group 'org-clock
143 :type '(choice
144 (const :tag "Just the running clock" clock)
145 (const :tag "Clock and history" t)
146 (const :tag "No persistence" nil)))
148 (defcustom org-clock-persist-file (convert-standard-filename
149 "~/.emacs.d/org-clock-save.el")
150 "File to save clock data to."
151 :group 'org-clock
152 :type 'string)
154 (defcustom org-clock-persist-query-save nil
155 "When non-nil, ask before saving the current clock on exit."
156 :group 'org-clock
157 :type 'boolean)
159 (defcustom org-clock-persist-query-resume t
160 "When non-nil, ask before resuming any stored clock during load."
161 :group 'org-clock
162 :type 'boolean)
164 (defcustom org-clock-sound nil
165 "Sound that will used for notifications.
166 Possible values:
168 nil no sound played.
169 t standard Emacs beep
170 file name play this sound file. If not possible, fall back to beep"
171 :group 'org-clock
172 :type '(choice
173 (const :tag "No sound" nil)
174 (const :tag "Standard beep" t)
175 (file :tag "Play sound file")))
177 (defcustom org-clock-modeline-total 'auto
178 "Default setting for the time included for the modeline clock.
179 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
180 Allowed values are:
182 current Only the time in the current instance of the clock
183 today All time clocked inot this task today
184 repeat All time clocked into this task since last repeat
185 all All time ever recorded for this task
186 auto Automtically, either `all', or `repeat' for repeating tasks"
187 :group 'org-clock
188 :type '(choice
189 (const :tag "Current clock" current)
190 (const :tag "Today's task time" today)
191 (const :tag "Since last repeat" repeat)
192 (const :tag "All task time" all)
193 (const :tag "Automatically, `all' or since `repeat'" auto)))
195 (defcustom org-show-notification-handler nil
196 "Function or program to send notification with.
197 The function or program will be called with the notification
198 string as argument."
199 :group 'org-clock
200 :type '(choice
201 (string :tag "Program")
202 (function :tag "Function")))
204 (defvar org-clock-in-prepare-hook nil
205 "Hook run when preparing the clock.
206 This hook is run before anything happens to the task that
207 you want to clock in. For example, you can use this hook
208 to add an effort property.")
209 (defvar org-clock-in-hook nil
210 "Hook run when starting the clock.")
211 (defvar org-clock-out-hook nil
212 "Hook run when stopping the current clock.")
214 (defvar org-clock-cancel-hook nil
215 "Hook run when cancelling the current clock.")
216 (defvar org-clock-goto-hook nil
217 "Hook run when selecting the currently clocked-in entry.")
219 ;;; The clock for measuring work time.
221 (defvar org-mode-line-string "")
222 (put 'org-mode-line-string 'risky-local-variable t)
224 (defvar org-clock-mode-line-timer nil)
225 (defvar org-clock-heading "")
226 (defvar org-clock-heading-for-remember "")
227 (defvar org-clock-start-time "")
229 (defvar org-clock-effort ""
230 "Effort estimate of the currently clocking task")
232 (defvar org-clock-total-time nil
233 "Holds total time, spent previously on currently clocked item.
234 This does not include the time in the currently running clock.")
236 (defvar org-clock-history nil
237 "List of marker pointing to recent clocked tasks.")
239 (defvar org-clock-default-task (make-marker)
240 "Marker pointing to the default task that should clock time.
241 The clock can be made to switch to this task after clocking out
242 of a different task.")
244 (defvar org-clock-interrupted-task (make-marker)
245 "Marker pointing to the task that has been interrupted by the current clock.")
247 (defvar org-clock-mode-line-map (make-sparse-keymap))
248 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
249 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
251 (defun org-clock-menu ()
252 (interactive)
253 (popup-menu
254 '("Clock"
255 ["Clock out" org-clock-out t]
256 ["Change effort estimate" org-clock-modify-effort-estimate t]
257 ["Go to clock entry" org-clock-goto t]
258 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
260 (defun org-clock-history-push (&optional pos buffer)
261 "Push a marker to the clock history."
262 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
263 (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
264 (while (setq n (member m org-clock-history))
265 (move-marker (car n) nil))
266 (setq org-clock-history
267 (delq nil
268 (mapcar (lambda (x) (if (marker-buffer x) x nil))
269 org-clock-history)))
270 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
271 (setq org-clock-history
272 (nreverse
273 (nthcdr (- l org-clock-history-length -1)
274 (nreverse org-clock-history)))))
275 (push m org-clock-history)))
277 (defun org-clock-save-markers-for-cut-and-paste (beg end)
278 "Save relative positions of markers in region."
279 (org-check-and-save-marker org-clock-marker beg end)
280 (org-check-and-save-marker org-clock-default-task beg end)
281 (org-check-and-save-marker org-clock-interrupted-task beg end)
282 (mapc (lambda (m) (org-check-and-save-marker m beg end))
283 org-clock-history))
285 (defun org-clock-select-task (&optional prompt)
286 "Select a task that recently was associated with clocking."
287 (interactive)
288 (let (sel-list rpl (i 0) s)
289 (save-window-excursion
290 (org-switch-to-buffer-other-window
291 (get-buffer-create "*Clock Task Select*"))
292 (erase-buffer)
293 (when (marker-buffer org-clock-default-task)
294 (insert (org-add-props "Default Task\n" nil 'face 'bold))
295 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
296 (push s sel-list))
297 (when (marker-buffer org-clock-interrupted-task)
298 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
299 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
300 (push s sel-list))
301 (when (marker-buffer org-clock-marker)
302 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
303 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
304 (push s sel-list))
305 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
306 (mapc
307 (lambda (m)
308 (when (marker-buffer m)
309 (setq i (1+ i)
310 s (org-clock-insert-selection-line
311 (if (< i 10)
312 (+ i ?0)
313 (+ i (- ?A 10))) m))
314 (push s sel-list)))
315 org-clock-history)
316 (org-fit-window-to-buffer)
317 (message (or prompt "Select task for clocking:"))
318 (setq rpl (read-char-exclusive))
319 (cond
320 ((eq rpl ?q) nil)
321 ((eq rpl ?x) nil)
322 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
323 (t (error "Invalid task choice %c" rpl))))))
325 (defun org-clock-insert-selection-line (i marker)
326 "Insert a line for the clock selection menu.
327 And return a cons cell with the selection character integer and the marker
328 pointing to it."
329 (when (marker-buffer marker)
330 (let (file cat task heading prefix)
331 (with-current-buffer (org-base-buffer (marker-buffer marker))
332 (save-excursion
333 (save-restriction
334 (widen)
335 (goto-char marker)
336 (setq file (buffer-file-name (marker-buffer marker))
337 cat (or (org-get-category)
338 (progn (org-refresh-category-properties)
339 (org-get-category)))
340 heading (org-get-heading 'notags)
341 prefix (save-excursion
342 (org-back-to-heading t)
343 (looking-at "\\*+ ")
344 (match-string 0))
345 task (substring
346 (org-fontify-like-in-org-mode
347 (concat prefix heading)
348 org-odd-levels-only)
349 (length prefix))))))
350 (when (and cat task)
351 (insert (format "[%c] %-15s %s\n" i cat task))
352 (cons i marker)))))
354 (defun org-clock-get-clock-string ()
355 "Form a clock-string, that will be show in the mode line.
356 If an effort estimate was defined for current item, use
357 01:30/01:50 format (clocked/estimated).
358 If not, show simply the clocked time like 01:50."
359 (let* ((clocked-time (org-clock-get-clocked-time))
360 (h (floor clocked-time 60))
361 (m (- clocked-time (* 60 h))))
362 (if (and org-clock-effort)
363 (let* ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
364 (effort-h (floor effort-in-minutes 60))
365 (effort-m (- effort-in-minutes (* effort-h 60))))
366 (format (concat "-[" org-time-clocksum-format "/" org-time-clocksum-format " (%s)]")
367 h m effort-h effort-m org-clock-heading))
368 (format (concat "-[" org-time-clocksum-format " (%s)]")
369 h m org-clock-heading))))
371 (defun org-clock-update-mode-line ()
372 (setq org-mode-line-string
373 (org-propertize
374 (let ((clock-string (org-clock-get-clock-string))
375 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
376 (if (and (> org-clock-string-limit 0)
377 (> (length clock-string) org-clock-string-limit))
378 (org-propertize (substring clock-string 0 org-clock-string-limit)
379 'help-echo (concat help-text ": " org-clock-heading))
380 (org-propertize clock-string 'help-echo help-text)))
381 'local-map org-clock-mode-line-map
382 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
383 'face 'org-mode-line-clock))
384 (if org-clock-effort (org-clock-notify-once-if-expired))
385 (force-mode-line-update))
387 (defun org-clock-get-clocked-time ()
388 "Get the clocked time for the current item in minutes.
389 The time returned includes the the time spent on this task in
390 previous clocking intervals."
391 (let ((currently-clocked-time
392 (floor (- (time-to-seconds (current-time))
393 (time-to-seconds org-clock-start-time)) 60)))
394 (+ currently-clocked-time (or org-clock-total-time 0))))
396 (defun org-clock-modify-effort-estimate (&optional value)
397 "Add to or set the effort estimate of the item currently being clocked.
398 VALUE can be a number of minutes, or a string with forat hh:mm or mm.
399 WHen the strig starts with a + or a - sign, the current value of the effort
400 property will be changed by that amount.
401 This will update the \"Effort\" property of currently clocked item, and
402 the mode line."
403 (interactive)
404 (when (org-clock-is-active)
405 (let ((current org-clock-effort) sign)
406 (unless value
407 ;; Prompt user for a value or a change
408 (setq value
409 (read-string
410 (format "Set effort (hh:mm or mm%s): "
411 (if current
412 (format ", prefix + to add to %s" org-clock-effort)
413 "")))))
414 (when (stringp value)
415 ;; A string. See if it is a delta
416 (setq sign (string-to-char value))
417 (if (member sign '(?- ?+))
418 (setq current (org-hh:mm-string-to-minutes (substring current 1)))
419 (setq current 0))
420 (setq value (org-hh:mm-string-to-minutes value))
421 (if (equal ?- sign)
422 (setq value (- current value))
423 (if (equal ?+ sign) (setq value (+ current value)))))
424 (setq value (max 0 value)
425 org-clock-effort (org-minutes-to-hh:mm-string value))
426 (org-entry-put org-clock-marker "Effort" org-clock-effort)
427 (org-clock-update-mode-line))))
429 (defvar org-clock-notification-was-shown nil
430 "Shows if we have shown notification already.")
432 (defun org-clock-notify-once-if-expired ()
433 "Show notification if we spent more time than we estimated before.
434 Notification is shown only once."
435 (when (marker-buffer org-clock-marker)
436 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
437 (clocked-time (org-clock-get-clocked-time)))
438 (if (>= clocked-time effort-in-minutes)
439 (unless org-clock-notification-was-shown
440 (setq org-clock-notification-was-shown t)
441 (org-clock-play-sound)
442 (org-show-notification
443 (format "Task '%s' should be finished by now. (%s)"
444 org-clock-heading org-clock-effort)))
445 (setq org-clock-notification-was-shown nil)))))
447 (defun org-show-notification (notification)
448 "Show notification.
449 Use `org-show-notification-handler' if defined,
450 use libnotify if available, or fall back on a message."
451 (cond ((functionp org-show-notification-handler)
452 (funcall org-show-notification-handler notification))
453 ((stringp org-show-notification-handler)
454 (start-process "emacs-timer-notification" nil
455 org-show-notification-handler notification))
456 ((org-program-exists "notify-send")
457 (start-process "emacs-timer-notification" nil
458 "notify-send" notification))
459 ;; Maybe the handler will send a message, so only use message as
460 ;; a fall back option
461 (t (message notification))))
463 (defun org-clock-play-sound ()
464 "Play sound as configured by `org-clock-sound'.
465 Use alsa's aplay tool if available."
466 (cond
467 ((not org-clock-sound))
468 ((eq org-clock-sound t) (beep t) (beep t))
469 ((stringp org-clock-sound)
470 (if (file-exists-p org-clock-sound)
471 (if (org-program-exists "aplay")
472 (start-process "org-clock-play-notification" nil
473 "aplay" org-clock-sound)
474 (condition-case nil
475 (play-sound-file org-clock-sound)
476 (error (beep t) (beep t))))))))
478 (defun org-program-exists (program-name)
479 "Checks whenever we can locate program and launch it."
480 (if (eq system-type 'gnu/linux)
481 (= 0 (call-process "which" nil nil nil program-name))))
483 (defvar org-clock-mode-line-entry nil
484 "Information for the modeline about the running clock.")
486 (defun org-clock-in (&optional select)
487 "Start the clock on the current item.
488 If necessary, clock-out of the currently active clock.
489 With prefix arg SELECT, offer a list of recently clocked tasks to
490 clock into. When SELECT is `C-u C-u', clock into the current task and mark
491 is as the default task, a special task that will always be offered in
492 the clocking selection, associated with the letter `d'."
493 (interactive "P")
494 (setq org-clock-notification-was-shown nil)
495 (catch 'abort
496 (let ((interrupting (marker-buffer org-clock-marker))
497 ts selected-task target-pos (msg-extra ""))
498 (when (equal select '(4))
499 (setq selected-task (org-clock-select-task "Clock-in on task: "))
500 (if selected-task
501 (setq selected-task (copy-marker selected-task))
502 (error "Abort")))
503 (when interrupting
504 ;; We are interrupting the clocking of a different task.
505 ;; Save a marker to this task, so that we can go back.
506 (move-marker org-clock-interrupted-task
507 (marker-position org-clock-marker)
508 (marker-buffer org-clock-marker))
509 (org-clock-out t))
511 (when (equal select '(16))
512 ;; Mark as default clocking task
513 (org-clock-mark-default-task))
515 (setq target-pos (point)) ;; we want to clock in at this location
516 (run-hooks 'org-clock-in-prepare-hook)
517 (save-excursion
518 (when (and selected-task (marker-buffer selected-task))
519 ;; There is a selected task, move to the correct buffer
520 ;; and set the new target position.
521 (set-buffer (org-base-buffer (marker-buffer selected-task)))
522 (setq target-pos (marker-position selected-task))
523 (move-marker selected-task nil))
524 (save-excursion
525 (save-restriction
526 (widen)
527 (goto-char target-pos)
528 (org-back-to-heading t)
529 (or interrupting (move-marker org-clock-interrupted-task nil))
530 (org-clock-history-push)
531 (cond ((functionp org-clock-in-switch-to-state)
532 (looking-at org-complex-heading-regexp)
533 (let ((newstate (funcall org-clock-in-switch-to-state
534 (match-string 2))))
535 (if newstate (org-todo newstate))))
536 ((and org-clock-in-switch-to-state
537 (not (looking-at (concat outline-regexp "[ \t]*"
538 org-clock-in-switch-to-state
539 "\\>"))))
540 (org-todo org-clock-in-switch-to-state)))
541 (setq org-clock-heading-for-remember
542 (and (looking-at org-complex-heading-regexp)
543 (match-end 4)
544 (org-trim (buffer-substring (match-end 1)
545 (match-end 4)))))
546 (setq org-clock-heading
547 (cond ((and org-clock-heading-function
548 (functionp org-clock-heading-function))
549 (funcall org-clock-heading-function))
550 ((looking-at org-complex-heading-regexp)
551 (match-string 4))
552 (t "???")))
553 (setq org-clock-heading (org-propertize org-clock-heading
554 'face nil))
555 (org-clock-find-position org-clock-in-resume)
556 (cond
557 ((and org-clock-in-resume
558 (looking-at
559 (concat "^[ \t]* " org-clock-string
560 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
561 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
562 (message "Matched %s" (match-string 1))
563 (setq ts (concat "[" (match-string 1) "]"))
564 (goto-char (match-end 1))
565 (setq org-clock-start-time
566 (apply 'encode-time
567 (org-parse-time-string (match-string 1))))
568 (setq org-clock-effort (org-get-effort))
569 (setq org-clock-total-time (org-clock-sum-current-item
570 (org-clock-get-sum-start))))
571 ((eq org-clock-in-resume 'auto-restart)
572 ;; called from org-clock-load during startup,
573 ;; do not interrupt, but warn!
574 (message "Cannot restart clock because task does not contain unfinished clock")
575 (ding)
576 (sit-for 2)
577 (throw 'abort nil))
579 (insert-before-markers "\n")
580 (backward-char 1)
581 (org-indent-line-function)
582 (when (and (save-excursion
583 (end-of-line 0)
584 (org-in-item-p)))
585 (beginning-of-line 1)
586 (org-indent-line-to (- (org-get-indentation) 2)))
587 (insert org-clock-string " ")
588 (setq org-clock-effort (org-get-effort))
589 (setq org-clock-total-time (org-clock-sum-current-item
590 (org-clock-get-sum-start)))
591 (setq org-clock-start-time (current-time))
592 (setq ts (org-insert-time-stamp org-clock-start-time
593 'with-hm 'inactive))))
594 (move-marker org-clock-marker (point) (buffer-base-buffer))
595 (or global-mode-string (setq global-mode-string '("")))
596 (or (memq 'org-mode-line-string global-mode-string)
597 (setq global-mode-string
598 (append global-mode-string '(org-mode-line-string))))
599 (org-clock-update-mode-line)
600 (setq org-clock-mode-line-timer
601 (run-with-timer 60 60 'org-clock-update-mode-line))
602 (message "Clock starts at %s - %s" ts msg-extra)
603 (run-hooks 'org-clock-in-hook)))))))
605 (defun org-clock-mark-default-task ()
606 "Mark current task as default task."
607 (interactive)
608 (save-excursion
609 (org-back-to-heading t)
610 (move-marker org-clock-default-task (point))))
612 (defvar msg-extra)
613 (defun org-clock-get-sum-start ()
614 "Return the time from which clock times should be counted.
615 This is for the currently running clock as it is displayed
616 in the mode line. This function looks at the properties
617 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
618 corresponding variable `org-clock-modeline-total' and then
619 decides which time to use."
620 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
621 (symbol-name org-clock-modeline-total)))
622 (lr (org-entry-get nil "LAST_REPEAT")))
623 (cond
624 ((equal cmt "current")
625 (setq msg-extra "showing time in current clock instance")
626 (current-time))
627 ((equal cmt "today")
628 (setq msg-extra "showing today's task time.")
629 (let* ((dt (decode-time (current-time))))
630 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
631 (if org-extend-today-until
632 (setf (nth 2 dt) org-extend-today-until))
633 (apply 'encode-time dt)))
634 ((or (equal cmt "all")
635 (and (or (not cmt) (equal cmt "auto"))
636 (not lr)))
637 (setq msg-extra "showing entire task time.")
638 nil)
639 ((or (equal cmt "repeat")
640 (and (or (not cmt) (equal cmt "auto"))
641 lr))
642 (setq msg-extra "showing task time since last repeat.")
643 (if (not lr)
645 (org-time-string-to-time lr)))
646 (t nil))))
648 (defun org-clock-find-position (find-unclosed)
649 "Find the location where the next clock line should be inserted.
650 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
651 line and position cursor in that line."
652 (org-back-to-heading t)
653 (catch 'exit
654 (let ((beg (save-excursion
655 (beginning-of-line 2)
656 (or (bolp) (newline))
657 (point)))
658 (end (progn (outline-next-heading) (point)))
659 (re (concat "^[ \t]*" org-clock-string))
660 (cnt 0)
661 (drawer (if (stringp org-clock-into-drawer)
662 org-clock-into-drawer "LOGBOOK"))
663 first last ind-last)
664 (goto-char beg)
665 (when (and find-unclosed
666 (re-search-forward
667 (concat "^[ \t]* " org-clock-string
668 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
669 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
670 end t))
671 (beginning-of-line 1)
672 (throw 'exit t))
673 (when (eobp) (newline) (setq end (max (point) end)))
674 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
675 ;; we seem to have a CLOCK drawer, so go there.
676 (beginning-of-line 2)
677 (or org-log-states-order-reversed
678 (and (re-search-forward org-property-end-re nil t)
679 (goto-char (match-beginning 0))))
680 (throw 'exit t))
681 ;; Lets count the CLOCK lines
682 (goto-char beg)
683 (while (re-search-forward re end t)
684 (setq first (or first (match-beginning 0))
685 last (match-beginning 0)
686 cnt (1+ cnt)))
687 (when (and (integerp org-clock-into-drawer)
688 last
689 (>= (1+ cnt) org-clock-into-drawer))
690 ;; Wrap current entries into a new drawer
691 (goto-char last)
692 (setq ind-last (org-get-indentation))
693 (beginning-of-line 2)
694 (if (and (>= (org-get-indentation) ind-last)
695 (org-at-item-p))
696 (org-end-of-item))
697 (insert ":END:\n")
698 (beginning-of-line 0)
699 (org-indent-line-to ind-last)
700 (goto-char first)
701 (insert ":" drawer ":\n")
702 (beginning-of-line 0)
703 (org-indent-line-function)
704 (org-flag-drawer t)
705 (beginning-of-line 2)
706 (or org-log-states-order-reversed
707 (and (re-search-forward org-property-end-re nil t)
708 (goto-char (match-beginning 0))))
709 (throw 'exit nil))
711 (goto-char beg)
712 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
713 (not (equal (match-string 1) org-clock-string)))
714 ;; Planning info, skip to after it
715 (beginning-of-line 2)
716 (or (bolp) (newline)))
717 (when (or (eq org-clock-into-drawer t)
718 (stringp org-clock-into-drawer)
719 (and (integerp org-clock-into-drawer)
720 (< org-clock-into-drawer 2)))
721 (insert ":" drawer ":\n:END:\n")
722 (beginning-of-line -1)
723 (org-indent-line-function)
724 (org-flag-drawer t)
725 (beginning-of-line 2)
726 (org-indent-line-function)
727 (beginning-of-line)
728 (or org-log-states-order-reversed
729 (and (re-search-forward org-property-end-re nil t)
730 (goto-char (match-beginning 0))))))))
732 (defun org-clock-out (&optional fail-quietly)
733 "Stop the currently running clock.
734 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
735 (interactive)
736 (catch 'exit
737 (if (not (marker-buffer org-clock-marker))
738 (if fail-quietly (throw 'exit t) (error "No active clock")))
739 (let (ts te s h m remove)
740 (save-excursion
741 (set-buffer (marker-buffer org-clock-marker))
742 (save-restriction
743 (widen)
744 (goto-char org-clock-marker)
745 (beginning-of-line 1)
746 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
747 (equal (match-string 1) org-clock-string))
748 (setq ts (match-string 2))
749 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
750 (goto-char (match-end 0))
751 (delete-region (point) (point-at-eol))
752 (insert "--")
753 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
754 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
755 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
756 h (floor (/ s 3600))
757 s (- s (* 3600 h))
758 m (floor (/ s 60))
759 s (- s (* 60 s)))
760 (insert " => " (format "%2d:%02d" h m))
761 (when (setq remove (and org-clock-out-remove-zero-time-clocks
762 (= (+ h m) 0)))
763 (beginning-of-line 1)
764 (delete-region (point) (point-at-eol))
765 (and (looking-at "\n") (> (point-max) (1+ (point)))
766 (delete-char 1)))
767 (move-marker org-clock-marker nil)
768 (when org-log-note-clock-out
769 (org-add-log-setup 'clock-out nil nil nil nil
770 (concat "# Task: " (org-get-heading t) "\n\n")))
771 (when org-clock-mode-line-timer
772 (cancel-timer org-clock-mode-line-timer)
773 (setq org-clock-mode-line-timer nil))
774 (setq global-mode-string
775 (delq 'org-mode-line-string global-mode-string))
776 (when org-clock-out-switch-to-state
777 (save-excursion
778 (org-back-to-heading t)
779 (let ((org-inhibit-logging t))
780 (cond
781 ((functionp org-clock-out-switch-to-state)
782 (looking-at org-complex-heading-regexp)
783 (let ((newstate (funcall org-clock-out-switch-to-state
784 (match-string 2))))
785 (if newstate (org-todo newstate))))
786 ((and org-clock-out-switch-to-state
787 (not (looking-at (concat outline-regexp "[ \t]*"
788 org-clock-out-switch-to-state
789 "\\>"))))
790 (org-todo org-clock-out-switch-to-state))))))
791 (force-mode-line-update)
792 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
793 (if remove " => LINE REMOVED" ""))
794 (run-hooks 'org-clock-out-hook))))))
796 (defun org-clock-cancel ()
797 "Cancel the running clock be removing the start timestamp."
798 (interactive)
799 (if (not (marker-buffer org-clock-marker))
800 (error "No active clock"))
801 (save-excursion
802 (set-buffer (marker-buffer org-clock-marker))
803 (goto-char org-clock-marker)
804 (delete-region (1- (point-at-bol)) (point-at-eol)))
805 (setq global-mode-string
806 (delq 'org-mode-line-string global-mode-string))
807 (force-mode-line-update)
808 (message "Clock canceled")
809 (run-hooks 'org-clock-cancel-hook))
811 (defun org-clock-goto (&optional select)
812 "Go to the currently clocked-in entry, or to the most recently clocked one.
813 With prefix arg SELECT, offer recently clocked tasks for selection."
814 (interactive "@P")
815 (let* ((recent nil)
816 (m (cond
817 (select
818 (or (org-clock-select-task "Select task to go to: ")
819 (error "No task selected")))
820 ((marker-buffer org-clock-marker) org-clock-marker)
821 ((and org-clock-goto-may-find-recent-task
822 (car org-clock-history)
823 (marker-buffer (car org-clock-history)))
824 (setq recent t)
825 (car org-clock-history))
826 (t (error "No active or recent clock task")))))
827 (switch-to-buffer (marker-buffer m))
828 (if (or (< m (point-min)) (> m (point-max))) (widen))
829 (goto-char m)
830 (org-show-entry)
831 (org-back-to-heading t)
832 (org-cycle-hide-drawers 'children)
833 (recenter)
834 (if recent
835 (message "No running clock, this is the most recently clocked task"))
836 (run-hooks 'org-clock-goto-hook)))
838 (defvar org-clock-file-total-minutes nil
839 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
840 (make-variable-buffer-local 'org-clock-file-total-minutes)
842 (defun org-clock-sum (&optional tstart tend)
843 "Sum the times for each subtree.
844 Puts the resulting times in minutes as a text property on each headline.
845 TSTART and TEND can mark a time range to be considered."
846 (interactive)
847 (let* ((bmp (buffer-modified-p))
848 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
849 org-clock-string
850 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
851 (lmax 30)
852 (ltimes (make-vector lmax 0))
853 (t1 0)
854 (level 0)
855 ts te dt
856 time)
857 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
858 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
859 (if (consp tstart) (setq tstart (time-to-seconds tstart)))
860 (if (consp tend) (setq tend (time-to-seconds tend)))
861 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
862 (save-excursion
863 (goto-char (point-max))
864 (while (re-search-backward re nil t)
865 (cond
866 ((match-end 2)
867 ;; Two time stamps
868 (setq ts (match-string 2)
869 te (match-string 3)
870 ts (time-to-seconds
871 (apply 'encode-time (org-parse-time-string ts)))
872 te (time-to-seconds
873 (apply 'encode-time (org-parse-time-string te)))
874 ts (if tstart (max ts tstart) ts)
875 te (if tend (min te tend) te)
876 dt (- te ts)
877 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
878 ((match-end 4)
879 ;; A naked time
880 (setq t1 (+ t1 (string-to-number (match-string 5))
881 (* 60 (string-to-number (match-string 4))))))
882 (t ;; A headline
883 (setq level (- (match-end 1) (match-beginning 1)))
884 (when (or (> t1 0) (> (aref ltimes level) 0))
885 (loop for l from 0 to level do
886 (aset ltimes l (+ (aref ltimes l) t1)))
887 (setq t1 0 time (aref ltimes level))
888 (loop for l from level to (1- lmax) do
889 (aset ltimes l 0))
890 (goto-char (match-beginning 0))
891 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
892 (setq org-clock-file-total-minutes (aref ltimes 0)))
893 (set-buffer-modified-p bmp)))
895 (defun org-clock-sum-current-item (&optional tstart)
896 "Returns time, clocked on current item in total"
897 (save-excursion
898 (save-restriction
899 (org-narrow-to-subtree)
900 (org-clock-sum tstart)
901 org-clock-file-total-minutes)))
903 (defun org-clock-display (&optional total-only)
904 "Show subtree times in the entire buffer.
905 If TOTAL-ONLY is non-nil, only show the total time for the entire file
906 in the echo area."
907 (interactive)
908 (org-clock-remove-overlays)
909 (let (time h m p)
910 (org-clock-sum)
911 (unless total-only
912 (save-excursion
913 (goto-char (point-min))
914 (while (or (and (equal (setq p (point)) (point-min))
915 (get-text-property p :org-clock-minutes))
916 (setq p (next-single-property-change
917 (point) :org-clock-minutes)))
918 (goto-char p)
919 (when (setq time (get-text-property p :org-clock-minutes))
920 (org-clock-put-overlay time (funcall outline-level))))
921 (setq h (/ org-clock-file-total-minutes 60)
922 m (- org-clock-file-total-minutes (* 60 h)))
923 ;; Arrange to remove the overlays upon next change.
924 (when org-remove-highlights-with-change
925 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
926 nil 'local))))
927 (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
929 (defvar org-clock-overlays nil)
930 (make-variable-buffer-local 'org-clock-overlays)
932 (defun org-clock-put-overlay (time &optional level)
933 "Put an overlays on the current line, displaying TIME.
934 If LEVEL is given, prefix time with a corresponding number of stars.
935 This creates a new overlay and stores it in `org-clock-overlays', so that it
936 will be easy to remove."
937 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
938 (l (if level (org-get-valid-level level 0) 0))
939 (fmt (concat "%s " org-time-clocksum-format "%s"))
940 (off 0)
941 ov tx)
942 (org-move-to-column c)
943 (unless (eolp) (skip-chars-backward "^ \t"))
944 (skip-chars-backward " \t")
945 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
946 tx (concat (buffer-substring (1- (point)) (point))
947 (make-string (+ off (max 0 (- c (current-column)))) ?.)
948 (org-add-props (format fmt
949 (make-string l ?*) h m
950 (make-string (- 16 l) ?\ ))
951 (list 'face 'org-clock-overlay))
952 ""))
953 (if (not (featurep 'xemacs))
954 (org-overlay-put ov 'display tx)
955 (org-overlay-put ov 'invisible t)
956 (org-overlay-put ov 'end-glyph (make-glyph tx)))
957 (push ov org-clock-overlays)))
959 (defun org-clock-remove-overlays (&optional beg end noremove)
960 "Remove the occur highlights from the buffer.
961 BEG and END are ignored. If NOREMOVE is nil, remove this function
962 from the `before-change-functions' in the current buffer."
963 (interactive)
964 (unless org-inhibit-highlight-removal
965 (mapc 'org-delete-overlay org-clock-overlays)
966 (setq org-clock-overlays nil)
967 (unless noremove
968 (remove-hook 'before-change-functions
969 'org-clock-remove-overlays 'local))))
971 (defvar state) ;; dynamically scoped into this function
972 (defun org-clock-out-if-current ()
973 "Clock out if the current entry contains the running clock.
974 This is used to stop the clock after a TODO entry is marked DONE,
975 and is only done if the variable `org-clock-out-when-done' is not nil."
976 (when (and org-clock-out-when-done
977 (member state org-done-keywords)
978 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker))
979 (marker-buffer org-clock-marker))
980 (or (buffer-base-buffer (current-buffer))
981 (current-buffer)))
982 (< (point) org-clock-marker)
983 (> (save-excursion (outline-next-heading) (point))
984 org-clock-marker))
985 ;; Clock out, but don't accept a logging message for this.
986 (let ((org-log-note-clock-out nil))
987 (org-clock-out))))
989 (add-hook 'org-after-todo-state-change-hook
990 'org-clock-out-if-current)
992 ;;;###autoload
993 (defun org-get-clocktable (&rest props)
994 "Get a formatted clocktable with parameters according to PROPS.
995 The table is created in a temporary buffer, fully formatted and
996 fontified, and then returned."
997 ;; Set the defaults
998 (setq props (plist-put props :name "clocktable"))
999 (unless (plist-member props :maxlevel)
1000 (setq props (plist-put props :maxlevel 2)))
1001 (unless (plist-member props :scope)
1002 (setq props (plist-put props :scope 'agenda)))
1003 (with-temp-buffer
1004 (org-mode)
1005 (org-create-dblock props)
1006 (org-update-dblock)
1007 (font-lock-fontify-buffer)
1008 (forward-line 2)
1009 (buffer-substring (point) (progn
1010 (re-search-forward "^#\\+END" nil t)
1011 (point-at-bol)))))
1013 (defun org-clock-report (&optional arg)
1014 "Create a table containing a report about clocked time.
1015 If the cursor is inside an existing clocktable block, then the table
1016 will be updated. If not, a new clocktable will be inserted.
1017 When called with a prefix argument, move to the first clock table in the
1018 buffer and update it."
1019 (interactive "P")
1020 (org-clock-remove-overlays)
1021 (when arg
1022 (org-find-dblock "clocktable")
1023 (org-show-entry))
1024 (if (org-in-clocktable-p)
1025 (goto-char (org-in-clocktable-p))
1026 (org-create-dblock (list :name "clocktable"
1027 :maxlevel 2 :scope 'file)))
1028 (org-update-dblock))
1030 (defun org-in-clocktable-p ()
1031 "Check if the cursor is in a clocktable."
1032 (let ((pos (point)) start)
1033 (save-excursion
1034 (end-of-line 1)
1035 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
1036 (setq start (match-beginning 0))
1037 (re-search-forward "^#\\+END:.*" nil t)
1038 (>= (match-end 0) pos)
1039 start))))
1041 (defun org-clock-special-range (key &optional time as-strings)
1042 "Return two times bordering a special time range.
1043 Key is a symbol specifying the range and can be one of `today', `yesterday',
1044 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1045 A week starts Monday 0:00 and ends Sunday 24:00.
1046 The range is determined relative to TIME. TIME defaults to the current time.
1047 The return value is a cons cell with two internal times like the ones
1048 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1049 the returned times will be formatted strings."
1050 (if (integerp key) (setq key (intern (number-to-string key))))
1051 (let* ((tm (decode-time (or time (current-time))))
1052 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1053 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1054 (dow (nth 6 tm))
1055 (skey (symbol-name key))
1056 (shift 0)
1057 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
1058 (cond
1059 ((string-match "^[0-9]+$" skey)
1060 (setq y (string-to-number skey) m 1 d 1 key 'year))
1061 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1062 (setq y (string-to-number (match-string 1 skey))
1063 month (string-to-number (match-string 2 skey))
1064 d 1 key 'month))
1065 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1066 (require 'cal-iso)
1067 (setq y (string-to-number (match-string 1 skey))
1068 w (string-to-number (match-string 2 skey)))
1069 (setq date (calendar-gregorian-from-absolute
1070 (calendar-absolute-from-iso (list w 1 y))))
1071 (setq d (nth 1 date) month (car date) y (nth 2 date)
1072 dow 1
1073 key 'week))
1074 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1075 (setq y (string-to-number (match-string 1 skey))
1076 month (string-to-number (match-string 2 skey))
1077 d (string-to-number (match-string 3 skey))
1078 key 'day))
1079 ((string-match "\\([-+][0-9]+\\)$" skey)
1080 (setq shift (string-to-number (match-string 1 skey))
1081 key (intern (substring skey 0 (match-beginning 1))))))
1082 (when (= shift 0)
1083 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1084 ((eq key 'lastweek) (setq key 'week shift -1))
1085 ((eq key 'lastmonth) (setq key 'month shift -1))
1086 ((eq key 'lastyear) (setq key 'year shift -1))))
1087 (cond
1088 ((memq key '(day today))
1089 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1090 ((memq key '(week thisweek))
1091 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1092 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1093 ((memq key '(month thismonth))
1094 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1095 ((memq key '(year thisyear))
1096 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1097 (t (error "No such time block %s" key)))
1098 (setq ts (encode-time s m h d month y)
1099 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1100 (or d1 d) (or month1 month) (or y1 y)))
1101 (setq fm (cdr org-time-stamp-formats))
1102 (cond
1103 ((memq key '(day today))
1104 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1105 ((memq key '(week thisweek))
1106 (setq txt (format-time-string "week %G-W%V" ts)))
1107 ((memq key '(month thismonth))
1108 (setq txt (format-time-string "%B %Y" ts)))
1109 ((memq key '(year thisyear))
1110 (setq txt (format-time-string "the year %Y" ts))))
1111 (if as-strings
1112 (list (format-time-string fm ts) (format-time-string fm te) txt)
1113 (list ts te txt))))
1115 (defun org-clocktable-shift (dir n)
1116 "Try to shift the :block date of the clocktable at point.
1117 Point must be in the #+BEGIN: line of a clocktable, or this function
1118 will throw an error.
1119 DIR is a direction, a symbol `left', `right', `up', or `down'.
1120 Both `left' and `down' shift the block toward the past, `up' and `right'
1121 push it toward the future.
1122 N is the number of shift steps to take. The size of the step depends on
1123 the currently selected interval size."
1124 (setq n (prefix-numeric-value n))
1125 (and (memq dir '(left down)) (setq n (- n)))
1126 (save-excursion
1127 (goto-char (point-at-bol))
1128 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1129 (error "Line needs a :block definition before this command works")
1130 (let* ((b (match-beginning 1)) (e (match-end 1))
1131 (s (match-string 1))
1132 block shift ins y mw d date wp m)
1133 (cond
1134 ((equal s "yesterday") (setq s "today-1"))
1135 ((equal s "lastweek") (setq s "thisweek-1"))
1136 ((equal s "lastmonth") (setq s "thismonth-1"))
1137 ((equal s "lastyear") (setq s "thisyear-1")))
1138 (cond
1139 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
1140 (setq block (match-string 1 s)
1141 shift (if (match-end 2)
1142 (string-to-number (match-string 2 s))
1144 (setq shift (+ shift n))
1145 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1146 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1147 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1148 (setq y (string-to-number (match-string 1 s))
1149 wp (and (match-end 3) (match-string 3 s))
1150 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1151 d (and (match-end 6) (string-to-number (match-string 6 s))))
1152 (cond
1153 (d (setq ins (format-time-string
1154 "%Y-%m-%d"
1155 (encode-time 0 0 0 (+ d n) m y))))
1156 ((and wp mw (> (length wp) 0))
1157 (require 'cal-iso)
1158 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1159 (setq ins (format-time-string
1160 "%G-W%V"
1161 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1163 (setq ins (format-time-string
1164 "%Y-%m"
1165 (encode-time 0 0 0 1 (+ mw n) y))))
1167 (setq ins (number-to-string (+ y n))))))
1168 (t (error "Cannot shift clocktable block")))
1169 (when ins
1170 (goto-char b)
1171 (insert ins)
1172 (delete-region (point) (+ (point) (- e b)))
1173 (beginning-of-line 1)
1174 (org-update-dblock)
1175 t)))))
1177 (defun org-dblock-write:clocktable (params)
1178 "Write the standard clocktable."
1179 (catch 'exit
1180 (let* ((hlchars '((1 . "*") (2 . "/")))
1181 (ins (make-marker))
1182 (total-time nil)
1183 (scope (plist-get params :scope))
1184 (tostring (plist-get params :tostring))
1185 (multifile (plist-get params :multifile))
1186 (header (plist-get params :header))
1187 (maxlevel (or (plist-get params :maxlevel) 3))
1188 (step (plist-get params :step))
1189 (emph (plist-get params :emphasize))
1190 (timestamp (plist-get params :timestamp))
1191 (ts (plist-get params :tstart))
1192 (te (plist-get params :tend))
1193 (block (plist-get params :block))
1194 (link (plist-get params :link))
1195 ipos time p level hlc hdl tsp props content recalc formula pcol
1196 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
1197 (setq org-clock-file-total-minutes nil)
1198 (when step
1199 (unless (or block (and ts te))
1200 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1201 (org-clocktable-steps params)
1202 (throw 'exit nil))
1203 (when block
1204 (setq cc (org-clock-special-range block nil t)
1205 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1206 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
1207 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
1208 (when (and ts (listp ts))
1209 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
1210 (when (and te (listp te))
1211 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
1212 ;; Now the times are strings we can parse.
1213 (if ts (setq ts (time-to-seconds
1214 (apply 'encode-time (org-parse-time-string ts)))))
1215 (if te (setq te (time-to-seconds
1216 (apply 'encode-time (org-parse-time-string te)))))
1217 (move-marker ins (point))
1218 (setq ipos (point))
1220 ;; Get the right scope
1221 (setq pos (point))
1222 (cond
1223 ((and scope (listp scope) (symbolp (car scope)))
1224 (setq scope (eval scope)))
1225 ((eq scope 'agenda)
1226 (setq scope (org-agenda-files t)))
1227 ((eq scope 'agenda-with-archives)
1228 (setq scope (org-agenda-files t))
1229 (setq scope (org-add-archive-files scope)))
1230 ((eq scope 'file-with-archives)
1231 (setq scope (org-add-archive-files (list (buffer-file-name)))
1232 rm-file-column t)))
1233 (setq scope-is-list (and scope (listp scope)))
1234 (save-restriction
1235 (cond
1236 ((not scope))
1237 ((eq scope 'file) (widen))
1238 ((eq scope 'subtree) (org-narrow-to-subtree))
1239 ((eq scope 'tree)
1240 (while (org-up-heading-safe))
1241 (org-narrow-to-subtree))
1242 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1243 (symbol-name scope)))
1244 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1245 (catch 'exit
1246 (while (org-up-heading-safe)
1247 (looking-at outline-regexp)
1248 (if (<= (org-reduced-level (funcall outline-level)) level)
1249 (throw 'exit nil))))
1250 (org-narrow-to-subtree))
1251 (scope-is-list
1252 (let* ((files scope)
1253 (scope 'agenda)
1254 (p1 (copy-sequence params))
1255 file)
1256 (setq p1 (plist-put p1 :tostring t))
1257 (setq p1 (plist-put p1 :multifile t))
1258 (setq p1 (plist-put p1 :scope 'file))
1259 (org-prepare-agenda-buffers files)
1260 (while (setq file (pop files))
1261 (with-current-buffer (find-buffer-visiting file)
1262 (setq tbl1 (org-dblock-write:clocktable p1))
1263 (when tbl1
1264 (push (org-clocktable-add-file
1265 file
1266 (concat "| |*File time*|*"
1267 (org-minutes-to-hh:mm-string
1268 org-clock-file-total-minutes)
1269 "*|\n"
1270 tbl1)) tbl)
1271 (setq total-time (+ (or total-time 0)
1272 org-clock-file-total-minutes))))))))
1273 (goto-char pos)
1275 (unless scope-is-list
1276 (org-clock-sum ts te)
1277 (goto-char (point-min))
1278 (setq st t)
1279 (while (or (and (bobp) (prog1 st (setq st nil))
1280 (get-text-property (point) :org-clock-minutes)
1281 (setq p (point-min)))
1282 (setq p (next-single-property-change (point) :org-clock-minutes)))
1283 (goto-char p)
1284 (when (setq time (get-text-property p :org-clock-minutes))
1285 (save-excursion
1286 (beginning-of-line 1)
1287 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1288 (setq level (org-reduced-level
1289 (- (match-end 1) (match-beginning 1))))
1290 (<= level maxlevel))
1291 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
1292 hdl (if (not link)
1293 (match-string 2)
1294 (org-make-link-string
1295 (format "file:%s::%s"
1296 (buffer-file-name)
1297 (save-match-data
1298 (org-make-org-heading-search-string
1299 (match-string 2))))
1300 (match-string 2)))
1301 tsp (when timestamp
1302 (setq props (org-entry-properties (point)))
1303 (or (cdr (assoc "SCHEDULED" props))
1304 (cdr (assoc "TIMESTAMP" props))
1305 (cdr (assoc "DEADLINE" props))
1306 (cdr (assoc "TIMESTAMP_IA" props)))))
1307 (if (and (not multifile) (= level 1)) (push "|-" tbl))
1308 (push (concat
1309 "| " (int-to-string level) "|"
1310 (if timestamp (concat tsp "|") "")
1311 hlc hdl hlc " |"
1312 (make-string (1- level) ?|)
1313 hlc (org-minutes-to-hh:mm-string time) hlc
1314 " |") tbl))))))
1315 (setq tbl (nreverse tbl))
1316 (if tostring
1317 (if tbl (mapconcat 'identity tbl "\n") nil)
1318 (goto-char ins)
1319 (insert-before-markers
1320 (or header
1321 (concat
1322 "Clock summary at ["
1323 (substring
1324 (format-time-string (cdr org-time-stamp-formats))
1325 1 -1)
1327 (if block (concat ", for " range-text ".") "")
1328 "\n\n"))
1329 (if scope-is-list "|File" "")
1330 "|L|" (if timestamp "Timestamp|" "") "Headline|Time|\n")
1331 (setq total-time (or total-time org-clock-file-total-minutes))
1332 (insert-before-markers
1333 "|-\n|"
1334 (if scope-is-list "|" "")
1335 (if timestamp "|Timestamp|" "|")
1336 "*Total time*| *"
1337 (org-minutes-to-hh:mm-string (or total-time 0))
1338 "*|\n|-\n")
1339 (setq tbl (delq nil tbl))
1340 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
1341 (equal (substring (car tbl) 0 2) "|-"))
1342 (pop tbl))
1343 (insert-before-markers (mapconcat
1344 'identity (delq nil tbl)
1345 (if scope-is-list "\n|-\n" "\n")))
1346 (backward-delete-char 1)
1347 (if (setq formula (plist-get params :formula))
1348 (cond
1349 ((eq formula '%)
1350 (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
1351 (insert
1352 (format
1353 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1354 pcol
1356 (+ 3 (if scope-is-list 1 0))
1357 (+ (if scope-is-list 1 0) 3)
1358 (1- pcol)))
1359 (setq recalc t))
1360 ((stringp formula)
1361 (insert "\n#+TBLFM: " formula)
1362 (setq recalc t))
1363 (t (error "invalid formula in clocktable")))
1364 ;; Should we rescue an old formula?
1365 (when (stringp (setq content (plist-get params :content)))
1366 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
1367 (setq recalc t)
1368 (insert "\n" (match-string 1 (plist-get params :content)))
1369 (beginning-of-line 0))))
1370 (goto-char ipos)
1371 (skip-chars-forward "^|")
1372 (org-table-align)
1373 (when recalc
1374 (if (eq formula '%)
1375 (save-excursion (org-table-goto-column pcol nil 'force)
1376 (insert "%")))
1377 (org-table-recalculate 'all))
1378 (when rm-file-column
1379 (forward-char 1)
1380 (org-table-delete-column)))))))
1382 (defun org-clocktable-steps (params)
1383 (let* ((p1 (copy-sequence params))
1384 (ts (plist-get p1 :tstart))
1385 (te (plist-get p1 :tend))
1386 (step0 (plist-get p1 :step))
1387 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
1388 (block (plist-get p1 :block))
1389 cc range-text)
1390 (when block
1391 (setq cc (org-clock-special-range block nil t)
1392 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1393 (if ts (setq ts (time-to-seconds
1394 (apply 'encode-time (org-parse-time-string ts)))))
1395 (if te (setq te (time-to-seconds
1396 (apply 'encode-time (org-parse-time-string te)))))
1397 (setq p1 (plist-put p1 :header ""))
1398 (setq p1 (plist-put p1 :step nil))
1399 (setq p1 (plist-put p1 :block nil))
1400 (while (< ts te)
1401 (or (bolp) (insert "\n"))
1402 (setq p1 (plist-put p1 :tstart (format-time-string
1403 (org-time-stamp-format nil t)
1404 (seconds-to-time ts))))
1405 (setq p1 (plist-put p1 :tend (format-time-string
1406 (org-time-stamp-format nil t)
1407 (seconds-to-time (setq ts (+ ts step))))))
1408 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
1409 (plist-get p1 :tstart) "\n")
1410 (org-dblock-write:clocktable p1)
1411 (re-search-forward "#\\+END:")
1412 (end-of-line 0))))
1414 (defun org-clocktable-add-file (file table)
1415 (if table
1416 (let ((lines (org-split-string table "\n"))
1417 (ff (file-name-nondirectory file)))
1418 (mapconcat 'identity
1419 (mapcar (lambda (x)
1420 (if (string-match org-table-dataline-regexp x)
1421 (concat "|" ff x)
1423 lines)
1424 "\n"))))
1426 (defun org-clock-time% (total &rest strings)
1427 "Compute a time fraction in percent.
1428 TOTAL s a time string like 10:21 specifying the total times.
1429 STRINGS is a list of strings that should be checked for a time.
1430 The first string that does have a time will be used.
1431 This function is made for clock tables."
1432 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1433 tot s)
1434 (save-match-data
1435 (catch 'exit
1436 (if (not (string-match re total))
1437 (throw 'exit 0.)
1438 (setq tot (+ (string-to-number (match-string 2 total))
1439 (* 60 (string-to-number (match-string 1 total)))))
1440 (if (= tot 0.) (throw 'exit 0.)))
1441 (while (setq s (pop strings))
1442 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
1443 (throw 'exit
1444 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
1445 (* 60 (string-to-number (match-string 1 s)))))
1446 tot))))
1447 0))))
1449 (defun org-clock-save ()
1450 "Persist various clock-related data to disk.
1451 The details of what will be saved are regulated by the variable
1452 `org-clock-persist'."
1453 (when org-clock-persist
1454 (let (b)
1455 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
1456 (progn
1457 (delete-region (point-min) (point-max))
1458 ;;Store clock
1459 (insert (format ";; org-persist.el - %s at %s\n"
1460 system-name (format-time-string
1461 (cdr org-time-stamp-formats))))
1462 (if (and (setq b (marker-buffer org-clock-marker))
1463 (setq b (or (buffer-base-buffer b) b))
1464 (buffer-live-p b)
1465 (buffer-file-name b)
1466 (or (not org-clock-persist-query-save)
1467 (y-or-n-p (concat "Save current clock ("
1468 (substring-no-properties org-clock-heading)
1469 ") "))))
1470 (insert "(setq resume-clock '(\""
1471 (buffer-file-name (marker-buffer org-clock-marker))
1472 "\" . " (int-to-string (marker-position org-clock-marker))
1473 "))\n"))
1474 ;; Store clocked task history. Tasks are stored reversed to make
1475 ;; reading simpler
1476 (when (and org-clock-history (eq org-clock-persist t))
1477 (insert
1478 "(setq stored-clock-history '("
1479 (mapconcat
1480 (lambda (m)
1481 (when (and (setq b (marker-buffer m))
1482 (setq b (or (buffer-base-buffer b) b))
1483 (buffer-live-p b)
1484 (buffer-file-name b))
1485 (concat "(\"" (buffer-file-name b)
1486 "\" . " (int-to-string (marker-position m))
1487 ")")))
1488 (reverse org-clock-history) " ") "))\n"))
1489 (save-buffer)
1490 (kill-buffer (current-buffer)))))))
1492 (defvar org-clock-loaded nil
1493 "Was the clock file loaded?")
1495 (defun org-clock-load ()
1496 "Load clock-related data from disk, maybe resuming a stored clock."
1497 (when (and org-clock-persist (not org-clock-loaded))
1498 (let ((filename (expand-file-name org-clock-persist-file))
1499 (org-clock-in-resume 'auto-restart)
1500 resume-clock stored-clock-history)
1501 (if (not (file-readable-p filename))
1502 (message "Not restoring clock data; %s not found"
1503 org-clock-persist-file)
1504 (message "%s" "Restoring clock data")
1505 (setq org-clock-loaded t)
1506 (load-file filename)
1507 ;; load history
1508 (when stored-clock-history
1509 (save-window-excursion
1510 (mapc (lambda (task)
1511 (if (file-exists-p (car task))
1512 (org-clock-history-push (cdr task)
1513 (find-file (car task)))))
1514 stored-clock-history)))
1515 ;; resume clock
1516 (when (and resume-clock org-clock-persist
1517 (file-exists-p (car resume-clock))
1518 (or (not org-clock-persist-query-resume)
1519 (y-or-n-p
1520 (concat
1521 "Resume clock ("
1522 (with-current-buffer (find-file (car resume-clock))
1523 (save-excursion
1524 (goto-char (cdr resume-clock))
1525 (org-back-to-heading t)
1526 (and (looking-at org-complex-heading-regexp)
1527 (match-string 4))))
1528 ") "))))
1529 (when (file-exists-p (car resume-clock))
1530 (with-current-buffer (find-file (car resume-clock))
1531 (goto-char (cdr resume-clock))
1532 (org-clock-in)
1533 (if (org-invisible-p)
1534 (org-show-context)))))))))
1536 ;;;###autoload
1537 (defun org-clock-persistence-insinuate ()
1538 "Set up hooks for clock persistence"
1539 (add-hook 'org-mode-hook 'org-clock-load)
1540 (add-hook 'kill-emacs-hook 'org-clock-save))
1542 ;; Suggested bindings
1543 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
1545 (provide 'org-clock)
1547 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1549 ;;; org-clock.el ends here