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