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

3
;; Copyright (C) 2004-2014 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 30
;;; Code:

31
(eval-when-compile
32
  (require 'cl))
Bastien Guerry's avatar
Bastien Guerry committed
33
(require 'org)
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
(declare-function org-refresh-properties "org" (dprop tprop))
39
(defvar org-time-stamp-formats)
40
(defvar org-ts-what)
41
(defvar org-frame-title-format-backup frame-title-format)
42 43 44 45 46 47

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

48
(defcustom org-clock-into-drawer org-log-into-drawer
49
  "Should clocking info be wrapped into a drawer?
50
When t, clocking info will always be inserted into a :LOGBOOK: drawer.
51 52 53
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
54 55 56 57 58
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."
59 60 61 62 63
  :group 'org-todo
  :group 'org-clock
  :type '(choice
	  (const :tag "Always" t)
	  (const :tag "Only when drawer exists" nil)
64 65 66
	  (integer :tag "When at least N clock entries")
	  (const :tag "Into LOGBOOK drawer" "LOGBOOK")
	  (string :tag "Into Drawer named...")))
67

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
(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))))

84
(defcustom org-clock-out-when-done t
85
  "When non-nil, clock will be stopped when the clocked entry is marked DONE.
86 87 88 89 90
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."
91
  :group 'org-clock
92 93 94 95 96
  :type '(choice
	  (const :tag "No" nil)
	  (const :tag "Yes, when done" t)
	  (repeat :tag "State list"
		  (string :tag "TODO keyword"))))
97

