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