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
'(face 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'."
273 (let ((interrupting (marker-buffer org-clock-marker
))
274 ts selected-task target-pos
)
275 (when (equal select
'(4))
276 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
278 (setq selected-task
(copy-marker selected-task
))
281 ;; We are interrupting the clocking of a differnt task.
282 ;; Save a marker to this task, so that we can go back.
283 (move-marker org-clock-interrupted-task
284 (marker-position org-clock-marker
)
285 (marker-buffer org-clock-marker
))
288 (when (equal select
'(16))
289 ;; Mark as default clocking task
291 (org-back-to-heading t
)
292 (move-marker org-clock-default-task
(point))))
294 (setq target-pos
(point)) ;; we want to clock in at this location
296 (when (and selected-task
(marker-buffer selected-task
))
297 ;; There is a selected task, move to the correct buffer
298 ;; and set the new target position.
299 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
300 (setq target-pos
(marker-position selected-task
))
301 (move-marker selected-task nil
))
305 (goto-char target-pos
)
306 (org-back-to-heading t
)
307 (or interrupting
(move-marker org-clock-interrupted-task nil
))
308 (org-clock-history-push)
309 (cond ((functionp org-clock-in-switch-to-state
)
310 (looking-at org-complex-heading-regexp
)
311 (let ((newstate (funcall org-clock-in-switch-to-state
(match-string 2))))
312 (if newstate
(org-todo newstate
))))
313 ((and org-clock-in-switch-to-state
314 (not (looking-at (concat outline-regexp
"[ \t]*"
315 org-clock-in-switch-to-state
317 (org-todo org-clock-in-switch-to-state
)))
318 (setq org-clock-heading-for-remember
319 (and (looking-at org-complex-heading-regexp
)
321 (org-trim (buffer-substring (match-end 1) (match-end 4)))))
322 (setq org-clock-heading
323 (cond ((and org-clock-heading-function
324 (functionp org-clock-heading-function
))
325 (funcall org-clock-heading-function
))
326 ((looking-at org-complex-heading-regexp
)
329 (setq org-clock-heading
(org-propertize org-clock-heading
'face nil
))
330 (org-clock-find-position)
331 (if (and org-clock-in-resume
332 (looking-at (concat "^[ \\t]* " org-clock-string
333 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
334 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\]$")))
335 (progn (message "Matched %s" (match-string 1))
336 (setq ts
(concat "[" (match-string 1) "]"))
337 (goto-char (match-end 1))
338 (setq org-clock-start-time
339 (apply 'encode-time
(org-parse-time-string (match-string 1)))))
341 (insert "\n") (backward-char 1)
342 (org-indent-line-function)
343 (insert org-clock-string
" ")
344 (setq org-clock-start-time
(current-time))
345 (setq ts
(org-insert-time-stamp org-clock-start-time
'with-hm
'inactive
))))
346 (move-marker org-clock-marker
(point) (buffer-base-buffer))
347 (or global-mode-string
(setq global-mode-string
'("")))
348 (or (memq 'org-mode-line-string global-mode-string
)
349 (setq global-mode-string
350 (append global-mode-string
'(org-mode-line-string))))
351 (org-update-mode-line)
352 (setq org-mode-line-timer
353 (run-with-timer 60 60 'org-update-mode-line
))
354 (message "Clock started at %s" ts
))))))
356 (defun org-clock-find-position ()
357 "Find the location where the next clock line should be inserted."
358 (org-back-to-heading t
)
360 (let ((beg (save-excursion
361 (beginning-of-line 2)
362 (or (bolp) (newline))
364 (end (progn (outline-next-heading) (point)))
365 (re (concat "^[ \t]*" org-clock-string
))
369 (when (eobp) (newline) (setq end
(max (point) end
)))
370 (when (re-search-forward "^[ \t]*:CLOCK:" end t
)
371 ;; we seem to have a CLOCK drawer, so go there.
372 (beginning-of-line 2)
374 ;; Lets count the CLOCK lines
376 (while (re-search-forward re end t
)
377 (setq first
(or first
(match-beginning 0))
378 last
(match-beginning 0)
380 (when (and (integerp org-clock-into-drawer
)
381 (>= (1+ cnt
) org-clock-into-drawer
))
382 ;; Wrap current entries into a new drawer
384 (beginning-of-line 2)
385 (if (org-at-item-p) (org-end-of-item))
387 (beginning-of-line 0)
388 (org-indent-line-function)
391 (beginning-of-line 0)
392 (org-indent-line-function)
394 (beginning-of-line 2)
398 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
399 (not (equal (match-string 1) org-clock-string
)))
400 ;; Planning info, skip to after it
401 (beginning-of-line 2)
402 (or (bolp) (newline)))
403 (when (eq t org-clock-into-drawer
)
404 (insert ":CLOCK:\n:END:\n")
405 (beginning-of-line 0)
406 (org-indent-line-function)
407 (beginning-of-line 0)
409 (org-indent-line-function)
410 (beginning-of-line 2)))))
412 (defun org-clock-out (&optional fail-quietly
)
413 "Stop the currently running clock.
414 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
417 (if (not (marker-buffer org-clock-marker
))
418 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
419 (let (ts te s h m remove
)
421 (set-buffer (marker-buffer org-clock-marker
))
424 (goto-char org-clock-marker
)
425 (beginning-of-line 1)
426 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
427 (equal (match-string 1) org-clock-string
))
428 (setq ts
(match-string 2))
429 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
430 (goto-char (match-end 0))
431 (delete-region (point) (point-at-eol))
433 (setq te
(org-insert-time-stamp (current-time) 'with-hm
'inactive
))
434 (setq s
(- (time-to-seconds (apply 'encode-time
(org-parse-time-string te
)))
435 (time-to-seconds (apply 'encode-time
(org-parse-time-string ts
))))
440 (insert " => " (format "%2d:%02d" h m
))
441 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
443 (beginning-of-line 1)
444 (delete-region (point) (point-at-eol))
445 (and (looking-at "\n") (> (point-max) (1+ (point)))
447 (move-marker org-clock-marker nil
)
448 (when org-log-note-clock-out
449 (org-add-log-setup 'clock-out nil nil nil
450 (concat "# Task: " (org-get-heading t
) "\n\n")))
451 (when org-mode-line-timer
452 (cancel-timer org-mode-line-timer
)
453 (setq org-mode-line-timer nil
))
454 (setq global-mode-string
455 (delq 'org-mode-line-string global-mode-string
))
456 (force-mode-line-update)
457 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
458 (if remove
" => LINE REMOVED" "")))))))
460 (defun org-clock-cancel ()
461 "Cancel the running clock be removing the start timestamp."
463 (if (not (marker-buffer org-clock-marker
))
464 (error "No active clock"))
466 (set-buffer (marker-buffer org-clock-marker
))
467 (goto-char org-clock-marker
)
468 (delete-region (1- (point-at-bol)) (point-at-eol)))
469 (setq global-mode-string
470 (delq 'org-mode-line-string global-mode-string
))
471 (force-mode-line-update)
472 (message "Clock canceled"))
474 (defun org-clock-goto (&optional select
)
475 "Go to the currently clocked-in entry.
476 With prefix arg SELECT, offer recently clocked tasks."
479 (org-clock-select-task "Select task to go to: ")
481 (if (not (marker-buffer m
))
483 (error "No task selected")
484 (error "No active clock")))
485 (switch-to-buffer (marker-buffer m
))
486 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
489 (org-back-to-heading)
490 (org-cycle-hide-drawers 'children
)
493 (defvar org-clock-file-total-minutes nil
494 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
495 (make-variable-buffer-local 'org-clock-file-total-minutes
)
497 (defun org-clock-sum (&optional tstart tend
)
498 "Sum the times for each subtree.
499 Puts the resulting times in minutes as a text property on each headline."
501 (let* ((bmp (buffer-modified-p))
502 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
504 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
506 (ltimes (make-vector lmax
0))
511 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
513 (goto-char (point-max))
514 (while (re-search-backward re nil t
)
518 (setq ts
(match-string 2)
521 (apply 'encode-time
(org-parse-time-string ts
)))
523 (apply 'encode-time
(org-parse-time-string te
)))
524 ts
(if tstart
(max ts tstart
) ts
)
525 te
(if tend
(min te tend
) te
)
527 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
530 (setq t1
(+ t1
(string-to-number (match-string 5))
531 (* 60 (string-to-number (match-string 4))))))
533 (setq level
(- (match-end 1) (match-beginning 1)))
534 (when (or (> t1
0) (> (aref ltimes level
) 0))
535 (loop for l from
0 to level do
536 (aset ltimes l
(+ (aref ltimes l
) t1
)))
537 (setq t1
0 time
(aref ltimes level
))
538 (loop for l from level to
(1- lmax
) do
540 (goto-char (match-beginning 0))
541 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
542 (setq org-clock-file-total-minutes
(aref ltimes
0)))
543 (set-buffer-modified-p bmp
)))
545 (defun org-clock-display (&optional total-only
)
546 "Show subtree times in the entire buffer.
547 If TOTAL-ONLY is non-nil, only show the total time for the entire file
550 (org-remove-clock-overlays)
555 (goto-char (point-min))
556 (while (or (and (equal (setq p
(point)) (point-min))
557 (get-text-property p
:org-clock-minutes
))
558 (setq p
(next-single-property-change
559 (point) :org-clock-minutes
)))
561 (when (setq time
(get-text-property p
:org-clock-minutes
))
562 (org-put-clock-overlay time
(funcall outline-level
))))
563 (setq h
(/ org-clock-file-total-minutes
60)
564 m
(- org-clock-file-total-minutes
(* 60 h
)))
565 ;; Arrange to remove the overlays upon next change.
566 (when org-remove-highlights-with-change
567 (org-add-hook 'before-change-functions
'org-remove-clock-overlays
569 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
571 (defvar org-clock-overlays nil
)
572 (make-variable-buffer-local 'org-clock-overlays
)
574 (defun org-put-clock-overlay (time &optional level
)
575 "Put an overlays on the current line, displaying TIME.
576 If LEVEL is given, prefix time with a corresponding number of stars.
577 This creates a new overlay and stores it in `org-clock-overlays', so that it
578 will be easy to remove."
579 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
580 (l (if level
(org-get-valid-level level
0) 0))
581 (fmt (concat "%s " org-time-clocksum-format
"%s"))
584 (org-move-to-column c
)
585 (unless (eolp) (skip-chars-backward "^ \t"))
586 (skip-chars-backward " \t")
587 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
588 tx
(concat (buffer-substring (1- (point)) (point))
589 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
590 (org-add-props (format fmt
591 (make-string l ?
*) h m
592 (make-string (- 16 l
) ?\
))
593 '(face secondary-selection
))
595 (if (not (featurep 'xemacs
))
596 (org-overlay-put ov
'display tx
)
597 (org-overlay-put ov
'invisible t
)
598 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
599 (push ov org-clock-overlays
)))
601 (defun org-remove-clock-overlays (&optional beg end noremove
)
602 "Remove the occur highlights from the buffer.
603 BEG and END are ignored. If NOREMOVE is nil, remove this function
604 from the `before-change-functions' in the current buffer."
606 (unless org-inhibit-highlight-removal
607 (mapc 'org-delete-overlay org-clock-overlays
)
608 (setq org-clock-overlays nil
)
610 (remove-hook 'before-change-functions
611 'org-remove-clock-overlays
'local
))))
613 (defvar state
) ;; dynamically scoped into this function
614 (defun org-clock-out-if-current ()
615 "Clock out if the current entry contains the running clock.
616 This is used to stop the clock after a TODO entry is marked DONE,
617 and is only done if the variable `org-clock-out-when-done' is not nil."
618 (when (and org-clock-out-when-done
619 (member state org-done-keywords
)
620 (equal (marker-buffer org-clock-marker
) (current-buffer))
621 (< (point) org-clock-marker
)
622 (> (save-excursion (outline-next-heading) (point))
624 ;; Clock out, but don't accept a logging message for this.
625 (let ((org-log-note-clock-out nil
))
628 (add-hook 'org-after-todo-state-change-hook
629 'org-clock-out-if-current
)
632 (defun org-get-clocktable (&rest props
)
633 "Get a formatted clocktable with parameters according to PROPS.
634 The table is created in a temporary buffer, fully formatted and
635 fontified, and then returned."
637 (setq props
(plist-put props
:name
"clocktable"))
638 (unless (plist-member props
:maxlevel
)
639 (setq props
(plist-put props
:maxlevel
2)))
640 (unless (plist-member props
:scope
)
641 (setq props
(plist-put props
:scope
'agenda
)))
644 (org-create-dblock props
)
646 (font-lock-fontify-buffer)
648 (buffer-substring (point) (progn
649 (re-search-forward "^#\\+END" nil t
)
652 (defun org-clock-report (&optional arg
)
653 "Create a table containing a report about clocked time.
654 If the cursor is inside an existing clocktable block, then the table
655 will be updated. If not, a new clocktable will be inserted.
656 When called with a prefix argument, move to the first clock table in the
657 buffer and update it."
659 (org-remove-clock-overlays)
661 (org-find-dblock "clocktable")
663 (if (org-in-clocktable-p)
664 (goto-char (org-in-clocktable-p))
665 (org-create-dblock (list :name
"clocktable"
666 :maxlevel
2 :scope
'file
)))
669 (defun org-in-clocktable-p ()
670 "Check if the cursor is in a clocktable."
671 (let ((pos (point)) start
)
674 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
675 (setq start
(match-beginning 0))
676 (re-search-forward "^#\\+END:.*" nil t
)
677 (>= (match-end 0) pos
)
680 (defun org-clock-special-range (key &optional time as-strings
)
681 "Return two times bordering a special time range.
682 Key is a symbol specifying the range and can be one of `today', `yesterday',
683 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
684 A week starts Monday 0:00 and ends Sunday 24:00.
685 The range is determined relative to TIME. TIME defaults to the current time.
686 The return value is a cons cell with two internal times like the ones
687 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
688 the returned times will be formatted strings."
689 (if (integerp key
) (setq key
(intern (number-to-string key
))))
690 (let* ((tm (decode-time (or time
(current-time))))
691 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
692 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
694 (skey (symbol-name key
))
696 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
698 ((string-match "^[0-9]+$" skey
)
699 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
700 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
701 (setq y
(string-to-number (match-string 1 skey
))
702 month
(string-to-number (match-string 2 skey
))
704 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
706 (setq y
(string-to-number (match-string 1 skey
))
707 w
(string-to-number (match-string 2 skey
)))
708 (setq date
(calendar-gregorian-from-absolute
709 (calendar-absolute-from-iso (list w
1 y
))))
710 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
712 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
713 (setq y
(string-to-number (match-string 1 skey
))
714 month
(string-to-number (match-string 2 skey
))
715 d
(string-to-number (match-string 3 skey
))
717 ((string-match "\\([-+][0-9]+\\)$" skey
)
718 (setq shift
(string-to-number (match-string 1 skey
))
719 key
(intern (substring skey
0 (match-beginning 1))))))
721 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
722 ((eq key
'lastweek
) (setq key
'week shift -
1))
723 ((eq key
'lastmonth
) (setq key
'month shift -
1))
724 ((eq key
'lastyear
) (setq key
'year shift -
1))))
726 ((memq key
'(day today
))
727 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
728 ((memq key
'(week thisweek
))
729 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
730 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
731 ((memq key
'(month thismonth
))
732 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
733 ((memq key
'(year thisyear
))
734 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
735 (t (error "No such time block %s" key
)))
736 (setq ts
(encode-time s m h d month y
)
737 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
738 (or d1 d
) (or month1 month
) (or y1 y
)))
739 (setq fm
(cdr org-time-stamp-formats
))
741 ((memq key
'(day today
))
742 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
743 ((memq key
'(week thisweek
))
744 (setq txt
(format-time-string "week %G-W%V" ts
)))
745 ((memq key
'(month thismonth
))
746 (setq txt
(format-time-string "%B %Y" ts
)))
747 ((memq key
'(year thisyear
))
748 (setq txt
(format-time-string "the year %Y" ts
))))
750 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
753 (defun org-clocktable-shift (dir n
)
754 "Try to shift the :block date of the clocktable at point.
755 Point must be in the #+BEGIN: line of a clocktable, or this function
757 DIR is a direction, a symbol `left', `right', `up', or `down'.
758 Both `left' and `down' shift the block toward the past, `up' and `right'
759 push it toward the future.
760 N is the number of shift steps to take. The size of the step depends on
761 the currently selected interval size."
762 (setq n
(prefix-numeric-value n
))
763 (and (memq dir
'(left down
)) (setq n
(- n
)))
765 (goto-char (point-at-bol))
766 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
767 (error "Line needs a :block definition before this command works")
768 (let* ((b (match-beginning 1)) (e (match-end 1))
770 block shift ins y mw d date wp m
)
772 ((equal s
"yesterday") (setq s
"today-1"))
773 ((equal s
"lastweek") (setq s
"thisweek-1"))
774 ((equal s
"lastmonth") (setq s
"thismonth-1"))
775 ((equal s
"lastyear") (setq s
"thisyear-1")))
777 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
778 (setq block
(match-string 1 s
)
779 shift
(if (match-end 2)
780 (string-to-number (match-string 2 s
))
782 (setq shift
(+ shift n
))
783 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
784 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
785 ;; 1 1 2 3 3 4 4 5 6 6 5 2
786 (setq y
(string-to-number (match-string 1 s
))
787 wp
(and (match-end 3) (match-string 3 s
))
788 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
789 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
791 (d (setq ins
(format-time-string
793 (encode-time 0 0 0 (+ d n
) m y
))))
794 ((and wp mw
(> (length wp
) 0))
796 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
797 (setq ins
(format-time-string
799 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
801 (setq ins
(format-time-string
803 (encode-time 0 0 0 1 (+ mw n
) y
))))
805 (setq ins
(number-to-string (+ y n
))))))
806 (t (error "Cannot shift clocktable block")))
810 (delete-region (point) (+ (point) (- e b
)))
811 (beginning-of-line 1)
815 (defun org-dblock-write:clocktable
(params)
816 "Write the standard clocktable."
818 (let* ((hlchars '((1 .
"*") (2 .
"/")))
821 (scope (plist-get params
:scope
))
822 (tostring (plist-get params
:tostring
))
823 (multifile (plist-get params
:multifile
))
824 (header (plist-get params
:header
))
825 (maxlevel (or (plist-get params
:maxlevel
) 3))
826 (step (plist-get params
:step
))
827 (emph (plist-get params
:emphasize
))
828 (ts (plist-get params
:tstart
))
829 (te (plist-get params
:tend
))
830 (block (plist-get params
:block
))
831 (link (plist-get params
:link
))
832 ipos time p level hlc hdl content recalc formula pcol
833 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list
)
834 (setq org-clock-file-total-minutes nil
)
836 (unless (or block
(and ts te
))
837 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
838 (org-clocktable-steps params
)
841 (setq cc
(org-clock-special-range block nil t
)
842 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
843 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
844 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
845 (when (and ts
(listp ts
))
846 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
847 (when (and te
(listp te
))
848 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
849 ;; Now the times are strings we can parse.
850 (if ts
(setq ts
(time-to-seconds
851 (apply 'encode-time
(org-parse-time-string ts
)))))
852 (if te
(setq te
(time-to-seconds
853 (apply 'encode-time
(org-parse-time-string te
)))))
854 (move-marker ins
(point))
857 ;; Get the right scope
860 ((and scope
(listp scope
) (symbolp (car scope
)))
861 (setq scope
(eval scope
)))
863 (setq scope
(org-agenda-files t
)))
864 ((eq scope
'agenda-with-archives
)
865 (setq scope
(org-agenda-files t
))
866 (setq scope
(org-add-archive-files scope
)))
867 ((eq scope
'file-with-archives
)
868 (setq scope
(org-add-archive-files (list (buffer-file-name)))
870 (setq scope-is-list
(and scope
(listp scope
)))
874 ((eq scope
'file
) (widen))
875 ((eq scope
'subtree
) (org-narrow-to-subtree))
877 (while (org-up-heading-safe))
878 (org-narrow-to-subtree))
879 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
880 (symbol-name scope
)))
881 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
883 (while (org-up-heading-safe)
884 (looking-at outline-regexp
)
885 (if (<= (org-reduced-level (funcall outline-level
)) level
)
887 (org-narrow-to-subtree))
891 (p1 (copy-sequence params
))
893 (setq p1
(plist-put p1
:tostring t
))
894 (setq p1
(plist-put p1
:multifile t
))
895 (setq p1
(plist-put p1
:scope
'file
))
896 (org-prepare-agenda-buffers files
)
897 (while (setq file
(pop files
))
898 (with-current-buffer (find-buffer-visiting file
)
899 (setq tbl1
(org-dblock-write:clocktable p1
))
901 (push (org-clocktable-add-file
903 (concat "| |*File time*|*"
904 (org-minutes-to-hh:mm-string
905 org-clock-file-total-minutes
)
908 (setq total-time
(+ (or total-time
0)
909 org-clock-file-total-minutes
))))))))
912 (unless scope-is-list
913 (org-clock-sum ts te
)
914 (goto-char (point-min))
915 (while (setq p
(next-single-property-change (point) :org-clock-minutes
))
917 (when (setq time
(get-text-property p
:org-clock-minutes
))
919 (beginning-of-line 1)
920 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
921 (setq level
(org-reduced-level
922 (- (match-end 1) (match-beginning 1))))
924 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
927 (org-make-link-string
928 (format "file:%s::%s"
931 (org-make-org-heading-search-string
934 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
936 "| " (int-to-string level
) "|" hlc hdl hlc
" |"
937 (make-string (1- level
) ?|
)
938 hlc
(org-minutes-to-hh:mm-string time
) hlc
940 (setq tbl
(nreverse tbl
))
942 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
944 (insert-before-markers
949 (format-time-string (cdr org-time-stamp-formats
))
952 (if block
(concat ", for " range-text
".") "")
954 (if scope-is-list
"|File" "")
955 "|L|Headline|Time|\n")
956 (setq total-time
(or total-time org-clock-file-total-minutes
))
957 (insert-before-markers
959 (if scope-is-list
"|" "")
962 (org-minutes-to-hh:mm-string
(or total-time
0))
964 (setq tbl
(delq nil tbl
))
965 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
966 (equal (substring (car tbl
) 0 2) "|-"))
968 (insert-before-markers (mapconcat
969 'identity
(delq nil tbl
)
970 (if scope-is-list
"\n|-\n" "\n")))
971 (backward-delete-char 1)
972 (if (setq formula
(plist-get params
:formula
))
975 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
978 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
981 (+ 3 (if scope-is-list
1 0))
982 (+ (if scope-is-list
1 0) 3)
986 (insert "\n#+TBLFM: " formula
)
988 (t (error "invalid formula in clocktable")))
989 ;; Should we rescue an old formula?
990 (when (stringp (setq content
(plist-get params
:content
)))
991 (when (string-match "^\\(#\\+TBLFM:.*\\)" content
)
993 (insert "\n" (match-string 1 (plist-get params
:content
)))
994 (beginning-of-line 0))))
996 (skip-chars-forward "^|")
1000 (save-excursion (org-table-goto-column pcol nil
'force
)
1002 (org-table-recalculate 'all
))
1003 (when rm-file-column
1005 (org-table-delete-column)))))))
1007 (defun org-clocktable-steps (params)
1008 (let* ((p1 (copy-sequence params
))
1009 (ts (plist-get p1
:tstart
))
1010 (te (plist-get p1
:tend
))
1011 (step0 (plist-get p1
:step
))
1012 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1013 (block (plist-get p1
:block
))
1016 (setq cc
(org-clock-special-range block nil t
)
1017 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1018 (if ts
(setq ts
(time-to-seconds
1019 (apply 'encode-time
(org-parse-time-string ts
)))))
1020 (if te
(setq te
(time-to-seconds
1021 (apply 'encode-time
(org-parse-time-string te
)))))
1022 (setq p1
(plist-put p1
:header
""))
1023 (setq p1
(plist-put p1
:step nil
))
1024 (setq p1
(plist-put p1
:block nil
))
1026 (or (bolp) (insert "\n"))
1027 (setq p1
(plist-put p1
:tstart
(format-time-string
1028 (car org-time-stamp-formats
)
1029 (seconds-to-time ts
))))
1030 (setq p1
(plist-put p1
:tend
(format-time-string
1031 (car org-time-stamp-formats
)
1032 (seconds-to-time (setq ts
(+ ts step
))))))
1033 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1034 (plist-get p1
:tstart
) "\n")
1035 (org-dblock-write:clocktable p1
)
1036 (re-search-forward "#\\+END:")
1039 (defun org-clocktable-add-file (file table
)
1041 (let ((lines (org-split-string table
"\n"))
1042 (ff (file-name-nondirectory file
)))
1043 (mapconcat 'identity
1045 (if (string-match org-table-dataline-regexp x
)
1051 (defun org-clock-time%
(total &rest strings
)
1052 "Compute a time fraction in percent.
1053 TOTAL s a time string like 10:21 specifying the total times.
1054 STRINGS is a list of strings that should be checked for a time.
1055 The first string that does have a time will be used.
1056 This function is made for clock tables."
1057 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1061 (if (not (string-match re total
))
1063 (setq tot
(+ (string-to-number (match-string 2 total
))
1064 (* 60 (string-to-number (match-string 1 total
)))))
1065 (if (= tot
0.
) (throw 'exit
0.
)))
1066 (while (setq s
(pop strings
))
1067 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1069 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1070 (* 60 (string-to-number (match-string 1 s
)))))
1074 (defun org-clock-save ()
1075 "Persist various clock-related data to disk.
1076 The details of what will be saved are regulated by the variable
1077 `org-clock-persist'."
1078 (when org-clock-persist
1080 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1082 (delete-region (point-min) (point-max))
1084 (insert (format ";; org-persist.el - %s at %s\n"
1085 system-name
(format-time-string
1086 (cdr org-time-stamp-formats
))))
1087 (if (and (setq b
(marker-buffer org-clock-marker
))
1088 (setq b
(or (buffer-base-buffer b
) b
))
1090 (buffer-file-name b
)
1091 (or (not org-clock-persist-query-save
)
1092 (y-or-n-p (concat "Save current clock ("
1093 (substring-no-properties org-clock-heading
)
1095 (insert "(setq resume-clock '(\""
1096 (buffer-file-name (marker-buffer org-clock-marker
))
1097 "\" . " (int-to-string (marker-position org-clock-marker
))
1099 ;; Store clocked task history. Tasks are stored reversed to make
1101 (when (and org-clock-history
(eq org-clock-persist t
))
1103 "(setq stored-clock-history '("
1106 (when (and (setq b
(marker-buffer m
))
1107 (setq b
(or (buffer-base-buffer b
) b
))
1109 (buffer-file-name b
))
1110 (concat "(\"" (buffer-file-name b
)
1111 "\" . " (int-to-string (marker-position m
))
1113 (reverse org-clock-history
) " ") "))\n"))
1115 (kill-buffer (current-buffer)))))))
1117 (defvar org-clock-loaded nil
1118 "Was the clock file loaded?")
1120 (defun org-clock-load ()
1121 "Load various clock-related data from disk, optionally resuming
1123 (when (and org-clock-persist
(not org-clock-loaded
))
1124 (let ((filename (expand-file-name org-clock-persist-file
))
1125 (org-clock-in-resume t
)
1126 resume-clock stored-clock-history
)
1127 (if (not (file-readable-p filename
))
1128 (message "Not restoring clock data; %s not found"
1129 org-clock-persist-file
)
1130 (message "%s" "Restoring clock data")
1131 (setq org-clock-loaded t
)
1132 (load-file filename
)
1134 (when stored-clock-history
1135 (save-window-excursion
1136 (mapc (lambda (task)
1137 (if (file-exists-p (car task
))
1138 (org-clock-history-push (cdr task
)
1139 (find-file (car task
)))))
1140 stored-clock-history
)))
1142 (when (and resume-clock org-clock-persist
1143 (file-exists-p (car resume-clock
))
1144 (or (not org-clock-persist-query-resume
)
1148 (with-current-buffer (find-file (car resume-clock
))
1150 (goto-char (cdr resume-clock
))
1151 (org-back-to-heading t
)
1152 (and (looking-at org-complex-heading-regexp
)
1155 (when (file-exists-p (car resume-clock
))
1156 (with-current-buffer (find-file (car resume-clock
))
1157 (goto-char (cdr resume-clock
))
1159 (if (org-invisible-p)
1160 (org-show-context)))))))))
1163 (defun org-clock-persistence-insinuate ()
1164 "Set up hooks for clock persistence"
1165 (add-hook 'org-mode-hook
'org-clock-load
)
1166 (add-hook 'kill-emacs-hook
'org-clock-save
))
1168 (provide 'org-clock
)
1170 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1172 ;;; org-clock.el ends here