org-clock.el 103 KB
Newer Older
1 2
;;; org-clock.el --- The time clocking code for Org-mode

3
;; Copyright (C) 2004-2012  Free Software Foundation, Inc.
4 5 6 7 8 9 10

;; Author: Carsten Dominik <carsten at orgmode dot org>
;; Keywords: outlines, hypermedia, calendar, wp
;; Homepage: http://orgmode.org
;;
;; This file is part of GNU Emacs.
;;
11
;; GNU Emacs is free software: you can redistribute it and/or modify
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23 24 25 26 27 28
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Commentary:

;; This file contains the time clocking code for Org-mode

29
(require 'org-exp)
30 31
;;; Code:

32
(eval-when-compile
33
  (require 'cl))
34

Carsten Dominik's avatar
Carsten Dominik committed
35
(declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
Carsten Dominik's avatar
Carsten Dominik committed
36
(declare-function notifications-notify "notifications" (&rest params))
Bastien Guerry's avatar
Bastien Guerry committed
37
(declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
38
(defvar org-time-stamp-formats)
39
(defvar org-ts-what)
40
(defvar org-frame-title-format-backup frame-title-format)
41 42 43 44 45 46

(defgroup org-clock nil
  "Options concerning clocking working time in Org-mode."
  :tag "Org Clock"
  :group 'org-progress)

47
(defcustom org-clock-into-drawer org-log-into-drawer
48
  "Should clocking info be wrapped into a drawer?
49
When t, clocking info will always be inserted into a :LOGBOOK: drawer.
50 51 52
If necessary, the drawer will be created.
When nil, the drawer will not be created, but used when present.
When an integer and the number of clocking entries in an item
53 54 55 56 57
reaches or exceeds this number, a drawer will be created.
When a string, it names the drawer to be used.

The default for this variable is the value of `org-log-into-drawer',
which see."
58 59 60 61 62
  :group 'org-todo
  :group 'org-clock
  :type '(choice
	  (const :tag "Always" t)
	  (const :tag "Only when drawer exists" nil)
63 64 65
	  (integer :tag "When at least N clock entries")
	  (const :tag "Into LOGBOOK drawer" "LOGBOOK")
	  (string :tag "Into Drawer named...")))
66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
(defun org-clock-into-drawer ()
  "Return the value of `org-clock-into-drawer', but let properties overrule.
If the current entry has or inherits a CLOCK_INTO_DRAWER
property, it will be used instead of the default value; otherwise
if the current entry has or inherits a LOG_INTO_DRAWER property,
it will be used instead of the default value.
The default is the value of the customizable variable `org-clock-into-drawer',
which see."
  (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit))
	(q (org-entry-get nil "LOG_INTO_DRAWER" 'inherit)))
    (cond
     ((or (not (or p q)) (equal p "nil") (equal q "nil")) org-clock-into-drawer)
     ((or (equal p "t") (equal q "t")) "LOGBOOK")
     ((not p) q)
     (t p))))

83
(defcustom org-clock-out-when-done t
84
  "When non-nil, clock will be stopped when the clocked entry is marked DONE.
85 86 87 88 89
DONE here means any DONE-like state.
A nil value means clock will keep running until stopped explicitly with
`C-c C-x C-o', or until the clock is started in a different item.
Instead of t, this can also be a list of TODO states that should trigger
clocking out."
90
  :group 'org-clock
91 92 93 94 95
  :type '(choice
	  (const :tag "No" nil)
	  (const :tag "Yes, when done" t)
	  (repeat :tag "State list"
		  (string :tag "TODO keyword"))))
96 97

(defcustom org-clock-out-remove-zero-time-clocks nil
98
  "Non-nil means remove the clock line when the resulting time is zero."
99 100 101 102 103
  :group 'org-clock
  :type 'boolean)

(defcustom org-clock-in-switch-to-state nil
  "Set task to a special todo state while clocking it.
104
The value should be the state to which the entry should be
105
switched.  If the value is a function, it must take one
106 107
parameter (the current TODO state of the item) and return the
state to switch it to."
108 109 110 111
  :group 'org-clock
  :group 'org-todo
  :type '(choice
	  (const :tag "Don't force a state" nil)
112 113
	  (string :tag "State")
	  (symbol :tag "Function")))
114

115 116 117
(defcustom org-clock-out-switch-to-state nil
  "Set task to a special todo state after clocking out.
The value should be the state to which the entry should be
118
switched.  If the value is a function, it must take one
119 120 121 122 123 124 125 126 127
parameter (the current TODO state of the item) and return the
state to switch it to."
  :group 'org-clock
  :group 'org-todo
  :type '(choice
	  (const :tag "Don't force a state" nil)
	  (string :tag "State")
	  (symbol :tag "Function")))

128 129 130 131 132
(defcustom org-clock-history-length 5
  "Number of clock tasks to remember in history."
  :group 'org-clock
  :type 'integer)

133
(defcustom org-clock-goto-may-find-recent-task t
134
  "Non-nil means `org-clock-goto' can go to recent task if no active clock."
135 136 137
  :group 'org-clock
  :type 'boolean)

138 139 140 141 142 143 144
(defcustom org-clock-heading-function nil
  "When non-nil, should be a function to create `org-clock-heading'.
This is the string shown in the mode line when a clock is running.
The function is called with point at the beginning of the headline."
  :group 'org-clock
  :type 'function)

145
(defcustom org-clock-string-limit 0
146
  "Maximum length of clock strings in the mode line.  0 means no limit."
147 148
  :group 'org-clock
  :type 'integer)
149

150
(defcustom org-clock-in-resume nil
151 152 153
  "If non-nil, resume clock when clocking into task with open clock.
When clocking into a task with a clock entry which has not been closed,
the clock can be resumed from that point."
154 155 156 157
  :group 'org-clock
  :type 'boolean)

(defcustom org-clock-persist nil
158 159
  "When non-nil, save the running clock when Emacs is closed.
The clock is resumed when Emacs restarts.
160 161 162 163 164 165
When this is t, both the running clock, and the entire clock
history are saved.  When this is the symbol `clock', only the
running clock is saved.

When Emacs restarts with saved clock information, the file containing the
running clock as well as all files mentioned in the clock history will
166 167
be visited.
All this depends on running `org-clock-persistence-insinuate' in .emacs"
168
  :group 'org-clock
169 170
  :type '(choice
	  (const :tag "Just the running clock" clock)
171
	  (const :tag "Just the history" history)
172 173
	  (const :tag "Clock and history" t)
	  (const :tag "No persistence" nil)))
174

175 176
(defcustom org-clock-persist-file (convert-standard-filename
				   "~/.emacs.d/org-clock-save.el")
177
  "File to save clock data to."
178 179 180 181
  :group 'org-clock
  :type 'string)

(defcustom org-clock-persist-query-save nil
182
  "When non-nil, ask before saving the current clock on exit."
183 184 185 186
  :group 'org-clock
  :type 'boolean)

(defcustom org-clock-persist-query-resume t
187
  "When non-nil, ask before resuming any stored clock during load."
188 189 190
  :group 'org-clock
  :type 'boolean)

191 192 193 194 195 196 197 198 199 200 201 202 203
(defcustom org-clock-sound nil
  "Sound that will used for notifications.
Possible values:

nil        no sound played.
t          standard Emacs beep
file name  play this sound file.  If not possible, fall back to beep"
  :group 'org-clock
  :type '(choice
	  (const :tag "No sound" nil)
	  (const :tag "Standard beep" t)
	  (file :tag "Play sound file")))

204 205 206 207
(define-obsolete-variable-alias 'org-clock-modeline-total
  'org-clock-mode-line-total "24.3")

(defcustom org-clock-mode-line-total 'auto
208
  "Default setting for the time included for the mode line clock.
209 210 211 212
This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
Allowed values are:

current  Only the time in the current instance of the clock
213
today    All time clocked into this task today
214 215
repeat   All time clocked into this task since last repeat
all      All time ever recorded for this task
216
auto     Automatically, either `all', or `repeat' for repeating tasks"
217 218 219 220 221 222 223 224
  :group 'org-clock
  :type '(choice
	  (const :tag "Current clock" current)
	  (const :tag "Today's task time" today)
	  (const :tag "Since last repeat" repeat)
	  (const :tag "All task time" all)
	  (const :tag "Automatically, `all' or since `repeat'" auto)))

225 226
(defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
(defcustom org-clock-task-overrun-text nil
227
  "Extra mode line text to indicate that the clock is overrun.
228 229 230 231 232
The can be nil to indicate that instead of adding text, the clock time
should get a different face (`org-mode-line-clock-overrun').
When this is a string, it is prepended to the clock string as an indication,
also using the face `org-mode-line-clock-overrun'."
  :group 'org-clock
233
  :version "24.1"
234 235 236 237
  :type '(choice
	  (const :tag "Just mark the time string" nil)
	  (string :tag "Text to prepend")))

238 239 240 241 242 243 244 245 246
(defcustom org-show-notification-handler nil
  "Function or program to send notification with.
The function or program will be called with the notification
string as argument."
  :group 'org-clock
  :type '(choice
	  (string :tag "Program")
	  (function :tag "Function")))

Carsten Dominik's avatar
Carsten Dominik committed
247 248 249 250 251 252
(defgroup org-clocktable nil
  "Options concerning the clock table in Org-mode."
  :tag "Org Clock Table"
  :group 'org-clock)

(defcustom org-clocktable-defaults
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  (list
   :maxlevel 2
   :lang org-export-default-language
   :scope 'file
   :block nil
   :tstart nil
   :tend nil
   :step nil
   :stepskip0 nil
   :fileskip0 nil
   :tags nil
   :emphasize nil
   :link nil
   :narrow '40!
   :indent t
   :formula nil
   :timestamp nil
   :level nil
   :tcolumns nil
   :formatter nil)
Carsten Dominik's avatar
Carsten Dominik committed
273
  "Default properties for clock tables."
274
  :group 'org-clock
275
  :version "24.1"
276 277
  :type 'plist)

Carsten Dominik's avatar
Carsten Dominik committed
278 279 280 281
(defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
  "Function to turn clocking data into a table.
For more information, see `org-clocktable-write-default'."
  :group 'org-clocktable
282
  :version "24.1"
Carsten Dominik's avatar
Carsten Dominik committed
283 284
  :type 'function)

285 286 287 288 289 290 291 292
;; FIXME: translate es and nl last string "Clock summary at"
(defcustom org-clock-clocktable-language-setup
  '(("en" "File"     "L"  "Timestamp"  "Headline" "Time"  "ALL"   "Total time"   "File time" "Clock summary at")
    ("es" "Archivo"  "N"  "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
    ("fr" "Fichier"  "N"  "Horodatage" "En-tête"  "Durée" "TOUT"  "Durée totale" "Durée fichier" "Horodatage sommaire à")
    ("nl" "Bestand"  "N"  "Tijdstip"   "Hoofding" "Duur"  "ALLES" "Totale duur"  "Bestandstijd" "Clock summary at"))
  "Terms used in clocktable, translated to different languages."
  :group 'org-clocktable
293
  :version "24.1"
294 295
  :type 'alist)

Carsten Dominik's avatar
Carsten Dominik committed
296 297 298 299 300 301 302
(defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
  "Default properties for new clocktables.
These will be inserted into the BEGIN line, to make it easy for users to
play with them."
  :group 'org-clocktable
  :type 'plist)

303 304 305 306 307 308 309 310 311 312 313 314 315 316
(defcustom org-clock-idle-time nil
  "When non-nil, resolve open clocks if the user is idle more than X minutes."
  :group 'org-clock
  :type '(choice
	  (const :tag "Never" nil)
	  (integer :tag "After N minutes")))

(defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
  "When to automatically resolve open clocks found in Org buffers."
  :group 'org-clock
  :type '(choice
	  (const :tag "Never" nil)
	  (const :tag "Always" t)
	  (const :tag "When no clock is running" when-no-clock-is-running)))
317

318 319 320
(defcustom org-clock-report-include-clocking-task nil
  "When non-nil, include the current clocking task time in clock reports."
  :group 'org-clock
321
  :version "24.1"
322 323
  :type 'boolean)

324 325 326
(defcustom org-clock-resolve-expert nil
  "Non-nil means do not show the splash buffer with the clock resolver."
  :group 'org-clock
327
  :version "24.1"
328 329
  :type 'boolean)

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
(defcustom org-clock-continuously nil
  "Non-nil means to start clocking from the last clock-out time, if any."
  :type 'boolean
  :version "24.1"
  :group 'org-clock)

(defcustom org-clock-total-time-cell-format "*%s*"
  "Format string for the total time cells."
  :group 'org-clock
  :version "24.1"
  :type 'boolean)

(defcustom org-clock-file-time-cell-format "*%s*"
  "Format string for the file time cells."
  :group 'org-clock
  :version "24.1"
  :type 'boolean)

(defcustom org-clock-clocked-in-display 'mode-line
  "When clocked in for a task, org-mode can display the current
task and accumulated time in the mode line and/or frame title.
Allowed values are:

both         displays in both mode line and frame title
mode-line    displays only in mode line (default)
frame-title  displays only in frame title
nil          current clock is not displayed"
  :group 'org-clock
  :type '(choice
	  (const :tag "Mode line" mode-line)
	  (const :tag "Frame title" frame-title)
	  (const :tag "Both" both)
	  (const :tag "None" nil)))

(defcustom org-clock-frame-title-format '(t org-mode-line-string)
  "The value for `frame-title-format' when clocking in.

When `org-clock-clocked-in-display' is set to 'frame-title
or 'both, clocking in will replace `frame-title-format' with
this value.  Clocking out will restore `frame-title-format'.

`org-frame-title-string' is a format string using the same
specifications than `frame-title-format', which see."
  :version "24.1"
  :group 'org-clock
  :type 'sexp)

377 378 379 380 381 382 383 384 385 386 387
(defvar org-clock-in-prepare-hook nil
  "Hook run when preparing the clock.
This hook is run before anything happens to the task that
you want to clock in.  For example, you can use this hook
to add an effort property.")
(defvar org-clock-in-hook nil
  "Hook run when starting the clock.")
(defvar org-clock-out-hook nil
  "Hook run when stopping the current clock.")

(defvar org-clock-cancel-hook nil
Bastien Guerry's avatar
Bastien Guerry committed
388
  "Hook run when cancelling the current clock.")
389 390
(defvar org-clock-goto-hook nil
  "Hook run when selecting the currently clocked-in entry.")
391 392
(defvar org-clock-has-been-used nil
  "Has the clock been used during the current Emacs session?")
393

394 395 396 397 398
;;; The clock for measuring work time.

(defvar org-mode-line-string "")
(put 'org-mode-line-string 'risky-local-variable t)

399
(defvar org-clock-mode-line-timer nil)
400 401
(defvar org-clock-idle-timer nil)
(defvar org-clock-heading) ; defined in org.el
402
(defvar org-clock-heading-for-remember "")
403 404
(defvar org-clock-start-time "")

405
(defvar org-clock-leftover-time nil
Bastien Guerry's avatar
Bastien Guerry committed
406
  "If non-nil, user cancelled a clock; this is when leftover time started.")
407

408
(defvar org-clock-effort ""
409
  "Effort estimate of the currently clocking task.")
410 411 412 413 414

(defvar org-clock-total-time nil
  "Holds total time, spent previously on currently clocked item.
This does not include the time in the currently running clock.")

415
(defvar org-clock-history nil
416
  "List of marker pointing to recent clocked tasks.")
417 418 419 420 421 422 423

(defvar org-clock-default-task (make-marker)
  "Marker pointing to the default task that should clock time.
The clock can be made to switch to this task after clocking out
of a different task.")

(defvar org-clock-interrupted-task (make-marker)
424
  "Marker pointing to the task that has been interrupted by the current clock.")
425

426 427
(defvar org-clock-mode-line-map (make-sparse-keymap))
(define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
428 429 430 431 432 433 434 435 436 437
(define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)

(defun org-clock-menu ()
  (interactive)
  (popup-menu
   '("Clock"
     ["Clock out" org-clock-out t]
     ["Change effort estimate" org-clock-modify-effort-estimate t]
     ["Go to clock entry" org-clock-goto t]
     ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
438

439 440
(defun org-clock-history-push (&optional pos buffer)
  "Push a marker to the clock history."
441
  (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
442 443 444 445
  (let ((m (move-marker (make-marker)
			(or pos (point)) (org-base-buffer
					  (or buffer (current-buffer)))))
	n l)
446 447 448 449 450 451 452 453 454 455 456 457 458
    (while (setq n (member m org-clock-history))
      (move-marker (car n) nil))
    (setq org-clock-history
	  (delq nil
		(mapcar (lambda (x) (if (marker-buffer x) x nil))
			org-clock-history)))
    (when (>= (setq l (length org-clock-history)) org-clock-history-length)
      (setq org-clock-history
	    (nreverse
	     (nthcdr (- l org-clock-history-length -1)
		     (nreverse org-clock-history)))))
    (push m org-clock-history)))

459 460 461
(defun org-clock-save-markers-for-cut-and-paste (beg end)
  "Save relative positions of markers in region."
  (org-check-and-save-marker org-clock-marker beg end)
462
  (org-check-and-save-marker org-clock-hd-marker beg end)
463 464 465 466 467
  (org-check-and-save-marker org-clock-default-task beg end)
  (org-check-and-save-marker org-clock-interrupted-task beg end)
  (mapc (lambda (m) (org-check-and-save-marker m beg end))
	org-clock-history))

468
(defun org-clocking-buffer ()
469
  "Return the clocking buffer if we are currently clocking a task or nil."
470 471 472
  (marker-buffer org-clock-marker))

(defun org-clocking-p ()
473
  "Return t when clocking a task."
474 475
  (not (equal (org-clocking-buffer) nil)))

476 477 478
(defvar org-clock-before-select-task-hook nil
  "Hook called in task selection just before prompting the user.")

479 480 481
(defun org-clock-select-task (&optional prompt)
  "Select a task that recently was associated with clocking."
  (interactive)
482
  (let (sel-list rpl (i 0) s)
483
    (save-window-excursion
484 485 486 487 488 489 490 491 492 493 494
      (org-switch-to-buffer-other-window
       (get-buffer-create "*Clock Task Select*"))
      (erase-buffer)
      (when (marker-buffer org-clock-default-task)
	(insert (org-add-props "Default Task\n" nil 'face 'bold))
	(setq s (org-clock-insert-selection-line ?d org-clock-default-task))
	(push s sel-list))
      (when (marker-buffer org-clock-interrupted-task)
	(insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
	(setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
	(push s sel-list))
495
      (when (org-clocking-p)
496 497 498 499 500 501 502 503 504
	(insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
	(setq s (org-clock-insert-selection-line ?c org-clock-marker))
	(push s sel-list))
      (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
      (mapc
       (lambda (m)
	 (when (marker-buffer m)
	   (setq i (1+ i)
		 s (org-clock-insert-selection-line
505 506 507
		    (if (< i 10)
			(+ i ?0)
		      (+ i (- ?A 10))) m))
508
	   (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
509 510
	   (push s sel-list)))
       org-clock-history)
511
      (run-hooks 'org-clock-before-select-task-hook)
512
      (org-fit-window-to-buffer)
513 514 515 516 517 518 519 520 521
      (message (or prompt "Select task for clocking:"))
      (setq rpl (read-char-exclusive))
      (cond
       ((eq rpl ?q) nil)
       ((eq rpl ?x) nil)
       ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
       (t (error "Invalid task choice %c" rpl))))))

(defun org-clock-insert-selection-line (i marker)
522 523 524
  "Insert a line for the clock selection menu.
And return a cons cell with the selection character integer and the marker
pointing to it."
525
  (when (marker-buffer marker)
526
    (let (file cat task heading prefix)
527
      (with-current-buffer (org-base-buffer (marker-buffer marker))
528
	(save-excursion
529 530
	  (save-restriction
	    (widen)
531 532 533
	    (ignore-errors
	      (goto-char marker)
	      (setq file (buffer-file-name (marker-buffer marker))
534
		    cat (org-get-category)
535 536 537
		    heading (org-get-heading 'notags)
		    prefix (save-excursion
			     (org-back-to-heading t)
538
			     (looking-at org-outline-regexp)
539 540 541 542 543 544
			     (match-string 0))
		    task (substring
			  (org-fontify-like-in-org-mode
			   (concat prefix heading)
			   org-odd-levels-only)
			  (length prefix)))))))
545 546 547
      (when (and cat task)
	(insert (format "[%c] %-15s %s\n" i cat task))
	(cons i marker)))))
548

549
(defvar org-clock-task-overrun nil
550 551 552 553
  "Internal flag indicating if the clock has overrun the planned time.")
(defvar org-clock-update-period 60
  "Number of seconds between mode line clock string updates.")

554
(defun org-clock-get-clock-string ()
555 556
  "Form a clock-string, that will be shown in the mode line.
If an effort estimate was defined for the current item, use
557 558 559 560 561
01:30/01:50 format (clocked/estimated).
If not, show simply the clocked time like 01:50."
  (let* ((clocked-time (org-clock-get-clocked-time))
	 (h (floor clocked-time 60))
	 (m (- clocked-time (* 60 h))))
562 563
    (if org-clock-effort
	(let* ((effort-in-minutes
564
		(org-duration-string-to-minutes org-clock-effort))
565
	       (effort-h (floor effort-in-minutes 60))
566 567 568 569
	       (effort-m (- effort-in-minutes (* effort-h 60)))
	       (work-done-str
		(org-propertize
		 (format org-time-clocksum-format h m)
570
		 'face (if (and org-clock-task-overrun (not org-clock-task-overrun-text))
571 572 573
			   'org-mode-line-clock-overrun 'org-mode-line-clock)))
	       (effort-str (format org-time-clocksum-format effort-h effort-m))
	       (clockstr (org-propertize
574
			  (concat  " [%s/" effort-str
575 576 577 578 579 580 581
				   "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
			  'face 'org-mode-line-clock)))
	  (format clockstr work-done-str))
      (org-propertize (format
		       (concat "[" org-time-clocksum-format " (%s)]")
		       h m org-clock-heading)
		      'face 'org-mode-line-clock))))
582

583
(defun org-clock-update-mode-line ()
584 585
  (if org-clock-effort
      (org-clock-notify-once-if-expired)
586
    (setq org-clock-task-overrun nil))
587 588 589 590 591 592
  (setq org-mode-line-string
	(org-propertize
	 (let ((clock-string (org-clock-get-clock-string))
	       (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
	   (if (and (> org-clock-string-limit 0)
		    (> (length clock-string) org-clock-string-limit))
593 594 595
	       (org-propertize
		(substring clock-string 0 org-clock-string-limit)
		'help-echo (concat help-text ": " org-clock-heading))
596 597
	     (org-propertize clock-string 'help-echo help-text)))
	 'local-map org-clock-mode-line-map
598
	 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)))
599
  (if (and org-clock-task-overrun org-clock-task-overrun-text)
600 601
      (setq org-mode-line-string
	    (concat (org-propertize
602
		     org-clock-task-overrun-text
603
		     'face 'org-mode-line-clock-overrun) org-mode-line-string)))
604 605 606 607
  (force-mode-line-update))

(defun org-clock-get-clocked-time ()
  "Get the clocked time for the current item in minutes.
608
The time returned includes the time spent on this task in
609 610
previous clocking intervals."
  (let ((currently-clocked-time
611 612
	 (floor (- (org-float-time)
		   (org-float-time org-clock-start-time)) 60)))
613 614 615
    (+ currently-clocked-time (or org-clock-total-time 0))))

(defun org-clock-modify-effort-estimate (&optional value)
616
  "Add to or set the effort estimate of the item currently being clocked.
617 618
VALUE can be a number of minutes, or a string with format hh:mm or mm.
When the string starts with a + or a - sign, the current value of the effort
619 620 621
property will be changed by that amount.
This will update the \"Effort\" property of currently clocked item, and
the mode line."
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  (interactive)
  (if (org-clock-is-active)
      (let ((current org-clock-effort) sign)
	(unless value
	  ;; Prompt user for a value or a change
	  (setq value
		(read-string
		 (format "Set effort (hh:mm or mm%s): "
			 (if current
			     (format ", prefix + to add to %s" org-clock-effort)
			   "")))))
	(when (stringp value)
	  ;; A string.  See if it is a delta
	  (setq sign (string-to-char value))
	  (if (member sign '(?- ?+))
	      (setq current (org-duration-string-to-minutes current)
		    value (substring value 1))
	    (setq current 0))
	  (setq value (org-duration-string-to-minutes value))
	  (if (equal ?- sign)
	      (setq value (- current value))
	    (if (equal ?+ sign) (setq value (+ current value)))))
	(setq value (max 0 value)
	      org-clock-effort (org-minutes-to-hh:mm-string value))
	(org-entry-put org-clock-marker "Effort" org-clock-effort)
	(org-clock-update-mode-line)
	(message "Effort is now %s" org-clock-effort))
    (message "Clock is not currently active")))
650 651 652 653 654 655 656

(defvar org-clock-notification-was-shown nil
  "Shows if we have shown notification already.")

(defun org-clock-notify-once-if-expired ()
  "Show notification if we spent more time than we estimated before.
Notification is shown only once."
657
  (when (org-clocking-p)
658
    (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort))
659
	  (clocked-time (org-clock-get-clocked-time)))
660
      (if (setq org-clock-task-overrun
661 662 663
		(if (or (null effort-in-minutes) (zerop effort-in-minutes))
		    nil
		  (>= clocked-time effort-in-minutes)))
664 665
	  (unless org-clock-notification-was-shown
	    (setq org-clock-notification-was-shown t)
666
	    (org-notify
667
	     (format "Task '%s' should be finished by now. (%s)"
668
		     org-clock-heading org-clock-effort) t))
669 670
	(setq org-clock-notification-was-shown nil)))))

671 672 673 674 675
(defun org-notify (notification &optional play-sound)
  "Send a NOTIFICATION and maybe PLAY-SOUND."
  (org-show-notification notification)
  (if play-sound (org-clock-play-sound)))

676 677 678 679 680 681 682 683 684
(defun org-show-notification (notification)
  "Show notification.
Use `org-show-notification-handler' if defined,
use libnotify if available, or fall back on a message."
  (cond ((functionp org-show-notification-handler)
	 (funcall org-show-notification-handler notification))
	((stringp org-show-notification-handler)
	 (start-process "emacs-timer-notification" nil
			org-show-notification-handler notification))
685
	((fboundp 'notifications-notify)
Carsten Dominik's avatar
Carsten Dominik committed
686 687 688 689 690 691
	 (notifications-notify
	  :title "Org-mode message"
	  :body notification
	  ;; FIXME how to link to the Org icon?
	  ;; :app-icon "~/.emacs.d/icons/mail.png"
	  :urgency 'low))
692
	((executable-find "notify-send")
693 694 695 696
	 (start-process "emacs-timer-notification" nil
			"notify-send" notification))
	;; Maybe the handler will send a message, so only use message as
	;; a fall back option
697
	(t (message "%s" notification))))
698 699 700 701 702 703 704 705

(defun org-clock-play-sound ()
  "Play sound as configured by `org-clock-sound'.
Use alsa's aplay tool if available."
  (cond
   ((not org-clock-sound))
   ((eq org-clock-sound t) (beep t) (beep t))
   ((stringp org-clock-sound)
706 707
    (let ((file (expand-file-name org-clock-sound)))
      (if (file-exists-p file)
708
	  (if (executable-find "aplay")
709 710 711 712 713
	      (start-process "org-clock-play-notification" nil
			     "aplay" file)
	    (condition-case nil
		(play-sound-file file)
	      (error (beep t) (beep t)))))))))
714

715
(defvar org-clock-mode-line-entry nil
716
  "Information for the mode line about the running clock.")
717

718 719 720 721 722 723 724 725 726
(defun org-find-open-clocks (file)
  "Search through the given file and find all open clocks."
  (let ((buf (or (get-file-buffer file)
		 (find-file-noselect file)))
	clocks)
    (with-current-buffer buf
      (save-excursion
	(goto-char (point-min))
	(while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
727
	  (push (cons (copy-marker (match-end 1) t)
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
		      (org-time-string-to-time (match-string 1))) clocks))))
    clocks))

(defsubst org-is-active-clock (clock)
  "Return t if CLOCK is the currently active clock."
  (and (org-clock-is-active)
       (= org-clock-marker (car clock))))

(defmacro org-with-clock-position (clock &rest forms)
  "Evaluate FORMS with CLOCK as the current active clock."
  `(with-current-buffer (marker-buffer (car ,clock))
     (save-excursion
       (save-restriction
	 (widen)
	 (goto-char (car ,clock))
	 (beginning-of-line)
	 ,@forms))))
Bastien Guerry's avatar
Bastien Guerry committed
745
(def-edebug-spec org-with-clock-position (form body))
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
(put 'org-with-clock-position 'lisp-indent-function 1)

(defmacro org-with-clock (clock &rest forms)
  "Evaluate FORMS with CLOCK as the current active clock.
This macro also protects the current active clock from being altered."
  `(org-with-clock-position ,clock
     (let ((org-clock-start-time (cdr ,clock))
	   (org-clock-total-time)
	   (org-clock-history)
	   (org-clock-effort)
	   (org-clock-marker (car ,clock))
	   (org-clock-hd-marker (save-excursion
				  (outline-back-to-heading t)
				  (point-marker))))
       ,@forms)))
Bastien Guerry's avatar
Bastien Guerry committed
761
(def-edebug-spec org-with-clock (form body))
762 763
(put 'org-with-clock 'lisp-indent-function 1)

764
(defsubst org-clock-clock-in (clock &optional resume start-time)
765 766 767 768
  "Clock in to the clock located by CLOCK.
If necessary, clock-out of the currently active clock."
  (org-with-clock-position clock
    (let ((org-clock-in-resume (or resume org-clock-in-resume)))
769
      (org-clock-in nil start-time))))
770 771 772 773 774 775

(defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  "Clock out of the clock located by CLOCK."
  (let ((temp (copy-marker (car clock)
			   (marker-insertion-type (car clock)))))
    (if (org-is-active-clock clock)
776
	(org-clock-out nil fail-quietly at-time)
777
      (org-with-clock clock
778
	(org-clock-out nil fail-quietly at-time)))
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    (setcar clock temp)))

(defsubst org-clock-clock-cancel (clock)
  "Cancel the clock located by CLOCK."
  (let ((temp (copy-marker (car clock)
			   (marker-insertion-type (car clock)))))
    (if (org-is-active-clock clock)
	(org-clock-cancel)
      (org-with-clock clock
	(org-clock-cancel)))
    (setcar clock temp)))

(defvar org-clock-clocking-in nil)
(defvar org-clock-resolving-clocks nil)
(defvar org-clock-resolving-clocks-due-to-idleness nil)

795 796
(defun org-clock-resolve-clock (clock resolve-to clock-out-time
				      &optional close-p restart-p fail-quietly)
797
  "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
798
`CLOCK' is a cons cell of the form (MARKER START-TIME)."
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  (let ((org-clock-resolving-clocks t))
    (cond
     ((null resolve-to)
      (org-clock-clock-cancel clock)
      (if (and restart-p (not org-clock-clocking-in))
	  (org-clock-clock-in clock)))

     ((eq resolve-to 'now)
      (if restart-p
	  (error "RESTART-P is not valid here"))
      (if (or close-p org-clock-clocking-in)
	  (org-clock-clock-out clock fail-quietly)
	(unless (org-is-active-clock clock)
	  (org-clock-clock-in clock t))))

     ((not (time-less-p resolve-to (current-time)))
      (error "RESOLVE-TO must refer to a time in the past"))

     (t
      (if restart-p
	  (error "RESTART-P is not valid here"))
820 821
      (org-clock-clock-out clock fail-quietly (or clock-out-time
						  resolve-to))
822 823
      (unless org-clock-clocking-in
	(if close-p
824 825 826 827 828 829 830
	    (setq org-clock-leftover-time (and (null clock-out-time)
					       resolve-to))
	  (org-clock-clock-in clock nil (and clock-out-time
					     resolve-to))))))))

(defun org-clock-jump-to-current-clock (&optional effective-clock)
  (interactive)
831 832
  (let ((org-clock-into-drawer (org-clock-into-drawer))
	(clock (or effective-clock (cons org-clock-marker
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
					 org-clock-start-time))))
    (unless (marker-buffer (car clock))
      (error "No clock is currently running"))
    (org-with-clock clock (org-clock-goto))
    (with-current-buffer (marker-buffer (car clock))
      (goto-char (car clock))
      (if org-clock-into-drawer
	  (let ((logbook
		 (if (stringp org-clock-into-drawer)
		     (concat ":" org-clock-into-drawer ":")
		   ":LOGBOOK:")))
	    (ignore-errors
	      (outline-flag-region
	       (save-excursion
		 (outline-back-to-heading t)
		 (search-forward logbook)
		 (goto-char (match-beginning 0)))
	       (save-excursion
		 (outline-back-to-heading t)
		 (search-forward logbook)
		 (search-forward ":END:")
		 (goto-char (match-end 0)))
	       nil)))))))
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880

(defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  "Resolve an open org-mode clock.
An open clock was found, with `dangling' possibly being non-nil.
If this function was invoked with a prefix argument, non-dangling
open clocks are ignored.  The given clock requires some sort of
user intervention to resolve it, either because a clock was left
dangling or due to an idle timeout.  The clock resolution can
either be:

  (a) deleted, the user doesn't care about the clock
  (b) restarted from the current time (if no other clock is open)
  (c) closed, giving the clock X minutes
  (d) closed and then restarted
  (e) resumed, as if the user had never left

The format of clock is (CONS MARKER START-TIME), where MARKER
identifies the buffer and position the clock is open at (and
thus, the heading it's under), and START-TIME is when the clock
was started."
  (assert clock)
  (let* ((ch
	  (save-window-excursion
	    (save-excursion
	      (unless org-clock-resolving-clocks-due-to-idleness
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
		(org-clock-jump-to-current-clock clock))
	      (unless org-clock-resolve-expert
		(with-output-to-temp-buffer "*Org Clock*"
		  (princ "Select a Clock Resolution Command:

i/q/C-g  Ignore this question; the same as keeping all the idle time.

k/K      Keep X minutes of the idle time (default is all).  If this
         amount is less than the default, you will be clocked out
         that many minutes after the time that idling began, and then
         clocked back in at the present time.
g/G      Indicate that you \"got back\" X minutes ago.  This is quite
         different from 'k': it clocks you out from the beginning of
         the idle period and clock you back in X minutes ago.
s/S      Subtract the idle time from the current clock.  This is the
         same as keeping 0 minutes.
C        Cancel the open timer altogether.  It will be as though you
         never clocked in.
j/J      Jump to the current clock, to make manual adjustments.

For all these options, using uppercase makes your final state
to be CLOCKED OUT.")))
	      (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
904
	      (let (char-pressed)
905 906 907 908
		(when (featurep 'xemacs)
		  (message (concat (funcall prompt-fn clock)
				   " [jkKgGsScCiq]? "))
		  (setq char-pressed (read-char-exclusive)))
909
		(while (or (null char-pressed)
910 911 912
			   (and (not (memq char-pressed
					   '(?k ?K ?g ?G ?s ?S ?C
						?j ?J ?i ?q)))
913
				(or (ding) t)))
914 915
		  (setq char-pressed
			(read-char (concat (funcall prompt-fn clock)
916
					   " [jkKgGSscCiq]? ")
917
				   nil 45)))
918 919 920 921 922 923 924 925 926 927
		(and (not (memq char-pressed '(?i ?q))) char-pressed)))))
	 (default
	   (floor (/ (org-float-time
		      (time-subtract (current-time) last-valid)) 60)))
	 (keep
	  (and (memq ch '(?k ?K))
	       (read-number "Keep how many minutes? " default)))
	 (gotback
	  (and (memq ch '(?g ?G))
	       (read-number "Got back how many minutes ago? " default)))
928 929 930 931
	 (subtractp (memq ch '(?s ?S)))
	 (barely-started-p (< (- (org-float-time last-valid)
				 (org-float-time (cdr clock))) 45))
	 (start-over (and subtractp barely-started-p)))
932 933 934 935 936 937 938 939 940
    (cond
     ((memq ch '(?j ?J))
      (if (eq ch ?J)
	  (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
      (org-clock-jump-to-current-clock clock))
     ((or (null ch)
	  (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
      (message ""))
     (t
941 942 943 944 945 946 947 948
      (org-clock-resolve-clock
       clock (cond
	      ((or (eq ch ?C)
		   ;; If the time on the clock was less than a minute before
		   ;; the user went away, and they've ask to subtract all the
		   ;; time...
		   start-over)
	       nil)
949 950
	      ((or subtractp
		   (and gotback (= gotback 0)))
951
	       last-valid)
952 953
	      ((or (and keep (= keep default))
		   (and gotback (= gotback default)))
954
	       'now)
955 956 957 958 959
	      (keep
	       (time-add last-valid (seconds-to-time (* 60 keep))))
	      (gotback
	       (time-subtract (current-time)
			      (seconds-to-time (* 60 gotback))))
960
	      (t
961 962 963
	       (error "Unexpected, please report this as a bug")))
       (and gotback last-valid)
       (memq ch '(?K ?G ?S))
964
       (and start-over
965 966
	    (not (memq ch '(?K ?G ?S ?C))))
       fail-quietly)))))
967

968
;;;###autoload
969
(defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
970
  "Resolve all currently open org-mode clocks.
971 972
If `only-dangling-p' is non-nil, only ask to resolve dangling
\(i.e., not currently open and valid) clocks."
973 974 975 976 977 978 979 980
  (interactive "P")
  (unless org-clock-resolving-clocks
    (let ((org-clock-resolving-clocks t))
      (dolist (file (org-files-list))
	(let ((clocks (org-find-open-clocks file)))
	  (dolist (clock clocks)
	    (let ((dangling (or (not (org-clock-is-active))
				(/= (car clock) org-clock-marker))))
981
	      (if (or (not only-dangling-p) dangling)
982 983 984 985 986 987 988 989 990 991 992 993
		  (org-clock-resolve
		   clock
		   (or prompt-fn
		       (function
			(lambda (clock)
			  (format
			   "Dangling clock started %d mins ago"
			   (floor
			    (/ (- (org-float-time (current-time))
				  (org-float-time (cdr clock))) 60))))))
		   (or last-valid
		       (cdr clock)))))))))))
994 995 996 997 998 999 1000 1001 1002

(defun org-emacs-idle-seconds ()
  "Return the current Emacs idle time in seconds, or nil if not idle."
  (let ((idle-time (current-idle-time)))
    (if idle-time
	(org-float-time idle-time)
      0)))

(defun org-mac-idle-seconds ()
1003
  "Return the current Mac idle time in seconds."
1004 1005
  (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))

1006 1007 1008 1009 1010 1011 1012
(defvar org-x11idle-exists-p
  ;; Check that x11idle exists
  (and (eq window-system 'x)
       (eq (call-process-shell-command "command" nil nil nil "-v" "x11idle") 0)
       ;; Check that x11idle can retrieve the idle time
       (eq (call-process-shell-command "x11idle" nil nil nil) 0)))

1013
(defun org-x11-idle-seconds ()
1014
  "Return the current X11 idle time in seconds."
1015 1016 1017 1018 1019
  (/ (string-to-number (shell-command-to-string "x11idle")) 1000))

(defun org-user-idle-seconds ()
  "Return the number of seconds the user has been idle for.
This routine returns a floating point number."
1020 1021 1022
  (cond
   ((eq system-type 'darwin)
    (org-mac-idle-seconds))
1023
   ((and (eq window-system 'x) org-x11idle-exists-p)
1024 1025 1026
    (org-x11-idle-seconds))
   (t
    (org-emacs-idle-seconds))))
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

(defvar org-clock-user-idle-seconds)

(defun org-resolve-clocks-if-idle ()
  "Resolve all currently open org-mode clocks.
This is performed after `org-clock-idle-time' minutes, to check
if the user really wants to stay clocked in after being idle for
so long."
  (when (and org-clock-idle-time (not org-clock-resolving-clocks)
	     org-clock-marker)
1037 1038 1039 1040 1041
    (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
	   (org-clock-user-idle-start
	    (time-subtract (current-time)
			   (seconds-to-time org-clock-user-idle-seconds)))
	   (org-clock-resolving-clocks-due-to-idleness t))
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
      (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
	  (org-clock-resolve
	   (cons org-clock-marker
		 org-clock-start-time)
	   (function
	    (lambda (clock)
	      (format "Clocked in & idle for %.1f mins"
		      (/ (org-float-time
			  (time-subtract (current-time)
					 org-clock-user-idle-start))
			 60.0))))
	   org-clock-user-idle-start)))))

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
(defvar org-clock-current-task nil
  "Task currently clocked in.")
(defun org-clock-set-current ()
  "Set `org-clock-current-task' to the task currently clocked in."
  (setq org-clock-current-task (nth 4 (org-heading-components))))

(defun org-clock-delete-current ()
  "Reset `org-clock-current-task' to nil."
  (setq org-clock-current-task nil))

1065
(defvar org-clock-out-time nil) ; store the time of the last clock-out
1066 1067

;;;###autoload
1068
(defun org-clock-in (&optional select start-time)
1069 1070
  "Start the clock on the current item.
If necessary, clock-out of the currently active clock.
1071 1072 1073 1074 1075 1076 1077 1078
With a prefix argument SELECT (\\[universal-argument]), offer a list of recently clocked
tasks to clock into.  When SELECT is \\[universal-argument] \\[universal-argument], clock into the current task
and mark it as the default task, a special task that will always be offered
in the clocking selection, associated with the letter `d'.
When SELECT is \\[universal-argument] \\[universal-argument] \\[universal-argument], \
clock in by using the last clock-out
time as the start time \(see `org-clock-continuously' to
make this the default behavior.)"
1079
  (interactive "P")
1080
  (setq org-clock-notification-was-shown nil)
1081
  (catch 'abort
1082
    (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
1083
			     (org-clocking-p)))
1084
	  ts selected-task target-pos (msg-extra "")
1085
	  (leftover (and (not org-clock-resolving-clocks)
1086
			 org-clock-leftover-time)))
1087

1088 1089 1090 1091 1092
      (when (and org-clock-auto-clock-resolution
		 (or (not interrupting)
		     (eq t org-clock-auto-clock-resolution))
		 (not org-clock-clocking-in)
		 (not org-clock-resolving-clocks))
1093
	(setq org-clock-leftover-time nil)
1094 1095
	(let ((org-clock-clocking-in t))
	  (org-resolve-clocks)))	; check if any clocks are dangling
1096

1097 1098 1099 1100 1101
      (when (equal select '(64))
	;; Set start-time to `org-clock-out-time'
	(let ((org-clock-continuously t))
	  (org-clock-in nil org-clock-out-time)))

1102 1103 1104 1105 1106
      (when (equal select '(4))
	(setq selected-task (org-clock-select-task "Clock-in on task: "))
	(if selected-task
	    (setq selected-task (copy-marker selected-task))
	  (error "Abort")))
1107 1108 1109 1110 1111

      (when (equal select '(16))
	;; Mark as default clocking task
	(org-clock-mark-default-task))

1112
      (when interrupting
1113
	;; We are interrupting the clocking of a different task.
1114
	;; Save a marker to this task, so that we can go back.
1115
	;; First check if we are trying to clock into the same task!
Carsten Dominik's avatar
Carsten Dominik committed
1116
	(when (save-excursion
1117 1118 1119 1120 1121 1122 1123 1124 1125
		(unless selected-task
		  (org-back-to-heading t))
		(and (equal (marker-buffer org-clock-hd-marker)
			    (if selected-task
				(marker-buffer selected-task)
			      (current-buffer)))
		     (= (marker-position org-clock-hd-marker)
			(if selected-task
			    (marker-position selected-task)
1126 1127
			  (point)))
		     (equal org-clock-current-task (nth 4 (org-heading-components)))))
Carsten Dominik's avatar
Carsten Dominik committed
1128 1129 1130 1131 1132 1133
	  (message "Clock continues in \"%s\"" org-clock-heading)
	  (throw 'abort nil))
	(move-marker org-clock-interrupted-task
		     (marker-position org-clock-marker)
		     (marker-buffer org-clock-marker))
	(let ((org-clock-clocking-in t))
1134
	  (org-clock-out nil t)))
1135

1136 1137
      ;; Clock in at which position?
      (setq target-pos
Bastien Guerry's avatar
Bastien Guerry committed
1138
	    (if (and (eobp) (not (org-at-heading-p)))
1139 1140
		(point-at-bol 0)
	      (point)))
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
      (save-excursion
	(when (and selected-task (marker-buffer selected-task))
	  ;; There is a selected task, move to the correct buffer
	  ;; and set the new target position.
	  (set-buffer (org-base-buffer (marker-buffer selected-task)))
	  (setq target-pos (marker-position selected-task))
	  (move-marker selected-task nil))
	(save-excursion
	  (save-restriction
	    (widen)
	    (goto-char target-pos)
	    (org-back-to-heading t)
	    (or interrupting (move-marker org-clock-interrupted-task nil))
1154 1155 1156 1157 1158
	    (save-excursion
	      (forward-char) ;; make sure the marker is not at the
	      ;; beginning of the heading, since the
	      ;; user is liking to insert stuff here
	      ;; manually
1159
	      (run-hooks 'org-clock-in-prepare-hook)
1160
	      (org-clock-history-push))
1161
	    (org-clock-set-current)
1162 1163 1164 1165 1166 1167
	    (cond ((functionp org-clock-in-switch-to-state)
		   (looking-at org-complex-heading-regexp)
		   (let ((newstate (funcall org-clock-in-switch-to-state
					    (match-string 2))))
		     (if newstate (org-todo newstate))))
		  ((and org-clock-in-switch-to-state
1168
			(not (looking-at (concat org-outline-regexp "[ \t]*"
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
						 org-clock-in-switch-to-state
						 "\\>"))))
		   (org-todo org-clock-in-switch-to-state)))
	    (setq org-clock-heading-for-remember
		  (and (looking-at org-complex-heading-regexp)
		       (match-end 4)
		       (org-trim (buffer-substring (match-end 1)
						   (match-end 4)))))
	    (setq org-clock-heading
		  (cond ((and org-clock-heading-function
			      (functionp org-clock-heading-function))
			 (funcall org-clock-heading-function))
1181 1182
			((and (looking-at org-complex-heading-regexp)
			      (match-string 4))
1183 1184 1185
			 (replace-regexp-in-string
			  "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
			  (match-string 4)))
1186 1187 1188
			(t "???")))
	    (setq org-clock-heading (org-propertize org-clock-heading
						    'face nil))
1189
	    (org-clock-find-position org-clock-in-resume)
1190 1191 1192
	    (cond
	     ((and org-clock-in-resume
		   (looking-at
Bastien Guerry's avatar
Bastien Guerry committed
1193
		    (concat "^[ \t]*" org-clock-string
1194
			    " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
Bastien Guerry's avatar
Bastien Guerry committed
1195
			    " *\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
1196 1197 1198 1199 1200
	      (message "Matched %s" (match-string 1))
	      (setq ts (concat "[" (match-string 1) "]"))
	      (goto-char (match-end 1))
	      (setq org-clock-start-time
		    (apply 'encode-time
1201 1202 1203 1204
			   (org-parse-time-string (match-string 1))))
	      (setq org-clock-effort (org-get-effort))
	      (setq org-clock-total-time (org-clock-sum-current-item
					  (org-clock-get-sum-start))))
1205 1206 1207 1208 1209 1210 1211