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