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