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
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;; This file contains the time clocking code for Org-mode
35 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
36 (defvar org-time-stamp-formats
)
38 (defgroup org-clock nil
39 "Options concerning clocking working time in Org-mode."
43 (defcustom org-clock-into-drawer
2
44 "Should clocking info be wrapped into a drawer?
45 When t, clocking info will always be inserted into a :CLOCK: drawer.
46 If necessary, the drawer will be created.
47 When nil, the drawer will not be created, but used when present.
48 When an integer and the number of clocking entries in an item
49 reaches or exceeds this number, a drawer will be created."
53 (const :tag
"Always" t
)
54 (const :tag
"Only when drawer exists" nil
)
55 (integer :tag
"When at least N clock entries")))
57 (defcustom org-clock-out-when-done t
58 "When non-nil, the clock will be stopped when the relevant entry is marked DONE.
59 A nil value means, clock will keep running until stopped explicitly with
60 `C-c C-x C-o', or until the clock is started in a different item."
64 (defcustom org-clock-out-remove-zero-time-clocks nil
65 "Non-nil means, remove the clock line when the resulting time is zero."
69 (defcustom org-clock-in-switch-to-state nil
70 "Set task to a special todo state while clocking it.
71 The value should be the state to which the entry should be
72 switched. If the value is a function, it must take one
73 parameter (the current TODO state of the item) and return the
74 state to switch it to."
78 (const :tag
"Don't force a state" nil
)
80 (symbol :tag
"Function")))
82 (defcustom org-clock-history-length
5
83 "Number of clock tasks to remember in history."
87 (defcustom org-clock-heading-function nil
88 "When non-nil, should be a function to create `org-clock-heading'.
89 This is the string shown in the mode line when a clock is running.
90 The function is called with point at the beginning of the headline."
94 (defcustom org-clock-string-limit
0
95 "Maximum length of clock strings in the modeline. 0 means no limit"
99 (defcustom org-clock-in-resume nil
100 "If non-nil, when clocking into a task with a clock entry which
101 has not been closed, resume the clock from that point"
105 (defcustom org-clock-persist nil
106 "When non-nil, save the running clock when emacs is closed, and
107 resume it next time emacs is started.
108 When this is t, both the running clock, and the entire clock
109 history are saved. When this is the symbol `clock', only the
110 running clock is saved.
112 When Emacs restarts with saved clock information, the file containing the
113 running clock as well as all files mentioned in the clock history will
117 (const :tag
"Just the running clock" clock
)
118 (const :tag
"Clock and history" t
)
119 (const :tag
"No persistence" nil
)))
121 (defcustom org-clock-persist-file
"~/.emacs.d/org-clock-save.el"
122 "File to save clock data to"
126 (defcustom org-clock-persist-query-save nil
127 "When non-nil, ask before saving the current clock on exit"
131 (defcustom org-clock-persist-query-resume t
132 "When non-nil, ask before resuming any stored clock during
137 ;;; The clock for measuring work time.
139 (defvar org-mode-line-string
"")
140 (put 'org-mode-line-string
'risky-local-variable t
)
142 (defvar org-mode-line-timer nil
)
143 (defvar org-clock-heading
"")
144 (defvar org-clock-heading-for-remember
"")
145 (defvar org-clock-start-time
"")
147 (defvar org-clock-history nil
148 "List of marker pointing to recent clocked tasks.")
150 (defvar org-clock-default-task
(make-marker)
151 "Marker pointing to the default task that should clock time.
152 The clock can be made to switch to this task after clocking out
153 of a different task.")
155 (defvar org-clock-interrupted-task
(make-marker)
156 "Marker pointing to the task that has been interrupted by the current clock.")
158 (defvar org-clock-mode-map
(make-sparse-keymap))
159 (define-key org-clock-mode-map
[mode-line mouse-2
] 'org-clock-goto
)
161 (defun org-clock-history-push (&optional pos buffer
)
162 "Push a marker to the clock history."
163 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
164 (let ((m (move-marker (make-marker) (or pos
(point)) buffer
)) n l
)
165 (while (setq n
(member m org-clock-history
))
166 (move-marker (car n
) nil
))
167 (setq org-clock-history
169 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
171 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
172 (setq org-clock-history
174 (nthcdr (- l org-clock-history-length -
1)
175 (nreverse org-clock-history
)))))
176 (push m org-clock-history
)))
178 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
179 "Save relative positions of markers in region."
180 (org-check-and-save-marker org-clock-marker beg end
)
181 (org-check-and-save-marker org-clock-default-task beg end
)
182 (org-check-and-save-marker org-clock-interrupted-task beg end
)
183 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
186 (defun org-clock-select-task (&optional prompt
)
187 "Select a task that recently was associated with clocking."
189 (let (sel-list rpl file task
(i 0) s
)
190 (save-window-excursion
191 (org-switch-to-buffer-other-window
192 (get-buffer-create "*Clock Task Select*"))
194 (when (marker-buffer org-clock-default-task
)
195 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
196 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
198 (when (marker-buffer org-clock-interrupted-task
)
199 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
200 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
202 (when (marker-buffer org-clock-marker
)
203 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
204 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
206 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
209 (when (marker-buffer m
)
211 s
(org-clock-insert-selection-line
217 (org-fit-window-to-buffer)
218 (message (or prompt
"Select task for clocking:"))
219 (setq rpl
(read-char-exclusive))
223 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
224 (t (error "Invalid task choice %c" rpl
))))))
226 (defun org-clock-insert-selection-line (i marker
)
227 (when (marker-buffer marker
)
229 (with-current-buffer (org-base-buffer (marker-buffer marker
))
234 (setq file
(buffer-file-name (marker-buffer marker
))
235 cat
(or (org-get-category)
236 (progn (org-refresh-category-properties)
238 task
(org-get-heading 'notags
)))))
240 (insert (format "[%c] %-15s %s\n" i cat task
))
243 (defun org-update-mode-line ()
244 (let* ((delta (- (time-to-seconds (current-time))
245 (time-to-seconds org-clock-start-time
)))
246 (h (floor delta
3600))
247 (m (floor (- delta
(* 3600 h
)) 60)))
248 (setq org-mode-line-string
250 (let ((clock-string (format (concat "-[" org-time-clocksum-format
" (%s)]")
251 h m org-clock-heading
))
252 (help-text "Org-mode clock is running. Mouse-2 to go there."))
253 (if (and (> org-clock-string-limit
0)
254 (> (length clock-string
) org-clock-string-limit
))
255 (org-propertize (substring clock-string
0 org-clock-string-limit
)
256 'help-echo
(concat help-text
": " org-clock-heading
))
257 (org-propertize clock-string
'help-echo help-text
)))
258 'local-map org-clock-mode-map
259 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)))
260 (force-mode-line-update)))
262 (defvar org-clock-mode-line-entry nil
263 "Information for the modeline about the running clock.")
265 (defun org-clock-in (&optional select
)
266 "Start the clock on the current item.
267 If necessary, clock-out of the currently active clock.
268 With prefix arg SELECT, offer a list of recently clocked tasks to
269 clock into. When SELECT is `C-u C-u', clock into the current task and mark
270 is as the default task, a special task that will always be offered in
271 the clocking selection, associated with the letter `d'."
274 (let ((interrupting (marker-buffer org-clock-marker
))
275 ts selected-task target-pos
)
276 (when (equal select
'(4))
277 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
279 (setq selected-task
(copy-marker selected-task
))
282 ;; We are interrupting the clocking of a differnt task.
283 ;; Save a marker to this task, so that we can go back.
284 (move-marker org-clock-interrupted-task
285 (marker-position org-clock-marker
)
286 (marker-buffer org-clock-marker
))
289 (when (equal select
'(16))
290 ;; Mark as default clocking task
292 (org-back-to-heading t
)
293 (move-marker org-clock-default-task
(point))))
295 (setq target-pos
(point)) ;; we want to clock in at this location
297 (when (and selected-task
(marker-buffer selected-task
))
298 ;; There is a selected task, move to the correct buffer
299 ;; and set the new target position.
300 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
301 (setq target-pos
(marker-position selected-task
))
302 (move-marker selected-task nil
))
306 (goto-char target-pos
)
307 (org-back-to-heading t
)
308 (or interrupting
(move-marker org-clock-interrupted-task nil
))
309 (org-clock-history-push)
310 (cond ((functionp org-clock-in-switch-to-state
)
311 (looking-at org-complex-heading-regexp
)
312 (let ((newstate (funcall org-clock-in-switch-to-state
314 (if newstate
(org-todo newstate
))))
315 ((and org-clock-in-switch-to-state
316 (not (looking-at (concat outline-regexp
"[ \t]*"
317 org-clock-in-switch-to-state
319 (org-todo org-clock-in-switch-to-state
)))
320 (setq org-clock-heading-for-remember
321 (and (looking-at org-complex-heading-regexp
)
323 (org-trim (buffer-substring (match-end 1)
325 (setq org-clock-heading
326 (cond ((and org-clock-heading-function
327 (functionp org-clock-heading-function
))
328 (funcall org-clock-heading-function
))
329 ((looking-at org-complex-heading-regexp
)
332 (setq org-clock-heading
(org-propertize org-clock-heading
334 (org-clock-find-position)
336 ((and org-clock-in-resume
338 (concat "^[ \\t]* " org-clock-string
339 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
340 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
341 (message "Matched %s" (match-string 1))
342 (setq ts
(concat "[" (match-string 1) "]"))
343 (goto-char (match-end 1))
344 (setq org-clock-start-time
346 (org-parse-time-string (match-string 1)))))
347 ((eq org-clock-in-resume
'auto-restart
)
348 ;; called from org-clock-load during startup,
349 ;; do not interrupt, but warn!
350 (message "Cannot restart clock because task does not contain unfinished clock")
355 (insert "\n") (backward-char 1)
356 (org-indent-line-function)
357 (insert org-clock-string
" ")
358 (setq org-clock-start-time
(current-time))
359 (setq ts
(org-insert-time-stamp org-clock-start-time
'with-hm
'inactive
))))
360 (move-marker org-clock-marker
(point) (buffer-base-buffer))
361 (or global-mode-string
(setq global-mode-string
'("")))
362 (or (memq 'org-mode-line-string global-mode-string
)
363 (setq global-mode-string
364 (append global-mode-string
'(org-mode-line-string))))
365 (org-update-mode-line)
366 (setq org-mode-line-timer
367 (run-with-timer 60 60 'org-update-mode-line
))
368 (message "Clock started at %s" ts
)))))))
370 (defun org-clock-find-position ()
371 "Find the location where the next clock line should be inserted."
372 (org-back-to-heading t
)
374 (let ((beg (save-excursion
375 (beginning-of-line 2)
376 (or (bolp) (newline))
378 (end (progn (outline-next-heading) (point)))
379 (re (concat "^[ \t]*" org-clock-string
))
383 (when (eobp) (newline) (setq end
(max (point) end
)))
384 (when (re-search-forward "^[ \t]*:CLOCK:" end t
)
385 ;; we seem to have a CLOCK drawer, so go there.
386 (beginning-of-line 2)
388 ;; Lets count the CLOCK lines
390 (while (re-search-forward re end t
)
391 (setq first
(or first
(match-beginning 0))
392 last
(match-beginning 0)
394 (when (and (integerp org-clock-into-drawer
)
395 (>= (1+ cnt
) org-clock-into-drawer
))
396 ;; Wrap current entries into a new drawer
398 (beginning-of-line 2)
399 (if (org-at-item-p) (org-end-of-item))
401 (beginning-of-line 0)
402 (org-indent-line-function)
405 (beginning-of-line 0)
406 (org-indent-line-function)
408 (beginning-of-line 2)
412 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
413 (not (equal (match-string 1) org-clock-string
)))
414 ;; Planning info, skip to after it
415 (beginning-of-line 2)
416 (or (bolp) (newline)))
417 (when (eq t org-clock-into-drawer
)
418 (insert ":CLOCK:\n:END:\n")
419 (beginning-of-line 0)
420 (org-indent-line-function)
421 (beginning-of-line 0)
423 (org-indent-line-function)
424 (beginning-of-line 2)))))
426 (defun org-clock-out (&optional fail-quietly
)
427 "Stop the currently running clock.
428 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
431 (if (not (marker-buffer org-clock-marker
))
432 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
433 (let (ts te s h m remove
)
435 (set-buffer (marker-buffer org-clock-marker
))
438 (goto-char org-clock-marker
)
439 (beginning-of-line 1)
440 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
441 (equal (match-string 1) org-clock-string
))
442 (setq ts
(match-string 2))
443 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
444 (goto-char (match-end 0))
445 (delete-region (point) (point-at-eol))
447 (setq te
(org-insert-time-stamp (current-time) 'with-hm
'inactive
))
448 (setq s
(- (time-to-seconds (apply 'encode-time
(org-parse-time-string te
)))
449 (time-to-seconds (apply 'encode-time
(org-parse-time-string ts
))))
454 (insert " => " (format "%2d:%02d" h m
))
455 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
457 (beginning-of-line 1)
458 (delete-region (point) (point-at-eol))
459 (and (looking-at "\n") (> (point-max) (1+ (point)))
461 (move-marker org-clock-marker nil
)
462 (when org-log-note-clock-out
463 (org-add-log-setup 'clock-out nil nil nil
464 (concat "# Task: " (org-get-heading t
) "\n\n")))
465 (when org-mode-line-timer
466 (cancel-timer org-mode-line-timer
)
467 (setq org-mode-line-timer nil
))
468 (setq global-mode-string
469 (delq 'org-mode-line-string global-mode-string
))
470 (force-mode-line-update)
471 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
472 (if remove
" => LINE REMOVED" "")))))))
474 (defun org-clock-cancel ()
475 "Cancel the running clock be removing the start timestamp."
477 (if (not (marker-buffer org-clock-marker
))
478 (error "No active clock"))
480 (set-buffer (marker-buffer org-clock-marker
))
481 (goto-char org-clock-marker
)
482 (delete-region (1- (point-at-bol)) (point-at-eol)))
483 (setq global-mode-string
484 (delq 'org-mode-line-string global-mode-string
))
485 (force-mode-line-update)
486 (message "Clock canceled"))
488 (defun org-clock-goto (&optional select
)
489 "Go to the currently clocked-in entry.
490 With prefix arg SELECT, offer recently clocked tasks."
493 (org-clock-select-task "Select task to go to: ")
495 (if (not (marker-buffer m
))
497 (error "No task selected")
498 (error "No active clock")))
499 (switch-to-buffer (marker-buffer m
))
500 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
503 (org-back-to-heading)
504 (org-cycle-hide-drawers 'children
)
507 (defvar org-clock-file-total-minutes nil
508 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
509 (make-variable-buffer-local 'org-clock-file-total-minutes
)
511 (defun org-clock-sum (&optional tstart tend
)
512 "Sum the times for each subtree.
513 Puts the resulting times in minutes as a text property on each headline."
515 (let* ((bmp (buffer-modified-p))
516 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
518 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
520 (ltimes (make-vector lmax
0))
525 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
527 (goto-char (point-max))
528 (while (re-search-backward re nil t
)
532 (setq ts
(match-string 2)
535 (apply 'encode-time
(org-parse-time-string ts
)))
537 (apply 'encode-time
(org-parse-time-string te
)))
538 ts
(if tstart
(max ts tstart
) ts
)
539 te
(if tend
(min te tend
) te
)
541 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
544 (setq t1
(+ t1
(string-to-number (match-string 5))
545 (* 60 (string-to-number (match-string 4))))))
547 (setq level
(- (match-end 1) (match-beginning 1)))
548 (when (or (> t1
0) (> (aref ltimes level
) 0))
549 (loop for l from
0 to level do
550 (aset ltimes l
(+ (aref ltimes l
) t1
)))
551 (setq t1
0 time
(aref ltimes level
))
552 (loop for l from level to
(1- lmax
) do
554 (goto-char (match-beginning 0))
555 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
556 (setq org-clock-file-total-minutes
(aref ltimes
0)))
557 (set-buffer-modified-p bmp
)))
559 (defun org-clock-display (&optional total-only
)
560 "Show subtree times in the entire buffer.
561 If TOTAL-ONLY is non-nil, only show the total time for the entire file
564 (org-remove-clock-overlays)
569 (goto-char (point-min))
570 (while (or (and (equal (setq p
(point)) (point-min))
571 (get-text-property p
:org-clock-minutes
))
572 (setq p
(next-single-property-change
573 (point) :org-clock-minutes
)))
575 (when (setq time
(get-text-property p
:org-clock-minutes
))
576 (org-put-clock-overlay time
(funcall outline-level
))))
577 (setq h
(/ org-clock-file-total-minutes
60)
578 m
(- org-clock-file-total-minutes
(* 60 h
)))
579 ;; Arrange to remove the overlays upon next change.
580 (when org-remove-highlights-with-change
581 (org-add-hook 'before-change-functions
'org-remove-clock-overlays
583 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
585 (defvar org-clock-overlays nil
)
586 (make-variable-buffer-local 'org-clock-overlays
)
588 (defun org-put-clock-overlay (time &optional level
)
589 "Put an overlays on the current line, displaying TIME.
590 If LEVEL is given, prefix time with a corresponding number of stars.
591 This creates a new overlay and stores it in `org-clock-overlays', so that it
592 will be easy to remove."
593 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
594 (l (if level
(org-get-valid-level level
0) 0))
595 (fmt (concat "%s " org-time-clocksum-format
"%s"))
598 (org-move-to-column c
)
599 (unless (eolp) (skip-chars-backward "^ \t"))
600 (skip-chars-backward " \t")
601 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
602 tx
(concat (buffer-substring (1- (point)) (point))
603 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
604 (org-add-props (format fmt
605 (make-string l ?
*) h m
606 (make-string (- 16 l
) ?\
))
607 '(face secondary-selection
))
609 (if (not (featurep 'xemacs
))
610 (org-overlay-put ov
'display tx
)
611 (org-overlay-put ov
'invisible t
)
612 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
613 (push ov org-clock-overlays
)))
615 (defun org-remove-clock-overlays (&optional beg end noremove
)
616 "Remove the occur highlights from the buffer.
617 BEG and END are ignored. If NOREMOVE is nil, remove this function
618 from the `before-change-functions' in the current buffer."
620 (unless org-inhibit-highlight-removal
621 (mapc 'org-delete-overlay org-clock-overlays
)
622 (setq org-clock-overlays nil
)
624 (remove-hook 'before-change-functions
625 'org-remove-clock-overlays
'local
))))
627 (defvar state
) ;; dynamically scoped into this function
628 (defun org-clock-out-if-current ()
629 "Clock out if the current entry contains the running clock.
630 This is used to stop the clock after a TODO entry is marked DONE,
631 and is only done if the variable `org-clock-out-when-done' is not nil."
632 (when (and org-clock-out-when-done
633 (member state org-done-keywords
)
634 (equal (marker-buffer org-clock-marker
) (current-buffer))
635 (< (point) org-clock-marker
)
636 (> (save-excursion (outline-next-heading) (point))
638 ;; Clock out, but don't accept a logging message for this.
639 (let ((org-log-note-clock-out nil
))
642 (add-hook 'org-after-todo-state-change-hook
643 'org-clock-out-if-current
)
646 (defun org-get-clocktable (&rest props
)
647 "Get a formatted clocktable with parameters according to PROPS.
648 The table is created in a temporary buffer, fully formatted and
649 fontified, and then returned."
651 (setq props
(plist-put props
:name
"clocktable"))
652 (unless (plist-member props
:maxlevel
)
653 (setq props
(plist-put props
:maxlevel
2)))
654 (unless (plist-member props
:scope
)
655 (setq props
(plist-put props
:scope
'agenda
)))
658 (org-create-dblock props
)
660 (font-lock-fontify-buffer)
662 (buffer-substring (point) (progn
663 (re-search-forward "^#\\+END" nil t
)
666 (defun org-clock-report (&optional arg
)
667 "Create a table containing a report about clocked time.
668 If the cursor is inside an existing clocktable block, then the table
669 will be updated. If not, a new clocktable will be inserted.
670 When called with a prefix argument, move to the first clock table in the
671 buffer and update it."
673 (org-remove-clock-overlays)
675 (org-find-dblock "clocktable")
677 (if (org-in-clocktable-p)
678 (goto-char (org-in-clocktable-p))
679 (org-create-dblock (list :name
"clocktable"
680 :maxlevel
2 :scope
'file
)))
683 (defun org-in-clocktable-p ()
684 "Check if the cursor is in a clocktable."
685 (let ((pos (point)) start
)
688 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
689 (setq start
(match-beginning 0))
690 (re-search-forward "^#\\+END:.*" nil t
)
691 (>= (match-end 0) pos
)
694 (defun org-clock-special-range (key &optional time as-strings
)
695 "Return two times bordering a special time range.
696 Key is a symbol specifying the range and can be one of `today', `yesterday',
697 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
698 A week starts Monday 0:00 and ends Sunday 24:00.
699 The range is determined relative to TIME. TIME defaults to the current time.
700 The return value is a cons cell with two internal times like the ones
701 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
702 the returned times will be formatted strings."
703 (if (integerp key
) (setq key
(intern (number-to-string key
))))
704 (let* ((tm (decode-time (or time
(current-time))))
705 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
706 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
708 (skey (symbol-name key
))
710 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
712 ((string-match "^[0-9]+$" skey
)
713 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
714 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
715 (setq y
(string-to-number (match-string 1 skey
))
716 month
(string-to-number (match-string 2 skey
))
718 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
720 (setq y
(string-to-number (match-string 1 skey
))
721 w
(string-to-number (match-string 2 skey
)))
722 (setq date
(calendar-gregorian-from-absolute
723 (calendar-absolute-from-iso (list w
1 y
))))
724 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
726 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
727 (setq y
(string-to-number (match-string 1 skey
))
728 month
(string-to-number (match-string 2 skey
))
729 d
(string-to-number (match-string 3 skey
))
731 ((string-match "\\([-+][0-9]+\\)$" skey
)
732 (setq shift
(string-to-number (match-string 1 skey
))
733 key
(intern (substring skey
0 (match-beginning 1))))))
735 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
736 ((eq key
'lastweek
) (setq key
'week shift -
1))
737 ((eq key
'lastmonth
) (setq key
'month shift -
1))
738 ((eq key
'lastyear
) (setq key
'year shift -
1))))
740 ((memq key
'(day today
))
741 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
742 ((memq key
'(week thisweek
))
743 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
744 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
745 ((memq key
'(month thismonth
))
746 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
747 ((memq key
'(year thisyear
))
748 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
749 (t (error "No such time block %s" key
)))
750 (setq ts
(encode-time s m h d month y
)
751 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
752 (or d1 d
) (or month1 month
) (or y1 y
)))
753 (setq fm
(cdr org-time-stamp-formats
))
755 ((memq key
'(day today
))
756 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
757 ((memq key
'(week thisweek
))
758 (setq txt
(format-time-string "week %G-W%V" ts
)))
759 ((memq key
'(month thismonth
))
760 (setq txt
(format-time-string "%B %Y" ts
)))
761 ((memq key
'(year thisyear
))
762 (setq txt
(format-time-string "the year %Y" ts
))))
764 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
767 (defun org-clocktable-shift (dir n
)
768 "Try to shift the :block date of the clocktable at point.
769 Point must be in the #+BEGIN: line of a clocktable, or this function
771 DIR is a direction, a symbol `left', `right', `up', or `down'.
772 Both `left' and `down' shift the block toward the past, `up' and `right'
773 push it toward the future.
774 N is the number of shift steps to take. The size of the step depends on
775 the currently selected interval size."
776 (setq n
(prefix-numeric-value n
))
777 (and (memq dir
'(left down
)) (setq n
(- n
)))
779 (goto-char (point-at-bol))
780 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
781 (error "Line needs a :block definition before this command works")
782 (let* ((b (match-beginning 1)) (e (match-end 1))
784 block shift ins y mw d date wp m
)
786 ((equal s
"yesterday") (setq s
"today-1"))
787 ((equal s
"lastweek") (setq s
"thisweek-1"))
788 ((equal s
"lastmonth") (setq s
"thismonth-1"))
789 ((equal s
"lastyear") (setq s
"thisyear-1")))
791 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
792 (setq block
(match-string 1 s
)
793 shift
(if (match-end 2)
794 (string-to-number (match-string 2 s
))
796 (setq shift
(+ shift n
))
797 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
798 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
799 ;; 1 1 2 3 3 4 4 5 6 6 5 2
800 (setq y
(string-to-number (match-string 1 s
))
801 wp
(and (match-end 3) (match-string 3 s
))
802 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
803 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
805 (d (setq ins
(format-time-string
807 (encode-time 0 0 0 (+ d n
) m y
))))
808 ((and wp mw
(> (length wp
) 0))
810 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
811 (setq ins
(format-time-string
813 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
815 (setq ins
(format-time-string
817 (encode-time 0 0 0 1 (+ mw n
) y
))))
819 (setq ins
(number-to-string (+ y n
))))))
820 (t (error "Cannot shift clocktable block")))
824 (delete-region (point) (+ (point) (- e b
)))
825 (beginning-of-line 1)
829 (defun org-dblock-write:clocktable
(params)
830 "Write the standard clocktable."
832 (let* ((hlchars '((1 .
"*") (2 .
"/")))
835 (scope (plist-get params
:scope
))
836 (tostring (plist-get params
:tostring
))
837 (multifile (plist-get params
:multifile
))
838 (header (plist-get params
:header
))
839 (maxlevel (or (plist-get params
:maxlevel
) 3))
840 (step (plist-get params
:step
))
841 (emph (plist-get params
:emphasize
))
842 (ts (plist-get params
:tstart
))
843 (te (plist-get params
:tend
))
844 (block (plist-get params
:block
))
845 (link (plist-get params
:link
))
846 ipos time p level hlc hdl content recalc formula pcol
847 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st
)
848 (setq org-clock-file-total-minutes nil
)
850 (unless (or block
(and ts te
))
851 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
852 (org-clocktable-steps params
)
855 (setq cc
(org-clock-special-range block nil t
)
856 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
857 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
858 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
859 (when (and ts
(listp ts
))
860 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
861 (when (and te
(listp te
))
862 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
863 ;; Now the times are strings we can parse.
864 (if ts
(setq ts
(time-to-seconds
865 (apply 'encode-time
(org-parse-time-string ts
)))))
866 (if te
(setq te
(time-to-seconds
867 (apply 'encode-time
(org-parse-time-string te
)))))
868 (move-marker ins
(point))
871 ;; Get the right scope
874 ((and scope
(listp scope
) (symbolp (car scope
)))
875 (setq scope
(eval scope
)))
877 (setq scope
(org-agenda-files t
)))
878 ((eq scope
'agenda-with-archives
)
879 (setq scope
(org-agenda-files t
))
880 (setq scope
(org-add-archive-files scope
)))
881 ((eq scope
'file-with-archives
)
882 (setq scope
(org-add-archive-files (list (buffer-file-name)))
884 (setq scope-is-list
(and scope
(listp scope
)))
888 ((eq scope
'file
) (widen))
889 ((eq scope
'subtree
) (org-narrow-to-subtree))
891 (while (org-up-heading-safe))
892 (org-narrow-to-subtree))
893 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
894 (symbol-name scope
)))
895 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
897 (while (org-up-heading-safe)
898 (looking-at outline-regexp
)
899 (if (<= (org-reduced-level (funcall outline-level
)) level
)
901 (org-narrow-to-subtree))
905 (p1 (copy-sequence params
))
907 (setq p1
(plist-put p1
:tostring t
))
908 (setq p1
(plist-put p1
:multifile t
))
909 (setq p1
(plist-put p1
:scope
'file
))
910 (org-prepare-agenda-buffers files
)
911 (while (setq file
(pop files
))
912 (with-current-buffer (find-buffer-visiting file
)
913 (setq tbl1
(org-dblock-write:clocktable p1
))
915 (push (org-clocktable-add-file
917 (concat "| |*File time*|*"
918 (org-minutes-to-hh:mm-string
919 org-clock-file-total-minutes
)
922 (setq total-time
(+ (or total-time
0)
923 org-clock-file-total-minutes
))))))))
926 (unless scope-is-list
927 (org-clock-sum ts te
)
928 (goto-char (point-min))
930 (while (or (and (bobp) (prog1 st
(setq st nil
))
931 (get-text-property (point) :org-clock-minutes
)
932 (setq p
(point-min)))
933 (setq p
(next-single-property-change (point) :org-clock-minutes
)))
935 (when (setq time
(get-text-property p
:org-clock-minutes
))
937 (beginning-of-line 1)
938 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
939 (setq level
(org-reduced-level
940 (- (match-end 1) (match-beginning 1))))
942 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
945 (org-make-link-string
946 (format "file:%s::%s"
949 (org-make-org-heading-search-string
952 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
954 "| " (int-to-string level
) "|" hlc hdl hlc
" |"
955 (make-string (1- level
) ?|
)
956 hlc
(org-minutes-to-hh:mm-string time
) hlc
958 (setq tbl
(nreverse tbl
))
960 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
962 (insert-before-markers
967 (format-time-string (cdr org-time-stamp-formats
))
970 (if block
(concat ", for " range-text
".") "")
972 (if scope-is-list
"|File" "")
973 "|L|Headline|Time|\n")
974 (setq total-time
(or total-time org-clock-file-total-minutes
))
975 (insert-before-markers
977 (if scope-is-list
"|" "")
980 (org-minutes-to-hh:mm-string
(or total-time
0))
982 (setq tbl
(delq nil tbl
))
983 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
984 (equal (substring (car tbl
) 0 2) "|-"))
986 (insert-before-markers (mapconcat
987 'identity
(delq nil tbl
)
988 (if scope-is-list
"\n|-\n" "\n")))
989 (backward-delete-char 1)
990 (if (setq formula
(plist-get params
:formula
))
993 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
996 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
999 (+ 3 (if scope-is-list
1 0))
1000 (+ (if scope-is-list
1 0) 3)
1004 (insert "\n#+TBLFM: " formula
)
1006 (t (error "invalid formula in clocktable")))
1007 ;; Should we rescue an old formula?
1008 (when (stringp (setq content
(plist-get params
:content
)))
1009 (when (string-match "^\\(#\\+TBLFM:.*\\)" content
)
1011 (insert "\n" (match-string 1 (plist-get params
:content
)))
1012 (beginning-of-line 0))))
1014 (skip-chars-forward "^|")
1018 (save-excursion (org-table-goto-column pcol nil
'force
)
1020 (org-table-recalculate 'all
))
1021 (when rm-file-column
1023 (org-table-delete-column)))))))
1025 (defun org-clocktable-steps (params)
1026 (let* ((p1 (copy-sequence params
))
1027 (ts (plist-get p1
:tstart
))
1028 (te (plist-get p1
:tend
))
1029 (step0 (plist-get p1
:step
))
1030 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1031 (block (plist-get p1
:block
))
1034 (setq cc
(org-clock-special-range block nil t
)
1035 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1036 (if ts
(setq ts
(time-to-seconds
1037 (apply 'encode-time
(org-parse-time-string ts
)))))
1038 (if te
(setq te
(time-to-seconds
1039 (apply 'encode-time
(org-parse-time-string te
)))))
1040 (setq p1
(plist-put p1
:header
""))
1041 (setq p1
(plist-put p1
:step nil
))
1042 (setq p1
(plist-put p1
:block nil
))
1044 (or (bolp) (insert "\n"))
1045 (setq p1
(plist-put p1
:tstart
(format-time-string
1046 (car org-time-stamp-formats
)
1047 (seconds-to-time ts
))))
1048 (setq p1
(plist-put p1
:tend
(format-time-string
1049 (car org-time-stamp-formats
)
1050 (seconds-to-time (setq ts
(+ ts step
))))))
1051 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1052 (plist-get p1
:tstart
) "\n")
1053 (org-dblock-write:clocktable p1
)
1054 (re-search-forward "#\\+END:")
1057 (defun org-clocktable-add-file (file table
)
1059 (let ((lines (org-split-string table
"\n"))
1060 (ff (file-name-nondirectory file
)))
1061 (mapconcat 'identity
1063 (if (string-match org-table-dataline-regexp x
)
1069 (defun org-clock-time%
(total &rest strings
)
1070 "Compute a time fraction in percent.
1071 TOTAL s a time string like 10:21 specifying the total times.
1072 STRINGS is a list of strings that should be checked for a time.
1073 The first string that does have a time will be used.
1074 This function is made for clock tables."
1075 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1079 (if (not (string-match re total
))
1081 (setq tot
(+ (string-to-number (match-string 2 total
))
1082 (* 60 (string-to-number (match-string 1 total
)))))
1083 (if (= tot
0.
) (throw 'exit
0.
)))
1084 (while (setq s
(pop strings
))
1085 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1087 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1088 (* 60 (string-to-number (match-string 1 s
)))))
1092 (defun org-clock-save ()
1093 "Persist various clock-related data to disk.
1094 The details of what will be saved are regulated by the variable
1095 `org-clock-persist'."
1096 (when org-clock-persist
1098 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1100 (delete-region (point-min) (point-max))
1102 (insert (format ";; org-persist.el - %s at %s\n"
1103 system-name
(format-time-string
1104 (cdr org-time-stamp-formats
))))
1105 (if (and (setq b
(marker-buffer org-clock-marker
))
1106 (setq b
(or (buffer-base-buffer b
) b
))
1108 (buffer-file-name b
)
1109 (or (not org-clock-persist-query-save
)
1110 (y-or-n-p (concat "Save current clock ("
1111 (substring-no-properties org-clock-heading
)
1113 (insert "(setq resume-clock '(\""
1114 (buffer-file-name (marker-buffer org-clock-marker
))
1115 "\" . " (int-to-string (marker-position org-clock-marker
))
1117 ;; Store clocked task history. Tasks are stored reversed to make
1119 (when (and org-clock-history
(eq org-clock-persist t
))
1121 "(setq stored-clock-history '("
1124 (when (and (setq b
(marker-buffer m
))
1125 (setq b
(or (buffer-base-buffer b
) b
))
1127 (buffer-file-name b
))
1128 (concat "(\"" (buffer-file-name b
)
1129 "\" . " (int-to-string (marker-position m
))
1131 (reverse org-clock-history
) " ") "))\n"))
1133 (kill-buffer (current-buffer)))))))
1135 (defvar org-clock-loaded nil
1136 "Was the clock file loaded?")
1138 (defun org-clock-load ()
1139 "Load various clock-related data from disk, optionally resuming
1141 (when (and org-clock-persist
(not org-clock-loaded
))
1142 (let ((filename (expand-file-name org-clock-persist-file
))
1143 (org-clock-in-resume 'auto-restart
)
1144 resume-clock stored-clock-history
)
1145 (if (not (file-readable-p filename
))
1146 (message "Not restoring clock data; %s not found"
1147 org-clock-persist-file
)
1148 (message "%s" "Restoring clock data")
1149 (setq org-clock-loaded t
)
1150 (load-file filename
)
1152 (when stored-clock-history
1153 (save-window-excursion
1154 (mapc (lambda (task)
1155 (if (file-exists-p (car task
))
1156 (org-clock-history-push (cdr task
)
1157 (find-file (car task
)))))
1158 stored-clock-history
)))
1160 (when (and resume-clock org-clock-persist
1161 (file-exists-p (car resume-clock
))
1162 (or (not org-clock-persist-query-resume
)
1166 (with-current-buffer (find-file (car resume-clock
))
1168 (goto-char (cdr resume-clock
))
1169 (org-back-to-heading t
)
1170 (and (looking-at org-complex-heading-regexp
)
1173 (when (file-exists-p (car resume-clock
))
1174 (with-current-buffer (find-file (car resume-clock
))
1175 (goto-char (cdr resume-clock
))
1177 (if (org-invisible-p)
1178 (org-show-context)))))))))
1181 (defun org-clock-persistence-insinuate ()
1182 "Set up hooks for clock persistence"
1183 (add-hook 'org-mode-hook
'org-clock-load
)
1184 (add-hook 'kill-emacs-hook
'org-clock-save
))
1186 (provide 'org-clock
)
1188 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1190 ;;; org-clock.el ends here