lisp/org-clock.el: allow to set the language through a new :lang parameter.
[org-mode/org-jambu.git] / lisp / org-clock.el
blob5de2733482b5b2c1bc83d111a152875e6f283c66
1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
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: 7.4
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 ;;; Code:
34 (eval-when-compile
35 (require 'cl))
37 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
38 (declare-function notifications-notify "notifications" (&rest params))
39 (defvar org-time-stamp-formats)
41 (defgroup org-clock nil
42 "Options concerning clocking working time in Org-mode."
43 :tag "Org Clock"
44 :group 'org-progress)
46 (defcustom org-clock-into-drawer org-log-into-drawer
47 "Should clocking info be wrapped into a drawer?
48 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
49 If necessary, the drawer will be created.
50 When nil, the drawer will not be created, but used when present.
51 When an integer and the number of clocking entries in an item
52 reaches or exceeds this number, a drawer will be created.
53 When a string, it names the drawer to be used.
55 The default for this variable is the value of `org-log-into-drawer',
56 which see."
57 :group 'org-todo
58 :group 'org-clock
59 :type '(choice
60 (const :tag "Always" t)
61 (const :tag "Only when drawer exists" nil)
62 (integer :tag "When at least N clock entries")
63 (const :tag "Into LOGBOOK drawer" "LOGBOOK")
64 (string :tag "Into Drawer named...")))
66 (defcustom org-clock-out-when-done t
67 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
68 DONE here means any DONE-like state.
69 A nil value means clock will keep running until stopped explicitly with
70 `C-c C-x C-o', or until the clock is started in a different item.
71 Instead of t, this can also be a list of TODO states that should trigger
72 clocking out."
73 :group 'org-clock
74 :type '(choice
75 (const :tag "No" nil)
76 (const :tag "Yes, when done" t)
77 (repeat :tag "State list"
78 (string :tag "TODO keyword"))))
80 (defcustom org-clock-out-remove-zero-time-clocks nil
81 "Non-nil means remove the clock line when the resulting time is zero."
82 :group 'org-clock
83 :type 'boolean)
85 (defcustom org-clock-in-switch-to-state nil
86 "Set task to a special todo state while clocking it.
87 The value should be the state to which the entry should be
88 switched. If the value is a function, it must take one
89 parameter (the current TODO state of the item) and return the
90 state to switch it to."
91 :group 'org-clock
92 :group 'org-todo
93 :type '(choice
94 (const :tag "Don't force a state" nil)
95 (string :tag "State")
96 (symbol :tag "Function")))
98 (defcustom org-clock-out-switch-to-state nil
99 "Set task to a special todo state after clocking out.
100 The value should be the state to which the entry should be
101 switched. If the value is a function, it must take one
102 parameter (the current TODO state of the item) and return the
103 state to switch it to."
104 :group 'org-clock
105 :group 'org-todo
106 :type '(choice
107 (const :tag "Don't force a state" nil)
108 (string :tag "State")
109 (symbol :tag "Function")))
111 (defcustom org-clock-history-length 5
112 "Number of clock tasks to remember in history."
113 :group 'org-clock
114 :type 'integer)
116 (defcustom org-clock-goto-may-find-recent-task t
117 "Non-nil means `org-clock-goto' can go to recent task if no active clock."
118 :group 'org-clock
119 :type 'boolean)
121 (defcustom org-clock-heading-function nil
122 "When non-nil, should be a function to create `org-clock-heading'.
123 This is the string shown in the mode line when a clock is running.
124 The function is called with point at the beginning of the headline."
125 :group 'org-clock
126 :type 'function)
128 (defcustom org-clock-string-limit 0
129 "Maximum length of clock strings in the modeline. 0 means no limit."
130 :group 'org-clock
131 :type 'integer)
133 (defcustom org-clock-in-resume nil
134 "If non-nil, resume clock when clocking into task with open clock.
135 When clocking into a task with a clock entry which has not been closed,
136 the clock can be resumed from that point."
137 :group 'org-clock
138 :type 'boolean)
140 (defcustom org-clock-persist nil
141 "When non-nil, save the running clock when Emacs is closed.
142 The clock is resumed when Emacs restarts.
143 When this is t, both the running clock, and the entire clock
144 history are saved. When this is the symbol `clock', only the
145 running clock is saved.
147 When Emacs restarts with saved clock information, the file containing the
148 running clock as well as all files mentioned in the clock history will
149 be visited.
150 All this depends on running `org-clock-persistence-insinuate' in .emacs"
151 :group 'org-clock
152 :type '(choice
153 (const :tag "Just the running clock" clock)
154 (const :tag "Just the history" history)
155 (const :tag "Clock and history" t)
156 (const :tag "No persistence" nil)))
158 (defcustom org-clock-persist-file (convert-standard-filename
159 "~/.emacs.d/org-clock-save.el")
160 "File to save clock data to."
161 :group 'org-clock
162 :type 'string)
164 (defcustom org-clock-persist-query-save nil
165 "When non-nil, ask before saving the current clock on exit."
166 :group 'org-clock
167 :type 'boolean)
169 (defcustom org-clock-persist-query-resume t
170 "When non-nil, ask before resuming any stored clock during load."
171 :group 'org-clock
172 :type 'boolean)
174 (defcustom org-clock-sound nil
175 "Sound that will used for notifications.
176 Possible values:
178 nil no sound played.
179 t standard Emacs beep
180 file name play this sound file. If not possible, fall back to beep"
181 :group 'org-clock
182 :type '(choice
183 (const :tag "No sound" nil)
184 (const :tag "Standard beep" t)
185 (file :tag "Play sound file")))
187 (defcustom org-clock-modeline-total 'auto
188 "Default setting for the time included for the modeline clock.
189 This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
190 Allowed values are:
192 current Only the time in the current instance of the clock
193 today All time clocked into this task today
194 repeat All time clocked into this task since last repeat
195 all All time ever recorded for this task
196 auto Automatically, either `all', or `repeat' for repeating tasks"
197 :group 'org-clock
198 :type '(choice
199 (const :tag "Current clock" current)
200 (const :tag "Today's task time" today)
201 (const :tag "Since last repeat" repeat)
202 (const :tag "All task time" all)
203 (const :tag "Automatically, `all' or since `repeat'" auto)))
205 (defcustom org-task-overrun-text nil
206 "The extra modeline text that should indicate that the clock is overrun.
207 The can be nil to indicate that instead of adding text, the clock time
208 should get a different face (`org-mode-line-clock-overrun').
209 When this is a string, it is prepended to the clock string as an indication,
210 also using the face `org-mode-line-clock-overrun'."
211 :group 'org-clock
212 :type '(choice
213 (const :tag "Just mark the time string" nil)
214 (string :tag "Text to prepend")))
216 (defcustom org-show-notification-handler nil
217 "Function or program to send notification with.
218 The function or program will be called with the notification
219 string as argument."
220 :group 'org-clock
221 :type '(choice
222 (string :tag "Program")
223 (function :tag "Function")))
225 (defgroup org-clocktable nil
226 "Options concerning the clock table in Org-mode."
227 :tag "Org Clock Table"
228 :group 'org-clock)
230 (defcustom org-clocktable-defaults
231 `(list
232 :maxlevel 2
233 :lang ,org-export-default-language
234 :scope 'file
235 :block nil
236 :tstart nil
237 :tend nil
238 :step nil
239 :stepskip0 nil
240 :fileskip0 nil
241 :tags nil
242 :emphasize nil
243 :link nil
244 :narrow '40!
245 :indent t
246 :formula nil
247 :timestamp nil
248 :level nil
249 :tcolumns nil
250 :formatter nil)
251 "Default properties for clock tables."
252 :group 'org-clock
253 :type 'plist)
255 (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
256 "Function to turn clocking data into a table.
257 For more information, see `org-clocktable-write-default'."
258 :group 'org-clocktable
259 :type 'function)
261 (defcustom org-clock-clocktable-language-setup
262 '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time")
263 ("fr" "Fichier" "N" "Horodatage" "Tâche" "Durée" "TOUT" "Durée totale" "Durée fichier"))
264 "Terms used in clocktable, translated to different languages."
265 :group 'org-clocktable
266 :type 'alist)
268 (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
269 "Default properties for new clocktables.
270 These will be inserted into the BEGIN line, to make it easy for users to
271 play with them."
272 :group 'org-clocktable
273 :type 'plist)
275 (defcustom org-clock-idle-time nil
276 "When non-nil, resolve open clocks if the user is idle more than X minutes."
277 :group 'org-clock
278 :type '(choice
279 (const :tag "Never" nil)
280 (integer :tag "After N minutes")))
282 (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
283 "When to automatically resolve open clocks found in Org buffers."
284 :group 'org-clock
285 :type '(choice
286 (const :tag "Never" nil)
287 (const :tag "Always" t)
288 (const :tag "When no clock is running" when-no-clock-is-running)))
290 (defcustom org-clock-report-include-clocking-task nil
291 "When non-nil, include the current clocking task time in clock reports."
292 :group 'org-clock
293 :type 'boolean)
295 (defcustom org-clock-resolve-expert nil
296 "Non-nil means do not show the splash buffer with the clock resolver."
297 :group 'org-clock
298 :type 'boolean)
300 (defvar org-clock-in-prepare-hook nil
301 "Hook run when preparing the clock.
302 This hook is run before anything happens to the task that
303 you want to clock in. For example, you can use this hook
304 to add an effort property.")
305 (defvar org-clock-in-hook nil
306 "Hook run when starting the clock.")
307 (defvar org-clock-out-hook nil
308 "Hook run when stopping the current clock.")
310 (defvar org-clock-cancel-hook nil
311 "Hook run when cancelling the current clock.")
312 (defvar org-clock-goto-hook nil
313 "Hook run when selecting the currently clocked-in entry.")
314 (defvar org-clock-has-been-used nil
315 "Has the clock been used during the current Emacs session?")
317 ;;; The clock for measuring work time.
319 (defvar org-mode-line-string "")
320 (put 'org-mode-line-string 'risky-local-variable t)
322 (defvar org-clock-mode-line-timer nil)
323 (defvar org-clock-idle-timer nil)
324 (defvar org-clock-heading) ; defined in org.el
325 (defvar org-clock-heading-for-remember "")
326 (defvar org-clock-start-time "")
328 (defvar org-clock-leftover-time nil
329 "If non-nil, user cancelled a clock; this is when leftover time started.")
331 (defvar org-clock-effort ""
332 "Effort estimate of the currently clocking task.")
334 (defvar org-clock-total-time nil
335 "Holds total time, spent previously on currently clocked item.
336 This does not include the time in the currently running clock.")
338 (defvar org-clock-history nil
339 "List of marker pointing to recent clocked tasks.")
341 (defvar org-clock-default-task (make-marker)
342 "Marker pointing to the default task that should clock time.
343 The clock can be made to switch to this task after clocking out
344 of a different task.")
346 (defvar org-clock-interrupted-task (make-marker)
347 "Marker pointing to the task that has been interrupted by the current clock.")
349 (defvar org-clock-mode-line-map (make-sparse-keymap))
350 (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
351 (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
353 (defun org-clock-menu ()
354 (interactive)
355 (popup-menu
356 '("Clock"
357 ["Clock out" org-clock-out t]
358 ["Change effort estimate" org-clock-modify-effort-estimate t]
359 ["Go to clock entry" org-clock-goto t]
360 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
362 (defun org-clock-history-push (&optional pos buffer)
363 "Push a marker to the clock history."
364 (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
365 (let ((m (move-marker (make-marker)
366 (or pos (point)) (org-base-buffer
367 (or buffer (current-buffer)))))
368 n l)
369 (while (setq n (member m org-clock-history))
370 (move-marker (car n) nil))
371 (setq org-clock-history
372 (delq nil
373 (mapcar (lambda (x) (if (marker-buffer x) x nil))
374 org-clock-history)))
375 (when (>= (setq l (length org-clock-history)) org-clock-history-length)
376 (setq org-clock-history
377 (nreverse
378 (nthcdr (- l org-clock-history-length -1)
379 (nreverse org-clock-history)))))
380 (push m org-clock-history)))
382 (defun org-clock-save-markers-for-cut-and-paste (beg end)
383 "Save relative positions of markers in region."
384 (org-check-and-save-marker org-clock-marker beg end)
385 (org-check-and-save-marker org-clock-hd-marker beg end)
386 (org-check-and-save-marker org-clock-default-task beg end)
387 (org-check-and-save-marker org-clock-interrupted-task beg end)
388 (mapc (lambda (m) (org-check-and-save-marker m beg end))
389 org-clock-history))
391 (defun org-clocking-buffer ()
392 "Return the clocking buffer if we are currently clocking a task or nil."
393 (marker-buffer org-clock-marker))
395 (defun org-clocking-p ()
396 "Return t when clocking a task."
397 (not (equal (org-clocking-buffer) nil)))
399 (defvar org-clock-before-select-task-hook nil
400 "Hook called in task selection just before prompting the user.")
402 (defun org-clock-select-task (&optional prompt)
403 "Select a task that recently was associated with clocking."
404 (interactive)
405 (let (sel-list rpl (i 0) s)
406 (save-window-excursion
407 (org-switch-to-buffer-other-window
408 (get-buffer-create "*Clock Task Select*"))
409 (erase-buffer)
410 (when (marker-buffer org-clock-default-task)
411 (insert (org-add-props "Default Task\n" nil 'face 'bold))
412 (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
413 (push s sel-list))
414 (when (marker-buffer org-clock-interrupted-task)
415 (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
416 (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
417 (push s sel-list))
418 (when (org-clocking-p)
419 (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
420 (setq s (org-clock-insert-selection-line ?c org-clock-marker))
421 (push s sel-list))
422 (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
423 (mapc
424 (lambda (m)
425 (when (marker-buffer m)
426 (setq i (1+ i)
427 s (org-clock-insert-selection-line
428 (if (< i 10)
429 (+ i ?0)
430 (+ i (- ?A 10))) m))
431 (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
432 (push s sel-list)))
433 org-clock-history)
434 (run-hooks 'org-clock-before-select-task-hook)
435 (org-fit-window-to-buffer)
436 (message (or prompt "Select task for clocking:"))
437 (setq rpl (read-char-exclusive))
438 (cond
439 ((eq rpl ?q) nil)
440 ((eq rpl ?x) nil)
441 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
442 (t (error "Invalid task choice %c" rpl))))))
444 (defun org-clock-insert-selection-line (i marker)
445 "Insert a line for the clock selection menu.
446 And return a cons cell with the selection character integer and the marker
447 pointing to it."
448 (when (marker-buffer marker)
449 (let (file cat task heading prefix)
450 (with-current-buffer (org-base-buffer (marker-buffer marker))
451 (save-excursion
452 (save-restriction
453 (widen)
454 (ignore-errors
455 (goto-char marker)
456 (setq file (buffer-file-name (marker-buffer marker))
457 cat (org-get-category)
458 heading (org-get-heading 'notags)
459 prefix (save-excursion
460 (org-back-to-heading t)
461 (looking-at "\\*+ ")
462 (match-string 0))
463 task (substring
464 (org-fontify-like-in-org-mode
465 (concat prefix heading)
466 org-odd-levels-only)
467 (length prefix)))))))
468 (when (and cat task)
469 (insert (format "[%c] %-15s %s\n" i cat task))
470 (cons i marker)))))
472 (defvar org-task-overrun nil
473 "Internal flag indicating if the clock has overrun the planned time.")
474 (defvar org-clock-update-period 60
475 "Number of seconds between mode line clock string updates.")
477 (defun org-clock-get-clock-string ()
478 "Form a clock-string, that will be shown in the mode line.
479 If an effort estimate was defined for the current item, use
480 01:30/01:50 format (clocked/estimated).
481 If not, show simply the clocked time like 01:50."
482 (let* ((clocked-time (org-clock-get-clocked-time))
483 (h (floor clocked-time 60))
484 (m (- clocked-time (* 60 h))))
485 (if org-clock-effort
486 (let* ((effort-in-minutes
487 (org-hh:mm-string-to-minutes org-clock-effort))
488 (effort-h (floor effort-in-minutes 60))
489 (effort-m (- effort-in-minutes (* effort-h 60)))
490 (work-done-str
491 (org-propertize
492 (format org-time-clocksum-format h m)
493 'face (if (and org-task-overrun (not org-task-overrun-text))
494 'org-mode-line-clock-overrun 'org-mode-line-clock)))
495 (effort-str (format org-time-clocksum-format effort-h effort-m))
496 (clockstr (org-propertize
497 (concat "[%s/" effort-str
498 "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
499 'face 'org-mode-line-clock)))
500 (format clockstr work-done-str))
501 (org-propertize (format
502 (concat "[" org-time-clocksum-format " (%s)]")
503 h m org-clock-heading)
504 'face 'org-mode-line-clock))))
506 (defun org-clock-update-mode-line ()
507 (if org-clock-effort
508 (org-clock-notify-once-if-expired)
509 (setq org-task-overrun nil))
510 (setq org-mode-line-string
511 (org-propertize
512 (let ((clock-string (org-clock-get-clock-string))
513 (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
514 (if (and (> org-clock-string-limit 0)
515 (> (length clock-string) org-clock-string-limit))
516 (org-propertize
517 (substring clock-string 0 org-clock-string-limit)
518 'help-echo (concat help-text ": " org-clock-heading))
519 (org-propertize clock-string 'help-echo help-text)))
520 'local-map org-clock-mode-line-map
521 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
523 (if (and org-task-overrun org-task-overrun-text)
524 (setq org-mode-line-string
525 (concat (org-propertize
526 org-task-overrun-text
527 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
528 (force-mode-line-update))
530 (defun org-clock-get-clocked-time ()
531 "Get the clocked time for the current item in minutes.
532 The time returned includes the time spent on this task in
533 previous clocking intervals."
534 (let ((currently-clocked-time
535 (floor (- (org-float-time)
536 (org-float-time org-clock-start-time)) 60)))
537 (+ currently-clocked-time (or org-clock-total-time 0))))
539 (defun org-clock-modify-effort-estimate (&optional value)
540 "Add to or set the effort estimate of the item currently being clocked.
541 VALUE can be a number of minutes, or a string with format hh:mm or mm.
542 When the string starts with a + or a - sign, the current value of the effort
543 property will be changed by that amount.
544 This will update the \"Effort\" property of currently clocked item, and
545 the mode line."
546 (interactive)
547 (when (org-clock-is-active)
548 (let ((current org-clock-effort) sign)
549 (unless value
550 ;; Prompt user for a value or a change
551 (setq value
552 (read-string
553 (format "Set effort (hh:mm or mm%s): "
554 (if current
555 (format ", prefix + to add to %s" org-clock-effort)
556 "")))))
557 (when (stringp value)
558 ;; A string. See if it is a delta
559 (setq sign (string-to-char value))
560 (if (member sign '(?- ?+))
561 (setq current (org-hh:mm-string-to-minutes current)
562 value (substring value 1))
563 (setq current 0))
564 (setq value (org-hh:mm-string-to-minutes value))
565 (if (equal ?- sign)
566 (setq value (- current value))
567 (if (equal ?+ sign) (setq value (+ current value)))))
568 (setq value (max 0 value)
569 org-clock-effort (org-minutes-to-hh:mm-string value))
570 (org-entry-put org-clock-marker "Effort" org-clock-effort)
571 (org-clock-update-mode-line)
572 (message "Effort is now %s" org-clock-effort))))
574 (defvar org-clock-notification-was-shown nil
575 "Shows if we have shown notification already.")
577 (defun org-clock-notify-once-if-expired ()
578 "Show notification if we spent more time than we estimated before.
579 Notification is shown only once."
580 (when (org-clocking-p)
581 (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
582 (clocked-time (org-clock-get-clocked-time)))
583 (if (setq org-task-overrun
584 (if (or (null effort-in-minutes) (zerop effort-in-minutes))
586 (>= clocked-time effort-in-minutes)))
587 (unless org-clock-notification-was-shown
588 (setq org-clock-notification-was-shown t)
589 (org-notify
590 (format "Task '%s' should be finished by now. (%s)"
591 org-clock-heading org-clock-effort) t))
592 (setq org-clock-notification-was-shown nil)))))
594 (defun org-notify (notification &optional play-sound)
595 "Send a NOTIFICATION and maybe PLAY-SOUND."
596 (org-show-notification notification)
597 (if play-sound (org-clock-play-sound)))
599 (defun org-show-notification (notification)
600 "Show notification.
601 Use `org-show-notification-handler' if defined,
602 use libnotify if available, or fall back on a message."
603 (cond ((functionp org-show-notification-handler)
604 (funcall org-show-notification-handler notification))
605 ((stringp org-show-notification-handler)
606 (start-process "emacs-timer-notification" nil
607 org-show-notification-handler notification))
608 ((featurep 'notifications)
609 (require 'notifications)
610 (notifications-notify
611 :title "Org-mode message"
612 :body notification
613 ;; FIXME how to link to the Org icon?
614 ;; :app-icon "~/.emacs.d/icons/mail.png"
615 :urgency 'low))
616 ((org-program-exists "notify-send")
617 (start-process "emacs-timer-notification" nil
618 "notify-send" notification))
619 ;; Maybe the handler will send a message, so only use message as
620 ;; a fall back option
621 (t (message "%s" notification))))
623 (defun org-clock-play-sound ()
624 "Play sound as configured by `org-clock-sound'.
625 Use alsa's aplay tool if available."
626 (cond
627 ((not org-clock-sound))
628 ((eq org-clock-sound t) (beep t) (beep t))
629 ((stringp org-clock-sound)
630 (let ((file (expand-file-name org-clock-sound)))
631 (if (file-exists-p file)
632 (if (org-program-exists "aplay")
633 (start-process "org-clock-play-notification" nil
634 "aplay" file)
635 (condition-case nil
636 (play-sound-file file)
637 (error (beep t) (beep t)))))))))
639 (defun org-program-exists (program-name)
640 "Checks whenever we can locate program and launch it."
641 (if (eq system-type 'gnu/linux)
642 (= 0 (call-process "which" nil nil nil program-name))))
644 (defvar org-clock-mode-line-entry nil
645 "Information for the modeline about the running clock.")
647 (defun org-find-open-clocks (file)
648 "Search through the given file and find all open clocks."
649 (let ((buf (or (get-file-buffer file)
650 (find-file-noselect file)))
651 clocks)
652 (with-current-buffer buf
653 (save-excursion
654 (goto-char (point-min))
655 (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
656 (push (cons (copy-marker (match-end 1) t)
657 (org-time-string-to-time (match-string 1))) clocks))))
658 clocks))
660 (defsubst org-is-active-clock (clock)
661 "Return t if CLOCK is the currently active clock."
662 (and (org-clock-is-active)
663 (= org-clock-marker (car clock))))
665 (defmacro org-with-clock-position (clock &rest forms)
666 "Evaluate FORMS with CLOCK as the current active clock."
667 `(with-current-buffer (marker-buffer (car ,clock))
668 (save-excursion
669 (save-restriction
670 (widen)
671 (goto-char (car ,clock))
672 (beginning-of-line)
673 ,@forms))))
675 (put 'org-with-clock-position 'lisp-indent-function 1)
677 (defmacro org-with-clock (clock &rest forms)
678 "Evaluate FORMS with CLOCK as the current active clock.
679 This macro also protects the current active clock from being altered."
680 `(org-with-clock-position ,clock
681 (let ((org-clock-start-time (cdr ,clock))
682 (org-clock-total-time)
683 (org-clock-history)
684 (org-clock-effort)
685 (org-clock-marker (car ,clock))
686 (org-clock-hd-marker (save-excursion
687 (outline-back-to-heading t)
688 (point-marker))))
689 ,@forms)))
691 (put 'org-with-clock 'lisp-indent-function 1)
693 (defsubst org-clock-clock-in (clock &optional resume start-time)
694 "Clock in to the clock located by CLOCK.
695 If necessary, clock-out of the currently active clock."
696 (org-with-clock-position clock
697 (let ((org-clock-in-resume (or resume org-clock-in-resume)))
698 (org-clock-in nil start-time))))
700 (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
701 "Clock out of the clock located by CLOCK."
702 (let ((temp (copy-marker (car clock)
703 (marker-insertion-type (car clock)))))
704 (if (org-is-active-clock clock)
705 (org-clock-out fail-quietly at-time)
706 (org-with-clock clock
707 (org-clock-out fail-quietly at-time)))
708 (setcar clock temp)))
710 (defsubst org-clock-clock-cancel (clock)
711 "Cancel the clock located by CLOCK."
712 (let ((temp (copy-marker (car clock)
713 (marker-insertion-type (car clock)))))
714 (if (org-is-active-clock clock)
715 (org-clock-cancel)
716 (org-with-clock clock
717 (org-clock-cancel)))
718 (setcar clock temp)))
720 (defvar org-clock-clocking-in nil)
721 (defvar org-clock-resolving-clocks nil)
722 (defvar org-clock-resolving-clocks-due-to-idleness nil)
724 (defun org-clock-resolve-clock (clock resolve-to clock-out-time
725 &optional close-p restart-p fail-quietly)
726 "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
727 `CLOCK' is a cons cell of the form (MARKER START-TIME)."
728 (let ((org-clock-resolving-clocks t))
729 (cond
730 ((null resolve-to)
731 (org-clock-clock-cancel clock)
732 (if (and restart-p (not org-clock-clocking-in))
733 (org-clock-clock-in clock)))
735 ((eq resolve-to 'now)
736 (if restart-p
737 (error "RESTART-P is not valid here"))
738 (if (or close-p org-clock-clocking-in)
739 (org-clock-clock-out clock fail-quietly)
740 (unless (org-is-active-clock clock)
741 (org-clock-clock-in clock t))))
743 ((not (time-less-p resolve-to (current-time)))
744 (error "RESOLVE-TO must refer to a time in the past"))
747 (if restart-p
748 (error "RESTART-P is not valid here"))
749 (org-clock-clock-out clock fail-quietly (or clock-out-time
750 resolve-to))
751 (unless org-clock-clocking-in
752 (if close-p
753 (setq org-clock-leftover-time (and (null clock-out-time)
754 resolve-to))
755 (org-clock-clock-in clock nil (and clock-out-time
756 resolve-to))))))))
758 (defun org-clock-jump-to-current-clock (&optional effective-clock)
759 (interactive)
760 (let ((clock (or effective-clock (cons org-clock-marker
761 org-clock-start-time))))
762 (unless (marker-buffer (car clock))
763 (error "No clock is currently running"))
764 (org-with-clock clock (org-clock-goto))
765 (with-current-buffer (marker-buffer (car clock))
766 (goto-char (car clock))
767 (if org-clock-into-drawer
768 (let ((logbook
769 (if (stringp org-clock-into-drawer)
770 (concat ":" org-clock-into-drawer ":")
771 ":LOGBOOK:")))
772 (ignore-errors
773 (outline-flag-region
774 (save-excursion
775 (outline-back-to-heading t)
776 (search-forward logbook)
777 (goto-char (match-beginning 0)))
778 (save-excursion
779 (outline-back-to-heading t)
780 (search-forward logbook)
781 (search-forward ":END:")
782 (goto-char (match-end 0)))
783 nil)))))))
785 (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
786 "Resolve an open org-mode clock.
787 An open clock was found, with `dangling' possibly being non-nil.
788 If this function was invoked with a prefix argument, non-dangling
789 open clocks are ignored. The given clock requires some sort of
790 user intervention to resolve it, either because a clock was left
791 dangling or due to an idle timeout. The clock resolution can
792 either be:
794 (a) deleted, the user doesn't care about the clock
795 (b) restarted from the current time (if no other clock is open)
796 (c) closed, giving the clock X minutes
797 (d) closed and then restarted
798 (e) resumed, as if the user had never left
800 The format of clock is (CONS MARKER START-TIME), where MARKER
801 identifies the buffer and position the clock is open at (and
802 thus, the heading it's under), and START-TIME is when the clock
803 was started."
804 (assert clock)
805 (let* ((ch
806 (save-window-excursion
807 (save-excursion
808 (unless org-clock-resolving-clocks-due-to-idleness
809 (org-clock-jump-to-current-clock clock))
810 (unless org-clock-resolve-expert
811 (with-output-to-temp-buffer "*Org Clock*"
812 (princ "Select a Clock Resolution Command:
814 i/q/C-g Ignore this question; the same as keeping all the idle time.
816 k/K Keep X minutes of the idle time (default is all). If this
817 amount is less than the default, you will be clocked out
818 that many minutes after the time that idling began, and then
819 clocked back in at the present time.
820 g/G Indicate that you \"got back\" X minutes ago. This is quite
821 different from 'k': it clocks you out from the beginning of
822 the idle period and clock you back in X minutes ago.
823 s/S Subtract the idle time from the current clock. This is the
824 same as keeping 0 minutes.
825 C Cancel the open timer altogether. It will be as though you
826 never clocked in.
827 j/J Jump to the current clock, to make manual adjustments.
829 For all these options, using uppercase makes your final state
830 to be CLOCKED OUT.")))
831 (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
832 (let (char-pressed)
833 (when (featurep 'xemacs)
834 (message (concat (funcall prompt-fn clock)
835 " [jkKgGsScCiq]? "))
836 (setq char-pressed (read-char-exclusive)))
837 (while (or (null char-pressed)
838 (and (not (memq char-pressed
839 '(?k ?K ?g ?G ?s ?S ?C
840 ?j ?J ?i ?q)))
841 (or (ding) t)))
842 (setq char-pressed
843 (read-char (concat (funcall prompt-fn clock)
844 " [jkKgGSscCiq]? ")
845 nil 45)))
846 (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
847 (default
848 (floor (/ (org-float-time
849 (time-subtract (current-time) last-valid)) 60)))
850 (keep
851 (and (memq ch '(?k ?K))
852 (read-number "Keep how many minutes? " default)))
853 (gotback
854 (and (memq ch '(?g ?G))
855 (read-number "Got back how many minutes ago? " default)))
856 (subtractp (memq ch '(?s ?S)))
857 (barely-started-p (< (- (org-float-time last-valid)
858 (org-float-time (cdr clock))) 45))
859 (start-over (and subtractp barely-started-p)))
860 (cond
861 ((memq ch '(?j ?J))
862 (if (eq ch ?J)
863 (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
864 (org-clock-jump-to-current-clock clock))
865 ((or (null ch)
866 (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
867 (message ""))
869 (org-clock-resolve-clock
870 clock (cond
871 ((or (eq ch ?C)
872 ;; If the time on the clock was less than a minute before
873 ;; the user went away, and they've ask to subtract all the
874 ;; time...
875 start-over)
876 nil)
877 ((or subtractp
878 (and gotback (= gotback 0)))
879 last-valid)
880 ((or (and keep (= keep default))
881 (and gotback (= gotback default)))
882 'now)
883 (keep
884 (time-add last-valid (seconds-to-time (* 60 keep))))
885 (gotback
886 (time-subtract (current-time)
887 (seconds-to-time (* 60 gotback))))
889 (error "Unexpected, please report this as a bug")))
890 (and gotback last-valid)
891 (memq ch '(?K ?G ?S))
892 (and start-over
893 (not (memq ch '(?K ?G ?S ?C))))
894 fail-quietly)))))
896 (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
897 "Resolve all currently open org-mode clocks.
898 If `only-dangling-p' is non-nil, only ask to resolve dangling
899 \(i.e., not currently open and valid) clocks."
900 (interactive "P")
901 (unless org-clock-resolving-clocks
902 (let ((org-clock-resolving-clocks t))
903 (dolist (file (org-files-list))
904 (let ((clocks (org-find-open-clocks file)))
905 (dolist (clock clocks)
906 (let ((dangling (or (not (org-clock-is-active))
907 (/= (car clock) org-clock-marker))))
908 (if (or (not only-dangling-p) dangling)
909 (org-clock-resolve
910 clock
911 (or prompt-fn
912 (function
913 (lambda (clock)
914 (format
915 "Dangling clock started %d mins ago"
916 (floor
917 (/ (- (org-float-time (current-time))
918 (org-float-time (cdr clock))) 60))))))
919 (or last-valid
920 (cdr clock)))))))))))
922 (defun org-emacs-idle-seconds ()
923 "Return the current Emacs idle time in seconds, or nil if not idle."
924 (let ((idle-time (current-idle-time)))
925 (if idle-time
926 (org-float-time idle-time)
927 0)))
929 (defun org-mac-idle-seconds ()
930 "Return the current Mac idle time in seconds."
931 (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
933 (defun org-x11-idle-seconds ()
934 "Return the current X11 idle time in seconds."
935 (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
937 (defun org-user-idle-seconds ()
938 "Return the number of seconds the user has been idle for.
939 This routine returns a floating point number."
940 (cond
941 ((eq system-type 'darwin)
942 (org-mac-idle-seconds))
943 ((eq window-system 'x)
944 (org-x11-idle-seconds))
946 (org-emacs-idle-seconds))))
948 (defvar org-clock-user-idle-seconds)
950 (defun org-resolve-clocks-if-idle ()
951 "Resolve all currently open org-mode clocks.
952 This is performed after `org-clock-idle-time' minutes, to check
953 if the user really wants to stay clocked in after being idle for
954 so long."
955 (when (and org-clock-idle-time (not org-clock-resolving-clocks)
956 org-clock-marker)
957 (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
958 (org-clock-user-idle-start
959 (time-subtract (current-time)
960 (seconds-to-time org-clock-user-idle-seconds)))
961 (org-clock-resolving-clocks-due-to-idleness t))
962 (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
963 (org-clock-resolve
964 (cons org-clock-marker
965 org-clock-start-time)
966 (function
967 (lambda (clock)
968 (format "Clocked in & idle for %.1f mins"
969 (/ (org-float-time
970 (time-subtract (current-time)
971 org-clock-user-idle-start))
972 60.0))))
973 org-clock-user-idle-start)))))
975 (defun org-clock-in (&optional select start-time)
976 "Start the clock on the current item.
977 If necessary, clock-out of the currently active clock.
978 With a prefix argument SELECT (\\[universal-argument]), offer a list of \
979 recently clocked tasks to
980 clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
981 clock into the current task and mark
982 is as the default task, a special task that will always be offered in
983 the clocking selection, associated with the letter `d'."
984 (interactive "P")
985 (setq org-clock-notification-was-shown nil)
986 (catch 'abort
987 (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
988 (org-clocking-p)))
989 ts selected-task target-pos (msg-extra "")
990 (leftover (and (not org-clock-resolving-clocks)
991 org-clock-leftover-time)))
992 (when (and org-clock-auto-clock-resolution
993 (or (not interrupting)
994 (eq t org-clock-auto-clock-resolution))
995 (not org-clock-clocking-in)
996 (not org-clock-resolving-clocks))
997 (setq org-clock-leftover-time nil)
998 (let ((org-clock-clocking-in t))
999 (org-resolve-clocks))) ; check if any clocks are dangling
1000 (when (equal select '(4))
1001 (setq selected-task (org-clock-select-task "Clock-in on task: "))
1002 (if selected-task
1003 (setq selected-task (copy-marker selected-task))
1004 (error "Abort")))
1005 (when interrupting
1006 ;; We are interrupting the clocking of a different task.
1007 ;; Save a marker to this task, so that we can go back.
1008 ;; First check if we are trying to clock into the same task!
1009 (when (save-excursion
1010 (unless selected-task
1011 (org-back-to-heading t))
1012 (and (equal (marker-buffer org-clock-hd-marker)
1013 (if selected-task
1014 (marker-buffer selected-task)
1015 (current-buffer)))
1016 (= (marker-position org-clock-hd-marker)
1017 (if selected-task
1018 (marker-position selected-task)
1019 (point)))))
1020 (message "Clock continues in \"%s\"" org-clock-heading)
1021 (throw 'abort nil))
1022 (move-marker org-clock-interrupted-task
1023 (marker-position org-clock-marker)
1024 (marker-buffer org-clock-marker))
1025 (let ((org-clock-clocking-in t))
1026 (org-clock-out t)))
1028 (when (equal select '(16))
1029 ;; Mark as default clocking task
1030 (org-clock-mark-default-task))
1032 ;; Clock in at which position?
1033 (setq target-pos
1034 (if (and (eobp) (not (org-on-heading-p)))
1035 (point-at-bol 0)
1036 (point)))
1037 (run-hooks 'org-clock-in-prepare-hook)
1038 (save-excursion
1039 (when (and selected-task (marker-buffer selected-task))
1040 ;; There is a selected task, move to the correct buffer
1041 ;; and set the new target position.
1042 (set-buffer (org-base-buffer (marker-buffer selected-task)))
1043 (setq target-pos (marker-position selected-task))
1044 (move-marker selected-task nil))
1045 (save-excursion
1046 (save-restriction
1047 (widen)
1048 (goto-char target-pos)
1049 (org-back-to-heading t)
1050 (or interrupting (move-marker org-clock-interrupted-task nil))
1051 (org-clock-history-push)
1052 (org-clock-set-current)
1053 (cond ((functionp org-clock-in-switch-to-state)
1054 (looking-at org-complex-heading-regexp)
1055 (let ((newstate (funcall org-clock-in-switch-to-state
1056 (match-string 2))))
1057 (if newstate (org-todo newstate))))
1058 ((and org-clock-in-switch-to-state
1059 (not (looking-at (concat outline-regexp "[ \t]*"
1060 org-clock-in-switch-to-state
1061 "\\>"))))
1062 (org-todo org-clock-in-switch-to-state)))
1063 (setq org-clock-heading-for-remember
1064 (and (looking-at org-complex-heading-regexp)
1065 (match-end 4)
1066 (org-trim (buffer-substring (match-end 1)
1067 (match-end 4)))))
1068 (setq org-clock-heading
1069 (cond ((and org-clock-heading-function
1070 (functionp org-clock-heading-function))
1071 (funcall org-clock-heading-function))
1072 ((looking-at org-complex-heading-regexp)
1073 (replace-regexp-in-string
1074 "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
1075 (match-string 4)))
1076 (t "???")))
1077 (setq org-clock-heading (org-propertize org-clock-heading
1078 'face nil))
1079 (org-clock-find-position org-clock-in-resume)
1080 (cond
1081 ((and org-clock-in-resume
1082 (looking-at
1083 (concat "^[ \t]* " org-clock-string
1084 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1085 " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1086 (message "Matched %s" (match-string 1))
1087 (setq ts (concat "[" (match-string 1) "]"))
1088 (goto-char (match-end 1))
1089 (setq org-clock-start-time
1090 (apply 'encode-time
1091 (org-parse-time-string (match-string 1))))
1092 (setq org-clock-effort (org-get-effort))
1093 (setq org-clock-total-time (org-clock-sum-current-item
1094 (org-clock-get-sum-start))))
1095 ((eq org-clock-in-resume 'auto-restart)
1096 ;; called from org-clock-load during startup,
1097 ;; do not interrupt, but warn!
1098 (message "Cannot restart clock because task does not contain unfinished clock")
1099 (ding)
1100 (sit-for 2)
1101 (throw 'abort nil))
1103 (insert-before-markers "\n")
1104 (backward-char 1)
1105 (org-indent-line-function)
1106 (when (and (save-excursion
1107 (end-of-line 0)
1108 (org-in-item-p)))
1109 (beginning-of-line 1)
1110 (org-indent-line-to (- (org-get-indentation) 2)))
1111 (insert org-clock-string " ")
1112 (setq org-clock-effort (org-get-effort))
1113 (setq org-clock-total-time (org-clock-sum-current-item
1114 (org-clock-get-sum-start)))
1115 (setq org-clock-start-time
1116 (or (and leftover
1117 (y-or-n-p
1118 (format
1119 "You stopped another clock %d mins ago; start this one from then? "
1120 (/ (- (org-float-time (current-time))
1121 (org-float-time leftover)) 60)))
1122 leftover)
1123 start-time
1124 (current-time)))
1125 (setq ts (org-insert-time-stamp org-clock-start-time
1126 'with-hm 'inactive))))
1127 (move-marker org-clock-marker (point) (buffer-base-buffer))
1128 (move-marker org-clock-hd-marker
1129 (save-excursion (org-back-to-heading t) (point))
1130 (buffer-base-buffer))
1131 (setq org-clock-has-been-used t)
1132 (or global-mode-string (setq global-mode-string '("")))
1133 (or (memq 'org-mode-line-string global-mode-string)
1134 (setq global-mode-string
1135 (append global-mode-string '(org-mode-line-string))))
1136 (org-clock-update-mode-line)
1137 (when org-clock-mode-line-timer
1138 (cancel-timer org-clock-mode-line-timer)
1139 (setq org-clock-mode-line-timer nil))
1140 (setq org-clock-mode-line-timer
1141 (run-with-timer org-clock-update-period
1142 org-clock-update-period
1143 'org-clock-update-mode-line))
1144 (when org-clock-idle-timer
1145 (cancel-timer org-clock-idle-timer)
1146 (setq org-clock-idle-timer nil))
1147 (setq org-clock-idle-timer
1148 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1149 (message "Clock starts at %s - %s" ts msg-extra)
1150 (run-hooks 'org-clock-in-hook)))))))
1152 (defvar org-clock-current-task nil
1153 "Task currently clocked in.")
1154 (defun org-clock-set-current ()
1155 "Set `org-clock-current-task' to the task currently clocked in."
1156 (setq org-clock-current-task (nth 4 (org-heading-components))))
1158 (defun org-clock-delete-current ()
1159 "Reset `org-clock-current-task' to nil."
1160 (setq org-clock-current-task nil))
1162 (defun org-clock-mark-default-task ()
1163 "Mark current task as default task."
1164 (interactive)
1165 (save-excursion
1166 (org-back-to-heading t)
1167 (move-marker org-clock-default-task (point))))
1169 (defvar msg-extra)
1170 (defun org-clock-get-sum-start ()
1171 "Return the time from which clock times should be counted.
1172 This is for the currently running clock as it is displayed
1173 in the mode line. This function looks at the properties
1174 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1175 corresponding variable `org-clock-modeline-total' and then
1176 decides which time to use."
1177 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1178 (symbol-name org-clock-modeline-total)))
1179 (lr (org-entry-get nil "LAST_REPEAT")))
1180 (cond
1181 ((equal cmt "current")
1182 (setq msg-extra "showing time in current clock instance")
1183 (current-time))
1184 ((equal cmt "today")
1185 (setq msg-extra "showing today's task time.")
1186 (let* ((dt (decode-time (current-time))))
1187 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1188 (if org-extend-today-until
1189 (setf (nth 2 dt) org-extend-today-until))
1190 (apply 'encode-time dt)))
1191 ((or (equal cmt "all")
1192 (and (or (not cmt) (equal cmt "auto"))
1193 (not lr)))
1194 (setq msg-extra "showing entire task time.")
1195 nil)
1196 ((or (equal cmt "repeat")
1197 (and (or (not cmt) (equal cmt "auto"))
1198 lr))
1199 (setq msg-extra "showing task time since last repeat.")
1200 (if (not lr)
1202 (org-time-string-to-time lr)))
1203 (t nil))))
1205 (defun org-clock-find-position (find-unclosed)
1206 "Find the location where the next clock line should be inserted.
1207 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1208 line and position cursor in that line."
1209 (org-back-to-heading t)
1210 (catch 'exit
1211 (let ((beg (save-excursion
1212 (beginning-of-line 2)
1213 (or (bolp) (newline))
1214 (point)))
1215 (end (progn (outline-next-heading) (point)))
1216 (re (concat "^[ \t]*" org-clock-string))
1217 (cnt 0)
1218 (drawer (if (stringp org-clock-into-drawer)
1219 org-clock-into-drawer "LOGBOOK"))
1220 first last ind-last)
1221 (goto-char beg)
1222 (when (and find-unclosed
1223 (re-search-forward
1224 (concat "^[ \t]* " org-clock-string
1225 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1226 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1227 end t))
1228 (beginning-of-line 1)
1229 (throw 'exit t))
1230 (when (eobp) (newline) (setq end (max (point) end)))
1231 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1232 ;; we seem to have a CLOCK drawer, so go there.
1233 (beginning-of-line 2)
1234 (or org-log-states-order-reversed
1235 (and (re-search-forward org-property-end-re nil t)
1236 (goto-char (match-beginning 0))))
1237 (throw 'exit t))
1238 ;; Lets count the CLOCK lines
1239 (goto-char beg)
1240 (while (re-search-forward re end t)
1241 (setq first (or first (match-beginning 0))
1242 last (match-beginning 0)
1243 cnt (1+ cnt)))
1244 (when (and (integerp org-clock-into-drawer)
1245 last
1246 (>= (1+ cnt) org-clock-into-drawer))
1247 ;; Wrap current entries into a new drawer
1248 (goto-char last)
1249 (setq ind-last (org-get-indentation))
1250 (beginning-of-line 2)
1251 (if (and (>= (org-get-indentation) ind-last)
1252 (org-at-item-p))
1253 (org-end-of-item))
1254 (insert ":END:\n")
1255 (beginning-of-line 0)
1256 (org-indent-line-to ind-last)
1257 (goto-char first)
1258 (insert ":" drawer ":\n")
1259 (beginning-of-line 0)
1260 (org-indent-line-function)
1261 (org-flag-drawer t)
1262 (beginning-of-line 2)
1263 (or org-log-states-order-reversed
1264 (and (re-search-forward org-property-end-re nil t)
1265 (goto-char (match-beginning 0))))
1266 (throw 'exit nil))
1268 (goto-char beg)
1269 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1270 (not (equal (match-string 1) org-clock-string)))
1271 ;; Planning info, skip to after it
1272 (beginning-of-line 2)
1273 (or (bolp) (newline)))
1274 (when (or (eq org-clock-into-drawer t)
1275 (stringp org-clock-into-drawer)
1276 (and (integerp org-clock-into-drawer)
1277 (< org-clock-into-drawer 2)))
1278 (insert ":" drawer ":\n:END:\n")
1279 (beginning-of-line -1)
1280 (org-indent-line-function)
1281 (org-flag-drawer t)
1282 (beginning-of-line 2)
1283 (org-indent-line-function)
1284 (beginning-of-line)
1285 (or org-log-states-order-reversed
1286 (and (re-search-forward org-property-end-re nil t)
1287 (goto-char (match-beginning 0))))))))
1289 (defun org-clock-out (&optional fail-quietly at-time)
1290 "Stop the currently running clock.
1291 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1292 (interactive)
1293 (catch 'exit
1294 (when (not (org-clocking-p))
1295 (setq global-mode-string
1296 (delq 'org-mode-line-string global-mode-string))
1297 (force-mode-line-update)
1298 (if fail-quietly (throw 'exit t) (error "No active clock")))
1299 (let (ts te s h m remove)
1300 (save-excursion ; Do not replace this with `with-current-buffer'.
1301 (with-no-warnings (set-buffer (org-clocking-buffer)))
1302 (save-restriction
1303 (widen)
1304 (goto-char org-clock-marker)
1305 (beginning-of-line 1)
1306 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1307 (equal (match-string 1) org-clock-string))
1308 (setq ts (match-string 2))
1309 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1310 (goto-char (match-end 0))
1311 (delete-region (point) (point-at-eol))
1312 (insert "--")
1313 (setq te (org-insert-time-stamp (or at-time (current-time))
1314 'with-hm 'inactive))
1315 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1316 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1317 h (floor (/ s 3600))
1318 s (- s (* 3600 h))
1319 m (floor (/ s 60))
1320 s (- s (* 60 s)))
1321 (insert " => " (format "%2d:%02d" h m))
1322 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1323 (= (+ h m) 0)))
1324 (beginning-of-line 1)
1325 (delete-region (point) (point-at-eol))
1326 (and (looking-at "\n") (> (point-max) (1+ (point)))
1327 (delete-char 1)))
1328 (move-marker org-clock-marker nil)
1329 (move-marker org-clock-hd-marker nil)
1330 (when org-log-note-clock-out
1331 (org-add-log-setup 'clock-out nil nil nil nil
1332 (concat "# Task: " (org-get-heading t) "\n\n")))
1333 (when org-clock-mode-line-timer
1334 (cancel-timer org-clock-mode-line-timer)
1335 (setq org-clock-mode-line-timer nil))
1336 (when org-clock-idle-timer
1337 (cancel-timer org-clock-idle-timer)
1338 (setq org-clock-idle-timer nil))
1339 (setq global-mode-string
1340 (delq 'org-mode-line-string global-mode-string))
1341 (when org-clock-out-switch-to-state
1342 (save-excursion
1343 (org-back-to-heading t)
1344 (let ((org-inhibit-logging t)
1345 (org-clock-out-when-done nil))
1346 (cond
1347 ((functionp org-clock-out-switch-to-state)
1348 (looking-at org-complex-heading-regexp)
1349 (let ((newstate (funcall org-clock-out-switch-to-state
1350 (match-string 2))))
1351 (if newstate (org-todo newstate))))
1352 ((and org-clock-out-switch-to-state
1353 (not (looking-at (concat outline-regexp "[ \t]*"
1354 org-clock-out-switch-to-state
1355 "\\>"))))
1356 (org-todo org-clock-out-switch-to-state))))))
1357 (force-mode-line-update)
1358 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1359 (if remove " => LINE REMOVED" ""))
1360 (run-hooks 'org-clock-out-hook)
1361 (org-clock-delete-current))))))
1363 (defun org-clock-cancel ()
1364 "Cancel the running clock by removing the start timestamp."
1365 (interactive)
1366 (when (not (org-clocking-p))
1367 (setq global-mode-string
1368 (delq 'org-mode-line-string global-mode-string))
1369 (force-mode-line-update)
1370 (error "No active clock"))
1371 (save-excursion ; Do not replace this with `with-current-buffer'.
1372 (with-no-warnings (set-buffer (org-clocking-buffer)))
1373 (goto-char org-clock-marker)
1374 (delete-region (1- (point-at-bol)) (point-at-eol))
1375 ;; Just in case, remove any empty LOGBOOK left over
1376 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1377 (move-marker org-clock-marker nil)
1378 (move-marker org-clock-hd-marker nil)
1379 (setq global-mode-string
1380 (delq 'org-mode-line-string global-mode-string))
1381 (force-mode-line-update)
1382 (message "Clock canceled")
1383 (run-hooks 'org-clock-cancel-hook))
1385 (defun org-clock-goto (&optional select)
1386 "Go to the currently clocked-in entry, or to the most recently clocked one.
1387 With prefix arg SELECT, offer recently clocked tasks for selection."
1388 (interactive "@P")
1389 (let* ((recent nil)
1390 (m (cond
1391 (select
1392 (or (org-clock-select-task "Select task to go to: ")
1393 (error "No task selected")))
1394 ((org-clocking-p) org-clock-marker)
1395 ((and org-clock-goto-may-find-recent-task
1396 (car org-clock-history)
1397 (marker-buffer (car org-clock-history)))
1398 (setq recent t)
1399 (car org-clock-history))
1400 (t (error "No active or recent clock task")))))
1401 (switch-to-buffer (marker-buffer m))
1402 (if (or (< m (point-min)) (> m (point-max))) (widen))
1403 (goto-char m)
1404 (org-show-entry)
1405 (org-back-to-heading t)
1406 (org-cycle-hide-drawers 'children)
1407 (recenter)
1408 (org-reveal)
1409 (if recent
1410 (message "No running clock, this is the most recently clocked task"))
1411 (run-hooks 'org-clock-goto-hook)))
1413 (defvar org-clock-file-total-minutes nil
1414 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1415 (make-variable-buffer-local 'org-clock-file-total-minutes)
1417 (defun org-clock-sum (&optional tstart tend headline-filter)
1418 "Sum the times for each subtree.
1419 Puts the resulting times in minutes as a text property on each headline.
1420 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1421 zero-arg function that, if specified, is called for each headline in the time
1422 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1423 nil are excluded from the clock summation."
1424 (interactive)
1425 (let* ((bmp (buffer-modified-p))
1426 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1427 org-clock-string
1428 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1429 (lmax 30)
1430 (ltimes (make-vector lmax 0))
1431 (t1 0)
1432 (level 0)
1433 ts te dt
1434 time)
1435 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1436 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1437 (if (consp tstart) (setq tstart (org-float-time tstart)))
1438 (if (consp tend) (setq tend (org-float-time tend)))
1439 (remove-text-properties (point-min) (point-max)
1440 '(:org-clock-minutes t
1441 :org-clock-force-headline-inclusion t))
1442 (save-excursion
1443 (goto-char (point-max))
1444 (while (re-search-backward re nil t)
1445 (cond
1446 ((match-end 2)
1447 ;; Two time stamps
1448 (setq ts (match-string 2)
1449 te (match-string 3)
1450 ts (org-float-time
1451 (apply 'encode-time (org-parse-time-string ts)))
1452 te (org-float-time
1453 (apply 'encode-time (org-parse-time-string te)))
1454 ts (if tstart (max ts tstart) ts)
1455 te (if tend (min te tend) te)
1456 dt (- te ts)
1457 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1458 ((match-end 4)
1459 ;; A naked time
1460 (setq t1 (+ t1 (string-to-number (match-string 5))
1461 (* 60 (string-to-number (match-string 4))))))
1462 (t ;; A headline
1463 ;; Add the currently clocking item time to the total
1464 (when (and org-clock-report-include-clocking-task
1465 (equal (org-clocking-buffer) (current-buffer))
1466 (equal (marker-position org-clock-hd-marker) (point))
1467 tstart
1468 tend
1469 (>= (org-float-time org-clock-start-time) tstart)
1470 (<= (org-float-time org-clock-start-time) tend))
1471 (let ((time (floor (- (org-float-time)
1472 (org-float-time org-clock-start-time)) 60)))
1473 (setq t1 (+ t1 time))))
1474 (let* ((headline-forced
1475 (get-text-property (point)
1476 :org-clock-force-headline-inclusion))
1477 (headline-included
1478 (or (null headline-filter)
1479 (save-excursion
1480 (save-match-data (funcall headline-filter))))))
1481 (setq level (- (match-end 1) (match-beginning 1)))
1482 (when (or (> t1 0) (> (aref ltimes level) 0))
1483 (when (or headline-included headline-forced)
1484 (if headline-included
1485 (loop for l from 0 to level do
1486 (aset ltimes l (+ (aref ltimes l) t1))))
1487 (setq time (aref ltimes level))
1488 (goto-char (match-beginning 0))
1489 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1490 (if headline-filter
1491 (save-excursion
1492 (save-match-data
1493 (while
1494 (> (funcall outline-level) 1)
1495 (outline-up-heading 1 t)
1496 (put-text-property
1497 (point) (point-at-eol)
1498 :org-clock-force-headline-inclusion t))))))
1499 (setq t1 0)
1500 (loop for l from level to (1- lmax) do
1501 (aset ltimes l 0)))))))
1502 (setq org-clock-file-total-minutes (aref ltimes 0)))
1503 (set-buffer-modified-p bmp)))
1505 (defun org-clock-sum-current-item (&optional tstart)
1506 "Return time, clocked on current item in total."
1507 (save-excursion
1508 (save-restriction
1509 (org-narrow-to-subtree)
1510 (org-clock-sum tstart)
1511 org-clock-file-total-minutes)))
1513 (defun org-clock-display (&optional total-only)
1514 "Show subtree times in the entire buffer.
1515 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1516 in the echo area."
1517 (interactive)
1518 (org-clock-remove-overlays)
1519 (let (time h m p)
1520 (org-clock-sum)
1521 (unless total-only
1522 (save-excursion
1523 (goto-char (point-min))
1524 (while (or (and (equal (setq p (point)) (point-min))
1525 (get-text-property p :org-clock-minutes))
1526 (setq p (next-single-property-change
1527 (point) :org-clock-minutes)))
1528 (goto-char p)
1529 (when (setq time (get-text-property p :org-clock-minutes))
1530 (org-clock-put-overlay time (funcall outline-level))))
1531 (setq h (/ org-clock-file-total-minutes 60)
1532 m (- org-clock-file-total-minutes (* 60 h)))
1533 ;; Arrange to remove the overlays upon next change.
1534 (when org-remove-highlights-with-change
1535 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1536 nil 'local))))
1537 (if org-time-clocksum-use-fractional
1538 (message (concat "Total file time: " org-time-clocksum-fractional-format
1539 " (%d hours and %d minutes)")
1540 (/ (+ (* h 60.0) m) 60.0) h m)
1541 (message (concat "Total file time: " org-time-clocksum-format
1542 " (%d hours and %d minutes)") h m h m))))
1544 (defvar org-clock-overlays nil)
1545 (make-variable-buffer-local 'org-clock-overlays)
1547 (defun org-clock-put-overlay (time &optional level)
1548 "Put an overlays on the current line, displaying TIME.
1549 If LEVEL is given, prefix time with a corresponding number of stars.
1550 This creates a new overlay and stores it in `org-clock-overlays', so that it
1551 will be easy to remove."
1552 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1553 (l (if level (org-get-valid-level level 0) 0))
1554 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1555 org-time-clocksum-fractional-format
1556 org-time-clocksum-format) "%s"))
1557 (off 0)
1558 ov tx)
1559 (org-move-to-column c)
1560 (unless (eolp) (skip-chars-backward "^ \t"))
1561 (skip-chars-backward " \t")
1562 (setq ov (make-overlay (1- (point)) (point-at-eol))
1563 tx (concat (buffer-substring (1- (point)) (point))
1564 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1565 (org-add-props (if org-time-clocksum-use-fractional
1566 (format fmt
1567 (make-string l ?*)
1568 (/ (+ (* h 60.0) m) 60.0)
1569 (make-string (- 16 l) ?\ ))
1570 (format fmt
1571 (make-string l ?*) h m
1572 (make-string (- 16 l) ?\ )))
1573 (list 'face 'org-clock-overlay))
1574 ""))
1575 (if (not (featurep 'xemacs))
1576 (overlay-put ov 'display tx)
1577 (overlay-put ov 'invisible t)
1578 (overlay-put ov 'end-glyph (make-glyph tx)))
1579 (push ov org-clock-overlays)))
1581 (defun org-clock-remove-overlays (&optional beg end noremove)
1582 "Remove the occur highlights from the buffer.
1583 BEG and END are ignored. If NOREMOVE is nil, remove this function
1584 from the `before-change-functions' in the current buffer."
1585 (interactive)
1586 (unless org-inhibit-highlight-removal
1587 (mapc 'delete-overlay org-clock-overlays)
1588 (setq org-clock-overlays nil)
1589 (unless noremove
1590 (remove-hook 'before-change-functions
1591 'org-clock-remove-overlays 'local))))
1593 (defvar state) ;; dynamically scoped into this function
1594 (defun org-clock-out-if-current ()
1595 "Clock out if the current entry contains the running clock.
1596 This is used to stop the clock after a TODO entry is marked DONE,
1597 and is only done if the variable `org-clock-out-when-done' is not nil."
1598 (when (and org-clock-out-when-done
1599 (or (and (eq t org-clock-out-when-done)
1600 (member state org-done-keywords))
1601 (and (listp org-clock-out-when-done)
1602 (member state org-clock-out-when-done)))
1603 (equal (or (buffer-base-buffer (org-clocking-buffer))
1604 (org-clocking-buffer))
1605 (or (buffer-base-buffer (current-buffer))
1606 (current-buffer)))
1607 (< (point) org-clock-marker)
1608 (> (save-excursion (outline-next-heading) (point))
1609 org-clock-marker))
1610 ;; Clock out, but don't accept a logging message for this.
1611 (let ((org-log-note-clock-out nil)
1612 (org-clock-out-switch-to-state nil))
1613 (org-clock-out))))
1615 (add-hook 'org-after-todo-state-change-hook
1616 'org-clock-out-if-current)
1618 ;;;###autoload
1619 (defun org-get-clocktable (&rest props)
1620 "Get a formatted clocktable with parameters according to PROPS.
1621 The table is created in a temporary buffer, fully formatted and
1622 fontified, and then returned."
1623 ;; Set the defaults
1624 (setq props (plist-put props :name "clocktable"))
1625 (unless (plist-member props :maxlevel)
1626 (setq props (plist-put props :maxlevel 2)))
1627 (unless (plist-member props :scope)
1628 (setq props (plist-put props :scope 'agenda)))
1629 (with-temp-buffer
1630 (org-mode)
1631 (org-create-dblock props)
1632 (org-update-dblock)
1633 (font-lock-fontify-buffer)
1634 (forward-line 2)
1635 (buffer-substring (point) (progn
1636 (re-search-forward "^[ \t]*#\\+END" nil t)
1637 (point-at-bol)))))
1639 (defun org-clock-report (&optional arg)
1640 "Create a table containing a report about clocked time.
1641 If the cursor is inside an existing clocktable block, then the table
1642 will be updated. If not, a new clocktable will be inserted.
1643 When called with a prefix argument, move to the first clock table in the
1644 buffer and update it."
1645 (interactive "P")
1646 (org-clock-remove-overlays)
1647 (when arg
1648 (org-find-dblock "clocktable")
1649 (org-show-entry))
1650 (if (org-in-clocktable-p)
1651 (goto-char (org-in-clocktable-p))
1652 (org-create-dblock (append (list :name "clocktable")
1653 org-clock-clocktable-default-properties)))
1654 (org-update-dblock))
1656 (defun org-in-clocktable-p ()
1657 "Check if the cursor is in a clocktable."
1658 (let ((pos (point)) start)
1659 (save-excursion
1660 (end-of-line 1)
1661 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
1662 (setq start (match-beginning 0))
1663 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
1664 (>= (match-end 0) pos)
1665 start))))
1667 (defun org-day-of-week (day month year)
1668 "Returns the day of the week as an integer."
1669 (nth 6
1670 (decode-time
1671 (date-to-time
1672 (format "%d-%02d-%02dT00:00:00" year month day)))))
1674 (defun org-quarter-to-date (quarter year)
1675 "Get the date (week day year) of the first day of a given quarter."
1676 (let (startday)
1677 (cond
1678 ((= quarter 1)
1679 (setq startday (org-day-of-week 1 1 year))
1680 (cond
1681 ((= startday 0)
1682 (list 52 7 (- year 1)))
1683 ((= startday 6)
1684 (list 52 6 (- year 1)))
1685 ((<= startday 4)
1686 (list 1 startday year))
1687 ((> startday 4)
1688 (list 53 startday (- year 1)))
1691 ((= quarter 2)
1692 (setq startday (org-day-of-week 1 4 year))
1693 (cond
1694 ((= startday 0)
1695 (list 13 startday year))
1696 ((< startday 4)
1697 (list 14 startday year))
1698 ((>= startday 4)
1699 (list 13 startday year))
1702 ((= quarter 3)
1703 (setq startday (org-day-of-week 1 7 year))
1704 (cond
1705 ((= startday 0)
1706 (list 26 startday year))
1707 ((< startday 4)
1708 (list 27 startday year))
1709 ((>= startday 4)
1710 (list 26 startday year))
1713 ((= quarter 4)
1714 (setq startday (org-day-of-week 1 10 year))
1715 (cond
1716 ((= startday 0)
1717 (list 39 startday year))
1718 ((<= startday 4)
1719 (list 40 startday year))
1720 ((> startday 4)
1721 (list 39 startday year)))))))
1723 (defun org-clock-special-range (key &optional time as-strings)
1724 "Return two times bordering a special time range.
1725 Key is a symbol specifying the range and can be one of `today', `yesterday',
1726 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1727 A week starts Monday 0:00 and ends Sunday 24:00.
1728 The range is determined relative to TIME. TIME defaults to the current time.
1729 The return value is a cons cell with two internal times like the ones
1730 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1731 the returned times will be formatted strings."
1732 (if (integerp key) (setq key (intern (number-to-string key))))
1733 (let* ((tm (decode-time (or time (current-time))))
1734 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1735 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1736 (dow (nth 6 tm))
1737 (skey (symbol-name key))
1738 (shift 0)
1739 (q (cond ((>= (nth 4 tm) 10) 4)
1740 ((>= (nth 4 tm) 7) 3)
1741 ((>= (nth 4 tm) 4) 2)
1742 ((>= (nth 4 tm) 1) 1)))
1743 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1744 interval tmp shiftedy shiftedm shiftedq)
1745 (cond
1746 ((string-match "^[0-9]+$" skey)
1747 (setq y (string-to-number skey) m 1 d 1 key 'year))
1748 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1749 (setq y (string-to-number (match-string 1 skey))
1750 month (string-to-number (match-string 2 skey))
1751 d 1 key 'month))
1752 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1753 (require 'cal-iso)
1754 (setq y (string-to-number (match-string 1 skey))
1755 w (string-to-number (match-string 2 skey)))
1756 (setq date (calendar-gregorian-from-absolute
1757 (calendar-absolute-from-iso (list w 1 y))))
1758 (setq d (nth 1 date) month (car date) y (nth 2 date)
1759 dow 1
1760 key 'week))
1761 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
1762 (require 'cal-iso)
1763 (setq y (string-to-number (match-string 1 skey)))
1764 (setq q (string-to-number (match-string 2 skey)))
1765 (setq date (calendar-gregorian-from-absolute
1766 (calendar-absolute-from-iso (org-quarter-to-date q y))))
1767 (setq d (nth 1 date) month (car date) y (nth 2 date)
1768 dow 1
1769 key 'quarter))
1770 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1771 (setq y (string-to-number (match-string 1 skey))
1772 month (string-to-number (match-string 2 skey))
1773 d (string-to-number (match-string 3 skey))
1774 key 'day))
1775 ((string-match "\\([-+][0-9]+\\)$" skey)
1776 (setq shift (string-to-number (match-string 1 skey))
1777 key (intern (substring skey 0 (match-beginning 1))))
1778 (if(and (memq key '(quarter thisq)) (> shift 0))
1779 (error "Looking forward with quarters isn't implemented.")
1780 ())))
1782 (when (= shift 0)
1783 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1784 ((eq key 'lastweek) (setq key 'week shift -1))
1785 ((eq key 'lastmonth) (setq key 'month shift -1))
1786 ((eq key 'lastyear) (setq key 'year shift -1))
1787 ((eq key 'lastq) (setq key 'quarter shift -1))))
1788 (cond
1789 ((memq key '(day today))
1790 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1791 ((memq key '(week thisweek))
1792 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1793 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1794 ((memq key '(month thismonth))
1795 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1796 ((memq key '(quarter thisq))
1797 ; compute if this shift remains in this year
1798 ; if not, compute how many years and quarters we have to shift (via floor*)
1799 ; and compute the shifted years, months and quarters
1800 (cond
1801 ((< (+ (- q 1) shift) 0) ; shift not in this year
1802 (setq interval (* -1 (+ (- q 1) shift)))
1803 ; set tmp to ((years to shift) (quarters to shift))
1804 (setq tmp (org-floor* interval 4))
1805 ; due to the use of floor, 0 quarters actually means 4
1806 (if (= 0 (nth 1 tmp))
1807 (setq shiftedy (- y (nth 0 tmp))
1808 shiftedm 1
1809 shiftedq 1)
1810 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
1811 shiftedm (- 13 (* 3 (nth 1 tmp)))
1812 shiftedq (- 5 (nth 1 tmp))))
1813 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
1814 ((> (+ q shift) 0) ; shift is whitin this year
1815 (setq shiftedq (+ q shift))
1816 (setq shiftedy y)
1817 (setq d 1 h 0 m 0 d1 1 month (+ 1 (* 3 (- (+ q shift) 1))) month1 (+ 4 (* 3 (- (+ q shift) 1))) h1 0 m1 0))))
1818 ((memq key '(year thisyear))
1819 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1820 (t (error "No such time block %s" key)))
1821 (setq ts (encode-time s m h d month y)
1822 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1823 (or d1 d) (or month1 month) (or y1 y)))
1824 (setq fm (cdr org-time-stamp-formats))
1825 (cond
1826 ((memq key '(day today))
1827 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1828 ((memq key '(week thisweek))
1829 (setq txt (format-time-string "week %G-W%V" ts)))
1830 ((memq key '(month thismonth))
1831 (setq txt (format-time-string "%B %Y" ts)))
1832 ((memq key '(year thisyear))
1833 (setq txt (format-time-string "the year %Y" ts)))
1834 ((memq key '(quarter thisq))
1835 (setq txt (concatenate 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
1837 (if as-strings
1838 (list (format-time-string fm ts) (format-time-string fm te) txt)
1839 (list ts te txt))))
1841 (defun org-count-quarter (n)
1842 (cond
1843 ((= n 1) "1st")
1844 ((= n 2) "2nd")
1845 ((= n 3) "3rd")
1846 ((= n 4) "4th")))
1848 (defun org-clocktable-shift (dir n)
1849 "Try to shift the :block date of the clocktable at point.
1850 Point must be in the #+BEGIN: line of a clocktable, or this function
1851 will throw an error.
1852 DIR is a direction, a symbol `left', `right', `up', or `down'.
1853 Both `left' and `down' shift the block toward the past, `up' and `right'
1854 push it toward the future.
1855 N is the number of shift steps to take. The size of the step depends on
1856 the currently selected interval size."
1857 (setq n (prefix-numeric-value n))
1858 (and (memq dir '(left down)) (setq n (- n)))
1859 (save-excursion
1860 (goto-char (point-at-bol))
1861 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
1862 (error "Line needs a :block definition before this command works")
1863 (let* ((b (match-beginning 1)) (e (match-end 1))
1864 (s (match-string 1))
1865 block shift ins y mw d date wp m)
1866 (cond
1867 ((equal s "yesterday") (setq s "today-1"))
1868 ((equal s "lastweek") (setq s "thisweek-1"))
1869 ((equal s "lastmonth") (setq s "thismonth-1"))
1870 ((equal s "lastyear") (setq s "thisyear-1"))
1871 ((equal s "lastq") (setq s "thisq-1")))
1873 (cond
1874 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
1875 (setq block (match-string 1 s)
1876 shift (if (match-end 2)
1877 (string-to-number (match-string 2 s))
1879 (setq shift (+ shift n))
1880 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
1881 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
1882 ;; 1 1 2 3 3 4 4 5 6 6 5 2
1883 (setq y (string-to-number (match-string 1 s))
1884 wp (and (match-end 3) (match-string 3 s))
1885 mw (and (match-end 4) (string-to-number (match-string 4 s)))
1886 d (and (match-end 6) (string-to-number (match-string 6 s))))
1887 (cond
1888 (d (setq ins (format-time-string
1889 "%Y-%m-%d"
1890 (encode-time 0 0 0 (+ d n) m y))))
1891 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
1892 (require 'cal-iso)
1893 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
1894 (setq ins (format-time-string
1895 "%G-W%V"
1896 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1897 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
1898 (require 'cal-iso)
1899 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
1900 (if (> (+ mw n) 4)
1901 (setq mw 0
1902 y (+ 1 y))
1904 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
1905 (if (= (+ mw n) 0)
1906 (setq mw 5
1907 y (- y 1))
1909 (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
1910 (setq ins (format-time-string
1911 (concatenate 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
1912 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
1914 (setq ins (format-time-string
1915 "%Y-%m"
1916 (encode-time 0 0 0 1 (+ mw n) y))))
1918 (setq ins (number-to-string (+ y n))))))
1919 (t (error "Cannot shift clocktable block")))
1920 (when ins
1921 (goto-char b)
1922 (insert ins)
1923 (delete-region (point) (+ (point) (- e b)))
1924 (beginning-of-line 1)
1925 (org-update-dblock)
1926 t)))))
1928 (defun org-dblock-write:clocktable (params)
1929 "Write the standard clocktable."
1930 (setq params (org-combine-plists org-clocktable-defaults params))
1931 (catch 'exit
1932 (let* ((scope (plist-get params :scope))
1933 (block (plist-get params :block))
1934 (ts (plist-get params :tstart))
1935 (te (plist-get params :tend))
1936 (link (plist-get params :link))
1937 (maxlevel (or (plist-get params :maxlevel) 3))
1938 (step (plist-get params :step))
1939 (timestamp (plist-get params :timestamp))
1940 (formatter (or (plist-get params :formatter)
1941 org-clock-clocktable-formatter
1942 'org-clocktable-write-default))
1943 cc range-text ipos pos one-file-with-archives
1944 scope-is-list tbls level)
1946 ;; Check if we need to do steps
1947 (when block
1948 ;; Get the range text for the header
1949 (setq cc (org-clock-special-range block nil t)
1950 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
1951 (when step
1952 ;; Write many tables, in steps
1953 (unless (or block (and ts te))
1954 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
1955 (org-clocktable-steps params)
1956 (throw 'exit nil))
1958 (setq ipos (point)) ; remember the insertion position
1960 ;; Get the right scope
1961 (setq pos (point))
1962 (cond
1963 ((and scope (listp scope) (symbolp (car scope)))
1964 (setq scope (eval scope)))
1965 ((eq scope 'agenda)
1966 (setq scope (org-agenda-files t)))
1967 ((eq scope 'agenda-with-archives)
1968 (setq scope (org-agenda-files t))
1969 (setq scope (org-add-archive-files scope)))
1970 ((eq scope 'file-with-archives)
1971 (setq scope (org-add-archive-files (list (buffer-file-name)))
1972 one-file-with-archives t)))
1973 (setq scope-is-list (and scope (listp scope)))
1974 (if scope-is-list
1975 ;; we collect from several files
1976 (let* ((files scope)
1977 file)
1978 (org-prepare-agenda-buffers files)
1979 (while (setq file (pop files))
1980 (with-current-buffer (find-buffer-visiting file)
1981 (save-excursion
1982 (save-restriction
1983 (push (org-clock-get-table-data file params) tbls))))))
1984 ;; Just from the current file
1985 (save-restriction
1986 ;; get the right range into the restriction
1987 (org-prepare-agenda-buffers (list (buffer-file-name)))
1988 (cond
1989 ((not scope)) ; use the restriction as it is now
1990 ((eq scope 'file) (widen))
1991 ((eq scope 'subtree) (org-narrow-to-subtree))
1992 ((eq scope 'tree)
1993 (while (org-up-heading-safe))
1994 (org-narrow-to-subtree))
1995 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
1996 (symbol-name scope)))
1997 (setq level (string-to-number (match-string 1 (symbol-name scope))))
1998 (catch 'exit
1999 (while (org-up-heading-safe)
2000 (looking-at outline-regexp)
2001 (if (<= (org-reduced-level (funcall outline-level)) level)
2002 (throw 'exit nil))))
2003 (org-narrow-to-subtree)))
2004 ;; do the table, with no file name.
2005 (push (org-clock-get-table-data nil params) tbls)))
2007 ;; OK, at this point we tbls as a list of tables, one per file
2008 (setq tbls (nreverse tbls))
2010 (setq params (plist-put params :multifile scope-is-list))
2011 (setq params (plist-put params :one-file-with-archives
2012 one-file-with-archives))
2014 (funcall formatter ipos tbls params))))
2016 (defun org-clocktable-write-default (ipos tables params)
2017 "Write out a clock table at position IPOS in the current buffer.
2018 TABLES is a list of tables with clocking data as produced by
2019 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2020 from the dynamic block defintion."
2021 ;; This function looks quite complicated, mainly because there are a lot
2022 ;; of options which can add or remove columns. I have massively commented
2023 ;; function, to I hope it is understandable. If someone want to write
2024 ;; there own special formatter, this maybe much easier because there can
2025 ;; be a fixed format with a well-defined number of columns...
2026 (let* ((hlchars '((1 . "*") (2 . "/")))
2027 (lwords (assoc (plist-get params :lang)
2028 org-clock-clocktable-language-setup))
2029 (multifile (plist-get params :multifile))
2030 (block (plist-get params :block))
2031 (ts (plist-get params :tstart))
2032 (te (plist-get params :tend))
2033 (header (plist-get params :header))
2034 (narrow (plist-get params :narrow))
2035 (link (plist-get params :link))
2036 (maxlevel (or (plist-get params :maxlevel) 3))
2037 (emph (plist-get params :emphasize))
2038 (level-p (plist-get params :level))
2039 (timestamp (plist-get params :timestamp))
2040 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2041 (rm-file-column (plist-get params :one-file-with-archives))
2042 (indent (plist-get params :indent))
2043 range-text total-time tbl level hlc formula pcol
2044 file-time entries entry headline
2045 recalc content narrow-cut-p tcol)
2047 ;; Implement abbreviations
2048 (when (plist-get params :compact)
2049 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2051 ;; Some consistency test for parameters
2052 (unless (integerp ntcol)
2053 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2055 (when (and narrow (integerp narrow) link)
2056 ;; We cannot have both integer narrow and link
2057 (message
2058 "Using hard narrowing in clocktable to allow for links")
2059 (setq narrow (intern (format "%d!" narrow))))
2061 (when narrow
2062 (cond
2063 ((integerp narrow))
2064 ((and (symbolp narrow)
2065 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2066 (setq narrow-cut-p t
2067 narrow (string-to-number (substring (symbol-name narrow)
2068 0 -1))))
2070 (error "Invalid value %s of :narrow property in clock table"
2071 narrow))))
2073 (when block
2074 ;; Get the range text for the header
2075 (setq range-text (nth 2 (org-clock-special-range block nil t))))
2077 ;; Compute the total time
2078 (setq total-time (apply '+ (mapcar 'cadr tables)))
2080 ;; Now we need to output this tsuff
2081 (goto-char ipos)
2083 ;; Insert the text *before* the actual table
2084 (insert-before-markers
2085 (or header
2086 ;; Format the standard header
2087 (concat
2088 "Clock summary at ["
2089 (substring
2090 (format-time-string (cdr org-time-stamp-formats))
2091 1 -1)
2093 (if block (concat ", for " range-text ".") "")
2094 "\n\n")))
2096 ;; Insert the narrowing line
2097 (when (and narrow (integerp narrow) (not narrow-cut-p))
2098 (insert-before-markers
2099 "|" ; table line starter
2100 (if multifile "|" "") ; file column, maybe
2101 (if level-p "|" "") ; level column, maybe
2102 (if timestamp "|" "") ; timestamp column, maybe
2103 (format "<%d>| |\n" narrow))) ; headline and time columns
2105 ;; Insert the table header line
2106 (insert-before-markers
2107 "|" ; table line starter
2108 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2109 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2110 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2111 (concat (nth 4 lwords) "|"
2112 (nth 5 lwords) "|\n")) ; headline and time columns
2114 ;; Insert the total time in the table
2115 (insert-before-markers
2116 "|-\n" ; a hline
2117 "|" ; table line starter
2118 (if multifile (concat "| " (nth 6 lwords) " ") "")
2119 ; file column, maybe
2120 (if level-p "|" "") ; level column, maybe
2121 (if timestamp "|" "") ; timestamp column, maybe
2122 (concat "*" (nth 7 lwords) "*| ") ; instead of a headline
2124 (org-minutes-to-hh:mm-string (or total-time 0)) ; the time
2125 "*|\n") ; close line
2127 ;; Now iterate over the tables and insert the data
2128 ;; but only if any time has been collected
2129 (when (and total-time (> total-time 0))
2131 (while (setq tbl (pop tables))
2132 ;; now tbl is the table resulting from one file.
2133 (setq file-time (nth 1 tbl))
2134 (when (or (and file-time (> file-time 0))
2135 (not (plist-get params :fileskip0)))
2136 (insert-before-markers "|-\n") ; a hline because a new file starts
2137 ;; First the file time, if we have multiple files
2138 (when multifile
2139 ;; Summarize the time colleted from this file
2140 (insert-before-markers
2141 (format (concat "| %s %s | %s*" (nth 8 lwords) "* | *%s*|\n")
2142 (file-name-nondirectory (car tbl))
2143 (if level-p "| " "") ; level column, maybe
2144 (if timestamp "| " "") ; timestamp column, maybe
2145 (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
2147 ;; Get the list of node entries and iterate over it
2148 (setq entries (nth 2 tbl))
2149 (while (setq entry (pop entries))
2150 (setq level (car entry)
2151 headline (nth 1 entry)
2152 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2153 (when narrow-cut-p
2154 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2155 "\\'")
2156 headline)
2157 (match-end 3))
2158 (setq headline
2159 (format "[[%s][%s]]"
2160 (match-string 1 headline)
2161 (org-shorten-string (match-string 3 headline)
2162 narrow)))
2163 (setq headline (org-shorten-string headline narrow))))
2164 (insert-before-markers
2165 "|" ; start the table line
2166 (if multifile "|" "") ; free space for file name column?
2167 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2168 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2169 (if indent (org-clocktable-indent-string level) "") ; indentation
2170 hlc headline hlc "|" ; headline
2171 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2172 ; empty fields for higher levels
2173 hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
2174 "|\n" ; close line
2175 )))))
2176 (backward-delete-char 1)
2177 (if (setq formula (plist-get params :formula))
2178 (cond
2179 ((eq formula '%)
2180 ;; compute the column where the % numbers need to go
2181 (setq pcol (+ 2
2182 (if multifile 1 0)
2183 (if level-p 1 0)
2184 (if timestamp 1 0)
2185 (min maxlevel (or ntcol 100))))
2186 ;; compute the column where the total time is
2187 (setq tcol (+ 2
2188 (if multifile 1 0)
2189 (if level-p 1 0)
2190 (if timestamp 1 0)))
2191 (insert
2192 (format
2193 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2194 pcol ; the column where the % numbers should go
2195 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2196 tcol ; column of the total time
2197 tcol (1- pcol) ; range of columns where times can be found
2199 (setq recalc t))
2200 ((stringp formula)
2201 (insert "\n#+TBLFM: " formula)
2202 (setq recalc t))
2203 (t (error "invalid formula in clocktable")))
2204 ;; Should we rescue an old formula?
2205 (when (stringp (setq content (plist-get params :content)))
2206 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
2207 (setq recalc t)
2208 (insert "\n" (match-string 1 (plist-get params :content)))
2209 (beginning-of-line 0))))
2210 ;; Back to beginning, align the table, recalculate if necessary
2211 (goto-char ipos)
2212 (skip-chars-forward "^|")
2213 (org-table-align)
2214 (when org-hide-emphasis-markers
2215 ;; we need to align a second time
2216 (org-table-align))
2217 (when recalc
2218 (if (eq formula '%)
2219 (save-excursion
2220 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2221 (org-table-goto-column pcol nil 'force)
2222 (insert "%")))
2223 (org-table-recalculate 'all))
2224 (when rm-file-column
2225 ;; The file column is actually not wanted
2226 (forward-char 1)
2227 (org-table-delete-column))
2228 total-time))
2230 (defun org-clocktable-indent-string (level)
2231 (if (= level 1)
2233 (let ((str "\\__"))
2234 (while (> level 2)
2235 (setq level (1- level)
2236 str (concat str "___")))
2237 (concat str " "))))
2239 (defun org-clocktable-steps (params)
2240 "Step through the range to make a number of clock tables."
2241 (let* ((p1 (copy-sequence params))
2242 (ts (plist-get p1 :tstart))
2243 (te (plist-get p1 :tend))
2244 (step0 (plist-get p1 :step))
2245 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2246 (stepskip0 (plist-get p1 :stepskip0))
2247 (block (plist-get p1 :block))
2248 cc range-text step-time)
2249 (when block
2250 (setq cc (org-clock-special-range block nil t)
2251 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2252 (cond
2253 ((numberp ts)
2254 ;; If ts is a number, it's an absolute day number from org-agenda.
2255 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2256 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2258 (setq ts (org-float-time
2259 (apply 'encode-time (org-parse-time-string ts))))))
2260 (cond
2261 ((numberp te)
2262 ;; Likewise for te.
2263 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2264 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2266 (setq te (org-float-time
2267 (apply 'encode-time (org-parse-time-string te))))))
2268 (setq p1 (plist-put p1 :header ""))
2269 (setq p1 (plist-put p1 :step nil))
2270 (setq p1 (plist-put p1 :block nil))
2271 (while (< ts te)
2272 (or (bolp) (insert "\n"))
2273 (setq p1 (plist-put p1 :tstart (format-time-string
2274 (org-time-stamp-format nil t)
2275 (seconds-to-time ts))))
2276 (setq p1 (plist-put p1 :tend (format-time-string
2277 (org-time-stamp-format nil t)
2278 (seconds-to-time (setq ts (+ ts step))))))
2279 (insert "\n" (if (eq step0 'day) "Daily report: "
2280 "Weekly report starting on: ")
2281 (plist-get p1 :tstart) "\n")
2282 (setq step-time (org-dblock-write:clocktable p1))
2283 (re-search-forward "^[ \t]*#\\+END:")
2284 (when (and (equal step-time 0) stepskip0)
2285 ;; Remove the empty table
2286 (delete-region (point-at-bol)
2287 (save-excursion
2288 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2289 nil t)
2290 (point))))
2291 (end-of-line 0))))
2293 (defun org-clock-get-table-data (file params)
2294 "Get the clocktable data for file FILE, with parameters PARAMS.
2295 FILE is only for identification - this function assumes that
2296 the correct buffer is current, and that the wanted restriction is
2297 in place.
2298 The return value will be a list with the file name and the total
2299 file time (in minutes) as 1st and 2nd elements. The third element
2300 of this list will be a list of headline entries. Each entry has the
2301 following structure:
2303 (LEVEL HEADLINE TIMESTAMP TIME)
2305 LEVEL: The level of the headline, as an integer. This will be
2306 the reduced leve, so 1,2,3,... even if only odd levels
2307 are being used.
2308 HEADLINE: The text of the headline. Depending on PARAMS, this may
2309 already be formatted like a link.
2310 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2311 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2312 in this sequence.
2313 TIME: The sum of all time spend in this tree, in minutes. This time
2314 will of cause be restricted to the time block and tags match
2315 specified in PARAMS."
2316 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2317 (timestamp (plist-get params :timestamp))
2318 (ts (plist-get params :tstart))
2319 (te (plist-get params :tend))
2320 (block (plist-get params :block))
2321 (link (plist-get params :link))
2322 (tags (plist-get params :tags))
2323 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2324 cc range-text st p time level hdl props tsp tbl)
2326 (setq org-clock-file-total-minutes nil)
2327 (when block
2328 (setq cc (org-clock-special-range block nil t)
2329 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2330 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2331 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2332 (when (and ts (listp ts))
2333 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2334 (when (and te (listp te))
2335 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2336 ;; Now the times are strings we can parse.
2337 (if ts (setq ts (org-float-time
2338 (apply 'encode-time (org-parse-time-string ts)))))
2339 (if te (setq te (org-float-time
2340 (apply 'encode-time (org-parse-time-string te)))))
2341 (save-excursion
2342 (org-clock-sum ts te
2343 (unless (null matcher)
2344 (lambda ()
2345 (let ((tags-list (org-get-tags-at)))
2346 (eval matcher)))))
2347 (goto-char (point-min))
2348 (setq st t)
2349 (while (or (and (bobp) (prog1 st (setq st nil))
2350 (get-text-property (point) :org-clock-minutes)
2351 (setq p (point-min)))
2352 (setq p (next-single-property-change
2353 (point) :org-clock-minutes)))
2354 (goto-char p)
2355 (when (setq time (get-text-property p :org-clock-minutes))
2356 (save-excursion
2357 (beginning-of-line 1)
2358 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2359 (setq level (org-reduced-level
2360 (- (match-end 1) (match-beginning 1))))
2361 (<= level maxlevel))
2362 (setq hdl (if (not link)
2363 (match-string 2)
2364 (org-make-link-string
2365 (format "file:%s::%s"
2366 (buffer-file-name)
2367 (save-match-data
2368 (org-make-org-heading-search-string
2369 (match-string 2))))
2370 (match-string 2)))
2371 tsp (when timestamp
2372 (setq props (org-entry-properties (point)))
2373 (or (cdr (assoc "SCHEDULED" props))
2374 (cdr (assoc "DEADLINE" props))
2375 (cdr (assoc "TIMESTAMP" props))
2376 (cdr (assoc "TIMESTAMP_IA" props)))))
2377 (when (> time 0) (push (list level hdl tsp time) tbl))))))
2378 (setq tbl (nreverse tbl))
2379 (list file org-clock-file-total-minutes tbl))))
2381 (defun org-clock-time% (total &rest strings)
2382 "Compute a time fraction in percent.
2383 TOTAL s a time string like 10:21 specifying the total times.
2384 STRINGS is a list of strings that should be checked for a time.
2385 The first string that does have a time will be used.
2386 This function is made for clock tables."
2387 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2388 tot s)
2389 (save-match-data
2390 (catch 'exit
2391 (if (not (string-match re total))
2392 (throw 'exit 0.)
2393 (setq tot (+ (string-to-number (match-string 2 total))
2394 (* 60 (string-to-number (match-string 1 total)))))
2395 (if (= tot 0.) (throw 'exit 0.)))
2396 (while (setq s (pop strings))
2397 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2398 (throw 'exit
2399 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2400 (* 60 (string-to-number
2401 (match-string 1 s)))))
2402 tot))))
2403 0))))
2405 (defvar org-clock-loaded nil
2406 "Was the clock file loaded?")
2408 (defun org-clock-save ()
2409 "Persist various clock-related data to disk.
2410 The details of what will be saved are regulated by the variable
2411 `org-clock-persist'."
2412 (when (and org-clock-persist
2413 (or org-clock-loaded
2414 org-clock-has-been-used
2415 (not (file-exists-p org-clock-persist-file))))
2416 (let (b)
2417 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2418 (progn
2419 (delete-region (point-min) (point-max))
2420 ;;Store clock
2421 (insert (format ";; org-persist.el - %s at %s\n"
2422 system-name (format-time-string
2423 (cdr org-time-stamp-formats))))
2424 (if (and (memq org-clock-persist '(t clock))
2425 (setq b (org-clocking-buffer))
2426 (setq b (or (buffer-base-buffer b) b))
2427 (buffer-live-p b)
2428 (buffer-file-name b)
2429 (or (not org-clock-persist-query-save)
2430 (y-or-n-p (concat "Save current clock ("
2431 (substring-no-properties
2432 org-clock-heading)
2433 ") "))))
2434 (insert "(setq resume-clock '(\""
2435 (buffer-file-name (org-clocking-buffer))
2436 "\" . " (int-to-string (marker-position org-clock-marker))
2437 "))\n"))
2438 ;; Store clocked task history. Tasks are stored reversed to make
2439 ;; reading simpler
2440 (when (and (memq org-clock-persist '(t history))
2441 org-clock-history)
2442 (insert
2443 "(setq stored-clock-history '("
2444 (mapconcat
2445 (lambda (m)
2446 (when (and (setq b (marker-buffer m))
2447 (setq b (or (buffer-base-buffer b) b))
2448 (buffer-live-p b)
2449 (buffer-file-name b))
2450 (concat "(\"" (buffer-file-name b)
2451 "\" . " (int-to-string (marker-position m))
2452 ")")))
2453 (reverse org-clock-history) " ") "))\n"))
2454 (save-buffer)
2455 (kill-buffer (current-buffer)))))))
2457 (defun org-clock-load ()
2458 "Load clock-related data from disk, maybe resuming a stored clock."
2459 (when (and org-clock-persist (not org-clock-loaded))
2460 (let ((filename (expand-file-name org-clock-persist-file))
2461 (org-clock-in-resume 'auto-restart)
2462 resume-clock stored-clock-history)
2463 (if (not (file-readable-p filename))
2464 (message "Not restoring clock data; %s not found"
2465 org-clock-persist-file)
2466 (message "%s" "Restoring clock data")
2467 (setq org-clock-loaded t)
2468 (load-file filename)
2469 ;; load history
2470 (when stored-clock-history
2471 (save-window-excursion
2472 (mapc (lambda (task)
2473 (if (file-exists-p (car task))
2474 (org-clock-history-push (cdr task)
2475 (find-file (car task)))))
2476 stored-clock-history)))
2477 ;; resume clock
2478 (when (and resume-clock org-clock-persist
2479 (file-exists-p (car resume-clock))
2480 (or (not org-clock-persist-query-resume)
2481 (y-or-n-p
2482 (concat
2483 "Resume clock ("
2484 (with-current-buffer (find-file (car resume-clock))
2485 (save-excursion
2486 (goto-char (cdr resume-clock))
2487 (org-back-to-heading t)
2488 (and (looking-at org-complex-heading-regexp)
2489 (match-string 4))))
2490 ") "))))
2491 (when (file-exists-p (car resume-clock))
2492 (with-current-buffer (find-file (car resume-clock))
2493 (goto-char (cdr resume-clock))
2494 (let ((org-clock-auto-clock-resolution nil))
2495 (org-clock-in)
2496 (if (outline-invisible-p)
2497 (org-show-context))))))))))
2499 ;;;###autoload
2500 (defun org-clock-persistence-insinuate ()
2501 "Set up hooks for clock persistence."
2502 (add-hook 'org-mode-hook 'org-clock-load)
2503 (add-hook 'kill-emacs-hook 'org-clock-save))
2505 ;; Suggested bindings
2506 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2508 (provide 'org-clock)
2510 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
2512 ;;; org-clock.el ends here