Update years in copyright notice; nfc.
[bpt/emacs.git] / lisp / type-break.el
index 2e0025c..beb7e6f 100644 (file)
@@ -1,15 +1,14 @@
 ;;; type-break.el --- encourage rests from typing at appropriate intervals
 
-;; Copyright (C) 1994, 1995, 1997 Free Software Foundation, Inc.
+;; Copyright (C) 1994, 1995, 1997, 2000, 2002, 2003,
+;;   2004, 2005, 2006 Free Software Foundation, Inc.
 
-;; Author: Noah Friedman <friedman@prep.ai.mit.edu>
-;; Maintainer: friedman@prep.ai.mit.edu
+;; Author: Noah Friedman
+;; Maintainer: Noah Friedman <friedman@splode.com>
 ;; Keywords: extensions, timers
 ;; Status: Works in GNU Emacs 19.25 or later, some versions of XEmacs
 ;; Created: 1994-07-13
 
-;; $Id: type-break.el,v 1.14 1998/03/14 04:47:44 rms Exp done $
-
 ;; This file is part of GNU Emacs.
 
 ;; GNU Emacs is free software; you can redistribute it and/or modify
 
 ;; You should have received a copy of the GNU General Public License
 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
-;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-;; Boston, MA 02111-1307, USA.
+;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+;; Boston, MA 02110-1301, USA.
 
 ;;; Commentary:
 
 ;; The docstring for the function `type-break-mode' summarizes most of the
 ;; details of the interface.
 
-;; This package relies on the assumption that you live entirely in emacs,
+;; This package relies on the assumption that you live entirely in Emacs,
 ;; as the author does.  If that's not the case for you (e.g. you often
-;; suspend emacs or work in other windows) then this won't help very much;
-;; it will depend on just how often you switch back to emacs.  At the very
+;; suspend Emacs or work in other windows) then this won't help very much;
+;; it will depend on just how often you switch back to Emacs.  At the very
 ;; least, you will want to turn off the keystroke thresholds and rest
 ;; interval tracking.
 
@@ -60,9 +59,9 @@
 
 ;; This package was inspired by Roland McGrath's hanoi-break.el.
 ;; Several people contributed feedback and ideas, including
-;;      Roland McGrath <roland@gnu.ai.mit.edu>
-;;      Kleanthes Koniaris <kgk@martigny.ai.mit.edu>
-;;      Mark Ashton <mpashton@gnu.ai.mit.edu>
+;;      Roland McGrath <roland@gnu.org>
+;;      Kleanthes Koniaris <kgk@koniaris.com>
+;;      Mark Ashton <mpashton@gnu.org>
 ;;      Matt Wilding <wilding@cli.com>
 ;;      Robert S. Boyer <boyer@cs.utexas.edu>
 
 
 ;;;###autoload
 (defcustom type-break-mode nil
-  "*Non-`nil' means typing break mode is enabled.
+  "Toggle typing break mode.
 See the docstring for the `type-break-mode' command for more information.
-You must modify via \\[customize] for this variable to have an effect."
+Setting this variable directly does not take effect;
+use either \\[customize] or the function `type-break-mode'."
   :set (lambda (symbol value)
         (type-break-mode (if value 1 -1)))
-  :initialize 'custom-initialize-default  
+  :initialize 'custom-initialize-default
   :type 'boolean
   :group 'type-break
