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