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