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