Merge from trunk.
[bpt/emacs.git] / lisp / type-break.el
1 ;;; type-break.el --- encourage rests from typing at appropriate intervals
2
3 ;; Copyright (C) 1994-1995, 1997, 2000-2011 Free Software Foundation, Inc.
4
5 ;; Author: Noah Friedman
6 ;; Maintainer: Noah Friedman <friedman@splode.com>
7 ;; Keywords: extensions, timers
8 ;; Created: 1994-07-13
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; The docstring for the function `type-break-mode' summarizes most of the
28 ;; details of the interface.
29
30 ;; This package relies on the assumption that you live entirely in Emacs,
31 ;; as the author does. If that's not the case for you (e.g. you often
32 ;; suspend Emacs or work in other windows) then this won't help very much;
33 ;; it will depend on just how often you switch back to Emacs. At the very
34 ;; least, you will want to turn off the keystroke thresholds and rest
35 ;; interval tracking.
36
37 ;; If you prefer not to be queried about taking breaks, but instead just
38 ;; want to be reminded, do the following:
39 ;;
40 ;; (setq type-break-query-mode nil)
41 ;;
42 ;; Or call the command `type-break-query-mode' with a negative prefix
43 ;; argument.
44
45 ;; If you find echo area messages annoying and would prefer to see messages
46 ;; in the mode line instead, do M-x type-break-mode-line-message-mode
47 ;; or set the variable of the same name to `t'.
48
49 ;; This program can truly cons up a storm because of all the calls to
50 ;; `current-time' (which always returns fresh conses). I'm dismayed by
51 ;; this, but I think the health of my hands is far more important than a
52 ;; few pages of virtual memory.
53
54 ;; This program has no hope of working in Emacs 18.
55
56 ;; This package was inspired by Roland McGrath's hanoi-break.el.
57 ;; Several people contributed feedback and ideas, including
58 ;; Roland McGrath <roland@gnu.org>
59 ;; Kleanthes Koniaris <kgk@koniaris.com>
60 ;; Mark Ashton <mpashton@gnu.org>
61 ;; Matt Wilding <wilding@cli.com>
62 ;; Robert S. Boyer <boyer@cs.utexas.edu>
63
64 ;;; Code:
65
66 \f
67 (defgroup type-break nil
68 "Encourage the user to take a rest from typing at suitable intervals."
69 :prefix "type-break"
70 :group 'keyboard)
71
72 ;;;###autoload
73 (defcustom type-break-mode nil
74 "Toggle typing break mode.
75 See the docstring for the `type-break-mode' command for more information.
76 Setting this variable directly does not take effect;
77 use either \\[customize] or the function `type-break-mode'."
78 :set (lambda (_symbol value)
79 (type-break-mode (if value 1 -1)))
80 :initialize 'custom-initialize-default
81 :type 'boolean
82 :group 'type-break
83 :require 'type-break)
84
85 ;;;###autoload
86 (defcustom type-break-interval (* 60 60)
87 "Number of seconds between scheduled typing breaks."
88 :type 'integer
89 :group 'type-break)
90
91 ;;;###autoload
92 (defcustom type-break-good-rest-interval (/ type-break-interval 6)
93 "Number of seconds of idle time considered to be an adequate typing rest.
94
95 When this variable is non-nil, Emacs checks the idle time between
96 keystrokes. If this idle time is long enough to be considered a \"good\"
97 rest from typing, then the next typing break is simply rescheduled for later.
98
99 If a break is interrupted before this much time elapses, the user will be
100 asked whether or not really to interrupt the break."
101 :type 'integer
102 :group 'type-break)
103
104 ;;;###autoload
105 (defcustom type-break-good-break-interval nil
106 "Number of seconds considered to be an adequate explicit typing rest.
107
108 When this variable is non-nil, its value is considered to be a \"good\"
109 length (in seconds) for a break initiated by the command `type-break',
110 overriding `type-break-good-rest-interval'. This provides querying of
111 break interruptions when `type-break-good-rest-interval' is nil."
112 :type 'integer
113 :group 'type-break)
114
115 ;;;###autoload
116 (defcustom type-break-keystroke-threshold
117 ;; Assuming typing speed is 35wpm (on the average, do you really
118 ;; type more than that in a minute? I spend a lot of time reading mail
119 ;; and simply studying code in buffers) and average word length is
120 ;; about 5 letters, default upper threshold to the average number of
121 ;; keystrokes one is likely to type in a break interval. That way if the
122 ;; user goes through a furious burst of typing activity, cause a typing
123 ;; break to be required sooner than originally scheduled.
124 ;; Conversely, the minimum threshold should be about a fifth of this.
125 (let* ((wpm 35)
126 (avg-word-length 5)
127 (upper (* wpm avg-word-length (/ type-break-interval 60)))
128 (lower (/ upper 5)))
129 (cons lower upper))
130 "Upper and lower bound on number of keystrokes for considering typing break.
131 This structure is a pair of numbers (MIN . MAX).
132
133 The first number is the minimum number of keystrokes that must have been
134 entered since the last typing break before considering another one, even if
135 the scheduled time has elapsed; the break is simply rescheduled until later
136 if the minimum threshold hasn't been reached. If this first value is nil,
137 then there is no minimum threshold; as soon as the scheduled time has
138 elapsed, the user will always be queried.
139
140 The second number is the maximum number of keystrokes that can be entered
141 before a typing break is requested immediately, pre-empting the originally
142 scheduled break. If this second value is nil, then no pre-emptive breaks
143 will occur; only scheduled ones will.
144
145 Keys with bucky bits (shift, control, meta, etc) are counted as only one
146 keystroke even though they really require multiple keys to generate them.
147
148 The command `type-break-guesstimate-keystroke-threshold' can be used to
149 guess a reasonably good pair of values for this variable."
150 :type 'sexp
151 :group 'type-break)
152
153 (defcustom type-break-query-function 'yes-or-no-p
154 "Function to use for making query for a typing break.
155 It should take a string as an argument, the prompt.
156 Usually this should be set to `yes-or-no-p' or `y-or-n-p'.
157
158 To avoid being queried at all, set `type-break-query-mode' to nil."
159 :type '(radio function
160 (function-item yes-or-no-p)
161 (function-item y-or-n-p))
162 :group 'type-break)
163
164 (defcustom type-break-query-interval 60
165 "Number of seconds between queries to take a break, if put off.
166 The user will continue to be prompted at this interval until he or she
167 finally submits to taking a typing break."
168 :type 'integer
169 :group 'type-break)
170
171 (defcustom type-break-time-warning-intervals '(300 120 60 30)
172 "List of time intervals for warnings about upcoming typing break.
173 At each of the intervals (specified in seconds) away from a scheduled
174 typing break, print a warning in the echo area."
175 :type '(repeat integer)
176 :group 'type-break)
177
178 (defcustom type-break-keystroke-warning-intervals '(300 200 100 50)
179 "List of keystroke measurements for warnings about upcoming typing break.
180 At each of the intervals (specified in keystrokes) away from the upper
181 keystroke threshold, print a warning in the echo area.
182 If either this variable or the upper threshold is set, then no warnings
183 will occur."
184 :type '(repeat integer)
185 :group 'type-break)
186
187 (defcustom type-break-warning-repeat 40
188 "Number of keystrokes for which warnings should be repeated.
189 That is, for each of this many keystrokes the warning is redisplayed
190 in the echo area to make sure it's really seen."
191 :type 'integer
192 :group 'type-break)
193
194 (defcustom type-break-time-stamp-format "[%H:%M] "
195 "Timestamp format used to prefix messages.
196 Format specifiers are as used by `format-time-string'."
197 :type 'string
198 :group 'type-break)
199
200 (defcustom type-break-demo-functions
201 '(type-break-demo-boring type-break-demo-life type-break-demo-hanoi)
202 "List of functions to consider running as demos during typing breaks.
203 When a typing break begins, one of these functions is selected randomly
204 to have Emacs do something interesting.
205
206 Any function in this list should start a demo which ceases as soon as a
207 key is pressed."
208 :type '(repeat function)
209 :group 'type-break)
210
211 (defcustom type-break-demo-boring-stats nil
212 "Show word per minute and keystroke figures in the Boring demo."
213 :type 'boolean
214 :group 'type-break)
215
216 (defcustom type-break-terse-messages nil
217 "Use slightly terser messages."
218 :type 'boolean
219 :group 'type-break)
220
221 (defcustom type-break-file-name (convert-standard-filename "~/.type-break")
222 "Name of file used to save state across sessions.
223 If this is nil, no data will be saved across sessions."
224 :type 'file
225 :group 'type-break)
226
227 (defvar type-break-post-command-hook '(type-break-check)
228 "Hook run indirectly by `post-command-hook' for typing break functions.
229 This is not really intended to be set by the user, but it's probably
230 harmless to do so. Mainly it is used by various parts of the typing break
231 program to delay actions until after the user has completed some command.
232 It exists because `post-command-hook' itself is inaccessible while its
233 functions are being run, and some type-break--related functions want to
234 remove themselves after running.")
235
236 \f
237 ;; Mode line frobs
238
239 (defvar type-break-mode-line-format
240 '(type-break-mode-line-message-mode
241 (""
242 type-break-mode-line-break-message
243 type-break-mode-line-warning))
244 "*Format of messages in the mode line concerning typing breaks.")
245
246 (defvar type-break-mode-line-break-message
247 '(type-break-mode-line-break-message-p
248 type-break-mode-line-break-string))
249
250 (defvar type-break-mode-line-break-message-p nil)
251 (defvar type-break-mode-line-break-string " *** TAKE A TYPING BREAK NOW ***")
252
253 (defvar type-break-mode-line-warning
254 '(type-break-mode-line-break-message-p
255 ("")
256 (type-break-warning-countdown-string
257 (" *** "
258 "Break in "
259 type-break-warning-countdown-string
260 " "
261 type-break-warning-countdown-string-type
262 "***"))))
263
264 (defvar type-break-warning-countdown-string nil
265 "If non-nil, this is a countdown for the next typing break.
266
267 This variable, in conjunction with `type-break-warning-countdown-string-type'
268 \(which indicates whether this value is a number of keystrokes or seconds)
269 is installed in `mode-line-format' to notify of imminent typing breaks.")
270
271 (defvar type-break-warning-countdown-string-type nil
272 "Indicates the unit type of `type-break-warning-countdown-string'.
273 It will be either \"seconds\" or \"keystrokes\".")
274
275 \f
276 ;; These are internal variables. Do not set them yourself.
277
278 (defvar type-break-alarm-p nil)
279 (defvar type-break-keystroke-count 0)
280 (defvar type-break-time-last-break nil)
281 (defvar type-break-time-next-break nil)
282 (defvar type-break-time-last-command (current-time))
283 (defvar type-break-current-time-warning-interval nil)
284 (defvar type-break-current-keystroke-warning-interval nil)
285 (defvar type-break-time-warning-count 0)
286 (defvar type-break-keystroke-warning-count 0)
287 (defvar type-break-interval-start nil)
288
289 \f
290 ;;;###autoload
291 (defun type-break-mode (&optional prefix)
292 "Enable or disable typing-break mode.
293 This is a minor mode, but it is global to all buffers by default.
294
295 When this mode is enabled, the user is encouraged to take typing breaks at
296 appropriate intervals; either after a specified amount of time or when the
297 user has exceeded a keystroke threshold. When the time arrives, the user
298 is asked to take a break. If the user refuses at that time, Emacs will ask
299 again in a short period of time. The idea is to give the user enough time
300 to find a good breaking point in his or her work, but be sufficiently
301 annoying to discourage putting typing breaks off indefinitely.
302
303 A negative prefix argument disables this mode.
304 No argument or any non-negative argument enables it.
305
306 The user may enable or disable this mode by setting the variable of the
307 same name, though setting it in that way doesn't reschedule a break or
308 reset the keystroke counter.
309
310 If the mode was previously disabled and is enabled as a consequence of
311 calling this function, it schedules a break with `type-break-schedule' to
312 make sure one occurs (the user can call that command to reschedule the
313 break at any time). It also initializes the keystroke counter.
314
315 The variable `type-break-interval' specifies the number of seconds to
316 schedule between regular typing breaks. This variable doesn't directly
317 affect the time schedule; it simply provides a default for the
318 `type-break-schedule' command.
319
320 If set, the variable `type-break-good-rest-interval' specifies the minimum
321 amount of time which is considered a reasonable typing break. Whenever
322 that time has elapsed, typing breaks are automatically rescheduled for
323 later even if Emacs didn't prompt you to take one first. Also, if a break
324 is ended before this much time has elapsed, the user will be asked whether
325 or not to continue. A nil value for this variable prevents automatic
326 break rescheduling, making `type-break-interval' an upper bound on the time
327 between breaks. In this case breaks will be prompted for as usual before
328 the upper bound if the keystroke threshold is reached.
329
330 If `type-break-good-rest-interval' is nil and
331 `type-break-good-break-interval' is set, then confirmation is required to
332 interrupt a break before `type-break-good-break-interval' seconds
333 have passed. This provides for an upper bound on the time between breaks
334 together with confirmation of interruptions to these breaks.
335
336 The variable `type-break-keystroke-threshold' is used to determine the
337 thresholds at which typing breaks should be considered. You can use
338 the command `type-break-guesstimate-keystroke-threshold' to try to
339 approximate good values for this.
340
341 There are several variables that affect how or when warning messages about
342 imminent typing breaks are displayed. They include:
343
344 `type-break-mode-line-message-mode'
345 `type-break-time-warning-intervals'
346 `type-break-keystroke-warning-intervals'
347 `type-break-warning-repeat'
348 `type-break-warning-countdown-string'
349 `type-break-warning-countdown-string-type'
350
351 There are several variables that affect if, how, and when queries to begin
352 a typing break occur. They include:
353
354 `type-break-query-mode'
355 `type-break-query-function'
356 `type-break-query-interval'
357
358 The command `type-break-statistics' prints interesting things.
359
360 Finally, a file (named `type-break-file-name') is used to store information
361 across Emacs sessions. This provides recovery of the break status between
362 sessions and after a crash. Manual changes to the file may result in
363 problems."
364 (interactive "P")
365 (type-break-check-post-command-hook)
366
367 (let ((already-enabled type-break-mode))
368 (setq type-break-mode (>= (prefix-numeric-value prefix) 0))
369
370 (cond
371 ((and already-enabled type-break-mode)
372 (and (called-interactively-p 'interactive)
373 (message "Type Break mode is already enabled")))
374 (type-break-mode
375 (when type-break-file-name
376 (with-current-buffer (find-file-noselect type-break-file-name 'nowarn)
377 (setq buffer-save-without-query t)))
378
379 (or global-mode-string
380 (setq global-mode-string '("")))
381 (or (assq 'type-break-mode-line-message-mode
382 minor-mode-alist)
383 (setq minor-mode-alist
384 (cons type-break-mode-line-format
385 minor-mode-alist)))
386 (type-break-keystroke-reset)
387 (type-break-mode-line-countdown-or-break nil)
388
389 (setq type-break-time-last-break
390 (or (type-break-get-previous-time)
391 (current-time)))
392
393 ;; schedule according to break time from session file
394 (type-break-schedule
395 (let (diff)
396 (if (and type-break-time-last-break
397 (< (setq diff (type-break-time-difference
398 type-break-time-last-break
399 (current-time)))
400 type-break-interval))
401 ;; use the file's value
402 (progn
403 (setq type-break-keystroke-count
404 (type-break-get-previous-count))
405 ;; file the time, in case it was read from the auto-save file
406 (type-break-file-time type-break-interval-start)
407 (setq type-break-interval-start type-break-time-last-break)
408 (- type-break-interval diff))
409 ;; schedule from now
410 (setq type-break-interval-start (current-time))
411 (type-break-file-time type-break-interval-start)
412 type-break-interval))
413 type-break-interval-start
414 type-break-interval)
415
416 (and (called-interactively-p 'interactive)
417 (message "Type Break mode is enabled and set")))
418 (t
419 (type-break-keystroke-reset)
420 (type-break-mode-line-countdown-or-break nil)
421 (type-break-cancel-schedule)
422 (do-auto-save)
423 (when type-break-file-name
424 (with-current-buffer (find-file-noselect type-break-file-name
425 'nowarn)
426 (set-buffer-modified-p nil)
427 (unlock-buffer)
428 (kill-this-buffer)))
429 (and (called-interactively-p 'interactive)
430 (message "Type Break mode is disabled")))))
431 type-break-mode)
432
433 (define-minor-mode type-break-mode-line-message-mode
434 "Enable or disable warnings in the mode line about typing breaks.
435
436 A negative PREFIX argument disables this mode.
437 No argument or any non-negative argument enables it.
438
439 The user may also enable or disable this mode simply by setting the
440 variable of the same name.
441
442 Variables controlling the display of messages in the mode line include:
443
444 `mode-line-format'
445 `global-mode-string'
446 `type-break-mode-line-break-message'
447 `type-break-mode-line-warning'"
448 :global t)
449
450 (define-minor-mode type-break-query-mode
451 "Enable or disable warnings in the mode line about typing breaks.
452
453 When enabled, the user is periodically queried about whether to take a
454 typing break at that moment. The function which does this query is
455 specified by the variable `type-break-query-function'.
456
457 A negative PREFIX argument disables this mode.
458 No argument or any non-negative argument enables it.
459
460 The user may also enable or disable this mode simply by setting the
461 variable of the same name."
462 :global t)
463
464 \f
465 ;;; session file functions
466
467 (defvar type-break-auto-save-file-name
468 (let ((buffer-file-name type-break-file-name))
469 (make-auto-save-file-name))
470 "Auto-save name of `type-break-file-name'.")
471
472 (defun type-break-file-time (&optional time)
473 "File break time in `type-break-file-name', unless the file is locked."
474 (if (and type-break-file-name
475 (not (stringp (file-locked-p type-break-file-name))))
476 (with-current-buffer (find-file-noselect type-break-file-name
477 'nowarn)
478 (let ((inhibit-read-only t))
479 (erase-buffer)
480 (insert (format "%s\n\n" (or time type-break-interval-start)))
481 ;; file saving is left to auto-save
482 ))))
483
484 (defun type-break-file-keystroke-count ()
485 "File keystroke count in `type-break-file-name', unless the file is locked."
486 (if (and type-break-file-name
487 (not (stringp (file-locked-p type-break-file-name))))
488 ;; Prevent deactivation of the mark in some other buffer.
489 (let (deactivate-mark)
490 (with-current-buffer (find-file-noselect type-break-file-name
491 'nowarn)
492 (save-excursion
493 (let ((inhibit-read-only t))
494 (goto-char (point-min))
495 (forward-line)
496 (delete-region (point) (line-end-position))
497 (insert (format "%s" type-break-keystroke-count))
498 ;; file saving is left to auto-save
499 ))))))
500
501 (defun timep (time)
502 "If TIME is in the format returned by `current-time' then
503 return TIME, else return nil."
504 (condition-case nil
505 (and (float-time time) time)
506 (error nil)))
507
508 (defun type-break-choose-file ()
509 "Return file to read from."
510 (cond
511 ((not type-break-file-name)
512 nil)
513 ((and (file-exists-p type-break-auto-save-file-name)
514 (file-readable-p type-break-auto-save-file-name))
515 type-break-auto-save-file-name)
516 ((and (file-exists-p type-break-file-name)
517 (file-readable-p type-break-file-name))
518 type-break-file-name)
519 (t nil)))
520
521 (defun type-break-get-previous-time ()
522 "Get previous break time from `type-break-file-name'.
523 Returns nil if the file is missing or if the time breaks with the
524 `current-time' format."
525 (let ((file (type-break-choose-file)))
526 (if file
527 (timep ;; returns expected format, else nil
528 (with-current-buffer (find-file-noselect file 'nowarn)
529 (condition-case nil
530 (save-excursion
531 (goto-char (point-min))
532 (read (current-buffer)))
533 (end-of-file
534 (error "End of file in `%s'" file))))))))
535
536 (defun type-break-get-previous-count ()
537 "Get previous keystroke count from `type-break-file-name'.
538 Return 0 if the file is missing or if the form read is not an
539 integer."
540 (let ((file (type-break-choose-file)))
541 (if (and file
542 (integerp
543 (setq file
544 (with-current-buffer
545 (find-file-noselect file 'nowarn)
546 (condition-case nil
547 (save-excursion
548 (goto-char (point-min))
549 (forward-line 1)
550 (read (current-buffer)))
551 (end-of-file
552 (error "End of file in `%s'" file)))))))
553 file
554 0)))
555
556 \f
557 ;;;###autoload
558 (defun type-break ()
559 "Take a typing break.
560
561 During the break, a demo selected from the functions listed in
562 `type-break-demo-functions' is run.
563
564 After the typing break is finished, the next break is scheduled
565 as per the function `type-break-schedule'."
566 (interactive)
567 (do-auto-save)
568 (type-break-cancel-schedule)
569 ;; remove any query scheduled during interactive invocation
570 (remove-hook 'type-break-post-command-hook 'type-break-do-query)
571 (let ((continue t)
572 (start-time (current-time)))
573 (setq type-break-time-last-break start-time)
574 (while continue
575 (save-window-excursion
576 ;; Eat the screen.
577 (and (eq (selected-window) (minibuffer-window))
578 (other-window 1))
579 (delete-other-windows)
580 (scroll-right (window-width))
581 (unless type-break-terse-messages
582 (message "Press any key to resume from typing break."))
583
584 (random t)
585 (let* ((len (length type-break-demo-functions))
586 (idx (random len))
587 (fn (nth idx type-break-demo-functions)))
588 (condition-case ()
589 (funcall fn)
590 (error nil))))
591
592 (let ((good-interval (or type-break-good-rest-interval
593 type-break-good-break-interval)))
594 (cond
595 (good-interval
596 (let ((break-secs (type-break-time-difference
597 start-time (current-time))))
598 (cond
599 ((>= break-secs good-interval)
600 (setq continue nil))
601 ;; 60 seconds may be too much leeway if the break is only 3
602 ;; minutes to begin with. You can just say "no" to the query
603 ;; below if you're in that much of a hurry.
604 ;;((> 60 (abs (- break-secs good-interval)))
605 ;; (setq continue nil))
606 ((funcall
607 type-break-query-function
608 (format
609 (if type-break-terse-messages
610 "%s%s remaining. Continue break? "
611 "%sYou really ought to rest %s more. Continue break? ")
612 (type-break-time-stamp)
613 (type-break-format-time (- good-interval
614 break-secs)))))
615 (t
616 (setq continue nil)))))
617 (t (setq continue nil))))))
618
619 (type-break-keystroke-reset)
620 (type-break-file-time)
621 (type-break-mode-line-countdown-or-break nil)
622 (type-break-schedule))
623
624 \f
625 (defun type-break-schedule (&optional time start interval)
626 "Schedule a typing break for TIME seconds from now.
627 If time is not specified it defaults to `type-break-interval'.
628 START and INTERVAL are used when recovering a break.
629 START is the start of the break (defaults to now).
630 INTERVAL is the full length of an interval (defaults to TIME)."
631 (interactive (list (and current-prefix-arg
632 (prefix-numeric-value current-prefix-arg))))
633 (or time (setq time type-break-interval))
634 (type-break-check-post-command-hook)
635 (type-break-cancel-schedule)
636 (type-break-time-warning-schedule time 'reset)
637 (type-break-run-at-time (max 1 time) nil 'type-break-alarm)
638 (setq type-break-time-next-break
639 (type-break-time-sum (or start (current-time))
640 (or interval time))))
641
642 (defun type-break-cancel-schedule ()
643 (type-break-cancel-time-warning-schedule)
644 (type-break-cancel-function-timers 'type-break-alarm)
645 (setq type-break-alarm-p nil)
646 (setq type-break-time-next-break nil))
647
648 (defun type-break-time-warning-schedule (&optional time resetp)
649 (let ((type-break-current-time-warning-interval nil))
650 (type-break-cancel-time-warning-schedule))
651 (add-hook 'type-break-post-command-hook 'type-break-time-warning 'append)
652 (cond
653 (type-break-time-warning-intervals
654 (and resetp
655 (setq type-break-current-time-warning-interval
656 type-break-time-warning-intervals))
657
658 (or time
659 (setq time (type-break-time-difference (current-time)
660 type-break-time-next-break)))
661
662 (while (and type-break-current-time-warning-interval
663 (> (car type-break-current-time-warning-interval) time))
664 (setq type-break-current-time-warning-interval
665 (cdr type-break-current-time-warning-interval)))
666
667 (cond
668 (type-break-current-time-warning-interval
669 (setq time (- time (car type-break-current-time-warning-interval)))
670 (setq type-break-current-time-warning-interval
671 (cdr type-break-current-time-warning-interval))
672
673 ;(let (type-break-current-time-warning-interval)
674 ; (type-break-cancel-time-warning-schedule))
675 (type-break-run-at-time (max 1 time) nil 'type-break-time-warning-alarm)
676
677 (cond
678 (resetp
679 (setq type-break-warning-countdown-string nil))
680 (t
681 (setq type-break-warning-countdown-string (number-to-string time))
682 (setq type-break-warning-countdown-string-type "seconds"))))))))
683
684 (defun type-break-cancel-time-warning-schedule ()
685 (type-break-cancel-function-timers 'type-break-time-warning-alarm)
686 (remove-hook 'type-break-post-command-hook 'type-break-time-warning)
687 (setq type-break-current-time-warning-interval
688 type-break-time-warning-intervals)
689 (setq type-break-time-warning-count 0) ; avoid warnings after break
690 (setq type-break-warning-countdown-string nil))
691
692 (defun type-break-alarm ()
693 (type-break-check-post-command-hook)
694 (setq type-break-alarm-p t)
695 (type-break-mode-line-countdown-or-break 'break))
696
697 (defun type-break-time-warning-alarm ()
698 (type-break-check-post-command-hook)
699 (type-break-time-warning-schedule)
700 (setq type-break-time-warning-count type-break-warning-repeat)
701 (type-break-time-warning)
702 (type-break-mode-line-countdown-or-break 'countdown))
703
704 \f
705 (defun type-break-run-tb-post-command-hook ()
706 (and type-break-mode
707 (run-hooks 'type-break-post-command-hook)))
708
709 (defun type-break-check ()
710 "Ask to take a typing break if appropriate.
711 This may be the case either because the scheduled time has come \(and the
712 minimum keystroke threshold has been reached\) or because the maximum
713 keystroke threshold has been exceeded."
714 (type-break-file-keystroke-count)
715 (let* ((min-threshold (car type-break-keystroke-threshold))
716 (max-threshold (cdr type-break-keystroke-threshold)))
717 (and type-break-good-rest-interval
718 (progn
719 (and (> (type-break-time-difference
720 type-break-time-last-command (current-time))
721 type-break-good-rest-interval)
722 (progn
723 (type-break-keystroke-reset)
724 (type-break-mode-line-countdown-or-break nil)
725 (setq type-break-time-last-break (current-time))
726 (type-break-schedule)))
727 (setq type-break-time-last-command (current-time))))
728
729 (and type-break-keystroke-threshold
730 (let ((keys (this-command-keys)))
731 (cond
732 ;; Ignore mouse motion
733 ((and (vectorp keys)
734 (consp (aref keys 0))
735 (memq (car (aref keys 0)) '(mouse-movement))))
736 (t
737 (setq type-break-keystroke-count
738 (+ type-break-keystroke-count (length keys)))))))
739
740 (cond
741 (type-break-alarm-p
742 (cond
743 ((input-pending-p))
744 ((eq (selected-window) (minibuffer-window)))
745 ((and min-threshold
746 (< type-break-keystroke-count min-threshold))
747 (type-break-schedule))
748 (t
749 ;; If keystroke count is within min-threshold of
750 ;; max-threshold, lower it to reduce the likelihood of an
751 ;; immediate subsequent query.
752 (and max-threshold
753 min-threshold
754 (< (- max-threshold type-break-keystroke-count) min-threshold)
755 (progn
756 (type-break-keystroke-reset)
757 (setq type-break-keystroke-count min-threshold)))
758 (type-break-query))))
759 ((and type-break-keystroke-warning-intervals
760 max-threshold
761 (= type-break-keystroke-warning-count 0)
762 (type-break-check-keystroke-warning)))
763 ((and max-threshold
764 (> type-break-keystroke-count max-threshold)
765 (not (input-pending-p))
766 (not (eq (selected-window) (minibuffer-window))))
767 (type-break-keystroke-reset)
768 (setq type-break-keystroke-count (or min-threshold 0))
769 (type-break-query)))))
770
771 ;; This should return t if warnings were enabled, nil otherwise.
772 (defun type-break-check-keystroke-warning ()
773 ;; This is safe because the caller should have checked that the cdr was
774 ;; non-nil already.
775 (let ((left (- (cdr type-break-keystroke-threshold)
776 type-break-keystroke-count)))
777 (cond
778 ((null (car type-break-current-keystroke-warning-interval))
779 nil)
780 ((> left (car type-break-current-keystroke-warning-interval))
781 nil)
782 (t
783 (while (and (car type-break-current-keystroke-warning-interval)
784 (< left (car type-break-current-keystroke-warning-interval)))
785 (setq type-break-current-keystroke-warning-interval
786 (cdr type-break-current-keystroke-warning-interval)))
787 (setq type-break-keystroke-warning-count type-break-warning-repeat)
788 (add-hook 'type-break-post-command-hook 'type-break-keystroke-warning)
789 (setq type-break-warning-countdown-string (number-to-string left))
790 (setq type-break-warning-countdown-string-type "keystrokes")
791 (type-break-mode-line-countdown-or-break 'countdown)
792 t))))
793
794 ;; Arrange for a break query to be made, when the user stops typing furiously.
795 (defun type-break-query ()
796 (add-hook 'type-break-post-command-hook 'type-break-do-query))
797
798 (defun type-break-do-query ()
799 (cond
800 ((not type-break-query-mode)
801 (type-break-noninteractive-query)
802 (type-break-schedule type-break-query-interval)
803 (remove-hook 'type-break-post-command-hook 'type-break-do-query))
804 ((sit-for 2)
805 (condition-case ()
806 (cond
807 ((let ((type-break-mode nil)
808 ;; yes-or-no-p sets this-command to exit-minibuffer,
809 ;; which hoses undo or yank-pop (if you happened to be
810 ;; yanking just when the query occurred).
811 (this-command this-command))
812 ;; Cancel schedule to prevent possibility of a second query
813 ;; from taking place before this one has even returned.
814 ;; The condition-case wrapper will reschedule on quit.
815 (type-break-cancel-schedule)
816 ;; Also prevent a second query when the break is interrupted.
817 (remove-hook 'type-break-post-command-hook 'type-break-do-query)
818 (funcall type-break-query-function
819 (format "%s%s"
820 (type-break-time-stamp)
821 (if type-break-terse-messages
822 "Break now? "
823 "Take a break from typing now? "))))
824 (type-break))
825 (t
826 (type-break-schedule type-break-query-interval)))
827 (quit
828 (type-break-schedule type-break-query-interval))))))
829
830 (defun type-break-noninteractive-query (&optional _ignored-args)
831 "Null query function which doesn't interrupt user and assumes `no'.
832 It prints a reminder in the echo area to take a break, but doesn't enforce
833 this or ask the user to start one right now."
834 (cond
835 (type-break-mode-line-message-mode)
836 (t
837 (beep t)
838 (message "%sYou should take a typing break now. Do `M-x type-break'."
839 (type-break-time-stamp))
840 (sit-for 1)
841 (beep t)
842 ;; return nil so query caller knows to reset reminder, as if user
843 ;; said "no" in response to yes-or-no-p.
844 nil)))
845
846 (defun type-break-time-warning ()
847 (cond
848 ((and (car type-break-keystroke-threshold)
849 (< type-break-keystroke-count (car type-break-keystroke-threshold))))
850 ((> type-break-time-warning-count 0)
851 (let ((timeleft (type-break-time-difference (current-time)
852 type-break-time-next-break)))
853 (setq type-break-warning-countdown-string (number-to-string timeleft))
854 (cond
855 ((eq (selected-window) (minibuffer-window)))
856 ;; Do nothing if the command was just a prefix arg, since that will
857 ;; immediately be followed by some other interactive command.
858 ;; Otherwise, it is particularly annoying for the sit-for below to
859 ;; delay redisplay when one types sequences like `C-u -1 C-l'.
860 ((memq this-command '(digit-argument universal-argument)))
861 ((not type-break-mode-line-message-mode)
862 ;; Pause for a moment so any previous message can be seen.
863 (sit-for 2)
864 (message "%sWarning: typing break due in %s."
865 (type-break-time-stamp)
866 (type-break-format-time timeleft))
867 (setq type-break-time-warning-count
868 (1- type-break-time-warning-count))))))
869 (t
870 (remove-hook 'type-break-post-command-hook 'type-break-time-warning)
871 (setq type-break-warning-countdown-string nil))))
872
873 (defun type-break-keystroke-warning ()
874 (cond
875 ((> type-break-keystroke-warning-count 0)
876 (setq type-break-warning-countdown-string
877 (number-to-string (- (cdr type-break-keystroke-threshold)
878 type-break-keystroke-count)))
879 (cond
880 ((eq (selected-window) (minibuffer-window)))
881 ;; Do nothing if the command was just a prefix arg, since that will
882 ;; immediately be followed by some other interactive command.
883 ;; Otherwise, it is particularly annoying for the sit-for below to
884 ;; delay redisplay when one types sequences like `C-u -1 C-l'.
885 ((memq this-command '(digit-argument universal-argument)))
886 ((not type-break-mode-line-message-mode)
887 (sit-for 2)
888 (message "%sWarning: typing break due in %s keystrokes."
889 (type-break-time-stamp)
890 (- (cdr type-break-keystroke-threshold)
891 type-break-keystroke-count))
892 (setq type-break-keystroke-warning-count
893 (1- type-break-keystroke-warning-count)))))
894 (t
895 (remove-hook 'type-break-post-command-hook
896 'type-break-keystroke-warning)
897 (setq type-break-warning-countdown-string nil))))
898
899 (defun type-break-mode-line-countdown-or-break (&optional type)
900 (cond
901 ((not type-break-mode-line-message-mode))
902 ((eq type 'countdown)
903 ;(setq type-break-mode-line-break-message-p nil)
904 (add-hook 'type-break-post-command-hook
905 'type-break-force-mode-line-update 'append))
906 ((eq type 'break)
907 ;; Alternate
908 (setq type-break-mode-line-break-message-p
909 (not type-break-mode-line-break-message-p))
910 (remove-hook 'type-break-post-command-hook
911 'type-break-force-mode-line-update))
912 (t
913 (setq type-break-mode-line-break-message-p nil)
914 (setq type-break-warning-countdown-string nil)
915 (remove-hook 'type-break-post-command-hook
916 'type-break-force-mode-line-update)))
917 (type-break-force-mode-line-update))
918
919 \f
920 ;;;###autoload
921 (defun type-break-statistics ()
922 "Print statistics about typing breaks in a temporary buffer.
923 This includes the last time a typing break was taken, when the next one is
924 scheduled, the keystroke thresholds and the current keystroke count, etc."
925 (interactive)
926 (with-output-to-temp-buffer "*Typing Break Statistics*"
927 (princ (format "Typing break statistics\n-----------------------\n
928 Typing break mode is currently %s.
929 Interactive query for breaks is %s.
930 Warnings of imminent typing breaks in mode line is %s.
931
932 Last typing break ended : %s
933 Next scheduled typing break : %s\n
934 Minimum keystroke threshold : %s
935 Maximum keystroke threshold : %s
936 Current keystroke count : %s"
937 (if type-break-mode "enabled" "disabled")
938 (if type-break-query-mode "enabled" "disabled")
939 (if type-break-mode-line-message-mode "enabled" "disabled")
940 (if type-break-time-last-break
941 (current-time-string type-break-time-last-break)
942 "never")
943 (if (and type-break-mode type-break-time-next-break)
944 (format "%s\t(%s from now)"
945 (current-time-string type-break-time-next-break)
946 (type-break-format-time
947 (type-break-time-difference
948 (current-time)
949 type-break-time-next-break)))
950 "none scheduled")
951 (or (car type-break-keystroke-threshold) "none")
952 (or (cdr type-break-keystroke-threshold) "none")
953 type-break-keystroke-count))))
954
955 ;;;###autoload
956 (defun type-break-guesstimate-keystroke-threshold (wpm &optional wordlen frac)
957 "Guess values for the minimum/maximum keystroke threshold for typing breaks.
958
959 If called interactively, the user is prompted for their guess as to how
960 many words per minute they usually type. This value should not be your
961 maximum WPM, but your average. Of course, this is harder to gauge since it
962 can vary considerably depending on what you are doing. For example, one
963 tends to type less when debugging a program as opposed to writing
964 documentation. (Perhaps a separate program should be written to estimate
965 average typing speed.)
966
967 From that, this command sets the values in `type-break-keystroke-threshold'
968 based on a fairly simple algorithm involving assumptions about the average
969 length of words (5). For the minimum threshold, it uses about a fifth of
970 the computed maximum threshold.
971
972 When called from Lisp programs, the optional args WORDLEN and FRAC can be
973 used to override the default assumption about average word length and the
974 fraction of the maximum threshold to which to set the minimum threshold.
975 FRAC should be the inverse of the fractional value; for example, a value of
976 2 would mean to use one half, a value of 4 would mean to use one quarter, etc."
977 (interactive "NOn average, how many words per minute do you type? ")
978 (let* ((upper (* wpm (or wordlen 5) (/ type-break-interval 60)))
979 (lower (/ upper (or frac 5))))
980 (or type-break-keystroke-threshold
981 (setq type-break-keystroke-threshold (cons nil nil)))
982 (setcar type-break-keystroke-threshold lower)
983 (setcdr type-break-keystroke-threshold upper)
984 (if (called-interactively-p 'interactive)
985 (message "min threshold: %d\tmax threshold: %d" lower upper))
986 type-break-keystroke-threshold))
987
988 \f
989 ;;; misc functions
990
991 ;; Compute the difference, in seconds, between a and b, two structures
992 ;; similar to those returned by `current-time'.
993 (defun type-break-time-difference (a b)
994 (round (float-time (time-subtract b a))))
995
996 ;; Return (in a new list the same in structure to that returned by
997 ;; `current-time') the sum of the arguments. Each argument may be a time
998 ;; list or a single integer, a number of seconds.
999 ;; This function keeps the high and low 16 bits of the seconds properly
1000 ;; balanced so that the lower value never exceeds 16 bits. Otherwise, when
1001 ;; the result is passed to `current-time-string' it will toss some of the
1002 ;; "low" bits and format the time incorrectly.
1003 (defun type-break-time-sum (&rest tmlist)
1004 (let ((sum '(0 0 0)))
1005 (dolist (tem tmlist sum)
1006 (setq sum (time-add sum (if (integerp tem)
1007 (list (floor tem 65536) (mod tem 65536))
1008 tem))))))
1009
1010 (defun type-break-time-stamp (&optional when)
1011 (if (fboundp 'format-time-string)
1012 (format-time-string type-break-time-stamp-format when)
1013 ;; Emacs 19.28 and prior do not have format-time-string.
1014 ;; In that case, result is not customizable. Upgrade today!
1015 (format "[%s] " (substring (current-time-string when) 11 16))))
1016
1017 (defun type-break-format-time (secs)
1018 (let ((mins (/ secs 60)))
1019 (cond
1020 ((= mins 1) (format "%d minute" mins))
1021 ((> mins 0) (format "%d minutes" mins))
1022 ((= secs 1) (format "%d second" secs))
1023 (t (format "%d seconds" secs)))))
1024
1025 (defun type-break-keystroke-reset ()
1026 (setq type-break-interval-start (current-time)) ; not a keystroke
1027 (setq type-break-keystroke-count 0)
1028 (setq type-break-keystroke-warning-count 0)
1029 (setq type-break-current-keystroke-warning-interval
1030 type-break-keystroke-warning-intervals)
1031 (remove-hook 'type-break-post-command-hook 'type-break-keystroke-warning))
1032
1033 (defun type-break-force-mode-line-update (&optional all)
1034 "Force the mode-line of the current buffer to be redisplayed.
1035 With optional non-nil ALL, force redisplay of all mode-lines."
1036 (and all (with-current-buffer (other-buffer)))
1037 (set-buffer-modified-p (buffer-modified-p)))
1038
1039 ;; If an exception occurs in Emacs while running the post command hook, the
1040 ;; value of that hook is clobbered. This is because the value of the
1041 ;; variable is temporarily set to nil while it's running to prevent
1042 ;; recursive application, but it also means an exception aborts the routine
1043 ;; of restoring it. This function is called from the timers to restore it,
1044 ;; just in case.
1045 (defun type-break-check-post-command-hook ()
1046 (add-hook 'post-command-hook 'type-break-run-tb-post-command-hook 'append))
1047
1048 \f
1049 ;;; Timer wrapper functions
1050 ;;
1051 ;; These shield type-break from variations in the interval timer packages
1052 ;; for different versions of Emacs.
1053
1054 (defun type-break-run-at-time (time repeat function)
1055 (condition-case nil (or (require 'timer) (require 'itimer)) (error nil))
1056 (run-at-time time repeat function))
1057
1058 (defvar timer-dont-exit)
1059 (defun type-break-cancel-function-timers (function)
1060 (let ((timer-dont-exit t))
1061 (cancel-function-timers function)))
1062
1063 \f
1064 ;;; Demo wrappers
1065
1066 (defun type-break-catch-up-event ()
1067 ;; If the last input event is a down-event, read and discard the
1068 ;; corresponding up-event too, to avoid triggering another prompt.
1069 (and (eventp last-input-event)
1070 (memq 'down (event-modifiers last-input-event))
1071 (read-event)))
1072
1073 ;; This is a wrapper around hanoi that calls it with an arg large enough to
1074 ;; make the largest discs possible that will fit in the window.
1075 ;; Also, clean up the *Hanoi* buffer after we're done.
1076 (defun type-break-demo-hanoi ()
1077 "Take a hanoiing typing break."
1078 (and (get-buffer "*Hanoi*")
1079 (kill-buffer "*Hanoi*"))
1080 (condition-case ()
1081 (progn
1082 (hanoi (/ (window-width) 8))
1083 ;; Wait for user to come back.
1084 (read-event)
1085 (type-break-catch-up-event)
1086 (kill-buffer "*Hanoi*"))
1087 (quit
1088 (read-event)
1089 (type-break-catch-up-event)
1090 (and (get-buffer "*Hanoi*")
1091 (kill-buffer "*Hanoi*")))))
1092
1093 ;; This is a wrapper around life that calls it with a `sleep' arg to make
1094 ;; it run a little more leisurely.
1095 ;; Also, clean up the *Life* buffer after we're done.
1096 (defun type-break-demo-life ()
1097 "Take a typing break and get a life."
1098 (let ((continue t))
1099 (while continue
1100 (setq continue nil)
1101 (and (get-buffer "*Life*")
1102 (kill-buffer "*Life*"))
1103 (condition-case ()
1104 (progn
1105 (life 3)
1106 ;; wait for user to return
1107 (read-event)
1108 (type-break-catch-up-event)
1109 (kill-buffer "*Life*"))
1110 (life-extinct
1111 (message "%s" (get 'life-extinct 'error-message))
1112 ;; restart demo
1113 (setq continue t))
1114 (quit
1115 (type-break-catch-up-event)
1116 (and (get-buffer "*Life*")
1117 (kill-buffer "*Life*")))))))
1118
1119 ;; Boring demo, but doesn't use many cycles
1120 (defun type-break-demo-boring ()
1121 "Boring typing break demo."
1122 (let ((rmsg (if type-break-terse-messages
1123 ""
1124 "Press any key to resume from typing break"))
1125 (buffer-name "*Typing Break Buffer*")
1126 lines elapsed timeleft tmsg)
1127 (condition-case ()
1128 (progn
1129 (switch-to-buffer (get-buffer-create buffer-name))
1130 (buffer-disable-undo (current-buffer))
1131 (setq lines (/ (window-body-height) 2))
1132 (unless type-break-terse-messages (setq lines (1- lines)))
1133 (if type-break-demo-boring-stats
1134 (setq lines (- lines 2)))
1135 (setq lines (make-string lines ?\C-j))
1136 (while (not (input-pending-p))
1137 (erase-buffer)
1138 (setq elapsed (type-break-time-difference
1139 type-break-time-last-break
1140 (current-time)))
1141 (let ((good-interval (or type-break-good-rest-interval
1142 type-break-good-break-interval)))
1143 (cond
1144 (good-interval
1145 (setq timeleft (- good-interval elapsed))
1146 (if (> timeleft 0)
1147 (setq tmsg
1148 (format (if type-break-terse-messages
1149 "Break remaining: %s"
1150 "You should rest for %s more")
1151 (type-break-format-time timeleft)))
1152 (setq tmsg
1153 (format (if type-break-terse-messages
1154 "Break complete (%s elapsed in total)"
1155 "Typing break has lasted %s")
1156 (type-break-format-time elapsed)))))
1157 (t
1158 (setq tmsg
1159 (format (if type-break-terse-messages
1160 "Break has lasted %s"
1161 "Typing break has lasted %s")
1162 (type-break-format-time elapsed))))))
1163 (insert lines
1164 (make-string (/ (- (window-width) (length tmsg)) 2) ?\ )
1165 tmsg)
1166 (if (> (length rmsg) 0)
1167 (insert "\n"
1168 (make-string (/ (- (window-width) (length rmsg)) 2)
1169 ?\ )
1170 rmsg))
1171 (if type-break-demo-boring-stats
1172 (let*
1173 ((message
1174 (format
1175 (if type-break-terse-messages
1176 "Since last break: %s keystrokes\n"
1177 "Since your last break you've typed %s keystrokes\n")
1178 type-break-keystroke-count))
1179 (column-spaces
1180 (make-string (/ (- (window-width) (length message)) 2)
1181 ?\ ))
1182 (wpm (/ (/ (float type-break-keystroke-count) 5)
1183 (/ (type-break-time-difference
1184 type-break-interval-start
1185 type-break-time-last-break)
1186 60.0))))
1187 (insert "\n\n" column-spaces message)
1188 (if type-break-terse-messages
1189 (insert (format " %s%.2f wpm"
1190 column-spaces
1191 wpm))
1192 (setq message
1193 (format "at an average of %.2f words per minute"
1194 wpm))
1195 (insert
1196 (make-string (/ (- (window-width) (length message)) 2)
1197 ?\ )
1198 message))))
1199 (goto-char (point-min))
1200 (sit-for 60))
1201 (read-event)
1202 (type-break-catch-up-event)
1203 (kill-buffer buffer-name))
1204 (quit
1205 (and (get-buffer buffer-name)
1206 (kill-buffer buffer-name))))))
1207
1208 \f
1209 (provide 'type-break)
1210
1211 (if type-break-mode
1212 (type-break-mode 1))
1213
1214 ;;; type-break.el ends here