-  :require 'type-break
-  :version "20.3")
+  :require 'type-break)
 
 ;;;###autoload
 (defcustom type-break-interval (* 60 60)
@@ -97,7 +96,7 @@ You must modify via \\[customize] for this variable to have an effect."
 (defcustom type-break-good-rest-interval (/ type-break-interval 6)
   "*Number of seconds of idle time considered to be an adequate typing rest.
 
-When this variable is non-`nil', emacs checks the idle time between
+When this variable is non-nil, Emacs checks the idle time between
 keystrokes.  If this idle time is long enough to be considered a \"good\"
 rest from typing, then the next typing break is simply rescheduled for later.
 
@@ -106,6 +105,17 @@ asked whether or not really to interrupt the break."
   :type 'integer
   :group 'type-break)
 
+;;;###autoload
+(defcustom type-break-good-break-interval nil
+  "*Number of seconds considered to be an adequate explicit typing rest.
+
+When this variable is non-nil, its value is considered to be a \"good\"
+length (in seconds) for a break initiated by the command `type-break',
+overriding `type-break-good-rest-interval'.  This provides querying of
+break interruptions when `type-break-good-rest-interval' is nil."
+  :type 'integer
+  :group 'type-break)
+
 ;;;###autoload
 (defcustom type-break-keystroke-threshold
   ;; Assuming typing speed is 35wpm (on the average, do you really
@@ -145,18 +155,22 @@ guess a reasonably good pair of values for this variable."
   :group 'type-break)
 
 (defcustom type-break-query-mode t
-  "*Non-`nil' means ask whether or not to prompt user for breaks.
+  "*Non-nil means ask whether or not to prompt user for breaks.
 If so, call the function specified in the value of the variable
 `type-break-query-function' to do the asking."
   :type 'boolean
   :group 'type-break)
 
-(defvar type-break-query-function 'yes-or-no-p
-  "Function to use for making query for a typing break.
+(defcustom type-break-query-function 'yes-or-no-p
+  "*Function to use for making query for a typing break.
 It should take a string as an argument, the prompt.
 Usually this should be set to `yes-or-no-p' or `y-or-n-p'.
 
-To avoid being queried at all, set `type-break-query-mode' to `nil'.")
+To avoid being queried at all, set `type-break-query-mode' to nil."
+  :type '(radio function
+                (function-item yes-or-no-p)
+                (function-item y-or-n-p))
+  :group 'type-break)
 
 (defcustom type-break-query-interval 60
   "*Number of seconds between queries to take a break, if put off.
@@ -181,7 +195,6 @@ will occur."
   :type '(repeat integer)
   :group 'type-break)
 
-
 (defcustom type-break-warning-repeat 40
   "*Number of keystrokes for which warnings should be repeated.
 That is, for each of this many keystrokes the warning is redisplayed
@@ -189,19 +202,41 @@ in the echo area to make sure it's really seen."
   :type 'integer
   :group 'type-break)
 
+(defcustom type-break-time-stamp-format "[%H:%M] "
+  "*Timestamp format used to prefix messages.
+Format specifiers are as used by `format-time-string'."
+  :type 'string
+  :group 'type-break)
+
 (defcustom type-break-demo-functions
   '(type-break-demo-boring type-break-demo-life type-break-demo-hanoi)
   "*List of functions to consider running as demos during typing breaks.
 When a typing break begins, one of these functions is selected randomly
-to have emacs do something interesting.
+to have Emacs do something interesting.
 
 Any function in this list should start a demo which ceases as soon as a
 key is pressed."
   :type '(repeat function)
   :group 'type-break)
 
+(defcustom type-break-demo-boring-stats nil
+  "*Show word per minute and keystroke figures in the Boring demo."
+  :type 'boolean
+  :group 'type-break)
+
+(defcustom type-break-terse-messages nil
+  "*Use slightly terser messages."
+  :type 'boolean
+  :group 'type-break)
+
+(defcustom type-break-file-name (convert-standard-filename "~/.type-break")
+  "*Name of file used to save state across sessions.
+If this is nil, no data will be saved across sessions."
+  :type 'file
+  :group 'type-break)
+
 (defvar type-break-post-command-hook '(type-break-check)
-  "Hook run indirectly by post-command-hook for typing break functions.
+  "Hook run indirectly by `post-command-hook' for typing break functions.
 This is not really intended to be set by the user, but it's probably
 harmless to do so.  Mainly it is used by various parts of the typing break
 program to delay actions until after the user has completed some command.
@@ -213,7 +248,7 @@ remove themselves after running.")
 ;; Mode line frobs
 
 (defcustom type-break-mode-line-message-mode nil
-  "*Non-`nil' means put type-break related messages in the mode line.
+  "*Non-nil means put type-break related messages in the mode line.
 Otherwise, messages typically go in the echo area.
 
 See also `type-break-mode-line-format' and its members."
@@ -232,13 +267,14 @@ See also `type-break-mode-line-format' and its members."
     type-break-mode-line-break-string))
 
 (defvar type-break-mode-line-break-message-p nil)
-(defvar type-break-mode-line-break-string " *** TAKE A TYPING BREAK ***")
+(defvar type-break-mode-line-break-string " *** TAKE A TYPING BREAK NOW ***")
 
 (defvar type-break-mode-line-warning
       '(type-break-mode-line-break-message-p
         ("")
         (type-break-warning-countdown-string
-         (" ***Break in "
+         (" *** "
+          "Break in "
           type-break-warning-countdown-string
           " "
           type-break-warning-countdown-string-type
@@ -248,8 +284,8 @@ See also `type-break-mode-line-format' and its members."
   "If non-nil, this is a countdown for the next typing break.
 
 This variable, in conjunction with `type-break-warning-countdown-string-type'
-(which indicates whether this value is a number of keystrokes or seconds)
-is installed in mode-line-format to notify of imminent typing breaks.")
+\(which indicates whether this value is a number of keystrokes or seconds)
+is installed in `mode-line-format' to notify of imminent typing breaks.")
 
 (defvar type-break-warning-countdown-string-type nil
   "Indicates the unit type of `type-break-warning-countdown-string'.
@@ -267,38 +303,7 @@ It will be either \"seconds\" or \"keystrokes\".")
 (defvar type-break-current-keystroke-warning-interval nil)
 (defvar type-break-time-warning-count 0)
 (defvar type-break-keystroke-warning-count 0)
-
-;; Constant indicating emacs variant.
-;; This can be one of `xemacs', `lucid', `epoch', `mule', etc.
-(defconst type-break-emacs-variant
-  (let ((data (match-data))
-        (version (cond
-                  ((fboundp 'nemacs-version)
-                   (nemacs-version))
-                  (t
-                   (emacs-version))))
-        (alist '(("\\bXEmacs\\b"  . xemacs)
-                 ("\\bLucid\\b"   . lucid)
-                 ("^Nemacs\\b"    . nemacs)
-                 ("^GNU Emacs 19" . standard19)
-                 ("^GNU Emacs 20" . standard19)
-                 ("^GNU Emacs 18" . emacs18)))
-        result)
-    (while alist
-      (cond
-       ((string-match (car (car alist)) version)
-        (setq result (cdr (car alist)))
-        (setq alist nil))
-       (t
-        (setq alist (cdr alist)))))
-    (set-match-data data)
-    (cond ((eq result 'lucid)
-           (and (string= emacs-version "19.8 Lucid")
-                (setq result 'lucid-19-8)))
-          ((memq result '(nemacs emacs18))
-           (signal 'error
-                   "type-break not supported in this version of emacs.")))
-    result))
+(defvar type-break-interval-start nil)
 
 \f
 ;;;###autoload
@@ -309,7 +314,7 @@ This is a minor mode, but it is global to all buffers by default.
 When this mode is enabled, the user is encouraged to take typing breaks at
 appropriate intervals; either after a specified amount of time or when the
 user has exceeded a keystroke threshold.  When the time arrives, the user
-is asked to take a break.  If the user refuses at that time, emacs will ask
+is asked to take a break.  If the user refuses at that time, Emacs will ask
 again in a short period of time.  The idea is to give the user enough time
 to find a good breaking point in his or her work, but be sufficiently
 annoying to discourage putting typing breaks off indefinitely.
@@ -334,9 +339,18 @@ affect the time schedule; it simply provides a default for the
 If set, the variable `type-break-good-rest-interval' specifies the minimum
 amount of time which is considered a reasonable typing break.  Whenever
 that time has elapsed, typing breaks are automatically rescheduled for
-later even if emacs didn't prompt you to take one first.  Also, if a break
+later even if Emacs didn't prompt you to take one first.  Also, if a break
 is ended before this much time has elapsed, the user will be asked whether
-or not to continue.
+or not to continue.  A nil value for this variable prevents automatic
+break rescheduling, making `type-break-interval' an upper bound on the time
+between breaks.  In this case breaks will be prompted for as usual before
+the upper bound if the keystroke threshold is reached.
+
+If `type-break-good-rest-interval' is nil and
+`type-break-good-break-interval' is set, then confirmation is required to
+interrupt a break before `type-break-good-break-interval' seconds
+have passed.  This provides for an upper bound on the time between breaks
+together with confirmation of interruptions to these breaks.
 
 The variable `type-break-keystroke-threshold' is used to determine the
 thresholds at which typing breaks should be considered.  You can use
@@ -346,21 +360,26 @@ approximate good values for this.
 There are several variables that affect how or when warning messages about
 imminent typing breaks are displayed.  They include:
 
-        type-break-mode-line-message-mode
-        type-break-time-warning-intervals
-        type-break-keystroke-warning-intervals
-        type-break-warning-repeat
-        type-break-warning-countdown-string
-        type-break-warning-countdown-string-type
+        `type-break-mode-line-message-mode'
+        `type-break-time-warning-intervals'
+        `type-break-keystroke-warning-intervals'
+        `type-break-warning-repeat'
+        `type-break-warning-countdown-string'
+        `type-break-warning-countdown-string-type'
 
 There are several variables that affect if, how, and when queries to begin
 a typing break occur.  They include:
 
-        type-break-query-mode
-        type-break-query-function
-        type-break-query-interval
+        `type-break-query-mode'
+        `type-break-query-function'
+        `type-break-query-interval'
+
+The command `type-break-statistics' prints interesting things.
 
-Finally, the command `type-break-statistics' prints interesting things."
+Finally, a file (named `type-break-file-name') is used to store information
+across Emacs sessions.  This provides recovery of the break status between
+sessions and after a crash.  Manual changes to the file may result in
+problems."
   (interactive "P")
   (type-break-check-post-command-hook)
 
@@ -370,32 +389,70 @@ Finally, the command `type-break-statistics' prints interesting things."
     (cond
      ((and already-enabled type-break-mode)
       (and (interactive-p)
-           (message "type-break-mode is already enabled")))
+           (message "Type Break mode is already enabled")))
      (type-break-mode
+      (when type-break-file-name
+       (with-current-buffer (find-file-noselect type-break-file-name 'nowarn)
+         (setq buffer-save-without-query t)))
+
       (or global-mode-string
           (setq global-mode-string '("")))
-      (or (memq 'type-break-mode-line-format
-                (default-value 'global-mode-string))
-          (setq-default global-mode-string
-                        (nconc (default-value 'global-mode-string)
-                               '(type-break-mode-line-format))))
+      (or (assq 'type-break-mode-line-message-mode
+               minor-mode-alist)
+         (setq minor-mode-alist
+               (cons type-break-mode-line-format
+                     minor-mode-alist)))
       (type-break-keystroke-reset)
       (type-break-mode-line-countdown-or-break nil)
-      (type-break-schedule)
+
+      (setq type-break-time-last-break
+            (or (type-break-get-previous-time)
+                (current-time)))
+
+      ;; schedule according to break time from session file
+      (type-break-schedule
+       (let (diff)
+         (if (and type-break-time-last-break
+                  (< (setq diff (type-break-time-difference
+                                 type-break-time-last-break
+                                 (current-time)))
+                     type-break-interval))
+             ;; use the file's value
+             (progn
+               (setq type-break-keystroke-count
+                     (type-break-get-previous-count))
+               ;; file the time, in case it was read from the auto-save file
+               (type-break-file-time type-break-interval-start)
+               (setq type-break-interval-start type-break-time-last-break)
+               (- type-break-interval diff))
+           ;; schedule from now
+           (setq type-break-interval-start (current-time))
+           (type-break-file-time type-break-interval-start)
+           type-break-interval))
+       type-break-interval-start
+       type-break-interval)
+
       (and (interactive-p)
-           (message "type-break-mode is enabled and reset")))
+           (message "Type Break mode is enabled and set")))
      (t
       (type-break-keystroke-reset)
       (type-break-mode-line-countdown-or-break nil)
       (type-break-cancel-schedule)
+      (do-auto-save)
+      (when type-break-file-name
+       (with-current-buffer (find-file-noselect type-break-file-name
+                                                'nowarn)
+         (set-buffer-modified-p nil)
+         (unlock-buffer)
+         (kill-this-buffer)))
       (and (interactive-p)
-           (message "type-break-mode is disabled")))))
+           (message "Type Break mode is disabled")))))
   type-break-mode)
 
 (defun type-break-mode-line-message-mode (&optional prefix)
   "Enable or disable warnings in the mode line about typing breaks.
 
-A negative prefix argument disables this mode.
+A negative PREFIX argument disables this mode.
 No argument or any non-negative argument enables it.
 
 The user may also enable or disable this mode simply by setting the
@@ -403,10 +460,10 @@ variable of the same name.
 
 Variables controlling the display of messages in the mode line include:
 
-        mode-line-format
-        global-mode-string
-        type-break-mode-line-break-message
-        type-break-mode-line-warning"
+        `mode-line-format'
+        `global-mode-string'
+        `type-break-mode-line-break-message'
+        `type-break-mode-line-warning'"
   (interactive "P")
   (setq type-break-mode-line-message-mode
         (>= (prefix-numeric-value prefix) 0))
@@ -423,7 +480,7 @@ When enabled, the user is periodically queried about whether to take a
 typing break at that moment.  The function which does this query is
 specified by the variable `type-break-query-function'.
 
-A negative prefix argument disables this mode.
+A negative PREFIX argument disables this mode.
 No argument or any non-negative argument enables it.
 
 The user may also enable or disable this mode simply by setting the
@@ -438,6 +495,95 @@ variable of the same name."
   type-break-query-mode)
 
 \f
+;;; session file functions
+
+(defvar type-break-auto-save-file-name
+  (let ((buffer-file-name type-break-file-name))
+    (make-auto-save-file-name))
+  "Auto-save name of `type-break-file-name'.")
+
+(defun type-break-file-time (&optional time)
+  "File break time in `type-break-file-name', unless the file is locked."
+  (if (and type-break-file-name
+           (not (stringp (file-locked-p type-break-file-name))))
+      (with-current-buffer (find-file-noselect type-break-file-name
+                                               'nowarn)
+        (let ((inhibit-read-only t))
+          (erase-buffer)
+          (insert (format "%s\n\n" (or time type-break-interval-start)))
+          ;; file saving is left to auto-save
+          ))))
+
+(defun type-break-file-keystroke-count ()
+  "File keystroke count in `type-break-file-name', unless the file is locked."
+  (if (and type-break-file-name
+           (not (stringp (file-locked-p type-break-file-name))))
+      ;; Prevent deactivation of the mark in some other buffer.
+      (let (deactivate-mark)
+       (with-current-buffer (find-file-noselect type-break-file-name
+                                                'nowarn)
+         (save-excursion
+           (let ((inhibit-read-only t))
+             (goto-char (point-min))
+             (forward-line)
+             (delete-region (point) (save-excursion (end-of-line) (point)))
+             (insert (format "%s" type-break-keystroke-count))
+             ;; file saving is left to auto-save
+             ))))))
+
+(defun timep (time)
+  "If TIME is in the format returned by `current-time' then
+return TIME, else return nil."
+  (and (listp time)
+       (eq (length time) 3)
+       (integerp (car time))
+       (integerp (nth 1 time))
+       (integerp (nth 2 time))
+       time))
+
+(defun type-break-choose-file ()
+  "Return file to read from."
+  (cond
+   ((not type-break-file-name)
+    nil)
+   ((and (file-exists-p type-break-auto-save-file-name)
+         (file-readable-p type-break-auto-save-file-name))
+    type-break-auto-save-file-name)
+   ((and (file-exists-p type-break-file-name)
+         (file-readable-p type-break-file-name))
+    type-break-file-name)
+   (t nil)))
+
+(defun type-break-get-previous-time ()
+  "Get previous break time from `type-break-file-name'.
+Returns nil if the file is missing or if the time breaks with the
+`current-time' format."
+  (let ((file (type-break-choose-file)))
+    (if file
+        (timep ;; returns expected format, else nil
+         (with-current-buffer (find-file-noselect file 'nowarn)
+           (save-excursion
+             (goto-char (point-min))
+             (read (current-buffer))))))))
+
+(defun type-break-get-previous-count ()
+  "Get previous keystroke count from `type-break-file-name'.
+Return 0 if the file is missing or if the form read is not an
+integer."
+  (let ((file (type-break-choose-file)))
+    (if (and file
+             (integerp
+              (setq file
+                    (with-current-buffer
+                        (find-file-noselect file 'nowarn)
+                      (save-excursion
+                        (goto-char (point-min))
+                        (forward-line 1)
+                        (read (current-buffer)))))))
+        file
+      0)))
+
+\f
 ;;;###autoload
 (defun type-break ()
   "Take a typing break.
@@ -448,7 +594,10 @@ During the break, a demo selected from the functions listed in
 After the typing break is finished, the next break is scheduled
 as per the function `type-break-schedule'."
   (interactive)
+  (do-auto-save)
   (type-break-cancel-schedule)
+  ;; remove any query scheduled during interactive invocation
+  (remove-hook 'type-break-post-command-hook 'type-break-do-query)
   (let ((continue t)
         (start-time (current-time)))
     (setq type-break-time-last-break start-time)
@@ -459,7 +608,8 @@ as per the function `type-break-schedule'."
              (other-window 1))
         (delete-other-windows)
         (scroll-right (window-width))
-        (message "Press any key to resume from typing break.")
+        (unless type-break-terse-messages
+          (message "Press any key to resume from typing break."))
 
         (random t)
         (let* ((len (length type-break-demo-functions))
@@ -469,35 +619,45 @@ as per the function `type-break-schedule'."
               (funcall fn)
             (error nil))))
 
-      (cond
-       (type-break-good-rest-interval
-        (let ((break-secs (type-break-time-difference
-                           start-time (current-time))))
-          (cond
-           ((>= break-secs type-break-good-rest-interval)
-            (setq continue nil))
-           ;; 60 seconds may be too much leeway if the break is only 3
-           ;; minutes to begin with.  You can just say "no" to the query
-           ;; below if you're in that much of a hurry.
-           ;((> 60 (abs (- break-secs type-break-good-rest-interval)))
-           ; (setq continue nil))
-           ((funcall
-             type-break-query-function
-             (format "You really ought to rest %s more.  Continue break? "
-                     (type-break-format-time (- type-break-good-rest-interval
-                                                break-secs)))))
-           (t
-            (setq continue nil)))))
-       (t (setq continue nil)))))
+      (let ((good-interval (or type-break-good-rest-interval
+                               type-break-good-break-interval)))
+        (cond
+         (good-interval
+          (let ((break-secs (type-break-time-difference
+                             start-time (current-time))))
+            (cond
+             ((>= break-secs good-interval)
+              (setq continue nil))
+             ;; 60 seconds may be too much leeway if the break is only 3
+             ;; minutes to begin with.  You can just say "no" to the query
+             ;; below if you're in that much of a hurry.
+             ;;((> 60 (abs (- break-secs good-interval)))
+             ;; (setq continue nil))
+             ((funcall
+               type-break-query-function
+               (format
+                (if type-break-terse-messages
+                    "%s%s remaining.  Continue break? "
+                  "%sYou really ought to rest %s more.  Continue break? ")
+                (type-break-time-stamp)
+                (type-break-format-time (- good-interval
+                                           break-secs)))))
+             (t
+              (setq continue nil)))))
+         (t (setq continue nil))))))
 
   (type-break-keystroke-reset)
+  (type-break-file-time)
   (type-break-mode-line-countdown-or-break nil)
   (type-break-schedule))
 
 \f
-(defun type-break-schedule (&optional time)
+(defun type-break-schedule (&optional time start interval)
   "Schedule a typing break for TIME seconds from now.
-If time is not specified, default to `type-break-interval'."
+If time is not specified it defaults to `type-break-interval'.
+START and INTERVAL are used when recovering a break.
+START is the start of the break (defaults to now).
+INTERVAL is the full length of an interval (defaults to TIME)."
   (interactive (list (and current-prefix-arg
                           (prefix-numeric-value current-prefix-arg))))
   (or time (setq time type-break-interval))
@@ -506,7 +666,8 @@ If time is not specified, default to `type-break-interval'."
   (type-break-time-warning-schedule time 'reset)
   (type-break-run-at-time (max 1 time) nil 'type-break-alarm)
   (setq type-break-time-next-break
-        (type-break-time-sum (current-time) time)))
+        (type-break-time-sum (or start (current-time))
+                             (or interval time))))
 
 (defun type-break-cancel-schedule ()
   (type-break-cancel-time-warning-schedule)
@@ -555,6 +716,7 @@ If time is not specified, default to `type-break-interval'."
   (remove-hook 'type-break-post-command-hook 'type-break-time-warning)
   (setq type-break-current-time-warning-interval
         type-break-time-warning-intervals)
+  (setq type-break-time-warning-count 0) ; avoid warnings after break
   (setq type-break-warning-countdown-string nil))
 
 (defun type-break-alarm ()
@@ -579,6 +741,7 @@ If time is not specified, default to `type-break-interval'."
 This may be the case either because the scheduled time has come \(and the
 minimum keystroke threshold has been reached\) or because the maximum
 keystroke threshold has been exceeded."
+  (type-break-file-keystroke-count)
   (let* ((min-threshold (car type-break-keystroke-threshold))
          (max-threshold (cdr type-break-keystroke-threshold)))
     (and type-break-good-rest-interval
@@ -594,8 +757,6 @@ keystroke threshold has been exceeded."
            (setq type-break-time-last-command (current-time))))
 
     (and type-break-keystroke-threshold
-        ;; next line is test for 20.2 that can be deleted
-        ;;(setq type-break-keystroke-count (1+ type-break-keystroke-count))
          (let ((keys (this-command-keys)))
            (cond
             ;; Ignore mouse motion
@@ -678,14 +839,23 @@ keystroke threshold has been exceeded."
                 ;; which hoses undo or yank-pop (if you happened to be
                 ;; yanking just when the query occurred).
                 (this-command this-command))
+            ;; Cancel schedule to prevent possibility of a second query
+            ;; from taking place before this one has even returned.
+            ;; The condition-case wrapper will reschedule on quit.
+            (type-break-cancel-schedule)
+            ;; Also prevent a second query when the break is interrupted.
+            (remove-hook 'type-break-post-command-hook 'type-break-do-query)
             (funcall type-break-query-function
-                     "Take a break from typing now? "))
+                     (format "%s%s"
+                             (type-break-time-stamp)
+                            (if type-break-terse-messages
+                                "Break now? "
+                              "Take a break from typing now? "))))
           (type-break))
          (t
           (type-break-schedule type-break-query-interval)))
       (quit
-       (type-break-schedule type-break-query-interval)))
-    (remove-hook 'type-break-post-command-hook 'type-break-do-query))))
+       (type-break-schedule type-break-query-interval))))))
 
 (defun type-break-noninteractive-query (&optional ignored-args)
   "Null query function which doesn't interrupt user and assumes `no'.
@@ -695,7 +865,8 @@ this or ask the user to start one right now."
    (type-break-mode-line-message-mode)
    (t
     (beep t)
-    (message "You should take a typing break now.  Do `M-x type-break'.")
+    (message "%sYou should take a typing break now.  Do `M-x type-break'."
+             (type-break-time-stamp))
     (sit-for 1)
     (beep t)
     ;; return nil so query caller knows to reset reminder, as if user
@@ -720,7 +891,8 @@ this or ask the user to start one right now."
        ((not type-break-mode-line-message-mode)
         ;; Pause for a moment so any previous message can be seen.
         (sit-for 2)
-        (message "Warning: typing break due in %s."
+        (message "%sWarning: typing break due in %s."
+                 (type-break-time-stamp)
                  (type-break-format-time timeleft))
         (setq type-break-time-warning-count
               (1- type-break-time-warning-count))))))
@@ -743,7 +915,8 @@ this or ask the user to start one right now."
      ((memq this-command '(digit-argument universal-argument)))
      ((not type-break-mode-line-message-mode)
       (sit-for 2)
-      (message "Warning: typing break due in %s keystrokes."
+      (message "%sWarning: typing break due in %s keystrokes."
+               (type-break-time-stamp)
                (- (cdr type-break-keystroke-threshold)
                   type-break-keystroke-count))
       (setq type-break-keystroke-warning-count
@@ -826,7 +999,7 @@ based on a fairly simple algorithm involving assumptions about the average
 length of words (5).  For the minimum threshold, it uses about a fifth of
 the computed maximum threshold.
 
-When called from lisp programs, the optional args WORDLEN and FRAC can be
+When called from Lisp programs, the optional args WORDLEN and FRAC can be
 used to override the default assumption about average word length and the
 fraction of the maximum threshold to which to set the minimum threshold.
 FRAC should be the inverse of the fractional value; for example, a value of
@@ -839,8 +1012,8 @@ FRAC should be the inverse of the fractional value; for example, a value of
     (setcar type-break-keystroke-threshold lower)
     (setcdr type-break-keystroke-threshold upper)
     (if (interactive-p)
-        (message "min threshold: %d\tmax threshold: %d" lower upper)
-      type-break-keystroke-threshold)))
+        (message "min threshold: %d\tmax threshold: %d" lower upper))
+    type-break-keystroke-threshold))
 
 \f
 ;;; misc functions
@@ -891,6 +1064,13 @@ FRAC should be the inverse of the fractional value; for example, a value of
 
     (list high low micro)))
 
+(defun type-break-time-stamp (&optional when)
+  (if (fboundp 'format-time-string)
+      (format-time-string type-break-time-stamp-format when)
+    ;; Emacs 19.28 and prior do not have format-time-string.
+    ;; In that case, result is not customizable.  Upgrade today!
+    (format "[%s] " (substring (current-time-string when) 11 16))))
+
 (defun type-break-format-time (secs)
   (let ((mins (/ secs 60)))
     (cond
@@ -900,6 +1080,7 @@ FRAC should be the inverse of the fractional value; for example, a value of
      (t (format "%d seconds" secs)))))
 
 (defun type-break-keystroke-reset ()
+  (setq type-break-interval-start (current-time)) ; not a keystroke
   (setq type-break-keystroke-count 0)
   (setq type-break-keystroke-warning-count 0)
   (setq type-break-current-keystroke-warning-interval
@@ -912,7 +1093,7 @@ With optional non-nil ALL, force redisplay of all mode-lines."
   (and all (save-excursion (set-buffer (other-buffer))))
   (set-buffer-modified-p (buffer-modified-p)))
 
-;; If an exception occurs in emacs while running the post command hook, the
+;; If an exception occurs in Emacs while running the post command hook, the
 ;; value of that hook is clobbered.  This is because the value of the
 ;; variable is temporarily set to nil while it's running to prevent
 ;; recursive application, but it also means an exception aborts the routine
@@ -925,41 +1106,16 @@ With optional non-nil ALL, force redisplay of all mode-lines."
 ;;; Timer wrapper functions
 ;;;
 ;;; These shield type-break from variations in the interval timer packages
-;;; for different versions of emacs.
+;;; for different versions of Emacs.
 
 (defun type-break-run-at-time (time repeat function)
-  (cond ((eq type-break-emacs-variant 'standard19)
-         (require 'timer)
-         (funcall 'run-at-time time repeat function))
-        ((eq type-break-emacs-variant 'lucid-19-8)
-         (let ((name (if (symbolp function)
-                         (symbol-name function)
-                       "type-break")))
-           (require 'timer)
-           (funcall 'start-timer name function time repeat)))
-        ((memq type-break-emacs-variant '(xemacs lucid))
-         (let ((name (if (symbolp function)
-                         (symbol-name function)
-                       "type-break")))
-           (require 'itimer)
-           (funcall 'start-itimer name function time repeat)))))
+  (condition-case nil (or (require 'timer) (require 'itimer)) (error nil))
+  (run-at-time time repeat function))
 
+(defvar timer-dont-exit)
 (defun type-break-cancel-function-timers (function)
-  (cond ((eq type-break-emacs-variant 'standard19)
-         (let ((timer-dont-exit t))
-           (funcall 'cancel-function-timers function)))
-        ((eq type-break-emacs-variant 'lucid-19-8)
-         (let ((list timer-list))
-           (while list
-             (and (eq (funcall 'timer-function (car list)) function)
-                  (funcall 'delete-timer (car list)))
-             (setq list (cdr list)))))
-        ((memq type-break-emacs-variant '(xemacs lucid))
-         (let ((list itimer-list))
-           (while list
-             (and (eq (funcall 'itimer-function (car list)) function)
-                  (funcall 'delete-itimer (car list)))
-             (setq list (cdr list)))))))
+  (let ((timer-dont-exit t))
+    (cancel-function-timers function)))
 
 \f
 ;;; Demo wrappers
@@ -1011,44 +1167,83 @@ With optional non-nil ALL, force redisplay of all mode-lines."
 ;; Boring demo, but doesn't use many cycles
 (defun type-break-demo-boring ()
   "Boring typing break demo."
-  (let ((rmsg "Press any key to resume from typing break")
+  (let ((rmsg (if type-break-terse-messages
+                  ""
+                "Press any key to resume from typing break"))
         (buffer-name "*Typing Break Buffer*")
-        line col pos
-        elapsed timeleft tmsg)
+        lines elapsed timeleft tmsg)
     (condition-case ()
         (progn
           (switch-to-buffer (get-buffer-create buffer-name))
           (buffer-disable-undo (current-buffer))
-          (erase-buffer)
-          (setq line (1+ (/ (window-height) 2)))
-          (setq col (/ (- (window-width) (length rmsg)) 2))
-          (insert (make-string line ?\C-j)
-                  (make-string col ?\ )
-                  rmsg)
-          (forward-line -1)
-          (beginning-of-line)
-          (setq pos (point))
+          (setq lines (/ (window-body-height) 2))
+          (unless type-break-terse-messages (setq lines (1- lines)))
+          (if type-break-demo-boring-stats
+              (setq lines (- lines 2)))
+          (setq lines (make-string lines ?\C-j))
           (while (not (input-pending-p))
-            (delete-region pos (progn
-                                 (goto-char pos)
-                                 (end-of-line)
-                                 (point)))
+            (erase-buffer)
             (setq elapsed (type-break-time-difference
                            type-break-time-last-break
                            (current-time)))
-            (cond
-             (type-break-good-rest-interval
-              (setq timeleft (- type-break-good-rest-interval elapsed))
-              (if (> timeleft 0)
-                  (setq tmsg (format "You should rest for %s more"
-                                     (type-break-format-time timeleft)))
-                (setq tmsg (format "Typing break has lasted %s"
-                                   (type-break-format-time elapsed)))))
-             (t
-              (setq tmsg (format "Typing break has lasted %s"
-                                 (type-break-format-time elapsed)))))
-            (setq col (/ (- (window-width) (length tmsg)) 2))
-            (insert (make-string col ?\ ) tmsg)
+            (let ((good-interval (or type-break-good-rest-interval
+                                     type-break-good-break-interval)))
+              (cond
+               (good-interval
+                (setq timeleft (- good-interval elapsed))
+                (if (> timeleft 0)
+                    (setq tmsg
+                          (format (if type-break-terse-messages
+                                      "Break remaining: %s"
+                                    "You should rest for %s more")
+                                  (type-break-format-time timeleft)))
+                  (setq tmsg
+                        (format (if type-break-terse-messages
+                                    "Break complete (%s elapsed in total)"
+                                  "Typing break has lasted %s")
+                                (type-break-format-time elapsed)))))
+               (t
+                (setq tmsg
+                      (format (if type-break-terse-messages
+                                  "Break has lasted %s"
+                                "Typing break has lasted %s")
+                              (type-break-format-time elapsed))))))
+            (insert lines
+                    (make-string (/ (- (window-width) (length tmsg)) 2) ?\ )
+                    tmsg)
+            (if (> (length rmsg) 0)
+                (insert "\n"
+                        (make-string (/ (- (window-width) (length rmsg)) 2)
+                                     ?\ )
+                        rmsg))
+            (if type-break-demo-boring-stats
+                (let*
+                    ((message
+                      (format
+                       (if type-break-terse-messages
+                           "Since last break: %s keystrokes\n"
+                         "Since your last break you've typed %s keystrokes\n")
+                       type-break-keystroke-count))
+                     (column-spaces
+                      (make-string (/ (- (window-width) (length message)) 2)
+                                   ?\ ))
+                     (wpm (/ (/ (float type-break-keystroke-count) 5)
+                             (/ (type-break-time-difference
+                                 type-break-interval-start
+                                 type-break-time-last-break)
+                                60.0))))
+                  (insert "\n\n" column-spaces message)
+                  (if type-break-terse-messages
+                      (insert (format "                  %s%.2f wpm"
+                                      column-spaces
+                                      wpm))
+                    (setq message
+                          (format "at an average of %.2f words per minute"
+                                  wpm))
+                    (insert
+                     (make-string (/ (- (window-width) (length message)) 2)
+                                  ?\ )
+                     message))))
             (goto-char (point-min))
             (sit-for 60))
           (read-char)
@@ -1062,4 +1257,6 @@ With optional non-nil ALL, force redisplay of all mode-lines."
 
 (if type-break-mode
     (type-break-mode 1))
+
+;;; arch-tag: 943a2eb3-07e6-420b-993f-96e4796f5fd0
 ;;; type-break.el ends here