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