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