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