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