Fix problems caused by calling 'recenter' in auto-revert (Bug#20122)
[emacs.git] / lisp / tutorial.el
blob3b007610c9e8af5b1bb1ced1967136f00b220065
1 ;;; tutorial.el --- tutorial for Emacs
3 ;; Copyright (C) 2006-2015 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: help, internal
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Code for running the Emacs tutorial.
28 ;;; History:
30 ;; File was created 2006-09.
32 ;;; Code:
34 (require 'help-mode) ;; for function help-buffer
36 (defface tutorial-warning-face
37 '((t :inherit font-lock-warning-face))
38 "Face used to highlight warnings in the tutorial."
39 :group 'help)
41 (defvar tutorial--point-before-chkeys 0
42 "Point before display of key changes.")
43 (make-variable-buffer-local 'tutorial--point-before-chkeys)
45 (defvar tutorial--point-after-chkeys 0
46 "Point after display of key changes.")
47 (make-variable-buffer-local 'tutorial--point-after-chkeys)
49 (defvar tutorial--lang nil
50 "Tutorial language.")
51 (make-variable-buffer-local 'tutorial--lang)
53 (defun tutorial--describe-nonstandard-key (value)
54 "Give more information about a changed key binding.
55 This is used in `help-with-tutorial'. The information includes
56 the key sequence that no longer has a default binding, the
57 default binding and the current binding. It also tells in what
58 keymap the new binding has been done and how to access the
59 function in the default binding from the keyboard.
61 For `cua-mode' key bindings that try to combine CUA key bindings
62 with default Emacs bindings information about this is shown.
64 VALUE should have either of these formats:
66 \(cua-mode)
67 \(current-binding KEY-FUN DEF-FUN KEY WHERE)
69 Where
70 KEY is a key sequence whose standard binding has been changed
71 KEY-FUN is the actual binding for KEY
72 DEF-FUN is the standard binding of KEY
73 WHERE is a text describing the key sequences to which DEF-FUN is
74 bound now (or, if it is remapped, a key sequence
75 for the function it is remapped to)"
76 (with-output-to-temp-buffer (help-buffer)
77 (help-setup-xref (list #'tutorial--describe-nonstandard-key value)
78 (called-interactively-p 'interactive))
79 (with-current-buffer (help-buffer)
80 (insert
81 "Your Emacs customizations override the default binding for this key:"
82 "\n\n")
83 (let ((inhibit-read-only t))
84 (cond
85 ((eq (car value) 'cua-mode)
86 (insert
87 "CUA mode is enabled.
89 When CUA mode is enabled, you can use C-z, C-x, C-c, and C-v to
90 undo, cut, copy, and paste in addition to the normal Emacs
91 bindings. The C-x and C-c keys only do cut and copy when the
92 region is active, so in most cases, they do not conflict with the
93 normal function of these prefix keys.
95 If you really need to perform a command which starts with one of
96 the prefix keys even when the region is active, you have three
97 options:
98 - press the prefix key twice very quickly (within 0.2 seconds),
99 - press the prefix key and the following key within 0.2 seconds, or
100 - use the SHIFT key with the prefix key, i.e. C-S-x or C-S-c."))
101 ((eq (car value) 'current-binding)
102 (let ((cb (nth 1 value))
103 (db (nth 2 value))
104 (key (nth 3 value))
105 (where (nth 4 value))
107 (maps (current-active-maps))
108 mapsym)
109 ;; Look at the currently active keymaps and try to find
110 ;; first the keymap where the current binding occurs:
111 (while maps
112 (let* ((m (car maps))
113 (mb (lookup-key m key t)))
114 (setq maps (cdr maps))
115 (when (eq mb cb)
116 (setq map m)
117 (setq maps nil))))
118 ;; Now, if a keymap was found we must found the symbol
119 ;; name for it to display to the user. This can not
120 ;; always be found since all keymaps does not have a
121 ;; symbol pointing to them, but here they should have
122 ;; that:
123 (when map
124 (mapatoms (lambda (s)
125 (and
126 ;; If not already found
127 (not mapsym)
128 ;; and if s is a keymap
129 (and (boundp s)
130 (keymapp (symbol-value s)))
131 ;; and not the local symbol map
132 (not (eq s 'map))
133 ;; and the value of s is map
134 (eq map (symbol-value s))
135 ;; then save this value in mapsym
136 (setq mapsym s)))))
137 (insert "The default Emacs binding for the key "
138 (key-description key)
139 " is the command `")
140 (insert (format "%s" db))
141 (insert "'. "
142 "However, your customizations have "
143 (if cb
144 (format "rebound it to the command `%s'" cb)
145 "unbound it"))
146 (insert ".")
147 (when mapsym
148 (insert " (For the more advanced user:"
149 " This binding is in the keymap `"
150 (format "%s" mapsym)
151 "'.)"))
152 (if (string= where "")
153 (unless (keymapp db)
154 (insert "\n\nYou can use M-x "
155 (format "%s" db)
156 " RET instead."))
157 (insert "\n\nWith your current key bindings"
158 " you can use "
159 (if (string-match-p "^the .*menus?$" where)
161 "the key")
162 where
163 " to get the function `"
164 (format "%s" db)
165 "'.")))
166 (fill-region (point-min) (point)))))
167 (help-print-return-message))))
169 (defun tutorial--sort-keys (left right)
170 "Sort predicate for use with `tutorial--default-keys'.
171 This is a predicate function to `sort'.
173 The sorting is for presentation purpose only and is done on the
174 key sequence.
176 LEFT and RIGHT are the elements to compare."
177 (let ((x (append (cadr left) nil))
178 (y (append (cadr right) nil)))
179 ;; Skip the front part of the key sequences if they are equal:
180 (while (and x y
181 (listp x) (listp y)
182 (equal (car x) (car y)))
183 (setq x (cdr x))
184 (setq y (cdr y)))
185 ;; Try to make a comparison that is useful for presentation (this
186 ;; could be made nicer perhaps):
187 (let ((cx (car x))
188 (cy (car y)))
189 ;;(message "x=%s, y=%s;;;; cx=%s, cy=%s" x y cx cy)
190 (cond
191 ;; Lists? Then call this again
192 ((and cx cy
193 (listp cx)
194 (listp cy))
195 (tutorial--sort-keys cx cy))
196 ;; Are both numbers? Then just compare them
197 ((and (wholenump cx)
198 (wholenump cy))
199 (> cx cy))
200 ;; Is one of them a number? Let that be bigger then.
201 ((wholenump cx)
203 ((wholenump cy)
204 nil)
205 ;; Are both symbols? Compare the names then.
206 ((and (symbolp cx)
207 (symbolp cy))
208 (string< (symbol-name cy)
209 (symbol-name cx)))))))
211 (defconst tutorial--default-keys
212 ;; On window system, `suspend-emacs' is replaced in the default keymap.
213 (let* ((suspend-emacs 'suspend-frame)
214 (default-keys
215 ;; The first few are not mentioned but are basic:
216 `((ESC-prefix [27])
217 (Control-X-prefix [?\C-x])
218 (mode-specific-command-prefix [?\C-c])
219 (save-buffers-kill-terminal [?\C-x ?\C-c])
221 ;; * SUMMARY
222 (scroll-up-command [?\C-v])
223 (scroll-down-command [?\M-v])
224 (recenter-top-bottom [?\C-l])
226 ;; * BASIC CURSOR CONTROL
227 (forward-char [?\C-f])
228 (backward-char [?\C-b])
229 (forward-word [?\M-f])
230 (backward-word [?\M-b])
231 (next-line [?\C-n])
232 (previous-line [?\C-p])
233 (move-beginning-of-line [?\C-a])
234 (move-end-of-line [?\C-e])
235 (backward-sentence [?\M-a])
236 (forward-sentence [?\M-e])
237 (newline "\r")
238 (beginning-of-buffer [?\M-<])
239 (end-of-buffer [?\M->])
240 (universal-argument [?\C-u])
242 ;; * WHEN EMACS IS HUNG
243 (keyboard-quit [?\C-g])
245 ;; * DISABLED COMMANDS
246 (downcase-region [?\C-x ?\C-l])
248 ;; * WINDOWS
249 (delete-other-windows [?\C-x ?1])
250 ;; C-u 0 C-l
251 ;; Type CONTROL-h k CONTROL-f.
253 ;; * INSERTING AND DELETING
254 ;; C-u 8 * to insert ********.
255 (delete-backward-char "\d")
256 (delete-char [?\C-d])
257 (backward-kill-word [?\M-\d])
258 (kill-word [?\M-d])
259 (kill-line [?\C-k])
260 (kill-sentence [?\M-k])
261 (set-mark-command [?\C-@])
262 (set-mark-command [?\C- ])
263 (kill-region [?\C-w])
264 (yank [?\C-y])
265 (yank-pop [?\M-y])
267 ;; * UNDO
268 (undo [?\C-x ?u])
270 ;; * FILES
271 (find-file [?\C-x ?\C-f])
272 (save-buffer [?\C-x ?\C-s])
274 ;; * BUFFERS
275 (list-buffers [?\C-x ?\C-b])
276 (switch-to-buffer [?\C-x ?b])
277 (save-some-buffers [?\C-x ?s])
279 ;; * EXTENDING THE COMMAND SET
280 ;; C-x Character eXtend. Followed by one character.
281 (execute-extended-command [?\M-x])
282 ;; C-x C-f Find file
283 ;; C-x C-s Save file
284 ;; C-x s Save some buffers
285 ;; C-x C-b List buffers
286 ;; C-x b Switch buffer
287 ;; C-x C-c Quit Emacs
288 ;; C-x 1 Delete all but one window
289 ;; C-x u Undo
291 ;; * MODE LINE
292 (describe-mode [?\C-h ?m])
293 (set-fill-column [?\C-x ?f])
294 (fill-paragraph [?\M-q])
296 ;; * SEARCHING
297 (isearch-forward [?\C-s])
298 (isearch-backward [?\C-r])
300 ;; * MULTIPLE WINDOWS
301 (split-window-below [?\C-x ?2])
302 (scroll-other-window [?\C-\M-v])
303 (other-window [?\C-x ?o])
304 (find-file-other-window [?\C-x ?4 ?\C-f])
306 ;; * RECURSIVE EDITING LEVELS
307 (keyboard-escape-quit [27 27 27])
309 ;; * GETTING MORE HELP
310 ;; The most basic HELP feature is C-h c
311 (describe-key-briefly [?\C-h ?c])
312 (describe-key [?\C-h ?k])
314 ;; * MORE FEATURES
315 ;; F10
317 ;; * CONCLUSION
318 ;;(iconify-or-deiconify-frame [?\C-z])
319 (,suspend-emacs [?\C-z]))))
320 (sort default-keys 'tutorial--sort-keys))
321 "Default Emacs key bindings that the tutorial depends on.")
323 (defun tutorial--detailed-help (button)
324 "Give detailed help about changed keys."
325 (with-output-to-temp-buffer (help-buffer)
326 (help-setup-xref (list #'tutorial--detailed-help button)
327 (called-interactively-p 'interactive))
328 (with-current-buffer (help-buffer)
329 (let* ((tutorial-buffer (button-get button 'tutorial-buffer))
330 (explain-key-desc (button-get button 'explain-key-desc))
331 (changed-keys (with-current-buffer tutorial-buffer
332 (save-excursion
333 (goto-char (point-min))
334 (tutorial--find-changed-keys
335 tutorial--default-keys)))))
336 (when changed-keys
337 (insert
338 "The following key bindings used in the tutorial have been changed
339 from the Emacs default:\n\n" )
340 (let ((frm " %-14s %-27s %-16s\n"))
341 (insert (format frm
342 "Standard Key" "Command" "In Your Emacs")))
343 (dolist (tk changed-keys)
344 (let* ((def-fun (nth 1 tk))
345 (key (nth 0 tk))
346 (def-fun-txt (nth 2 tk))
347 (where (nth 3 tk))
348 (remark (nth 4 tk))
349 (key-txt (key-description key))
350 (key-fun (with-current-buffer tutorial-buffer (key-binding key))))
351 (unless (eq def-fun key-fun)
352 ;; Insert key binding description:
353 (when (string= key-txt explain-key-desc)
354 (put-text-property 0 (length key-txt)
355 'face 'tutorial-warning-face key-txt))
356 (insert " " key-txt " ")
357 (indent-to 18)
358 ;; Insert a link describing the old binding:
359 (insert-button def-fun-txt
360 'value def-fun
361 'action
362 (lambda (button) (interactive)
363 (describe-function
364 (button-get button 'value)))
365 'follow-link t)
366 (indent-to 45)
367 (when (listp where)
368 (setq where "list"))
369 ;; Tell where the old binding is now:
370 (insert (format " %-16s "
371 (if (string= "" where)
372 (format "M-x %s" def-fun-txt)
373 where)))
374 ;; Insert a link with more information, for example
375 ;; current binding and keymap or information about
376 ;; cua-mode replacements:
377 (insert-button (car remark)
378 'action
379 (lambda (b) (interactive)
380 (let ((value (button-get b 'value)))
381 (tutorial--describe-nonstandard-key value)))
382 'value (cdr remark)
383 'follow-link t)
384 (insert "\n")))))
386 (insert "
387 It is OK to change key bindings, but changed bindings do not
388 correspond to what the tutorial says.\n\n")
389 (help-print-return-message)))))
391 (defun tutorial--find-changed-keys (default-keys)
392 "Find the key bindings used in the tutorial that have changed.
393 Return a list with elements of the form
395 '(KEY DEF-FUN DEF-FUN-TXT WHERE REMARK QUIET)
397 where
399 KEY is a key sequence whose standard binding has been changed
400 DEF-FUN is the standard binding of KEY
401 DEF-FUN-TXT is a short descriptive text for DEF-FUN
402 WHERE is a text describing the key sequences to which DEF-FUN is
403 bound now (or, if it is remapped, a key sequence
404 for the function it is remapped to)
405 REMARK is a list with info about rebinding. It has either of
406 these formats:
408 \(TEXT cua-mode)
409 \(TEXT current-binding KEY-FUN DEF-FUN KEY WHERE)
411 Here TEXT is a link text to show to the user. The
412 rest of the list is used to show information when
413 the user clicks the link.
415 KEY-FUN is the actual binding for KEY.
416 QUIET is t if this changed keybinding should be handled quietly.
417 This is used by `tutorial--display-changes'."
418 (let (changed-keys remark)
419 ;; Look up the bindings in a Fundamental mode buffer
420 ;; so we do not get fooled by some other major mode.
421 (with-temp-buffer
422 (fundamental-mode)
423 (dolist (kdf default-keys)
424 ;; The variables below corresponds to those with the same names
425 ;; described in the doc string.
426 (let* ((key (nth 1 kdf))
427 (def-fun (nth 0 kdf))
428 (def-fun-txt (format "%s" def-fun))
429 (rem-fun (command-remapping def-fun))
430 ;; Handle prefix definitions specially
431 ;; so that a mode that rebinds some subcommands
432 ;; won't make it appear that the whole prefix is gone.
433 (key-fun (if (eq def-fun 'ESC-prefix)
434 (lookup-key global-map [27])
435 (if (eq def-fun 'Control-X-prefix)
436 (lookup-key global-map [24])
437 (key-binding key))))
438 (where (where-is-internal (if rem-fun rem-fun def-fun)))
439 cwhere)
441 (if where
442 (progn
443 (setq cwhere (car where)
444 where (key-description cwhere))
445 (when (and (< 10 (length where))
446 (string= (substring where 0 (length "<menu-bar>"))
447 "<menu-bar>"))
448 (setq where
449 (if (and (vectorp cwhere)
450 (setq cwhere (elt cwhere 1))
451 (setq cwhere
452 (cadr
453 (assoc cwhere
454 (lookup-key global-map
455 [menu-bar]))))
456 (stringp cwhere))
457 (format "the `%s' menu" cwhere)
458 "the menus"))))
459 (setq where ""))
460 (setq remark nil)
461 (unless
462 (cond ((eq key-fun def-fun)
463 ;; No rebinding, return t
465 ((and key-fun
466 (eq key-fun (command-remapping def-fun)))
467 ;; Just a remapping, return t
469 ;; cua-mode specials:
470 ((and cua-mode
471 (or (and
472 (equal key [?\C-v])
473 (eq key-fun 'cua-paste))
474 (and
475 (equal key [?\C-z])
476 (eq key-fun 'undo))))
477 (setq remark (list "cua-mode, more info" 'cua-mode))
478 nil)
479 ((and cua-mode
480 (or (and (eq def-fun 'ESC-prefix)
481 (equal key-fun
482 `(keymap
483 (118 . cua-repeat-replace-region)))
484 (setq def-fun-txt "\"ESC prefix\""))
485 (and (eq def-fun 'mode-specific-command-prefix)
486 (equal key-fun
487 '(keymap
488 (timeout . copy-region-as-kill)))
489 (setq def-fun-txt "\"C-c prefix\""))
490 (and (eq def-fun 'Control-X-prefix)
491 (equal key-fun
492 '(keymap (timeout . kill-region)))
493 (setq def-fun-txt "\"C-x prefix\""))))
494 (setq remark (list "cua-mode replacement" 'cua-mode))
495 (setq where "Same key")
496 nil)
497 ;; viper-mode specials:
498 ((and (boundp 'viper-mode-string)
499 (boundp 'viper-current-state)
500 (eq viper-current-state 'vi-state)
501 (or (and (eq def-fun 'isearch-forward)
502 (eq key-fun 'viper-isearch-forward))
503 (and (eq def-fun 'isearch-backward)
504 (eq key-fun 'viper-isearch-backward))))
505 ;; These bindings works as the default bindings,
506 ;; return t
508 ((when normal-erase-is-backspace
509 (or (and (equal key [C-delete])
510 (equal key-fun 'kill-word))
511 (and (equal key [C-backspace])
512 (equal key-fun 'backward-kill-word))))
513 ;; This is the strange handling of C-delete and
514 ;; C-backspace, return t
517 ;; This key has indeed been rebound. Put information
518 ;; in `remark' and return nil
519 (setq remark
520 (list "more info" 'current-binding
521 key-fun def-fun key where))
522 nil))
523 (add-to-list 'changed-keys
524 (list key def-fun def-fun-txt where remark nil))))))
525 changed-keys))
527 (defun tutorial--key-description (key)
528 (let ((desc (key-description key)))
529 (cond ((string= "ESC" desc) "<ESC>")
530 ((string= "RET" desc) "<Return>")
531 ((string= "DEL" desc) "<Delback>")
532 (t desc))))
534 (defun tutorial--display-changes ()
535 "Display changes to some default key bindings.
536 If some of the default key bindings that the tutorial depends on
537 have been changed then display the changes in the tutorial buffer
538 with some explanatory links."
539 (let* ((changed-keys (tutorial--find-changed-keys
540 tutorial--default-keys))
541 ;; Alist of element (DESC . CK) where DESC is the
542 ;; key-description of a changed key and CK is the
543 ;; corresponding element in `changed-keys'.
544 (changed-keys-alist
545 (mapcar (lambda (ck) (cons (tutorial--key-description (car ck)) ck))
546 changed-keys))
547 changed-key
548 (start (point))
549 (case-fold-search nil)
550 (keybindings-regexp
551 ;; Accept either [:space:] or [:punct:] before the key
552 ;; binding because the Hebrew tutorial uses directional
553 ;; controls and Hebrew character maqaf, the Hebrew hyphen,
554 ;; immediately before the binding string.
555 (concat "\\(?:[[:space:]]\\|[[:punct:]]\\)\\("
556 (mapconcat (lambda (kdf) (regexp-quote
557 (tutorial--key-description
558 (nth 1 kdf))))
559 tutorial--default-keys
560 "\\|")
561 "\\)[[:punct:][:space:]]")))
562 ;; Need the custom button face for viper buttons:
563 (if (boundp 'viper-mode-string) (require 'cus-edit))
565 (if (or changed-keys (boundp 'viper-mode-string))
566 (let ((head (get-lang-string tutorial--lang 'tut-chgdhead))
567 (head2 (get-lang-string tutorial--lang 'tut-chgdhead2)))
568 (when (and head head2)
569 (goto-char tutorial--point-before-chkeys)
570 (insert head " [")
571 (insert-button head2 'tutorial-buffer (current-buffer)
572 'action 'tutorial--detailed-help
573 'follow-link t 'face 'link)
574 (insert "]\n\n")
575 (add-text-properties tutorial--point-before-chkeys (point)
576 '(tutorial-remark remark
577 face tutorial-warning-face
578 read-only t)))))
580 ;; Scan the tutorial for all key sequences.
581 (goto-char (point-min))
582 (while (re-search-forward keybindings-regexp (point-max) t)
583 ;; Then highlight each rebound key sequence.
584 ;; This avoids issuing a warning for, e.g., C-x C-b if C-b is rebound.
585 (setq changed-key (assoc (match-string 1) changed-keys-alist))
586 (and changed-key
587 (not (get-text-property (match-beginning 1) 'tutorial-remark))
588 (let* ((desc (car changed-key))
589 (ck (cdr changed-key))
590 (def-fun (nth 1 ck))
591 (where (nth 3 ck))
592 s1 s2 help-string)
593 (unless (string= where "Same key")
594 (when (string= where "")
595 (setq where (format "M-x %s" def-fun)))
596 (setq tutorial--point-after-chkeys (point-marker)
597 s1 (get-lang-string tutorial--lang 'tut-chgdkey)
598 s2 (get-lang-string tutorial--lang 'tut-chgdkey2)
599 help-string (and s1 s2 (format s1 desc where)))
600 (add-text-properties (match-beginning 1) (match-end 1)
601 '(face tutorial-warning-face
602 tutorial-remark key-sequence))
603 (if help-string
604 (if (nth 5 ck)
605 ;; Put help string in the tooltip.
606 (put-text-property (match-beginning 1) (match-end 1)
607 'help-echo help-string)
608 ;; Put help string in the buffer.
609 (save-excursion
610 (setcar (nthcdr 5 ck) t)
611 (forward-line)
612 ;; Two or more changed keys were on the same line.
613 (while (eq (get-text-property (point) 'tutorial-remark)
614 'remark)
615 (forward-line))
616 (setq start (point))
617 (insert "** " help-string " [")
618 (insert-button s2 'tutorial-buffer (current-buffer)
619 'action 'tutorial--detailed-help
620 'explain-key-desc desc 'follow-link t
621 'face 'link)
622 (insert "] **\n")
623 (add-text-properties start (point)
624 '(tutorial-remark remark
625 rear-nonsticky t
626 face tutorial-warning-face
627 read-only t)))))))))))
629 (defun tutorial--saved-dir ()
630 "Directory to which tutorials are saved."
631 (locate-user-emacs-file "tutorial/"))
633 (defun tutorial--saved-file ()
634 "File name in which to save tutorials."
635 (let ((file-name tutorial--lang)
636 (ext (file-name-extension tutorial--lang)))
637 (when (or (not ext)
638 (string= ext ""))
639 (setq file-name (concat file-name ".tut")))
640 (expand-file-name file-name (tutorial--saved-dir))))
642 (defun tutorial--remove-remarks ()
643 "Remove the remark lines that was added to the tutorial buffer."
644 (save-excursion
645 (goto-char (point-min))
646 (let (prop-start
647 prop-end
648 prop-val)
649 ;; Catch the case when we already are on a remark line
650 (while (if (get-text-property (point) 'tutorial-remark)
651 (setq prop-start (point))
652 (setq prop-start (next-single-property-change (point) 'tutorial-remark)))
653 (setq prop-end (next-single-property-change prop-start 'tutorial-remark))
654 (setq prop-val (get-text-property prop-start 'tutorial-remark))
655 (unless prop-end
656 (setq prop-end (point-max)))
657 (goto-char prop-end)
658 (unless (eq prop-val 'key-sequence)
659 (delete-region prop-start prop-end))))))
661 (defun tutorial--save-tutorial ()
662 "Save the tutorial buffer.
663 This saves the part of the tutorial before and after the area
664 showing changed keys. It also saves the point position and the
665 position where the display of changed bindings was inserted."
666 ;; This runs in a hook so protect it:
667 (condition-case err
668 (if (y-or-n-p "Save your position in the tutorial? ")
669 (tutorial--save-tutorial-to (tutorial--saved-file))
670 (message "Tutorial position not saved"))
671 (error (message "Error saving tutorial state: %s"
672 (error-message-string err)))))
674 (defun tutorial--save-tutorial-to (saved-file)
675 "Save the tutorial buffer to SAVED-FILE.
676 See `tutorial--save-tutorial' for more information."
677 ;; Anything to save?
678 (when (or (buffer-modified-p)
679 (< 1 (point)))
680 (let ((tutorial-dir (tutorial--saved-dir))
681 save-err)
682 ;; The tutorial is saved in a subdirectory in the user home
683 ;; directory. Create this subdirectory first.
684 (unless (file-directory-p tutorial-dir)
685 (condition-case err
686 (make-directory tutorial-dir nil)
687 (error (setq save-err t)
688 (warn "Could not create directory %s: %s" tutorial-dir
689 (error-message-string err)))))
690 ;; Make sure we have that directory.
691 (if (file-directory-p tutorial-dir)
692 (let ((tut-point (if (= 0 tutorial--point-after-chkeys)
693 ;; No info about changed keys is
694 ;; displayed.
695 (point)
696 (if (< (point) tutorial--point-after-chkeys)
697 (- (point))
698 (- (point) tutorial--point-after-chkeys))))
699 (old-point (point))
700 ;; Use a special undo list so that we easily can undo
701 ;; the changes we make to the tutorial buffer. This is
702 ;; currently not needed since we now delete the buffer
703 ;; after saving, but kept for possible future use of
704 ;; this function.
705 buffer-undo-list
706 (inhibit-read-only t))
707 ;; Delete the area displaying info about changed keys.
708 ;; (when (< 0 tutorial--point-after-chkeys)
709 ;; (delete-region tutorial--point-before-chkeys
710 ;; tutorial--point-after-chkeys))
711 ;; Delete the remarks:
712 (tutorial--remove-remarks)
713 ;; Put the value of point first in the buffer so it will
714 ;; be saved with the tutorial.
715 (goto-char (point-min))
716 (insert (number-to-string tut-point)
717 "\n"
718 (number-to-string (marker-position
719 tutorial--point-before-chkeys))
720 "\n")
721 (condition-case err
722 (write-region nil nil saved-file)
723 (error (setq save-err t)
724 (warn "Could not save tutorial to %s: %s"
725 saved-file
726 (error-message-string err))))
727 ;; An error is raised here?? Is this a bug?
728 (ignore-errors (undo-only))
729 ;; Restore point
730 (goto-char old-point)
731 (if save-err
732 (message "Could not save tutorial state.")
733 (message "Saved tutorial state.")))
734 (message "Can't save tutorial: %s is not a directory"
735 tutorial-dir)))))
738 ;;;###autoload
739 (defun help-with-tutorial (&optional arg dont-ask-for-revert)
740 "Select the Emacs learn-by-doing tutorial.
741 If there is a tutorial version written in the language
742 of the selected language environment, that version is used.
743 If there's no tutorial in that language, `TUTORIAL' is selected.
744 With ARG, you are asked to choose which language.
745 If DONT-ASK-FOR-REVERT is non-nil the buffer is reverted without
746 any question when restarting the tutorial.
748 If any of the standard Emacs key bindings that are used in the
749 tutorial have been changed then an explanatory note about this is
750 shown in the beginning of the tutorial buffer.
752 When the tutorial buffer is killed the content and the point
753 position in the buffer is saved so that the tutorial may be
754 resumed later."
755 (interactive "P")
756 (if (boundp 'viper-current-state)
757 (let ((prompt1
758 "You can not run the Emacs tutorial directly because you have \
759 enabled Viper.")
760 (prompt2 "\nThere is however a Viper tutorial you can run instead.
761 Run the Viper tutorial? "))
762 (if (fboundp 'viper-tutorial)
763 (if (y-or-n-p (concat prompt1 prompt2))
764 (progn (message "")
765 (funcall 'viper-tutorial 0))
766 (message "Tutorial aborted by user"))
767 (message prompt1)))
768 (let* ((lang (cond
769 (arg
770 (minibuffer-with-setup-hook #'minibuffer-completion-help
771 (read-language-name 'tutorial "Language: " "English")))
772 ((get-language-info current-language-environment 'tutorial)
773 current-language-environment)
774 (t "English")))
775 (filename (get-language-info lang 'tutorial))
776 (tut-buf-name filename)
777 (old-tut-buf (get-buffer tut-buf-name))
778 (old-tut-win (when old-tut-buf (get-buffer-window old-tut-buf t)))
779 (old-tut-is-ok (when old-tut-buf
780 (not (buffer-modified-p old-tut-buf))))
781 old-tut-file
782 (old-tut-point 1))
783 (setq tutorial--point-after-chkeys (point-min))
784 ;; Try to display the tutorial buffer before asking to revert it.
785 ;; If the tutorial buffer is shown in some window make sure it is
786 ;; selected and displayed:
787 (if old-tut-win
788 (raise-frame
789 (window-frame
790 (select-window (get-buffer-window old-tut-buf t))))
791 ;; Else, is there an old tutorial buffer? Then display it:
792 (when old-tut-buf
793 (switch-to-buffer old-tut-buf)))
794 ;; Use whole frame for tutorial
795 (delete-other-windows)
796 ;; If the tutorial buffer has been changed then ask if it should
797 ;; be reverted:
798 (when (and old-tut-buf
799 (not old-tut-is-ok))
800 (setq old-tut-is-ok
801 (if dont-ask-for-revert
803 (not (y-or-n-p
804 "You have changed the Tutorial buffer. Revert it? ")))))
805 ;; (Re)build the tutorial buffer if it is not ok
806 (unless old-tut-is-ok
807 (switch-to-buffer (get-buffer-create tut-buf-name))
808 ;; (unless old-tut-buf (text-mode))
809 (unless lang (error "Variable lang is nil"))
810 (setq tutorial--lang lang)
811 (setq old-tut-file (file-exists-p (tutorial--saved-file)))
812 (let ((inhibit-read-only t))
813 (erase-buffer))
814 (message "Preparing tutorial ...") (sit-for 0)
816 ;; Do not associate the tutorial buffer with a file. Instead use
817 ;; a hook to save it when the buffer is killed.
818 (setq buffer-auto-save-file-name nil)
819 (add-hook 'kill-buffer-hook 'tutorial--save-tutorial nil t)
821 ;; Insert the tutorial. First offer to resume last tutorial
822 ;; editing session.
823 (when dont-ask-for-revert
824 (setq old-tut-file nil))
825 (when old-tut-file
826 (setq old-tut-file
827 (y-or-n-p "Resume your last saved tutorial? ")))
828 (if old-tut-file
829 (progn
830 (insert-file-contents (tutorial--saved-file))
831 (let ((enable-local-variables :safe)
832 (enable-local-eval nil)
833 (enable-dir-local-variables nil)) ; bug#11127
834 (hack-local-variables))
835 (goto-char (point-min))
836 (setq old-tut-point
837 (string-to-number
838 (buffer-substring-no-properties
839 (line-beginning-position) (line-end-position))))
840 (forward-line)
841 (setq tutorial--point-before-chkeys
842 (string-to-number
843 (buffer-substring-no-properties
844 (line-beginning-position) (line-end-position))))
845 (forward-line)
846 (delete-region (point-min) (point))
847 (goto-char tutorial--point-before-chkeys)
848 (setq tutorial--point-before-chkeys (point-marker)))
849 (insert-file-contents (expand-file-name filename tutorial-directory))
850 (let ((enable-local-variables :safe)
851 (enable-local-eval nil)
852 (enable-dir-local-variables nil)) ; bug#11127
853 (hack-local-variables))
854 (forward-line)
855 (setq tutorial--point-before-chkeys (point-marker)))
857 (tutorial--display-changes)
859 ;; Clear message:
860 (unless dont-ask-for-revert
861 (message "") (sit-for 0))
864 (if old-tut-file
865 ;; Just move to old point in saved tutorial.
866 (let ((old-point
867 (if (> 0 old-tut-point)
868 (- old-tut-point)
869 (+ old-tut-point tutorial--point-after-chkeys))))
870 (when (< old-point 1)
871 (setq old-point 1))
872 (goto-char old-point))
873 ;; Delete the arch-tag line, so as not to confuse readers.
874 (goto-char (point-max))
875 (if (search-backward ";;; arch-tag: " nil t)
876 (delete-region (point) (point-max)))
877 (goto-char (point-min))
878 (search-forward "\n<<")
879 (beginning-of-line)
880 ;; Convert the <<...>> line to the proper [...] line,
881 ;; or just delete the <<...>> line if a [...] line follows.
882 (cond ((save-excursion
883 (forward-line 1)
884 (looking-at-p "\\["))
885 (delete-region (point) (progn (forward-line 1) (point))))
886 ((looking-at "<<Blank lines inserted.*>>")
887 (replace-match "[Middle of page left blank for didactic purposes. Text continues below]"))
889 (looking-at "<<")
890 (replace-match "[")
891 (search-forward ">>")
892 (replace-match "]")))
893 (beginning-of-line)
894 ;; FIXME: if the window is not tall, and especially if the
895 ;; big red "NOTICE: The main purpose..." text has been
896 ;; inserted at the start of the buffer, the "type C-v to
897 ;; move to the next screen" might not be visible on the
898 ;; first screen (n < 0). How will the novice know what to do?
899 (let ((n (- (window-height)
900 (count-lines (point-min) (point))
901 6)))
902 (if (< n 8)
903 (progn
904 ;; For a short gap, we don't need the [...] line,
905 ;; so delete it.
906 (delete-region (point) (progn (end-of-line) (point)))
907 (if (> n 0) (newline n)))
908 ;; Some people get confused by the large gap.
909 (newline (/ n 2))
911 ;; Skip the [...] line (don't delete it).
912 (forward-line 1)
913 (newline (- n (/ n 2)))))
914 (goto-char (point-min)))
915 (setq buffer-undo-list nil)
916 (set-buffer-modified-p nil)))))
919 ;; Below is some attempt to handle language specific strings. These
920 ;; are currently only used in the tutorial.
922 (defconst lang-strings
923 '(("English" .
924 ((tut-chgdkey . "%s has been rebound, but you can use %s instead")
925 (tut-chgdkey2 . "More")
926 (tut-chgdhead . "
927 NOTICE: The main purpose of the Emacs tutorial is to teach you
928 the most important standard Emacs commands (key bindings).
929 However, your Emacs has been customized by changing some of
930 these basic editing commands, so it doesn't correspond to the
931 tutorial. We have inserted colored notices where the altered
932 commands have been introduced.")
933 (tut-chgdhead2 . "More"))))
934 "Language specific strings for Emacs.
935 This is an association list with the keys equal to the strings
936 that can be returned by `read-language-name'. The elements in
937 the list are themselves association lists with keys that are
938 string ids and values that are the language specific strings.
940 See `get-lang-string' for more information.")
942 (defun get-lang-string (lang stringid &optional no-eng-fallback)
943 "Get a language specific string for Emacs.
944 In certain places Emacs can replace a string shown to the user with
945 a language specific string. This function retrieves such strings.
947 LANG is the language specification. It should be one of those
948 strings that can be returned by `read-language-name'. STRINGID
949 is a symbol that specifies the string to retrieve.
951 If no string is found for STRINGID in the chosen language then
952 the English string is returned unless NO-ENG-FALLBACK is non-nil.
954 See `lang-strings' for more information.
956 Currently this feature is only used in `help-with-tutorial'."
957 (let ((my-lang-strings (assoc lang lang-strings))
958 (found-string))
959 (when my-lang-strings
960 (let ((entry (assoc stringid (cdr my-lang-strings))))
961 (when entry
962 (setq found-string (cdr entry)))))
963 ;; Fallback to English strings
964 (unless (or found-string
965 no-eng-fallback)
966 (setq found-string (get-lang-string "English" stringid t)))
967 found-string))
969 ;;(get-lang-string "English" 'tut-chgdkey)
971 (provide 'tutorial)
973 ;;; tutorial.el ends here