Release 6.08a.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org-clock.el
blob698b79036240ee87c4907feea95dd70ae5c9f225
1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.08a
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains the time clocking code for Org-mode
30 (require 'org)
31 (eval-when-compile
32 (require 'cl)
33 (require 'calendar))
35 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
37 (defgroup org-clock nil
38 "Options concerning clocking working time in Org-mode."
39 :tag "Org Clock"
40 :group 'org-progress)
42 (defcustom org-clock-into-drawer 2
43 "Should clocking info be wrapped into a drawer?
44 When t, clocking info will always be inserted into a :CLOCK: drawer.
45 If necessary, the drawer will be created.
46 When nil, the drawer will not be created, but used when present.
47 When an integer and the number of clocking entries in an item
48 reaches or exceeds this number, a drawer will be created."
49 :group 'org-todo
50 :group 'org-clock
51 :type '(choice
52 (const :tag "Always" t)
53 (const :tag "Only when drawer exists" nil)
54 (integer :tag "When at least N clock entries")))
56 (defcustom org-clock-out-when-done t
57 "When non-nil, the clock will be stopped when the relevant entry is marked DONE.
58 A nil value means, clock will keep running until stopped explicitly with
59 `C-c C-x C-o', or until the clock is started in a different item."
60 :group 'org-clock
61 :type 'boolean)
63 (defcustom org-clock-out-remove-zero-time-clocks nil
64 "Non-nil means, remove the clock line when the resulting time is zero."
65 :group 'org-clock
66 :type 'boolean)
68 (defcustom org-clock-in-switch-to-state nil
69 "Set task to a special todo state while clocking it.
70 The value should be the state to which the entry should be switched."
71 :group 'org-clock
72 :group 'org-todo
73 :type '(choice
74 (const :tag "Don't force a state" nil)
75 (string :tag "State")))
77 (defcustom org-clock-history-length 5
78 "Number of clock tasks to remember in history."
79 :group 'org-clock
80 :type 'integer)
82 (defcustom org-clock-heading-function nil
83 "When non-nil, should be a function to create `org-clock-heading'.
84 This is the string shown in the mode line when a clock is running.
85 The function is called with point at the beginning of the headline."
86 :group 'org-clock
87 :type 'function)
89 (defcustom org-clock-string-limit 0
90 "Maximum length of clock strings in the modeline. 0 means no limit"
91 :group 'org-clock
92 :type 'integer)
94 ;;; The clock for measuring work time.
96 (defvar org-mode-line-string "")
97 (put 'org-mode-line-string 'risky-local-variable t)
99 (defvar org-mode-line-timer nil)
100 (defvar org-clock-heading "")
101 (defvar org-clock-heading-for-remember "")
102 (defvar org-clock-start-time "")
104 (defvar org-clock-history nil
105 "List of marker pointing to recent clocked tasks.")
107 (defvar org-clock-default-task (make-marker)
108 "Marker pointing to the default task that should clock time.
109 The clock can be made to switch to this task after clocking out
110 of a different task.")
112 (defvar org-clock-interrupted-task (make-marker)
113 "Marker pointing to the task that has been interrupted by the current clock.")
115 (defvar org-clock-mode-map (make-sparse-keymap))
116 (define-key org-clock-mode-map [mode-line mouse-2] 'org-clock-goto)
118 (defun org-clock-history-push (&optional pos buffer)
119 "Push a marker to the clock history."
120 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
121 (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
122 (while (setq n (member m org-clock-history))
123 (move-marker (car n) nil))
124 (setq org-clock-history
125 (delq nil
126 (mapcar (lambda (x) (if (marker-buffer x) x nil))
127 org-clock-history)))
128 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
129 (setq org-clock-history
130 (nreverse
131 (nthcdr (- l org-clock-history-length -1)
132 (nreverse org-clock-history)))))
133 (push m org-clock-history)))
135 (defun org-clock-save-markers-for-cut-and-paste (beg end)
136 "Save relative positions of markers in region."
137 (org-check-and-save-marker org-clock-marker beg end)
138 (org-check-and-save-marker org-clock-default-task beg end)
139 (org-check-and-save-marker org-clock-interrupted-task beg end)
140 (mapc (lambda (m) (org-check-and-save-marker m beg end))
141 org-clock-history))
143 (defun org-clock-select-task (&optional prompt)
144 "Select a task that recently was associated with clocking."
145 (interactive)
146 (let (sel-list rpl file task (i 0) s)
147 (save-window-excursion
148 (org-switch-to-buffer-other-window
149 (get-buffer-create "*Clock Task Select*"))
150 (erase-buffer)
151 (when (marker-buffer org-clock-default-task)
152 (insert (org-add-props "Default Task\n" nil 'face 'bold))
153 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
154 (push s sel-list))
155 (when (marker-buffer org-clock-interrupted-task)
156 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
157 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
158 (push s sel-list))
159 (when (marker-buffer org-clock-marker)
160 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
161 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
162 (push s sel-list))
163 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
164 (mapc
165 (lambda (m)
166 (when (marker-buffer m)
167 (setq i (1+ i)
168 s (org-clock-insert-selection-line
169 (if (< i 10)
170 (+ i ?0)
171 (+ i (- ?A 10))) m))
172 (push s sel-list)))
173 org-clock-history)
174 (if (fboundp 'fit-window-to-buffer)
175 (fit-window-to-buffer)
176 (shrink-window-if-larger-than-buffer))
177 (message (or prompt "Select task for clocking:"))
178 (setq rpl (read-char-exclusive))
179 (cond
180 ((eq rpl ?q) nil)
181 ((eq rpl ?x) nil)
182 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
183 (t (error "Invalid task choice %c" rpl))))))
185 (defun org-clock-insert-selection-line (i marker)
186 (when (marker-buffer marker)
187 (let (file cat task)
188 (with-current-buffer (org-base-buffer (marker-buffer marker))
189 (save-excursion
190 (save-restriction
191 (widen)
192 (goto-char marker)
193 (setq file (buffer-file-name (marker-buffer marker))
194 cat (or (org-get-category)
195 (progn (org-refresh-category-properties)
196 (org-get-category)))
197 task (org-get-heading 'notags)))))
198 (when (and cat task)
199 (insert (format "[%c] %-15s %s\n" i cat task))
200 (cons i marker)))))
202 (defun org-update-mode-line ()
203 (let* ((delta (- (time-to-seconds (current-time))
204 (time-to-seconds org-clock-start-time)))
205 (h (floor delta 3600))
206 (m (floor (- delta (* 3600 h)) 60)))
207 (setq org-mode-line-string
208 (org-propertize
209 (let ((clock-string (format (concat "-[" org-time-clocksum-format " (%s)]")
210 h m org-clock-heading))
211 (help-text "Org-mode clock is running. Mouse-2 to go there."))
212 (if (and (> org-clock-string-limit 0)
213 (> (length clock-string) org-clock-string-limit))
214 (org-propertize (substring clock-string 0 org-clock-string-limit)
215 'help-echo (concat help-text ": " org-clock-heading))
216 (org-propertize clock-string 'help-echo help-text)))
217 'local-map org-clock-mode-map
218 'mouse-face '(face mode-line-highlight)))
219 (force-mode-line-update)))
221 (defvar org-clock-mode-line-entry nil
222 "Information for the modeline about the running clock.")
224 (defun org-clock-in (&optional select)
225 "Start the clock on the current item.
226 If necessary, clock-out of the currently active clock.
227 With prefix arg SELECT, offer a list of recently clocked tasks to
228 clock into. When SELECT is `C-u C-u', clock into the current task and mark
229 is as the default task, a special task that will always be offered in
230 the clocking selection, associated with the letter `d'."
231 (interactive "P")
232 (let ((interrupting (marker-buffer org-clock-marker))
233 ts selected-task target-pos)
234 (when (equal select '(4))
235 (setq selected-task (org-clock-select-task "Clock-in on task: "))
236 (if selected-task
237 (setq selected-task (copy-marker selected-task))
238 (error "Abort")))
239 (when interrupting
240 ;; We are interrupting the clocking of a differnt task.
241 ;; Save a marker to this task, so that we can go back.
242 (move-marker org-clock-interrupted-task
243 (marker-position org-clock-marker)
244 (marker-buffer org-clock-marker))
245 (org-clock-out t))
247 (when (equal select '(16))
248 ;; Mark as default clocking task
249 (save-excursion
250 (org-back-to-heading t)
251 (move-marker org-clock-default-task (point))))
253 (setq target-pos (point)) ;; we want to clock in at this location
254 (save-excursion
255 (when (and selected-task (marker-buffer selected-task))
256 ;; There is a selected task, move to the correct buffer
257 ;; and set the new target position.
258 (set-buffer (org-base-buffer (marker-buffer selected-task)))
259 (setq target-pos (marker-position selected-task))
260 (move-marker selected-task nil))
261 (save-excursion
262 (save-restriction
263 (widen)
264 (goto-char target-pos)
265 (org-back-to-heading t)
266 (or interrupting (move-marker org-clock-interrupted-task nil))
267 (org-clock-history-push)
268 (when (and org-clock-in-switch-to-state
269 (not (looking-at (concat outline-regexp "[ \t]*"
270 org-clock-in-switch-to-state
271 "\\>"))))
272 (org-todo org-clock-in-switch-to-state))
273 (setq org-clock-heading-for-remember
274 (and (looking-at org-complex-heading-regexp)
275 (match-end 4)
276 (org-trim (buffer-substring (match-end 1) (match-end 4)))))
277 (setq org-clock-heading
278 (cond ((and org-clock-heading-function
279 (functionp org-clock-heading-function))
280 (funcall org-clock-heading-function))
281 ((looking-at org-complex-heading-regexp)
282 (match-string 4))
283 (t "???")))
284 (setq org-clock-heading (org-propertize org-clock-heading 'face nil))
285 (org-clock-find-position)
287 (insert "\n") (backward-char 1)
288 (indent-relative)
289 (insert org-clock-string " ")
290 (setq org-clock-start-time (current-time))
291 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
292 (move-marker org-clock-marker (point) (buffer-base-buffer))
293 (or global-mode-string (setq global-mode-string '("")))
294 (or (memq 'org-mode-line-string global-mode-string)
295 (setq global-mode-string
296 (append global-mode-string '(org-mode-line-string))))
297 (org-update-mode-line)
298 (setq org-mode-line-timer
299 (run-with-timer 60 60 'org-update-mode-line))
300 (message "Clock started at %s" ts))))))
302 (defun org-clock-find-position ()
303 "Find the location where the next clock line should be inserted."
304 (org-back-to-heading t)
305 (catch 'exit
306 (let ((beg (save-excursion
307 (beginning-of-line 2)
308 (or (bolp) (newline))
309 (point)))
310 (end (progn (outline-next-heading) (point)))
311 (re (concat "^[ \t]*" org-clock-string))
312 (cnt 0)
313 first last)
314 (goto-char beg)
315 (when (eobp) (newline) (setq end (max (point) end)))
316 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
317 ;; we seem to have a CLOCK drawer, so go there.
318 (beginning-of-line 2)
319 (throw 'exit t))
320 ;; Lets count the CLOCK lines
321 (goto-char beg)
322 (while (re-search-forward re end t)
323 (setq first (or first (match-beginning 0))
324 last (match-beginning 0)
325 cnt (1+ cnt)))
326 (when (and (integerp org-clock-into-drawer)
327 (>= (1+ cnt) org-clock-into-drawer))
328 ;; Wrap current entries into a new drawer
329 (goto-char last)
330 (beginning-of-line 2)
331 (if (org-at-item-p) (org-end-of-item))
332 (insert ":END:\n")
333 (beginning-of-line 0)
334 (org-indent-line-function)
335 (goto-char first)
336 (insert ":CLOCK:\n")
337 (beginning-of-line 0)
338 (org-indent-line-function)
339 (org-flag-drawer t)
340 (beginning-of-line 2)
341 (throw 'exit nil))
343 (goto-char beg)
344 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
345 (not (equal (match-string 1) org-clock-string)))
346 ;; Planning info, skip to after it
347 (beginning-of-line 2)
348 (or (bolp) (newline)))
349 (when (eq t org-clock-into-drawer)
350 (insert ":CLOCK:\n:END:\n")
351 (beginning-of-line -1)
352 (org-indent-line-function)
353 (org-flag-drawer t)
354 (beginning-of-line 2)
355 (org-indent-line-function)))))
357 (defun org-clock-out (&optional fail-quietly)
358 "Stop the currently running clock.
359 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
360 (interactive)
361 (catch 'exit
362 (if (not (marker-buffer org-clock-marker))
363 (if fail-quietly (throw 'exit t) (error "No active clock")))
364 (let (ts te s h m remove)
365 (save-excursion
366 (set-buffer (marker-buffer org-clock-marker))
367 (save-restriction
368 (widen)
369 (goto-char org-clock-marker)
370 (beginning-of-line 1)
371 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
372 (equal (match-string 1) org-clock-string))
373 (setq ts (match-string 2))
374 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
375 (goto-char (match-end 0))
376 (delete-region (point) (point-at-eol))
377 (insert "--")
378 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
379 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
380 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
381 h (floor (/ s 3600))
382 s (- s (* 3600 h))
383 m (floor (/ s 60))
384 s (- s (* 60 s)))
385 (insert " => " (format "%2d:%02d" h m))
386 (when (setq remove (and org-clock-out-remove-zero-time-clocks
387 (= (+ h m) 0)))
388 (beginning-of-line 1)
389 (delete-region (point) (point-at-eol))
390 (and (looking-at "\n") (> (point-max) (1+ (point)))
391 (delete-char 1)))
392 (move-marker org-clock-marker nil)
393 (when org-log-note-clock-out
394 (org-add-log-setup 'clock-out nil nil nil
395 (concat "# Task: " (org-get-heading t) "\n\n")))
396 (when org-mode-line-timer
397 (cancel-timer org-mode-line-timer)
398 (setq org-mode-line-timer nil))
399 (setq global-mode-string
400 (delq 'org-mode-line-string global-mode-string))
401 (force-mode-line-update)
402 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
403 (if remove " => LINE REMOVED" "")))))))
405 (defun org-clock-cancel ()
406 "Cancel the running clock be removing the start timestamp."
407 (interactive)
408 (if (not (marker-buffer org-clock-marker))
409 (error "No active clock"))
410 (save-excursion
411 (set-buffer (marker-buffer org-clock-marker))
412 (goto-char org-clock-marker)
413 (delete-region (1- (point-at-bol)) (point-at-eol)))
414 (setq global-mode-string
415 (delq 'org-mode-line-string global-mode-string))
416 (force-mode-line-update)
417 (message "Clock canceled"))
419 (defun org-clock-goto (&optional select)
420 "Go to the currently clocked-in entry.
421 With prefix arg SELECT, offer recently clocked tasks."
422 (interactive "P")
423 (let ((m (if select
424 (org-clock-select-task "Select task to go to: ")
425 org-clock-marker)))
426 (if (not (marker-buffer m))
427 (if select
428 (error "No task selected")
429 (error "No active clock")))
430 (switch-to-buffer (marker-buffer m))
431 (if (or (< m (point-min)) (> m (point-max))) (widen))
432 (goto-char m)
433 (org-show-entry)
434 (org-back-to-heading)
435 (org-cycle-hide-drawers 'children)
436 (recenter)))
438 (defvar org-clock-file-total-minutes nil
439 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
440 (make-variable-buffer-local 'org-clock-file-total-minutes)
442 (defun org-clock-sum (&optional tstart tend)
443 "Sum the times for each subtree.
444 Puts the resulting times in minutes as a text property on each headline."
445 (interactive)
446 (let* ((bmp (buffer-modified-p))
447 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
448 org-clock-string
449 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
450 (lmax 30)
451 (ltimes (make-vector lmax 0))
452 (t1 0)
453 (level 0)
454 ts te dt
455 time)
456 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
457 (save-excursion
458 (goto-char (point-max))
459 (while (re-search-backward re nil t)
460 (cond
461 ((match-end 2)
462 ;; Two time stamps
463 (setq ts (match-string 2)
464 te (match-string 3)
465 ts (time-to-seconds
466 (apply 'encode-time (org-parse-time-string ts)))
467 te (time-to-seconds
468 (apply 'encode-time (org-parse-time-string te)))
469 ts (if tstart (max ts tstart) ts)
470 te (if tend (min te tend) te)
471 dt (- te ts)
472 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
473 ((match-end 4)
474 ;; A naket time
475 (setq t1 (+ t1 (string-to-number (match-string 5))
476 (* 60 (string-to-number (match-string 4))))))
477 (t ;; A headline
478 (setq level (- (match-end 1) (match-beginning 1)))
479 (when (or (> t1 0) (> (aref ltimes level) 0))
480 (loop for l from 0 to level do
481 (aset ltimes l (+ (aref ltimes l) t1)))
482 (setq t1 0 time (aref ltimes level))
483 (loop for l from level to (1- lmax) do
484 (aset ltimes l 0))
485 (goto-char (match-beginning 0))
486 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
487 (setq org-clock-file-total-minutes (aref ltimes 0)))
488 (set-buffer-modified-p bmp)))
490 (defun org-clock-display (&optional total-only)
491 "Show subtree times in the entire buffer.
492 If TOTAL-ONLY is non-nil, only show the total time for the entire file
493 in the echo area."
494 (interactive)
495 (org-remove-clock-overlays)
496 (let (time h m p)
497 (org-clock-sum)
498 (unless total-only
499 (save-excursion
500 (goto-char (point-min))
501 (while (or (and (equal (setq p (point)) (point-min))
502 (get-text-property p :org-clock-minutes))
503 (setq p (next-single-property-change
504 (point) :org-clock-minutes)))
505 (goto-char p)
506 (when (setq time (get-text-property p :org-clock-minutes))
507 (org-put-clock-overlay time (funcall outline-level))))
508 (setq h (/ org-clock-file-total-minutes 60)
509 m (- org-clock-file-total-minutes (* 60 h)))
510 ;; Arrange to remove the overlays upon next change.
511 (when org-remove-highlights-with-change
512 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
513 nil 'local))))
514 (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
516 (defvar org-clock-overlays nil)
517 (make-variable-buffer-local 'org-clock-overlays)
519 (defun org-put-clock-overlay (time &optional level)
520 "Put an overlays on the current line, displaying TIME.
521 If LEVEL is given, prefix time with a corresponding number of stars.
522 This creates a new overlay and stores it in `org-clock-overlays', so that it
523 will be easy to remove."
524 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
525 (l (if level (org-get-valid-level level 0) 0))
526 (fmt (concat "%s " org-time-clocksum-format "%s"))
527 (off 0)
528 ov tx)
529 (org-move-to-column c)
530 (unless (eolp) (skip-chars-backward "^ \t"))
531 (skip-chars-backward " \t")
532 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
533 tx (concat (buffer-substring (1- (point)) (point))
534 (make-string (+ off (max 0 (- c (current-column)))) ?.)
535 (org-add-props (format fmt
536 (make-string l ?*) h m
537 (make-string (- 16 l) ?\ ))
538 '(face secondary-selection))
539 ""))
540 (if (not (featurep 'xemacs))
541 (org-overlay-put ov 'display tx)
542 (org-overlay-put ov 'invisible t)
543 (org-overlay-put ov 'end-glyph (make-glyph tx)))
544 (push ov org-clock-overlays)))
546 (defun org-remove-clock-overlays (&optional beg end noremove)
547 "Remove the occur highlights from the buffer.
548 BEG and END are ignored. If NOREMOVE is nil, remove this function
549 from the `before-change-functions' in the current buffer."
550 (interactive)
551 (unless org-inhibit-highlight-removal
552 (mapc 'org-delete-overlay org-clock-overlays)
553 (setq org-clock-overlays nil)
554 (unless noremove
555 (remove-hook 'before-change-functions
556 'org-remove-clock-overlays 'local))))
558 (defvar state) ;; dynamically scoped into this function
559 (defun org-clock-out-if-current ()
560 "Clock out if the current entry contains the running clock.
561 This is used to stop the clock after a TODO entry is marked DONE,
562 and is only done if the variable `org-clock-out-when-done' is not nil."
563 (when (and org-clock-out-when-done
564 (member state org-done-keywords)
565 (equal (marker-buffer org-clock-marker) (current-buffer))
566 (< (point) org-clock-marker)
567 (> (save-excursion (outline-next-heading) (point))
568 org-clock-marker))
569 ;; Clock out, but don't accept a logging message for this.
570 (let ((org-log-note-clock-out nil))
571 (org-clock-out))))
573 (add-hook 'org-after-todo-state-change-hook
574 'org-clock-out-if-current)
576 ;;;###autoload
577 (defun org-get-clocktable (&rest props)
578 "Get a formatted clocktable with parameters according to PROPS.
579 The table is created in a temporary buffer, fully formatted and
580 fontified, and then returned."
581 ;; Set the defaults
582 (setq props (plist-put props :name "clocktable"))
583 (unless (plist-member props :maxlevel)
584 (setq props (plist-put props :maxlevel 2)))
585 (unless (plist-member props :scope)
586 (setq props (plist-put props :scope 'agenda)))
587 (with-temp-buffer
588 (org-mode)
589 (org-create-dblock props)
590 (org-update-dblock)
591 (font-lock-fontify-buffer)
592 (forward-line 2)
593 (buffer-substring (point) (progn
594 (re-search-forward "^#\\+END" nil t)
595 (point-at-bol)))))
597 (defun org-clock-report (&optional arg)
598 "Create a table containing a report about clocked time.
599 If the cursor is inside an existing clocktable block, then the table
600 will be updated. If not, a new clocktable will be inserted.
601 When called with a prefix argument, move to the first clock table in the
602 buffer and update it."
603 (interactive "P")
604 (org-remove-clock-overlays)
605 (when arg
606 (org-find-dblock "clocktable")
607 (org-show-entry))
608 (if (org-in-clocktable-p)
609 (goto-char (org-in-clocktable-p))
610 (org-create-dblock (list :name "clocktable"
611 :maxlevel 2 :scope 'file)))
612 (org-update-dblock))
614 (defun org-in-clocktable-p ()
615 "Check if the cursor is in a clocktable."
616 (let ((pos (point)) start)
617 (save-excursion
618 (end-of-line 1)
619 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
620 (setq start (match-beginning 0))
621 (re-search-forward "^#\\+END:.*" nil t)
622 (>= (match-end 0) pos)
623 start))))
625 (defun org-clock-special-range (key &optional time as-strings)
626 "Return two times bordering a special time range.
627 Key is a symbol specifying the range and can be one of `today', `yesterday',
628 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
629 A week starts Monday 0:00 and ends Sunday 24:00.
630 The range is determined relative to TIME. TIME defaults to the current time.
631 The return value is a cons cell with two internal times like the ones
632 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
633 the returned times will be formatted strings."
634 (if (integerp key) (setq key (intern (number-to-string key))))
635 (let* ((tm (decode-time (or time (current-time))))
636 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
637 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
638 (dow (nth 6 tm))
639 (skey (symbol-name key))
640 (shift 0)
641 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
642 (cond
643 ((string-match "^[0-9]+$" skey)
644 (setq y (string-to-number skey) m 1 d 1 key 'year))
645 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
646 (setq y (string-to-number (match-string 1 skey))
647 month (string-to-number (match-string 2 skey))
648 d 1 key 'month))
649 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
650 (require 'cal-iso)
651 (setq y (string-to-number (match-string 1 skey))
652 w (string-to-number (match-string 2 skey)))
653 (setq date (calendar-gregorian-from-absolute
654 (calendar-absolute-from-iso (list w 1 y))))
655 (setq d (nth 1 date) month (car date) y (nth 2 date)
656 key 'week))
657 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
658 (setq y (string-to-number (match-string 1 skey))
659 month (string-to-number (match-string 2 skey))
660 d (string-to-number (match-string 3 skey))
661 key 'day))
662 ((string-match "\\([-+][0-9]+\\)$" skey)
663 (setq shift (string-to-number (match-string 1 skey))
664 key (intern (substring skey 0 (match-beginning 1))))))
665 (when (= shift 0)
666 (cond ((eq key 'yesterday) (setq key 'today shift -1))
667 ((eq key 'lastweek) (setq key 'week shift -1))
668 ((eq key 'lastmonth) (setq key 'month shift -1))
669 ((eq key 'lastyear) (setq key 'year shift -1))))
670 (cond
671 ((memq key '(day today))
672 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
673 ((memq key '(week thisweek))
674 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
675 m 0 h 0 d (- d diff) d1 (+ 7 d)))
676 ((memq key '(month thismonth))
677 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
678 ((memq key '(year thisyear))
679 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
680 (t (error "No such time block %s" key)))
681 (setq ts (encode-time s m h d month y)
682 te (encode-time (or s1 s) (or m1 m) (or h1 h)
683 (or d1 d) (or month1 month) (or y1 y)))
684 (setq fm (cdr org-time-stamp-formats))
685 (cond
686 ((memq key '(day today))
687 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
688 ((memq key '(week thisweek))
689 (setq txt (format-time-string "week %G-W%V" ts)))
690 ((memq key '(month thismonth))
691 (setq txt (format-time-string "%B %Y" ts)))
692 ((memq key '(year thisyear))
693 (setq txt (format-time-string "the year %Y" ts))))
694 (if as-strings
695 (list (format-time-string fm ts) (format-time-string fm te) txt)
696 (list ts te txt))))
698 (defun org-clocktable-shift (dir n)
699 "Try to shift the :block date of the clocktable at point.
700 Point must be in the #+BEGIN: line of a clocktable, or this function
701 will throw an error.
702 DIR is a direction, a symbol `left', `right', `up', or `down'.
703 Both `left' and `down' shift the block toward the past, `up' and `right'
704 push it toward the future.
705 N is the number of shift steps to take. The size of the step depends on
706 the currently selected interval size."
707 (setq n (prefix-numeric-value n))
708 (and (memq dir '(left down)) (setq n (- n)))
709 (save-excursion
710 (goto-char (point-at-bol))
711 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
712 (error "Line needs a :block definition before this command works")
713 (let* ((b (match-beginning 1)) (e (match-end 1))
714 (s (match-string 1))
715 block shift ins y mw d date wp m)
716 (cond
717 ((equal s "yesterday") (setq s "today-1"))
718 ((equal s "lastweek") (setq s "thisweek-1"))
719 ((equal s "lastmonth") (setq s "thismonth-1"))
720 ((equal s "lastyear") (setq s "thisyear-1")))
721 (cond
722 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
723 (setq block (match-string 1 s)
724 shift (if (match-end 2)
725 (string-to-number (match-string 2 s))
727 (setq shift (+ shift n))
728 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
729 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
730 ;; 1 1 2 3 3 4 4 5 6 6 5 2
731 (setq y (string-to-number (match-string 1 s))
732 wp (and (match-end 3) (match-string 3 s))
733 mw (and (match-end 4) (string-to-number (match-string 4 s)))
734 d (and (match-end 6) (string-to-number (match-string 6 s))))
735 (cond
736 (d (setq ins (format-time-string
737 "%Y-%m-%d"
738 (encode-time 0 0 0 (+ d n) m y))))
739 ((and wp mw (> (length wp) 0))
740 (require 'cal-iso)
741 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
742 (setq ins (format-time-string
743 "%G-W%V"
744 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
746 (setq ins (format-time-string
747 "%Y-%m"
748 (encode-time 0 0 0 1 (+ mw n) y))))
750 (setq ins (number-to-string (+ y n))))))
751 (t (error "Cannot shift clocktable block")))
752 (when ins
753 (goto-char b)
754 (insert ins)
755 (delete-region (point) (+ (point) (- e b)))
756 (beginning-of-line 1)
757 (org-update-dblock)
758 t)))))
760 (defun org-dblock-write:clocktable (params)
761 "Write the standard clocktable."
762 (catch 'exit
763 (let* ((hlchars '((1 . "*") (2 . "/")))
764 (ins (make-marker))
765 (total-time nil)
766 (scope (plist-get params :scope))
767 (tostring (plist-get params :tostring))
768 (multifile (plist-get params :multifile))
769 (header (plist-get params :header))
770 (maxlevel (or (plist-get params :maxlevel) 3))
771 (step (plist-get params :step))
772 (emph (plist-get params :emphasize))
773 (ts (plist-get params :tstart))
774 (te (plist-get params :tend))
775 (block (plist-get params :block))
776 (link (plist-get params :link))
777 ipos time p level hlc hdl
778 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list)
779 (setq org-clock-file-total-minutes nil)
780 (when step
781 (unless (or block (and ts te))
782 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
783 (org-clocktable-steps params)
784 (throw 'exit nil))
785 (when block
786 (setq cc (org-clock-special-range block nil t)
787 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
788 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
789 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
790 (when (and ts (listp ts))
791 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
792 (when (and te (listp te))
793 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
794 ;; Now the times are strings we can parse.
795 (if ts (setq ts (time-to-seconds
796 (apply 'encode-time (org-parse-time-string ts)))))
797 (if te (setq te (time-to-seconds
798 (apply 'encode-time (org-parse-time-string te)))))
799 (move-marker ins (point))
800 (setq ipos (point))
802 ;; Get the right scope
803 (setq pos (point))
804 (cond
805 ((and scope (listp scope) (symbolp (car scope)))
806 (setq scope (eval scope)))
807 ((eq scope 'agenda)
808 (setq scope (org-agenda-files t)))
809 ((eq scope 'agenda-with-archives)
810 (setq scope (org-agenda-files t))
811 (setq scope (org-add-archive-files scope)))
812 ((eq scope 'file-with-archives)
813 (setq scope (org-add-archive-files (list (buffer-file-name)))
814 rm-file-column t)))
815 (setq scope-is-list (and scope (listp scope)))
816 (save-restriction
817 (cond
818 ((not scope))
819 ((eq scope 'file) (widen))
820 ((eq scope 'subtree) (org-narrow-to-subtree))
821 ((eq scope 'tree)
822 (while (org-up-heading-safe))
823 (org-narrow-to-subtree))
824 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
825 (symbol-name scope)))
826 (setq level (string-to-number (match-string 1 (symbol-name scope))))
827 (catch 'exit
828 (while (org-up-heading-safe)
829 (looking-at outline-regexp)
830 (if (<= (org-reduced-level (funcall outline-level)) level)
831 (throw 'exit nil))))
832 (org-narrow-to-subtree))
833 (scope-is-list
834 (let* ((files scope)
835 (scope 'agenda)
836 (p1 (copy-sequence params))
837 file)
838 (setq p1 (plist-put p1 :tostring t))
839 (setq p1 (plist-put p1 :multifile t))
840 (setq p1 (plist-put p1 :scope 'file))
841 (org-prepare-agenda-buffers files)
842 (while (setq file (pop files))
843 (with-current-buffer (find-buffer-visiting file)
844 (setq tbl1 (org-dblock-write:clocktable p1))
845 (when tbl1
846 (push (org-clocktable-add-file
847 file
848 (concat "| |*File time*|*"
849 (org-minutes-to-hh:mm-string
850 org-clock-file-total-minutes)
851 "*|\n"
852 tbl1)) tbl)
853 (setq total-time (+ (or total-time 0)
854 org-clock-file-total-minutes))))))))
855 (goto-char pos)
857 (unless scope-is-list
858 (org-clock-sum ts te)
859 (goto-char (point-min))
860 (while (setq p (next-single-property-change (point) :org-clock-minutes))
861 (goto-char p)
862 (when (setq time (get-text-property p :org-clock-minutes))
863 (save-excursion
864 (beginning-of-line 1)
865 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
866 (setq level (org-reduced-level
867 (- (match-end 1) (match-beginning 1))))
868 (<= level maxlevel))
869 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
870 hdl (if (not link)
871 (match-string 2)
872 (org-make-link-string
873 (format "file:%s::%s"
874 (buffer-file-name)
875 (save-match-data
876 (org-make-org-heading-search-string
877 (match-string 2))))
878 (match-string 2))))
879 (if (and (not multifile) (= level 1)) (push "|-" tbl))
880 (push (concat
881 "| " (int-to-string level) "|" hlc hdl hlc " |"
882 (make-string (1- level) ?|)
883 hlc (org-minutes-to-hh:mm-string time) hlc
884 " |") tbl))))))
885 (setq tbl (nreverse tbl))
886 (if tostring
887 (if tbl (mapconcat 'identity tbl "\n") nil)
888 (goto-char ins)
889 (insert-before-markers
890 (or header
891 (concat
892 "Clock summary at ["
893 (substring
894 (format-time-string (cdr org-time-stamp-formats))
895 1 -1)
897 (if block (concat ", for " range-text ".") "")
898 "\n\n"))
899 (if scope-is-list "|File" "")
900 "|L|Headline|Time|\n")
901 (setq total-time (or total-time org-clock-file-total-minutes))
902 (insert-before-markers
903 "|-\n|"
904 (if scope-is-list "|" "")
906 "*Total time*| *"
907 (org-minutes-to-hh:mm-string (or total-time 0))
908 "*|\n|-\n")
909 (setq tbl (delq nil tbl))
910 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
911 (equal (substring (car tbl) 0 2) "|-"))
912 (pop tbl))
913 (insert-before-markers (mapconcat
914 'identity (delq nil tbl)
915 (if scope-is-list "\n|-\n" "\n")))
916 (backward-delete-char 1)
917 (goto-char ipos)
918 (skip-chars-forward "^|")
919 (org-table-align)
920 (when rm-file-column
921 (forward-char 1)
922 (org-table-delete-column)))))))
924 (defun org-clocktable-steps (params)
925 (let* ((p1 (copy-sequence params))
926 (ts (plist-get p1 :tstart))
927 (te (plist-get p1 :tend))
928 (step0 (plist-get p1 :step))
929 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
930 (block (plist-get p1 :block))
931 cc range-text)
932 (when block
933 (setq cc (org-clock-special-range block nil t)
934 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
935 (if ts (setq ts (time-to-seconds
936 (apply 'encode-time (org-parse-time-string ts)))))
937 (if te (setq te (time-to-seconds
938 (apply 'encode-time (org-parse-time-string te)))))
939 (setq p1 (plist-put p1 :header ""))
940 (setq p1 (plist-put p1 :step nil))
941 (setq p1 (plist-put p1 :block nil))
942 (while (< ts te)
943 (or (bolp) (insert "\n"))
944 (setq p1 (plist-put p1 :tstart (format-time-string
945 (car org-time-stamp-formats)
946 (seconds-to-time ts))))
947 (setq p1 (plist-put p1 :tend (format-time-string
948 (car org-time-stamp-formats)
949 (seconds-to-time (setq ts (+ ts step))))))
950 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
951 (plist-get p1 :tstart) "\n")
952 (org-dblock-write:clocktable p1)
953 (re-search-forward "#\\+END:")
954 (end-of-line 0))))
957 (defun org-clocktable-add-file (file table)
958 (if table
959 (let ((lines (org-split-string table "\n"))
960 (ff (file-name-nondirectory file)))
961 (mapconcat 'identity
962 (mapcar (lambda (x)
963 (if (string-match org-table-dataline-regexp x)
964 (concat "|" ff x)
966 lines)
967 "\n"))))
969 (provide 'org-clock)
971 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
973 ;;; org-clock.el ends here