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