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