New option org-open-directory-means-index-dot-org.
[org-mode.git] / lisp / org-clock.el
blobb46d48638eb086daf0bce787fcd28c3fdc2417f0
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.06pre01
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 (insert ":END:\n")
310 (beginning-of-line 0)
311 (org-indent-line-function)
312 (goto-char first)
313 (insert ":CLOCK:\n")
314 (beginning-of-line 0)
315 (org-indent-line-function)
316 (org-flag-drawer t)
317 (beginning-of-line 2)
318 (throw 'exit nil))
320 (goto-char beg)
321 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
322 (not (equal (match-string 1) org-clock-string)))
323 ;; Planning info, skip to after it
324 (beginning-of-line 2)
325 (or (bolp) (newline)))
326 (when (eq t org-clock-into-drawer)
327 (insert ":CLOCK:\n:END:\n")
328 (beginning-of-line -1)
329 (org-indent-line-function)
330 (org-flag-drawer t)
331 (beginning-of-line 2)
332 (org-indent-line-function)))))
334 (defun org-clock-out (&optional fail-quietly)
335 "Stop the currently running clock.
336 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
337 (interactive)
338 (catch 'exit
339 (if (not (marker-buffer org-clock-marker))
340 (if fail-quietly (throw 'exit t) (error "No active clock")))
341 (let (ts te s h m remove)
342 (save-excursion
343 (set-buffer (marker-buffer org-clock-marker))
344 (save-restriction
345 (widen)
346 (goto-char org-clock-marker)
347 (beginning-of-line 1)
348 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
349 (equal (match-string 1) org-clock-string))
350 (setq ts (match-string 2))
351 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
352 (goto-char (match-end 0))
353 (delete-region (point) (point-at-eol))
354 (insert "--")
355 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
356 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
357 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
358 h (floor (/ s 3600))
359 s (- s (* 3600 h))
360 m (floor (/ s 60))
361 s (- s (* 60 s)))
362 (insert " => " (format "%2d:%02d" h m))
363 (when (setq remove (and org-clock-out-remove-zero-time-clocks
364 (= (+ h m) 0)))
365 (beginning-of-line 1)
366 (delete-region (point) (point-at-eol))
367 (and (looking-at "\n") (> (point-max) (1+ (point)))
368 (delete-char 1)))
369 (move-marker org-clock-marker nil)
370 (when org-log-note-clock-out
371 (org-add-log-setup 'clock-out))
372 (when org-mode-line-timer
373 (cancel-timer org-mode-line-timer)
374 (setq org-mode-line-timer nil))
375 (setq global-mode-string
376 (delq 'org-mode-line-string global-mode-string))
377 (force-mode-line-update)
378 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
379 (if remove " => LINE REMOVED" "")))))))
381 (defun org-clock-cancel ()
382 "Cancel the running clock be removing the start timestamp."
383 (interactive)
384 (if (not (marker-buffer org-clock-marker))
385 (error "No active clock"))
386 (save-excursion
387 (set-buffer (marker-buffer org-clock-marker))
388 (goto-char org-clock-marker)
389 (delete-region (1- (point-at-bol)) (point-at-eol)))
390 (setq global-mode-string
391 (delq 'org-mode-line-string global-mode-string))
392 (force-mode-line-update)
393 (message "Clock canceled"))
395 (defun org-clock-goto (&optional select)
396 "Go to the currently clocked-in entry.
397 With prefix arg SELECT, offer recently clocked tasks."
398 (interactive "P")
399 (let ((m (if select
400 (org-clock-select-task "Select task to go to: ")
401 org-clock-marker)))
402 (if (not (marker-buffer m))
403 (if select
404 (error "No task selected")
405 (error "No active clock")))
406 (switch-to-buffer (marker-buffer m))
407 (if (or (< m (point-min)) (> m (point-max))) (widen))
408 (goto-char m)
409 (org-show-entry)
410 (org-back-to-heading)
411 (org-cycle-hide-drawers 'children)
412 (recenter)))
414 (defvar org-clock-file-total-minutes nil
415 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
416 (make-variable-buffer-local 'org-clock-file-total-minutes)
418 (defun org-clock-sum (&optional tstart tend)
419 "Sum the times for each subtree.
420 Puts the resulting times in minutes as a text property on each headline."
421 (interactive)
422 (let* ((bmp (buffer-modified-p))
423 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
424 org-clock-string
425 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
426 (lmax 30)
427 (ltimes (make-vector lmax 0))
428 (t1 0)
429 (level 0)
430 ts te dt
431 time)
432 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
433 (save-excursion
434 (goto-char (point-max))
435 (while (re-search-backward re nil t)
436 (cond
437 ((match-end 2)
438 ;; Two time stamps
439 (setq ts (match-string 2)
440 te (match-string 3)
441 ts (time-to-seconds
442 (apply 'encode-time (org-parse-time-string ts)))
443 te (time-to-seconds
444 (apply 'encode-time (org-parse-time-string te)))
445 ts (if tstart (max ts tstart) ts)
446 te (if tend (min te tend) te)
447 dt (- te ts)
448 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
449 ((match-end 4)
450 ;; A naket time
451 (setq t1 (+ t1 (string-to-number (match-string 5))
452 (* 60 (string-to-number (match-string 4))))))
453 (t ;; A headline
454 (setq level (- (match-end 1) (match-beginning 1)))
455 (when (or (> t1 0) (> (aref ltimes level) 0))
456 (loop for l from 0 to level do
457 (aset ltimes l (+ (aref ltimes l) t1)))
458 (setq t1 0 time (aref ltimes level))
459 (loop for l from level to (1- lmax) do
460 (aset ltimes l 0))
461 (goto-char (match-beginning 0))
462 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
463 (setq org-clock-file-total-minutes (aref ltimes 0)))
464 (set-buffer-modified-p bmp)))
466 (defun org-clock-display (&optional total-only)
467 "Show subtree times in the entire buffer.
468 If TOTAL-ONLY is non-nil, only show the total time for the entire file
469 in the echo area."
470 (interactive)
471 (org-remove-clock-overlays)
472 (let (time h m p)
473 (org-clock-sum)
474 (unless total-only
475 (save-excursion
476 (goto-char (point-min))
477 (while (or (and (equal (setq p (point)) (point-min))
478 (get-text-property p :org-clock-minutes))
479 (setq p (next-single-property-change
480 (point) :org-clock-minutes)))
481 (goto-char p)
482 (when (setq time (get-text-property p :org-clock-minutes))
483 (org-put-clock-overlay time (funcall outline-level))))
484 (setq h (/ org-clock-file-total-minutes 60)
485 m (- org-clock-file-total-minutes (* 60 h)))
486 ;; Arrange to remove the overlays upon next change.
487 (when org-remove-highlights-with-change
488 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
489 nil 'local))))
490 (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
492 (defvar org-clock-overlays nil)
493 (make-variable-buffer-local 'org-clock-overlays)
495 (defun org-put-clock-overlay (time &optional level)
496 "Put an overlays on the current line, displaying TIME.
497 If LEVEL is given, prefix time with a corresponding number of stars.
498 This creates a new overlay and stores it in `org-clock-overlays', so that it
499 will be easy to remove."
500 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
501 (l (if level (org-get-valid-level level 0) 0))
502 (fmt (concat "%s " org-time-clocksum-format "%s"))
503 (off 0)
504 ov tx)
505 (org-move-to-column c)
506 (unless (eolp) (skip-chars-backward "^ \t"))
507 (skip-chars-backward " \t")
508 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
509 tx (concat (buffer-substring (1- (point)) (point))
510 (make-string (+ off (max 0 (- c (current-column)))) ?.)
511 (org-add-props (format fmt
512 (make-string l ?*) h m
513 (make-string (- 16 l) ?\ ))
514 '(face secondary-selection))
515 ""))
516 (if (not (featurep 'xemacs))
517 (org-overlay-put ov 'display tx)
518 (org-overlay-put ov 'invisible t)
519 (org-overlay-put ov 'end-glyph (make-glyph tx)))
520 (push ov org-clock-overlays)))
522 (defun org-remove-clock-overlays (&optional beg end noremove)
523 "Remove the occur highlights from the buffer.
524 BEG and END are ignored. If NOREMOVE is nil, remove this function
525 from the `before-change-functions' in the current buffer."
526 (interactive)
527 (unless org-inhibit-highlight-removal
528 (mapc 'org-delete-overlay org-clock-overlays)
529 (setq org-clock-overlays nil)
530 (unless noremove
531 (remove-hook 'before-change-functions
532 'org-remove-clock-overlays 'local))))
534 (defvar state) ;; dynamically scoped into this function
535 (defun org-clock-out-if-current ()
536 "Clock out if the current entry contains the running clock.
537 This is used to stop the clock after a TODO entry is marked DONE,
538 and is only done if the variable `org-clock-out-when-done' is not nil."
539 (when (and org-clock-out-when-done
540 (member state org-done-keywords)
541 (equal (marker-buffer org-clock-marker) (current-buffer))
542 (< (point) org-clock-marker)
543 (> (save-excursion (outline-next-heading) (point))
544 org-clock-marker))
545 ;; Clock out, but don't accept a logging message for this.
546 (let ((org-log-note-clock-out nil))
547 (org-clock-out))))
549 (add-hook 'org-after-todo-state-change-hook
550 'org-clock-out-if-current)
552 ;;;###autoload
553 (defun org-get-clocktable (&rest props)
554 "Get a formatted clocktable with parameters according to PROPS.
555 The table is created in a temporary buffer, fully formatted and
556 fontified, and then returned."
557 ;; Set the defaults
558 (setq props (plist-put props :name "clocktable"))
559 (unless (plist-member props :maxlevel)
560 (setq props (plist-put props :maxlevel 2)))
561 (unless (plist-member props :scope)
562 (setq props (plist-put props :scope 'agenda)))
563 (with-temp-buffer
564 (org-mode)
565 (org-create-dblock props)
566 (org-update-dblock)
567 (font-lock-fontify-buffer)
568 (forward-line 2)
569 (buffer-substring (point) (progn
570 (re-search-forward "^#\\+END" nil t)
571 (point-at-bol)))))
573 (defun org-clock-report (&optional arg)
574 "Create a table containing a report about clocked time.
575 If the cursor is inside an existing clocktable block, then the table
576 will be updated. If not, a new clocktable will be inserted.
577 When called with a prefix argument, move to the first clock table in the
578 buffer and update it."
579 (interactive "P")
580 (org-remove-clock-overlays)
581 (when arg
582 (org-find-dblock "clocktable")
583 (org-show-entry))
584 (if (org-in-clocktable-p)
585 (goto-char (org-in-clocktable-p))
586 (org-create-dblock (list :name "clocktable"
587 :maxlevel 2 :scope 'file)))
588 (org-update-dblock))
590 (defun org-in-clocktable-p ()
591 "Check if the cursor is in a clocktable."
592 (let ((pos (point)) start)
593 (save-excursion
594 (end-of-line 1)
595 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
596 (setq start (match-beginning 0))
597 (re-search-forward "^#\\+END:.*" nil t)
598 (>= (match-end 0) pos)
599 start))))
601 (defun org-clock-special-range (key &optional time as-strings)
602 "Return two times bordering a special time range.
603 Key is a symbol specifying the range and can be one of `today', `yesterday',
604 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
605 A week starts Monday 0:00 and ends Sunday 24:00.
606 The range is determined relative to TIME. TIME defaults to the current time.
607 The return value is a cons cell with two internal times like the ones
608 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
609 the returned times will be formatted strings."
610 (if (integerp key) (setq key (intern (number-to-string key))))
611 (let* ((tm (decode-time (or time (current-time))))
612 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
613 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
614 (dow (nth 6 tm))
615 (skey (symbol-name key))
616 (shift 0)
617 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
618 (cond
619 ((string-match "^[0-9]+$" skey)
620 (setq y (string-to-number skey) m 1 d 1 key 'year))
621 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
622 (setq y (string-to-number (match-string 1 skey))
623 month (string-to-number (match-string 2 skey))
624 d 1 key 'month))
625 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
626 (require 'cal-iso)
627 (setq y (string-to-number (match-string 1 skey))
628 w (string-to-number (match-string 2 skey)))
629 (setq date (calendar-gregorian-from-absolute
630 (calendar-absolute-from-iso (list w 1 y))))
631 (setq d (nth 1 date) month (car date) y (nth 2 date)
632 key 'week))
633 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
634 (setq y (string-to-number (match-string 1 skey))
635 month (string-to-number (match-string 2 skey))
636 d (string-to-number (match-string 3 skey))
637 key 'day))
638 ((string-match "\\([-+][0-9]+\\)$" skey)
639 (setq shift (string-to-number (match-string 1 skey))
640 key (intern (substring skey 0 (match-beginning 1))))))
641 (when (= shift 0)
642 (cond ((eq key 'yesterday) (setq key 'today shift -1))
643 ((eq key 'lastweek) (setq key 'week shift -1))
644 ((eq key 'lastmonth) (setq key 'month shift -1))
645 ((eq key 'lastyear) (setq key 'year shift -1))))
646 (cond
647 ((memq key '(day today))
648 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
649 ((memq key '(week thisweek))
650 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
651 m 0 h 0 d (- d diff) d1 (+ 7 d)))
652 ((memq key '(month thismonth))
653 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
654 ((memq key '(year thisyear))
655 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
656 (t (error "No such time block %s" key)))
657 (setq ts (encode-time s m h d month y)
658 te (encode-time (or s1 s) (or m1 m) (or h1 h)
659 (or d1 d) (or month1 month) (or y1 y)))
660 (setq fm (cdr org-time-stamp-formats))
661 (cond
662 ((memq key '(day today))
663 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
664 ((memq key '(week thisweek))
665 (setq txt (format-time-string "week %G-W%V" ts)))
666 ((memq key '(month thismonth))
667 (setq txt (format-time-string "%B %Y" ts)))
668 ((memq key '(year thisyear))
669 (setq txt (format-time-string "the year %Y" ts))))
670 (if as-strings
671 (list (format-time-string fm ts) (format-time-string fm te) txt)
672 (list ts te txt))))
674 (defun org-clocktable-shift (dir n)
675 "Try to shift the :block date of the clocktable at point.
676 Point must be in the #+BEGIN: line of a clocktable, or this function
677 will throw an error.
678 DIR is a direction, a symbol `left', `right', `up', or `down'.
679 Both `left' and `down' shift the block toward the past, `up' and `right'
680 push it toward the future.
681 N is the number of shift steps to take. The size of the step depends on
682 the currently selected interval size."
683 (setq n (prefix-numeric-value n))
684 (and (memq dir '(left down)) (setq n (- n)))
685 (save-excursion
686 (goto-char (point-at-bol))
687 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
688 (error "Line needs a :block definition before this command works")
689 (let* ((b (match-beginning 1)) (e (match-end 1))
690 (s (match-string 1))
691 block shift ins y mw d date wp m)
692 (cond
693 ((equal s "yesterday") (setq s "today-1"))
694 ((equal s "lastweek") (setq s "thisweek-1"))
695 ((equal s "lastmonth") (setq s "thismonth-1"))
696 ((equal s "lastyear") (setq s "thisyear-1")))
697 (cond
698 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
699 (setq block (match-string 1 s)
700 shift (if (match-end 2)
701 (string-to-number (match-string 2 s))
703 (setq shift (+ shift n))
704 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
705 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
706 ;; 1 1 2 3 3 4 4 5 6 6 5 2
707 (setq y (string-to-number (match-string 1 s))
708 wp (and (match-end 3) (match-string 3 s))
709 mw (and (match-end 4) (string-to-number (match-string 4 s)))
710 d (and (match-end 6) (string-to-number (match-string 6 s))))
711 (cond
712 (d (setq ins (format-time-string
713 "%Y-%m-%d"
714 (encode-time 0 0 0 (+ d n) m y))))
715 ((and wp mw (> (length wp) 0))
716 (require 'cal-iso)
717 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
718 (setq ins (format-time-string
719 "%G-W%V"
720 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
722 (setq ins (format-time-string
723 "%Y-%m"
724 (encode-time 0 0 0 1 (+ mw n) y))))
726 (setq ins (number-to-string (+ y n))))))
727 (t (error "Cannot shift clocktable block")))
728 (when ins
729 (goto-char b)
730 (insert ins)
731 (delete-region (point) (+ (point) (- e b)))
732 (beginning-of-line 1)
733 (org-update-dblock)
734 t)))))
736 (defun org-dblock-write:clocktable (params)
737 "Write the standard clocktable."
738 (catch 'exit
739 (let* ((hlchars '((1 . "*") (2 . "/")))
740 (ins (make-marker))
741 (total-time nil)
742 (scope (plist-get params :scope))
743 (tostring (plist-get params :tostring))
744 (multifile (plist-get params :multifile))
745 (header (plist-get params :header))
746 (maxlevel (or (plist-get params :maxlevel) 3))
747 (step (plist-get params :step))
748 (emph (plist-get params :emphasize))
749 (ts (plist-get params :tstart))
750 (te (plist-get params :tend))
751 (block (plist-get params :block))
752 (link (plist-get params :link))
753 ipos time p level hlc hdl
754 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list)
755 (setq org-clock-file-total-minutes nil)
756 (when step
757 (unless (or block (and ts te))
758 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
759 (org-clocktable-steps params)
760 (throw 'exit nil))
761 (when block
762 (setq cc (org-clock-special-range block nil t)
763 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
764 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
765 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
766 (when (and ts (listp ts))
767 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
768 (when (and te (listp te))
769 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
770 ;; Now the times are strings we can parse.
771 (if ts (setq ts (time-to-seconds
772 (apply 'encode-time (org-parse-time-string ts)))))
773 (if te (setq te (time-to-seconds
774 (apply 'encode-time (org-parse-time-string te)))))
775 (move-marker ins (point))
776 (setq ipos (point))
778 ;; Get the right scope
779 (setq pos (point))
780 (cond
781 ((and scope (listp scope) (symbolp (car scope)))
782 (setq scope (eval scope)))
783 ((eq scope 'agenda)
784 (setq scope (org-agenda-files t)))
785 ((eq scope 'agenda-with-archives)
786 (setq scope (org-agenda-files t))
787 (setq scope (org-add-archive-files scope)))
788 ((eq scope 'file-with-archives)
789 (setq scope (org-add-archive-files (list (buffer-file-name)))
790 rm-file-column t)))
791 (setq scope-is-list (and scope (listp scope)))
792 (save-restriction
793 (cond
794 ((not scope))
795 ((eq scope 'file) (widen))
796 ((eq scope 'subtree) (org-narrow-to-subtree))
797 ((eq scope 'tree)
798 (while (org-up-heading-safe))
799 (org-narrow-to-subtree))
800 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
801 (symbol-name scope)))
802 (setq level (string-to-number (match-string 1 (symbol-name scope))))
803 (catch 'exit
804 (while (org-up-heading-safe)
805 (looking-at outline-regexp)
806 (if (<= (org-reduced-level (funcall outline-level)) level)
807 (throw 'exit nil))))
808 (org-narrow-to-subtree))
809 (scope-is-list
810 (let* ((files scope)
811 (scope 'agenda)
812 (p1 (copy-sequence params))
813 file)
814 (setq p1 (plist-put p1 :tostring t))
815 (setq p1 (plist-put p1 :multifile t))
816 (setq p1 (plist-put p1 :scope 'file))
817 (org-prepare-agenda-buffers files)
818 (while (setq file (pop files))
819 (with-current-buffer (find-buffer-visiting file)
820 (setq tbl1 (org-dblock-write:clocktable p1))
821 (when tbl1
822 (push (org-clocktable-add-file
823 file
824 (concat "| |*File time*|*"
825 (org-minutes-to-hh:mm-string
826 org-clock-file-total-minutes)
827 "*|\n"
828 tbl1)) tbl)
829 (setq total-time (+ (or total-time 0)
830 org-clock-file-total-minutes))))))))
831 (goto-char pos)
833 (unless scope-is-list
834 (org-clock-sum ts te)
835 (goto-char (point-min))
836 (while (setq p (next-single-property-change (point) :org-clock-minutes))
837 (goto-char p)
838 (when (setq time (get-text-property p :org-clock-minutes))
839 (save-excursion
840 (beginning-of-line 1)
841 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
842 (setq level (org-reduced-level
843 (- (match-end 1) (match-beginning 1))))
844 (<= level maxlevel))
845 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
846 hdl (if (not link)
847 (match-string 2)
848 (org-make-link-string
849 (format "file:%s::%s"
850 (buffer-file-name)
851 (save-match-data
852 (org-make-org-heading-search-string
853 (match-string 2))))
854 (match-string 2))))
855 (if (and (not multifile) (= level 1)) (push "|-" tbl))
856 (push (concat
857 "| " (int-to-string level) "|" hlc hdl hlc " |"
858 (make-string (1- level) ?|)
859 hlc (org-minutes-to-hh:mm-string time) hlc
860 " |") tbl))))))
861 (setq tbl (nreverse tbl))
862 (if tostring
863 (if tbl (mapconcat 'identity tbl "\n") nil)
864 (goto-char ins)
865 (insert-before-markers
866 (or header
867 (concat
868 "Clock summary at ["
869 (substring
870 (format-time-string (cdr org-time-stamp-formats))
871 1 -1)
873 (if block (concat ", for " range-text ".") "")
874 "\n\n"))
875 (if scope-is-list "|File" "")
876 "|L|Headline|Time|\n")
877 (setq total-time (or total-time org-clock-file-total-minutes))
878 (insert-before-markers
879 "|-\n|"
880 (if scope-is-list "|" "")
882 "*Total time*| *"
883 (org-minutes-to-hh:mm-string (or total-time 0))
884 "*|\n|-\n")
885 (setq tbl (delq nil tbl))
886 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
887 (equal (substring (car tbl) 0 2) "|-"))
888 (pop tbl))
889 (insert-before-markers (mapconcat
890 'identity (delq nil tbl)
891 (if scope-is-list "\n|-\n" "\n")))
892 (backward-delete-char 1)
893 (goto-char ipos)
894 (skip-chars-forward "^|")
895 (org-table-align)
896 (when rm-file-column
897 (forward-char 1)
898 (org-table-delete-column)))))))
900 (defun org-clocktable-steps (params)
901 (let* ((p1 (copy-sequence params))
902 (ts (plist-get p1 :tstart))
903 (te (plist-get p1 :tend))
904 (step0 (plist-get p1 :step))
905 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
906 (block (plist-get p1 :block))
907 cc range-text)
908 (when block
909 (setq cc (org-clock-special-range block nil t)
910 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
911 (if ts (setq ts (time-to-seconds
912 (apply 'encode-time (org-parse-time-string ts)))))
913 (if te (setq te (time-to-seconds
914 (apply 'encode-time (org-parse-time-string te)))))
915 (setq p1 (plist-put p1 :header ""))
916 (setq p1 (plist-put p1 :step nil))
917 (setq p1 (plist-put p1 :block nil))
918 (while (< ts te)
919 (or (bolp) (insert "\n"))
920 (setq p1 (plist-put p1 :tstart (format-time-string
921 (car org-time-stamp-formats)
922 (seconds-to-time ts))))
923 (setq p1 (plist-put p1 :tend (format-time-string
924 (car org-time-stamp-formats)
925 (seconds-to-time (setq ts (+ ts step))))))
926 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
927 (plist-get p1 :tstart) "\n")
928 (org-dblock-write:clocktable p1)
929 (re-search-forward "#\\+END:")
930 (end-of-line 0))))
933 (defun org-clocktable-add-file (file table)
934 (if table
935 (let ((lines (org-split-string table "\n"))
936 (ff (file-name-nondirectory file)))
937 (mapconcat 'identity
938 (mapcar (lambda (x)
939 (if (string-match org-table-dataline-regexp x)
940 (concat "|" ff x)
942 lines)
943 "\n"))))
945 (provide 'org-clock)
947 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
949 ;;; org-clock.el ends here