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