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