Initial documentation of the new clock features.
[org-mode.git] / lisp / org-clock.el
blob6eaa2045df3bcb6a53e171a819b6c2ac1c2ac9da
1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.10c
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains the time clocking code for Org-mode
30 (require 'org)
31 (eval-when-compile
32 (require 'cl)
33 (require 'calendar))
35 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
37 (defgroup org-clock nil
38 "Options concerning clocking working time in Org-mode."
39 :tag "Org Clock"
40 :group 'org-progress)
42 (defcustom org-clock-into-drawer 2
43 "Should clocking info be wrapped into a drawer?
44 When t, clocking info will always be inserted into a :CLOCK: drawer.
45 If necessary, the drawer will be created.
46 When nil, the drawer will not be created, but used when present.
47 When an integer and the number of clocking entries in an item
48 reaches or exceeds this number, a drawer will be created."
49 :group 'org-todo
50 :group 'org-clock
51 :type '(choice
52 (const :tag "Always" t)
53 (const :tag "Only when drawer exists" nil)
54 (integer :tag "When at least N clock entries")))
56 (defcustom org-clock-out-when-done t
57 "When non-nil, the clock will be stopped when the relevant entry is marked DONE.
58 A nil value means, clock will keep running until stopped explicitly with
59 `C-c C-x C-o', or until the clock is started in a different item."
60 :group 'org-clock
61 :type 'boolean)
63 (defcustom org-clock-out-remove-zero-time-clocks nil
64 "Non-nil means, remove the clock line when the resulting time is zero."
65 :group 'org-clock
66 :type 'boolean)
68 (defcustom org-clock-in-switch-to-state nil
69 "Set task to a special todo state while clocking it.
70 The value should be the state to which the entry should be
71 switched. If the value is a function, it must take one
72 parameter (the current TODO state of the item) and return the
73 state to switch it to."
74 :group 'org-clock
75 :group 'org-todo
76 :type '(choice
77 (const :tag "Don't force a state" nil)
78 (string :tag "State")
79 (symbol :tag "Function")))
81 (defcustom org-clock-history-length 5
82 "Number of clock tasks to remember in history."
83 :group 'org-clock
84 :type 'integer)
86 (defcustom org-clock-heading-function nil
87 "When non-nil, should be a function to create `org-clock-heading'.
88 This is the string shown in the mode line when a clock is running.
89 The function is called with point at the beginning of the headline."
90 :group 'org-clock
91 :type 'function)
93 (defcustom org-clock-string-limit 0
94 "Maximum length of clock strings in the modeline. 0 means no limit"
95 :group 'org-clock
96 :type 'integer)
98 (defcustom org-clock-in-resume nil
99 "If non-nil, when clocking into a task with a clock entry which
100 has not been closed, resume the clock from that point"
101 :group 'org-clock
102 :type 'boolean)
104 (defcustom org-clock-persist nil
105 "When non-nil, save the running clock when emacs is closed, and
106 resume it next time emacs is started."
107 :group 'org-clock
108 :type 'boolean)
110 (defcustom org-clock-persist-file "~/.emacs.d/org-clock-save.el"
111 "File to save clock data to"
112 :group 'org-clock
113 :type 'string)
115 (defcustom org-clock-persist-query-save nil
116 "When non-nil, ask before saving the current clock on exit"
117 :group 'org-clock
118 :type 'boolean)
120 (defcustom org-clock-persist-query-resume t
121 "When non-nil, ask before resuming any stored clock during
122 load."
123 :group 'org-clock
124 :type 'boolean)
126 ;;; The clock for measuring work time.
128 (defvar org-mode-line-string "")
129 (put 'org-mode-line-string 'risky-local-variable t)
131 (defvar org-mode-line-timer nil)
132 (defvar org-clock-heading "")
133 (defvar org-clock-heading-for-remember "")
134 (defvar org-clock-start-time "")
136 (defvar org-clock-history nil
137 "List of marker pointing to recent clocked tasks.")
139 (defvar org-clock-default-task (make-marker)
140 "Marker pointing to the default task that should clock time.
141 The clock can be made to switch to this task after clocking out
142 of a different task.")
144 (defvar org-clock-interrupted-task (make-marker)
145 "Marker pointing to the task that has been interrupted by the current clock.")
147 (defvar org-clock-mode-map (make-sparse-keymap))
148 (define-key org-clock-mode-map [mode-line mouse-2] 'org-clock-goto)
150 (defun org-clock-history-push (&optional pos buffer)
151 "Push a marker to the clock history."
152 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
153 (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
154 (while (setq n (member m org-clock-history))
155 (move-marker (car n) nil))
156 (setq org-clock-history
157 (delq nil
158 (mapcar (lambda (x) (if (marker-buffer x) x nil))
159 org-clock-history)))
160 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
161 (setq org-clock-history
162 (nreverse
163 (nthcdr (- l org-clock-history-length -1)
164 (nreverse org-clock-history)))))
165 (push m org-clock-history)))
167 (defun org-clock-save-markers-for-cut-and-paste (beg end)
168 "Save relative positions of markers in region."
169 (org-check-and-save-marker org-clock-marker beg end)
170 (org-check-and-save-marker org-clock-default-task beg end)
171 (org-check-and-save-marker org-clock-interrupted-task beg end)
172 (mapc (lambda (m) (org-check-and-save-marker m beg end))
173 org-clock-history))
175 (defun org-clock-select-task (&optional prompt)
176 "Select a task that recently was associated with clocking."
177 (interactive)
178 (let (sel-list rpl file task (i 0) s)
179 (save-window-excursion
180 (org-switch-to-buffer-other-window
181 (get-buffer-create "*Clock Task Select*"))
182 (erase-buffer)
183 (when (marker-buffer org-clock-default-task)
184 (insert (org-add-props "Default Task\n" nil 'face 'bold))
185 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
186 (push s sel-list))
187 (when (marker-buffer org-clock-interrupted-task)
188 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
189 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
190 (push s sel-list))
191 (when (marker-buffer org-clock-marker)
192 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
193 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
194 (push s sel-list))
195 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
196 (mapc
197 (lambda (m)
198 (when (marker-buffer m)
199 (setq i (1+ i)
200 s (org-clock-insert-selection-line
201 (if (< i 10)
202 (+ i ?0)
203 (+ i (- ?A 10))) m))
204 (push s sel-list)))
205 org-clock-history)
206 (if (fboundp 'fit-window-to-buffer)
207 (fit-window-to-buffer)
208 (shrink-window-if-larger-than-buffer))
209 (message (or prompt "Select task for clocking:"))
210 (setq rpl (read-char-exclusive))
211 (cond
212 ((eq rpl ?q) nil)
213 ((eq rpl ?x) nil)
214 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
215 (t (error "Invalid task choice %c" rpl))))))
217 (defun org-clock-insert-selection-line (i marker)
218 (when (marker-buffer marker)
219 (let (file cat task)
220 (with-current-buffer (org-base-buffer (marker-buffer marker))
221 (save-excursion
222 (save-restriction
223 (widen)
224 (goto-char marker)
225 (setq file (buffer-file-name (marker-buffer marker))
226 cat (or (org-get-category)
227 (progn (org-refresh-category-properties)
228 (org-get-category)))
229 task (org-get-heading 'notags)))))
230 (when (and cat task)
231 (insert (format "[%c] %-15s %s\n" i cat task))
232 (cons i marker)))))
234 (defun org-update-mode-line ()
235 (let* ((delta (- (time-to-seconds (current-time))
236 (time-to-seconds org-clock-start-time)))
237 (h (floor delta 3600))
238 (m (floor (- delta (* 3600 h)) 60)))
239 (setq org-mode-line-string
240 (org-propertize
241 (let ((clock-string (format (concat "-[" org-time-clocksum-format " (%s)]")
242 h m org-clock-heading))
243 (help-text "Org-mode clock is running. Mouse-2 to go there."))
244 (if (and (> org-clock-string-limit 0)
245 (> (length clock-string) org-clock-string-limit))
246 (org-propertize (substring clock-string 0 org-clock-string-limit)
247 'help-echo (concat help-text ": " org-clock-heading))
248 (org-propertize clock-string 'help-echo help-text)))
249 'local-map org-clock-mode-map
250 'mouse-face '(face mode-line-highlight)))
251 (force-mode-line-update)))
253 (defvar org-clock-mode-line-entry nil
254 "Information for the modeline about the running clock.")
256 (defun org-clock-in (&optional select)
257 "Start the clock on the current item.
258 If necessary, clock-out of the currently active clock.
259 With prefix arg SELECT, offer a list of recently clocked tasks to
260 clock into. When SELECT is `C-u C-u', clock into the current task and mark
261 is as the default task, a special task that will always be offered in
262 the clocking selection, associated with the letter `d'."
263 (interactive "P")
264 (let ((interrupting (marker-buffer org-clock-marker))
265 ts selected-task target-pos)
266 (when (equal select '(4))
267 (setq selected-task (org-clock-select-task "Clock-in on task: "))
268 (if selected-task
269 (setq selected-task (copy-marker selected-task))
270 (error "Abort")))
271 (when interrupting
272 ;; We are interrupting the clocking of a differnt task.
273 ;; Save a marker to this task, so that we can go back.
274 (move-marker org-clock-interrupted-task
275 (marker-position org-clock-marker)
276 (marker-buffer org-clock-marker))
277 (org-clock-out t))
279 (when (equal select '(16))
280 ;; Mark as default clocking task
281 (save-excursion
282 (org-back-to-heading t)
283 (move-marker org-clock-default-task (point))))
285 (setq target-pos (point)) ;; we want to clock in at this location
286 (save-excursion
287 (when (and selected-task (marker-buffer selected-task))
288 ;; There is a selected task, move to the correct buffer
289 ;; and set the new target position.
290 (set-buffer (org-base-buffer (marker-buffer selected-task)))
291 (setq target-pos (marker-position selected-task))
292 (move-marker selected-task nil))
293 (save-excursion
294 (save-restriction
295 (widen)
296 (goto-char target-pos)
297 (org-back-to-heading t)
298 (or interrupting (move-marker org-clock-interrupted-task nil))
299 (org-clock-history-push)
300 (cond ((functionp org-clock-in-switch-to-state)
301 (looking-at org-complex-heading-regexp)
302 (let ((newstate (funcall org-clock-in-switch-to-state (match-string 2))))
303 (if newstate (org-todo newstate))))
304 ((and org-clock-in-switch-to-state
305 (not (looking-at (concat outline-regexp "[ \t]*"
306 org-clock-in-switch-to-state
307 "\\>"))))
308 (org-todo org-clock-in-switch-to-state)))
309 (setq org-clock-heading-for-remember
310 (and (looking-at org-complex-heading-regexp)
311 (match-end 4)
312 (org-trim (buffer-substring (match-end 1) (match-end 4)))))
313 (setq org-clock-heading
314 (cond ((and org-clock-heading-function
315 (functionp org-clock-heading-function))
316 (funcall org-clock-heading-function))
317 ((looking-at org-complex-heading-regexp)
318 (match-string 4))
319 (t "???")))
320 (setq org-clock-heading (org-propertize org-clock-heading 'face nil))
321 (org-clock-find-position)
322 (if (and org-clock-in-resume
323 (looking-at (concat "^[ \\t]* " org-clock-string
324 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
325 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\]$")))
326 (progn (message "Matched %s" (match-string 1))
327 (setq ts (concat "[" (match-string 1) "]"))
328 (goto-char (match-end 1))
329 (setq org-clock-start-time
330 (apply 'encode-time (org-parse-time-string (match-string 1)))))
331 (progn
332 (insert "\n") (backward-char 1)
333 (org-indent-line-function)
334 (insert org-clock-string " ")
335 (setq org-clock-start-time (current-time))
336 (setq ts (org-insert-time-stamp org-clock-start-time 'with-hm 'inactive))))
337 (move-marker org-clock-marker (point) (buffer-base-buffer))
338 (or global-mode-string (setq global-mode-string '("")))
339 (or (memq 'org-mode-line-string global-mode-string)
340 (setq global-mode-string
341 (append global-mode-string '(org-mode-line-string))))
342 (org-update-mode-line)
343 (setq org-mode-line-timer
344 (run-with-timer 60 60 'org-update-mode-line))
345 (message "Clock started at %s" ts))))))
347 (defun org-clock-find-position ()
348 "Find the location where the next clock line should be inserted."
349 (org-back-to-heading t)
350 (catch 'exit
351 (let ((beg (save-excursion
352 (beginning-of-line 2)
353 (or (bolp) (newline))
354 (point)))
355 (end (progn (outline-next-heading) (point)))
356 (re (concat "^[ \t]*" org-clock-string))
357 (cnt 0)
358 first last)
359 (goto-char beg)
360 (when (eobp) (newline) (setq end (max (point) end)))
361 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
362 ;; we seem to have a CLOCK drawer, so go there.
363 (beginning-of-line 2)
364 (throw 'exit t))
365 ;; Lets count the CLOCK lines
366 (goto-char beg)
367 (while (re-search-forward re end t)
368 (setq first (or first (match-beginning 0))
369 last (match-beginning 0)
370 cnt (1+ cnt)))
371 (when (and (integerp org-clock-into-drawer)
372 (>= (1+ cnt) org-clock-into-drawer))
373 ;; Wrap current entries into a new drawer
374 (goto-char last)
375 (beginning-of-line 2)
376 (if (org-at-item-p) (org-end-of-item))
377 (insert ":END:\n")
378 (beginning-of-line 0)
379 (org-indent-line-function)
380 (goto-char first)
381 (insert ":CLOCK:\n")
382 (beginning-of-line 0)
383 (org-indent-line-function)
384 (org-flag-drawer t)
385 (beginning-of-line 2)
386 (throw 'exit nil))
388 (goto-char beg)
389 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
390 (not (equal (match-string 1) org-clock-string)))
391 ;; Planning info, skip to after it
392 (beginning-of-line 2)
393 (or (bolp) (newline)))
394 (when (eq t org-clock-into-drawer)
395 (insert ":CLOCK:\n:END:\n")
396 (beginning-of-line 0)
397 (org-indent-line-function)
398 (beginning-of-line 0)
399 (org-flag-drawer t)
400 (org-indent-line-function)
401 (beginning-of-line 2)))))
403 (defun org-clock-out (&optional fail-quietly)
404 "Stop the currently running clock.
405 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
406 (interactive)
407 (catch 'exit
408 (if (not (marker-buffer org-clock-marker))
409 (if fail-quietly (throw 'exit t) (error "No active clock")))
410 (let (ts te s h m remove)
411 (save-excursion
412 (set-buffer (marker-buffer org-clock-marker))
413 (save-restriction
414 (widen)
415 (goto-char org-clock-marker)
416 (beginning-of-line 1)
417 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
418 (equal (match-string 1) org-clock-string))
419 (setq ts (match-string 2))
420 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
421 (goto-char (match-end 0))
422 (delete-region (point) (point-at-eol))
423 (insert "--")
424 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
425 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
426 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
427 h (floor (/ s 3600))
428 s (- s (* 3600 h))
429 m (floor (/ s 60))
430 s (- s (* 60 s)))
431 (insert " => " (format "%2d:%02d" h m))
432 (when (setq remove (and org-clock-out-remove-zero-time-clocks
433 (= (+ h m) 0)))
434 (beginning-of-line 1)
435 (delete-region (point) (point-at-eol))
436 (and (looking-at "\n") (> (point-max) (1+ (point)))
437 (delete-char 1)))
438 (move-marker org-clock-marker nil)
439 (when org-log-note-clock-out
440 (org-add-log-setup 'clock-out nil nil nil
441 (concat "# Task: " (org-get-heading t) "\n\n")))
442 (when org-mode-line-timer
443 (cancel-timer org-mode-line-timer)
444 (setq org-mode-line-timer nil))
445 (setq global-mode-string
446 (delq 'org-mode-line-string global-mode-string))
447 (force-mode-line-update)
448 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
449 (if remove " => LINE REMOVED" "")))))))
451 (defun org-clock-cancel ()
452 "Cancel the running clock be removing the start timestamp."
453 (interactive)
454 (if (not (marker-buffer org-clock-marker))
455 (error "No active clock"))
456 (save-excursion
457 (set-buffer (marker-buffer org-clock-marker))
458 (goto-char org-clock-marker)
459 (delete-region (1- (point-at-bol)) (point-at-eol)))
460 (setq global-mode-string
461 (delq 'org-mode-line-string global-mode-string))
462 (force-mode-line-update)
463 (message "Clock canceled"))
465 (defun org-clock-goto (&optional select)
466 "Go to the currently clocked-in entry.
467 With prefix arg SELECT, offer recently clocked tasks."
468 (interactive "P")
469 (let ((m (if select
470 (org-clock-select-task "Select task to go to: ")
471 org-clock-marker)))
472 (if (not (marker-buffer m))
473 (if select
474 (error "No task selected")
475 (error "No active clock")))
476 (switch-to-buffer (marker-buffer m))
477 (if (or (< m (point-min)) (> m (point-max))) (widen))
478 (goto-char m)
479 (org-show-entry)
480 (org-back-to-heading)
481 (org-cycle-hide-drawers 'children)
482 (recenter)))
484 (defvar org-clock-file-total-minutes nil
485 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
486 (make-variable-buffer-local 'org-clock-file-total-minutes)
488 (defun org-clock-sum (&optional tstart tend)
489 "Sum the times for each subtree.
490 Puts the resulting times in minutes as a text property on each headline."
491 (interactive)
492 (let* ((bmp (buffer-modified-p))
493 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
494 org-clock-string
495 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
496 (lmax 30)
497 (ltimes (make-vector lmax 0))
498 (t1 0)
499 (level 0)
500 ts te dt
501 time)
502 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
503 (save-excursion
504 (goto-char (point-max))
505 (while (re-search-backward re nil t)
506 (cond
507 ((match-end 2)
508 ;; Two time stamps
509 (setq ts (match-string 2)
510 te (match-string 3)
511 ts (time-to-seconds
512 (apply 'encode-time (org-parse-time-string ts)))
513 te (time-to-seconds
514 (apply 'encode-time (org-parse-time-string te)))
515 ts (if tstart (max ts tstart) ts)
516 te (if tend (min te tend) te)
517 dt (- te ts)
518 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
519 ((match-end 4)
520 ;; A naket time
521 (setq t1 (+ t1 (string-to-number (match-string 5))
522 (* 60 (string-to-number (match-string 4))))))
523 (t ;; A headline
524 (setq level (- (match-end 1) (match-beginning 1)))
525 (when (or (> t1 0) (> (aref ltimes level) 0))
526 (loop for l from 0 to level do
527 (aset ltimes l (+ (aref ltimes l) t1)))
528 (setq t1 0 time (aref ltimes level))
529 (loop for l from level to (1- lmax) do
530 (aset ltimes l 0))
531 (goto-char (match-beginning 0))
532 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
533 (setq org-clock-file-total-minutes (aref ltimes 0)))
534 (set-buffer-modified-p bmp)))
536 (defun org-clock-display (&optional total-only)
537 "Show subtree times in the entire buffer.
538 If TOTAL-ONLY is non-nil, only show the total time for the entire file
539 in the echo area."
540 (interactive)
541 (org-remove-clock-overlays)
542 (let (time h m p)
543 (org-clock-sum)
544 (unless total-only
545 (save-excursion
546 (goto-char (point-min))
547 (while (or (and (equal (setq p (point)) (point-min))
548 (get-text-property p :org-clock-minutes))
549 (setq p (next-single-property-change
550 (point) :org-clock-minutes)))
551 (goto-char p)
552 (when (setq time (get-text-property p :org-clock-minutes))
553 (org-put-clock-overlay time (funcall outline-level))))
554 (setq h (/ org-clock-file-total-minutes 60)
555 m (- org-clock-file-total-minutes (* 60 h)))
556 ;; Arrange to remove the overlays upon next change.
557 (when org-remove-highlights-with-change
558 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
559 nil 'local))))
560 (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
562 (defvar org-clock-overlays nil)
563 (make-variable-buffer-local 'org-clock-overlays)
565 (defun org-put-clock-overlay (time &optional level)
566 "Put an overlays on the current line, displaying TIME.
567 If LEVEL is given, prefix time with a corresponding number of stars.
568 This creates a new overlay and stores it in `org-clock-overlays', so that it
569 will be easy to remove."
570 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
571 (l (if level (org-get-valid-level level 0) 0))
572 (fmt (concat "%s " org-time-clocksum-format "%s"))
573 (off 0)
574 ov tx)
575 (org-move-to-column c)
576 (unless (eolp) (skip-chars-backward "^ \t"))
577 (skip-chars-backward " \t")
578 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
579 tx (concat (buffer-substring (1- (point)) (point))
580 (make-string (+ off (max 0 (- c (current-column)))) ?.)
581 (org-add-props (format fmt
582 (make-string l ?*) h m
583 (make-string (- 16 l) ?\ ))
584 '(face secondary-selection))
585 ""))
586 (if (not (featurep 'xemacs))
587 (org-overlay-put ov 'display tx)
588 (org-overlay-put ov 'invisible t)
589 (org-overlay-put ov 'end-glyph (make-glyph tx)))
590 (push ov org-clock-overlays)))
592 (defun org-remove-clock-overlays (&optional beg end noremove)
593 "Remove the occur highlights from the buffer.
594 BEG and END are ignored. If NOREMOVE is nil, remove this function
595 from the `before-change-functions' in the current buffer."
596 (interactive)
597 (unless org-inhibit-highlight-removal
598 (mapc 'org-delete-overlay org-clock-overlays)
599 (setq org-clock-overlays nil)
600 (unless noremove
601 (remove-hook 'before-change-functions
602 'org-remove-clock-overlays 'local))))
604 (defvar state) ;; dynamically scoped into this function
605 (defun org-clock-out-if-current ()
606 "Clock out if the current entry contains the running clock.
607 This is used to stop the clock after a TODO entry is marked DONE,
608 and is only done if the variable `org-clock-out-when-done' is not nil."
609 (when (and org-clock-out-when-done
610 (member state org-done-keywords)
611 (equal (marker-buffer org-clock-marker) (current-buffer))
612 (< (point) org-clock-marker)
613 (> (save-excursion (outline-next-heading) (point))
614 org-clock-marker))
615 ;; Clock out, but don't accept a logging message for this.
616 (let ((org-log-note-clock-out nil))
617 (org-clock-out))))
619 (add-hook 'org-after-todo-state-change-hook
620 'org-clock-out-if-current)
622 ;;;###autoload
623 (defun org-get-clocktable (&rest props)
624 "Get a formatted clocktable with parameters according to PROPS.
625 The table is created in a temporary buffer, fully formatted and
626 fontified, and then returned."
627 ;; Set the defaults
628 (setq props (plist-put props :name "clocktable"))
629 (unless (plist-member props :maxlevel)
630 (setq props (plist-put props :maxlevel 2)))
631 (unless (plist-member props :scope)
632 (setq props (plist-put props :scope 'agenda)))
633 (with-temp-buffer
634 (org-mode)
635 (org-create-dblock props)
636 (org-update-dblock)
637 (font-lock-fontify-buffer)
638 (forward-line 2)
639 (buffer-substring (point) (progn
640 (re-search-forward "^#\\+END" nil t)
641 (point-at-bol)))))
643 (defun org-clock-report (&optional arg)
644 "Create a table containing a report about clocked time.
645 If the cursor is inside an existing clocktable block, then the table
646 will be updated. If not, a new clocktable will be inserted.
647 When called with a prefix argument, move to the first clock table in the
648 buffer and update it."
649 (interactive "P")
650 (org-remove-clock-overlays)
651 (when arg
652 (org-find-dblock "clocktable")
653 (org-show-entry))
654 (if (org-in-clocktable-p)
655 (goto-char (org-in-clocktable-p))
656 (org-create-dblock (list :name "clocktable"
657 :maxlevel 2 :scope 'file)))
658 (org-update-dblock))
660 (defun org-in-clocktable-p ()
661 "Check if the cursor is in a clocktable."
662 (let ((pos (point)) start)
663 (save-excursion
664 (end-of-line 1)
665 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
666 (setq start (match-beginning 0))
667 (re-search-forward "^#\\+END:.*" nil t)
668 (>= (match-end 0) pos)
669 start))))
671 (defun org-clock-special-range (key &optional time as-strings)
672 "Return two times bordering a special time range.
673 Key is a symbol specifying the range and can be one of `today', `yesterday',
674 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
675 A week starts Monday 0:00 and ends Sunday 24:00.
676 The range is determined relative to TIME. TIME defaults to the current time.
677 The return value is a cons cell with two internal times like the ones
678 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
679 the returned times will be formatted strings."
680 (if (integerp key) (setq key (intern (number-to-string key))))
681 (let* ((tm (decode-time (or time (current-time))))
682 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
683 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
684 (dow (nth 6 tm))
685 (skey (symbol-name key))
686 (shift 0)
687 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
688 (cond
689 ((string-match "^[0-9]+$" skey)
690 (setq y (string-to-number skey) m 1 d 1 key 'year))
691 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
692 (setq y (string-to-number (match-string 1 skey))
693 month (string-to-number (match-string 2 skey))
694 d 1 key 'month))
695 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
696 (require 'cal-iso)
697 (setq y (string-to-number (match-string 1 skey))
698 w (string-to-number (match-string 2 skey)))
699 (setq date (calendar-gregorian-from-absolute
700 (calendar-absolute-from-iso (list w 1 y))))
701 (setq d (nth 1 date) month (car date) y (nth 2 date)
702 key 'week))
703 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
704 (setq y (string-to-number (match-string 1 skey))
705 month (string-to-number (match-string 2 skey))
706 d (string-to-number (match-string 3 skey))
707 key 'day))
708 ((string-match "\\([-+][0-9]+\\)$" skey)
709 (setq shift (string-to-number (match-string 1 skey))
710 key (intern (substring skey 0 (match-beginning 1))))))
711 (when (= shift 0)
712 (cond ((eq key 'yesterday) (setq key 'today shift -1))
713 ((eq key 'lastweek) (setq key 'week shift -1))
714 ((eq key 'lastmonth) (setq key 'month shift -1))
715 ((eq key 'lastyear) (setq key 'year shift -1))))
716 (cond
717 ((memq key '(day today))
718 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
719 ((memq key '(week thisweek))
720 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
721 m 0 h 0 d (- d diff) d1 (+ 7 d)))
722 ((memq key '(month thismonth))
723 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
724 ((memq key '(year thisyear))
725 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
726 (t (error "No such time block %s" key)))
727 (setq ts (encode-time s m h d month y)
728 te (encode-time (or s1 s) (or m1 m) (or h1 h)
729 (or d1 d) (or month1 month) (or y1 y)))
730 (setq fm (cdr org-time-stamp-formats))
731 (cond
732 ((memq key '(day today))
733 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
734 ((memq key '(week thisweek))
735 (setq txt (format-time-string "week %G-W%V" ts)))
736 ((memq key '(month thismonth))
737 (setq txt (format-time-string "%B %Y" ts)))
738 ((memq key '(year thisyear))
739 (setq txt (format-time-string "the year %Y" ts))))
740 (if as-strings
741 (list (format-time-string fm ts) (format-time-string fm te) txt)
742 (list ts te txt))))
744 (defun org-clocktable-shift (dir n)
745 "Try to shift the :block date of the clocktable at point.
746 Point must be in the #+BEGIN: line of a clocktable, or this function
747 will throw an error.
748 DIR is a direction, a symbol `left', `right', `up', or `down'.
749 Both `left' and `down' shift the block toward the past, `up' and `right'
750 push it toward the future.
751 N is the number of shift steps to take. The size of the step depends on
752 the currently selected interval size."
753 (setq n (prefix-numeric-value n))
754 (and (memq dir '(left down)) (setq n (- n)))
755 (save-excursion
756 (goto-char (point-at-bol))
757 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
758 (error "Line needs a :block definition before this command works")
759 (let* ((b (match-beginning 1)) (e (match-end 1))
760 (s (match-string 1))
761 block shift ins y mw d date wp m)
762 (cond
763 ((equal s "yesterday") (setq s "today-1"))
764 ((equal s "lastweek") (setq s "thisweek-1"))
765 ((equal s "lastmonth") (setq s "thismonth-1"))
766 ((equal s "lastyear") (setq s "thisyear-1")))
767 (cond
768 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
769 (setq block (match-string 1 s)
770 shift (if (match-end 2)
771 (string-to-number (match-string 2 s))
773 (setq shift (+ shift n))
774 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
775 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
776 ;; 1 1 2 3 3 4 4 5 6 6 5 2
777 (setq y (string-to-number (match-string 1 s))
778 wp (and (match-end 3) (match-string 3 s))
779 mw (and (match-end 4) (string-to-number (match-string 4 s)))
780 d (and (match-end 6) (string-to-number (match-string 6 s))))
781 (cond
782 (d (setq ins (format-time-string
783 "%Y-%m-%d"
784 (encode-time 0 0 0 (+ d n) m y))))
785 ((and wp mw (> (length wp) 0))
786 (require 'cal-iso)
787 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
788 (setq ins (format-time-string
789 "%G-W%V"
790 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
792 (setq ins (format-time-string
793 "%Y-%m"
794 (encode-time 0 0 0 1 (+ mw n) y))))
796 (setq ins (number-to-string (+ y n))))))
797 (t (error "Cannot shift clocktable block")))
798 (when ins
799 (goto-char b)
800 (insert ins)
801 (delete-region (point) (+ (point) (- e b)))
802 (beginning-of-line 1)
803 (org-update-dblock)
804 t)))))
806 (defun org-dblock-write:clocktable (params)
807 "Write the standard clocktable."
808 (catch 'exit
809 (let* ((hlchars '((1 . "*") (2 . "/")))
810 (ins (make-marker))
811 (total-time nil)
812 (scope (plist-get params :scope))
813 (tostring (plist-get params :tostring))
814 (multifile (plist-get params :multifile))
815 (header (plist-get params :header))
816 (maxlevel (or (plist-get params :maxlevel) 3))
817 (step (plist-get params :step))
818 (emph (plist-get params :emphasize))
819 (ts (plist-get params :tstart))
820 (te (plist-get params :tend))
821 (block (plist-get params :block))
822 (link (plist-get params :link))
823 ipos time p level hlc hdl
824 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list)
825 (setq org-clock-file-total-minutes nil)
826 (when step
827 (unless (or block (and ts te))
828 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
829 (org-clocktable-steps params)
830 (throw 'exit nil))
831 (when block
832 (setq cc (org-clock-special-range block nil t)
833 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
834 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
835 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
836 (when (and ts (listp ts))
837 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
838 (when (and te (listp te))
839 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
840 ;; Now the times are strings we can parse.
841 (if ts (setq ts (time-to-seconds
842 (apply 'encode-time (org-parse-time-string ts)))))
843 (if te (setq te (time-to-seconds
844 (apply 'encode-time (org-parse-time-string te)))))
845 (move-marker ins (point))
846 (setq ipos (point))
848 ;; Get the right scope
849 (setq pos (point))
850 (cond
851 ((and scope (listp scope) (symbolp (car scope)))
852 (setq scope (eval scope)))
853 ((eq scope 'agenda)
854 (setq scope (org-agenda-files t)))
855 ((eq scope 'agenda-with-archives)
856 (setq scope (org-agenda-files t))
857 (setq scope (org-add-archive-files scope)))
858 ((eq scope 'file-with-archives)
859 (setq scope (org-add-archive-files (list (buffer-file-name)))
860 rm-file-column t)))
861 (setq scope-is-list (and scope (listp scope)))
862 (save-restriction
863 (cond
864 ((not scope))
865 ((eq scope 'file) (widen))
866 ((eq scope 'subtree) (org-narrow-to-subtree))
867 ((eq scope 'tree)
868 (while (org-up-heading-safe))
869 (org-narrow-to-subtree))
870 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
871 (symbol-name scope)))
872 (setq level (string-to-number (match-string 1 (symbol-name scope))))
873 (catch 'exit
874 (while (org-up-heading-safe)
875 (looking-at outline-regexp)
876 (if (<= (org-reduced-level (funcall outline-level)) level)
877 (throw 'exit nil))))
878 (org-narrow-to-subtree))
879 (scope-is-list
880 (let* ((files scope)
881 (scope 'agenda)
882 (p1 (copy-sequence params))
883 file)
884 (setq p1 (plist-put p1 :tostring t))
885 (setq p1 (plist-put p1 :multifile t))
886 (setq p1 (plist-put p1 :scope 'file))
887 (org-prepare-agenda-buffers files)
888 (while (setq file (pop files))
889 (with-current-buffer (find-buffer-visiting file)
890 (setq tbl1 (org-dblock-write:clocktable p1))
891 (when tbl1
892 (push (org-clocktable-add-file
893 file
894 (concat "| |*File time*|*"
895 (org-minutes-to-hh:mm-string
896 org-clock-file-total-minutes)
897 "*|\n"
898 tbl1)) tbl)
899 (setq total-time (+ (or total-time 0)
900 org-clock-file-total-minutes))))))))
901 (goto-char pos)
903 (unless scope-is-list
904 (org-clock-sum ts te)
905 (goto-char (point-min))
906 (while (setq p (next-single-property-change (point) :org-clock-minutes))
907 (goto-char p)
908 (when (setq time (get-text-property p :org-clock-minutes))
909 (save-excursion
910 (beginning-of-line 1)
911 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
912 (setq level (org-reduced-level
913 (- (match-end 1) (match-beginning 1))))
914 (<= level maxlevel))
915 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
916 hdl (if (not link)
917 (match-string 2)
918 (org-make-link-string
919 (format "file:%s::%s"
920 (buffer-file-name)
921 (save-match-data
922 (org-make-org-heading-search-string
923 (match-string 2))))
924 (match-string 2))))
925 (if (and (not multifile) (= level 1)) (push "|-" tbl))
926 (push (concat
927 "| " (int-to-string level) "|" hlc hdl hlc " |"
928 (make-string (1- level) ?|)
929 hlc (org-minutes-to-hh:mm-string time) hlc
930 " |") tbl))))))
931 (setq tbl (nreverse tbl))
932 (if tostring
933 (if tbl (mapconcat 'identity tbl "\n") nil)
934 (goto-char ins)
935 (insert-before-markers
936 (or header
937 (concat
938 "Clock summary at ["
939 (substring
940 (format-time-string (cdr org-time-stamp-formats))
941 1 -1)
943 (if block (concat ", for " range-text ".") "")
944 "\n\n"))
945 (if scope-is-list "|File" "")
946 "|L|Headline|Time|\n")
947 (setq total-time (or total-time org-clock-file-total-minutes))
948 (insert-before-markers
949 "|-\n|"
950 (if scope-is-list "|" "")
952 "*Total time*| *"
953 (org-minutes-to-hh:mm-string (or total-time 0))
954 "*|\n|-\n")
955 (setq tbl (delq nil tbl))
956 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
957 (equal (substring (car tbl) 0 2) "|-"))
958 (pop tbl))
959 (insert-before-markers (mapconcat
960 'identity (delq nil tbl)
961 (if scope-is-list "\n|-\n" "\n")))
962 (backward-delete-char 1)
963 (goto-char ipos)
964 (skip-chars-forward "^|")
965 (org-table-align)
966 (when rm-file-column
967 (forward-char 1)
968 (org-table-delete-column)))))))
970 (defun org-clocktable-steps (params)
971 (let* ((p1 (copy-sequence params))
972 (ts (plist-get p1 :tstart))
973 (te (plist-get p1 :tend))
974 (step0 (plist-get p1 :step))
975 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
976 (block (plist-get p1 :block))
977 cc range-text)
978 (when block
979 (setq cc (org-clock-special-range block nil t)
980 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
981 (if ts (setq ts (time-to-seconds
982 (apply 'encode-time (org-parse-time-string ts)))))
983 (if te (setq te (time-to-seconds
984 (apply 'encode-time (org-parse-time-string te)))))
985 (setq p1 (plist-put p1 :header ""))
986 (setq p1 (plist-put p1 :step nil))
987 (setq p1 (plist-put p1 :block nil))
988 (while (< ts te)
989 (or (bolp) (insert "\n"))
990 (setq p1 (plist-put p1 :tstart (format-time-string
991 (car org-time-stamp-formats)
992 (seconds-to-time ts))))
993 (setq p1 (plist-put p1 :tend (format-time-string
994 (car org-time-stamp-formats)
995 (seconds-to-time (setq ts (+ ts step))))))
996 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
997 (plist-get p1 :tstart) "\n")
998 (org-dblock-write:clocktable p1)
999 (re-search-forward "#\\+END:")
1000 (end-of-line 0))))
1002 (defun org-clocktable-add-file (file table)
1003 (if table
1004 (let ((lines (org-split-string table "\n"))
1005 (ff (file-name-nondirectory file)))
1006 (mapconcat 'identity
1007 (mapcar (lambda (x)
1008 (if (string-match org-table-dataline-regexp x)
1009 (concat "|" ff x)
1011 lines)
1012 "\n"))))
1014 (defun org-clock-save ()
1015 "Persist various clock-related data to disk"
1016 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
1017 (progn (delete-region (point-min) (point-max))
1018 ;;Store clock
1019 (insert (format ";; org-persist.el - %s at %s\n" system-name (time-stamp-string)))
1020 (if (and org-clock-persist (marker-buffer org-clock-marker)
1021 (or (not org-clock-persist-query-save)
1022 (y-or-n-p (concat "Save current clock ("
1023 (substring-no-properties org-clock-heading)
1024 ")"))))
1025 (insert "(setq resume-clock '(\""
1026 (buffer-file-name (marker-buffer org-clock-marker))
1027 "\" . " (int-to-string (marker-position org-clock-marker))
1028 "))\n"))
1029 ;;Store clocked task history. Tasks are stored reversed to make
1030 ;;reading simpler
1031 (if org-clock-history
1032 (insert "(setq stored-clock-history '("
1033 (mapconcat
1034 (lambda (m)
1035 (when (marker-buffer m)
1036 (concat "(\"" (buffer-file-name (marker-buffer m))
1037 "\" . " (int-to-string (marker-position m))
1038 ")")))
1039 (reverse org-clock-history) " ") "))\n"))
1040 (save-buffer)
1041 (kill-buffer (current-buffer)))))
1043 (defvar org-clock-loaded nil)
1045 (require 'timestamp)
1047 (defun org-clock-load ()
1048 "Load various clock-related data from disk, optionally resuming
1049 a stored clock"
1050 (if (not org-clock-loaded)
1051 (let ((filename (expand-file-name org-clock-persist-file))
1052 (org-clock-in-resume t))
1053 (if (file-readable-p filename)
1054 (progn
1055 (message "%s" "Restoring clock data")
1056 (setq org-clock-loaded t)
1057 (load-file filename)
1058 ;; load history
1059 (if (boundp 'stored-clock-history)
1060 (save-window-excursion
1061 (mapc (lambda (task)
1062 (org-clock-history-push (cdr task)
1063 (find-file (car task))))
1064 stored-clock-history)))
1065 ;; resume clock
1066 (if (and (boundp 'resume-clock) org-clock-persist
1067 (or (not org-clock-persist-query-resume)
1068 (y-or-n-p "Resume clock ("
1069 (with-current-buffer (find-file (car resume-clock))
1070 (progn (goto-char (cdr resume-clock))
1071 (looking-at org-complex-heading-regexp)
1072 (match-string 4))) ")")))
1073 (with-current-buffer (find-file (car resume-clock))
1074 (progn (goto-char (cdr resume-clock))
1075 (org-clock-in)))))
1076 (message "Not restoring clock data; %s not found"
1077 org-clock-persist-file)))))
1079 ;;;###autoload
1080 (defun org-clock-persistence-insinuate ()
1081 "Set up hooks for clock persistence"
1082 (add-hook 'org-mode-hook 'org-clock-load)
1083 (add-hook 'kill-emacs-hook 'org-clock-save))
1085 (provide 'org-clock)
1087 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1089 ;;; org-clock.el ends here