1 ;;; org-clock.el --- The time clocking code for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the time clocking code for Org-mode
36 (declare-function calendar-absolute-from-iso
"cal-iso" (&optional date
))
37 (defvar org-time-stamp-formats
)
39 (defgroup org-clock nil
40 "Options concerning clocking working time in Org-mode."
44 (defcustom org-clock-into-drawer org-log-into-drawer
45 "Should clocking info be wrapped into a drawer?
46 When t, clocking info will always be inserted into a :LOGBOOK: drawer.
47 If necessary, the drawer will be created.
48 When nil, the drawer will not be created, but used when present.
49 When an integer and the number of clocking entries in an item
50 reaches or exceeds this number, a drawer will be created.
51 When a string, it names the drawer to be used.
53 The default for this variable is the value of `org-log-into-drawer',
58 (const :tag
"Always" t
)
59 (const :tag
"Only when drawer exists" nil
)
60 (integer :tag
"When at least N clock entries")
61 (const :tag
"Into LOGBOOK drawer" "LOGBOOK")
62 (string :tag
"Into Drawer named...")))
64 (defcustom org-clock-out-when-done t
65 "When non-nil, clock will be stopped when the clocked entry is marked DONE.
66 A nil value means, clock will keep running until stopped explicitly with
67 `C-c C-x C-o', or until the clock is started in a different item."
71 (defcustom org-clock-out-remove-zero-time-clocks nil
72 "Non-nil means, remove the clock line when the resulting time is zero."
76 (defcustom org-clock-in-switch-to-state nil
77 "Set task to a special todo state while clocking it.
78 The value should be the state to which the entry should be
79 switched. If the value is a function, it must take one
80 parameter (the current TODO state of the item) and return the
81 state to switch it to."
85 (const :tag
"Don't force a state" nil
)
87 (symbol :tag
"Function")))
89 (defcustom org-clock-history-length
5
90 "Number of clock tasks to remember in history."
94 (defcustom org-clock-goto-may-find-recent-task t
95 "Non-nil means, `org-clock-goto' can go to recent task if no active clock."
99 (defcustom org-clock-heading-function nil
100 "When non-nil, should be a function to create `org-clock-heading'.
101 This is the string shown in the mode line when a clock is running.
102 The function is called with point at the beginning of the headline."
106 (defcustom org-clock-string-limit
0
107 "Maximum length of clock strings in the modeline. 0 means no limit."
111 (defcustom org-clock-in-resume nil
112 "If non-nil, resume clock when clocking into task with open clock.
113 When clocking into a task with a clock entry which has not been closed,
114 the clock can be resumed from that point."
118 (defcustom org-clock-persist nil
119 "When non-nil, save the running clock when emacs is closed.
120 The clock is resumed when emacs restarts.
121 When this is t, both the running clock, and the entire clock
122 history are saved. When this is the symbol `clock', only the
123 running clock is saved.
125 When Emacs restarts with saved clock information, the file containing the
126 running clock as well as all files mentioned in the clock history will
128 All this depends on running `org-clock-persistence-insinuate' in .emacs"
131 (const :tag
"Just the running clock" clock
)
132 (const :tag
"Clock and history" t
)
133 (const :tag
"No persistence" nil
)))
135 (defcustom org-clock-persist-file
(convert-standard-filename
136 "~/.emacs.d/org-clock-save.el")
137 "File to save clock data to."
141 (defcustom org-clock-persist-query-save nil
142 "When non-nil, ask before saving the current clock on exit."
146 (defcustom org-clock-persist-query-resume t
147 "When non-nil, ask before resuming any stored clock during load."
151 ;;; The clock for measuring work time.
153 (defvar org-mode-line-string
"")
154 (put 'org-mode-line-string
'risky-local-variable t
)
156 (defvar org-clock-mode-line-timer nil
)
157 (defvar org-clock-heading
"")
158 (defvar org-clock-heading-for-remember
"")
159 (defvar org-clock-start-time
"")
161 (defvar org-clock-history nil
162 "List of marker pointing to recent clocked tasks.")
164 (defvar org-clock-default-task
(make-marker)
165 "Marker pointing to the default task that should clock time.
166 The clock can be made to switch to this task after clocking out
167 of a different task.")
169 (defvar org-clock-interrupted-task
(make-marker)
170 "Marker pointing to the task that has been interrupted by the current clock.")
172 (defvar org-clock-mode-line-map
(make-sparse-keymap))
173 (define-key org-clock-mode-line-map
[mode-line mouse-2
] 'org-clock-goto
)
175 (defun org-clock-history-push (&optional pos buffer
)
176 "Push a marker to the clock history."
177 (setq org-clock-history-length
(max 1 (min 35 org-clock-history-length
)))
178 (let ((m (move-marker (make-marker) (or pos
(point)) buffer
)) n l
)
179 (while (setq n
(member m org-clock-history
))
180 (move-marker (car n
) nil
))
181 (setq org-clock-history
183 (mapcar (lambda (x) (if (marker-buffer x
) x nil
))
185 (when (>= (setq l
(length org-clock-history
)) org-clock-history-length
)
186 (setq org-clock-history
188 (nthcdr (- l org-clock-history-length -
1)
189 (nreverse org-clock-history
)))))
190 (push m org-clock-history
)))
192 (defun org-clock-save-markers-for-cut-and-paste (beg end
)
193 "Save relative positions of markers in region."
194 (org-check-and-save-marker org-clock-marker beg end
)
195 (org-check-and-save-marker org-clock-default-task beg end
)
196 (org-check-and-save-marker org-clock-interrupted-task beg end
)
197 (mapc (lambda (m) (org-check-and-save-marker m beg end
))
200 (defun org-clock-select-task (&optional prompt
)
201 "Select a task that recently was associated with clocking."
203 (let (sel-list rpl
(i 0) s
)
204 (save-window-excursion
205 (org-switch-to-buffer-other-window
206 (get-buffer-create "*Clock Task Select*"))
208 (when (marker-buffer org-clock-default-task
)
209 (insert (org-add-props "Default Task\n" nil
'face
'bold
))
210 (setq s
(org-clock-insert-selection-line ?d org-clock-default-task
))
212 (when (marker-buffer org-clock-interrupted-task
)
213 (insert (org-add-props "The task interrupted by starting the last one\n" nil
'face
'bold
))
214 (setq s
(org-clock-insert-selection-line ?i org-clock-interrupted-task
))
216 (when (marker-buffer org-clock-marker
)
217 (insert (org-add-props "Current Clocking Task\n" nil
'face
'bold
))
218 (setq s
(org-clock-insert-selection-line ?c org-clock-marker
))
220 (insert (org-add-props "Recent Tasks\n" nil
'face
'bold
))
223 (when (marker-buffer m
)
225 s
(org-clock-insert-selection-line
231 (org-fit-window-to-buffer)
232 (message (or prompt
"Select task for clocking:"))
233 (setq rpl
(read-char-exclusive))
237 ((assoc rpl sel-list
) (cdr (assoc rpl sel-list
)))
238 (t (error "Invalid task choice %c" rpl
))))))
240 (defun org-clock-insert-selection-line (i marker
)
241 "Insert a line for the clock selection menu.
242 And return a cons cell with the selection character integer and the marker
244 (when (marker-buffer marker
)
245 (let (file cat task heading prefix
)
246 (with-current-buffer (org-base-buffer (marker-buffer marker
))
251 (setq file
(buffer-file-name (marker-buffer marker
))
252 cat
(or (org-get-category)
253 (progn (org-refresh-category-properties)
255 heading
(org-get-heading 'notags
)
256 prefix
(save-excursion
257 (org-back-to-heading t
)
261 (org-fontify-like-in-org-mode
262 (concat prefix heading
)
266 (insert (format "[%c] %-15s %s\n" i cat task
))
269 (defun org-clock-update-mode-line ()
270 (let* ((delta (- (time-to-seconds (current-time))
271 (time-to-seconds org-clock-start-time
)))
272 (h (floor delta
3600))
273 (m (floor (- delta
(* 3600 h
)) 60)))
274 (setq org-mode-line-string
276 (let ((clock-string (format (concat "-[" org-time-clocksum-format
" (%s)]")
277 h m org-clock-heading
))
278 (help-text "Org-mode clock is running. Mouse-2 to go there."))
279 (if (and (> org-clock-string-limit
0)
280 (> (length clock-string
) org-clock-string-limit
))
281 (org-propertize (substring clock-string
0 org-clock-string-limit
)
282 'help-echo
(concat help-text
": " org-clock-heading
))
283 (org-propertize clock-string
'help-echo help-text
)))
284 'local-map org-clock-mode-line-map
285 'mouse-face
(if (featurep 'xemacs
) 'highlight
'mode-line-highlight
)))
286 (force-mode-line-update)))
288 (defvar org-clock-mode-line-entry nil
289 "Information for the modeline about the running clock.")
291 (defun org-clock-in (&optional select
)
292 "Start the clock on the current item.
293 If necessary, clock-out of the currently active clock.
294 With prefix arg SELECT, offer a list of recently clocked tasks to
295 clock into. When SELECT is `C-u C-u', clock into the current task and mark
296 is as the default task, a special task that will always be offered in
297 the clocking selection, associated with the letter `d'."
300 (let ((interrupting (marker-buffer org-clock-marker
))
301 ts selected-task target-pos
)
302 (when (equal select
'(4))
303 (setq selected-task
(org-clock-select-task "Clock-in on task: "))
305 (setq selected-task
(copy-marker selected-task
))
308 ;; We are interrupting the clocking of a different task.
309 ;; Save a marker to this task, so that we can go back.
310 (move-marker org-clock-interrupted-task
311 (marker-position org-clock-marker
)
312 (marker-buffer org-clock-marker
))
315 (when (equal select
'(16))
316 ;; Mark as default clocking task
318 (org-back-to-heading t
)
319 (move-marker org-clock-default-task
(point))))
321 (setq target-pos
(point)) ;; we want to clock in at this location
323 (when (and selected-task
(marker-buffer selected-task
))
324 ;; There is a selected task, move to the correct buffer
325 ;; and set the new target position.
326 (set-buffer (org-base-buffer (marker-buffer selected-task
)))
327 (setq target-pos
(marker-position selected-task
))
328 (move-marker selected-task nil
))
332 (goto-char target-pos
)
333 (org-back-to-heading t
)
334 (or interrupting
(move-marker org-clock-interrupted-task nil
))
335 (org-clock-history-push)
336 (cond ((functionp org-clock-in-switch-to-state
)
337 (looking-at org-complex-heading-regexp
)
338 (let ((newstate (funcall org-clock-in-switch-to-state
340 (if newstate
(org-todo newstate
))))
341 ((and org-clock-in-switch-to-state
342 (not (looking-at (concat outline-regexp
"[ \t]*"
343 org-clock-in-switch-to-state
345 (org-todo org-clock-in-switch-to-state
)))
346 (setq org-clock-heading-for-remember
347 (and (looking-at org-complex-heading-regexp
)
349 (org-trim (buffer-substring (match-end 1)
351 (setq org-clock-heading
352 (cond ((and org-clock-heading-function
353 (functionp org-clock-heading-function
))
354 (funcall org-clock-heading-function
))
355 ((looking-at org-complex-heading-regexp
)
358 (setq org-clock-heading
(org-propertize org-clock-heading
360 (org-clock-find-position org-clock-in-resume
)
362 ((and org-clock-in-resume
364 (concat "^[ \t]* " org-clock-string
365 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
366 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
367 (message "Matched %s" (match-string 1))
368 (setq ts
(concat "[" (match-string 1) "]"))
369 (goto-char (match-end 1))
370 (setq org-clock-start-time
372 (org-parse-time-string (match-string 1)))))
373 ((eq org-clock-in-resume
'auto-restart
)
374 ;; called from org-clock-load during startup,
375 ;; do not interrupt, but warn!
376 (message "Cannot restart clock because task does not contain unfinished clock")
381 (insert-before-markers "\n")
383 (org-indent-line-function)
384 (when (and (save-excursion
387 (beginning-of-line 1)
388 (org-indent-line-to (- (org-get-indentation) 2)))
389 (insert org-clock-string
" ")
390 (setq org-clock-start-time
(current-time))
391 (setq ts
(org-insert-time-stamp org-clock-start-time
'with-hm
'inactive
))))
392 (move-marker org-clock-marker
(point) (buffer-base-buffer))
393 (or global-mode-string
(setq global-mode-string
'("")))
394 (or (memq 'org-mode-line-string global-mode-string
)
395 (setq global-mode-string
396 (append global-mode-string
'(org-mode-line-string))))
397 (org-clock-update-mode-line)
398 (setq org-clock-mode-line-timer
399 (run-with-timer 60 60 'org-clock-update-mode-line
))
400 (message "Clock started at %s" ts
)))))))
402 (defun org-clock-find-position (find-unclosed)
403 "Find the location where the next clock line should be inserted.
404 When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
405 line and position cursor in that line."
406 (org-back-to-heading t
)
408 (let ((beg (save-excursion
409 (beginning-of-line 2)
410 (or (bolp) (newline))
412 (end (progn (outline-next-heading) (point)))
413 (re (concat "^[ \t]*" org-clock-string
))
415 (drawer (if (stringp org-clock-into-drawer
)
416 org-clock-into-drawer
"LOGBOOK"))
419 (when (and find-unclosed
421 (concat "^[ \t]* " org-clock-string
422 " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
423 " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
425 (beginning-of-line 1)
427 (when (eobp) (newline) (setq end
(max (point) end
)))
428 (when (re-search-forward (concat "^[ \t]*:" drawer
":") end t
)
429 ;; we seem to have a CLOCK drawer, so go there.
430 (beginning-of-line 2)
431 (or org-log-states-order-reversed
432 (and (re-search-forward org-property-end-re nil t
)
433 (goto-char (match-beginning 0))))
435 ;; Lets count the CLOCK lines
437 (while (re-search-forward re end t
)
438 (setq first
(or first
(match-beginning 0))
439 last
(match-beginning 0)
441 (when (and (integerp org-clock-into-drawer
)
443 (>= (1+ cnt
) org-clock-into-drawer
))
444 ;; Wrap current entries into a new drawer
446 (setq ind-last
(org-get-indentation))
447 (beginning-of-line 2)
448 (if (and (>= (org-get-indentation) ind-last
)
452 (beginning-of-line 0)
453 (org-indent-line-to ind-last
)
455 (insert ":" drawer
":\n")
456 (beginning-of-line 0)
457 (org-indent-line-function)
459 (beginning-of-line 2)
460 (or org-log-states-order-reversed
461 (and (re-search-forward org-property-end-re nil t
)
462 (goto-char (match-beginning 0))))
466 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
467 (not (equal (match-string 1) org-clock-string
)))
468 ;; Planning info, skip to after it
469 (beginning-of-line 2)
470 (or (bolp) (newline)))
471 (when (or (eq org-clock-into-drawer t
)
472 (stringp org-clock-into-drawer
)
473 (and (integerp org-clock-into-drawer
)
474 (< org-clock-into-drawer
2)))
475 (insert ":" drawer
":\n:END:\n")
476 (beginning-of-line -
1)
477 (org-indent-line-function)
479 (beginning-of-line 2)
480 (org-indent-line-function)
482 (or org-log-states-order-reversed
483 (and (re-search-forward org-property-end-re nil t
)
484 (goto-char (match-beginning 0))))))))
486 (defun org-clock-out (&optional fail-quietly
)
487 "Stop the currently running clock.
488 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
491 (if (not (marker-buffer org-clock-marker
))
492 (if fail-quietly
(throw 'exit t
) (error "No active clock")))
493 (let (ts te s h m remove
)
495 (set-buffer (marker-buffer org-clock-marker
))
498 (goto-char org-clock-marker
)
499 (beginning-of-line 1)
500 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp
))
501 (equal (match-string 1) org-clock-string
))
502 (setq ts
(match-string 2))
503 (if fail-quietly
(throw 'exit nil
) (error "Clock start time is gone")))
504 (goto-char (match-end 0))
505 (delete-region (point) (point-at-eol))
507 (setq te
(org-insert-time-stamp (current-time) 'with-hm
'inactive
))
508 (setq s
(- (time-to-seconds (apply 'encode-time
(org-parse-time-string te
)))
509 (time-to-seconds (apply 'encode-time
(org-parse-time-string ts
))))
514 (insert " => " (format "%2d:%02d" h m
))
515 (when (setq remove
(and org-clock-out-remove-zero-time-clocks
517 (beginning-of-line 1)
518 (delete-region (point) (point-at-eol))
519 (and (looking-at "\n") (> (point-max) (1+ (point)))
521 (move-marker org-clock-marker nil
)
522 (when org-log-note-clock-out
523 (org-add-log-setup 'clock-out nil nil nil nil
524 (concat "# Task: " (org-get-heading t
) "\n\n")))
525 (when org-clock-mode-line-timer
526 (cancel-timer org-clock-mode-line-timer
)
527 (setq org-clock-mode-line-timer nil
))
528 (setq global-mode-string
529 (delq 'org-mode-line-string global-mode-string
))
530 (force-mode-line-update)
531 (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format
"%s") te h m
532 (if remove
" => LINE REMOVED" "")))))))
534 (defun org-clock-cancel ()
535 "Cancel the running clock be removing the start timestamp."
537 (if (not (marker-buffer org-clock-marker
))
538 (error "No active clock"))
540 (set-buffer (marker-buffer org-clock-marker
))
541 (goto-char org-clock-marker
)
542 (delete-region (1- (point-at-bol)) (point-at-eol)))
543 (setq global-mode-string
544 (delq 'org-mode-line-string global-mode-string
))
545 (force-mode-line-update)
546 (message "Clock canceled"))
548 (defun org-clock-goto (&optional select
)
549 "Go to the currently clocked-in entry, or to the most recently clocked one.
550 With prefix arg SELECT, offer recently clocked tasks for selection."
555 (or (org-clock-select-task "Select task to go to: ")
556 (error "No task selected")))
557 ((marker-buffer org-clock-marker
) org-clock-marker
)
558 ((and org-clock-goto-may-find-recent-task
559 (car org-clock-history
)
560 (marker-buffer (car org-clock-history
)))
562 (car org-clock-history
))
563 (t (error "No active or recent clock task")))))
564 (switch-to-buffer (marker-buffer m
))
565 (if (or (< m
(point-min)) (> m
(point-max))) (widen))
568 (org-back-to-heading)
569 (org-cycle-hide-drawers 'children
)
572 (message "No running clock, this is the most recently clocked task"))))
575 (defvar org-clock-file-total-minutes nil
576 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
577 (make-variable-buffer-local 'org-clock-file-total-minutes
)
579 (defun org-clock-sum (&optional tstart tend
)
580 "Sum the times for each subtree.
581 Puts the resulting times in minutes as a text property on each headline."
583 (let* ((bmp (buffer-modified-p))
584 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
586 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
588 (ltimes (make-vector lmax
0))
593 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t
))
595 (goto-char (point-max))
596 (while (re-search-backward re nil t
)
600 (setq ts
(match-string 2)
603 (apply 'encode-time
(org-parse-time-string ts
)))
605 (apply 'encode-time
(org-parse-time-string te
)))
606 ts
(if tstart
(max ts tstart
) ts
)
607 te
(if tend
(min te tend
) te
)
609 t1
(if (> dt
0) (+ t1
(floor (/ dt
60))) t1
)))
612 (setq t1
(+ t1
(string-to-number (match-string 5))
613 (* 60 (string-to-number (match-string 4))))))
615 (setq level
(- (match-end 1) (match-beginning 1)))
616 (when (or (> t1
0) (> (aref ltimes level
) 0))
617 (loop for l from
0 to level do
618 (aset ltimes l
(+ (aref ltimes l
) t1
)))
619 (setq t1
0 time
(aref ltimes level
))
620 (loop for l from level to
(1- lmax
) do
622 (goto-char (match-beginning 0))
623 (put-text-property (point) (point-at-eol) :org-clock-minutes time
)))))
624 (setq org-clock-file-total-minutes
(aref ltimes
0)))
625 (set-buffer-modified-p bmp
)))
627 (defun org-clock-display (&optional total-only
)
628 "Show subtree times in the entire buffer.
629 If TOTAL-ONLY is non-nil, only show the total time for the entire file
632 (org-clock-remove-overlays)
637 (goto-char (point-min))
638 (while (or (and (equal (setq p
(point)) (point-min))
639 (get-text-property p
:org-clock-minutes
))
640 (setq p
(next-single-property-change
641 (point) :org-clock-minutes
)))
643 (when (setq time
(get-text-property p
:org-clock-minutes
))
644 (org-clock-put-overlay time
(funcall outline-level
))))
645 (setq h
(/ org-clock-file-total-minutes
60)
646 m
(- org-clock-file-total-minutes
(* 60 h
)))
647 ;; Arrange to remove the overlays upon next change.
648 (when org-remove-highlights-with-change
649 (org-add-hook 'before-change-functions
'org-clock-remove-overlays
651 (message (concat "Total file time: " org-time-clocksum-format
" (%d hours and %d minutes)") h m h m
)))
653 (defvar org-clock-overlays nil
)
654 (make-variable-buffer-local 'org-clock-overlays
)
656 (defun org-clock-put-overlay (time &optional level
)
657 "Put an overlays on the current line, displaying TIME.
658 If LEVEL is given, prefix time with a corresponding number of stars.
659 This creates a new overlay and stores it in `org-clock-overlays', so that it
660 will be easy to remove."
661 (let* ((c 60) (h (floor (/ time
60))) (m (- time
(* 60 h
)))
662 (l (if level
(org-get-valid-level level
0) 0))
663 (fmt (concat "%s " org-time-clocksum-format
"%s"))
666 (org-move-to-column c
)
667 (unless (eolp) (skip-chars-backward "^ \t"))
668 (skip-chars-backward " \t")
669 (setq ov
(org-make-overlay (1- (point)) (point-at-eol))
670 tx
(concat (buffer-substring (1- (point)) (point))
671 (make-string (+ off
(max 0 (- c
(current-column)))) ?.
)
672 (org-add-props (format fmt
673 (make-string l ?
*) h m
674 (make-string (- 16 l
) ?\
))
675 (list 'face
'org-clock-overlay
))
677 (if (not (featurep 'xemacs
))
678 (org-overlay-put ov
'display tx
)
679 (org-overlay-put ov
'invisible t
)
680 (org-overlay-put ov
'end-glyph
(make-glyph tx
)))
681 (push ov org-clock-overlays
)))
683 (defun org-clock-remove-overlays (&optional beg end noremove
)
684 "Remove the occur highlights from the buffer.
685 BEG and END are ignored. If NOREMOVE is nil, remove this function
686 from the `before-change-functions' in the current buffer."
688 (unless org-inhibit-highlight-removal
689 (mapc 'org-delete-overlay org-clock-overlays
)
690 (setq org-clock-overlays nil
)
692 (remove-hook 'before-change-functions
693 'org-clock-remove-overlays
'local
))))
695 (defvar state
) ;; dynamically scoped into this function
696 (defun org-clock-out-if-current ()
697 "Clock out if the current entry contains the running clock.
698 This is used to stop the clock after a TODO entry is marked DONE,
699 and is only done if the variable `org-clock-out-when-done' is not nil."
700 (when (and org-clock-out-when-done
701 (member state org-done-keywords
)
702 (equal (or (buffer-base-buffer (marker-buffer org-clock-marker
))
703 (marker-buffer org-clock-marker
))
704 (or (buffer-base-buffer (current-buffer))
706 (< (point) org-clock-marker
)
707 (> (save-excursion (outline-next-heading) (point))
709 ;; Clock out, but don't accept a logging message for this.
710 (let ((org-log-note-clock-out nil
))
713 (add-hook 'org-after-todo-state-change-hook
714 'org-clock-out-if-current
)
717 (defun org-get-clocktable (&rest props
)
718 "Get a formatted clocktable with parameters according to PROPS.
719 The table is created in a temporary buffer, fully formatted and
720 fontified, and then returned."
722 (setq props
(plist-put props
:name
"clocktable"))
723 (unless (plist-member props
:maxlevel
)
724 (setq props
(plist-put props
:maxlevel
2)))
725 (unless (plist-member props
:scope
)
726 (setq props
(plist-put props
:scope
'agenda
)))
729 (org-create-dblock props
)
731 (font-lock-fontify-buffer)
733 (buffer-substring (point) (progn
734 (re-search-forward "^#\\+END" nil t
)
737 (defun org-clock-report (&optional arg
)
738 "Create a table containing a report about clocked time.
739 If the cursor is inside an existing clocktable block, then the table
740 will be updated. If not, a new clocktable will be inserted.
741 When called with a prefix argument, move to the first clock table in the
742 buffer and update it."
744 (org-clock-remove-overlays)
746 (org-find-dblock "clocktable")
748 (if (org-in-clocktable-p)
749 (goto-char (org-in-clocktable-p))
750 (org-create-dblock (list :name
"clocktable"
751 :maxlevel
2 :scope
'file
)))
754 (defun org-in-clocktable-p ()
755 "Check if the cursor is in a clocktable."
756 (let ((pos (point)) start
)
759 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t
)
760 (setq start
(match-beginning 0))
761 (re-search-forward "^#\\+END:.*" nil t
)
762 (>= (match-end 0) pos
)
765 (defun org-clock-special-range (key &optional time as-strings
)
766 "Return two times bordering a special time range.
767 Key is a symbol specifying the range and can be one of `today', `yesterday',
768 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
769 A week starts Monday 0:00 and ends Sunday 24:00.
770 The range is determined relative to TIME. TIME defaults to the current time.
771 The return value is a cons cell with two internal times like the ones
772 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
773 the returned times will be formatted strings."
774 (if (integerp key
) (setq key
(intern (number-to-string key
))))
775 (let* ((tm (decode-time (or time
(current-time))))
776 (s 0) (m (nth 1 tm
)) (h (nth 2 tm
))
777 (d (nth 3 tm
)) (month (nth 4 tm
)) (y (nth 5 tm
))
779 (skey (symbol-name key
))
781 s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
)
783 ((string-match "^[0-9]+$" skey
)
784 (setq y
(string-to-number skey
) m
1 d
1 key
'year
))
785 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
786 (setq y
(string-to-number (match-string 1 skey
))
787 month
(string-to-number (match-string 2 skey
))
789 ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey
)
791 (setq y
(string-to-number (match-string 1 skey
))
792 w
(string-to-number (match-string 2 skey
)))
793 (setq date
(calendar-gregorian-from-absolute
794 (calendar-absolute-from-iso (list w
1 y
))))
795 (setq d
(nth 1 date
) month
(car date
) y
(nth 2 date
)
798 ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey
)
799 (setq y
(string-to-number (match-string 1 skey
))
800 month
(string-to-number (match-string 2 skey
))
801 d
(string-to-number (match-string 3 skey
))
803 ((string-match "\\([-+][0-9]+\\)$" skey
)
804 (setq shift
(string-to-number (match-string 1 skey
))
805 key
(intern (substring skey
0 (match-beginning 1))))))
807 (cond ((eq key
'yesterday
) (setq key
'today shift -
1))
808 ((eq key
'lastweek
) (setq key
'week shift -
1))
809 ((eq key
'lastmonth
) (setq key
'month shift -
1))
810 ((eq key
'lastyear
) (setq key
'year shift -
1))))
812 ((memq key
'(day today
))
813 (setq d
(+ d shift
) h
0 m
0 h1
24 m1
0))
814 ((memq key
'(week thisweek
))
815 (setq diff
(+ (* -
7 shift
) (if (= dow
0) 6 (1- dow
)))
816 m
0 h
0 d
(- d diff
) d1
(+ 7 d
)))
817 ((memq key
'(month thismonth
))
818 (setq d
1 h
0 m
0 d1
1 month
(+ month shift
) month1
(1+ month
) h1
0 m1
0))
819 ((memq key
'(year thisyear
))
820 (setq m
0 h
0 d
1 month
1 y
(+ y shift
) y1
(1+ y
)))
821 (t (error "No such time block %s" key
)))
822 (setq ts
(encode-time s m h d month y
)
823 te
(encode-time (or s1 s
) (or m1 m
) (or h1 h
)
824 (or d1 d
) (or month1 month
) (or y1 y
)))
825 (setq fm
(cdr org-time-stamp-formats
))
827 ((memq key
'(day today
))
828 (setq txt
(format-time-string "%A, %B %d, %Y" ts
)))
829 ((memq key
'(week thisweek
))
830 (setq txt
(format-time-string "week %G-W%V" ts
)))
831 ((memq key
'(month thismonth
))
832 (setq txt
(format-time-string "%B %Y" ts
)))
833 ((memq key
'(year thisyear
))
834 (setq txt
(format-time-string "the year %Y" ts
))))
836 (list (format-time-string fm ts
) (format-time-string fm te
) txt
)
839 (defun org-clocktable-shift (dir n
)
840 "Try to shift the :block date of the clocktable at point.
841 Point must be in the #+BEGIN: line of a clocktable, or this function
843 DIR is a direction, a symbol `left', `right', `up', or `down'.
844 Both `left' and `down' shift the block toward the past, `up' and `right'
845 push it toward the future.
846 N is the number of shift steps to take. The size of the step depends on
847 the currently selected interval size."
848 (setq n
(prefix-numeric-value n
))
849 (and (memq dir
'(left down
)) (setq n
(- n
)))
851 (goto-char (point-at-bol))
852 (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
853 (error "Line needs a :block definition before this command works")
854 (let* ((b (match-beginning 1)) (e (match-end 1))
856 block shift ins y mw d date wp m
)
858 ((equal s
"yesterday") (setq s
"today-1"))
859 ((equal s
"lastweek") (setq s
"thisweek-1"))
860 ((equal s
"lastmonth") (setq s
"thismonth-1"))
861 ((equal s
"lastyear") (setq s
"thisyear-1")))
863 ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s
)
864 (setq block
(match-string 1 s
)
865 shift
(if (match-end 2)
866 (string-to-number (match-string 2 s
))
868 (setq shift
(+ shift n
))
869 (setq ins
(if (= shift
0) block
(format "%s%+d" block shift
))))
870 ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s
)
871 ;; 1 1 2 3 3 4 4 5 6 6 5 2
872 (setq y
(string-to-number (match-string 1 s
))
873 wp
(and (match-end 3) (match-string 3 s
))
874 mw
(and (match-end 4) (string-to-number (match-string 4 s
)))
875 d
(and (match-end 6) (string-to-number (match-string 6 s
))))
877 (d (setq ins
(format-time-string
879 (encode-time 0 0 0 (+ d n
) m y
))))
880 ((and wp mw
(> (length wp
) 0))
882 (setq date
(calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n
) 1 y
))))
883 (setq ins
(format-time-string
885 (encode-time 0 0 0 (nth 1 date
) (car date
) (nth 2 date
)))))
887 (setq ins
(format-time-string
889 (encode-time 0 0 0 1 (+ mw n
) y
))))
891 (setq ins
(number-to-string (+ y n
))))))
892 (t (error "Cannot shift clocktable block")))
896 (delete-region (point) (+ (point) (- e b
)))
897 (beginning-of-line 1)
901 (defun org-dblock-write:clocktable
(params)
902 "Write the standard clocktable."
904 (let* ((hlchars '((1 .
"*") (2 .
"/")))
907 (scope (plist-get params
:scope
))
908 (tostring (plist-get params
:tostring
))
909 (multifile (plist-get params
:multifile
))
910 (header (plist-get params
:header
))
911 (maxlevel (or (plist-get params
:maxlevel
) 3))
912 (step (plist-get params
:step
))
913 (emph (plist-get params
:emphasize
))
914 (ts (plist-get params
:tstart
))
915 (te (plist-get params
:tend
))
916 (block (plist-get params
:block
))
917 (link (plist-get params
:link
))
918 ipos time p level hlc hdl content recalc formula pcol
919 cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st
)
920 (setq org-clock-file-total-minutes nil
)
922 (unless (or block
(and ts te
))
923 (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
924 (org-clocktable-steps params
)
927 (setq cc
(org-clock-special-range block nil t
)
928 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
929 (when (integerp ts
) (setq ts
(calendar-gregorian-from-absolute ts
)))
930 (when (integerp te
) (setq te
(calendar-gregorian-from-absolute te
)))
931 (when (and ts
(listp ts
))
932 (setq ts
(format "%4d-%02d-%02d" (nth 2 ts
) (car ts
) (nth 1 ts
))))
933 (when (and te
(listp te
))
934 (setq te
(format "%4d-%02d-%02d" (nth 2 te
) (car te
) (nth 1 te
))))
935 ;; Now the times are strings we can parse.
936 (if ts
(setq ts
(time-to-seconds
937 (apply 'encode-time
(org-parse-time-string ts
)))))
938 (if te
(setq te
(time-to-seconds
939 (apply 'encode-time
(org-parse-time-string te
)))))
940 (move-marker ins
(point))
943 ;; Get the right scope
946 ((and scope
(listp scope
) (symbolp (car scope
)))
947 (setq scope
(eval scope
)))
949 (setq scope
(org-agenda-files t
)))
950 ((eq scope
'agenda-with-archives
)
951 (setq scope
(org-agenda-files t
))
952 (setq scope
(org-add-archive-files scope
)))
953 ((eq scope
'file-with-archives
)
954 (setq scope
(org-add-archive-files (list (buffer-file-name)))
956 (setq scope-is-list
(and scope
(listp scope
)))
960 ((eq scope
'file
) (widen))
961 ((eq scope
'subtree
) (org-narrow-to-subtree))
963 (while (org-up-heading-safe))
964 (org-narrow-to-subtree))
965 ((and (symbolp scope
) (string-match "^tree\\([0-9]+\\)$"
966 (symbol-name scope
)))
967 (setq level
(string-to-number (match-string 1 (symbol-name scope
))))
969 (while (org-up-heading-safe)
970 (looking-at outline-regexp
)
971 (if (<= (org-reduced-level (funcall outline-level
)) level
)
973 (org-narrow-to-subtree))
977 (p1 (copy-sequence params
))
979 (setq p1
(plist-put p1
:tostring t
))
980 (setq p1
(plist-put p1
:multifile t
))
981 (setq p1
(plist-put p1
:scope
'file
))
982 (org-prepare-agenda-buffers files
)
983 (while (setq file
(pop files
))
984 (with-current-buffer (find-buffer-visiting file
)
985 (setq tbl1
(org-dblock-write:clocktable p1
))
987 (push (org-clocktable-add-file
989 (concat "| |*File time*|*"
990 (org-minutes-to-hh:mm-string
991 org-clock-file-total-minutes
)
994 (setq total-time
(+ (or total-time
0)
995 org-clock-file-total-minutes
))))))))
998 (unless scope-is-list
999 (org-clock-sum ts te
)
1000 (goto-char (point-min))
1002 (while (or (and (bobp) (prog1 st
(setq st nil
))
1003 (get-text-property (point) :org-clock-minutes
)
1004 (setq p
(point-min)))
1005 (setq p
(next-single-property-change (point) :org-clock-minutes
)))
1007 (when (setq time
(get-text-property p
:org-clock-minutes
))
1009 (beginning-of-line 1)
1010 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
1011 (setq level
(org-reduced-level
1012 (- (match-end 1) (match-beginning 1))))
1013 (<= level maxlevel
))
1014 (setq hlc
(if emph
(or (cdr (assoc level hlchars
)) "") "")
1017 (org-make-link-string
1018 (format "file:%s::%s"
1021 (org-make-org-heading-search-string
1024 (if (and (not multifile
) (= level
1)) (push "|-" tbl
))
1026 "| " (int-to-string level
) "|" hlc hdl hlc
" |"
1027 (make-string (1- level
) ?|
)
1028 hlc
(org-minutes-to-hh:mm-string time
) hlc
1030 (setq tbl
(nreverse tbl
))
1032 (if tbl
(mapconcat 'identity tbl
"\n") nil
)
1034 (insert-before-markers
1037 "Clock summary at ["
1039 (format-time-string (cdr org-time-stamp-formats
))
1042 (if block
(concat ", for " range-text
".") "")
1044 (if scope-is-list
"|File" "")
1045 "|L|Headline|Time|\n")
1046 (setq total-time
(or total-time org-clock-file-total-minutes
))
1047 (insert-before-markers
1049 (if scope-is-list
"|" "")
1052 (org-minutes-to-hh:mm-string
(or total-time
0))
1054 (setq tbl
(delq nil tbl
))
1055 (if (and (stringp (car tbl
)) (> (length (car tbl
)) 1)
1056 (equal (substring (car tbl
) 0 2) "|-"))
1058 (insert-before-markers (mapconcat
1059 'identity
(delq nil tbl
)
1060 (if scope-is-list
"\n|-\n" "\n")))
1061 (backward-delete-char 1)
1062 (if (setq formula
(plist-get params
:formula
))
1065 (setq pcol
(+ (if scope-is-list
1 0) maxlevel
3))
1068 "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
1071 (+ 3 (if scope-is-list
1 0))
1072 (+ (if scope-is-list
1 0) 3)
1076 (insert "\n#+TBLFM: " formula
)
1078 (t (error "invalid formula in clocktable")))
1079 ;; Should we rescue an old formula?
1080 (when (stringp (setq content
(plist-get params
:content
)))
1081 (when (string-match "^\\(#\\+TBLFM:.*\\)" content
)
1083 (insert "\n" (match-string 1 (plist-get params
:content
)))
1084 (beginning-of-line 0))))
1086 (skip-chars-forward "^|")
1090 (save-excursion (org-table-goto-column pcol nil
'force
)
1092 (org-table-recalculate 'all
))
1093 (when rm-file-column
1095 (org-table-delete-column)))))))
1097 (defun org-clocktable-steps (params)
1098 (let* ((p1 (copy-sequence params
))
1099 (ts (plist-get p1
:tstart
))
1100 (te (plist-get p1
:tend
))
1101 (step0 (plist-get p1
:step
))
1102 (step (cdr (assoc step0
'((day .
86400) (week .
604800)))))
1103 (block (plist-get p1
:block
))
1106 (setq cc
(org-clock-special-range block nil t
)
1107 ts
(car cc
) te
(nth 1 cc
) range-text
(nth 2 cc
)))
1108 (if ts
(setq ts
(time-to-seconds
1109 (apply 'encode-time
(org-parse-time-string ts
)))))
1110 (if te
(setq te
(time-to-seconds
1111 (apply 'encode-time
(org-parse-time-string te
)))))
1112 (setq p1
(plist-put p1
:header
""))
1113 (setq p1
(plist-put p1
:step nil
))
1114 (setq p1
(plist-put p1
:block nil
))
1116 (or (bolp) (insert "\n"))
1117 (setq p1
(plist-put p1
:tstart
(format-time-string
1118 (org-time-stamp-format nil t
)
1119 (seconds-to-time ts
))))
1120 (setq p1
(plist-put p1
:tend
(format-time-string
1121 (org-time-stamp-format nil t
)
1122 (seconds-to-time (setq ts
(+ ts step
))))))
1123 (insert "\n" (if (eq step0
'day
) "Daily report: " "Weekly report starting on: ")
1124 (plist-get p1
:tstart
) "\n")
1125 (org-dblock-write:clocktable p1
)
1126 (re-search-forward "#\\+END:")
1129 (defun org-clocktable-add-file (file table
)
1131 (let ((lines (org-split-string table
"\n"))
1132 (ff (file-name-nondirectory file
)))
1133 (mapconcat 'identity
1135 (if (string-match org-table-dataline-regexp x
)
1141 (defun org-clock-time%
(total &rest strings
)
1142 "Compute a time fraction in percent.
1143 TOTAL s a time string like 10:21 specifying the total times.
1144 STRINGS is a list of strings that should be checked for a time.
1145 The first string that does have a time will be used.
1146 This function is made for clock tables."
1147 (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
1151 (if (not (string-match re total
))
1153 (setq tot
(+ (string-to-number (match-string 2 total
))
1154 (* 60 (string-to-number (match-string 1 total
)))))
1155 (if (= tot
0.
) (throw 'exit
0.
)))
1156 (while (setq s
(pop strings
))
1157 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s
)
1159 (/ (* 100.0 (+ (string-to-number (match-string 2 s
))
1160 (* 60 (string-to-number (match-string 1 s
)))))
1164 (defun org-clock-save ()
1165 "Persist various clock-related data to disk.
1166 The details of what will be saved are regulated by the variable
1167 `org-clock-persist'."
1168 (when org-clock-persist
1170 (with-current-buffer (find-file (expand-file-name org-clock-persist-file
))
1172 (delete-region (point-min) (point-max))
1174 (insert (format ";; org-persist.el - %s at %s\n"
1175 system-name
(format-time-string
1176 (cdr org-time-stamp-formats
))))
1177 (if (and (setq b
(marker-buffer org-clock-marker
))
1178 (setq b
(or (buffer-base-buffer b
) b
))
1180 (buffer-file-name b
)
1181 (or (not org-clock-persist-query-save
)
1182 (y-or-n-p (concat "Save current clock ("
1183 (substring-no-properties org-clock-heading
)
1185 (insert "(setq resume-clock '(\""
1186 (buffer-file-name (marker-buffer org-clock-marker
))
1187 "\" . " (int-to-string (marker-position org-clock-marker
))
1189 ;; Store clocked task history. Tasks are stored reversed to make
1191 (when (and org-clock-history
(eq org-clock-persist t
))
1193 "(setq stored-clock-history '("
1196 (when (and (setq b
(marker-buffer m
))
1197 (setq b
(or (buffer-base-buffer b
) b
))
1199 (buffer-file-name b
))
1200 (concat "(\"" (buffer-file-name b
)
1201 "\" . " (int-to-string (marker-position m
))
1203 (reverse org-clock-history
) " ") "))\n"))
1205 (kill-buffer (current-buffer)))))))
1207 (defvar org-clock-loaded nil
1208 "Was the clock file loaded?")
1210 (defun org-clock-load ()
1211 "Load clock-related data from disk, maybe resuming a stored clock."
1212 (when (and org-clock-persist
(not org-clock-loaded
))
1213 (let ((filename (expand-file-name org-clock-persist-file
))
1214 (org-clock-in-resume 'auto-restart
)
1215 resume-clock stored-clock-history
)
1216 (if (not (file-readable-p filename
))
1217 (message "Not restoring clock data; %s not found"
1218 org-clock-persist-file
)
1219 (message "%s" "Restoring clock data")
1220 (setq org-clock-loaded t
)
1221 (load-file filename
)
1223 (when stored-clock-history
1224 (save-window-excursion
1225 (mapc (lambda (task)
1226 (if (file-exists-p (car task
))
1227 (org-clock-history-push (cdr task
)
1228 (find-file (car task
)))))
1229 stored-clock-history
)))
1231 (when (and resume-clock org-clock-persist
1232 (file-exists-p (car resume-clock
))
1233 (or (not org-clock-persist-query-resume
)
1237 (with-current-buffer (find-file (car resume-clock
))
1239 (goto-char (cdr resume-clock
))
1240 (org-back-to-heading t
)
1241 (and (looking-at org-complex-heading-regexp
)
1244 (when (file-exists-p (car resume-clock
))
1245 (with-current-buffer (find-file (car resume-clock
))
1246 (goto-char (cdr resume-clock
))
1248 (if (org-invisible-p)
1249 (org-show-context)))))))))
1252 (defun org-clock-persistence-insinuate ()
1253 "Set up hooks for clock persistence"
1254 (add-hook 'org-mode-hook
'org-clock-load
)
1255 (add-hook 'kill-emacs-hook
'org-clock-save
))
1257 (provide 'org-clock
)
1259 ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
1261 ;;; org-clock.el ends here