1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 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
(convert-standard-filename
122 "~/.emacs.d/org-clock-save.el")
123 "File to save clock data to"
127 (defcustom org-clock-persist-query-save nil
128 "When non-nil, ask before saving the current clock on exit"
132 (defcustom org-clock-persist-query-resume t
133 "When non-nil, ask before resuming any stored clock during
138 ;;; The clock for measuring work time.
140 (defvar org-mode-line-string
"")
141 (put 'org-mode-line-string
'risky-local-variable t
)
143 (defvar org-mode-line-timer nil
)
144 (defvar org-clock-heading
"")
145 (defvar org-clock-heading-for-remember
"")
146 (defvar org-clock-start-time
"")
148 (defvar org-clock-history nil
149 "List of marker pointing to recent clocked tasks.")
151 (defvar org-clock-default-task
(make-marker)
152 "Marker pointing to the default task that should clock time.
153 The clock can be made to switch to this task after clocking out
154 of a different task.")
156 (defvar org-clock-interrupted-task
(make-marker)
157 "Marker pointing to the task that has been interrupted by the current clock.")
159 (defvar org-clock-mode-map
(make-sparse-keymap))
160 (define-key org-clock-mode-map
[mode-line mouse-2
] 'org-clock-goto
)
162 (defun org-clock-history-push (&optional pos buffer
)
163 "Push a marker to the clock history."
164 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
165 (let ((m (move-marker (make-marker) (or pos
(point)) buffer
)) n l
)
166 (while (setq n
(member m org-clock-history
))
167 (move-marker (car n
) nil
))
168 (setq org-clock-history
170 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
172 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
173 (setq org-clock-history
175 (nthcdr (- l org-clock-history-length -
1)
176 (nreverse org-clock-history
)))))
177 (push m org-clock-history
)))
179 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
180 "Save relative positions of markers in region."
181 (org-check-and-save-marker org-clock-marker beg end
)
182 (org-check-and-save-marker org-clock-default-task beg end
)
183 (org-check-and-save-marker org-clock-interrupted-task beg end
)
184 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
187 (defun org-clock-select-task (&optional prompt
)
188 "Select a task that recently was associated with clocking."
190 (let (sel-list rpl file task
(i 0) s
)
191 (save-window-excursion
192 (org-switch-to-buffer-other-window
193 (get-buffer-create "*Clock Task Select*"))
195 (when (marker-buffer org-clock-default-task
)
196 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
197 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
199 (when (marker-buffer org-clock-interrupted-task
)
200 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
201 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
203 (when (marker-buffer org-clock-marker
)
204 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
205 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
207 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
210 (when (marker-buffer m
)
212 s
(org-clock-insert-selection-line
218 (org-fit-window-to-buffer)
219 (message (or prompt
"Select task for clocking:"))
220 (setq rpl
(read-char-exclusive))
224 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
225 (t (error "Invalid task choice %c" rpl
))))))
227 (defun org-clock-insert-selection-line (i marker
)
228 (when (marker-buffer marker
)
230 (with-current-buffer (org-base-buffer (marker-buffer marker
))
235 (setq file
(buffer-file-name (marker-buffer marker
))
236 cat
(or (org-get-category)
237 (progn (org-refresh-category-properties)
239 task
(org-get-heading 'notags
)))))
241 (insert (format "[%c] %-15s %s\n" i cat task
))
244 (defun org-update-mode-line ()
245 (let* ((delta (- (time-to-seconds (current-time))
246 (time-to-seconds org-clock-start-time
)))
247 (h (floor delta
3600))
248 (m (floor (- delta
(* 3600 h
)) 60)))
249 (setq org-mode-line-string
251 (let ((clock-string (format (concat "-[" org-time-clocksum-format
" (%s)]")
252 h m org-clock-heading
))
253 (help-text "Org-mode clock is running. Mouse-2 to go there."))
254 (if (and (> org-clock-string-limit
0)
255 (> (length clock-string
) org-clock-string-limit
))
256 (org-propertize (substring clock-string
0 org-clock-string-limit
)
257 'help-echo
(concat help-text
": " org-clock-heading
))
258 (org-propertize clock-string
'help-echo help-text
)))
259 'local-map org-clock-mode-map
260 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)))
261 (force-mode-line-update)))
263 (defvar org-clock-mode-line-entry nil
264 "Information for the modeline about the running clock.")
266 (defun org-clock-in (&optional select
)
267 "Start the clock on the current item.
268 If necessary, clock-out of the currently active clock.
269 With prefix arg SELECT, offer a list of recently clocked tasks to
270 clock into. When SELECT is `C-u C-u', clock into the current task and mark
271 is as the default task, a special task that will always be offered in
272 the clocking selection, associated with the letter `d'."
275 (let ((interrupting (marker-buffer org-clock-marker
))
276 ts selected-task target-pos
)
277 (when (equal select
'(4))
278 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
280 (setq selected-task
(copy-marker selected-task
))
283 ;; We are interrupting the clocking of a different task.
284 ;; Save a marker to this task, so that we can go back.
285 (move-marker org-clock-interrupted-task
286 (marker-position org-clock-marker
)
287 (marker-buffer org-clock-marker
))
290 (when (equal select
'(16))
291 ;; Mark as default clocking task
293 (org-back-to-heading t
)
294 (move-marker org-clock-default-task
(point))))
296 (setq target-pos
(point)) ;; we want to clock in at this location
298 (when (and selected-task
(marker-buffer selected-task
))
299 ;; There is a selected task, move to the correct buffer
300 ;; and set the new target position.
301 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
302 (setq target-pos
(marker-position selected-task
))
303 (move-marker selected-task nil
))
307 (goto-char target-pos
)
308 (org-back-to-heading t
)
309 (or interrupting
(move-marker org-clock-interrupted-task nil
))
310 (org-clock-history-push)
311 (cond ((functionp org-clock-in-switch-to-state
)
312 (looking-at org-complex-heading-regexp
)
313 (let ((newstate (funcall org-clock-in-switch-to-state
315 (if newstate
(org-todo newstate
))))
316 ((and org-clock-in-switch-to-state
317 (not (looking-at (concat outline-regexp
"[ \t]*"
318 org-clock-in-switch-to-state
320 (org-todo org-clock-in-switch-to-state
)))
321 (setq org-clock-heading-for-remember
322 (and (looking-at org-complex-heading-regexp
)
324 (org-trim (buffer-substring (match-end 1)
326 (setq org-clock-heading
327 (cond ((and org-clock-heading-function
328 (functionp org-clock-heading-function
))
329 (funcall org-clock-heading-function
))
330 ((looking-at org-complex-heading-regexp
)
333 (setq org-clock-heading
(org-propertize org-clock-heading
335 (org-clock-find-position)
337 ((and org-clock-in-resume
339 (concat "^[ \\t]* " org-clock-string
340 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
341 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
342 (message "Matched %s" (match-string 1))
343 (setq ts
(concat "[" (match-string 1) "]"))
344 (goto-char (match-end 1))
345 (setq org-clock-start-time
347 (org-parse-time-string (match-string 1)))))
348 ((eq org-clock-in-resume
'auto-restart
)
349 ;; called from org-clock-load during startup,
350 ;; do not interrupt, but warn!
351 (message "Cannot restart clock because task does not contain unfinished clock")
356 (insert "\n") (backward-char 1)
357 (org-indent-line-function)
358 (insert org-clock-string
" ")
359 (setq org-clock-start-time
(current-time))
360 (setq ts
(org-insert-time-stamp org-clock-start-time
'with-hm
'inactive
))))
361 (move-marker org-clock-marker
(point) (buffer-base-buffer))
362 (or global-mode-string
(setq global-mode-string
'("")))
363 (or (memq 'org-mode-line-string global-mode-string
)
364 (setq global-mode-string
365 (append global-mode-string
'(org-mode-line-string))))
366 (org-update-mode-line)
367 (setq org-mode-line-timer
368 (run-with-timer 60 60 'org-update-mode-line
))
369 (message "Clock started at %s" ts
)))))))
371 (defun org-clock-find-position ()
372 "Find the location where the next clock line should be inserted."
373 (org-back-to-heading t
)
375 (let ((beg (save-excursion
376 (beginning-of-line 2)
377 (or (bolp) (newline))
379 (end (progn (outline-next-heading) (point)))
380 (re (concat "^[ \t]*" org-clock-string
))
384 (when (eobp) (newline) (setq end
(max (point) end
)))
385 (when (re-search-forward "^[ \t]*:CLOCK:" end t
)
386 ;; we seem to have a CLOCK drawer, so go there.
387 (beginning-of-line 2)
389 ;; Lets count the CLOCK lines
391 (while (re-search-forward re end t
)
392 (setq first
(or first
(match-beginning 0))
393 last
(match-beginning 0)
395 (when (and (integerp org-clock-into-drawer
)
396 (>= (1+ cnt
) org-clock-into-drawer
))
397 ;; Wrap current entries into a new drawer
399 (beginning-of-line 2)
400 (if (org-at-item-p) (org-end-of-item))
402 (beginning-of-line 0)
403 (org-indent-line-function)
406 (beginning-of-line 0)
407 (org-indent-line-function)
409 (beginning-of-line 2)
413 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
414 (not (equal (match-string 1) org-clock-string
)))
415 ;; Planning info, skip to after it
416 (beginning-of-line 2)
417 (or (bolp) (newline)))
418 (when (eq t org-clock-into-drawer
)
419 (insert ":CLOCK:\n:END:\n")
420 (beginning-of-line 0)
421 (org-indent-line-function)
422 (beginning-of-line 0)
424 (org-indent-line-function)
425 (beginning-of-line 2)))))
427 (defun org-clock-out (&optional fail-quietly
)
428 "Stop the currently running clock.
429 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
432 (if (not (marker-buffer org-clock-marker
))
433 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
434 (let (ts te s h m remove
)
436 (set-buffer (marker-buffer org-clock-marker
))
439 (goto-char org-clock-marker
)
440 (beginning-of-line 1)
441 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
442 (equal (match-string 1) org-clock-string
))
443 (setq ts
(match-string 2))
444 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
445 (goto-char (match-end 0))
446 (delete-region (point) (point-at-eol))
448 (setq te
(org-insert-time-stamp (current-time) 'with-hm
'inactive
))
449 (setq s
(- (time-to-seconds (apply 'encode-time
(org-parse-time-string te
)))
450 (time-to-seconds (apply 'encode-time
(org-parse-time-string ts
))))
455 (insert " => " (format "%2d:%02d" h m
))
456 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
458 (beginning-of-line 1)
459 (delete-region (point) (point-at-eol))
460 (and (looking-at "\n") (> (point-max) (1+ (point)))
462 (move-marker org-clock-marker nil
)
463 (when org-log-note-clock-out
464 (org-add-log-setup 'clock-out nil nil nil
465 (concat "# Task: " (org-get-heading t
) "\n\n")))
466 (when org-mode-line-timer
467 (cancel-timer org-mode-line-timer
)
468 (setq org-mode-line-timer nil
))
469 (setq global-mode-string
470 (delq 'org-mode-line-string global-mode-string
))
471 (force-mode-line-update)
472 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
473 (if remove
" => LINE REMOVED" "")))))))
475 (defun org-clock-cancel ()
476 "Cancel the running clock be removing the start timestamp."
478 (if (not (marker-buffer org-clock-marker
))
479 (error "No active clock"))
481 (set-buffer (marker-buffer org-clock-marker
))
482 (goto-char org-clock-marker
)
483 (delete-region (1- (point-at-bol)) (point-at-eol)))
484 (setq global-mode-string
485 (delq 'org-mode-line-string global-mode-string
))
486 (force-mode-line-update)
487 (message "Clock canceled"))
489 (defun org-clock-goto (&optional select
)
490 "Go to the currently clocked-in entry.
491 With prefix arg SELECT, offer recently clocked tasks."
494 (org-clock-select-task "Select task to go to: ")
496 (if (not (marker-buffer m
))
498 (error "No task selected")
499 (error "No active clock")))
500 (switch-to-buffer (marker-buffer m
))
501 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
504 (org-back-to-heading)
505 (org-cycle-hide-drawers 'children
)
508 (defvar org-clock-file-total-minutes nil
509 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
510 (make-variable-buffer-local 'org-clock-file-total-minutes
)
512 (defun org-clock-sum (&optional tstart tend
)
513 "Sum the times for each subtree.
514 Puts the resulting times in minutes as a text property on each headline."
516 (let* ((bmp (buffer-modified-p))
517 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
519 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
521 (ltimes (make-vector lmax
0))
526 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
528 (goto-char (point-max))
529 (while (re-search-backward re nil t
)
533 (setq ts
(match-string 2)
536 (apply 'encode-time
(org-parse-time-string ts
)))
538 (apply 'encode-time
(org-parse-time-string te
)))
539 ts
(if tstart
(max ts tstart
) ts
)
540 te
(if tend
(min te tend
) te
)
542 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
545 (setq t1
(+ t1
(string-to-number (match-string 5))
546 (* 60 (string-to-number (match-string 4))))))
548 (setq level
(- (match-end 1) (match-beginning 1)))
549 (when (or (> t1
0) (> (aref ltimes level
) 0))
550 (loop for l from
0 to level do
551 (aset ltimes l
(+ (aref ltimes l
) t1
)))
552 (setq t1
0 time
(aref ltimes level
))
553 (loop for l from level to
(1- lmax
) do
555 (goto-char (match-beginning 0))
556 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
557 (setq org-clock-file-total-minutes
(aref ltimes
0)))
558 (set-buffer-modified-p bmp
)))
560 (defun org-clock-display (&optional total-only
)
561 "Show subtree times in the entire buffer.
562 If TOTAL-ONLY is non-nil, only show the total time for the entire file
565 (org-remove-clock-overlays)
570 (goto-char (point-min))
571 (while (or (and (equal (setq p
(point)) (point-min))
572 (get-text-property p
:org-clock-minutes
))
573 (setq p
(next-single-property-change
574 (point) :org-clock-minutes
)))
576 (when (setq time
(get-text-property p
:org-clock-minutes
))
577 (org-put-clock-overlay time
(funcall outline-level
))))
578 (setq h
(/ org-clock-file-total-minutes
60)
579 m
(- org-clock-file-total-minutes
(* 60 h
)))
580 ;; Arrange to remove the overlays upon next change.
581 (when org-remove-highlights-with-change
582 (org-add-hook 'before-change-functions
'org-remove-clock-overlays
584 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
586 (defvar org-clock-overlays nil
)
587 (make-variable-buffer-local 'org-clock-overlays
)
589 (defun org-put-clock-overlay (time &optional level
)
590 "Put an overlays on the current line, displaying TIME.
591 If LEVEL is given, prefix time with a corresponding number of stars.
592 This creates a new overlay and stores it in `org-clock-overlays', so that it
593 will be easy to remove."
594 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
595 (l (if level
(org-get-valid-level level
0) 0))
596 (fmt (concat "%s " org-time-clocksum-format
"%s"))
599 (org-move-to-column c
)
600 (unless (eolp) (skip-chars-backward "^ \t"))
601 (skip-chars-backward " \t")
602 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
603 tx
(concat (buffer-substring (1- (point)) (point))
604 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
605 (org-add-props (format fmt
606 (make-string l ?
*) h m
607 (make-string (- 16 l
) ?\
))
608 '(face secondary-selection
))
610 (if (not (featurep 'xemacs
))
611 (org-overlay-put ov
'display tx
)
612 (org-overlay-put ov
'invisible t
)
613 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
614 (push ov org-clock-overlays
)))
616 (defun org-remove-clock-overlays (&optional beg end noremove
)
617 "Remove the occur highlights from the buffer.
618 BEG and END are ignored. If NOREMOVE is nil, remove this function
619 from the `before-change-functions' in the current buffer."
621 (unless org-inhibit-highlight-removal
622 (mapc 'org-delete-overlay org-clock-overlays
)
623 (setq org-clock-overlays nil
)
625 (remove-hook 'before-change-functions
626 'org-remove-clock-overlays
'local
))))
628 (defvar state
) ;; dynamically scoped into this function
629 (defun org-clock-out-if-current ()
630 "Clock out if the current entry contains the running clock.
631 This is used to stop the clock after a TODO entry is marked DONE,
632 and is only done if the variable `org-clock-out-when-done' is not nil."
633 (when (and org-clock-out-when-done
634 (member state org-done-keywords
)
635 (equal (marker-buffer org-clock-marker
) (current-buffer))
636 (< (point) org-clock-marker
)
637 (> (save-excursion (outline-next-heading) (point))
639 ;; Clock out, but don't accept a logging message for this.
640 (let ((org-log-note-clock-out nil
))
643 (add-hook 'org-after-todo-state-change-hook
644 'org-clock-out-if-current
)
647 (defun org-get-clocktable (&rest props
)
648 "Get a formatted clocktable with parameters according to PROPS.
649 The table is created in a temporary buffer, fully formatted and
650 fontified, and then returned."
652 (setq props
(plist-put props
:name
"clocktable"))
653 (unless (plist-member props
:maxlevel
)
654 (setq props
(plist-put props
:maxlevel
2)))
655 (unless (plist-member props
:scope
)
656 (setq props
(plist-put props
:scope
'agenda
)))
659 (org-create-dblock props
)
661 (font-lock-fontify-buffer)
663 (buffer-substring (point) (progn
664 (re-search-forward "^#\\+END" nil t
)
667 (defun org-clock-report (&optional arg
)
668 "Create a table containing a report about clocked time.
669 If the cursor is inside an existing clocktable block, then the table
670 will be updated. If not, a new clocktable will be inserted.
671 When called with a prefix argument, move to the first clock table in the
672 buffer and update it."
674 (org-remove-clock-overlays)
676 (org-find-dblock "clocktable")
678 (if (org-in-clocktable-p)
679 (goto-char (org-in-clocktable-p))
680 (org-create-dblock (list :name
"clocktable"
681 :maxlevel
2 :scope
'file
)))
684 (defun org-in-clocktable-p ()
685 "Check if the cursor is in a clocktable."
686 (let ((pos (point)) start
)
689 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
690 (setq start
(match-beginning 0))
691 (re-search-forward "^#\\+END:.*" nil t
)
692 (>= (match-end 0) pos
)
695 (defun org-clock-special-range (key &optional time as-strings
)
696 "Return two times bordering a special time range.
697 Key is a symbol specifying the range and can be one of `today', `yesterday',
698 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
699 A week starts Monday 0:00 and ends Sunday 24:00.
700 The range is determined relative to TIME. TIME defaults to the current time.
701 The return value is a cons cell with two internal times like the ones
702 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
703 the returned times will be formatted strings."
704 (if (integerp key
) (setq key
(intern (number-to-string key
))))
705 (let* ((tm (decode-time (or time
(current-time))))
706 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
707 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
709 (skey (symbol-name key
))
711 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
713 ((string-match "^[0-9]+$" skey
)
714 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
715 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
716 (setq y
(string-to-number (match-string 1 skey
))
717 month
(string-to-number (match-string 2 skey
))
719 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
721 (setq y
(string-to-number (match-string 1 skey
))
722 w
(string-to-number (match-string 2 skey
)))
723 (setq date
(calendar-gregorian-from-absolute
724 (calendar-absolute-from-iso (list w
1 y
))))
725 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
727 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
728 (setq y
(string-to-number (match-string 1 skey
))
729 month
(string-to-number (match-string 2 skey
))
730 d
(string-to-number (match-string 3 skey
))
732 ((string-match "\\([-+][0-9]+\\)$" skey
)
733 (setq shift
(string-to-number (match-string 1 skey
))
734 key
(intern (substring skey
0 (match-beginning 1))))))
736 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
737 ((eq key
'lastweek
) (setq key
'week shift -
1))
738 ((eq key
'lastmonth
) (setq key
'month shift -
1))
739 ((eq key
'lastyear
) (setq key
'year shift -
1))))
741 ((memq key
'(day today
))
742 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
743 ((memq key
'(week thisweek
))
744 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
745 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
746 ((memq key
'(month thismonth
))
747 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
748 ((memq key
'(year thisyear
))
749 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
750 (t (error "No such time block %s" key
)))
751 (setq ts
(encode-time s m h d month y
)
752 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
753 (or d1 d
) (or month1 month
) (or y1 y
)))
754 (setq fm
(cdr org-time-stamp-formats
))
756 ((memq key
'(day today
))
757 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
758 ((memq key
'(week thisweek
))
759 (setq txt
(format-time-string "week %G-W%V" ts
)))
760 ((memq key
'(month thismonth
))
761 (setq txt
(format-time-string "%B %Y" ts
)))
762 ((memq key
'(year thisyear
))
763 (setq txt
(format-time-string "the year %Y" ts
))))
765 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
768 (defun org-clocktable-shift (dir n
)
769 "Try to shift the :block date of the clocktable at point.
770 Point must be in the #+BEGIN: line of a clocktable, or this function
772 DIR is a direction, a symbol `left', `right', `up', or `down'.
773 Both `left' and `down' shift the block toward the past, `up' and `right'
774 push it toward the future.
775 N is the number of shift steps to take. The size of the step depends on
776 the currently selected interval size."
777 (setq n
(prefix-numeric-value n
))
778 (and (memq dir
'(left down
)) (setq n
(- n
)))
780 (goto-char (point-at-bol))
781 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
782 (error "Line needs a :block definition before this command works")
783 (let* ((b (match-beginning 1)) (e (match-end 1))
785 block shift ins y mw d date wp m
)
787 ((equal s
"yesterday") (setq s
"today-1"))
788 ((equal s
"lastweek") (setq s
"thisweek-1"))
789 ((equal s
"lastmonth") (setq s
"thismonth-1"))
790 ((equal s
"lastyear") (setq s
"thisyear-1")))
792 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
793 (setq block
(match-string 1 s
)
794 shift
(if (match-end 2)
795 (string-to-number (match-string 2 s
))
797 (setq shift
(+ shift n
))
798 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
799 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
800 ;; 1 1 2 3 3 4 4 5 6 6 5 2
801 (setq y
(string-to-number (match-string 1 s
))
802 wp
(and (match-end 3) (match-string 3 s
))
803 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
804 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
806 (d (setq ins
(format-time-string
808 (encode-time 0 0 0 (+ d n
) m y
))))
809 ((and wp mw
(> (length wp
) 0))
811 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
812 (setq ins
(format-time-string
814 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
816 (setq ins
(format-time-string
818 (encode-time 0 0 0 1 (+ mw n
) y
))))
820 (setq ins
(number-to-string (+ y n
))))))
821 (t (error "Cannot shift clocktable block")))
825 (delete-region (point) (+ (point) (- e b
)))
826 (beginning-of-line 1)
830 (defun org-dblock-write:clocktable
(params)
831 "Write the standard clocktable."
833 (let* ((hlchars '((1 .
"*") (2 .
"/")))
836 (scope (plist-get params
:scope
))
837 (tostring (plist-get params
:tostring
))
838 (multifile (plist-get params
:multifile
))
839 (header (plist-get params
:header
))
840 (maxlevel (or (plist-get params
:maxlevel
) 3))
841 (step (plist-get params
:step
))
842 (emph (plist-get params
:emphasize
))
843 (ts (plist-get params
:tstart
))
844 (te (plist-get params
:tend
))
845 (block (plist-get params
:block
))
846 (link (plist-get params
:link
))
847 ipos time p level hlc hdl content recalc formula pcol
848 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st
)
849 (setq org-clock-file-total-minutes nil
)
851 (unless (or block
(and ts te
))
852 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
853 (org-clocktable-steps params
)
856 (setq cc
(org-clock-special-range block nil t
)
857 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
858 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
859 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
860 (when (and ts
(listp ts
))
861 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
862 (when (and te
(listp te
))
863 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
864 ;; Now the times are strings we can parse.
865 (if ts
(setq ts
(time-to-seconds
866 (apply 'encode-time
(org-parse-time-string ts
)))))
867 (if te
(setq te
(time-to-seconds
868 (apply 'encode-time
(org-parse-time-string te
)))))
869 (move-marker ins
(point))
872 ;; Get the right scope
875 ((and scope
(listp scope
) (symbolp (car scope
)))
876 (setq scope
(eval scope
)))
878 (setq scope
(org-agenda-files t
)))
879 ((eq scope
'agenda-with-archives
)
880 (setq scope
(org-agenda-files t
))
881 (setq scope
(org-add-archive-files scope
)))
882 ((eq scope
'file-with-archives
)
883 (setq scope
(org-add-archive-files (list (buffer-file-name)))
885 (setq scope-is-list
(and scope
(listp scope
)))
889 ((eq scope
'file
) (widen))
890 ((eq scope
'subtree
) (org-narrow-to-subtree))
892 (while (org-up-heading-safe))
893 (org-narrow-to-subtree))
894 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
895 (symbol-name scope
)))
896 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
898 (while (org-up-heading-safe)
899 (looking-at outline-regexp
)
900 (if (<= (org-reduced-level (funcall outline-level
)) level
)
902 (org-narrow-to-subtree))
906 (p1 (copy-sequence params
))
908 (setq p1
(plist-put p1
:tostring t
))
909 (setq p1
(plist-put p1
:multifile t
))
910 (setq p1
(plist-put p1
:scope
'file
))
911 (org-prepare-agenda-buffers files
)
912 (while (setq file
(pop files
))
913 (with-current-buffer (find-buffer-visiting file
)
914 (setq tbl1
(org-dblock-write:clocktable p1
))
916 (push (org-clocktable-add-file
918 (concat "| |*File time*|*"
919 (org-minutes-to-hh:mm-string
920 org-clock-file-total-minutes
)
923 (setq total-time
(+ (or total-time
0)
924 org-clock-file-total-minutes
))))))))
927 (unless scope-is-list
928 (org-clock-sum ts te
)
929 (goto-char (point-min))
931 (while (or (and (bobp) (prog1 st
(setq st nil
))
932 (get-text-property (point) :org-clock-minutes
)
933 (setq p
(point-min)))
934 (setq p
(next-single-property-change (point) :org-clock-minutes
)))
936 (when (setq time
(get-text-property p
:org-clock-minutes
))
938 (beginning-of-line 1)
939 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
940 (setq level
(org-reduced-level
941 (- (match-end 1) (match-beginning 1))))
943 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
946 (org-make-link-string
947 (format "file:%s::%s"
950 (org-make-org-heading-search-string
953 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
955 "| " (int-to-string level
) "|" hlc hdl hlc
" |"
956 (make-string (1- level
) ?|
)
957 hlc
(org-minutes-to-hh:mm-string time
) hlc
959 (setq tbl
(nreverse tbl
))
961 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
963 (insert-before-markers
968 (format-time-string (cdr org-time-stamp-formats
))
971 (if block
(concat ", for " range-text
".") "")
973 (if scope-is-list
"|File" "")
974 "|L|Headline|Time|\n")
975 (setq total-time
(or total-time org-clock-file-total-minutes
))
976 (insert-before-markers
978 (if scope-is-list
"|" "")
981 (org-minutes-to-hh:mm-string
(or total-time
0))
983 (setq tbl
(delq nil tbl
))
984 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
985 (equal (substring (car tbl
) 0 2) "|-"))
987 (insert-before-markers (mapconcat
988 'identity
(delq nil tbl
)
989 (if scope-is-list
"\n|-\n" "\n")))
990 (backward-delete-char 1)
991 (if (setq formula
(plist-get params
:formula
))
994 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
997 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1000 (+ 3 (if scope-is-list
1 0))
1001 (+ (if scope-is-list
1 0) 3)
1005 (insert "\n#+TBLFM: " formula
)
1007 (t (error "invalid formula in clocktable")))
1008 ;; Should we rescue an old formula?
1009 (when (stringp (setq content
(plist-get params
:content
)))
1010 (when (string-match "^\\(#\\+TBLFM:.*\\)" content
)
1012 (insert "\n" (match-string 1 (plist-get params
:content
)))
1013 (beginning-of-line 0))))
1015 (skip-chars-forward "^|")
1019 (save-excursion (org-table-goto-column pcol nil
'force
)
1021 (org-table-recalculate 'all
))
1022 (when rm-file-column
1024 (org-table-delete-column)))))))
1026 (defun org-clocktable-steps (params)
1027 (let* ((p1 (copy-sequence params
))
1028 (ts (plist-get p1
:tstart
))
1029 (te (plist-get p1
:tend
))
1030 (step0 (plist-get p1
:step
))
1031 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1032 (block (plist-get p1
:block
))
1035 (setq cc
(org-clock-special-range block nil t
)
1036 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1037 (if ts
(setq ts
(time-to-seconds
1038 (apply 'encode-time
(org-parse-time-string ts
)))))
1039 (if te
(setq te
(time-to-seconds
1040 (apply 'encode-time
(org-parse-time-string te
)))))
1041 (setq p1
(plist-put p1
:header
""))
1042 (setq p1
(plist-put p1
:step nil
))
1043 (setq p1
(plist-put p1
:block nil
))
1045 (or (bolp) (insert "\n"))
1046 (setq p1
(plist-put p1
:tstart
(format-time-string
1047 (car org-time-stamp-formats
)
1048 (seconds-to-time ts
))))
1049 (setq p1
(plist-put p1
:tend
(format-time-string
1050 (car org-time-stamp-formats
)
1051 (seconds-to-time (setq ts
(+ ts step
))))))
1052 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1053 (plist-get p1
:tstart
) "\n")
1054 (org-dblock-write:clocktable p1
)
1055 (re-search-forward "#\\+END:")
1058 (defun org-clocktable-add-file (file table
)
1060 (let ((lines (org-split-string table
"\n"))
1061 (ff (file-name-nondirectory file
)))
1062 (mapconcat 'identity
1064 (if (string-match org-table-dataline-regexp x
)
1070 (defun org-clock-time%
(total &rest strings
)
1071 "Compute a time fraction in percent.
1072 TOTAL s a time string like 10:21 specifying the total times.
1073 STRINGS is a list of strings that should be checked for a time.
1074 The first string that does have a time will be used.
1075 This function is made for clock tables."
1076 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1080 (if (not (string-match re total
))
1082 (setq tot
(+ (string-to-number (match-string 2 total
))
1083 (* 60 (string-to-number (match-string 1 total
)))))
1084 (if (= tot
0.
) (throw 'exit
0.
)))
1085 (while (setq s
(pop strings
))
1086 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1088 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1089 (* 60 (string-to-number (match-string 1 s
)))))
1093 (defun org-clock-save ()
1094 "Persist various clock-related data to disk.
1095 The details of what will be saved are regulated by the variable
1096 `org-clock-persist'."
1097 (when org-clock-persist
1099 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1101 (delete-region (point-min) (point-max))
1103 (insert (format ";; org-persist.el - %s at %s\n"
1104 system-name
(format-time-string
1105 (cdr org-time-stamp-formats
))))
1106 (if (and (setq b
(marker-buffer org-clock-marker
))
1107 (setq b
(or (buffer-base-buffer b
) b
))
1109 (buffer-file-name b
)
1110 (or (not org-clock-persist-query-save
)
1111 (y-or-n-p (concat "Save current clock ("
1112 (substring-no-properties org-clock-heading
)
1114 (insert "(setq resume-clock '(\""
1115 (buffer-file-name (marker-buffer org-clock-marker
))
1116 "\" . " (int-to-string (marker-position org-clock-marker
))
1118 ;; Store clocked task history. Tasks are stored reversed to make
1120 (when (and org-clock-history
(eq org-clock-persist t
))
1122 "(setq stored-clock-history '("
1125 (when (and (setq b
(marker-buffer m
))
1126 (setq b
(or (buffer-base-buffer b
) b
))
1128 (buffer-file-name b
))
1129 (concat "(\"" (buffer-file-name b
)
1130 "\" . " (int-to-string (marker-position m
))
1132 (reverse org-clock-history
) " ") "))\n"))
1134 (kill-buffer (current-buffer)))))))
1136 (defvar org-clock-loaded nil
1137 "Was the clock file loaded?")
1139 (defun org-clock-load ()
1140 "Load various clock-related data from disk, optionally resuming
1142 (when (and org-clock-persist
(not org-clock-loaded
))
1143 (let ((filename (expand-file-name org-clock-persist-file
))
1144 (org-clock-in-resume 'auto-restart
)
1145 resume-clock stored-clock-history
)
1146 (if (not (file-readable-p filename
))
1147 (message "Not restoring clock data; %s not found"
1148 org-clock-persist-file
)
1149 (message "%s" "Restoring clock data")
1150 (setq org-clock-loaded t
)
1151 (load-file filename
)
1153 (when stored-clock-history
1154 (save-window-excursion
1155 (mapc (lambda (task)
1156 (if (file-exists-p (car task
))
1157 (org-clock-history-push (cdr task
)
1158 (find-file (car task
)))))
1159 stored-clock-history
)))
1161 (when (and resume-clock org-clock-persist
1162 (file-exists-p (car resume-clock
))
1163 (or (not org-clock-persist-query-resume
)
1167 (with-current-buffer (find-file (car resume-clock
))
1169 (goto-char (cdr resume-clock
))
1170 (org-back-to-heading t
)
1171 (and (looking-at org-complex-heading-regexp
)
1174 (when (file-exists-p (car resume-clock
))
1175 (with-current-buffer (find-file (car resume-clock
))
1176 (goto-char (cdr resume-clock
))
1178 (if (org-invisible-p)
1179 (org-show-context)))))))))
1182 (defun org-clock-persistence-insinuate ()
1183 "Set up hooks for clock persistence"
1184 (add-hook 'org-mode-hook
'org-clock-load
)
1185 (add-hook 'kill-emacs-hook
'org-clock-save
))
1187 (provide 'org-clock
)
1189 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1191 ;;; org-clock.el ends here