Release 6.03.
[org-mode/org-tableheadings.git] / lisp / org-clock.el
blobfe841672b5d34ef6ddd7afa1ffedd0e46f10c4a2
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.03
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 t, the clock will be stopped when the relevant entry is marked DONE.
58 Nil 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 "-[%d:%02d (%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 ta sks 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 "Clock stopped at %s after HH:MM = %d:%02d%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 "Total file time: %d:%02d (%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 (off 0)
503 ov tx)
504 (org-move-to-column c)
505 (unless (eolp) (skip-chars-backward "^ \t"))
506 (skip-chars-backward " \t")
507 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
508 tx (concat (buffer-substring (1- (point)) (point))
509 (make-string (+ off (max 0 (- c (current-column)))) ?.)
510 (org-add-props (format "%s %2d:%02d%s"
511 (make-string l ?*) h m
512 (make-string (- 16 l) ?\ ))
513 '(face secondary-selection))
514 ""))
515 (if (not (featurep 'xemacs))
516 (org-overlay-put ov 'display tx)
517 (org-overlay-put ov 'invisible t)
518 (org-overlay-put ov 'end-glyph (make-glyph tx)))
519 (push ov org-clock-overlays)))
521 (defun org-remove-clock-overlays (&optional beg end noremove)
522 "Remove the occur highlights from the buffer.
523 BEG and END are ignored. If NOREMOVE is nil, remove this function
524 from the `before-change-functions' in the current buffer."
525 (interactive)
526 (unless org-inhibit-highlight-removal
527 (mapc 'org-delete-overlay org-clock-overlays)
528 (setq org-clock-overlays nil)
529 (unless noremove
530 (remove-hook 'before-change-functions
531 'org-remove-clock-overlays 'local))))
533 (defvar state) ;; dynamically scoped into this function
534 (defun org-clock-out-if-current ()
535 "Clock out if the current entry contains the running clock.
536 This is used to stop the clock after a TODO entry is marked DONE,
537 and is only done if the variable `org-clock-out-when-done' is not nil."
538 (when (and org-clock-out-when-done
539 (member state org-done-keywords)
540 (equal (marker-buffer org-clock-marker) (current-buffer))
541 (< (point) org-clock-marker)
542 (> (save-excursion (outline-next-heading) (point))
543 org-clock-marker))
544 ;; Clock out, but don't accept a logging message for this.
545 (let ((org-log-note-clock-out nil))
546 (org-clock-out))))
548 (add-hook 'org-after-todo-state-change-hook
549 'org-clock-out-if-current)
551 ;;;###autoload
552 (defun org-get-clocktable (&rest props)
553 "Get a formatted clocktable with parameters according to PROPS.
554 The table is created in a temporary buffer, fully formatted and
555 fontified, and then returned."
556 ;; Set the defaults
557 (setq props (plist-put props :name "clocktable"))
558 (unless (plist-member props :maxlevel)
559 (setq props (plist-put props :maxlevel 2)))
560 (unless (plist-member props :scope)
561 (setq props (plist-put props :scope 'agenda)))
562 (with-temp-buffer
563 (org-mode)
564 (org-create-dblock props)
565 (org-update-dblock)
566 (font-lock-fontify-buffer)
567 (forward-line 2)
568 (buffer-substring (point) (progn
569 (re-search-forward "^#\\+END" nil t)
570 (point-at-bol)))))
572 (defun org-clock-report (&optional arg)
573 "Create a table containing a report about clocked time.
574 If the cursor is inside an existing clocktable block, then the table
575 will be updated. If not, a new clocktable will be inserted.
576 When called with a prefix argument, move to the first clock table in the
577 buffer and update it."
578 (interactive "P")
579 (org-remove-clock-overlays)
580 (when arg
581 (org-find-dblock "clocktable")
582 (org-show-entry))
583 (if (org-in-clocktable-p)
584 (goto-char (org-in-clocktable-p))
585 (org-create-dblock (list :name "clocktable"
586 :maxlevel 2 :scope 'file)))
587 (org-update-dblock))
589 (defun org-in-clocktable-p ()
590 "Check if the cursor is in a clocktable."
591 (let ((pos (point)) start)
592 (save-excursion
593 (end-of-line 1)
594 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
595 (setq start (match-beginning 0))
596 (re-search-forward "^#\\+END:.*" nil t)
597 (>= (match-end 0) pos)
598 start))))
600 (defun org-clock-special-range (key &optional time as-strings)
601 "Return two times bordering a special time range.
602 Key is a symbol specifying the range and can be one of `today', `yesterday',
603 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
604 A week starts Monday 0:00 and ends Sunday 24:00.
605 The range is determined relative to TIME. TIME defaults to the current time.
606 The return value is a cons cell with two internal times like the ones
607 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
608 the returned times will be formatted strings."
609 (if (integerp key) (setq key (intern (number-to-string key))))
610 (let* ((tm (decode-time (or time (current-time))))
611 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
612 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
613 (dow (nth 6 tm))
614 (skey (symbol-name key))
615 (shift 0)
616 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
617 (cond
618 ((string-match "^[0-9]+$" skey)
619 (setq y (string-to-number skey) m 1 d 1 key 'year))
620 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
621 (setq y (string-to-number (match-string 1 skey))
622 month (string-to-number (match-string 2 skey))
623 d 1 key 'month))
624 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
625 (require 'cal-iso)
626 (setq y (string-to-number (match-string 1 skey))
627 w (string-to-number (match-string 2 skey)))
628 (setq date (calendar-gregorian-from-absolute
629 (calendar-absolute-from-iso (list w 1 y))))
630 (setq d (nth 1 date) month (car date) y (nth 2 date)
631 key 'week))
632 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
633 (setq y (string-to-number (match-string 1 skey))
634 month (string-to-number (match-string 2 skey))
635 d (string-to-number (match-string 3 skey))
636 key 'day))
637 ((string-match "\\([-+][0-9]+\\)$" skey)
638 (setq shift (string-to-number (match-string 1 skey))
639 key (intern (substring skey 0 (match-beginning 1))))))
640 (unless shift
641 (cond ((eq key 'yesterday) (setq key 'today shift -1))
642 ((eq key 'lastweek) (setq key 'week shift -1))
643 ((eq key 'lastmonth) (setq key 'month shift -1))
644 ((eq key 'lastyear) (setq key 'year shift -1))))
645 (cond
646 ((memq key '(day today))
647 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
648 ((memq key '(week thisweek))
649 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
650 m 0 h 0 d (- d diff) d1 (+ 7 d)))
651 ((memq key '(month thismonth))
652 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
653 ((memq key '(year thisyear))
654 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
655 (t (error "No such time block %s" key)))
656 (setq ts (encode-time s m h d month y)
657 te (encode-time (or s1 s) (or m1 m) (or h1 h)
658 (or d1 d) (or month1 month) (or y1 y)))
659 (setq fm (cdr org-time-stamp-formats))
660 (cond
661 ((memq key '(day today))
662 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
663 ((memq key '(week thisweek))
664 (setq txt (format-time-string "week %G-W%V" ts)))
665 ((memq key '(month thismonth))
666 (setq txt (format-time-string "%B %Y" ts)))
667 ((memq key '(year thisyear))
668 (setq txt (format-time-string "the year %Y" ts))))
669 (if as-strings
670 (list (format-time-string fm ts) (format-time-string fm te) txt)
671 (list ts te txt))))
673 (defun org-clocktable-shift (dir n)
674 "Try to shift the :block date of the clocktable at point.
675 Point must be in the #+BEGIN: line of a clocktable, or this function
676 will throw an error.
677 DIR is a direction, a symbol `left', `right', `up', or `down'.
678 Both `left' and `down' shift the block toward the past, `up' and `right'
679 push it toward the future.
680 N is the number of shift steps to take. The size of the step depends on
681 the currently selected interval size."
682 (setq n (prefix-numeric-value n))
683 (and (memq dir '(left down)) (setq n (- n)))
684 (save-excursion
685 (goto-char (point-at-bol))
686 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
687 (error "Line needs a :block definition before this command works")
688 (let* ((b (match-beginning 1)) (e (match-end 1))
689 (s (match-string 1))
690 block shift ins y mw d date wp m)
691 (cond
692 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
693 (setq block (match-string 1 s)
694 shift (if (match-end 2)
695 (string-to-number (match-string 2 s))
697 (setq shift (+ shift n))
698 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
699 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
700 ;; 1 1 2 3 3 4 4 5 6 6 5 2
701 (setq y (string-to-number (match-string 1 s))
702 wp (and (match-end 3) (match-string 3 s))
703 mw (and (match-end 4) (string-to-number (match-string 4 s)))
704 d (and (match-end 6) (string-to-number (match-string 6 s))))
705 (cond
706 (d (setq ins (format-time-string
707 "%Y-%m-%d"
708 (encode-time 0 0 0 (+ d n) m y))))
709 ((and wp mw (> (length wp) 0))
710 (require 'cal-iso)
711 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
712 (setq ins (format-time-string
713 "%G-W%V"
714 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
716 (setq ins (format-time-string
717 "%Y-%m"
718 (encode-time 0 0 0 1 (+ mw n) y))))
720 (setq ins (number-to-string (+ y n))))))
721 (t (error "Cannot shift clocktable block")))
722 (when ins
723 (goto-char b)
724 (insert ins)
725 (delete-region (point) (+ (point) (- e b)))
726 (beginning-of-line 1)
727 (org-update-dblock)
728 t)))))
730 (defun org-dblock-write:clocktable (params)
731 "Write the standard clocktable."
732 (catch 'exit
733 (let* ((hlchars '((1 . "*") (2 . "/")))
734 (ins (make-marker))
735 (total-time nil)
736 (scope (plist-get params :scope))
737 (tostring (plist-get params :tostring))
738 (multifile (plist-get params :multifile))
739 (header (plist-get params :header))
740 (maxlevel (or (plist-get params :maxlevel) 3))
741 (step (plist-get params :step))
742 (emph (plist-get params :emphasize))
743 (ts (plist-get params :tstart))
744 (te (plist-get params :tend))
745 (block (plist-get params :block))
746 (link (plist-get params :link))
747 ipos time p level hlc hdl
748 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list)
749 (setq org-clock-file-total-minutes nil)
750 (when step
751 (unless (or block (and ts te))
752 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
753 (org-clocktable-steps params)
754 (throw 'exit nil))
755 (when block
756 (setq cc (org-clock-special-range block nil t)
757 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
758 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
759 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
760 (when (and ts (listp ts))
761 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
762 (when (and te (listp te))
763 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
764 ;; Now the times are strings we can parse.
765 (if ts (setq ts (time-to-seconds
766 (apply 'encode-time (org-parse-time-string ts)))))
767 (if te (setq te (time-to-seconds
768 (apply 'encode-time (org-parse-time-string te)))))
769 (move-marker ins (point))
770 (setq ipos (point))
772 ;; Get the right scope
773 (setq pos (point))
774 (cond
775 ((and scope (listp scope) (symbolp (car scope)))
776 (setq scope (eval scope)))
777 ((eq scope 'agenda)
778 (setq scope (org-agenda-files t)))
779 ((eq scope 'agenda-with-archives)
780 (setq scope (org-agenda-files t))
781 (setq scope (org-add-archive-files scope)))
782 ((eq scope 'file-with-archives)
783 (setq scope (org-add-archive-files (list (buffer-file-name)))
784 rm-file-column t)))
785 (setq scope-is-list (and scope (listp scope)))
786 (save-restriction
787 (cond
788 ((not scope))
789 ((eq scope 'file) (widen))
790 ((eq scope 'subtree) (org-narrow-to-subtree))
791 ((eq scope 'tree)
792 (while (org-up-heading-safe))
793 (org-narrow-to-subtree))
794 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
795 (symbol-name scope)))
796 (setq level (string-to-number (match-string 1 (symbol-name scope))))
797 (catch 'exit
798 (while (org-up-heading-safe)
799 (looking-at outline-regexp)
800 (if (<= (org-reduced-level (funcall outline-level)) level)
801 (throw 'exit nil))))
802 (org-narrow-to-subtree))
803 (scope-is-list
804 (let* ((files scope)
805 (scope 'agenda)
806 (p1 (copy-sequence params))
807 file)
808 (setq p1 (plist-put p1 :tostring t))
809 (setq p1 (plist-put p1 :multifile t))
810 (setq p1 (plist-put p1 :scope 'file))
811 (org-prepare-agenda-buffers files)
812 (while (setq file (pop files))
813 (with-current-buffer (find-buffer-visiting file)
814 (setq tbl1 (org-dblock-write:clocktable p1))
815 (when tbl1
816 (push (org-clocktable-add-file
817 file
818 (concat "| |*File time*|*"
819 (org-minutes-to-hh:mm-string
820 org-clock-file-total-minutes)
821 "*|\n"
822 tbl1)) tbl)
823 (setq total-time (+ (or total-time 0)
824 org-clock-file-total-minutes))))))))
825 (goto-char pos)
827 (unless scope-is-list
828 (org-clock-sum ts te)
829 (goto-char (point-min))
830 (while (setq p (next-single-property-change (point) :org-clock-minutes))
831 (goto-char p)
832 (when (setq time (get-text-property p :org-clock-minutes))
833 (save-excursion
834 (beginning-of-line 1)
835 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
836 (setq level (org-reduced-level
837 (- (match-end 1) (match-beginning 1))))
838 (<= level maxlevel))
839 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
840 hdl (if (not link)
841 (match-string 2)
842 (org-make-link-string
843 (format "file:%s::%s"
844 (buffer-file-name)
845 (save-match-data
846 (org-make-org-heading-search-string
847 (match-string 2))))
848 (match-string 2))))
849 (if (and (not multifile) (= level 1)) (push "|-" tbl))
850 (push (concat
851 "| " (int-to-string level) "|" hlc hdl hlc " |"
852 (make-string (1- level) ?|)
853 hlc (org-minutes-to-hh:mm-string time) hlc
854 " |") tbl))))))
855 (setq tbl (nreverse tbl))
856 (if tostring
857 (if tbl (mapconcat 'identity tbl "\n") nil)
858 (goto-char ins)
859 (insert-before-markers
860 (or header
861 (concat
862 "Clock summary at ["
863 (substring
864 (format-time-string (cdr org-time-stamp-formats))
865 1 -1)
867 (if block (concat ", for " range-text ".") "")
868 "\n\n"))
869 (if scope-is-list "|File" "")
870 "|L|Headline|Time|\n")
871 (setq total-time (or total-time org-clock-file-total-minutes))
872 (insert-before-markers
873 "|-\n|"
874 (if scope-is-list "|" "")
876 "*Total time*| *"
877 (org-minutes-to-hh:mm-string (or total-time 0))
878 "*|\n|-\n")
879 (setq tbl (delq nil tbl))
880 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
881 (equal (substring (car tbl) 0 2) "|-"))
882 (pop tbl))
883 (insert-before-markers (mapconcat
884 'identity (delq nil tbl)
885 (if scope-is-list "\n|-\n" "\n")))
886 (backward-delete-char 1)
887 (goto-char ipos)
888 (skip-chars-forward "^|")
889 (org-table-align)
890 (when rm-file-column
891 (forward-char 1)
892 (org-table-delete-column)))))))
894 (defun org-clocktable-steps (params)
895 (let* ((p1 (copy-sequence params))
896 (ts (plist-get p1 :tstart))
897 (te (plist-get p1 :tend))
898 (step0 (plist-get p1 :step))
899 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
900 (block (plist-get p1 :block))
901 cc range-text)
902 (when block
903 (setq cc (org-clock-special-range block nil t)
904 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
905 (if ts (setq ts (time-to-seconds
906 (apply 'encode-time (org-parse-time-string ts)))))
907 (if te (setq te (time-to-seconds
908 (apply 'encode-time (org-parse-time-string te)))))
909 (setq p1 (plist-put p1 :header ""))
910 (setq p1 (plist-put p1 :step nil))
911 (setq p1 (plist-put p1 :block nil))
912 (while (< ts te)
913 (or (bolp) (insert "\n"))
914 (setq p1 (plist-put p1 :tstart (format-time-string
915 (car org-time-stamp-formats)
916 (seconds-to-time ts))))
917 (setq p1 (plist-put p1 :tend (format-time-string
918 (car org-time-stamp-formats)
919 (seconds-to-time (setq ts (+ ts step))))))
920 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
921 (plist-get p1 :tstart) "\n")
922 (org-dblock-write:clocktable p1)
923 (re-search-forward "#\\+END:")
924 (end-of-line 0))))
927 (defun org-clocktable-add-file (file table)
928 (if table
929 (let ((lines (org-split-string table "\n"))
930 (ff (file-name-nondirectory file)))
931 (mapconcat 'identity
932 (mapcar (lambda (x)
933 (if (string-match org-table-dataline-regexp x)
934 (concat "|" ff x)
936 lines)
937 "\n"))))
939 (provide 'org-clock)
941 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
943 ;;; org-clock.el ends here