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