Always "make clean" for lisp files before compiling them
[org-mode.git] / lisp / org-clock.el
blob25a36cf57fe4bd81b68feb3a9d38bd57fdc630ae
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 (or (eq org-clock-clocked-in-display 'frame-title)
1213 (eq org-clock-clocked-in-display 'both))
1214 (or (memq 'org-frame-title-string frame-title-format)
1215 (setq frame-title-format
1216 (append frame-title-format '(org-frame-title-string)))))
1217 (org-clock-update-mode-line)
1218 (when org-clock-mode-line-timer
1219 (cancel-timer org-clock-mode-line-timer)
1220 (setq org-clock-mode-line-timer nil))
1221 (when org-clock-clocked-in-display
1222 (setq org-clock-mode-line-timer
1223 (run-with-timer org-clock-update-period
1224 org-clock-update-period
1225 'org-clock-update-mode-line)))
1226 (when org-clock-idle-timer
1227 (cancel-timer org-clock-idle-timer)
1228 (setq org-clock-idle-timer nil))
1229 (setq org-clock-idle-timer
1230 (run-with-timer 60 60 'org-resolve-clocks-if-idle))
1231 (message "Clock starts at %s - %s" ts msg-extra)
1232 (run-hooks 'org-clock-in-hook)))))))
1234 (defun org-clock-mark-default-task ()
1235 "Mark current task as default task."
1236 (interactive)
1237 (save-excursion
1238 (org-back-to-heading t)
1239 (move-marker org-clock-default-task (point))))
1241 (defvar msg-extra)
1242 (defun org-clock-get-sum-start ()
1243 "Return the time from which clock times should be counted.
1244 This is for the currently running clock as it is displayed
1245 in the mode line. This function looks at the properties
1246 LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
1247 corresponding variable `org-clock-modeline-total' and then
1248 decides which time to use."
1249 (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
1250 (symbol-name org-clock-modeline-total)))
1251 (lr (org-entry-get nil "LAST_REPEAT")))
1252 (cond
1253 ((equal cmt "current")
1254 (setq msg-extra "showing time in current clock instance")
1255 (current-time))
1256 ((equal cmt "today")
1257 (setq msg-extra "showing today's task time.")
1258 (let* ((dt (decode-time (current-time))))
1259 (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
1260 (if org-extend-today-until
1261 (setf (nth 2 dt) org-extend-today-until))
1262 (apply 'encode-time dt)))
1263 ((or (equal cmt "all")
1264 (and (or (not cmt) (equal cmt "auto"))
1265 (not lr)))
1266 (setq msg-extra "showing entire task time.")
1267 nil)
1268 ((or (equal cmt "repeat")
1269 (and (or (not cmt) (equal cmt "auto"))
1270 lr))
1271 (setq msg-extra "showing task time since last repeat.")
1272 (if (not lr)
1274 (org-time-string-to-time lr)))
1275 (t nil))))
1277 (defun org-clock-find-position (find-unclosed)
1278 "Find the location where the next clock line should be inserted.
1279 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
1280 line and position cursor in that line."
1281 (org-back-to-heading t)
1282 (catch 'exit
1283 (let* ((org-clock-into-drawer (org-clock-into-drawer))
1284 (beg (save-excursion
1285 (beginning-of-line 2)
1286 (or (bolp) (newline))
1287 (point)))
1288 (end (progn (outline-next-heading) (point)))
1289 (re (concat "^[ \t]*" org-clock-string))
1290 (cnt 0)
1291 (drawer (if (stringp org-clock-into-drawer)
1292 org-clock-into-drawer "LOGBOOK"))
1293 first last ind-last)
1294 (goto-char beg)
1295 (when (and find-unclosed
1296 (re-search-forward
1297 (concat "^[ \t]*" org-clock-string
1298 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
1299 " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
1300 end t))
1301 (beginning-of-line 1)
1302 (throw 'exit t))
1303 (when (eobp) (newline) (setq end (max (point) end)))
1304 (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
1305 ;; we seem to have a CLOCK drawer, so go there.
1306 (beginning-of-line 2)
1307 (or org-log-states-order-reversed
1308 (and (re-search-forward org-property-end-re nil t)
1309 (goto-char (match-beginning 0))))
1310 (throw 'exit t))
1311 ;; Lets count the CLOCK lines
1312 (goto-char beg)
1313 (while (re-search-forward re end t)
1314 (setq first (or first (match-beginning 0))
1315 last (match-beginning 0)
1316 cnt (1+ cnt)))
1317 (when (and (integerp org-clock-into-drawer)
1318 last
1319 (>= (1+ cnt) org-clock-into-drawer))
1320 ;; Wrap current entries into a new drawer
1321 (goto-char last)
1322 (setq ind-last (org-get-indentation))
1323 (beginning-of-line 2)
1324 (if (and (>= (org-get-indentation) ind-last)
1325 (org-at-item-p))
1326 (when (and (>= (org-get-indentation) ind-last)
1327 (org-at-item-p))
1328 (let ((struct (org-list-struct)))
1329 (goto-char (org-list-get-bottom-point struct)))))
1330 (insert ":END:\n")
1331 (beginning-of-line 0)
1332 (org-indent-line-to ind-last)
1333 (goto-char first)
1334 (insert ":" drawer ":\n")
1335 (beginning-of-line 0)
1336 (org-indent-line-function)
1337 (org-flag-drawer t)
1338 (beginning-of-line 2)
1339 (or org-log-states-order-reversed
1340 (and (re-search-forward org-property-end-re nil t)
1341 (goto-char (match-beginning 0))))
1342 (throw 'exit nil))
1344 (goto-char beg)
1345 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1346 (not (equal (match-string 1) org-clock-string)))
1347 ;; Planning info, skip to after it
1348 (beginning-of-line 2)
1349 (or (bolp) (newline)))
1350 (when (or (eq org-clock-into-drawer t)
1351 (stringp org-clock-into-drawer)
1352 (and (integerp org-clock-into-drawer)
1353 (< org-clock-into-drawer 2)))
1354 (insert ":" drawer ":\n:END:\n")
1355 (beginning-of-line -1)
1356 (org-indent-line-function)
1357 (org-flag-drawer t)
1358 (beginning-of-line 2)
1359 (org-indent-line-function)
1360 (beginning-of-line)
1361 (or org-log-states-order-reversed
1362 (and (re-search-forward org-property-end-re nil t)
1363 (goto-char (match-beginning 0))))))))
1365 (defun org-clock-out (&optional fail-quietly at-time)
1366 "Stop the currently running clock.
1367 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
1368 (interactive)
1369 (catch 'exit
1370 (when (not (org-clocking-p))
1371 (setq global-mode-string
1372 (delq 'org-mode-line-string global-mode-string))
1373 (setq frame-title-format
1374 (delq 'org-frame-title-string frame-title-format))
1375 (force-mode-line-update)
1376 (if fail-quietly (throw 'exit t) (error "No active clock")))
1377 (let (ts te s h m remove)
1378 (save-excursion ; Do not replace this with `with-current-buffer'.
1379 (with-no-warnings (set-buffer (org-clocking-buffer)))
1380 (save-restriction
1381 (widen)
1382 (goto-char org-clock-marker)
1383 (beginning-of-line 1)
1384 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
1385 (equal (match-string 1) org-clock-string))
1386 (setq ts (match-string 2))
1387 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
1388 (goto-char (match-end 0))
1389 (delete-region (point) (point-at-eol))
1390 (insert "--")
1391 (setq te (org-insert-time-stamp (or at-time (current-time))
1392 'with-hm 'inactive))
1393 (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
1394 (org-float-time (apply 'encode-time (org-parse-time-string ts))))
1395 h (floor (/ s 3600))
1396 s (- s (* 3600 h))
1397 m (floor (/ s 60))
1398 s (- s (* 60 s)))
1399 (insert " => " (format "%2d:%02d" h m))
1400 (when (setq remove (and org-clock-out-remove-zero-time-clocks
1401 (= (+ h m) 0)))
1402 (beginning-of-line 1)
1403 (delete-region (point) (point-at-eol))
1404 (and (looking-at "\n") (> (point-max) (1+ (point)))
1405 (delete-char 1)))
1406 (move-marker org-clock-marker nil)
1407 (move-marker org-clock-hd-marker nil)
1408 (when org-log-note-clock-out
1409 (org-add-log-setup 'clock-out nil nil nil nil
1410 (concat "# Task: " (org-get-heading t) "\n\n")))
1411 (when org-clock-mode-line-timer
1412 (cancel-timer org-clock-mode-line-timer)
1413 (setq org-clock-mode-line-timer nil))
1414 (when org-clock-idle-timer
1415 (cancel-timer org-clock-idle-timer)
1416 (setq org-clock-idle-timer nil))
1417 (setq global-mode-string
1418 (delq 'org-mode-line-string global-mode-string))
1419 (setq frame-title-format
1420 (delq 'org-frame-title-string frame-title-format))
1421 (when org-clock-out-switch-to-state
1422 (save-excursion
1423 (org-back-to-heading t)
1424 (let ((org-inhibit-logging t)
1425 (org-clock-out-when-done nil))
1426 (cond
1427 ((functionp org-clock-out-switch-to-state)
1428 (looking-at org-complex-heading-regexp)
1429 (let ((newstate (funcall org-clock-out-switch-to-state
1430 (match-string 2))))
1431 (if newstate (org-todo newstate))))
1432 ((and org-clock-out-switch-to-state
1433 (not (looking-at (concat org-outline-regexp "[ \t]*"
1434 org-clock-out-switch-to-state
1435 "\\>"))))
1436 (org-todo org-clock-out-switch-to-state))))))
1437 (force-mode-line-update)
1438 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
1439 (if remove " => LINE REMOVED" ""))
1440 (run-hooks 'org-clock-out-hook)
1441 (unless (org-clocking-p)
1442 (org-clock-delete-current)))))))
1444 (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
1446 (defun org-clock-remove-empty-clock-drawer nil
1447 "Remove empty clock drawer in the current subtree."
1448 (let* ((olid (or (org-entry-get (point) "LOG_INTO_DRAWER")
1449 org-log-into-drawer))
1450 (clock-drawer (if (eq t olid) "LOGBOOK" olid))
1451 (end (save-excursion (org-end-of-subtree t t))))
1452 (when clock-drawer
1453 (save-excursion
1454 (org-back-to-heading t)
1455 (while (search-forward clock-drawer end t)
1456 (goto-char (match-beginning 0))
1457 (org-remove-empty-drawer-at clock-drawer (point))
1458 (forward-line 1))))))
1460 (defun org-at-clock-log-p nil
1461 "Is the cursor on the clock log line?"
1462 (save-excursion
1463 (move-beginning-of-line 1)
1464 (looking-at "^[ \t]*CLOCK:")))
1466 (defun org-clock-timestamps-up nil
1467 "Increase CLOCK timestamps at cursor."
1468 (interactive)
1469 (org-clock-timestamps-change 'up))
1471 (defun org-clock-timestamps-down nil
1472 "Increase CLOCK timestamps at cursor."
1473 (interactive)
1474 (org-clock-timestamps-change 'down))
1476 (defun org-clock-timestamps-change (updown)
1477 "Change CLOCK timestamps synchronously at cursor.
1478 UPDOWN tells whether to change 'up or 'down."
1479 (setq org-ts-what nil)
1480 (when (org-at-timestamp-p t)
1481 (let ((tschange (if (eq updown 'up) 'org-timestamp-up
1482 'org-timestamp-down))
1483 ts1 begts1 ts2 begts2 updatets1 tdiff)
1484 (save-excursion
1485 (move-beginning-of-line 1)
1486 (re-search-forward org-ts-regexp3 nil t)
1487 (setq ts1 (match-string 0) begts1 (match-beginning 0))
1488 (when (re-search-forward org-ts-regexp3 nil t)
1489 (setq ts2 (match-string 0) begts2 (match-beginning 0))))
1490 ;; Are we on the second timestamp?
1491 (if (<= begts2 (point)) (setq updatets1 t))
1492 (if (not ts2)
1493 ;; fall back on org-timestamp-up if there is only one
1494 (funcall tschange)
1495 ;; setq this so that (boundp 'org-ts-what is non-nil)
1496 (funcall tschange)
1497 (let ((ts (if updatets1 ts2 ts1))
1498 (begts (if updatets1 begts1 begts2)))
1499 (setq tdiff
1500 (subtract-time
1501 (org-time-string-to-time org-last-changed-timestamp)
1502 (org-time-string-to-time ts)))
1503 (save-excursion
1504 (goto-char begts)
1505 (org-timestamp-change
1506 (round (/ (org-float-time tdiff)
1507 (cond ((eq org-ts-what 'minute) 60)
1508 ((eq org-ts-what 'hour) 3600)
1509 ((eq org-ts-what 'day) (* 24 3600))
1510 ((eq org-ts-what 'month) (* 24 3600 31))
1511 ((eq org-ts-what 'year) (* 24 3600 365.2)))))
1512 org-ts-what 'updown)))))))
1514 (defun org-clock-cancel ()
1515 "Cancel the running clock by removing the start timestamp."
1516 (interactive)
1517 (when (not (org-clocking-p))
1518 (setq global-mode-string
1519 (delq 'org-mode-line-string global-mode-string))
1520 (setq frame-title-format
1521 (delq 'org-frame-title-string frame-title-format))
1522 (force-mode-line-update)
1523 (error "No active clock"))
1524 (save-excursion ; Do not replace this with `with-current-buffer'.
1525 (with-no-warnings (set-buffer (org-clocking-buffer)))
1526 (goto-char org-clock-marker)
1527 (delete-region (1- (point-at-bol)) (point-at-eol))
1528 ;; Just in case, remove any empty LOGBOOK left over
1529 (org-remove-empty-drawer-at "LOGBOOK" (point)))
1530 (move-marker org-clock-marker nil)
1531 (move-marker org-clock-hd-marker nil)
1532 (setq global-mode-string
1533 (delq 'org-mode-line-string global-mode-string))
1534 (setq frame-title-format
1535 (delq 'org-frame-title-string frame-title-format))
1536 (force-mode-line-update)
1537 (message "Clock canceled")
1538 (run-hooks 'org-clock-cancel-hook))
1540 (defun org-clock-goto (&optional select)
1541 "Go to the currently clocked-in entry, or to the most recently clocked one.
1542 With prefix arg SELECT, offer recently clocked tasks for selection."
1543 (interactive "@P")
1544 (let* ((recent nil)
1545 (m (cond
1546 (select
1547 (or (org-clock-select-task "Select task to go to: ")
1548 (error "No task selected")))
1549 ((org-clocking-p) org-clock-marker)
1550 ((and org-clock-goto-may-find-recent-task
1551 (car org-clock-history)
1552 (marker-buffer (car org-clock-history)))
1553 (setq recent t)
1554 (car org-clock-history))
1555 (t (error "No active or recent clock task")))))
1556 (org-pop-to-buffer-same-window (marker-buffer m))
1557 (if (or (< m (point-min)) (> m (point-max))) (widen))
1558 (goto-char m)
1559 (org-show-entry)
1560 (org-back-to-heading t)
1561 (org-cycle-hide-drawers 'children)
1562 (recenter)
1563 (org-reveal)
1564 (if recent
1565 (message "No running clock, this is the most recently clocked task"))
1566 (run-hooks 'org-clock-goto-hook)))
1568 (defvar org-clock-file-total-minutes nil
1569 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
1570 (make-variable-buffer-local 'org-clock-file-total-minutes)
1572 (defun org-clock-sum (&optional tstart tend headline-filter)
1573 "Sum the times for each subtree.
1574 Puts the resulting times in minutes as a text property on each headline.
1575 TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
1576 zero-arg function that, if specified, is called for each headline in the time
1577 range with point at the headline. Headlines for which HEADLINE-FILTER returns
1578 nil are excluded from the clock summation."
1579 (interactive)
1580 (let* ((bmp (buffer-modified-p))
1581 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
1582 org-clock-string
1583 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
1584 (lmax 30)
1585 (ltimes (make-vector lmax 0))
1586 (t1 0)
1587 (level 0)
1588 ts te dt
1589 time)
1590 (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
1591 (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
1592 (if (consp tstart) (setq tstart (org-float-time tstart)))
1593 (if (consp tend) (setq tend (org-float-time tend)))
1594 (remove-text-properties (point-min) (point-max)
1595 '(:org-clock-minutes t
1596 :org-clock-force-headline-inclusion t))
1597 (save-excursion
1598 (goto-char (point-max))
1599 (while (re-search-backward re nil t)
1600 (cond
1601 ((match-end 2)
1602 ;; Two time stamps
1603 (setq ts (match-string 2)
1604 te (match-string 3)
1605 ts (org-float-time
1606 (apply 'encode-time (org-parse-time-string ts)))
1607 te (org-float-time
1608 (apply 'encode-time (org-parse-time-string te)))
1609 ts (if tstart (max ts tstart) ts)
1610 te (if tend (min te tend) te)
1611 dt (- te ts)
1612 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
1613 ((match-end 4)
1614 ;; A naked time
1615 (setq t1 (+ t1 (string-to-number (match-string 5))
1616 (* 60 (string-to-number (match-string 4))))))
1617 (t ;; A headline
1618 ;; Add the currently clocking item time to the total
1619 (when (and org-clock-report-include-clocking-task
1620 (equal (org-clocking-buffer) (current-buffer))
1621 (equal (marker-position org-clock-hd-marker) (point))
1622 tstart
1623 tend
1624 (>= (org-float-time org-clock-start-time) tstart)
1625 (<= (org-float-time org-clock-start-time) tend))
1626 (let ((time (floor (- (org-float-time)
1627 (org-float-time org-clock-start-time)) 60)))
1628 (setq t1 (+ t1 time))))
1629 (let* ((headline-forced
1630 (get-text-property (point)
1631 :org-clock-force-headline-inclusion))
1632 (headline-included
1633 (or (null headline-filter)
1634 (save-excursion
1635 (save-match-data (funcall headline-filter))))))
1636 (setq level (- (match-end 1) (match-beginning 1)))
1637 (when (or (> t1 0) (> (aref ltimes level) 0))
1638 (when (or headline-included headline-forced)
1639 (if headline-included
1640 (loop for l from 0 to level do
1641 (aset ltimes l (+ (aref ltimes l) t1))))
1642 (setq time (aref ltimes level))
1643 (goto-char (match-beginning 0))
1644 (put-text-property (point) (point-at-eol) :org-clock-minutes time)
1645 (if headline-filter
1646 (save-excursion
1647 (save-match-data
1648 (while
1649 (> (funcall outline-level) 1)
1650 (outline-up-heading 1 t)
1651 (put-text-property
1652 (point) (point-at-eol)
1653 :org-clock-force-headline-inclusion t))))))
1654 (setq t1 0)
1655 (loop for l from level to (1- lmax) do
1656 (aset ltimes l 0)))))))
1657 (setq org-clock-file-total-minutes (aref ltimes 0)))
1658 (set-buffer-modified-p bmp)))
1660 (defun org-clock-sum-current-item (&optional tstart)
1661 "Return time, clocked on current item in total."
1662 (save-excursion
1663 (save-restriction
1664 (org-narrow-to-subtree)
1665 (org-clock-sum tstart)
1666 org-clock-file-total-minutes)))
1668 (defun org-clock-display (&optional total-only)
1669 "Show subtree times in the entire buffer.
1670 If TOTAL-ONLY is non-nil, only show the total time for the entire file
1671 in the echo area.
1673 Use \\[org-clock-remove-overlays] to remove the subtree times."
1674 (interactive)
1675 (org-clock-remove-overlays)
1676 (let (time h m p)
1677 (org-clock-sum)
1678 (unless total-only
1679 (save-excursion
1680 (goto-char (point-min))
1681 (while (or (and (equal (setq p (point)) (point-min))
1682 (get-text-property p :org-clock-minutes))
1683 (setq p (next-single-property-change
1684 (point) :org-clock-minutes)))
1685 (goto-char p)
1686 (when (setq time (get-text-property p :org-clock-minutes))
1687 (org-clock-put-overlay time (funcall outline-level))))
1688 (setq h (/ org-clock-file-total-minutes 60)
1689 m (- org-clock-file-total-minutes (* 60 h)))
1690 ;; Arrange to remove the overlays upon next change.
1691 (when org-remove-highlights-with-change
1692 (org-add-hook 'before-change-functions 'org-clock-remove-overlays
1693 nil 'local))))
1694 (if org-time-clocksum-use-fractional
1695 (message (concat "Total file time: " org-time-clocksum-fractional-format
1696 " (%d hours and %d minutes)")
1697 (/ (+ (* h 60.0) m) 60.0) h m)
1698 (message (concat "Total file time: " org-time-clocksum-format
1699 " (%d hours and %d minutes)") h m h m))))
1701 (defvar org-clock-overlays nil)
1702 (make-variable-buffer-local 'org-clock-overlays)
1704 (defun org-clock-put-overlay (time &optional level)
1705 "Put an overlays on the current line, displaying TIME.
1706 If LEVEL is given, prefix time with a corresponding number of stars.
1707 This creates a new overlay and stores it in `org-clock-overlays', so that it
1708 will be easy to remove."
1709 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
1710 (l (if level (org-get-valid-level level 0) 0))
1711 (fmt (concat "%s " (if org-time-clocksum-use-fractional
1712 org-time-clocksum-fractional-format
1713 org-time-clocksum-format) "%s"))
1714 (off 0)
1715 ov tx)
1716 (org-move-to-column c)
1717 (unless (eolp) (skip-chars-backward "^ \t"))
1718 (skip-chars-backward " \t")
1719 (setq ov (make-overlay (1- (point)) (point-at-eol))
1720 tx (concat (buffer-substring (1- (point)) (point))
1721 (make-string (+ off (max 0 (- c (current-column)))) ?.)
1722 (org-add-props (if org-time-clocksum-use-fractional
1723 (format fmt
1724 (make-string l ?*)
1725 (/ (+ (* h 60.0) m) 60.0)
1726 (make-string (- 16 l) ?\ ))
1727 (format fmt
1728 (make-string l ?*) h m
1729 (make-string (- 16 l) ?\ )))
1730 (list 'face 'org-clock-overlay))
1731 ""))
1732 (if (not (featurep 'xemacs))
1733 (overlay-put ov 'display tx)
1734 (overlay-put ov 'invisible t)
1735 (overlay-put ov 'end-glyph (make-glyph tx)))
1736 (push ov org-clock-overlays)))
1738 (defun org-clock-remove-overlays (&optional beg end noremove)
1739 "Remove the occur highlights from the buffer.
1740 BEG and END are ignored. If NOREMOVE is nil, remove this function
1741 from the `before-change-functions' in the current buffer."
1742 (interactive)
1743 (unless org-inhibit-highlight-removal
1744 (mapc 'delete-overlay org-clock-overlays)
1745 (setq org-clock-overlays nil)
1746 (unless noremove
1747 (remove-hook 'before-change-functions
1748 'org-clock-remove-overlays 'local))))
1750 (defvar org-state) ;; dynamically scoped into this function
1751 (defun org-clock-out-if-current ()
1752 "Clock out if the current entry contains the running clock.
1753 This is used to stop the clock after a TODO entry is marked DONE,
1754 and is only done if the variable `org-clock-out-when-done' is not nil."
1755 (when (and (org-clocking-p)
1756 org-clock-out-when-done
1757 (marker-buffer org-clock-marker)
1758 (or (and (eq t org-clock-out-when-done)
1759 (member org-state org-done-keywords))
1760 (and (listp org-clock-out-when-done)
1761 (member org-state org-clock-out-when-done)))
1762 (equal (or (buffer-base-buffer (org-clocking-buffer))
1763 (org-clocking-buffer))
1764 (or (buffer-base-buffer (current-buffer))
1765 (current-buffer)))
1766 (< (point) org-clock-marker)
1767 (> (save-excursion (outline-next-heading) (point))
1768 org-clock-marker))
1769 ;; Clock out, but don't accept a logging message for this.
1770 (let ((org-log-note-clock-out nil)
1771 (org-clock-out-switch-to-state nil))
1772 (org-clock-out))))
1774 (add-hook 'org-after-todo-state-change-hook
1775 'org-clock-out-if-current)
1777 ;;;###autoload
1778 (defun org-get-clocktable (&rest props)
1779 "Get a formatted clocktable with parameters according to PROPS.
1780 The table is created in a temporary buffer, fully formatted and
1781 fontified, and then returned."
1782 ;; Set the defaults
1783 (setq props (plist-put props :name "clocktable"))
1784 (unless (plist-member props :maxlevel)
1785 (setq props (plist-put props :maxlevel 2)))
1786 (unless (plist-member props :scope)
1787 (setq props (plist-put props :scope 'agenda)))
1788 (with-temp-buffer
1789 (org-mode)
1790 (org-create-dblock props)
1791 (org-update-dblock)
1792 (font-lock-fontify-buffer)
1793 (forward-line 2)
1794 (buffer-substring (point) (progn
1795 (re-search-forward "^[ \t]*#\\+END" nil t)
1796 (point-at-bol)))))
1798 (defun org-clock-report (&optional arg)
1799 "Create a table containing a report about clocked time.
1800 If the cursor is inside an existing clocktable block, then the table
1801 will be updated. If not, a new clocktable will be inserted. The scope
1802 of the new clock will be subtree when called from within a subtree, and
1803 file elsewhere.
1805 When called with a prefix argument, move to the first clock table in the
1806 buffer and update it."
1807 (interactive "P")
1808 (org-clock-remove-overlays)
1809 (when arg
1810 (org-find-dblock "clocktable")
1811 (org-show-entry))
1812 (if (org-in-clocktable-p)
1813 (goto-char (org-in-clocktable-p))
1814 (let ((props (if (ignore-errors
1815 (save-excursion (org-back-to-heading)))
1816 (list :name "clocktable" :scope 'subtree)
1817 (list :name "clocktable"))))
1818 (org-create-dblock
1819 (org-combine-plists org-clock-clocktable-default-properties props))))
1820 (org-update-dblock))
1822 (defun org-day-of-week (day month year)
1823 "Returns the day of the week as an integer."
1824 (nth 6
1825 (decode-time
1826 (date-to-time
1827 (format "%d-%02d-%02dT00:00:00" year month day)))))
1829 (defun org-quarter-to-date (quarter year)
1830 "Get the date (week day year) of the first day of a given quarter."
1831 (let (startday)
1832 (cond
1833 ((= quarter 1)
1834 (setq startday (org-day-of-week 1 1 year))
1835 (cond
1836 ((= startday 0)
1837 (list 52 7 (- year 1)))
1838 ((= startday 6)
1839 (list 52 6 (- year 1)))
1840 ((<= startday 4)
1841 (list 1 startday year))
1842 ((> startday 4)
1843 (list 53 startday (- year 1)))
1846 ((= quarter 2)
1847 (setq startday (org-day-of-week 1 4 year))
1848 (cond
1849 ((= startday 0)
1850 (list 13 startday year))
1851 ((< startday 4)
1852 (list 14 startday year))
1853 ((>= startday 4)
1854 (list 13 startday year))
1857 ((= quarter 3)
1858 (setq startday (org-day-of-week 1 7 year))
1859 (cond
1860 ((= startday 0)
1861 (list 26 startday year))
1862 ((< startday 4)
1863 (list 27 startday year))
1864 ((>= startday 4)
1865 (list 26 startday year))
1868 ((= quarter 4)
1869 (setq startday (org-day-of-week 1 10 year))
1870 (cond
1871 ((= startday 0)
1872 (list 39 startday year))
1873 ((<= startday 4)
1874 (list 40 startday year))
1875 ((> startday 4)
1876 (list 39 startday year)))))))
1878 (defun org-clock-special-range (key &optional time as-strings)
1879 "Return two times bordering a special time range.
1880 Key is a symbol specifying the range and can be one of `today', `yesterday',
1881 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
1882 A week starts Monday 0:00 and ends Sunday 24:00.
1883 The range is determined relative to TIME. TIME defaults to the current time.
1884 The return value is a cons cell with two internal times like the ones
1885 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
1886 the returned times will be formatted strings."
1887 (if (integerp key) (setq key (intern (number-to-string key))))
1888 (let* ((tm (decode-time (or time (current-time))))
1889 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
1890 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
1891 (dow (nth 6 tm))
1892 (skey (symbol-name key))
1893 (shift 0)
1894 (q (cond ((>= (nth 4 tm) 10) 4)
1895 ((>= (nth 4 tm) 7) 3)
1896 ((>= (nth 4 tm) 4) 2)
1897 ((>= (nth 4 tm) 1) 1)))
1898 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
1899 interval tmp shiftedy shiftedm shiftedq)
1900 (cond
1901 ((string-match "^[0-9]+$" skey)
1902 (setq y (string-to-number skey) m 1 d 1 key 'year))
1903 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1904 (setq y (string-to-number (match-string 1 skey))
1905 month (string-to-number (match-string 2 skey))
1906 d 1 key 'month))
1907 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
1908 (require 'cal-iso)
1909 (setq y (string-to-number (match-string 1 skey))
1910 w (string-to-number (match-string 2 skey)))
1911 (setq date (calendar-gregorian-from-absolute
1912 (calendar-absolute-from-iso (list w 1 y))))
1913 (setq d (nth 1 date) month (car date) y (nth 2 date)
1914 dow 1
1915 key 'week))
1916 ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
1917 (require 'cal-iso)
1918 (setq y (string-to-number (match-string 1 skey)))
1919 (setq q (string-to-number (match-string 2 skey)))
1920 (setq date (calendar-gregorian-from-absolute
1921 (calendar-absolute-from-iso (org-quarter-to-date q y))))
1922 (setq d (nth 1 date) month (car date) y (nth 2 date)
1923 dow 1
1924 key 'quarter))
1925 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
1926 (setq y (string-to-number (match-string 1 skey))
1927 month (string-to-number (match-string 2 skey))
1928 d (string-to-number (match-string 3 skey))
1929 key 'day))
1930 ((string-match "\\([-+][0-9]+\\)$" skey)
1931 (setq shift (string-to-number (match-string 1 skey))
1932 key (intern (substring skey 0 (match-beginning 1))))
1933 (if(and (memq key '(quarter thisq)) (> shift 0))
1934 (error "Looking forward with quarters isn't implemented.")
1935 ())))
1937 (when (= shift 0)
1938 (cond ((eq key 'yesterday) (setq key 'today shift -1))
1939 ((eq key 'lastweek) (setq key 'week shift -1))
1940 ((eq key 'lastmonth) (setq key 'month shift -1))
1941 ((eq key 'lastyear) (setq key 'year shift -1))
1942 ((eq key 'lastq) (setq key 'quarter shift -1))))
1943 (cond
1944 ((memq key '(day today))
1945 (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
1946 ((memq key '(week thisweek))
1947 (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
1948 m 0 h 0 d (- d diff) d1 (+ 7 d)))
1949 ((memq key '(month thismonth))
1950 (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
1951 ((memq key '(quarter thisq))
1952 ; compute if this shift remains in this year
1953 ; if not, compute how many years and quarters we have to shift (via floor*)
1954 ; and compute the shifted years, months and quarters
1955 (cond
1956 ((< (+ (- q 1) shift) 0) ; shift not in this year
1957 (setq interval (* -1 (+ (- q 1) shift)))
1958 ; set tmp to ((years to shift) (quarters to shift))
1959 (setq tmp (org-floor* interval 4))
1960 ; due to the use of floor, 0 quarters actually means 4
1961 (if (= 0 (nth 1 tmp))
1962 (setq shiftedy (- y (nth 0 tmp))
1963 shiftedm 1
1964 shiftedq 1)
1965 (setq shiftedy (- y (+ 1 (nth 0 tmp)))
1966 shiftedm (- 13 (* 3 (nth 1 tmp)))
1967 shiftedq (- 5 (nth 1 tmp))))
1968 (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
1969 ((> (+ q shift) 0) ; shift is within this year
1970 (setq shiftedq (+ q shift))
1971 (setq shiftedy y)
1972 (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))))
1973 ((memq key '(year thisyear))
1974 (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
1975 (t (error "No such time block %s" key)))
1976 (setq ts (encode-time s m h d month y)
1977 te (encode-time (or s1 s) (or m1 m) (or h1 h)
1978 (or d1 d) (or month1 month) (or y1 y)))
1979 (setq fm (cdr org-time-stamp-formats))
1980 (cond
1981 ((memq key '(day today))
1982 (setq txt (format-time-string "%A, %B %d, %Y" ts)))
1983 ((memq key '(week thisweek))
1984 (setq txt (format-time-string "week %G-W%V" ts)))
1985 ((memq key '(month thismonth))
1986 (setq txt (format-time-string "%B %Y" ts)))
1987 ((memq key '(year thisyear))
1988 (setq txt (format-time-string "the year %Y" ts)))
1989 ((memq key '(quarter thisq))
1990 (setq txt (concatenate 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
1992 (if as-strings
1993 (list (format-time-string fm ts) (format-time-string fm te) txt)
1994 (list ts te txt))))
1996 (defun org-count-quarter (n)
1997 (cond
1998 ((= n 1) "1st")
1999 ((= n 2) "2nd")
2000 ((= n 3) "3rd")
2001 ((= n 4) "4th")))
2003 (defun org-clocktable-shift (dir n)
2004 "Try to shift the :block date of the clocktable at point.
2005 Point must be in the #+BEGIN: line of a clocktable, or this function
2006 will throw an error.
2007 DIR is a direction, a symbol `left', `right', `up', or `down'.
2008 Both `left' and `down' shift the block toward the past, `up' and `right'
2009 push it toward the future.
2010 N is the number of shift steps to take. The size of the step depends on
2011 the currently selected interval size."
2012 (setq n (prefix-numeric-value n))
2013 (and (memq dir '(left down)) (setq n (- n)))
2014 (save-excursion
2015 (goto-char (point-at-bol))
2016 (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
2017 (error "Line needs a :block definition before this command works")
2018 (let* ((b (match-beginning 1)) (e (match-end 1))
2019 (s (match-string 1))
2020 block shift ins y mw d date wp m)
2021 (cond
2022 ((equal s "yesterday") (setq s "today-1"))
2023 ((equal s "lastweek") (setq s "thisweek-1"))
2024 ((equal s "lastmonth") (setq s "thismonth-1"))
2025 ((equal s "lastyear") (setq s "thisyear-1"))
2026 ((equal s "lastq") (setq s "thisq-1")))
2028 (cond
2029 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
2030 (setq block (match-string 1 s)
2031 shift (if (match-end 2)
2032 (string-to-number (match-string 2 s))
2034 (setq shift (+ shift n))
2035 (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
2036 ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
2037 ;; 1 1 2 3 3 4 4 5 6 6 5 2
2038 (setq y (string-to-number (match-string 1 s))
2039 wp (and (match-end 3) (match-string 3 s))
2040 mw (and (match-end 4) (string-to-number (match-string 4 s)))
2041 d (and (match-end 6) (string-to-number (match-string 6 s))))
2042 (cond
2043 (d (setq ins (format-time-string
2044 "%Y-%m-%d"
2045 (encode-time 0 0 0 (+ d n) m y))))
2046 ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
2047 (require 'cal-iso)
2048 (setq date (calendar-gregorian-from-absolute
2049 (calendar-absolute-from-iso (list (+ mw n) 1 y))))
2050 (setq ins (format-time-string
2051 "%G-W%V"
2052 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2053 ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
2054 (require 'cal-iso)
2055 ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
2056 (if (> (+ mw n) 4)
2057 (setq mw 0
2058 y (+ 1 y))
2060 ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
2061 (if (= (+ mw n) 0)
2062 (setq mw 5
2063 y (- y 1))
2065 (setq date (calendar-gregorian-from-absolute
2066 (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
2067 (setq ins (format-time-string
2068 (concatenate 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
2069 (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
2071 (setq ins (format-time-string
2072 "%Y-%m"
2073 (encode-time 0 0 0 1 (+ mw n) y))))
2075 (setq ins (number-to-string (+ y n))))))
2076 (t (error "Cannot shift clocktable block")))
2077 (when ins
2078 (goto-char b)
2079 (insert ins)
2080 (delete-region (point) (+ (point) (- e b)))
2081 (beginning-of-line 1)
2082 (org-update-dblock)
2083 t)))))
2085 (defun org-dblock-write:clocktable (params)
2086 "Write the standard clocktable."
2087 (setq params (org-combine-plists org-clocktable-defaults params))
2088 (catch 'exit
2089 (let* ((scope (plist-get params :scope))
2090 (block (plist-get params :block))
2091 (ts (plist-get params :tstart))
2092 (te (plist-get params :tend))
2093 (link (plist-get params :link))
2094 (maxlevel (or (plist-get params :maxlevel) 3))
2095 (step (plist-get params :step))
2096 (timestamp (plist-get params :timestamp))
2097 (formatter (or (plist-get params :formatter)
2098 org-clock-clocktable-formatter
2099 'org-clocktable-write-default))
2100 cc range-text ipos pos one-file-with-archives
2101 scope-is-list tbls level)
2102 ;; Check if we need to do steps
2103 (when block
2104 ;; Get the range text for the header
2105 (setq cc (org-clock-special-range block nil t)
2106 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2107 (when step
2108 ;; Write many tables, in steps
2109 (unless (or block (and ts te))
2110 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
2111 (org-clocktable-steps params)
2112 (throw 'exit nil))
2114 (setq ipos (point)) ; remember the insertion position
2116 ;; Get the right scope
2117 (setq pos (point))
2118 (cond
2119 ((and scope (listp scope) (symbolp (car scope)))
2120 (setq scope (eval scope)))
2121 ((eq scope 'agenda)
2122 (setq scope (org-agenda-files t)))
2123 ((eq scope 'agenda-with-archives)
2124 (setq scope (org-agenda-files t))
2125 (setq scope (org-add-archive-files scope)))
2126 ((eq scope 'file-with-archives)
2127 (setq scope (org-add-archive-files (list (buffer-file-name)))
2128 one-file-with-archives t)))
2129 (setq scope-is-list (and scope (listp scope)))
2130 (if scope-is-list
2131 ;; we collect from several files
2132 (let* ((files scope)
2133 file)
2134 (org-prepare-agenda-buffers files)
2135 (while (setq file (pop files))
2136 (with-current-buffer (find-buffer-visiting file)
2137 (save-excursion
2138 (save-restriction
2139 (push (org-clock-get-table-data file params) tbls))))))
2140 ;; Just from the current file
2141 (save-restriction
2142 ;; get the right range into the restriction
2143 (org-prepare-agenda-buffers (list (buffer-file-name)))
2144 (cond
2145 ((not scope)) ; use the restriction as it is now
2146 ((eq scope 'file) (widen))
2147 ((eq scope 'subtree) (org-narrow-to-subtree))
2148 ((eq scope 'tree)
2149 (while (org-up-heading-safe))
2150 (org-narrow-to-subtree))
2151 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
2152 (symbol-name scope)))
2153 (setq level (string-to-number (match-string 1 (symbol-name scope))))
2154 (catch 'exit
2155 (while (org-up-heading-safe)
2156 (looking-at org-outline-regexp)
2157 (if (<= (org-reduced-level (funcall outline-level)) level)
2158 (throw 'exit nil))))
2159 (org-narrow-to-subtree)))
2160 ;; do the table, with no file name.
2161 (push (org-clock-get-table-data nil params) tbls)))
2163 ;; OK, at this point we tbls as a list of tables, one per file
2164 (setq tbls (nreverse tbls))
2166 (setq params (plist-put params :multifile scope-is-list))
2167 (setq params (plist-put params :one-file-with-archives
2168 one-file-with-archives))
2170 (funcall formatter ipos tbls params))))
2172 (defun org-clocktable-write-default (ipos tables params)
2173 "Write out a clock table at position IPOS in the current buffer.
2174 TABLES is a list of tables with clocking data as produced by
2175 `org-clock-get-table-data'. PARAMS is the parameter property list obtained
2176 from the dynamic block definition."
2177 ;; This function looks quite complicated, mainly because there are a
2178 ;; lot of options which can add or remove columns. I have massively
2179 ;; commented this function, the I hope it is understandable. If
2180 ;; someone wants to write their own special formatter, this maybe
2181 ;; much easier because there can be a fixed format with a
2182 ;; well-defined number of columns...
2183 (let* ((hlchars '((1 . "*") (2 . "/")))
2184 (lwords (assoc (or (plist-get params :lang)
2185 org-export-default-language)
2186 org-clock-clocktable-language-setup))
2187 (multifile (plist-get params :multifile))
2188 (block (plist-get params :block))
2189 (ts (plist-get params :tstart))
2190 (te (plist-get params :tend))
2191 (header (plist-get params :header))
2192 (narrow (plist-get params :narrow))
2193 (link (plist-get params :link))
2194 (maxlevel (or (plist-get params :maxlevel) 3))
2195 (emph (plist-get params :emphasize))
2196 (level-p (plist-get params :level))
2197 (timestamp (plist-get params :timestamp))
2198 (properties (plist-get params :properties))
2199 (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
2200 (rm-file-column (plist-get params :one-file-with-archives))
2201 (indent (plist-get params :indent))
2202 range-text total-time tbl level hlc formula pcol
2203 file-time entries entry headline
2204 recalc content narrow-cut-p tcol)
2206 ;; Implement abbreviations
2207 (when (plist-get params :compact)
2208 (setq level nil indent t narrow (or narrow '40!) ntcol 1))
2210 ;; Some consistency test for parameters
2211 (unless (integerp ntcol)
2212 (setq params (plist-put params :tcolumns (setq ntcol 100))))
2214 (when (and narrow (integerp narrow) link)
2215 ;; We cannot have both integer narrow and link
2216 (message
2217 "Using hard narrowing in clocktable to allow for links")
2218 (setq narrow (intern (format "%d!" narrow))))
2220 (when narrow
2221 (cond
2222 ((integerp narrow))
2223 ((and (symbolp narrow)
2224 (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
2225 (setq narrow-cut-p t
2226 narrow (string-to-number (substring (symbol-name narrow)
2227 0 -1))))
2229 (error "Invalid value %s of :narrow property in clock table"
2230 narrow))))
2232 (when block
2233 ;; Get the range text for the header
2234 (setq range-text (nth 2 (org-clock-special-range block nil t))))
2236 ;; Compute the total time
2237 (setq total-time (apply '+ (mapcar 'cadr tables)))
2239 ;; Now we need to output this tsuff
2240 (goto-char ipos)
2242 ;; Insert the text *before* the actual table
2243 (insert-before-markers
2244 (or header
2245 ;; Format the standard header
2246 (concat
2247 (nth 9 lwords) " ["
2248 (substring
2249 (format-time-string (cdr org-time-stamp-formats))
2250 1 -1)
2252 (if block (concat ", for " range-text ".") "")
2253 "\n\n")))
2255 ;; Insert the narrowing line
2256 (when (and narrow (integerp narrow) (not narrow-cut-p))
2257 (insert-before-markers
2258 "|" ; table line starter
2259 (if multifile "|" "") ; file column, maybe
2260 (if level-p "|" "") ; level column, maybe
2261 (if timestamp "|" "") ; timestamp column, maybe
2262 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2263 (format "<%d>| |\n" narrow))) ; headline and time columns
2265 ;; Insert the table header line
2266 (insert-before-markers
2267 "|" ; table line starter
2268 (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
2269 (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
2270 (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
2271 (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
2272 (concat (nth 4 lwords) "|"
2273 (nth 5 lwords) "|\n")) ; headline and time columns
2275 ;; Insert the total time in the table
2276 (insert-before-markers
2277 "|-\n" ; a hline
2278 "|" ; table line starter
2279 (if multifile (concat "| " (nth 6 lwords) " ") "")
2280 ; file column, maybe
2281 (if level-p "|" "") ; level column, maybe
2282 (if timestamp "|" "") ; timestamp column, maybe
2283 (if properties (make-string (length properties) ?|) "") ; properties columns, maybe
2284 (concat (format org-clock-total-time-cell-format (nth 7 lwords)) "| ") ; instead of a headline
2285 (format org-clock-total-time-cell-format
2286 (org-minutes-to-hh:mm-string (or total-time 0))) ; the time
2287 "|\n") ; close line
2289 ;; Now iterate over the tables and insert the data
2290 ;; but only if any time has been collected
2291 (when (and total-time (> total-time 0))
2293 (while (setq tbl (pop tables))
2294 ;; now tbl is the table resulting from one file.
2295 (setq file-time (nth 1 tbl))
2296 (when (or (and file-time (> file-time 0))
2297 (not (plist-get params :fileskip0)))
2298 (insert-before-markers "|-\n") ; a hline because a new file starts
2299 ;; First the file time, if we have multiple files
2300 (when multifile
2301 ;; Summarize the time collected from this file
2302 (insert-before-markers
2303 (format (concat "| %s %s | %s%s"
2304 (format org-clock-file-time-cell-format (nth 8 lwords))
2305 " | *%s*|\n")
2306 (file-name-nondirectory (car tbl))
2307 (if level-p "| " "") ; level column, maybe
2308 (if timestamp "| " "") ; timestamp column, maybe
2309 (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
2310 (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
2312 ;; Get the list of node entries and iterate over it
2313 (setq entries (nth 2 tbl))
2314 (while (setq entry (pop entries))
2315 (setq level (car entry)
2316 headline (nth 1 entry)
2317 hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
2318 (when narrow-cut-p
2319 (if (and (string-match (concat "\\`" org-bracket-link-regexp
2320 "\\'")
2321 headline)
2322 (match-end 3))
2323 (setq headline
2324 (format "[[%s][%s]]"
2325 (match-string 1 headline)
2326 (org-shorten-string (match-string 3 headline)
2327 narrow)))
2328 (setq headline (org-shorten-string headline narrow))))
2329 (insert-before-markers
2330 "|" ; start the table line
2331 (if multifile "|" "") ; free space for file name column?
2332 (if level-p (format "%d|" (car entry)) "") ; level, maybe
2333 (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
2334 (if properties
2335 (concat
2336 (mapconcat
2337 (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
2338 properties "|") "|") "") ;properties columns, maybe
2339 (if indent (org-clocktable-indent-string level) "") ; indentation
2340 hlc headline hlc "|" ; headline
2341 (make-string (min (1- ntcol) (or (- level 1))) ?|)
2342 ; empty fields for higher levels
2343 hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
2344 "|\n" ; close line
2345 )))))
2346 (backward-delete-char 1)
2347 (if (setq formula (plist-get params :formula))
2348 (cond
2349 ((eq formula '%)
2350 ;; compute the column where the % numbers need to go
2351 (setq pcol (+ 2
2352 (if multifile 1 0)
2353 (if level-p 1 0)
2354 (if timestamp 1 0)
2355 (min maxlevel (or ntcol 100))))
2356 ;; compute the column where the total time is
2357 (setq tcol (+ 2
2358 (if multifile 1 0)
2359 (if level-p 1 0)
2360 (if timestamp 1 0)))
2361 (insert
2362 (format
2363 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
2364 pcol ; the column where the % numbers should go
2365 (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
2366 tcol ; column of the total time
2367 tcol (1- pcol) ; range of columns where times can be found
2369 (setq recalc t))
2370 ((stringp formula)
2371 (insert "\n#+TBLFM: " formula)
2372 (setq recalc t))
2373 (t (error "invalid formula in clocktable")))
2374 ;; Should we rescue an old formula?
2375 (when (stringp (setq content (plist-get params :content)))
2376 (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
2377 (setq recalc t)
2378 (insert "\n" (match-string 1 (plist-get params :content)))
2379 (beginning-of-line 0))))
2380 ;; Back to beginning, align the table, recalculate if necessary
2381 (goto-char ipos)
2382 (skip-chars-forward "^|")
2383 (org-table-align)
2384 (when org-hide-emphasis-markers
2385 ;; we need to align a second time
2386 (org-table-align))
2387 (when recalc
2388 (if (eq formula '%)
2389 (save-excursion
2390 (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
2391 (org-table-goto-column pcol nil 'force)
2392 (insert "%")))
2393 (org-table-recalculate 'all))
2394 (when rm-file-column
2395 ;; The file column is actually not wanted
2396 (forward-char 1)
2397 (org-table-delete-column))
2398 total-time))
2400 (defun org-clocktable-indent-string (level)
2401 (if (= level 1)
2403 (let ((str "\\__"))
2404 (while (> level 2)
2405 (setq level (1- level)
2406 str (concat str "___")))
2407 (concat str " "))))
2409 (defun org-clocktable-steps (params)
2410 "Step through the range to make a number of clock tables."
2411 (let* ((p1 (copy-sequence params))
2412 (ts (plist-get p1 :tstart))
2413 (te (plist-get p1 :tend))
2414 (step0 (plist-get p1 :step))
2415 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
2416 (stepskip0 (plist-get p1 :stepskip0))
2417 (block (plist-get p1 :block))
2418 cc range-text step-time)
2419 (when block
2420 (setq cc (org-clock-special-range block nil t)
2421 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2422 (cond
2423 ((numberp ts)
2424 ;; If ts is a number, it's an absolute day number from org-agenda.
2425 (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
2426 (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
2428 (setq ts (org-float-time
2429 (apply 'encode-time (org-parse-time-string ts))))))
2430 (cond
2431 ((numberp te)
2432 ;; Likewise for te.
2433 (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
2434 (setq te (org-float-time (encode-time 0 0 0 day month year)))))
2436 (setq te (org-float-time
2437 (apply 'encode-time (org-parse-time-string te))))))
2438 (setq p1 (plist-put p1 :header ""))
2439 (setq p1 (plist-put p1 :step nil))
2440 (setq p1 (plist-put p1 :block nil))
2441 (while (< ts te)
2442 (or (bolp) (insert "\n"))
2443 (setq p1 (plist-put p1 :tstart (format-time-string
2444 (org-time-stamp-format nil t)
2445 (seconds-to-time ts))))
2446 (setq p1 (plist-put p1 :tend (format-time-string
2447 (org-time-stamp-format nil t)
2448 (seconds-to-time (setq ts (+ ts step))))))
2449 (insert "\n" (if (eq step0 'day) "Daily report: "
2450 "Weekly report starting on: ")
2451 (plist-get p1 :tstart) "\n")
2452 (setq step-time (org-dblock-write:clocktable p1))
2453 (re-search-forward "^[ \t]*#\\+END:")
2454 (when (and (equal step-time 0) stepskip0)
2455 ;; Remove the empty table
2456 (delete-region (point-at-bol)
2457 (save-excursion
2458 (re-search-backward "^\\(Daily\\|Weekly\\) report"
2459 nil t)
2460 (point))))
2461 (end-of-line 0))))
2463 (defun org-clock-get-table-data (file params)
2464 "Get the clocktable data for file FILE, with parameters PARAMS.
2465 FILE is only for identification - this function assumes that
2466 the correct buffer is current, and that the wanted restriction is
2467 in place.
2468 The return value will be a list with the file name and the total
2469 file time (in minutes) as 1st and 2nd elements. The third element
2470 of this list will be a list of headline entries. Each entry has the
2471 following structure:
2473 (LEVEL HEADLINE TIMESTAMP TIME)
2475 LEVEL: The level of the headline, as an integer. This will be
2476 the reduced leve, so 1,2,3,... even if only odd levels
2477 are being used.
2478 HEADLINE: The text of the headline. Depending on PARAMS, this may
2479 already be formatted like a link.
2480 TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
2481 entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
2482 in this sequence.
2483 TIME: The sum of all time spend in this tree, in minutes. This time
2484 will of cause be restricted to the time block and tags match
2485 specified in PARAMS."
2486 (let* ((maxlevel (or (plist-get params :maxlevel) 3))
2487 (timestamp (plist-get params :timestamp))
2488 (ts (plist-get params :tstart))
2489 (te (plist-get params :tend))
2490 (block (plist-get params :block))
2491 (link (plist-get params :link))
2492 (tags (plist-get params :tags))
2493 (properties (plist-get params :properties))
2494 (inherit-property-p (plist-get params :inherit-props))
2495 todo-only
2496 (matcher (if tags (cdr (org-make-tags-matcher tags))))
2497 cc range-text st p time level hdl props tsp tbl)
2499 (setq org-clock-file-total-minutes nil)
2500 (when block
2501 (setq cc (org-clock-special-range block nil t)
2502 ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
2503 (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
2504 (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
2505 (when (and ts (listp ts))
2506 (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
2507 (when (and te (listp te))
2508 (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
2509 ;; Now the times are strings we can parse.
2510 (if ts (setq ts (org-float-time
2511 (apply 'encode-time (org-parse-time-string ts)))))
2512 (if te (setq te (org-float-time
2513 (apply 'encode-time (org-parse-time-string te)))))
2514 (save-excursion
2515 (org-clock-sum ts te
2516 (unless (null matcher)
2517 (lambda ()
2518 (let* ((tags-list (org-get-tags-at))
2519 (org-scanner-tags tags-list)
2520 (org-trust-scanner-tags t))
2521 (eval matcher)))))
2522 (goto-char (point-min))
2523 (setq st t)
2524 (while (or (and (bobp) (prog1 st (setq st nil))
2525 (get-text-property (point) :org-clock-minutes)
2526 (setq p (point-min)))
2527 (setq p (next-single-property-change
2528 (point) :org-clock-minutes)))
2529 (goto-char p)
2530 (when (setq time (get-text-property p :org-clock-minutes))
2531 (save-excursion
2532 (beginning-of-line 1)
2533 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
2534 (setq level (org-reduced-level
2535 (- (match-end 1) (match-beginning 1))))
2536 (<= level maxlevel))
2537 (setq hdl (if (not link)
2538 (match-string 2)
2539 (org-make-link-string
2540 (format "file:%s::%s"
2541 (buffer-file-name)
2542 (save-match-data
2543 (org-make-org-heading-search-string
2544 (match-string 2))))
2545 (match-string 2)))
2546 tsp (when timestamp
2547 (setq props (org-entry-properties (point)))
2548 (or (cdr (assoc "SCHEDULED" props))
2549 (cdr (assoc "DEADLINE" props))
2550 (cdr (assoc "TIMESTAMP" props))
2551 (cdr (assoc "TIMESTAMP_IA" props))))
2552 props (when properties
2553 (remove nil
2554 (mapcar
2555 (lambda (p)
2556 (when (org-entry-get (point) p inherit-property-p)
2557 (cons p (org-entry-get (point) p inherit-property-p))))
2558 properties))))
2559 (when (> time 0) (push (list level hdl tsp time props) tbl))))))
2560 (setq tbl (nreverse tbl))
2561 (list file org-clock-file-total-minutes tbl))))
2563 (defun org-clock-time% (total &rest strings)
2564 "Compute a time fraction in percent.
2565 TOTAL s a time string like 10:21 specifying the total times.
2566 STRINGS is a list of strings that should be checked for a time.
2567 The first string that does have a time will be used.
2568 This function is made for clock tables."
2569 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
2570 tot s)
2571 (save-match-data
2572 (catch 'exit
2573 (if (not (string-match re total))
2574 (throw 'exit 0.)
2575 (setq tot (+ (string-to-number (match-string 2 total))
2576 (* 60 (string-to-number (match-string 1 total)))))
2577 (if (= tot 0.) (throw 'exit 0.)))
2578 (while (setq s (pop strings))
2579 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
2580 (throw 'exit
2581 (/ (* 100.0 (+ (string-to-number (match-string 2 s))
2582 (* 60 (string-to-number
2583 (match-string 1 s)))))
2584 tot))))
2585 0))))
2587 ;; Saving and loading the clock
2589 (defvar org-clock-loaded nil
2590 "Was the clock file loaded?")
2592 (defun org-clock-save ()
2593 "Persist various clock-related data to disk.
2594 The details of what will be saved are regulated by the variable
2595 `org-clock-persist'."
2596 (when (and org-clock-persist
2597 (or org-clock-loaded
2598 org-clock-has-been-used
2599 (not (file-exists-p org-clock-persist-file))))
2600 (let (b)
2601 (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
2602 (progn
2603 (delete-region (point-min) (point-max))
2604 ;;Store clock
2605 (insert (format ";; org-persist.el - %s at %s\n"
2606 system-name (format-time-string
2607 (cdr org-time-stamp-formats))))
2608 (if (and (memq org-clock-persist '(t clock))
2609 (setq b (org-clocking-buffer))
2610 (setq b (or (buffer-base-buffer b) b))
2611 (buffer-live-p b)
2612 (buffer-file-name b)
2613 (or (not org-clock-persist-query-save)
2614 (y-or-n-p (concat "Save current clock ("
2615 (substring-no-properties
2616 org-clock-heading)
2617 ") "))))
2618 (insert "(setq resume-clock '(\""
2619 (buffer-file-name (org-clocking-buffer))
2620 "\" . " (int-to-string (marker-position org-clock-marker))
2621 "))\n"))
2622 ;; Store clocked task history. Tasks are stored reversed to make
2623 ;; reading simpler
2624 (when (and (memq org-clock-persist '(t history))
2625 org-clock-history)
2626 (insert
2627 "(setq stored-clock-history '("
2628 (mapconcat
2629 (lambda (m)
2630 (when (and (setq b (marker-buffer m))
2631 (setq b (or (buffer-base-buffer b) b))
2632 (buffer-live-p b)
2633 (buffer-file-name b))
2634 (concat "(\"" (buffer-file-name b)
2635 "\" . " (int-to-string (marker-position m))
2636 ")")))
2637 (reverse org-clock-history) " ") "))\n"))
2638 (save-buffer)
2639 (kill-buffer (current-buffer)))))))
2641 (defun org-clock-load ()
2642 "Load clock-related data from disk, maybe resuming a stored clock."
2643 (when (and org-clock-persist (not org-clock-loaded))
2644 (let ((filename (expand-file-name org-clock-persist-file))
2645 (org-clock-in-resume 'auto-restart)
2646 resume-clock stored-clock-history)
2647 (if (not (file-readable-p filename))
2648 (message "Not restoring clock data; %s not found"
2649 org-clock-persist-file)
2650 (message "%s" "Restoring clock data")
2651 (setq org-clock-loaded t)
2652 (load-file filename)
2653 ;; load history
2654 (when stored-clock-history
2655 (save-window-excursion
2656 (mapc (lambda (task)
2657 (if (file-exists-p (car task))
2658 (org-clock-history-push (cdr task)
2659 (find-file (car task)))))
2660 stored-clock-history)))
2661 ;; resume clock
2662 (when (and resume-clock org-clock-persist
2663 (file-exists-p (car resume-clock))
2664 (or (not org-clock-persist-query-resume)
2665 (y-or-n-p
2666 (concat
2667 "Resume clock ("
2668 (with-current-buffer (find-file (car resume-clock))
2669 (save-excursion
2670 (goto-char (cdr resume-clock))
2671 (org-back-to-heading t)
2672 (and (looking-at org-complex-heading-regexp)
2673 (match-string 4))))
2674 ") "))))
2675 (when (file-exists-p (car resume-clock))
2676 (with-current-buffer (find-file (car resume-clock))
2677 (goto-char (cdr resume-clock))
2678 (let ((org-clock-auto-clock-resolution nil))
2679 (org-clock-in)
2680 (if (outline-invisible-p)
2681 (org-show-context))))))))))
2683 ;;;###autoload
2684 (defun org-clock-persistence-insinuate ()
2685 "Set up hooks for clock persistence."
2686 (add-hook 'org-mode-hook 'org-clock-load)
2687 (add-hook 'kill-emacs-hook 'org-clock-save))
2689 ;; Suggested bindings
2690 (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
2692 (provide 'org-clock)
2694 ;;; org-clock.el ends here