Clock: Improve messages
[org-mode/org-tableheadings.git] / lisp / org-clock.el
blob4825c1a455e263d840af2c0be9ddef22dc86251d
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.27trans
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-out-switch-to-state nil
90 "Set task to a special todo state after clocking out.
91 The value should be the state to which the entry should be
92 switched. If the value is a function, it must take one
93 parameter (the current TODO state of the item) and return the
94 state to switch it to."
95 :group 'org-clock
96 :group 'org-todo
97 :type '(choice
98 (const :tag "Don't force a state" nil)
99 (string :tag "State")
100 (symbol :tag "Function")))
102 (defcustom org-clock-history-length 5
103 "Number of clock tasks to remember in history."
104 :group 'org-clock
105 :type 'integer)
107 (defcustom org-clock-goto-may-find-recent-task t
108 "Non-nil means, `org-clock-goto' can go to recent task if no active clock."
109 :group 'org-clock
110 :type 'boolean)
112 (defcustom org-clock-heading-function nil
113 "When non-nil, should be a function to create `org-clock-heading'.
114 This is the string shown in the mode line when a clock is running.
115 The function is called with point at the beginning of the headline."
116 :group 'org-clock
117 :type 'function)
119 (defcustom org-clock-string-limit 0
120 "Maximum length of clock strings in the modeline. 0 means no limit."
121 :group 'org-clock
122 :type 'integer)
124 (defcustom org-clock-in-resume nil
125 "If non-nil, resume clock when clocking into task with open clock.
126 When clocking into a task with a clock entry which has not been closed,
127 the clock can be resumed from that point."
128 :group 'org-clock
129 :type 'boolean)
131 (defcustom org-clock-persist nil
132 "When non-nil, save the running clock when emacs is closed.
133 The clock is resumed when emacs restarts.
134 When this is t, both the running clock, and the entire clock
135 history are saved. When this is the symbol `clock', only the
136 running clock is saved.
138 When Emacs restarts with saved clock information, the file containing the
139 running clock as well as all files mentioned in the clock history will
140 be visited.
141 All this depends on running `org-clock-persistence-insinuate' in .emacs"
142 :group 'org-clock
143 :type '(choice
144 (const :tag "Just the running clock" clock)
145 (const :tag "Clock and history" t)
146 (const :tag "No persistence" nil)))
148 (defcustom org-clock-persist-file (convert-standard-filename
149 "~/.emacs.d/org-clock-save.el")
150 "File to save clock data to."
151 :group 'org-clock
152 :type 'string)
154 (defcustom org-clock-persist-query-save nil
155 "When non-nil, ask before saving the current clock on exit."
156 :group 'org-clock
157 :type 'boolean)
159 (defcustom org-clock-persist-query-resume t
160 "When non-nil, ask before resuming any stored clock during load."
161 :group 'org-clock
162 :type 'boolean)
164 (defcustom org-clock-sound nil
165 "Sound that will used for notifications.
166 Possible values:
168 nil no sound played.
169 t standard Emacs beep
170 file name play this sound file. If not possible, fall back to beep"
171 :group 'org-clock
172 :type '(choice
173 (const :tag "No sound" nil)
174 (const :tag "Standard beep" t)
175 (file :tag "Play sound file")))
177 (defcustom org-clock-modeline-total 'auto
178 "Default setting for the time included for the modeline clock.
179 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
180 Allowed values are:
182 current Only the time in the current instance of the clock
183 today All time clocked inot this task today
184 repeat All time clocked into this task since last repeat
185 all All time ever recorded for this task
186 auto Automtically, either `all', or `repeat' for repeating tasks"
187 :group 'org-clock
188 :type '(choice
189 (const :tag "Current clock" current)
190 (const :tag "Today's task time" today)
191 (const :tag "Since last repeat" repeat)
192 (const :tag "All task time" all)
193 (const :tag "Automatically, `all' or since `repeat'" auto)))
195 ;;; The clock for measuring work time.
197 (defvar org-mode-line-string "")
198 (put 'org-mode-line-string 'risky-local-variable t)
200 (defvar org-clock-mode-line-timer nil)
201 (defvar org-clock-heading "")
202 (defvar org-clock-heading-for-remember "")
203 (defvar org-clock-start-time "")
205 (defvar org-clock-effort ""
206 "Effort estimate of the currently clocking task")
208 (defvar org-clock-total-time nil
209 "Holds total time, spent previously on currently clocked item.
210 This does not include the time in the currently running clock.")
212 (defvar org-clock-history nil
213 "List of marker pointing to recent clocked tasks.")
215 (defvar org-clock-default-task (make-marker)
216 "Marker pointing to the default task that should clock time.
217 The clock can be made to switch to this task after clocking out
218 of a different task.")
220 (defvar org-clock-interrupted-task (make-marker)
221 "Marker pointing to the task that has been interrupted by the current clock.")
223 (defvar org-clock-mode-line-map (make-sparse-keymap))
224 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
226 (defun org-clock-history-push (&optional pos buffer)
227 "Push a marker to the clock history."
228 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
229 (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
230 (while (setq n (member m org-clock-history))
231 (move-marker (car n) nil))
232 (setq org-clock-history
233 (delq nil
234 (mapcar (lambda (x) (if (marker-buffer x) x nil))
235 org-clock-history)))
236 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
237 (setq org-clock-history
238 (nreverse
239 (nthcdr (- l org-clock-history-length -1)
240 (nreverse org-clock-history)))))
241 (push m org-clock-history)))
243 (defun org-clock-save-markers-for-cut-and-paste (beg end)
244 "Save relative positions of markers in region."
245 (org-check-and-save-marker org-clock-marker beg end)
246 (org-check-and-save-marker org-clock-default-task beg end)
247 (org-check-and-save-marker org-clock-interrupted-task beg end)
248 (mapc (lambda (m) (org-check-and-save-marker m beg end))
249 org-clock-history))
251 (defun org-clock-select-task (&optional prompt)
252 "Select a task that recently was associated with clocking."
253 (interactive)
254 (let (sel-list rpl (i 0) s)
255 (save-window-excursion
256 (org-switch-to-buffer-other-window
257 (get-buffer-create "*Clock Task Select*"))
258 (erase-buffer)
259 (when (marker-buffer org-clock-default-task)
260 (insert (org-add-props "Default Task\n" nil 'face 'bold))
261 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
262 (push s sel-list))
263 (when (marker-buffer org-clock-interrupted-task)
264 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
265 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
266 (push s sel-list))
267 (when (marker-buffer org-clock-marker)
268 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
269 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
270 (push s sel-list))
271 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
272 (mapc
273 (lambda (m)
274 (when (marker-buffer m)
275 (setq i (1+ i)
276 s (org-clock-insert-selection-line
277 (if (< i 10)
278 (+ i ?0)
279 (+ i (- ?A 10))) m))
280 (push s sel-list)))
281 org-clock-history)
282 (org-fit-window-to-buffer)
283 (message (or prompt "Select task for clocking:"))
284 (setq rpl (read-char-exclusive))
285 (cond
286 ((eq rpl ?q) nil)
287 ((eq rpl ?x) nil)
288 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
289 (t (error "Invalid task choice %c" rpl))))))
291 (defun org-clock-insert-selection-line (i marker)
292 "Insert a line for the clock selection menu.
293 And return a cons cell with the selection character integer and the marker
294 pointing to it."
295 (when (marker-buffer marker)
296 (let (file cat task heading prefix)
297 (with-current-buffer (org-base-buffer (marker-buffer marker))
298 (save-excursion
299 (save-restriction
300 (widen)
301 (goto-char marker)
302 (setq file (buffer-file-name (marker-buffer marker))
303 cat (or (org-get-category)
304 (progn (org-refresh-category-properties)
305 (org-get-category)))
306 heading (org-get-heading 'notags)
307 prefix (save-excursion
308 (org-back-to-heading t)
309 (looking-at "\\*+ ")
310 (match-string 0))
311 task (substring
312 (org-fontify-like-in-org-mode
313 (concat prefix heading)
314 org-odd-levels-only)
315 (length prefix))))))
316 (when (and cat task)
317 (insert (format "[%c] %-15s %s\n" i cat task))
318 (cons i marker)))))
320 (defun org-clock-get-clock-string ()
321 "Form a clock-string, that will be show in the mode line.
322 If an effort estimate was defined for current item, use
323 01:30/01:50 format (clocked/estimated).
324 If not, show simply the clocked time like 01:50."
325 (let* ((clocked-time (org-clock-get-clocked-time))
326 (h (floor clocked-time 60))
327 (m (- clocked-time (* 60 h)))
329 (if (and org-clock-effort)
330 (let* ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
331 (effort-h (floor effort-in-minutes 60))
332 (effort-m (- effort-in-minutes (* effort-h 60)))
334 (format (concat "-[" org-time-clocksum-format "/" org-time-clocksum-format " (%s)]")
335 h m effort-h effort-m org-clock-heading)
337 (format (concat "-[" org-time-clocksum-format " (%s)]")
338 h m org-clock-heading))
341 (defun org-clock-update-mode-line ()
342 (setq org-mode-line-string
343 (org-propertize
344 (let ((clock-string (org-clock-get-clock-string))
345 (help-text "Org-mode clock is running. Mouse-2 to go there."))
346 (if (and (> org-clock-string-limit 0)
347 (> (length clock-string) org-clock-string-limit))
348 (org-propertize (substring clock-string 0 org-clock-string-limit)
349 'help-echo (concat help-text ": " org-clock-heading))
350 (org-propertize clock-string 'help-echo help-text)))
351 'local-map org-clock-mode-line-map
352 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)))
353 (if org-clock-effort (org-clock-notify-once-if-expired))
354 (force-mode-line-update))
356 (defun org-clock-get-clocked-time ()
357 "Get the clocked time for the rrent item in minutes.
358 The time returned includes the the time spent on this task in
359 previous clocking intervals."
360 (let ((currently-clocked-time
361 (floor (- (time-to-seconds (current-time))
362 (time-to-seconds org-clock-start-time)) 60)))
363 (+ currently-clocked-time (or org-clock-total-time 0))))
365 (defvar org-clock-notification-was-shown nil
366 "Shows if we have shown notification already.")
368 (defun org-clock-notify-once-if-expired ()
369 "Show notification if we spent more time then we estimated before.
370 Notification is shown only once."
371 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
372 (clocked-time (org-clock-get-clocked-time)))
373 (if (>= clocked-time effort-in-minutes)
374 (unless org-clock-notification-was-shown
375 (setq org-clock-notification-was-shown t)
376 (org-clock-play-sound)
377 (org-show-notification
378 (format "Task '%s' should be finished by now. (%s)"
379 org-clock-heading org-clock-effort)))
380 (setq org-clock-notification-was-shown nil))))
382 (defun org-show-notification (notification)
383 "Show notification. Use libnotify, if available."
384 (if (org-program-exists "notify-send")
385 (start-process "emacs-timer-notification" nil "notify-send" notification))
386 ;; In any case, show in message area
387 (message notification))
389 (defun org-clock-play-sound ()
390 "Play sound as configured by `org-clock-sound'.
391 Use alsa's aplay tool if available."
392 (cond
393 ((not org-clock-sound))
394 ((eq org-clock-sound t) (beep t) (beep t))
395 ((stringp org-clock-sound)
396 (if (file-exists-p org-clock-sound)
397 (if (org-program-exists "aplay")
398 (start-process "org-clock-play-notification" nil
399 "aplay" org-clock-sound)
400 (condition-case nil
401 (play-sound-file org-clock-sound)
402 (error (beep t) (beep t))))))))
404 (defun org-program-exists (program-name)
405 "Checks whenever we can locate program and launch it."
406 (if (eq system-type 'gnu/linux)
407 (= 0 (call-process "which" nil nil nil program-name))
411 (defvar org-clock-mode-line-entry nil
412 "Information for the modeline about the running clock.")
414 (defun org-clock-in (&optional select)
415 "Start the clock on the current item.
416 If necessary, clock-out of the currently active clock.
417 With prefix arg SELECT, offer a list of recently clocked tasks to
418 clock into. When SELECT is `C-u C-u', clock into the current task and mark
419 is as the default task, a special task that will always be offered in
420 the clocking selection, associated with the letter `d'."
421 (interactive "P")
422 (catch 'abort
423 (let ((interrupting (marker-buffer org-clock-marker))
424 ts selected-task target-pos (msg-extra ""))
425 (when (equal select '(4))
426 (setq selected-task (org-clock-select-task "Clock-in on task: "))
427 (if selected-task
428 (setq selected-task (copy-marker selected-task))
429 (error "Abort")))
430 (when interrupting
431 ;; We are interrupting the clocking of a different task.
432 ;; Save a marker to this task, so that we can go back.
433 (move-marker org-clock-interrupted-task
434 (marker-position org-clock-marker)
435 (marker-buffer org-clock-marker))
436 (org-clock-out t))
438 (when (equal select '(16))
439 ;; Mark as default clocking task
440 (save-excursion
441 (org-back-to-heading t)
442 (move-marker org-clock-default-task (point))))
444 (setq target-pos (point)) ;; we want to clock in at this location
445 (save-excursion
446 (when (and selected-task (marker-buffer selected-task))
447 ;; There is a selected task, move to the correct buffer
448 ;; and set the new target position.
449 (set-buffer (org-base-buffer (marker-buffer selected-task)))
450 (setq target-pos (marker-position selected-task))
451 (move-marker selected-task nil))
452 (save-excursion
453 (save-restriction
454 (widen)
455 (goto-char target-pos)
456 (org-back-to-heading t)
457 (or interrupting (move-marker org-clock-interrupted-task nil))
458 (org-clock-history-push)
459 (cond ((functionp org-clock-in-switch-to-state)
460 (looking-at org-complex-heading-regexp)
461 (let ((newstate (funcall org-clock-in-switch-to-state
462 (match-string 2))))
463 (if newstate (org-todo newstate))))
464 ((and org-clock-in-switch-to-state
465 (not (looking-at (concat outline-regexp "[ \t]*"
466 org-clock-in-switch-to-state
467 "\\>"))))
468 (org-todo org-clock-in-switch-to-state)))
469 (setq org-clock-heading-for-remember
470 (and (looking-at org-complex-heading-regexp)
471 (match-end 4)
472 (org-trim (buffer-substring (match-end 1)
473 (match-end 4)))))
474 (setq org-clock-heading
475 (cond ((and org-clock-heading-function
476 (functionp org-clock-heading-function))
477 (funcall org-clock-heading-function))
478 ((looking-at org-complex-heading-regexp)
479 (match-string 4))
480 (t "???")))
481 (setq org-clock-heading (org-propertize org-clock-heading
482 'face nil))
483 (org-clock-find-position org-clock-in-resume)
484 (cond
485 ((and org-clock-in-resume
486 (looking-at
487 (concat "^[ \t]* " org-clock-string
488 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
489 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
490 (message "Matched %s" (match-string 1))
491 (setq ts (concat "[" (match-string 1) "]"))
492 (goto-char (match-end 1))
493 (setq org-clock-start-time
494 (apply 'encode-time
495 (org-parse-time-string (match-string 1))))
496 (setq org-clock-effort (org-get-effort))
497 (setq org-clock-total-time (org-clock-sum-current-item
498 (org-clock-get-sum-start))))
499 ((eq org-clock-in-resume 'auto-restart)
500 ;; called from org-clock-load during startup,
501 ;; do not interrupt, but warn!
502 (message "Cannot restart clock because task does not contain unfinished clock")
503 (ding)
504 (sit-for 2)
505 (throw 'abort nil))
507 (insert-before-markers "\n")
508 (backward-char 1)
509 (org-indent-line-function)
510 (when (and (save-excursion
511 (end-of-line 0)
512 (org-in-item-p)))
513 (beginning-of-line 1)
514 (org-indent-line-to (- (org-get-indentation) 2)))
515 (insert org-clock-string " ")
516 (setq org-clock-effort (org-get-effort))
517 (setq org-clock-total-time (org-clock-sum-current-item
518 (org-clock-get-sum-start)))
519 (setq org-clock-start-time (current-time))
520 (setq ts (org-insert-time-stamp org-clock-start-time
521 'with-hm 'inactive))))
522 (move-marker org-clock-marker (point) (buffer-base-buffer))
523 (or global-mode-string (setq global-mode-string '("")))
524 (or (memq 'org-mode-line-string global-mode-string)
525 (setq global-mode-string
526 (append global-mode-string '(org-mode-line-string))))
527 (org-clock-update-mode-line)
528 (setq org-clock-mode-line-timer
529 (run-with-timer 60 60 'org-clock-update-mode-line))
530 (message "Clock starts at %s - %s" ts msg-extra)))))))
532 (defvar msg-extra)
533 (defun org-clock-get-sum-start ()
534 "Return the time from which clock times should be counted.
535 This is for the currently running clock as it is displayed
536 in the mode line. This function looks at the properties
537 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
538 corresponding variable `org-clock-modeline-total' and then
539 decides which time to use."
540 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
541 (symbol-name org-clock-modeline-total)))
542 (lr (org-entry-get nil "LAST_REPEAT")))
543 (cond
544 ((equal cmt "current")
545 (setq msg-extra "showing time in current clock instance")
546 (current-time))
547 ((equal cmt "today")
548 (setq msg-extra "showing today's task time.")
549 (let* ((dt (decode-time (current-time))))
550 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
551 (if org-extend-today-until
552 (setf (nth 2 dt) org-extend-today-until))
553 (apply 'encode-time dt)))
554 ((or (equal cmt "all")
555 (and (or (not cmt) (equal cmt "auto"))
556 (not lr)))
557 (setq msg-extra "showing entire task time.")
558 nil)
559 ((or (equal cmt "repeat")
560 (and (or (not cmt) (equal cmt "auto"))
561 lr))
562 (setq msg-extra "showing task time since last repeat.")
563 (if (not lr)
565 (org-time-string-to-time lr)))
566 (t nil))))
568 (defun org-clock-find-position (find-unclosed)
569 "Find the location where the next clock line should be inserted.
570 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
571 line and position cursor in that line."
572 (org-back-to-heading t)
573 (catch 'exit
574 (let ((beg (save-excursion
575 (beginning-of-line 2)
576 (or (bolp) (newline))
577 (point)))
578 (end (progn (outline-next-heading) (point)))
579 (re (concat "^[ \t]*" org-clock-string))
580 (cnt 0)
581 (drawer (if (stringp org-clock-into-drawer)
582 org-clock-into-drawer "LOGBOOK"))
583 first last ind-last)
584 (goto-char beg)
585 (when (and find-unclosed
586 (re-search-forward
587 (concat "^[ \t]* " org-clock-string
588 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
589 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
590 end t))
591 (beginning-of-line 1)
592 (throw 'exit t))
593 (when (eobp) (newline) (setq end (max (point) end)))
594 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
595 ;; we seem to have a CLOCK drawer, so go there.
596 (beginning-of-line 2)
597 (or org-log-states-order-reversed
598 (and (re-search-forward org-property-end-re nil t)
599 (goto-char (match-beginning 0))))
600 (throw 'exit t))
601 ;; Lets count the CLOCK lines
602 (goto-char beg)
603 (while (re-search-forward re end t)
604 (setq first (or first (match-beginning 0))
605 last (match-beginning 0)
606 cnt (1+ cnt)))
607 (when (and (integerp org-clock-into-drawer)
608 last
609 (>= (1+ cnt) org-clock-into-drawer))
610 ;; Wrap current entries into a new drawer
611 (goto-char last)
612 (setq ind-last (org-get-indentation))
613 (beginning-of-line 2)
614 (if (and (>= (org-get-indentation) ind-last)
615 (org-at-item-p))
616 (org-end-of-item))
617 (insert ":END:\n")
618 (beginning-of-line 0)
619 (org-indent-line-to ind-last)
620 (goto-char first)
621 (insert ":" drawer ":\n")
622 (beginning-of-line 0)
623 (org-indent-line-function)
624 (org-flag-drawer t)
625 (beginning-of-line 2)
626 (or org-log-states-order-reversed
627 (and (re-search-forward org-property-end-re nil t)
628 (goto-char (match-beginning 0))))
629 (throw 'exit nil))
631 (goto-char beg)
632 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
633 (not (equal (match-string 1) org-clock-string)))
634 ;; Planning info, skip to after it
635 (beginning-of-line 2)
636 (or (bolp) (newline)))
637 (when (or (eq org-clock-into-drawer t)
638 (stringp org-clock-into-drawer)
639 (and (integerp org-clock-into-drawer)
640 (< org-clock-into-drawer 2)))
641 (insert ":" drawer ":\n:END:\n")
642 (beginning-of-line -1)
643 (org-indent-line-function)
644 (org-flag-drawer t)
645 (beginning-of-line 2)
646 (org-indent-line-function)
647 (beginning-of-line)
648 (or org-log-states-order-reversed
649 (and (re-search-forward org-property-end-re nil t)
650 (goto-char (match-beginning 0))))))))
652 (defun org-clock-out (&optional fail-quietly)
653 "Stop the currently running clock.
654 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
655 (interactive)
656 (catch 'exit
657 (if (not (marker-buffer org-clock-marker))
658 (if fail-quietly (throw 'exit t) (error "No active clock")))
659 (let (ts te s h m remove)
660 (save-excursion
661 (set-buffer (marker-buffer org-clock-marker))
662 (save-restriction
663 (widen)
664 (goto-char org-clock-marker)
665 (beginning-of-line 1)
666 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
667 (equal (match-string 1) org-clock-string))
668 (setq ts (match-string 2))
669 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
670 (goto-char (match-end 0))
671 (delete-region (point) (point-at-eol))
672 (insert "--")
673 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
674 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
675 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
676 h (floor (/ s 3600))
677 s (- s (* 3600 h))
678 m (floor (/ s 60))
679 s (- s (* 60 s)))
680 (insert " => " (format "%2d:%02d" h m))
681 (when (setq remove (and org-clock-out-remove-zero-time-clocks
682 (= (+ h m) 0)))
683 (beginning-of-line 1)
684 (delete-region (point) (point-at-eol))
685 (and (looking-at "\n") (> (point-max) (1+ (point)))
686 (delete-char 1)))
687 (move-marker org-clock-marker nil)
688 (when org-log-note-clock-out
689 (org-add-log-setup 'clock-out nil nil nil nil
690 (concat "# Task: " (org-get-heading t) "\n\n")))
691 (when org-clock-mode-line-timer
692 (cancel-timer org-clock-mode-line-timer)
693 (setq org-clock-mode-line-timer nil))
694 (setq global-mode-string
695 (delq 'org-mode-line-string global-mode-string))
696 (when org-clock-out-switch-to-state
697 (save-excursion
698 (org-back-to-heading t)
699 (let ((org-inhibit-logging t))
700 (cond
701 ((functionp org-clock-out-switch-to-state)
702 (looking-at org-complex-heading-regexp)
703 (let ((newstate (funcall org-clock-out-switch-to-state
704 (match-string 2))))
705 (if newstate (org-todo newstate))))
706 ((and org-clock-out-switch-to-state
707 (not (looking-at (concat outline-regexp "[ \t]*"
708 org-clock-out-switch-to-state
709 "\\>"))))
710 (org-todo org-clock-out-switch-to-state))))))
711 (force-mode-line-update)
712 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
713 (if remove " => LINE REMOVED" "")))))))
715 (defun org-clock-cancel ()
716 "Cancel the running clock be removing the start timestamp."
717 (interactive)
718 (if (not (marker-buffer org-clock-marker))
719 (error "No active clock"))
720 (save-excursion
721 (set-buffer (marker-buffer org-clock-marker))
722 (goto-char org-clock-marker)
723 (delete-region (1- (point-at-bol)) (point-at-eol)))
724 (setq global-mode-string
725 (delq 'org-mode-line-string global-mode-string))
726 (force-mode-line-update)
727 (message "Clock canceled"))
729 (defun org-clock-goto (&optional select)
730 "Go to the currently clocked-in entry, or to the most recently clocked one.
731 With prefix arg SELECT, offer recently clocked tasks for selection."
732 (interactive "P")
733 (let* ((recent nil)
734 (m (cond
735 (select
736 (or (org-clock-select-task "Select task to go to: ")
737 (error "No task selected")))
738 ((marker-buffer org-clock-marker) org-clock-marker)
739 ((and org-clock-goto-may-find-recent-task
740 (car org-clock-history)
741 (marker-buffer (car org-clock-history)))
742 (setq recent t)
743 (car org-clock-history))
744 (t (error "No active or recent clock task")))))
745 (switch-to-buffer (marker-buffer m))
746 (if (or (< m (point-min)) (> m (point-max))) (widen))
747 (goto-char m)
748 (org-show-entry)
749 (org-back-to-heading)
750 (org-cycle-hide-drawers 'children)
751 (recenter)
752 (if recent
753 (message "No running clock, this is the most recently clocked task"))))
756 (defvar org-clock-file-total-minutes nil
757 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
758 (make-variable-buffer-local 'org-clock-file-total-minutes)
760 (defun org-clock-sum (&optional tstart tend)
761 "Sum the times for each subtree.
762 Puts the resulting times in minutes as a text property on each headline.
763 TSTART and TEND can mark a time range to be considered."
764 (interactive)
765 (let* ((bmp (buffer-modified-p))
766 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
767 org-clock-string
768 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
769 (lmax 30)
770 (ltimes (make-vector lmax 0))
771 (t1 0)
772 (level 0)
773 ts te dt
774 time)
775 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
776 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
777 (if (consp tstart) (setq tstart (time-to-seconds tstart)))
778 (if (consp tend) (setq tend (time-to-seconds tend)))
779 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
780 (save-excursion
781 (goto-char (point-max))
782 (while (re-search-backward re nil t)
783 (cond
784 ((match-end 2)
785 ;; Two time stamps
786 (setq ts (match-string 2)
787 te (match-string 3)
788 ts (time-to-seconds
789 (apply 'encode-time (org-parse-time-string ts)))
790 te (time-to-seconds
791 (apply 'encode-time (org-parse-time-string te)))
792 ts (if tstart (max ts tstart) ts)
793 te (if tend (min te tend) te)
794 dt (- te ts)
795 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
796 ((match-end 4)
797 ;; A naked time
798 (setq t1 (+ t1 (string-to-number (match-string 5))
799 (* 60 (string-to-number (match-string 4))))))
800 (t ;; A headline
801 (setq level (- (match-end 1) (match-beginning 1)))
802 (when (or (> t1 0) (> (aref ltimes level) 0))
803 (loop for l from 0 to level do
804 (aset ltimes l (+ (aref ltimes l) t1)))
805 (setq t1 0 time (aref ltimes level))
806 (loop for l from level to (1- lmax) do
807 (aset ltimes l 0))
808 (goto-char (match-beginning 0))
809 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
810 (setq org-clock-file-total-minutes (aref ltimes 0)))
811 (set-buffer-modified-p bmp)))
813 (defun org-clock-sum-current-item (&optional tstart)
814 "Returns time, clocked on current item in total"
815 (save-excursion
816 (save-restriction
817 (org-narrow-to-subtree)
818 (org-clock-sum tstart)
819 org-clock-file-total-minutes)))
821 (defun org-clock-display (&optional total-only)
822 "Show subtree times in the entire buffer.
823 If TOTAL-ONLY is non-nil, only show the total time for the entire file
824 in the echo area."
825 (interactive)
826 (org-clock-remove-overlays)
827 (let (time h m p)
828 (org-clock-sum)
829 (unless total-only
830 (save-excursion
831 (goto-char (point-min))
832 (while (or (and (equal (setq p (point)) (point-min))
833 (get-text-property p :org-clock-minutes))
834 (setq p (next-single-property-change
835 (point) :org-clock-minutes)))
836 (goto-char p)
837 (when (setq time (get-text-property p :org-clock-minutes))
838 (org-clock-put-overlay time (funcall outline-level))))
839 (setq h (/ org-clock-file-total-minutes 60)
840 m (- org-clock-file-total-minutes (* 60 h)))
841 ;; Arrange to remove the overlays upon next change.
842 (when org-remove-highlights-with-change
843 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
844 nil 'local))))
845 (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
847 (defvar org-clock-overlays nil)
848 (make-variable-buffer-local 'org-clock-overlays)
850 (defun org-clock-put-overlay (time &optional level)
851 "Put an overlays on the current line, displaying TIME.
852 If LEVEL is given, prefix time with a corresponding number of stars.
853 This creates a new overlay and stores it in `org-clock-overlays', so that it
854 will be easy to remove."
855 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
856 (l (if level (org-get-valid-level level 0) 0))
857 (fmt (concat "%s " org-time-clocksum-format "%s"))
858 (off 0)
859 ov tx)
860 (org-move-to-column c)
861 (unless (eolp) (skip-chars-backward "^ \t"))
862 (skip-chars-backward " \t")
863 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
864 tx (concat (buffer-substring (1- (point)) (point))
865 (make-string (+ off (max 0 (- c (current-column)))) ?.)
866 (org-add-props (format fmt
867 (make-string l ?*) h m
868 (make-string (- 16 l) ?\ ))
869 (list 'face 'org-clock-overlay))
870 ""))
871 (if (not (featurep 'xemacs))
872 (org-overlay-put ov 'display tx)
873 (org-overlay-put ov 'invisible t)
874 (org-overlay-put ov 'end-glyph (make-glyph tx)))
875 (push ov org-clock-overlays)))
877 (defun org-clock-remove-overlays (&optional beg end noremove)
878 "Remove the occur highlights from the buffer.
879 BEG and END are ignored. If NOREMOVE is nil, remove this function
880 from the `before-change-functions' in the current buffer."
881 (interactive)
882 (unless org-inhibit-highlight-removal
883 (mapc 'org-delete-overlay org-clock-overlays)
884 (setq org-clock-overlays nil)
885 (unless noremove
886 (remove-hook 'before-change-functions
887 'org-clock-remove-overlays 'local))))
889 (defvar state) ;; dynamically scoped into this function
890 (defun org-clock-out-if-current ()
891 "Clock out if the current entry contains the running clock.
892 This is used to stop the clock after a TODO entry is marked DONE,
893 and is only done if the variable `org-clock-out-when-done' is not nil."
894 (when (and org-clock-out-when-done
895 (member state org-done-keywords)
896 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker))
897 (marker-buffer org-clock-marker))
898 (or (buffer-base-buffer (current-buffer))
899 (current-buffer)))
900 (< (point) org-clock-marker)
901 (> (save-excursion (outline-next-heading) (point))
902 org-clock-marker))
903 ;; Clock out, but don't accept a logging message for this.
904 (let ((org-log-note-clock-out nil))
905 (org-clock-out))))
907 (add-hook 'org-after-todo-state-change-hook
908 'org-clock-out-if-current)
910 ;;;###autoload
911 (defun org-get-clocktable (&rest props)
912 "Get a formatted clocktable with parameters according to PROPS.
913 The table is created in a temporary buffer, fully formatted and
914 fontified, and then returned."
915 ;; Set the defaults
916 (setq props (plist-put props :name "clocktable"))
917 (unless (plist-member props :maxlevel)
918 (setq props (plist-put props :maxlevel 2)))
919 (unless (plist-member props :scope)
920 (setq props (plist-put props :scope 'agenda)))
921 (with-temp-buffer
922 (org-mode)
923 (org-create-dblock props)
924 (org-update-dblock)
925 (font-lock-fontify-buffer)
926 (forward-line 2)
927 (buffer-substring (point) (progn
928 (re-search-forward "^#\\+END" nil t)
929 (point-at-bol)))))
931 (defun org-clock-report (&optional arg)
932 "Create a table containing a report about clocked time.
933 If the cursor is inside an existing clocktable block, then the table
934 will be updated. If not, a new clocktable will be inserted.
935 When called with a prefix argument, move to the first clock table in the
936 buffer and update it."
937 (interactive "P")
938 (org-clock-remove-overlays)
939 (when arg
940 (org-find-dblock "clocktable")
941 (org-show-entry))
942 (if (org-in-clocktable-p)
943 (goto-char (org-in-clocktable-p))
944 (org-create-dblock (list :name "clocktable"
945 :maxlevel 2 :scope 'file)))
946 (org-update-dblock))
948 (defun org-in-clocktable-p ()
949 "Check if the cursor is in a clocktable."
950 (let ((pos (point)) start)
951 (save-excursion
952 (end-of-line 1)
953 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
954 (setq start (match-beginning 0))
955 (re-search-forward "^#\\+END:.*" nil t)
956 (>= (match-end 0) pos)
957 start))))
959 (defun org-clock-special-range (key &optional time as-strings)
960 "Return two times bordering a special time range.
961 Key is a symbol specifying the range and can be one of `today', `yesterday',
962 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
963 A week starts Monday 0:00 and ends Sunday 24:00.
964 The range is determined relative to TIME. TIME defaults to the current time.
965 The return value is a cons cell with two internal times like the ones
966 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
967 the returned times will be formatted strings."
968 (if (integerp key) (setq key (intern (number-to-string key))))
969 (let* ((tm (decode-time (or time (current-time))))
970 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
971 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
972 (dow (nth 6 tm))
973 (skey (symbol-name key))
974 (shift 0)
975 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
976 (cond
977 ((string-match "^[0-9]+$" skey)
978 (setq y (string-to-number skey) m 1 d 1 key 'year))
979 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
980 (setq y (string-to-number (match-string 1 skey))
981 month (string-to-number (match-string 2 skey))
982 d 1 key 'month))
983 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
984 (require 'cal-iso)
985 (setq y (string-to-number (match-string 1 skey))
986 w (string-to-number (match-string 2 skey)))
987 (setq date (calendar-gregorian-from-absolute
988 (calendar-absolute-from-iso (list w 1 y))))
989 (setq d (nth 1 date) month (car date) y (nth 2 date)
990 dow 1
991 key 'week))
992 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
993 (setq y (string-to-number (match-string 1 skey))
994 month (string-to-number (match-string 2 skey))
995 d (string-to-number (match-string 3 skey))
996 key 'day))
997 ((string-match "\\([-+][0-9]+\\)$" skey)
998 (setq shift (string-to-number (match-string 1 skey))
999 key (intern (substring skey 0 (match-beginning 1))))))
1000 (when (= shift 0)
1001 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1002 ((eq key 'lastweek) (setq key 'week shift -1))
1003 ((eq key 'lastmonth) (setq key 'month shift -1))
1004 ((eq key 'lastyear) (setq key 'year shift -1))))
1005 (cond
1006 ((memq key '(day today))
1007 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1008 ((memq key '(week thisweek))
1009 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1010 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1011 ((memq key '(month thismonth))
1012 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1013 ((memq key '(year thisyear))
1014 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1015 (t (error "No such time block %s" key)))
1016 (setq ts (encode-time s m h d month y)
1017 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1018 (or d1 d) (or month1 month) (or y1 y)))
1019 (setq fm (cdr org-time-stamp-formats))
1020 (cond
1021 ((memq key '(day today))
1022 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1023 ((memq key '(week thisweek))
1024 (setq txt (format-time-string "week %G-W%V" ts)))
1025 ((memq key '(month thismonth))
1026 (setq txt (format-time-string "%B %Y" ts)))
1027 ((memq key '(year thisyear))
1028 (setq txt (format-time-string "the year %Y" ts))))
1029 (if as-strings
1030 (list (format-time-string fm ts) (format-time-string fm te) txt)
1031 (list ts te txt))))
1033 (defun org-clocktable-shift (dir n)
1034 "Try to shift the :block date of the clocktable at point.
1035 Point must be in the #+BEGIN: line of a clocktable, or this function
1036 will throw an error.
1037 DIR is a direction, a symbol `left', `right', `up', or `down'.
1038 Both `left' and `down' shift the block toward the past, `up' and `right'
1039 push it toward the future.
1040 N is the number of shift steps to take. The size of the step depends on
1041 the currently selected interval size."
1042 (setq n (prefix-numeric-value n))
1043 (and (memq dir '(left down)) (setq n (- n)))
1044 (save-excursion
1045 (goto-char (point-at-bol))
1046 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1047 (error "Line needs a :block definition before this command works")
1048 (let* ((b (match-beginning 1)) (e (match-end 1))
1049 (s (match-string 1))
1050 block shift ins y mw d date wp m)
1051 (cond
1052 ((equal s "yesterday") (setq s "today-1"))
1053 ((equal s "lastweek") (setq s "thisweek-1"))
1054 ((equal s "lastmonth") (setq s "thismonth-1"))
1055 ((equal s "lastyear") (setq s "thisyear-1")))
1056 (cond
1057 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
1058 (setq block (match-string 1 s)
1059 shift (if (match-end 2)
1060 (string-to-number (match-string 2 s))
1062 (setq shift (+ shift n))
1063 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1064 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1065 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1066 (setq y (string-to-number (match-string 1 s))
1067 wp (and (match-end 3) (match-string 3 s))
1068 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1069 d (and (match-end 6) (string-to-number (match-string 6 s))))
1070 (cond
1071 (d (setq ins (format-time-string
1072 "%Y-%m-%d"
1073 (encode-time 0 0 0 (+ d n) m y))))
1074 ((and wp mw (> (length wp) 0))
1075 (require 'cal-iso)
1076 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1077 (setq ins (format-time-string
1078 "%G-W%V"
1079 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1081 (setq ins (format-time-string
1082 "%Y-%m"
1083 (encode-time 0 0 0 1 (+ mw n) y))))
1085 (setq ins (number-to-string (+ y n))))))
1086 (t (error "Cannot shift clocktable block")))
1087 (when ins
1088 (goto-char b)
1089 (insert ins)
1090 (delete-region (point) (+ (point) (- e b)))
1091 (beginning-of-line 1)
1092 (org-update-dblock)
1093 t)))))
1095 (defun org-dblock-write:clocktable (params)
1096 "Write the standard clocktable."
1097 (catch 'exit
1098 (let* ((hlchars '((1 . "*") (2 . "/")))
1099 (ins (make-marker))
1100 (total-time nil)
1101 (scope (plist-get params :scope))
1102 (tostring (plist-get params :tostring))
1103 (multifile (plist-get params :multifile))
1104 (header (plist-get params :header))
1105 (maxlevel (or (plist-get params :maxlevel) 3))
1106 (step (plist-get params :step))
1107 (emph (plist-get params :emphasize))
1108 (ts (plist-get params :tstart))
1109 (te (plist-get params :tend))
1110 (block (plist-get params :block))
1111 (link (plist-get params :link))
1112 ipos time p level hlc hdl content recalc formula pcol
1113 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
1114 (setq org-clock-file-total-minutes nil)
1115 (when step
1116 (unless (or block (and ts te))
1117 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1118 (org-clocktable-steps params)
1119 (throw 'exit nil))
1120 (when block
1121 (setq cc (org-clock-special-range block nil t)
1122 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1123 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
1124 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
1125 (when (and ts (listp ts))
1126 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
1127 (when (and te (listp te))
1128 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
1129 ;; Now the times are strings we can parse.
1130 (if ts (setq ts (time-to-seconds
1131 (apply 'encode-time (org-parse-time-string ts)))))
1132 (if te (setq te (time-to-seconds
1133 (apply 'encode-time (org-parse-time-string te)))))
1134 (move-marker ins (point))
1135 (setq ipos (point))
1137 ;; Get the right scope
1138 (setq pos (point))
1139 (cond
1140 ((and scope (listp scope) (symbolp (car scope)))
1141 (setq scope (eval scope)))
1142 ((eq scope 'agenda)
1143 (setq scope (org-agenda-files t)))
1144 ((eq scope 'agenda-with-archives)
1145 (setq scope (org-agenda-files t))
1146 (setq scope (org-add-archive-files scope)))
1147 ((eq scope 'file-with-archives)
1148 (setq scope (org-add-archive-files (list (buffer-file-name)))
1149 rm-file-column t)))
1150 (setq scope-is-list (and scope (listp scope)))
1151 (save-restriction
1152 (cond
1153 ((not scope))
1154 ((eq scope 'file) (widen))
1155 ((eq scope 'subtree) (org-narrow-to-subtree))
1156 ((eq scope 'tree)
1157 (while (org-up-heading-safe))
1158 (org-narrow-to-subtree))
1159 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1160 (symbol-name scope)))
1161 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1162 (catch 'exit
1163 (while (org-up-heading-safe)
1164 (looking-at outline-regexp)
1165 (if (<= (org-reduced-level (funcall outline-level)) level)
1166 (throw 'exit nil))))
1167 (org-narrow-to-subtree))
1168 (scope-is-list
1169 (let* ((files scope)
1170 (scope 'agenda)
1171 (p1 (copy-sequence params))
1172 file)
1173 (setq p1 (plist-put p1 :tostring t))
1174 (setq p1 (plist-put p1 :multifile t))
1175 (setq p1 (plist-put p1 :scope 'file))
1176 (org-prepare-agenda-buffers files)
1177 (while (setq file (pop files))
1178 (with-current-buffer (find-buffer-visiting file)
1179 (setq tbl1 (org-dblock-write:clocktable p1))
1180 (when tbl1
1181 (push (org-clocktable-add-file
1182 file
1183 (concat "| |*File time*|*"
1184 (org-minutes-to-hh:mm-string
1185 org-clock-file-total-minutes)
1186 "*|\n"
1187 tbl1)) tbl)
1188 (setq total-time (+ (or total-time 0)
1189 org-clock-file-total-minutes))))))))
1190 (goto-char pos)
1192 (unless scope-is-list
1193 (org-clock-sum ts te)
1194 (goto-char (point-min))
1195 (setq st t)
1196 (while (or (and (bobp) (prog1 st (setq st nil))
1197 (get-text-property (point) :org-clock-minutes)
1198 (setq p (point-min)))
1199 (setq p (next-single-property-change (point) :org-clock-minutes)))
1200 (goto-char p)
1201 (when (setq time (get-text-property p :org-clock-minutes))
1202 (save-excursion
1203 (beginning-of-line 1)
1204 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1205 (setq level (org-reduced-level
1206 (- (match-end 1) (match-beginning 1))))
1207 (<= level maxlevel))
1208 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
1209 hdl (if (not link)
1210 (match-string 2)
1211 (org-make-link-string
1212 (format "file:%s::%s"
1213 (buffer-file-name)
1214 (save-match-data
1215 (org-make-org-heading-search-string
1216 (match-string 2))))
1217 (match-string 2))))
1218 (if (and (not multifile) (= level 1)) (push "|-" tbl))
1219 (push (concat
1220 "| " (int-to-string level) "|" hlc hdl hlc " |"
1221 (make-string (1- level) ?|)
1222 hlc (org-minutes-to-hh:mm-string time) hlc
1223 " |") tbl))))))
1224 (setq tbl (nreverse tbl))
1225 (if tostring
1226 (if tbl (mapconcat 'identity tbl "\n") nil)
1227 (goto-char ins)
1228 (insert-before-markers
1229 (or header
1230 (concat
1231 "Clock summary at ["
1232 (substring
1233 (format-time-string (cdr org-time-stamp-formats))
1234 1 -1)
1236 (if block (concat ", for " range-text ".") "")
1237 "\n\n"))
1238 (if scope-is-list "|File" "")
1239 "|L|Headline|Time|\n")
1240 (setq total-time (or total-time org-clock-file-total-minutes))
1241 (insert-before-markers
1242 "|-\n|"
1243 (if scope-is-list "|" "")
1245 "*Total time*| *"
1246 (org-minutes-to-hh:mm-string (or total-time 0))
1247 "*|\n|-\n")
1248 (setq tbl (delq nil tbl))
1249 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
1250 (equal (substring (car tbl) 0 2) "|-"))
1251 (pop tbl))
1252 (insert-before-markers (mapconcat
1253 'identity (delq nil tbl)
1254 (if scope-is-list "\n|-\n" "\n")))
1255 (backward-delete-char 1)
1256 (if (setq formula (plist-get params :formula))
1257 (cond
1258 ((eq formula '%)
1259 (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
1260 (insert
1261 (format
1262 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1263 pcol
1265 (+ 3 (if scope-is-list 1 0))
1266 (+ (if scope-is-list 1 0) 3)
1267 (1- pcol)))
1268 (setq recalc t))
1269 ((stringp formula)
1270 (insert "\n#+TBLFM: " formula)
1271 (setq recalc t))
1272 (t (error "invalid formula in clocktable")))
1273 ;; Should we rescue an old formula?
1274 (when (stringp (setq content (plist-get params :content)))
1275 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
1276 (setq recalc t)
1277 (insert "\n" (match-string 1 (plist-get params :content)))
1278 (beginning-of-line 0))))
1279 (goto-char ipos)
1280 (skip-chars-forward "^|")
1281 (org-table-align)
1282 (when recalc
1283 (if (eq formula '%)
1284 (save-excursion (org-table-goto-column pcol nil 'force)
1285 (insert "%")))
1286 (org-table-recalculate 'all))
1287 (when rm-file-column
1288 (forward-char 1)
1289 (org-table-delete-column)))))))
1291 (defun org-clocktable-steps (params)
1292 (let* ((p1 (copy-sequence params))
1293 (ts (plist-get p1 :tstart))
1294 (te (plist-get p1 :tend))
1295 (step0 (plist-get p1 :step))
1296 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
1297 (block (plist-get p1 :block))
1298 cc range-text)
1299 (when block
1300 (setq cc (org-clock-special-range block nil t)
1301 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1302 (if ts (setq ts (time-to-seconds
1303 (apply 'encode-time (org-parse-time-string ts)))))
1304 (if te (setq te (time-to-seconds
1305 (apply 'encode-time (org-parse-time-string te)))))
1306 (setq p1 (plist-put p1 :header ""))
1307 (setq p1 (plist-put p1 :step nil))
1308 (setq p1 (plist-put p1 :block nil))
1309 (while (< ts te)
1310 (or (bolp) (insert "\n"))
1311 (setq p1 (plist-put p1 :tstart (format-time-string
1312 (org-time-stamp-format nil t)
1313 (seconds-to-time ts))))
1314 (setq p1 (plist-put p1 :tend (format-time-string
1315 (org-time-stamp-format nil t)
1316 (seconds-to-time (setq ts (+ ts step))))))
1317 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
1318 (plist-get p1 :tstart) "\n")
1319 (org-dblock-write:clocktable p1)
1320 (re-search-forward "#\\+END:")
1321 (end-of-line 0))))
1323 (defun org-clocktable-add-file (file table)
1324 (if table
1325 (let ((lines (org-split-string table "\n"))
1326 (ff (file-name-nondirectory file)))
1327 (mapconcat 'identity
1328 (mapcar (lambda (x)
1329 (if (string-match org-table-dataline-regexp x)
1330 (concat "|" ff x)
1332 lines)
1333 "\n"))))
1335 (defun org-clock-time% (total &rest strings)
1336 "Compute a time fraction in percent.
1337 TOTAL s a time string like 10:21 specifying the total times.
1338 STRINGS is a list of strings that should be checked for a time.
1339 The first string that does have a time will be used.
1340 This function is made for clock tables."
1341 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1342 tot s)
1343 (save-match-data
1344 (catch 'exit
1345 (if (not (string-match re total))
1346 (throw 'exit 0.)
1347 (setq tot (+ (string-to-number (match-string 2 total))
1348 (* 60 (string-to-number (match-string 1 total)))))
1349 (if (= tot 0.) (throw 'exit 0.)))
1350 (while (setq s (pop strings))
1351 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
1352 (throw 'exit
1353 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
1354 (* 60 (string-to-number (match-string 1 s)))))
1355 tot))))
1356 0))))
1358 (defun org-clock-save ()
1359 "Persist various clock-related data to disk.
1360 The details of what will be saved are regulated by the variable
1361 `org-clock-persist'."
1362 (when org-clock-persist
1363 (let (b)
1364 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
1365 (progn
1366 (delete-region (point-min) (point-max))
1367 ;;Store clock
1368 (insert (format ";; org-persist.el - %s at %s\n"
1369 system-name (format-time-string
1370 (cdr org-time-stamp-formats))))
1371 (if (and (setq b (marker-buffer org-clock-marker))
1372 (setq b (or (buffer-base-buffer b) b))
1373 (buffer-live-p b)
1374 (buffer-file-name b)
1375 (or (not org-clock-persist-query-save)
1376 (y-or-n-p (concat "Save current clock ("
1377 (substring-no-properties org-clock-heading)
1378 ") "))))
1379 (insert "(setq resume-clock '(\""
1380 (buffer-file-name (marker-buffer org-clock-marker))
1381 "\" . " (int-to-string (marker-position org-clock-marker))
1382 "))\n"))
1383 ;; Store clocked task history. Tasks are stored reversed to make
1384 ;; reading simpler
1385 (when (and org-clock-history (eq org-clock-persist t))
1386 (insert
1387 "(setq stored-clock-history '("
1388 (mapconcat
1389 (lambda (m)
1390 (when (and (setq b (marker-buffer m))
1391 (setq b (or (buffer-base-buffer b) b))
1392 (buffer-live-p b)
1393 (buffer-file-name b))
1394 (concat "(\"" (buffer-file-name b)
1395 "\" . " (int-to-string (marker-position m))
1396 ")")))
1397 (reverse org-clock-history) " ") "))\n"))
1398 (save-buffer)
1399 (kill-buffer (current-buffer)))))))
1401 (defvar org-clock-loaded nil
1402 "Was the clock file loaded?")
1404 (defun org-clock-load ()
1405 "Load clock-related data from disk, maybe resuming a stored clock."
1406 (when (and org-clock-persist (not org-clock-loaded))
1407 (let ((filename (expand-file-name org-clock-persist-file))
1408 (org-clock-in-resume 'auto-restart)
1409 resume-clock stored-clock-history)
1410 (if (not (file-readable-p filename))
1411 (message "Not restoring clock data; %s not found"
1412 org-clock-persist-file)
1413 (message "%s" "Restoring clock data")
1414 (setq org-clock-loaded t)
1415 (load-file filename)
1416 ;; load history
1417 (when stored-clock-history
1418 (save-window-excursion
1419 (mapc (lambda (task)
1420 (if (file-exists-p (car task))
1421 (org-clock-history-push (cdr task)
1422 (find-file (car task)))))
1423 stored-clock-history)))
1424 ;; resume clock
1425 (when (and resume-clock org-clock-persist
1426 (file-exists-p (car resume-clock))
1427 (or (not org-clock-persist-query-resume)
1428 (y-or-n-p
1429 (concat
1430 "Resume clock ("
1431 (with-current-buffer (find-file (car resume-clock))
1432 (save-excursion
1433 (goto-char (cdr resume-clock))
1434 (org-back-to-heading t)
1435 (and (looking-at org-complex-heading-regexp)
1436 (match-string 4))))
1437 ") "))))
1438 (when (file-exists-p (car resume-clock))
1439 (with-current-buffer (find-file (car resume-clock))
1440 (goto-char (cdr resume-clock))
1441 (org-clock-in)
1442 (if (org-invisible-p)
1443 (org-show-context)))))))))
1445 ;;;###autoload
1446 (defun org-clock-persistence-insinuate ()
1447 "Set up hooks for clock persistence"
1448 (add-hook 'org-mode-hook 'org-clock-load)
1449 (add-hook 'kill-emacs-hook 'org-clock-save))
1451 (provide 'org-clock)
1453 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1455 ;;; org-clock.el ends here