* trouble.texi (Crashing): Document ulimit -c.
[emacs.git] / lisp / type-break.el
blob8a95508d9393a2b4000652a0b135e24add2c404c
1 ;;; type-break.el --- encourage rests from typing at appropriate intervals
3 ;; Copyright (C) 1994-1995, 1997, 2000-2012 Free Software Foundation, Inc.
5 ;; Author: Noah Friedman
6 ;; Maintainer: Noah Friedman <friedman@splode.com>
7 ;; Keywords: extensions, timers
8 ;; Created: 1994-07-13
10 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;;; Commentary:
27 ;; The docstring for the function `type-break-mode' summarizes most of the
28 ;; details of the interface.
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.
37 ;; If you prefer not to be queried about taking breaks, but instead just
38 ;; want to be reminded, do the following:
40 ;; (setq type-break-query-mode nil)
42 ;; Or call the command `type-break-query-mode' with a negative prefix
43 ;; argument.
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'.
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.
54 ;; This program has no hope of working in Emacs 18.
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>
64 ;;; Code:
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)
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)
85 ;;;###autoload
86 (defcustom type-break-interval (* 60 60)
87 "Number of seconds between scheduled typing breaks."
88 :type 'integer
89 :group 'type-break)
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.
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.
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)
104 ;;;###autoload
105 (defcustom type-break-good-break-interval nil
106 "Number of seconds considered to be an adequate explicit typing rest.
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)
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).
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.
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.
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.
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)
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'.
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)
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)
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)
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)
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)
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)
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.
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)
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)
216 (defcustom type-break-terse-messages nil
217 "Use slightly terser messages."
218 :type 'boolean
219 :group 'type-break)
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)
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.")
237 ;; Mode line frobs
239 (defvar type-break-mode-line-format
240 '(type-break-mode-line-message-mode
242 type-break-mode-line-break-message
243 type-break-mode-line-warning))
244 "Format of messages in the mode line concerning typing breaks.")
246 (defvar type-break-mode-line-break-message
247 '(type-break-mode-line-break-message-p
248 type-break-mode-line-break-string))
250 (defvar type-break-mode-line-break-message-p nil)
251 (defvar type-break-mode-line-break-string " *** TAKE A TYPING BREAK NOW ***")
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
261 type-break-warning-countdown-string-type
262 "***"))))
264 (defvar type-break-warning-countdown-string nil
265 "If non-nil, this is a countdown for the next typing break.
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.")
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\".")
276 ;; These are internal variables. Do not set them yourself.
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)
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.
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.
303 A negative prefix argument disables this mode.
304 No argument or any non-negative argument enables it.
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.
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.
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.
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.
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.
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.
341 There are several variables that affect how or when warning messages about
342 imminent typing breaks are displayed. They include:
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'
351 There are several variables that affect if, how, and when queries to begin
352 a typing break occur. They include:
354 `type-break-query-mode'
355 `type-break-query-function'
356 `type-break-query-interval'
358 The command `type-break-statistics' prints interesting things.
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)
367 (let ((already-enabled type-break-mode))
368 (setq type-break-mode (>= (prefix-numeric-value prefix) 0))
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)))
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)
389 (setq type-break-time-last-break
390 (or (type-break-get-previous-time)
391 (current-time)))
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)
416 (and (called-interactively-p 'interactive)
417 (message "Type Break mode is enabled and set")))
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)
433 (define-minor-mode type-break-mode-line-message-mode
434 "Toggle warnings about typing breaks in the mode line.
435 With a prefix argument ARG, enable these warnings if ARG is
436 positive, and disable them otherwise. If called from Lisp,
437 enable them if ARG is omitted or nil.
439 The user may also enable or disable this mode simply by setting
440 the variable of the same name.
442 Variables controlling the display of messages in the mode line include:
444 `mode-line-format'
445 `global-mode-string'
446 `type-break-mode-line-break-message'
447 `type-break-mode-line-warning'"
448 :global t)
450 (define-minor-mode type-break-query-mode
451 "Toggle typing break queries.
452 With a prefix argument ARG, enable these queries if ARG is
453 positive, and disable them otherwise. If called from Lisp,
454 enable them if ARG is omitted or nil.
456 The user may also enable or disable this mode simply by setting
457 the variable of the same name."
458 :global t)
461 ;;; session file functions
463 (defvar type-break-auto-save-file-name
464 (let ((buffer-file-name type-break-file-name))
465 (make-auto-save-file-name))
466 "Auto-save name of `type-break-file-name'.")
468 (defun type-break-file-time (&optional time)
469 "File break time in `type-break-file-name', unless the file is locked."
470 (if (and type-break-file-name
471 (not (stringp (file-locked-p type-break-file-name))))
472 (with-current-buffer (find-file-noselect type-break-file-name
473 'nowarn)
474 (let ((inhibit-read-only t))
475 (erase-buffer)
476 (insert (format "%s\n\n" (or time type-break-interval-start)))
477 ;; file saving is left to auto-save
478 ))))
480 (defun type-break-file-keystroke-count ()
481 "File keystroke count in `type-break-file-name', unless the file is locked."
482 (if (and type-break-file-name
483 (not (stringp (file-locked-p type-break-file-name))))
484 ;; Prevent deactivation of the mark in some other buffer.
485 (let (deactivate-mark)
486 (with-current-buffer (find-file-noselect type-break-file-name
487 'nowarn)
488 (save-excursion
489 (let ((inhibit-read-only t))
490 (goto-char (point-min))
491 (forward-line)
492 (delete-region (point) (line-end-position))
493 (insert (format "%s" type-break-keystroke-count))
494 ;; file saving is left to auto-save
495 ))))))
497 (defun timep (time)
498 "If TIME is in the format returned by `current-time' then
499 return TIME, else return nil."
500 (condition-case nil
501 (and (float-time time) time)
502 (error nil)))
504 (defun type-break-choose-file ()
505 "Return file to read from."
506 (cond
507 ((not type-break-file-name)
508 nil)
509 ((and (file-exists-p type-break-auto-save-file-name)
510 (file-readable-p type-break-auto-save-file-name))
511 type-break-auto-save-file-name)
512 ((and (file-exists-p type-break-file-name)
513 (file-readable-p type-break-file-name))
514 type-break-file-name)
515 (t nil)))
517 (defun type-break-get-previous-time ()
518 "Get previous break time from `type-break-file-name'.
519 Returns nil if the file is missing or if the time breaks with the
520 `current-time' format."
521 (let ((file (type-break-choose-file)))
522 (if file
523 (timep ;; returns expected format, else nil
524 (with-current-buffer (find-file-noselect file 'nowarn)
525 (condition-case nil
526 (save-excursion
527 (goto-char (point-min))
528 (read (current-buffer)))
529 (end-of-file
530 (error "End of file in `%s'" file))))))))
532 (defun type-break-get-previous-count ()
533 "Get previous keystroke count from `type-break-file-name'.
534 Return 0 if the file is missing or if the form read is not an
535 integer."
536 (let ((file (type-break-choose-file)))
537 (if (and file
538 (integerp
539 (setq file
540 (with-current-buffer
541 (find-file-noselect file 'nowarn)
542 (condition-case nil
543 (save-excursion
544 (goto-char (point-min))
545 (forward-line 1)
546 (read (current-buffer)))
547 (end-of-file
548 (error "End of file in `%s'" file)))))))
549 file
550 0)))
553 ;;;###autoload
554 (defun type-break ()
555 "Take a typing break.
557 During the break, a demo selected from the functions listed in
558 `type-break-demo-functions' is run.
560 After the typing break is finished, the next break is scheduled
561 as per the function `type-break-schedule'."
562 (interactive)
563 (do-auto-save)
564 (type-break-cancel-schedule)
565 ;; remove any query scheduled during interactive invocation
566 (remove-hook 'type-break-post-command-hook 'type-break-do-query)
567 (let ((continue t)
568 (start-time (current-time)))
569 (setq type-break-time-last-break start-time)
570 (while continue
571 (save-window-excursion
572 ;; Eat the screen.
573 (and (eq (selected-window) (minibuffer-window))
574 (other-window 1))
575 (delete-other-windows)
576 (scroll-right (window-width))
577 (unless type-break-terse-messages
578 (message "Press any key to resume from typing break."))
580 (let* ((len (length type-break-demo-functions))
581 (idx (random len))
582 (fn (nth idx type-break-demo-functions)))
583 (condition-case ()
584 (funcall fn)
585 (error nil))))
587 (let ((good-interval (or type-break-good-rest-interval
588 type-break-good-break-interval)))
589 (cond
590 (good-interval
591 (let ((break-secs (type-break-time-difference
592 start-time (current-time))))
593 (cond
594 ((>= break-secs good-interval)
595 (setq continue nil))
596 ;; 60 seconds may be too much leeway if the break is only 3
597 ;; minutes to begin with. You can just say "no" to the query
598 ;; below if you're in that much of a hurry.
599 ;;((> 60 (abs (- break-secs good-interval)))
600 ;; (setq continue nil))
601 ((funcall
602 type-break-query-function
603 (format
604 (if type-break-terse-messages
605 "%s%s remaining. Continue break? "
606 "%sYou really ought to rest %s more. Continue break? ")
607 (type-break-time-stamp)
608 (type-break-format-time (- good-interval
609 break-secs)))))
611 (setq continue nil)))))
612 (t (setq continue nil))))))
614 (type-break-keystroke-reset)
615 (type-break-file-time)
616 (type-break-mode-line-countdown-or-break nil)
617 (type-break-schedule))
620 (defun type-break-schedule (&optional time start interval)
621 "Schedule a typing break for TIME seconds from now.
622 If time is not specified it defaults to `type-break-interval'.
623 START and INTERVAL are used when recovering a break.
624 START is the start of the break (defaults to now).
625 INTERVAL is the full length of an interval (defaults to TIME)."
626 (interactive (list (and current-prefix-arg
627 (prefix-numeric-value current-prefix-arg))))
628 (or time (setq time type-break-interval))
629 (type-break-check-post-command-hook)
630 (type-break-cancel-schedule)
631 (type-break-time-warning-schedule time 'reset)
632 (type-break-run-at-time (max 1 time) nil 'type-break-alarm)
633 (setq type-break-time-next-break
634 (type-break-time-sum (or start (current-time))
635 (or interval time))))
637 (defun type-break-cancel-schedule ()
638 (type-break-cancel-time-warning-schedule)
639 (type-break-cancel-function-timers 'type-break-alarm)
640 (setq type-break-alarm-p nil)
641 (setq type-break-time-next-break nil))
643 (defun type-break-time-warning-schedule (&optional time resetp)
644 (let ((type-break-current-time-warning-interval nil))
645 (type-break-cancel-time-warning-schedule))
646 (add-hook 'type-break-post-command-hook 'type-break-time-warning 'append)
647 (cond
648 (type-break-time-warning-intervals
649 (and resetp
650 (setq type-break-current-time-warning-interval
651 type-break-time-warning-intervals))
653 (or time
654 (setq time (type-break-time-difference (current-time)
655 type-break-time-next-break)))
657 (while (and type-break-current-time-warning-interval
658 (> (car type-break-current-time-warning-interval) time))
659 (setq type-break-current-time-warning-interval
660 (cdr type-break-current-time-warning-interval)))
662 (cond
663 (type-break-current-time-warning-interval
664 (setq time (- time (car type-break-current-time-warning-interval)))
665 (setq type-break-current-time-warning-interval
666 (cdr type-break-current-time-warning-interval))
668 ;(let (type-break-current-time-warning-interval)
669 ; (type-break-cancel-time-warning-schedule))
670 (type-break-run-at-time (max 1 time) nil 'type-break-time-warning-alarm)
672 (cond
673 (resetp
674 (setq type-break-warning-countdown-string nil))
676 (setq type-break-warning-countdown-string (number-to-string time))
677 (setq type-break-warning-countdown-string-type "seconds"))))))))
679 (defun type-break-cancel-time-warning-schedule ()
680 (type-break-cancel-function-timers 'type-break-time-warning-alarm)
681 (remove-hook 'type-break-post-command-hook 'type-break-time-warning)
682 (setq type-break-current-time-warning-interval
683 type-break-time-warning-intervals)
684 (setq type-break-time-warning-count 0) ; avoid warnings after break
685 (setq type-break-warning-countdown-string nil))
687 (defun type-break-alarm ()
688 (type-break-check-post-command-hook)
689 (setq type-break-alarm-p t)
690 (type-break-mode-line-countdown-or-break 'break))
692 (defun type-break-time-warning-alarm ()
693 (type-break-check-post-command-hook)
694 (type-break-time-warning-schedule)
695 (setq type-break-time-warning-count type-break-warning-repeat)
696 (type-break-time-warning)
697 (type-break-mode-line-countdown-or-break 'countdown))
700 (defun type-break-run-tb-post-command-hook ()
701 (and type-break-mode
702 (run-hooks 'type-break-post-command-hook)))
704 (defun type-break-check ()
705 "Ask to take a typing break if appropriate.
706 This may be the case either because the scheduled time has come \(and the
707 minimum keystroke threshold has been reached\) or because the maximum
708 keystroke threshold has been exceeded."
709 (type-break-file-keystroke-count)
710 (let* ((min-threshold (car type-break-keystroke-threshold))
711 (max-threshold (cdr type-break-keystroke-threshold)))
712 (and type-break-good-rest-interval
713 (progn
714 (and (> (type-break-time-difference
715 type-break-time-last-command (current-time))
716 type-break-good-rest-interval)
717 (progn
718 (type-break-keystroke-reset)
719 (type-break-mode-line-countdown-or-break nil)
720 (setq type-break-time-last-break (current-time))
721 (type-break-schedule)))
722 (setq type-break-time-last-command (current-time))))
724 (and type-break-keystroke-threshold
725 (let ((keys (this-command-keys)))
726 (cond
727 ;; Ignore mouse motion
728 ((and (vectorp keys)
729 (consp (aref keys 0))
730 (memq (car (aref keys 0)) '(mouse-movement))))
732 (setq type-break-keystroke-count
733 (+ type-break-keystroke-count (length keys)))))))
735 (cond
736 (type-break-alarm-p
737 (cond
738 ((input-pending-p))
739 ((eq (selected-window) (minibuffer-window)))
740 ((and min-threshold
741 (< type-break-keystroke-count min-threshold))
742 (type-break-schedule))
744 ;; If keystroke count is within min-threshold of
745 ;; max-threshold, lower it to reduce the likelihood of an
746 ;; immediate subsequent query.
747 (and max-threshold
748 min-threshold
749 (< (- max-threshold type-break-keystroke-count) min-threshold)
750 (progn
751 (type-break-keystroke-reset)
752 (setq type-break-keystroke-count min-threshold)))
753 (type-break-query))))
754 ((and type-break-keystroke-warning-intervals
755 max-threshold
756 (= type-break-keystroke-warning-count 0)
757 (type-break-check-keystroke-warning)))
758 ((and max-threshold
759 (> type-break-keystroke-count max-threshold)
760 (not (input-pending-p))
761 (not (eq (selected-window) (minibuffer-window))))
762 (type-break-keystroke-reset)
763 (setq type-break-keystroke-count (or min-threshold 0))
764 (type-break-query)))))
766 ;; This should return t if warnings were enabled, nil otherwise.
767 (defun type-break-check-keystroke-warning ()
768 ;; This is safe because the caller should have checked that the cdr was
769 ;; non-nil already.
770 (let ((left (- (cdr type-break-keystroke-threshold)
771 type-break-keystroke-count)))
772 (cond
773 ((null (car type-break-current-keystroke-warning-interval))
774 nil)
775 ((> left (car type-break-current-keystroke-warning-interval))
776 nil)
778 (while (and (car type-break-current-keystroke-warning-interval)
779 (< left (car type-break-current-keystroke-warning-interval)))
780 (setq type-break-current-keystroke-warning-interval
781 (cdr type-break-current-keystroke-warning-interval)))
782 (setq type-break-keystroke-warning-count type-break-warning-repeat)
783 (add-hook 'type-break-post-command-hook 'type-break-keystroke-warning)
784 (setq type-break-warning-countdown-string (number-to-string left))
785 (setq type-break-warning-countdown-string-type "keystrokes")
786 (type-break-mode-line-countdown-or-break 'countdown)
787 t))))
789 ;; Arrange for a break query to be made, when the user stops typing furiously.
790 (defun type-break-query ()
791 (add-hook 'type-break-post-command-hook 'type-break-do-query))
793 (defun type-break-do-query ()
794 (cond
795 ((not type-break-query-mode)
796 (type-break-noninteractive-query)
797 (type-break-schedule type-break-query-interval)
798 (remove-hook 'type-break-post-command-hook 'type-break-do-query))
799 ((sit-for 2)
800 (condition-case ()
801 (cond
802 ((let ((type-break-mode nil)
803 ;; yes-or-no-p sets this-command to exit-minibuffer,
804 ;; which hoses undo or yank-pop (if you happened to be
805 ;; yanking just when the query occurred).
806 (this-command this-command))
807 ;; Cancel schedule to prevent possibility of a second query
808 ;; from taking place before this one has even returned.
809 ;; The condition-case wrapper will reschedule on quit.
810 (type-break-cancel-schedule)
811 ;; Also prevent a second query when the break is interrupted.
812 (remove-hook 'type-break-post-command-hook 'type-break-do-query)
813 (funcall type-break-query-function
814 (format "%s%s"
815 (type-break-time-stamp)
816 (if type-break-terse-messages
817 "Break now? "
818 "Take a break from typing now? "))))
819 (type-break))
821 (type-break-schedule type-break-query-interval)))
822 (quit
823 (type-break-schedule type-break-query-interval))))))
825 (defun type-break-noninteractive-query (&optional _ignored-args)
826 "Null query function which doesn't interrupt user and assumes `no'.
827 It prints a reminder in the echo area to take a break, but doesn't enforce
828 this or ask the user to start one right now."
829 (cond
830 (type-break-mode-line-message-mode)
832 (beep t)
833 (message "%sYou should take a typing break now. Do `M-x type-break'."
834 (type-break-time-stamp))
835 (sit-for 1)
836 (beep t)
837 ;; return nil so query caller knows to reset reminder, as if user
838 ;; said "no" in response to yes-or-no-p.
839 nil)))
841 (defun type-break-time-warning ()
842 (cond
843 ((and (car type-break-keystroke-threshold)
844 (< type-break-keystroke-count (car type-break-keystroke-threshold))))
845 ((> type-break-time-warning-count 0)
846 (let ((timeleft (type-break-time-difference (current-time)
847 type-break-time-next-break)))
848 (setq type-break-warning-countdown-string (number-to-string timeleft))
849 (cond
850 ((eq (selected-window) (minibuffer-window)))
851 ;; Do nothing if the command was just a prefix arg, since that will
852 ;; immediately be followed by some other interactive command.
853 ;; Otherwise, it is particularly annoying for the sit-for below to
854 ;; delay redisplay when one types sequences like `C-u -1 C-l'.
855 ((memq this-command '(digit-argument universal-argument)))
856 ((not type-break-mode-line-message-mode)
857 ;; Pause for a moment so any previous message can be seen.
858 (sit-for 2)
859 (message "%sWarning: typing break due in %s."
860 (type-break-time-stamp)
861 (type-break-format-time timeleft))
862 (setq type-break-time-warning-count
863 (1- type-break-time-warning-count))))))
865 (remove-hook 'type-break-post-command-hook 'type-break-time-warning)
866 (setq type-break-warning-countdown-string nil))))
868 (defun type-break-keystroke-warning ()
869 (cond
870 ((> type-break-keystroke-warning-count 0)
871 (setq type-break-warning-countdown-string
872 (number-to-string (- (cdr type-break-keystroke-threshold)
873 type-break-keystroke-count)))
874 (cond
875 ((eq (selected-window) (minibuffer-window)))
876 ;; Do nothing if the command was just a prefix arg, since that will
877 ;; immediately be followed by some other interactive command.
878 ;; Otherwise, it is particularly annoying for the sit-for below to
879 ;; delay redisplay when one types sequences like `C-u -1 C-l'.
880 ((memq this-command '(digit-argument universal-argument)))
881 ((not type-break-mode-line-message-mode)
882 (sit-for 2)
883 (message "%sWarning: typing break due in %s keystrokes."
884 (type-break-time-stamp)
885 (- (cdr type-break-keystroke-threshold)
886 type-break-keystroke-count))
887 (setq type-break-keystroke-warning-count
888 (1- type-break-keystroke-warning-count)))))
890 (remove-hook 'type-break-post-command-hook
891 'type-break-keystroke-warning)
892 (setq type-break-warning-countdown-string nil))))
894 (defun type-break-mode-line-countdown-or-break (&optional type)
895 (cond
896 ((not type-break-mode-line-message-mode))
897 ((eq type 'countdown)
898 ;(setq type-break-mode-line-break-message-p nil)
899 (add-hook 'type-break-post-command-hook
900 'type-break-force-mode-line-update 'append))
901 ((eq type 'break)
902 ;; Alternate
903 (setq type-break-mode-line-break-message-p
904 (not type-break-mode-line-break-message-p))
905 (remove-hook 'type-break-post-command-hook
906 'type-break-force-mode-line-update))
908 (setq type-break-mode-line-break-message-p nil)
909 (setq type-break-warning-countdown-string nil)
910 (remove-hook 'type-break-post-command-hook
911 'type-break-force-mode-line-update)))
912 (type-break-force-mode-line-update))
915 ;;;###autoload
916 (defun type-break-statistics ()
917 "Print statistics about typing breaks in a temporary buffer.
918 This includes the last time a typing break was taken, when the next one is
919 scheduled, the keystroke thresholds and the current keystroke count, etc."
920 (interactive)
921 (with-output-to-temp-buffer "*Typing Break Statistics*"
922 (princ (format "Typing break statistics\n-----------------------\n
923 Typing break mode is currently %s.
924 Interactive query for breaks is %s.
925 Warnings of imminent typing breaks in mode line is %s.
927 Last typing break ended : %s
928 Next scheduled typing break : %s\n
929 Minimum keystroke threshold : %s
930 Maximum keystroke threshold : %s
931 Current keystroke count : %s"
932 (if type-break-mode "enabled" "disabled")
933 (if type-break-query-mode "enabled" "disabled")
934 (if type-break-mode-line-message-mode "enabled" "disabled")
935 (if type-break-time-last-break
936 (current-time-string type-break-time-last-break)
937 "never")
938 (if (and type-break-mode type-break-time-next-break)
939 (format "%s\t(%s from now)"
940 (current-time-string type-break-time-next-break)
941 (type-break-format-time
942 (type-break-time-difference
943 (current-time)
944 type-break-time-next-break)))
945 "none scheduled")
946 (or (car type-break-keystroke-threshold) "none")
947 (or (cdr type-break-keystroke-threshold) "none")
948 type-break-keystroke-count))))
950 ;;;###autoload
951 (defun type-break-guesstimate-keystroke-threshold (wpm &optional wordlen frac)
952 "Guess values for the minimum/maximum keystroke threshold for typing breaks.
954 If called interactively, the user is prompted for their guess as to how
955 many words per minute they usually type. This value should not be your
956 maximum WPM, but your average. Of course, this is harder to gauge since it
957 can vary considerably depending on what you are doing. For example, one
958 tends to type less when debugging a program as opposed to writing
959 documentation. (Perhaps a separate program should be written to estimate
960 average typing speed.)
962 From that, this command sets the values in `type-break-keystroke-threshold'
963 based on a fairly simple algorithm involving assumptions about the average
964 length of words (5). For the minimum threshold, it uses about a fifth of
965 the computed maximum threshold.
967 When called from Lisp programs, the optional args WORDLEN and FRAC can be
968 used to override the default assumption about average word length and the
969 fraction of the maximum threshold to which to set the minimum threshold.
970 FRAC should be the inverse of the fractional value; for example, a value of
971 2 would mean to use one half, a value of 4 would mean to use one quarter, etc."
972 (interactive "NOn average, how many words per minute do you type? ")
973 (let* ((upper (* wpm (or wordlen 5) (/ type-break-interval 60)))
974 (lower (/ upper (or frac 5))))
975 (or type-break-keystroke-threshold
976 (setq type-break-keystroke-threshold (cons nil nil)))
977 (setcar type-break-keystroke-threshold lower)
978 (setcdr type-break-keystroke-threshold upper)
979 (if (called-interactively-p 'interactive)
980 (message "min threshold: %d\tmax threshold: %d" lower upper))
981 type-break-keystroke-threshold))
984 ;;; misc functions
986 ;; Compute the difference, in seconds, between a and b, two structures
987 ;; similar to those returned by `current-time'.
988 (defun type-break-time-difference (a b)
989 (round (float-time (time-subtract b a))))
991 ;; Return (in a new list the same in structure to that returned by
992 ;; `current-time') the sum of the arguments. Each argument may be a time
993 ;; list or a single integer, a number of seconds.
994 ;; This function keeps the high and low 16 bits of the seconds properly
995 ;; balanced so that the lower value never exceeds 16 bits. Otherwise, when
996 ;; the result is passed to `current-time-string' it will toss some of the
997 ;; "low" bits and format the time incorrectly.
998 (defun type-break-time-sum (&rest tmlist)
999 (let ((sum '(0 0 0)))
1000 (dolist (tem tmlist sum)
1001 (setq sum (time-add sum (if (integerp tem)
1002 (list (floor tem 65536) (mod tem 65536))
1003 tem))))))
1005 (defun type-break-time-stamp (&optional when)
1006 (if (fboundp 'format-time-string)
1007 (format-time-string type-break-time-stamp-format when)
1008 ;; Emacs 19.28 and prior do not have format-time-string.
1009 ;; In that case, result is not customizable. Upgrade today!
1010 (format "[%s] " (substring (current-time-string when) 11 16))))
1012 (defun type-break-format-time (secs)
1013 (let ((mins (/ secs 60)))
1014 (cond
1015 ((= mins 1) (format "%d minute" mins))
1016 ((> mins 0) (format "%d minutes" mins))
1017 ((= secs 1) (format "%d second" secs))
1018 (t (format "%d seconds" secs)))))
1020 (defun type-break-keystroke-reset ()
1021 (setq type-break-interval-start (current-time)) ; not a keystroke
1022 (setq type-break-keystroke-count 0)
1023 (setq type-break-keystroke-warning-count 0)
1024 (setq type-break-current-keystroke-warning-interval
1025 type-break-keystroke-warning-intervals)
1026 (remove-hook 'type-break-post-command-hook 'type-break-keystroke-warning))
1028 (defun type-break-force-mode-line-update (&optional all)
1029 "Force the mode-line of the current buffer to be redisplayed.
1030 With optional non-nil ALL, force redisplay of all mode-lines."
1031 (and all (with-current-buffer (other-buffer)))
1032 (set-buffer-modified-p (buffer-modified-p)))
1034 ;; If an exception occurs in Emacs while running the post command hook, the
1035 ;; value of that hook is clobbered. This is because the value of the
1036 ;; variable is temporarily set to nil while it's running to prevent
1037 ;; recursive application, but it also means an exception aborts the routine
1038 ;; of restoring it. This function is called from the timers to restore it,
1039 ;; just in case.
1040 (defun type-break-check-post-command-hook ()
1041 (add-hook 'post-command-hook 'type-break-run-tb-post-command-hook 'append))
1044 ;;; Timer wrapper functions
1046 ;; These shield type-break from variations in the interval timer packages
1047 ;; for different versions of Emacs.
1049 (defun type-break-run-at-time (time repeat function)
1050 (condition-case nil (or (require 'timer) (require 'itimer)) (error nil))
1051 (run-at-time time repeat function))
1053 (defvar timer-dont-exit)
1054 (defun type-break-cancel-function-timers (function)
1055 (let ((timer-dont-exit t))
1056 (cancel-function-timers function)))
1059 ;;; Demo wrappers
1061 (defun type-break-catch-up-event ()
1062 ;; If the last input event is a down-event, read and discard the
1063 ;; corresponding up-event too, to avoid triggering another prompt.
1064 (and (eventp last-input-event)
1065 (memq 'down (event-modifiers last-input-event))
1066 (read-event)))
1068 ;; This is a wrapper around hanoi that calls it with an arg large enough to
1069 ;; make the largest discs possible that will fit in the window.
1070 ;; Also, clean up the *Hanoi* buffer after we're done.
1071 (defun type-break-demo-hanoi ()
1072 "Take a hanoiing typing break."
1073 (and (get-buffer "*Hanoi*")
1074 (kill-buffer "*Hanoi*"))
1075 (condition-case ()
1076 (progn
1077 (hanoi (/ (window-width) 8))
1078 ;; Wait for user to come back.
1079 (read-event)
1080 (type-break-catch-up-event)
1081 (kill-buffer "*Hanoi*"))
1082 (quit
1083 (read-event)
1084 (type-break-catch-up-event)
1085 (and (get-buffer "*Hanoi*")
1086 (kill-buffer "*Hanoi*")))))
1088 ;; This is a wrapper around life that calls it with a `sleep' arg to make
1089 ;; it run a little more leisurely.
1090 ;; Also, clean up the *Life* buffer after we're done.
1091 (defun type-break-demo-life ()
1092 "Take a typing break and get a life."
1093 (let ((continue t))
1094 (while continue
1095 (setq continue nil)
1096 (and (get-buffer "*Life*")
1097 (kill-buffer "*Life*"))
1098 (condition-case ()
1099 (progn
1100 (life 3)
1101 ;; wait for user to return
1102 (read-event)
1103 (type-break-catch-up-event)
1104 (kill-buffer "*Life*"))
1105 (life-extinct
1106 (message "%s" (get 'life-extinct 'error-message))
1107 ;; restart demo
1108 (setq continue t))
1109 (quit
1110 (type-break-catch-up-event)
1111 (and (get-buffer "*Life*")
1112 (kill-buffer "*Life*")))))))
1114 ;; Boring demo, but doesn't use many cycles
1115 (defun type-break-demo-boring ()
1116 "Boring typing break demo."
1117 (let ((rmsg (if type-break-terse-messages
1119 "Press any key to resume from typing break"))
1120 (buffer-name "*Typing Break Buffer*")
1121 lines elapsed timeleft tmsg)
1122 (condition-case ()
1123 (progn
1124 (switch-to-buffer (get-buffer-create buffer-name))
1125 (buffer-disable-undo (current-buffer))
1126 (setq lines (/ (window-body-height) 2))
1127 (unless type-break-terse-messages (setq lines (1- lines)))
1128 (if type-break-demo-boring-stats
1129 (setq lines (- lines 2)))
1130 (setq lines (make-string lines ?\C-j))
1131 (while (not (input-pending-p))
1132 (erase-buffer)
1133 (setq elapsed (type-break-time-difference
1134 type-break-time-last-break
1135 (current-time)))
1136 (let ((good-interval (or type-break-good-rest-interval
1137 type-break-good-break-interval)))
1138 (cond
1139 (good-interval
1140 (setq timeleft (- good-interval elapsed))
1141 (if (> timeleft 0)
1142 (setq tmsg
1143 (format (if type-break-terse-messages
1144 "Break remaining: %s"
1145 "You should rest for %s more")
1146 (type-break-format-time timeleft)))
1147 (setq tmsg
1148 (format (if type-break-terse-messages
1149 "Break complete (%s elapsed in total)"
1150 "Typing break has lasted %s")
1151 (type-break-format-time elapsed)))))
1153 (setq tmsg
1154 (format (if type-break-terse-messages
1155 "Break has lasted %s"
1156 "Typing break has lasted %s")
1157 (type-break-format-time elapsed))))))
1158 (insert lines
1159 (make-string (/ (- (window-width) (length tmsg)) 2) ?\ )
1160 tmsg)
1161 (if (> (length rmsg) 0)
1162 (insert "\n"
1163 (make-string (/ (- (window-width) (length rmsg)) 2)
1164 ?\ )
1165 rmsg))
1166 (if type-break-demo-boring-stats
1167 (let*
1168 ((message
1169 (format
1170 (if type-break-terse-messages
1171 "Since last break: %s keystrokes\n"
1172 "Since your last break you've typed %s keystrokes\n")
1173 type-break-keystroke-count))
1174 (column-spaces
1175 (make-string (/ (- (window-width) (length message)) 2)
1176 ?\ ))
1177 (wpm (/ (/ (float type-break-keystroke-count) 5)
1178 (/ (type-break-time-difference
1179 type-break-interval-start
1180 type-break-time-last-break)
1181 60.0))))
1182 (insert "\n\n" column-spaces message)
1183 (if type-break-terse-messages
1184 (insert (format " %s%.2f wpm"
1185 column-spaces
1186 wpm))
1187 (setq message
1188 (format "at an average of %.2f words per minute"
1189 wpm))
1190 (insert
1191 (make-string (/ (- (window-width) (length message)) 2)
1192 ?\ )
1193 message))))
1194 (goto-char (point-min))
1195 (sit-for 60))
1196 (read-event)
1197 (type-break-catch-up-event)
1198 (kill-buffer buffer-name))
1199 (quit
1200 (and (get-buffer buffer-name)
1201 (kill-buffer buffer-name))))))
1204 (provide 'type-break)
1206 (if type-break-mode
1207 (type-break-mode 1))
1209 ;;; type-break.el ends here