1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the time clocking code for Org-mode
36 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
37 (defvar org-time-stamp-formats
)
39 (defgroup org-clock nil
40 "Options concerning clocking working time in Org-mode."
44 (defcustom org-clock-into-drawer org-log-into-drawer
45 "Should clocking info be wrapped into a drawer?
46 When t, clocking info will always be inserted into a :LOGBOOK: 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 When a string, it names the drawer to be used.
53 The default for this variable is the value of `org-log-into-drawer',
58 (const :tag
"Always" t
)
59 (const :tag
"Only when drawer exists" nil
)
60 (integer :tag
"When at least N clock entries")
61 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
62 (string :tag
"Into Drawer named...")))
64 (defcustom org-clock-out-when-done t
65 "When non-nil, the clock will be stopped when the relevant entry is marked DONE.
66 A nil value means, clock will keep running until stopped explicitly with
67 `C-c C-x C-o', or until the clock is started in a different item."
71 (defcustom org-clock-out-remove-zero-time-clocks nil
72 "Non-nil means, remove the clock line when the resulting time is zero."
76 (defcustom org-clock-in-switch-to-state nil
77 "Set task to a special todo state while clocking it.
78 The value should be the state to which the entry should be
79 switched. If the value is a function, it must take one
80 parameter (the current TODO state of the item) and return the
81 state to switch it to."
85 (const :tag
"Don't force a state" nil
)
87 (symbol :tag
"Function")))
89 (defcustom org-clock-history-length
5
90 "Number of clock tasks to remember in history."
94 (defcustom org-clock-heading-function nil
95 "When non-nil, should be a function to create `org-clock-heading'.
96 This is the string shown in the mode line when a clock is running.
97 The function is called with point at the beginning of the headline."
101 (defcustom org-clock-string-limit
0
102 "Maximum length of clock strings in the modeline. 0 means no limit"
106 (defcustom org-clock-in-resume nil
107 "If non-nil, when clocking into a task with a clock entry which
108 has not been closed, resume the clock from that point"
112 (defcustom org-clock-persist nil
113 "When non-nil, save the running clock when emacs is closed, and
114 resume it next time emacs is started.
115 When this is t, both the running clock, and the entire clock
116 history are saved. When this is the symbol `clock', only the
117 running clock is saved.
119 When Emacs restarts with saved clock information, the file containing the
120 running clock as well as all files mentioned in the clock history will
124 (const :tag
"Just the running clock" clock
)
125 (const :tag
"Clock and history" t
)
126 (const :tag
"No persistence" nil
)))
128 (defcustom org-clock-persist-file
(convert-standard-filename
129 "~/.emacs.d/org-clock-save.el")
130 "File to save clock data to"
134 (defcustom org-clock-persist-query-save nil
135 "When non-nil, ask before saving the current clock on exit"
139 (defcustom org-clock-persist-query-resume t
140 "When non-nil, ask before resuming any stored clock during
145 ;;; The clock for measuring work time.
147 (defvar org-mode-line-string
"")
148 (put 'org-mode-line-string
'risky-local-variable t
)
150 (defvar org-clock-mode-line-timer nil
)
151 (defvar org-clock-heading
"")
152 (defvar org-clock-heading-for-remember
"")
153 (defvar org-clock-start-time
"")
155 (defvar org-clock-history nil
156 "List of marker pointing to recent clocked tasks.")
158 (defvar org-clock-default-task
(make-marker)
159 "Marker pointing to the default task that should clock time.
160 The clock can be made to switch to this task after clocking out
161 of a different task.")
163 (defvar org-clock-interrupted-task
(make-marker)
164 "Marker pointing to the task that has been interrupted by the current clock.")
166 (defvar org-clock-mode-line-map
(make-sparse-keymap))
167 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
169 (defun org-clock-history-push (&optional pos buffer
)
170 "Push a marker to the clock history."
171 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
172 (let ((m (move-marker (make-marker) (or pos
(point)) buffer
)) n l
)
173 (while (setq n
(member m org-clock-history
))
174 (move-marker (car n
) nil
))
175 (setq org-clock-history
177 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
179 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
180 (setq org-clock-history
182 (nthcdr (- l org-clock-history-length -
1)
183 (nreverse org-clock-history
)))))
184 (push m org-clock-history
)))
186 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
187 "Save relative positions of markers in region."
188 (org-check-and-save-marker org-clock-marker beg end
)
189 (org-check-and-save-marker org-clock-default-task beg end
)
190 (org-check-and-save-marker org-clock-interrupted-task beg end
)
191 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
194 (defun org-clock-select-task (&optional prompt
)
195 "Select a task that recently was associated with clocking."
197 (let (sel-list rpl
(i 0) s
)
198 (save-window-excursion
199 (org-switch-to-buffer-other-window
200 (get-buffer-create "*Clock Task Select*"))
202 (when (marker-buffer org-clock-default-task
)
203 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
204 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
206 (when (marker-buffer org-clock-interrupted-task
)
207 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
208 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
210 (when (marker-buffer org-clock-marker
)
211 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
212 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
214 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
217 (when (marker-buffer m
)
219 s
(org-clock-insert-selection-line
225 (org-fit-window-to-buffer)
226 (message (or prompt
"Select task for clocking:"))
227 (setq rpl
(read-char-exclusive))
231 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
232 (t (error "Invalid task choice %c" rpl
))))))
234 (defun org-clock-insert-selection-line (i marker
)
235 (when (marker-buffer marker
)
237 (with-current-buffer (org-base-buffer (marker-buffer marker
))
242 (setq file
(buffer-file-name (marker-buffer marker
))
243 cat
(or (org-get-category)
244 (progn (org-refresh-category-properties)
246 task
(org-get-heading 'notags
)))))
248 (insert (format "[%c] %-15s %s\n" i cat task
))
251 (defun org-clock-update-mode-line ()
252 (let* ((delta (- (time-to-seconds (current-time))
253 (time-to-seconds org-clock-start-time
)))
254 (h (floor delta
3600))
255 (m (floor (- delta
(* 3600 h
)) 60)))
256 (setq org-mode-line-string
258 (let ((clock-string (format (concat "-[" org-time-clocksum-format
" (%s)]")
259 h m org-clock-heading
))
260 (help-text "Org-mode clock is running. Mouse-2 to go there."))
261 (if (and (> org-clock-string-limit
0)
262 (> (length clock-string
) org-clock-string-limit
))
263 (org-propertize (substring clock-string
0 org-clock-string-limit
)
264 'help-echo
(concat help-text
": " org-clock-heading
))
265 (org-propertize clock-string
'help-echo help-text
)))
266 'local-map org-clock-mode-line-map
267 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)))
268 (force-mode-line-update)))
270 (defvar org-clock-mode-line-entry nil
271 "Information for the modeline about the running clock.")
273 (defun org-clock-in (&optional select
)
274 "Start the clock on the current item.
275 If necessary, clock-out of the currently active clock.
276 With prefix arg SELECT, offer a list of recently clocked tasks to
277 clock into. When SELECT is `C-u C-u', clock into the current task and mark
278 is as the default task, a special task that will always be offered in
279 the clocking selection, associated with the letter `d'."
282 (let ((interrupting (marker-buffer org-clock-marker
))
283 ts selected-task target-pos
)
284 (when (equal select
'(4))
285 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
287 (setq selected-task
(copy-marker selected-task
))
290 ;; We are interrupting the clocking of a different task.
291 ;; Save a marker to this task, so that we can go back.
292 (move-marker org-clock-interrupted-task
293 (marker-position org-clock-marker
)
294 (marker-buffer org-clock-marker
))
297 (when (equal select
'(16))
298 ;; Mark as default clocking task
300 (org-back-to-heading t
)
301 (move-marker org-clock-default-task
(point))))
303 (setq target-pos
(point)) ;; we want to clock in at this location
305 (when (and selected-task
(marker-buffer selected-task
))
306 ;; There is a selected task, move to the correct buffer
307 ;; and set the new target position.
308 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
309 (setq target-pos
(marker-position selected-task
))
310 (move-marker selected-task nil
))
314 (goto-char target-pos
)
315 (org-back-to-heading t
)
316 (or interrupting
(move-marker org-clock-interrupted-task nil
))
317 (org-clock-history-push)
318 (cond ((functionp org-clock-in-switch-to-state
)
319 (looking-at org-complex-heading-regexp
)
320 (let ((newstate (funcall org-clock-in-switch-to-state
322 (if newstate
(org-todo newstate
))))
323 ((and org-clock-in-switch-to-state
324 (not (looking-at (concat outline-regexp
"[ \t]*"
325 org-clock-in-switch-to-state
327 (org-todo org-clock-in-switch-to-state
)))
328 (setq org-clock-heading-for-remember
329 (and (looking-at org-complex-heading-regexp
)
331 (org-trim (buffer-substring (match-end 1)
333 (setq org-clock-heading
334 (cond ((and org-clock-heading-function
335 (functionp org-clock-heading-function
))
336 (funcall org-clock-heading-function
))
337 ((looking-at org-complex-heading-regexp
)
340 (setq org-clock-heading
(org-propertize org-clock-heading
342 (org-clock-find-position)
344 ((and org-clock-in-resume
346 (concat "^[ \\t]* " org-clock-string
347 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
348 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
349 (message "Matched %s" (match-string 1))
350 (setq ts
(concat "[" (match-string 1) "]"))
351 (goto-char (match-end 1))
352 (setq org-clock-start-time
354 (org-parse-time-string (match-string 1)))))
355 ((eq org-clock-in-resume
'auto-restart
)
356 ;; called from org-clock-load during startup,
357 ;; do not interrupt, but warn!
358 (message "Cannot restart clock because task does not contain unfinished clock")
363 (insert-before-markers "\n")
365 (org-indent-line-function)
366 (when (and (save-excursion
369 (beginning-of-line 1)
370 (org-indent-line-to (- (org-get-indentation) 2)))
371 (insert org-clock-string
" ")
372 (setq org-clock-start-time
(current-time))
373 (setq ts
(org-insert-time-stamp org-clock-start-time
'with-hm
'inactive
))))
374 (move-marker org-clock-marker
(point) (buffer-base-buffer))
375 (or global-mode-string
(setq global-mode-string
'("")))
376 (or (memq 'org-mode-line-string global-mode-string
)
377 (setq global-mode-string
378 (append global-mode-string
'(org-mode-line-string))))
379 (org-clock-update-mode-line)
380 (setq org-clock-mode-line-timer
381 (run-with-timer 60 60 'org-clock-update-mode-line
))
382 (message "Clock started at %s" ts
)))))))
384 (defun org-clock-find-position ()
385 "Find the location where the next clock line should be inserted."
386 (org-back-to-heading t
)
388 (let ((beg (save-excursion
389 (beginning-of-line 2)
390 (or (bolp) (newline))
392 (end (progn (outline-next-heading) (point)))
393 (re (concat "^[ \t]*" org-clock-string
))
395 (drawer (if (stringp org-clock-into-drawer
)
396 org-clock-into-drawer
"LOGBOOK"))
399 (when (eobp) (newline) (setq end
(max (point) end
)))
400 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
401 ;; we seem to have a CLOCK drawer, so go there.
402 (beginning-of-line 2)
403 (or org-log-states-order-reversed
404 (and (re-search-forward org-property-end-re nil t
)
405 (goto-char (match-beginning 0))))
407 ;; Lets count the CLOCK lines
409 (while (re-search-forward re end t
)
410 (setq first
(or first
(match-beginning 0))
411 last
(match-beginning 0)
413 (when (and (integerp org-clock-into-drawer
)
415 (>= (1+ cnt
) org-clock-into-drawer
))
416 ;; Wrap current entries into a new drawer
418 (setq ind-last
(org-get-indentation))
419 (beginning-of-line 2)
420 (if (and (>= (org-get-indentation) ind-last
)
424 (beginning-of-line 0)
425 (org-indent-line-to ind-last
)
427 (insert ":" drawer
":\n")
428 (beginning-of-line 0)
429 (org-indent-line-function)
431 (beginning-of-line 2)
432 (or org-log-states-order-reversed
433 (and (re-search-forward org-property-end-re nil t
)
434 (goto-char (match-beginning 0))))
438 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
439 (not (equal (match-string 1) org-clock-string
)))
440 ;; Planning info, skip to after it
441 (beginning-of-line 2)
442 (or (bolp) (newline)))
443 (when (or (eq org-clock-into-drawer t
)
444 (stringp org-clock-into-drawer
)
445 (and (integerp org-clock-into-drawer
)
446 (< org-clock-into-drawer
2)))
447 (insert ":" drawer
":\n:END:\n")
448 (beginning-of-line -
1)
449 (org-indent-line-function)
451 (beginning-of-line 2)
452 (org-indent-line-function)
454 (or org-log-states-order-reversed
455 (and (re-search-forward org-property-end-re nil t
)
456 (goto-char (match-beginning 0))))))))
458 (defun org-clock-out (&optional fail-quietly
)
459 "Stop the currently running clock.
460 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
463 (if (not (marker-buffer org-clock-marker
))
464 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
465 (let (ts te s h m remove
)
467 (set-buffer (marker-buffer org-clock-marker
))
470 (goto-char org-clock-marker
)
471 (beginning-of-line 1)
472 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
473 (equal (match-string 1) org-clock-string
))
474 (setq ts
(match-string 2))
475 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
476 (goto-char (match-end 0))
477 (delete-region (point) (point-at-eol))
479 (setq te
(org-insert-time-stamp (current-time) 'with-hm
'inactive
))
480 (setq s
(- (time-to-seconds (apply 'encode-time
(org-parse-time-string te
)))
481 (time-to-seconds (apply 'encode-time
(org-parse-time-string ts
))))
486 (insert " => " (format "%2d:%02d" h m
))
487 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
489 (beginning-of-line 1)
490 (delete-region (point) (point-at-eol))
491 (and (looking-at "\n") (> (point-max) (1+ (point)))
493 (move-marker org-clock-marker nil
)
494 (when org-log-note-clock-out
495 (org-add-log-setup 'clock-out nil nil nil nil
496 (concat "# Task: " (org-get-heading t
) "\n\n")))
497 (when org-clock-mode-line-timer
498 (cancel-timer org-clock-mode-line-timer
)
499 (setq org-clock-mode-line-timer nil
))
500 (setq global-mode-string
501 (delq 'org-mode-line-string global-mode-string
))
502 (force-mode-line-update)
503 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
504 (if remove
" => LINE REMOVED" "")))))))
506 (defun org-clock-cancel ()
507 "Cancel the running clock be removing the start timestamp."
509 (if (not (marker-buffer org-clock-marker
))
510 (error "No active clock"))
512 (set-buffer (marker-buffer org-clock-marker
))
513 (goto-char org-clock-marker
)
514 (delete-region (1- (point-at-bol)) (point-at-eol)))
515 (setq global-mode-string
516 (delq 'org-mode-line-string global-mode-string
))
517 (force-mode-line-update)
518 (message "Clock canceled"))
520 (defun org-clock-goto (&optional select
)
521 "Go to the currently clocked-in entry.
522 With prefix arg SELECT, offer recently clocked tasks."
525 (org-clock-select-task "Select task to go to: ")
527 (if (not (marker-buffer m
))
529 (error "No task selected")
530 (error "No active clock")))
531 (switch-to-buffer (marker-buffer m
))
532 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
535 (org-back-to-heading)
536 (org-cycle-hide-drawers 'children
)
539 (defvar org-clock-file-total-minutes nil
540 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
541 (make-variable-buffer-local 'org-clock-file-total-minutes
)
543 (defun org-clock-sum (&optional tstart tend
)
544 "Sum the times for each subtree.
545 Puts the resulting times in minutes as a text property on each headline."
547 (let* ((bmp (buffer-modified-p))
548 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
550 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
552 (ltimes (make-vector lmax
0))
557 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
559 (goto-char (point-max))
560 (while (re-search-backward re nil t
)
564 (setq ts
(match-string 2)
567 (apply 'encode-time
(org-parse-time-string ts
)))
569 (apply 'encode-time
(org-parse-time-string te
)))
570 ts
(if tstart
(max ts tstart
) ts
)
571 te
(if tend
(min te tend
) te
)
573 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
576 (setq t1
(+ t1
(string-to-number (match-string 5))
577 (* 60 (string-to-number (match-string 4))))))
579 (setq level
(- (match-end 1) (match-beginning 1)))
580 (when (or (> t1
0) (> (aref ltimes level
) 0))
581 (loop for l from
0 to level do
582 (aset ltimes l
(+ (aref ltimes l
) t1
)))
583 (setq t1
0 time
(aref ltimes level
))
584 (loop for l from level to
(1- lmax
) do
586 (goto-char (match-beginning 0))
587 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
588 (setq org-clock-file-total-minutes
(aref ltimes
0)))
589 (set-buffer-modified-p bmp
)))
591 (defun org-clock-display (&optional total-only
)
592 "Show subtree times in the entire buffer.
593 If TOTAL-ONLY is non-nil, only show the total time for the entire file
596 (org-clock-remove-overlays)
601 (goto-char (point-min))
602 (while (or (and (equal (setq p
(point)) (point-min))
603 (get-text-property p
:org-clock-minutes
))
604 (setq p
(next-single-property-change
605 (point) :org-clock-minutes
)))
607 (when (setq time
(get-text-property p
:org-clock-minutes
))
608 (org-clock-put-overlay time
(funcall outline-level
))))
609 (setq h
(/ org-clock-file-total-minutes
60)
610 m
(- org-clock-file-total-minutes
(* 60 h
)))
611 ;; Arrange to remove the overlays upon next change.
612 (when org-remove-highlights-with-change
613 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
615 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
617 (defvar org-clock-overlays nil
)
618 (make-variable-buffer-local 'org-clock-overlays
)
620 (defun org-clock-put-overlay (time &optional level
)
621 "Put an overlays on the current line, displaying TIME.
622 If LEVEL is given, prefix time with a corresponding number of stars.
623 This creates a new overlay and stores it in `org-clock-overlays', so that it
624 will be easy to remove."
625 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
626 (l (if level
(org-get-valid-level level
0) 0))
627 (fmt (concat "%s " org-time-clocksum-format
"%s"))
630 (org-move-to-column c
)
631 (unless (eolp) (skip-chars-backward "^ \t"))
632 (skip-chars-backward " \t")
633 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
634 tx
(concat (buffer-substring (1- (point)) (point))
635 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
636 (org-add-props (format fmt
637 (make-string l ?
*) h m
638 (make-string (- 16 l
) ?\
))
639 (list 'face
'org-clock-overlay
))
641 (if (not (featurep 'xemacs
))
642 (org-overlay-put ov
'display tx
)
643 (org-overlay-put ov
'invisible t
)
644 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
645 (push ov org-clock-overlays
)))
647 (defun org-clock-remove-overlays (&optional beg end noremove
)
648 "Remove the occur highlights from the buffer.
649 BEG and END are ignored. If NOREMOVE is nil, remove this function
650 from the `before-change-functions' in the current buffer."
652 (unless org-inhibit-highlight-removal
653 (mapc 'org-delete-overlay org-clock-overlays
)
654 (setq org-clock-overlays nil
)
656 (remove-hook 'before-change-functions
657 'org-clock-remove-overlays
'local
))))
659 (defvar state
) ;; dynamically scoped into this function
660 (defun org-clock-out-if-current ()
661 "Clock out if the current entry contains the running clock.
662 This is used to stop the clock after a TODO entry is marked DONE,
663 and is only done if the variable `org-clock-out-when-done' is not nil."
664 (when (and org-clock-out-when-done
665 (member state org-done-keywords
)
666 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker
))
667 (marker-buffer org-clock-marker
))
668 (or (buffer-base-buffer (current-buffer))
670 (< (point) org-clock-marker
)
671 (> (save-excursion (outline-next-heading) (point))
673 ;; Clock out, but don't accept a logging message for this.
674 (let ((org-log-note-clock-out nil
))
677 (add-hook 'org-after-todo-state-change-hook
678 'org-clock-out-if-current
)
681 (defun org-get-clocktable (&rest props
)
682 "Get a formatted clocktable with parameters according to PROPS.
683 The table is created in a temporary buffer, fully formatted and
684 fontified, and then returned."
686 (setq props
(plist-put props
:name
"clocktable"))
687 (unless (plist-member props
:maxlevel
)
688 (setq props
(plist-put props
:maxlevel
2)))
689 (unless (plist-member props
:scope
)
690 (setq props
(plist-put props
:scope
'agenda
)))
693 (org-create-dblock props
)
695 (font-lock-fontify-buffer)
697 (buffer-substring (point) (progn
698 (re-search-forward "^#\\+END" nil t
)
701 (defun org-clock-report (&optional arg
)
702 "Create a table containing a report about clocked time.
703 If the cursor is inside an existing clocktable block, then the table
704 will be updated. If not, a new clocktable will be inserted.
705 When called with a prefix argument, move to the first clock table in the
706 buffer and update it."
708 (org-clock-remove-overlays)
710 (org-find-dblock "clocktable")
712 (if (org-in-clocktable-p)
713 (goto-char (org-in-clocktable-p))
714 (org-create-dblock (list :name
"clocktable"
715 :maxlevel
2 :scope
'file
)))
718 (defun org-in-clocktable-p ()
719 "Check if the cursor is in a clocktable."
720 (let ((pos (point)) start
)
723 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
724 (setq start
(match-beginning 0))
725 (re-search-forward "^#\\+END:.*" nil t
)
726 (>= (match-end 0) pos
)
729 (defun org-clock-special-range (key &optional time as-strings
)
730 "Return two times bordering a special time range.
731 Key is a symbol specifying the range and can be one of `today', `yesterday',
732 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
733 A week starts Monday 0:00 and ends Sunday 24:00.
734 The range is determined relative to TIME. TIME defaults to the current time.
735 The return value is a cons cell with two internal times like the ones
736 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
737 the returned times will be formatted strings."
738 (if (integerp key
) (setq key
(intern (number-to-string key
))))
739 (let* ((tm (decode-time (or time
(current-time))))
740 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
741 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
743 (skey (symbol-name key
))
745 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
747 ((string-match "^[0-9]+$" skey
)
748 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
749 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
750 (setq y
(string-to-number (match-string 1 skey
))
751 month
(string-to-number (match-string 2 skey
))
753 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
755 (setq y
(string-to-number (match-string 1 skey
))
756 w
(string-to-number (match-string 2 skey
)))
757 (setq date
(calendar-gregorian-from-absolute
758 (calendar-absolute-from-iso (list w
1 y
))))
759 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
762 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
763 (setq y
(string-to-number (match-string 1 skey
))
764 month
(string-to-number (match-string 2 skey
))
765 d
(string-to-number (match-string 3 skey
))
767 ((string-match "\\([-+][0-9]+\\)$" skey
)
768 (setq shift
(string-to-number (match-string 1 skey
))
769 key
(intern (substring skey
0 (match-beginning 1))))))
771 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
772 ((eq key
'lastweek
) (setq key
'week shift -
1))
773 ((eq key
'lastmonth
) (setq key
'month shift -
1))
774 ((eq key
'lastyear
) (setq key
'year shift -
1))))
776 ((memq key
'(day today
))
777 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
778 ((memq key
'(week thisweek
))
779 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
780 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
781 ((memq key
'(month thismonth
))
782 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
783 ((memq key
'(year thisyear
))
784 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
785 (t (error "No such time block %s" key
)))
786 (setq ts
(encode-time s m h d month y
)
787 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
788 (or d1 d
) (or month1 month
) (or y1 y
)))
789 (setq fm
(cdr org-time-stamp-formats
))
791 ((memq key
'(day today
))
792 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
793 ((memq key
'(week thisweek
))
794 (setq txt
(format-time-string "week %G-W%V" ts
)))
795 ((memq key
'(month thismonth
))
796 (setq txt
(format-time-string "%B %Y" ts
)))
797 ((memq key
'(year thisyear
))
798 (setq txt
(format-time-string "the year %Y" ts
))))
800 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
803 (defun org-clocktable-shift (dir n
)
804 "Try to shift the :block date of the clocktable at point.
805 Point must be in the #+BEGIN: line of a clocktable, or this function
807 DIR is a direction, a symbol `left', `right', `up', or `down'.
808 Both `left' and `down' shift the block toward the past, `up' and `right'
809 push it toward the future.
810 N is the number of shift steps to take. The size of the step depends on
811 the currently selected interval size."
812 (setq n
(prefix-numeric-value n
))
813 (and (memq dir
'(left down
)) (setq n
(- n
)))
815 (goto-char (point-at-bol))
816 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
817 (error "Line needs a :block definition before this command works")
818 (let* ((b (match-beginning 1)) (e (match-end 1))
820 block shift ins y mw d date wp m
)
822 ((equal s
"yesterday") (setq s
"today-1"))
823 ((equal s
"lastweek") (setq s
"thisweek-1"))
824 ((equal s
"lastmonth") (setq s
"thismonth-1"))
825 ((equal s
"lastyear") (setq s
"thisyear-1")))
827 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
828 (setq block
(match-string 1 s
)
829 shift
(if (match-end 2)
830 (string-to-number (match-string 2 s
))
832 (setq shift
(+ shift n
))
833 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
834 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
835 ;; 1 1 2 3 3 4 4 5 6 6 5 2
836 (setq y
(string-to-number (match-string 1 s
))
837 wp
(and (match-end 3) (match-string 3 s
))
838 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
839 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
841 (d (setq ins
(format-time-string
843 (encode-time 0 0 0 (+ d n
) m y
))))
844 ((and wp mw
(> (length wp
) 0))
846 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
847 (setq ins
(format-time-string
849 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
851 (setq ins
(format-time-string
853 (encode-time 0 0 0 1 (+ mw n
) y
))))
855 (setq ins
(number-to-string (+ y n
))))))
856 (t (error "Cannot shift clocktable block")))
860 (delete-region (point) (+ (point) (- e b
)))
861 (beginning-of-line 1)
865 (defun org-dblock-write:clocktable
(params)
866 "Write the standard clocktable."
868 (let* ((hlchars '((1 .
"*") (2 .
"/")))
871 (scope (plist-get params
:scope
))
872 (tostring (plist-get params
:tostring
))
873 (multifile (plist-get params
:multifile
))
874 (header (plist-get params
:header
))
875 (maxlevel (or (plist-get params
:maxlevel
) 3))
876 (step (plist-get params
:step
))
877 (emph (plist-get params
:emphasize
))
878 (ts (plist-get params
:tstart
))
879 (te (plist-get params
:tend
))
880 (block (plist-get params
:block
))
881 (link (plist-get params
:link
))
882 ipos time p level hlc hdl content recalc formula pcol
883 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st
)
884 (setq org-clock-file-total-minutes nil
)
886 (unless (or block
(and ts te
))
887 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
888 (org-clocktable-steps params
)
891 (setq cc
(org-clock-special-range block nil t
)
892 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
893 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
894 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
895 (when (and ts
(listp ts
))
896 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
897 (when (and te
(listp te
))
898 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
899 ;; Now the times are strings we can parse.
900 (if ts
(setq ts
(time-to-seconds
901 (apply 'encode-time
(org-parse-time-string ts
)))))
902 (if te
(setq te
(time-to-seconds
903 (apply 'encode-time
(org-parse-time-string te
)))))
904 (move-marker ins
(point))
907 ;; Get the right scope
910 ((and scope
(listp scope
) (symbolp (car scope
)))
911 (setq scope
(eval scope
)))
913 (setq scope
(org-agenda-files t
)))
914 ((eq scope
'agenda-with-archives
)
915 (setq scope
(org-agenda-files t
))
916 (setq scope
(org-add-archive-files scope
)))
917 ((eq scope
'file-with-archives
)
918 (setq scope
(org-add-archive-files (list (buffer-file-name)))
920 (setq scope-is-list
(and scope
(listp scope
)))
924 ((eq scope
'file
) (widen))
925 ((eq scope
'subtree
) (org-narrow-to-subtree))
927 (while (org-up-heading-safe))
928 (org-narrow-to-subtree))
929 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
930 (symbol-name scope
)))
931 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
933 (while (org-up-heading-safe)
934 (looking-at outline-regexp
)
935 (if (<= (org-reduced-level (funcall outline-level
)) level
)
937 (org-narrow-to-subtree))
941 (p1 (copy-sequence params
))
943 (setq p1
(plist-put p1
:tostring t
))
944 (setq p1
(plist-put p1
:multifile t
))
945 (setq p1
(plist-put p1
:scope
'file
))
946 (org-prepare-agenda-buffers files
)
947 (while (setq file
(pop files
))
948 (with-current-buffer (find-buffer-visiting file
)
949 (setq tbl1
(org-dblock-write:clocktable p1
))
951 (push (org-clocktable-add-file
953 (concat "| |*File time*|*"
954 (org-minutes-to-hh:mm-string
955 org-clock-file-total-minutes
)
958 (setq total-time
(+ (or total-time
0)
959 org-clock-file-total-minutes
))))))))
962 (unless scope-is-list
963 (org-clock-sum ts te
)
964 (goto-char (point-min))
966 (while (or (and (bobp) (prog1 st
(setq st nil
))
967 (get-text-property (point) :org-clock-minutes
)
968 (setq p
(point-min)))
969 (setq p
(next-single-property-change (point) :org-clock-minutes
)))
971 (when (setq time
(get-text-property p
:org-clock-minutes
))
973 (beginning-of-line 1)
974 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
975 (setq level
(org-reduced-level
976 (- (match-end 1) (match-beginning 1))))
978 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
981 (org-make-link-string
982 (format "file:%s::%s"
985 (org-make-org-heading-search-string
988 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
990 "| " (int-to-string level
) "|" hlc hdl hlc
" |"
991 (make-string (1- level
) ?|
)
992 hlc
(org-minutes-to-hh:mm-string time
) hlc
994 (setq tbl
(nreverse tbl
))
996 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
998 (insert-before-markers
1001 "Clock summary at ["
1003 (format-time-string (cdr org-time-stamp-formats
))
1006 (if block
(concat ", for " range-text
".") "")
1008 (if scope-is-list
"|File" "")
1009 "|L|Headline|Time|\n")
1010 (setq total-time
(or total-time org-clock-file-total-minutes
))
1011 (insert-before-markers
1013 (if scope-is-list
"|" "")
1016 (org-minutes-to-hh:mm-string
(or total-time
0))
1018 (setq tbl
(delq nil tbl
))
1019 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
1020 (equal (substring (car tbl
) 0 2) "|-"))
1022 (insert-before-markers (mapconcat
1023 'identity
(delq nil tbl
)
1024 (if scope-is-list
"\n|-\n" "\n")))
1025 (backward-delete-char 1)
1026 (if (setq formula
(plist-get params
:formula
))
1029 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
1032 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1035 (+ 3 (if scope-is-list
1 0))
1036 (+ (if scope-is-list
1 0) 3)
1040 (insert "\n#+TBLFM: " formula
)
1042 (t (error "invalid formula in clocktable")))
1043 ;; Should we rescue an old formula?
1044 (when (stringp (setq content
(plist-get params
:content
)))
1045 (when (string-match "^\\(#\\+TBLFM:.*\\)" content
)
1047 (insert "\n" (match-string 1 (plist-get params
:content
)))
1048 (beginning-of-line 0))))
1050 (skip-chars-forward "^|")
1054 (save-excursion (org-table-goto-column pcol nil
'force
)
1056 (org-table-recalculate 'all
))
1057 (when rm-file-column
1059 (org-table-delete-column)))))))
1061 (defun org-clocktable-steps (params)
1062 (let* ((p1 (copy-sequence params
))
1063 (ts (plist-get p1
:tstart
))
1064 (te (plist-get p1
:tend
))
1065 (step0 (plist-get p1
:step
))
1066 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1067 (block (plist-get p1
:block
))
1070 (setq cc
(org-clock-special-range block nil t
)
1071 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1072 (if ts
(setq ts
(time-to-seconds
1073 (apply 'encode-time
(org-parse-time-string ts
)))))
1074 (if te
(setq te
(time-to-seconds
1075 (apply 'encode-time
(org-parse-time-string te
)))))
1076 (setq p1
(plist-put p1
:header
""))
1077 (setq p1
(plist-put p1
:step nil
))
1078 (setq p1
(plist-put p1
:block nil
))
1080 (or (bolp) (insert "\n"))
1081 (setq p1
(plist-put p1
:tstart
(format-time-string
1082 (org-time-stamp-format nil t
)
1083 (seconds-to-time ts
))))
1084 (setq p1
(plist-put p1
:tend
(format-time-string
1085 (org-time-stamp-format nil t
)
1086 (seconds-to-time (setq ts
(+ ts step
))))))
1087 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1088 (plist-get p1
:tstart
) "\n")
1089 (org-dblock-write:clocktable p1
)
1090 (re-search-forward "#\\+END:")
1093 (defun org-clocktable-add-file (file table
)
1095 (let ((lines (org-split-string table
"\n"))
1096 (ff (file-name-nondirectory file
)))
1097 (mapconcat 'identity
1099 (if (string-match org-table-dataline-regexp x
)
1105 (defun org-clock-time%
(total &rest strings
)
1106 "Compute a time fraction in percent.
1107 TOTAL s a time string like 10:21 specifying the total times.
1108 STRINGS is a list of strings that should be checked for a time.
1109 The first string that does have a time will be used.
1110 This function is made for clock tables."
1111 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1115 (if (not (string-match re total
))
1117 (setq tot
(+ (string-to-number (match-string 2 total
))
1118 (* 60 (string-to-number (match-string 1 total
)))))
1119 (if (= tot
0.
) (throw 'exit
0.
)))
1120 (while (setq s
(pop strings
))
1121 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1123 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1124 (* 60 (string-to-number (match-string 1 s
)))))
1128 (defun org-clock-save ()
1129 "Persist various clock-related data to disk.
1130 The details of what will be saved are regulated by the variable
1131 `org-clock-persist'."
1132 (when org-clock-persist
1134 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1136 (delete-region (point-min) (point-max))
1138 (insert (format ";; org-persist.el - %s at %s\n"
1139 system-name
(format-time-string
1140 (cdr org-time-stamp-formats
))))
1141 (if (and (setq b
(marker-buffer org-clock-marker
))
1142 (setq b
(or (buffer-base-buffer b
) b
))
1144 (buffer-file-name b
)
1145 (or (not org-clock-persist-query-save
)
1146 (y-or-n-p (concat "Save current clock ("
1147 (substring-no-properties org-clock-heading
)
1149 (insert "(setq resume-clock '(\""
1150 (buffer-file-name (marker-buffer org-clock-marker
))
1151 "\" . " (int-to-string (marker-position org-clock-marker
))
1153 ;; Store clocked task history. Tasks are stored reversed to make
1155 (when (and org-clock-history
(eq org-clock-persist t
))
1157 "(setq stored-clock-history '("
1160 (when (and (setq b
(marker-buffer m
))
1161 (setq b
(or (buffer-base-buffer b
) b
))
1163 (buffer-file-name b
))
1164 (concat "(\"" (buffer-file-name b
)
1165 "\" . " (int-to-string (marker-position m
))
1167 (reverse org-clock-history
) " ") "))\n"))
1169 (kill-buffer (current-buffer)))))))
1171 (defvar org-clock-loaded nil
1172 "Was the clock file loaded?")
1174 (defun org-clock-load ()
1175 "Load various clock-related data from disk, optionally resuming
1177 (when (and org-clock-persist
(not org-clock-loaded
))
1178 (let ((filename (expand-file-name org-clock-persist-file
))
1179 (org-clock-in-resume 'auto-restart
)
1180 resume-clock stored-clock-history
)
1181 (if (not (file-readable-p filename
))
1182 (message "Not restoring clock data; %s not found"
1183 org-clock-persist-file
)
1184 (message "%s" "Restoring clock data")
1185 (setq org-clock-loaded t
)
1186 (load-file filename
)
1188 (when stored-clock-history
1189 (save-window-excursion
1190 (mapc (lambda (task)
1191 (if (file-exists-p (car task
))
1192 (org-clock-history-push (cdr task
)
1193 (find-file (car task
)))))
1194 stored-clock-history
)))
1196 (when (and resume-clock org-clock-persist
1197 (file-exists-p (car resume-clock
))
1198 (or (not org-clock-persist-query-resume
)
1202 (with-current-buffer (find-file (car resume-clock
))
1204 (goto-char (cdr resume-clock
))
1205 (org-back-to-heading t
)
1206 (and (looking-at org-complex-heading-regexp
)
1209 (when (file-exists-p (car resume-clock
))
1210 (with-current-buffer (find-file (car resume-clock
))
1211 (goto-char (cdr resume-clock
))
1213 (if (org-invisible-p)
1214 (org-show-context)))))))))
1217 (defun org-clock-persistence-insinuate ()
1218 "Set up hooks for clock persistence"
1219 (add-hook 'org-mode-hook
'org-clock-load
)
1220 (add-hook 'kill-emacs-hook
'org-clock-save
))
1222 (provide 'org-clock
)
1224 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1226 ;;; org-clock.el ends here