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