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