Bastien Guerry's avatar
Bastien Guerry committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
(defcustom org-clock-rounding-minutes 0
  "Rounding minutes when clocking in or out.
The default value is 0 so that no rounding is done.
When set to a non-integer value, use the car of
`org-time-stamp-rounding-minutes', like for setting a time-stamp.

E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
and you clock in: then the clock starts at 14:45.  If you clock
out within the next 5 minutes, the clock line will be removed;
if you clock out 8 minutes after your clocked in, the clock
out time will be 14:50."
  :group 'org-clock
  :version "24.4"
  :package-version '(Org . "8.0")
  :type '(choice
	  (integer :tag "Minutes (0 for no rounding)")
	  (symbol  :tag "Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp)))

116
(defcustom org-clock-out-remove-zero-time-clocks nil
117
  "Non-nil means remove the clock line when the resulting time is zero."
118 119 120 121 122
  :group 'org-clock
  :type 'boolean)

(defcustom org-clock-in-switch-to-state nil
  "Set task to a special todo state while clocking it.
123
The value should be the state to which the entry should be
124
switched.  If the value is a function, it must take one
125 126
parameter (the current TODO state of the item) and return the
state to switch it to."
127 128 129 130
  :group 'org-clock
  :group 'org-todo
  :type '(choice
	  (const :tag "Don't force a state" nil)
131 132
	  (string :tag "State")
	  (symbol :tag "Function")))
133

134 135 136
(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
137
switched.  If the value is a function, it must take one
138 139 140 141 142 143 144 145 146
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")))

147 148 149 150 151
(defcustom org-clock-history-length 5
  "Number of clock tasks to remember in history."
  :group 'org-clock
  :type 'integer)

152
(defcustom org-clock-goto-may-find-recent-task t
153
  "Non-nil means `org-clock-goto' can go to recent task if no active clock."
154 155 156
  :group 'org-clock
  :type 'boolean)

157 158 159 160 161
(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
Bastien Guerry's avatar
Bastien Guerry committed
162
  :type '(choice (const nil) (function)))
163

164
(defcustom org-clock-string-limit 0
165
  "Maximum length of clock strings in the mode line.  0 means no limit."
166 167
  :group 'org-clock
  :type 'integer)
168

169
(defcustom org-clock-in-resume nil
170 171 172
  "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."
173 174 175 176
  :group 'org-clock
  :type 'boolean)

(defcustom org-clock-persist nil
177 178
  "When non-nil, save the running clock when Emacs is closed.
The clock is resumed when Emacs restarts.
179 180
When this is t, both the running clock, and the entire clock
history are saved.  When this is the symbol `clock', only the
181 182
running clock is saved.  When this is the symbol `history', only
the clock history is saved.
183

184 185 186 187 188 189
When Emacs restarts with saved clock information, the file containing
the running clock as well as all files mentioned in the clock history
will be visited.

All this depends on running `org-clock-persistence-insinuate' in your
Emacs initialization file."
190
  :group 'org-clock
191 192
  :type '(choice
	  (const :tag "Just the running clock" clock)
193
	  (const :tag "Just the history" history)
194 195
	  (const :tag "Clock and history" t)
	  (const :tag "No persistence" nil)))
196

197
(defcustom org-clock-persist-file (convert-standard-filename
Bastien Guerry's avatar
Bastien Guerry committed
198
				   (concat user-emacs-directory "org-clock-save.el"))
199
  "File to save clock data to."
200 201 202 203
  :group 'org-clock
  :type 'string)

(defcustom org-clock-persist-query-save nil
204
  "When non-nil, ask before saving the current clock on exit."
205 206 207 208
  :group 'org-clock
  :type 'boolean)

(defcustom org-clock-persist-query-resume t
209
  "When non-nil, ask before resuming any stored clock during load."
210 211 212
  :group 'org-clock
  :type 'boolean)

213
(defcustom org-clock-sound nil
Bastien Guerry's avatar
Bastien Guerry committed
214 215
  "Sound to use for notifications.
Possible values are:
216

Bastien Guerry's avatar
Bastien Guerry committed
217 218 219
nil        No sound played
t          Standard Emacs beep
file name  Play this sound file, fall back to beep"
220 221 222 223
  :group 'org-clock
  :type '(choice
	  (const :tag "No sound" nil)
	  (const :tag "Standard beep" t)
Bastien Guerry's avatar
Bastien Guerry committed
224
	  (file  :tag "Play sound file")))
225

226
(define-obsolete-variable-alias 'org-clock-modeline-total
227 228 229
  'org-clock-mode-line-total "24.3")

(defcustom org-clock-mode-line-total 'auto
230
  "Default setting for the time included for the mode line clock.
231 232 233 234
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
235
today    All time clocked into this task today
236 237
repeat   All time clocked into this task since last repeat
all      All time ever recorded for this task
238
auto     Automatically, either `all', or `repeat' for repeating tasks"
239 240 241 242 243 244 245 246
  :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)))

Bastien Guerry's avatar
Bastien Guerry committed
247
(org-defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
248
(defcustom org-clock-task-overrun-text nil
249
  "Extra mode line text to indicate that the clock is overrun.
250 251 252 253 254
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
255
  :version "24.1"
256 257 258 259
  :type '(choice
	  (const :tag "Just mark the time string" nil)
	  (string :tag "Text to prepend")))

260 261 262 263 264 265
(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
Bastien Guerry's avatar
Bastien Guerry committed
266
	  (const nil)
267 268 269
	  (string :tag "Program")
	  (function :tag "Function")))

Carsten Dominik's avatar
Carsten Dominik committed
270 271 272 273 274 275
(defgroup org-clocktable nil
  "Options concerning the clock table in Org-mode."
  :tag "Org Clock Table"
  :group 'org-clock)

(defcustom org-clocktable-defaults
276 277
  (list
   :maxlevel 2
Bastien Guerry's avatar
Bastien Guerry committed
278
   :lang (or (org-bound-and-true-p org-export-default-language) "en")
279 280
   :scope 'file
   :block nil
Bastien Guerry's avatar
Bastien Guerry committed
281 282
   :wstart 1
   :mstart 1
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
   :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
298
  "Default properties for clock tables."
299
  :group 'org-clock
300
  :version "24.1"
301 302
  :type 'plist)

Carsten Dominik's avatar
Carsten Dominik committed
303 304 305 306
(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
307
  :version "24.1"
Carsten Dominik's avatar
Carsten Dominik committed
308 309
  :type 'function)

310 311 312 313 314 315 316 317
;; 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
318
  :version "24.1"
319 320
  :type 'alist)

Carsten Dominik's avatar
Carsten Dominik committed
321 322 323 324 325 326 327
(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)

328 329 330 331 332 333 334 335 336 337 338 339 340 341
(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)))
342

343 344 345
(defcustom org-clock-report-include-clocking-task nil
  "When non-nil, include the current clocking task time in clock reports."
  :group 'org-clock
346
  :version "24.1"
347 348
  :type 'boolean)

349 350 351
(defcustom org-clock-resolve-expert nil
  "Non-nil means do not show the splash buffer with the clock resolver."
  :group 'org-clock
352
  :version "24.1"
353 354
  :type 'boolean)

355 356 357 358 359 360 361 362 363 364
(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"
Bastien Guerry's avatar
Bastien Guerry committed
365
  :type 'string)
366 367 368 369 370

(defcustom org-clock-file-time-cell-format "*%s*"
  "Format string for the file time cells."
  :group 'org-clock
  :version "24.1"
Bastien Guerry's avatar
Bastien Guerry committed
371
  :type 'string)
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

(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)

Bastien Guerry's avatar
Bastien Guerry committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415
(defcustom org-clock-x11idle-program-name "x11idle"
  "Name of the program which prints X11 idle time in milliseconds.

You can find x11idle.c in the contrib/scripts directory of the
Org git distribution. Or, you can do:

    sudo apt-get install xprintidle

if you are using Debian."
  :group 'org-clock
  :version "24.4"
  :package-version '(Org . "8.0")
  :type 'string)

416 417 418 419 420 421 422 423 424 425 426
(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
Paul Eggert's avatar
Paul Eggert committed
427
  "Hook run when canceling the current clock.")
428 429
(defvar org-clock-goto-hook nil
  "Hook run when selecting the currently clocked-in entry.")
430 431
(defvar org-clock-has-been-used nil
  "Has the clock been used during the current Emacs session?")
432

433 434 435 436 437
;;; The clock for measuring work time.

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

438
(defvar org-clock-mode-line-timer nil)
439 440
(defvar org-clock-idle-timer nil)
(defvar org-clock-heading) ; defined in org.el
441 442
(defvar org-clock-start-time "")

443
(defvar org-clock-leftover-time nil
Paul Eggert's avatar
Paul Eggert committed
444
  "If non-nil, user canceled a clock; this is when leftover time started.")
445

446
(defvar org-clock-effort ""
447
  "Effort estimate of the currently clocking task.")
448 449 450 451 452

(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.")

453
(defvar org-clock-history nil
454
  "List of marker pointing to recent clocked tasks.")
455 456 457 458 459 460 461

(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)
462
  "Marker pointing to the task that has been interrupted by the current clock.")
463

464 465
(defvar org-clock-mode-line-map (make-sparse-keymap))
(define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
466 467 468 469 470 471 472 473 474 475
(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"])))
476

477 478
(defun org-clock-history-push (&optional pos buffer)
  "Push a marker to the clock history."
479
  (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
480 481 482 483
  (let ((m (move-marker (make-marker)
			(or pos (point)) (org-base-buffer
					  (or buffer (current-buffer)))))
	n l)
484 485 486 487 488 489 490 491 492 493 494 495 496
    (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)))

497 498 499
(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)
500
  (org-check-and-save-marker org-clock-hd-marker beg end)
501 502 503 504 505
  (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))

506
(defun org-clocking-buffer ()
507
  "Return the clocking buffer if we are currently clocking a task or nil."
508 509 510
  (marker-buffer org-clock-marker))

(defun org-clocking-p ()
511
  "Return t when clocking a task."
512 513
  (not (equal (org-clocking-buffer) nil)))

514 515 516
(defvar org-clock-before-select-task-hook nil
  "Hook called in task selection just before prompting the user.")

517
(defun org-clock-select-task (&optional prompt)
Bastien Guerry's avatar
Bastien Guerry committed
518
  "Select a task that was recently associated with clocking."
519
  (interactive)
Bastien Guerry's avatar
Bastien Guerry committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  (let (och chl sel-list rpl (i 0) s)
    ;; Remove successive dups from the clock history to consider
    (mapc (lambda (c) (if (not (equal c (car och))) (push c och)))
	  org-clock-history)
    (setq och (reverse och) chl (length och))
    (if (zerop chl)
	(user-error "No recent clock")
      (save-window-excursion
	(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))
	(when (org-clocking-p)
	  (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
		      (if (< i 10)
			  (+ i ?0)
			(+ i (- ?A 10))) m))
	     (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
	     (push s sel-list)))
	 och)
	(run-hooks 'org-clock-before-select-task-hook)
	(goto-char (point-min))
	;; Set min-height relatively to circumvent a possible but in
	;; `fit-window-to-buffer'
	(fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl)))
	(message (or prompt "Select task for clocking:"))
	(setq cursor-type nil rpl (read-char-exclusive))
	(cond
	 ((eq rpl ?q) nil)
	 ((eq rpl ?x) nil)
	 ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
	 (t (user-error "Invalid task choice %c" rpl)))))))
567 568

(defun org-clock-insert-selection-line (i marker)
569 570 571
  "Insert a line for the clock selection menu.
And return a cons cell with the selection character integer and the marker
pointing to it."
572
  (when (marker-buffer marker)
573
    (let (file cat task heading prefix)
574
      (with-current-buffer (org-base-buffer (marker-buffer marker))
575
	(save-excursion
576 577
	  (save-restriction
	    (widen)
578 579 580
	    (ignore-errors
	      (goto-char marker)
	      (setq file (buffer-file-name (marker-buffer marker))
581
		    cat (org-get-category)
582 583 584
		    heading (org-get-heading 'notags)
		    prefix (save-excursion
			     (org-back-to-heading t)
585
			     (looking-at org-outline-regexp)
586 587 588 589 590 591
			     (match-string 0))
		    task (substring
			  (org-fontify-like-in-org-mode
			   (concat prefix heading)
			   org-odd-levels-only)
			  (length prefix)))))))
592
      (when (and cat task)
Bastien Guerry's avatar
Bastien Guerry committed
593
	(insert (format "[%c] %-12s  %s\n" i cat task))
594
	(cons i marker)))))
595

596
(defvar org-clock-task-overrun nil
597 598 599 600
  "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.")

601
(defun org-clock-get-clock-string ()
602 603
  "Form a clock-string, that will be shown in the mode line.
If an effort estimate was defined for the current item, use
604 605
01:30/01:50 format (clocked/estimated).
If not, show simply the clocked time like 01:50."
Bastien Guerry's avatar
Bastien Guerry committed
606
  (let ((clocked-time (org-clock-get-clocked-time)))
607 608
    (if org-clock-effort
	(let* ((effort-in-minutes
609
		(org-duration-string-to-minutes org-clock-effort))
610 611
	       (work-done-str
		(org-propertize
Bastien Guerry's avatar
Bastien Guerry committed
612
		 (org-minutes-to-clocksum-string clocked-time)
613
		 'face (if (and org-clock-task-overrun (not org-clock-task-overrun-text))
614
			   'org-mode-line-clock-overrun 'org-mode-line-clock)))
Bastien Guerry's avatar
Bastien Guerry committed
615
	       (effort-str (org-minutes-to-clocksum-string effort-in-minutes))
616
	       (clockstr (org-propertize
617
			  (concat  " [%s/" effort-str
618 619 620
				   "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
			  'face 'org-mode-line-clock)))
	  (format clockstr work-done-str))
Bastien Guerry's avatar
Bastien Guerry committed
621 622
      (org-propertize (concat "[" (org-minutes-to-clocksum-string clocked-time)
			      (format " (%s)" org-clock-heading) "]")
623
		      'face 'org-mode-line-clock))))
624

Bastien Guerry's avatar
Bastien Guerry committed
625 626 627 628 629 630 631 632
(defun org-clock-get-last-clock-out-time ()
  "Get the last clock-out time for the current subtree."
  (save-excursion
    (let ((end (save-excursion (org-end-of-subtree))))
      (when (re-search-forward (concat org-clock-string
				       ".*\\]--\\(\\[[^]]+\\]\\)") end t)
	(org-time-string-to-time (match-string 1))))))

633
(defun org-clock-update-mode-line ()
634 635
  (if org-clock-effort
      (org-clock-notify-once-if-expired)
636
    (setq org-clock-task-overrun nil))
637 638 639 640 641 642
  (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))
643 644 645
	       (org-propertize
		(substring clock-string 0 org-clock-string-limit)
		'help-echo (concat help-text ": " org-clock-heading))
646 647
	     (org-propertize clock-string 'help-echo help-text)))
	 'local-map org-clock-mode-line-map
648
	 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)))
649
  (if (and org-clock-task-overrun org-clock-task-overrun-text)
650 651
      (setq org-mode-line-string
	    (concat (org-propertize
652
		     org-clock-task-overrun-text
653
		     'face 'org-mode-line-clock-overrun) org-mode-line-string)))
654 655 656 657
  (force-mode-line-update))

(defun org-clock-get-clocked-time ()
  "Get the clocked time for the current item in minutes.
658
The time returned includes the time spent on this task in
659 660
previous clocking intervals."
  (let ((currently-clocked-time
661 662
	 (floor (- (org-float-time)
		   (org-float-time org-clock-start-time)) 60)))
663 664 665
    (+ currently-clocked-time (or org-clock-total-time 0))))

(defun org-clock-modify-effort-estimate (&optional value)
666
  "Add to or set the effort estimate of the item currently being clocked.
667 668
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
Bastien Guerry's avatar
Bastien Guerry committed
669
property will be changed by that amount.  If the effort value is expressed
Paul Eggert's avatar
Paul Eggert committed
670
as an `org-effort-durations' (e.g. \"3h\"), the modified value will be
Bastien Guerry's avatar
Bastien Guerry committed
671 672 673 674
converted to a hh:mm duration.

This command will update the \"Effort\" property of the currently
clocked item, and the value displayed in the mode line."
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
  (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)
Bastien Guerry's avatar
Bastien Guerry committed
698
	      org-clock-effort (org-minutes-to-clocksum-string value))
699 700 701 702
	(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")))
703 704 705 706 707 708 709

(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."
710
  (when (org-clocking-p)
711
    (let ((effort-in-minutes (org-duration-string-to-minutes org-clock-effort))
712
	  (clocked-time (org-clock-get-clocked-time)))
713
      (if (setq org-clock-task-overrun
714 715 716
		(if (or (null effort-in-minutes) (zerop effort-in-minutes))
		    nil
		  (>= clocked-time effort-in-minutes)))
717 718
	  (unless org-clock-notification-was-shown
	    (setq org-clock-notification-was-shown t)
719
	    (org-notify
720
	     (format "Task '%s' should be finished by now. (%s)"
Bastien Guerry's avatar
Bastien Guerry committed
721
		     org-clock-heading org-clock-effort) org-clock-sound))
722 723
	(setq org-clock-notification-was-shown nil)))))

724
(defun org-notify (notification &optional play-sound)
Bastien Guerry's avatar
Bastien Guerry committed
725 726
  "Send a NOTIFICATION and maybe PLAY-SOUND.
If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
727
  (org-show-notification notification)
Bastien Guerry's avatar
Bastien Guerry committed
728
  (if play-sound (org-clock-play-sound play-sound)))
729

730 731 732 733 734 735 736 737 738
(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))
739
	((fboundp 'notifications-notify)
Carsten Dominik's avatar
Carsten Dominik committed
740 741 742 743 744 745
	 (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))
746
	((executable-find "notify-send")
747 748 749 750
	 (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
751
	(t (message "%s" notification))))
752

Bastien Guerry's avatar
Bastien Guerry committed
753
(defun org-clock-play-sound (&optional clock-sound)
754
  "Play sound as configured by `org-clock-sound'.
Bastien Guerry's avatar
Bastien Guerry committed
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
Use alsa's aplay tool if available.
If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
  (let ((org-clock-sound (or clock-sound org-clock-sound)))
    (cond
     ((not org-clock-sound))
     ((eq org-clock-sound t) (beep t) (beep t))
     ((stringp org-clock-sound)
      (let ((file (expand-file-name org-clock-sound)))
	(if (file-exists-p file)
	    (if (executable-find "aplay")
		(start-process "org-clock-play-notification" nil
			       "aplay" file)
	      (condition-case nil
		  (play-sound-file file)
		(error (beep t) (beep t))))))))))
770

771
(defvar org-clock-mode-line-entry nil
772
  "Information for the mode line about the running clock.")
773

774 775 776 777 778 779 780 781 782
(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)
783
	  (push (cons (copy-marker (match-end 1) t)
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
		      (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
801
(def-edebug-spec org-with-clock-position (form body))
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
(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
817
(def-edebug-spec org-with-clock (form body))
818 819
(put 'org-with-clock 'lisp-indent-function 1)

820
(defsubst org-clock-clock-in (clock &optional resume start-time)
821 822 823 824
  "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)))
825
      (org-clock-in nil start-time))))
826 827 828 829 830 831

(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)
832
	(org-clock-out nil fail-quietly at-time)
833
      (org-with-clock clock
834
	(org-clock-out nil fail-quietly at-time)))
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
    (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)

851 852
(defun org-clock-resolve-clock (clock resolve-to clock-out-time
				      &optional close-p restart-p fail-quietly)
853
  "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
854
`CLOCK' is a cons cell of the form (MARKER START-TIME)."
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
  (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"))
876 877
      (org-clock-clock-out clock fail-quietly (or clock-out-time
						  resolve-to))
878 879
      (unless org-clock-clocking-in
	(if close-p
880 881 882 883 884 885 886
	    (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)
887 888
  (let ((org-clock-into-drawer (org-clock-into-drawer))
	(clock (or effective-clock (cons org-clock-marker
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
					 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)))))))
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936

(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
937 938 939 940 941
		(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:

Bastien Guerry's avatar
Bastien Guerry committed
942
i/q      Ignore this question; the same as keeping all the idle time.
943 944 945 946 947

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.
Bastien Guerry's avatar
Bastien Guerry committed
948

949 950 951
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.
Bastien Guerry's avatar
Bastien Guerry committed
952

953 954
s/S      Subtract the idle time from the current clock.  This is the
         same as keeping 0 minutes.
Bastien Guerry's avatar
Bastien Guerry committed
955

956 957
C        Cancel the open timer altogether.  It will be as though you
         never clocked in.
Bastien Guerry's avatar
Bastien Guerry committed
958

959 960 961 962 963
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*"))
964
	      (let (char-pressed)
965 966 967 968
		(when (featurep 'xemacs)
		  (message (concat (funcall prompt-fn clock)
				   " [jkKgGsScCiq]? "))
		  (setq char-pressed (read-char-exclusive)))
969
		(while (or (null char-pressed)
970 971 972
			   (and (not (memq char-pressed
					   '(?k ?K ?g ?G ?s ?S ?C
						?j ?J ?i ?q)))
973
				(or (ding) t)))
974 975
		  (setq char-pressed
			(read-char (concat (funcall prompt-fn clock)
976
					   " [jkKgGSscCiq]? ")
977
				   nil 45)))
978 979 980 981 982 983 984 985 986 987
		(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)))
988 989 990 991
	 (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)))
992 993 994 995 996 997 998 999 1000
    (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
1001 1002 1003 1004 1005 1006 1007 1008
      (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)
1009 1010
	      ((or subtractp
		   (and gotback (= gotback 0)))
1011
	       last-valid)
1012 1013
	      ((or (and keep (= keep default))
		   (and gotback (= gotback default)))
1014
	       'now)
1015 1016 1017 1018 1019
	      (keep
	       (time-add last-valid (seconds-to-time (* 60 keep))))
	      (gotback
	       (time-subtract (current-time)
			      (seconds-to-time (* 60 gotback))))
1020
	      (t
1021 1022 1023
	       (error "Unexpected, please report this as a bug")))
       (and gotback last-valid)
       (memq ch '(?K ?G ?S))
1024
       (and start-over
1025 1026
	    (not (memq ch '(?K ?G ?S ?C))))
       fail-quietly)))))
1027

1028
;;;###autoload
1029
(defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
1030
  "Resolve all currently open org-mode clocks.
1031 1032
If `only-dangling-p' is non-nil, only ask to resolve dangling
\(i.e., not currently open and valid) clocks."
1033 1034 1035 1036 1037 1038 1039 1040
  (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))))
1041
	      (if (or (not only-dangling-p) dangling)
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
		  (org-clock-resolve
		   clock
		   (or prompt-fn
		       (function