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