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