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