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