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