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