help.el 45.5 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1 2
;;; help.el --- help commands for Emacs

3
;; Copyright (C) 1985-1986, 1993-1994, 1998-2012 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
4

Eric S. Raymond's avatar
Eric S. Raymond committed
5
;; Maintainer: FSF
Eric S. Raymond's avatar
Eric S. Raymond committed
6
;; Keywords: help, internal
7
;; Package: emacs
Eric S. Raymond's avatar
Eric S. Raymond committed
8

Richard M. Stallman's avatar
Richard M. Stallman committed
9 10
;; This file is part of GNU Emacs.

11
;; GNU Emacs is free software: you can redistribute it and/or modify
Richard M. Stallman's avatar
Richard M. Stallman committed
12
;; it under the terms of the GNU General Public License as published by
13 14
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
15 16 17 18 19 20 21

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; 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/>.
Richard M. Stallman's avatar
Richard M. Stallman committed
23

24 25
;;; Commentary:

26
;; This code implements GNU Emacs's on-line help system, the one invoked by
27
;; `M-x help-for-help'.
28

Eric S. Raymond's avatar
Eric S. Raymond committed
29 30
;;; Code:

31 32
;; Get the macro make-help-screen when this is compiled,
;; or run interpreted, but not when the compiled code is loaded.
33
(eval-when-compile (require 'help-macro))
34 35 36 37

;; This makes `with-output-to-temp-buffer' buffers use `help-mode'.
(add-hook 'temp-buffer-setup-hook 'help-mode-setup)
(add-hook 'temp-buffer-show-hook 'help-mode-finish)
38

39 40 41
;; `help-window-point-marker' is a marker you can move to a valid
;; position of the buffer shown in the help window in order to override
;; the standard positioning mechanism (`point-min') chosen by
42 43 44 45
;; `with-output-to-temp-buffer' and `with-temp-buffer-window'.
;; `with-help-window' has this point nowhere before exiting.  Currently
;; used by `view-lossage' to assert that the last keystrokes are always
;; visible.
46
(defvar help-window-point-marker (make-marker)
47
  "Marker to override default `window-point' in help windows.")
48

49 50 51 52 53 54 55 56
(defvar help-map
  (let ((map (make-sparse-keymap)))
    (define-key map (char-to-string help-char) 'help-for-help)
    (define-key map [help] 'help-for-help)
    (define-key map [f1] 'help-for-help)
    (define-key map "." 'display-local-help)
    (define-key map "?" 'help-for-help)

57
    (define-key map "\C-a" 'about-emacs)
58
    (define-key map "\C-c" 'describe-copying)
59 60
    (define-key map "\C-d" 'view-emacs-debugging)
    (define-key map "\C-e" 'view-external-packages)
61 62 63
    (define-key map "\C-f" 'view-emacs-FAQ)
    (define-key map "\C-m" 'view-order-manuals)
    (define-key map "\C-n" 'view-emacs-news)
64 65 66
    (define-key map "\C-o" 'describe-distribution)
    (define-key map "\C-p" 'view-emacs-problems)
    (define-key map "\C-t" 'view-emacs-todo)
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    (define-key map "\C-w" 'describe-no-warranty)

    ;; This does not fit the pattern, but it is natural given the C-\ command.
    (define-key map "\C-\\" 'describe-input-method)

    (define-key map "C" 'describe-coding-system)
    (define-key map "F" 'Info-goto-emacs-command-node)
    (define-key map "I" 'describe-input-method)
    (define-key map "K" 'Info-goto-emacs-key-command-node)
    (define-key map "L" 'describe-language-environment)
    (define-key map "S" 'info-lookup-symbol)

    (define-key map "a" 'apropos-command)
    (define-key map "b" 'describe-bindings)
    (define-key map "c" 'describe-key-briefly)
    (define-key map "d" 'apropos-documentation)
    (define-key map "e" 'view-echo-area-messages)
    (define-key map "f" 'describe-function)
85
    (define-key map "g" 'describe-gnu-project)
86 87 88 89 90 91 92 93 94 95
    (define-key map "h" 'view-hello-file)

    (define-key map "i" 'info)
    (define-key map "4i" 'info-other-window)

    (define-key map "k" 'describe-key)
    (define-key map "l" 'view-lossage)
    (define-key map "m" 'describe-mode)
    (define-key map "n" 'view-emacs-news)
    (define-key map "p" 'finder-by-keyword)
96
    (define-key map "P" 'describe-package)
97 98 99 100 101 102 103
    (define-key map "r" 'info-emacs-manual)
    (define-key map "s" 'describe-syntax)
    (define-key map "t" 'help-with-tutorial)
    (define-key map "w" 'where-is)
    (define-key map "v" 'describe-variable)
    (define-key map "q" 'help-quit)
    map)
Richard M. Stallman's avatar
Richard M. Stallman committed
104 105
  "Keymap for characters following the Help key.")

Eric S. Raymond's avatar
Eric S. Raymond committed
106
(define-key global-map (char-to-string help-char) 'help-command)
107 108
(define-key global-map [help] 'help-command)
(define-key global-map [f1] 'help-command)
Richard M. Stallman's avatar
Richard M. Stallman committed
109 110
(fset 'help-command help-map)

111 112 113
;; insert-button makes the action nil if it is not store somewhere
(defvar help-button-cache nil)

114

Richard M. Stallman's avatar
Richard M. Stallman committed
115
(defun help-quit ()
Richard M. Stallman's avatar
Richard M. Stallman committed
116
  "Just exit from the Help command's command loop."
Richard M. Stallman's avatar
Richard M. Stallman committed
117 118 119
  (interactive)
  nil)

120 121 122
(defvar help-return-method nil
  "What to do to \"exit\" the help buffer.
This is a list
123
 (WINDOW . t)              delete the selected window (and possibly its frame,
124
                           see `quit-window'), go to WINDOW.
125 126 127
 (WINDOW . quit-window)    do quit-window, then select WINDOW.
 (WINDOW BUF START POINT)  display BUF at START, POINT, then select WINDOW.")

128 129
(define-obsolete-function-alias 'print-help-return-message 'help-print-return-message "23.2")
(defun help-print-return-message (&optional function)
Richard M. Stallman's avatar
Richard M. Stallman committed
130
  "Display or return message saying how to restore windows after help command.
131 132
This function assumes that `standard-output' is the help buffer.
It computes a message, and applies the optional argument FUNCTION to it.
133 134 135
If FUNCTION is nil, it applies `message', thus displaying the message.
In addition, this function sets up `help-return-method', which see, that
specifies what to do when the user exits the help buffer."
Richard M. Stallman's avatar
Richard M. Stallman committed
136
  (and (not (get-buffer-window standard-output))
137
       (let ((first-message
138 139 140
	      (cond ((or
		      pop-up-frames
		      (special-display-p (buffer-name standard-output)))
141
		     (setq help-return-method (cons (selected-window) t))
142 143 144 145 146 147 148 149
		     ;; If the help output buffer is a special display buffer,
		     ;; don't say anything about how to get rid of it.
		     ;; First of all, the user will do that with the window
		     ;; manager, not with Emacs.
		     ;; Secondly, the buffer has not been displayed yet,
		     ;; so we don't know whether its frame will be selected.
		     nil)
		    ((not (one-window-p t))
150 151
		     (setq help-return-method
			   (cons (selected-window) 'quit-window))
152
		     "Type \\[display-buffer] RET to restore the other window.")
153
		    (pop-up-windows
154
		     (setq help-return-method (cons (selected-window) t))
155 156
		     "Type \\[delete-other-windows] to remove help window.")
		    (t
157 158 159
		     (setq help-return-method
			   (list (selected-window) (window-buffer)
				 (window-start) (window-point)))
160 161 162 163
		     "Type \\[switch-to-buffer] RET to remove help window."))))
	 (funcall (or function 'message)
		  (concat
		   (if first-message
Dave Love's avatar
Dave Love committed
164 165
		       (substitute-command-keys first-message))
		   (if first-message "  ")
166 167
		   ;; If the help buffer will go in a separate frame,
		   ;; it's no use mentioning a command to scroll, so don't.
168 169
		   (if (or pop-up-windows
			   (special-display-p (buffer-name standard-output)))
170
		       nil
171
		     (if (same-window-p (buffer-name standard-output))
172 173 174 175
			 ;; Say how to scroll this window.
			 (substitute-command-keys
			  "\\[scroll-up] to scroll the help.")
		       ;; Say how to scroll some other window.
176
		       (substitute-command-keys
177
			"\\[scroll-other-window] to scroll the help."))))))))
Richard M. Stallman's avatar
Richard M. Stallman committed
178 179 180 181

;; So keyboard macro definitions are documented correctly
(fset 'defining-kbd-macro (symbol-function 'start-kbd-macro))

182 183 184 185 186
(defalias 'help 'help-for-help-internal)
;; find-function can find this.
(defalias 'help-for-help 'help-for-help-internal)
;; It can't find this, but nobody will look.
(make-help-screen help-for-help-internal
187
  (purecopy "Type a help option: [abcCdefFgiIkKlLmnprstvw.] C-[cdefmnoptw] or ?")
188 189 190
  ;; Don't purecopy this one, because it's not evaluated (it's
  ;; directly used as a docstring in a function definition, so it'll
  ;; be moved to the DOC file anyway: no need for purecopying it).
191 192 193
  "You have typed %THIS-KEY%, the help character.  Type a Help option:
\(Use SPC or DEL to scroll through this text.  Type \\<help-map>\\[help-quit] to exit the Help command.)

194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
a PATTERN   Show commands whose name matches the PATTERN (a list of words
              or a regexp).  See also the `apropos' command.
b           Display all key bindings.
c KEYS      Display the command name run by the given key sequence.
C CODING    Describe the given coding system, or RET for current ones.
d PATTERN   Show a list of functions, variables, and other items whose
              documentation matches the PATTERN (a list of words or a regexp).
e           Go to the *Messages* buffer which logs echo-area messages.
f FUNCTION  Display documentation for the given function.
F COMMAND   Show the on-line manual's section that describes the command.
g           Display information about the GNU project.
h           Display the HELLO file which illustrates various scripts.
i           Start the Info documentation reader: read on-line manuals.
I METHOD    Describe a specific input method, or RET for current.
k KEYS      Display the full documentation for the key sequence.
K KEYS      Show the on-line manual's section for the command bound to KEYS.
210
l           Show last 300 input keystrokes (lossage).
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
L LANG-ENV  Describes a specific language environment, or RET for current.
m           Display documentation of current minor modes and current major mode,
              including their special commands.
n           Display news of recent Emacs changes.
p TOPIC     Find packages matching a given topic keyword.
r           Display the Emacs manual in Info mode.
s           Display contents of current syntax table, plus explanations.
S SYMBOL    Show the section for the given symbol in the on-line manual
              for the programming language used in this buffer.
t           Start the Emacs learn-by-doing tutorial.
v VARIABLE  Display the given variable's documentation and value.
w COMMAND   Display which keystrokes invoke the given command (where-is).
.           Display any available local help at point in the echo area.

C-a         Information about Emacs.
C-c         Emacs copying permission (GNU General Public License).
C-d         Instructions for debugging GNU Emacs.
C-e         External packages and information about Emacs.
C-f         Emacs FAQ.
C-m         How to order printed Emacs manuals.
C-n         News of recent Emacs changes.
C-o         Emacs ordering and distribution information.
C-p         Info about known Emacs problems.
C-t         Emacs TODO list.
235
C-w         Information on absence of warranty for GNU Emacs."
236 237 238 239 240 241 242
  help-map)



(defun function-called-at-point ()
  "Return a function around point or else called by the list containing point.
If that doesn't give a function, return nil."
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  (with-syntax-table emacs-lisp-mode-syntax-table
    (or (condition-case ()
            (save-excursion
              (or (not (zerop (skip-syntax-backward "_w")))
                  (eq (char-syntax (following-char)) ?w)
                  (eq (char-syntax (following-char)) ?_)
                  (forward-sexp -1))
              (skip-chars-forward "'")
              (let ((obj (read (current-buffer))))
                (and (symbolp obj) (fboundp obj) obj)))
          (error nil))
        (condition-case ()
            (save-excursion
              (save-restriction
                (narrow-to-region (max (point-min)
                                       (- (point) 1000)) (point-max))
                ;; Move up to surrounding paren, then after the open.
                (backward-up-list 1)
                (forward-char 1)
                ;; If there is space here, this is probably something
                ;; other than a real Lisp function call, so ignore it.
                (if (looking-at "[ \t]")
                    (error "Probably not a Lisp function call"))
                (let ((obj (read (current-buffer))))
                  (and (symbolp obj) (fboundp obj) obj))))
          (error nil))
        (let* ((str (find-tag-default))
               (sym (if str (intern-soft str))))
          (if (and sym (fboundp sym))
              sym
            (save-match-data
              (when (and str (string-match "\\`\\W*\\(.*?\\)\\W*\\'" str))
                (setq sym (intern-soft (match-string 1 str)))
                (and (fboundp sym) sym))))))))
277 278 279 280


;;; `User' help functions

281 282
(defun view-help-file (file &optional dir)
  (view-file (expand-file-name file (or dir data-directory)))
283
  (goto-address-mode 1)
284 285
  (goto-char (point-min)))

Richard M. Stallman's avatar
Richard M. Stallman committed
286 287 288
(defun describe-distribution ()
  "Display info on how to obtain the latest version of GNU Emacs."
  (interactive)
289
  (view-help-file "DISTRIB"))
Richard M. Stallman's avatar
Richard M. Stallman committed
290 291 292 293

(defun describe-copying ()
  "Display info on how you may redistribute copies of GNU Emacs."
  (interactive)
294
  (view-help-file "COPYING"))
Richard M. Stallman's avatar
Richard M. Stallman committed
295

296
(defun describe-gnu-project ()
297 298
  "Display info on the GNU project."
  (interactive)
299
  (view-help-file "THE-GNU-PROJECT"))
300

301 302
(define-obsolete-function-alias 'describe-project 'describe-gnu-project "22.2")

Richard M. Stallman's avatar
Richard M. Stallman committed
303 304 305 306 307
(defun describe-no-warranty ()
  "Display info on all the kinds of warranty Emacs does NOT have."
  (interactive)
  (describe-copying)
  (let (case-fold-search)
308 309
    (search-forward "Disclaimer of Warranty")
    (forward-line 0)
Richard M. Stallman's avatar
Richard M. Stallman committed
310 311
    (recenter 0)))

312
(defun describe-prefix-bindings ()
313 314 315
  "Describe the bindings of the prefix used to reach this command.
The prefix described consists of all but the last event
of the key sequence that ran this command."
316
  (interactive)
317
  (let ((key (this-command-keys)))
318 319 320 321 322 323 324 325 326
    (describe-bindings
     (if (stringp key)
	 (substring key 0 (1- (length key)))
       (let ((prefix (make-vector (1- (length key)) nil))
	     (i 0))
	 (while (< i (length prefix))
	   (aset prefix i (aref key i))
	   (setq i (1+ i)))
	 prefix)))))
327
;; Make C-h after a prefix, when not specifically bound,
328
;; run describe-prefix-bindings.
329 330
(setq prefix-help-command 'describe-prefix-bindings)

331
(defun view-emacs-news (&optional version)
332
  "Display info on recent changes to Emacs.
333
With argument, display info only for the selected version."
334
  (interactive "P")
335 336 337 338 339
  (unless version
    (setq version emacs-major-version))
  (when (consp version)
    (let* ((all-versions
	    (let (res)
340
	      (mapc
341 342 343 344 345 346 347 348 349 350 351 352 353
	       (lambda (file)
		 (with-temp-buffer
		   (insert-file-contents
		    (expand-file-name file data-directory))
		   (while (re-search-forward
			   (if (member file '("NEWS.18" "NEWS.1-17"))
			       "Changes in \\(?:Emacs\\|version\\)?[ \t]*\\([0-9]+\\(?:\\.[0-9]+\\)?\\)"
			     "^\* [^0-9\n]*\\([0-9]+\\.[0-9]+\\)") nil t)
		     (setq res (cons (match-string-no-properties 1) res)))))
	       (cons "NEWS"
		     (directory-files data-directory nil
				      "^NEWS\\.[0-9][-0-9]*$" nil)))
	      (sort (delete-dups res) (lambda (a b) (string< b a)))))
354
	   (current (car all-versions)))
355 356 357 358 359 360 361 362 363 364 365 366 367 368
      (setq version (completing-read
		     (format "Read NEWS for the version (default %s): " current)
		     all-versions nil nil nil nil current))
      (if (integerp (string-to-number version))
	  (setq version (string-to-number version))
	(unless (or (member version all-versions)
		    (<= (string-to-number version) (string-to-number current)))
	  (error "No news about version %s" version)))))
  (when (integerp version)
    (cond ((<= version 12)
	   (setq version (format "1.%d" version)))
	  ((<= version 18)
	   (setq version (format "%d" version)))
	  ((> version emacs-major-version)
369
	   (error "No news about Emacs %d (yet)" version))))
370 371 372 373 374 375
  (let* ((vn (if (stringp version)
		 (string-to-number version)
	       version))
	 (file (cond
		((>= vn emacs-major-version) "NEWS")
		((< vn 18) "NEWS.1-17")
376 377
		(t (format "NEWS.%d" vn))))
	 res)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    (view-file (expand-file-name file data-directory))
    (widen)
    (goto-char (point-min))
    (when (stringp version)
      (when (re-search-forward
	     (concat (if (< vn 19)
			 "Changes in Emacs[ \t]*"
		       "^\* [^0-9\n]*") version "$")
	     nil t)
	(beginning-of-line)
	(narrow-to-region
	 (point)
	 (save-excursion
	   (while (and (setq res
			     (re-search-forward
			      (if (< vn 19)
				  "Changes in \\(?:Emacs\\|version\\)?[ \t]*\\([0-9]+\\(?:\\.[0-9]+\\)?\\)"
				"^\* [^0-9\n]*\\([0-9]+\\.[0-9]+\\)") nil t))
		       (equal (match-string-no-properties 1) version)))
	   (or res (goto-char (point-max)))
	   (beginning-of-line)
	   (point)))))))

401
(defun view-emacs-todo (&optional _arg)
402 403
  "Display the Emacs TODO list."
  (interactive "P")
404
  (view-help-file "TODO"))
405

406 407 408
(define-obsolete-function-alias 'view-todo 'view-emacs-todo "22.2")


409 410 411 412 413 414 415
(defun view-echo-area-messages ()
  "View the log of recent echo-area messages: the `*Messages*' buffer.
The number of messages retained in that buffer
is specified by the variable `message-log-max'."
  (interactive)
  (switch-to-buffer (get-buffer-create "*Messages*")))

416 417 418
(defun view-order-manuals ()
  "Display the Emacs ORDERS file."
  (interactive)
419
  (view-help-file "ORDERS"))
420

421 422 423
(defun view-emacs-FAQ ()
  "Display the Emacs Frequently Asked Questions (FAQ) file."
  (interactive)
424
  ;; (find-file-read-only (expand-file-name "FAQ" data-directory))
425
  (info "(efaq)"))
426

427 428 429
(defun view-emacs-problems ()
  "Display info on known problems with Emacs and possible workarounds."
  (interactive)
430 431 432 433 434 435 436 437 438 439 440
  (view-help-file "PROBLEMS"))

(defun view-emacs-debugging ()
  "Display info on how to debug Emacs problems."
  (interactive)
  (view-help-file "DEBUG"))

(defun view-external-packages ()
  "Display external packages and information about Emacs."
  (interactive)
  (view-help-file "MORE.STUFF"))
441

Richard M. Stallman's avatar
Richard M. Stallman committed
442
(defun view-lossage ()
443
  "Display last 300 input keystrokes.
444 445

To record all your input on a file, use `open-dribble-file'."
Richard M. Stallman's avatar
Richard M. Stallman committed
446
  (interactive)
447 448
  (help-setup-xref (list #'view-lossage)
		   (called-interactively-p 'interactive))
449
  (with-help-window (help-buffer)
450 451 452 453
    (princ (mapconcat (lambda (key)
			(if (or (integerp key) (symbolp key) (listp key))
			    (single-key-description key)
			  (prin1-to-string key nil)))
454 455
		      (recent-keys)
		      " "))
456
    (with-current-buffer standard-output
Richard M. Stallman's avatar
Richard M. Stallman committed
457 458
      (goto-char (point-min))
      (while (progn (move-to-column 50) (not (eobp)))
459 460
        (when (search-forward " " nil t)
          (delete-char -1))
461 462 463
        (insert "\n"))
      ;; jidanni wants to see the last keystrokes immediately.
      (set-marker help-window-point-marker (point)))))
Richard M. Stallman's avatar
Richard M. Stallman committed
464

465 466

;; Key bindings
Richard M. Stallman's avatar
Richard M. Stallman committed
467

468
(defun describe-bindings (&optional prefix buffer)
469 470 471 472
  "Show a list of all defined keys, and their definitions.
We put that list in a buffer, and display the buffer.

The optional argument PREFIX, if non-nil, should be a key sequence;
473 474
then we display only bindings that start with that prefix.
The optional argument BUFFER specifies which buffer's bindings
Luc Teirlinck's avatar
Luc Teirlinck committed
475 476
to display (default, the current buffer).  BUFFER can be a buffer
or a buffer name."
477
  (interactive)
478
  (or buffer (setq buffer (current-buffer)))
479 480
  (help-setup-xref (list #'describe-bindings prefix buffer)
		   (called-interactively-p 'interactive))
481
  (with-current-buffer buffer
482
    (describe-bindings-internal nil prefix)))
483

484 485 486 487 488 489 490 491 492 493
;; This function used to be in keymap.c.
(defun describe-bindings-internal (&optional menus prefix)
  "Show a list of all defined keys, and their definitions.
We put that list in a buffer, and display the buffer.

The optional argument MENUS, if non-nil, says to mention menu bindings.
\(Ordinarily these are omitted from the output.)
The optional argument PREFIX, if non-nil, should be a key sequence;
then we display only bindings that start with that prefix."
  (let ((buf (current-buffer)))
494
    (with-help-window "*Help*"
495 496 497
      (with-current-buffer standard-output
	(describe-buffer-bindings buf prefix menus)))))

498
(defun where-is (definition &optional insert)
499
  "Print message listing key sequences that invoke the command DEFINITION.
500 501
Argument is a command definition, usually a symbol with a function definition.
If INSERT (the prefix arg) is non-nil, insert the message in the buffer."
502 503
  (interactive
   (let ((fn (function-called-at-point))
504
	 (enable-recursive-minibuffers t)
505
	 val)
506 507 508 509 510 511
     (setq val (completing-read
		(if fn
		    (format "Where is command (default %s): " fn)
		  "Where is command: ")
		obarray 'commandp t))
     (list (if (equal val "") fn (intern val)) current-prefix-arg)))
512
  (unless definition (error "No command"))
513
  (let ((func (indirect-function definition))
514
        (defs nil)
515
        (standard-output (if insert (current-buffer) standard-output)))
516
    ;; In DEFS, find all symbols that are aliases for DEFINITION.
517 518 519
    (mapatoms (lambda (symbol)
		(and (fboundp symbol)
		     (not (eq symbol definition))
520 521 522
		     (eq func (condition-case ()
				  (indirect-function symbol)
				(error symbol)))
523
		     (push symbol defs))))
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    ;; Look at all the symbols--first DEFINITION,
    ;; then its aliases.
    (dolist (symbol (cons definition defs))
      (let* ((remapped (command-remapping symbol))
	     (keys (where-is-internal
		    symbol overriding-local-map nil nil remapped))
	     (keys (mapconcat 'key-description keys ", "))
	     string)
	(setq string
	      (if insert
		  (if (> (length keys) 0)
		      (if remapped
			  (format "%s (%s) (remapped from %s)"
				  keys remapped symbol)
			(format "%s (%s)" keys symbol))
		    (format "M-x %s RET" symbol))
		(if (> (length keys) 0)
		    (if remapped
			(format "%s is remapped to %s which is on %s"
543
				symbol remapped keys)
544 545 546 547 548 549 550 551 552 553 554
		      (format "%s is on %s" symbol keys))
		  ;; If this is the command the user asked about,
		  ;; and it is not on any key, say so.
		  ;; For other symbols, its aliases, say nothing
		  ;; about them unless they are on keys.
		  (if (eq symbol definition)
		      (format "%s is not on any key" symbol)))))
	(when string
	  (unless (eq symbol definition)
	    (princ ";\n its alias "))
	  (princ string)))))
555 556
  nil)

557 558
(defun help-key-description (key untranslated)
  (let ((string (key-description key)))
559 560
    (if (or (not untranslated)
	    (and (eq (aref untranslated 0) ?\e) (not (eq (aref key 0) ?\e))))
561 562 563 564 565
	string
      (let ((otherstring (key-description untranslated)))
	(if (equal string otherstring)
	    string
	  (format "%s (translated from %s)" string otherstring))))))
566

567 568 569 570 571 572 573 574
(defun describe-key-briefly (&optional key insert untranslated)
  "Print the name of the function KEY invokes.  KEY is a string.
If INSERT (the prefix arg) is non-nil, insert the message in the buffer.
If non-nil, UNTRANSLATED is a vector of the untranslated events.
It can also be a number in which case the untranslated events from
the last key hit are used.

If KEY is a menu item or a tool-bar button that is disabled, this command
575
temporarily enables it to allow getting help on disabled items and buttons."
576 577 578 579 580 581 582 583 584 585 586 587
  (interactive
   (let ((enable-disabled-menus-and-buttons t)
	 (cursor-in-echo-area t)
	 saved-yank-menu)
     (unwind-protect
	 (let (key)
	   ;; If yank-menu is empty, populate it temporarily, so that
	   ;; "Select and Paste" menu can generate a complete event.
	   (when (null (cdr yank-menu))
	     (setq saved-yank-menu (copy-sequence yank-menu))
	     (menu-bar-update-yank-menu "(any string)" nil))
	   (setq key (read-key-sequence "Describe key (or click or menu item): "))
588 589
	   ;; Clear the echo area message (Bug#7014).
	   (message nil)
590
	   ;; If KEY is a down-event, read and discard the
591 592 593 594
	   ;; corresponding up-event.  Note that there are also
	   ;; down-events on scroll bars and mode lines: the actual
	   ;; event then is in the second element of the vector.
	   (and (vectorp key)
595 596 597
		(let ((last-idx (1- (length key))))
		  (and (eventp (aref key last-idx))
		       (memq 'down (event-modifiers (aref key last-idx)))))
598
		(read-event))
599 600
	   (list
	    key
601 602
	    (if current-prefix-arg (prefix-numeric-value current-prefix-arg))
	    1))
603 604 605 606
       ;; Put yank-menu back as it was, if we changed it.
       (when saved-yank-menu
	 (setq yank-menu (copy-sequence saved-yank-menu))
	 (fset 'yank-menu (cons 'keymap yank-menu))))))
607 608
  (if (numberp untranslated)
      (setq untranslated (this-single-command-raw-keys)))
609 610 611 612 613 614
  (let* ((event (if (and (symbolp (aref key 0))
			 (> (length key) 1)
			 (consp (aref key 1)))
		    (aref key 1)
		  (aref key 0)))
	 (modifiers (event-modifiers event))
615
	 (standard-output (if insert (current-buffer) standard-output))
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
	 (mouse-msg (if (or (memq 'click modifiers) (memq 'down modifiers)
			    (memq 'drag modifiers)) " at that spot" ""))
	 (defn (key-binding key t))
	 key-desc)
    ;; Handle the case where we faked an entry in "Select and Paste" menu.
    (if (and (eq defn nil)
	     (stringp (aref key (1- (length key))))
	     (eq (key-binding (substring key 0 -1)) 'yank-menu))
	(setq defn 'menu-bar-select-yank))
    ;; Don't bother user with strings from (e.g.) the select-paste menu.
    (if (stringp (aref key (1- (length key))))
	(aset key (1- (length key)) "(any string)"))
    (if (and (> (length untranslated) 0)
	     (stringp (aref untranslated (1- (length untranslated)))))
	(aset untranslated (1- (length untranslated)) "(any string)"))
    ;; Now describe the key, perhaps as changed.
    (setq key-desc (help-key-description key untranslated))
    (if (or (null defn) (integerp defn) (equal defn 'undefined))
	(princ (format "%s%s is undefined" key-desc mouse-msg))
      (princ (format "%s%s runs the command %S" key-desc mouse-msg defn)))))
636

637 638 639 640 641 642 643 644 645 646 647 648
(defun describe-key (&optional key untranslated up-event)
  "Display documentation of the function invoked by KEY.
KEY can be any kind of a key sequence; it can include keyboard events,
mouse events, and/or menu events.  When calling from a program,
pass KEY as a string or a vector.

If non-nil, UNTRANSLATED is a vector of the corresponding untranslated events.
It can also be a number, in which case the untranslated events from
the last key sequence entered are used.
UP-EVENT is the up-event that was discarded by reading KEY, or nil.

If KEY is a menu item or a tool-bar button that is disabled, this command
649
temporarily enables it to allow getting help on disabled items and buttons."
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
  (interactive
   (let ((enable-disabled-menus-and-buttons t)
	 (cursor-in-echo-area t)
	 saved-yank-menu)
     (unwind-protect
	 (let (key)
	   ;; If yank-menu is empty, populate it temporarily, so that
	   ;; "Select and Paste" menu can generate a complete event.
	   (when (null (cdr yank-menu))
	     (setq saved-yank-menu (copy-sequence yank-menu))
	     (menu-bar-update-yank-menu "(any string)" nil))
	   (setq key (read-key-sequence "Describe key (or click or menu item): "))
	   (list
	    key
	    (prefix-numeric-value current-prefix-arg)
Chong Yidong's avatar
Chong Yidong committed
665
	    ;; If KEY is a down-event, read and include the
666 667 668
	    ;; corresponding up-event.  Note that there are also
	    ;; down-events on scroll bars and mode lines: the actual
	    ;; event then is in the second element of the vector.
669
	    (and (vectorp key)
670 671 672
		 (let ((last-idx (1- (length key))))
		   (and (eventp (aref key last-idx))
			(memq 'down (event-modifiers (aref key last-idx)))))
673
		 (or (and (eventp (aref key 0))
674 675 676 677 678 679
			  (memq 'down (event-modifiers (aref key 0)))
			  ;; However, for the C-down-mouse-2 popup
			  ;; menu, there is no subsequent up-event.  In
			  ;; this case, the up-event is the next
			  ;; element in the supplied vector.
			  (= (length key) 1))
680 681 682 683
		     (and (> (length key) 1)
			  (eventp (aref key 1))
			  (memq 'down (event-modifiers (aref key 1)))))
		 (read-event))))
684 685 686 687
       ;; Put yank-menu back as it was, if we changed it.
       (when saved-yank-menu
	 (setq yank-menu (copy-sequence saved-yank-menu))
	 (fset 'yank-menu (cons 'keymap yank-menu))))))
688 689
  (if (numberp untranslated)
      (setq untranslated (this-single-command-raw-keys)))
690 691 692 693 694
  (let* ((event (aref key (if (and (symbolp (aref key 0))
				   (> (length key) 1)
				   (consp (aref key 1)))
			      1
			    0)))
695
	 (modifiers (event-modifiers event))
696 697
	 (mouse-msg (if (or (memq 'click modifiers) (memq 'down modifiers)
			    (memq 'drag modifiers)) " at that spot" ""))
698 699 700
	 (defn (key-binding key t))
	 defn-up defn-up-tricky ev-type
	 mouse-1-remapped mouse-1-tricky)
701

702
    ;; Handle the case where we faked an entry in "Select and Paste" menu.
703
    (when (and (eq defn nil)
704 705
	       (stringp (aref key (1- (length key))))
	       (eq (key-binding (substring key 0 -1)) 'yank-menu))
706 707 708 709
      (setq defn 'menu-bar-select-yank))
    (if (or (null defn) (integerp defn) (equal defn 'undefined))
	(message "%s%s is undefined"
		 (help-key-description key untranslated) mouse-msg)
710 711
      (help-setup-xref (list #'describe-function defn)
		       (called-interactively-p 'interactive))
712 713 714 715
      ;; Don't bother user with strings from (e.g.) the select-paste menu.
      (when (stringp (aref key (1- (length key))))
	(aset key (1- (length key)) "(any string)"))
      (when (and untranslated
716
		 (stringp (aref untranslated (1- (length untranslated)))))
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
	(aset untranslated (1- (length untranslated))
	      "(any string)"))
      ;; Need to do this before erasing *Help* buffer in case event
      ;; is a mouse click in an existing *Help* buffer.
      (when up-event
	(setq ev-type (event-basic-type up-event))
	(let ((sequence (vector up-event)))
	  (when (and (eq ev-type 'mouse-1)
		     mouse-1-click-follows-link
		     (not (eq mouse-1-click-follows-link 'double))
		     (setq mouse-1-remapped
			   (mouse-on-link-p (event-start up-event))))
	    (setq mouse-1-tricky (and (integerp mouse-1-click-follows-link)
				      (> mouse-1-click-follows-link 0)))
	    (cond ((stringp mouse-1-remapped)
		   (setq sequence mouse-1-remapped))
		  ((vectorp mouse-1-remapped)
		   (setcar up-event (elt mouse-1-remapped 0)))
		  (t (setcar up-event 'mouse-2))))
	  (setq defn-up (key-binding sequence nil nil (event-start up-event)))
	  (when mouse-1-tricky
	    (setq sequence (vector up-event))
	    (aset sequence 0 'mouse-1)
	    (setq defn-up-tricky (key-binding sequence nil nil (event-start up-event))))))
741
      (with-help-window (help-buffer)
742 743
	(princ (help-key-description key untranslated))
	(princ (format "\
744
%s runs the command %S, which is "
745 746
		       mouse-msg defn))
	(describe-function-1 defn)
747
	(when up-event
748 749 750 751 752 753 754
	  (unless (or (null defn-up)
		      (integerp defn-up)
		      (equal defn-up 'undefined))
	    (princ (format "

----------------- up-event %s----------------

755
%s%s%s runs the command %S, which is "
756
			   (if mouse-1-tricky "(short click) " "")
757 758
			   (key-description (vector up-event))
			   mouse-msg
759
			   (if mouse-1-remapped
760
                               " is remapped to <mouse-2>, which" "")
761 762 763 764 765 766 767 768 769 770
			   defn-up))
	    (describe-function-1 defn-up))
	  (unless (or (null defn-up-tricky)
		      (integerp defn-up-tricky)
		      (eq defn-up-tricky 'undefined))
	    (princ (format "

----------------- up-event (long click) ----------------

Pressing <%S>%s for longer than %d milli-seconds
771
runs the command %S, which is "
772 773 774
			   ev-type mouse-msg
			   mouse-1-click-follows-link
			   defn-up-tricky))
775
	    (describe-function-1 defn-up-tricky)))))))
776

777 778
(defun describe-mode (&optional buffer)
  "Display documentation of current major mode and minor modes.
779 780 781 782 783 784
A brief summary of the minor modes comes first, followed by the
major mode description.  This is followed by detailed
descriptions of the minor modes, each on a separate page.

For this to work correctly for a minor mode, the mode's indicator
variable \(listed in `minor-mode-alist') must also be a function
Chong Yidong's avatar
Chong Yidong committed
785 786 787 788
whose documentation describes the minor mode.

If called from Lisp with a non-nil BUFFER argument, display
documentation for the major and minor modes of that buffer."
789
  (interactive "@")
790 791
  (unless buffer (setq buffer (current-buffer)))
  (help-setup-xref (list #'describe-mode buffer)
792
		   (called-interactively-p 'interactive))
793 794
  ;; For the sake of help-do-xref and help-xref-go-back,
  ;; don't switch buffers before calling `help-buffer'.
795
  (with-help-window (help-buffer)
796
    (with-current-buffer buffer
797
      (let (minor-modes)
798 799 800 801 802 803
	;; Older packages do not register in minor-mode-list but only in
	;; minor-mode-alist.
	(dolist (x minor-mode-alist)
	  (setq x (car x))
	  (unless (memq x minor-mode-list)
	    (push x minor-mode-list)))
804 805 806 807
	;; Find enabled minor mode we will want to mention.
	(dolist (mode minor-mode-list)
	  ;; Document a minor mode if it is listed in minor-mode-alist,
	  ;; non-nil, and has a function definition.
808 809 810 811 812 813 814 815 816 817 818 819 820
	  (let ((fmode (or (get mode :minor-mode-function) mode)))
	    (and (boundp mode) (symbol-value mode)
		 (fboundp fmode)
		 (let ((pretty-minor-mode
			(if (string-match "\\(\\(-minor\\)?-mode\\)?\\'"
					  (symbol-name fmode))
			    (capitalize
			     (substring (symbol-name fmode)
					0 (match-beginning 0)))
			  fmode)))
		   (push (list fmode pretty-minor-mode
			       (format-mode-line (assq mode minor-mode-alist)))
			 minor-modes)))))
821 822
	(setq minor-modes
	      (sort minor-modes
823
		    (lambda (a b) (string-lessp (cadr a) (cadr b)))))
824
	(when minor-modes
825
	  (princ "Enabled minor modes:\n")
826 827 828
	  (make-local-variable 'help-button-cache)
	  (with-current-buffer standard-output
	    (dolist (mode minor-modes)
829 830
	      (let ((mode-function (nth 0 mode))
		    (pretty-minor-mode (nth 1 mode))
831 832 833 834 835 836 837 838 839
		    (indicator (nth 2 mode)))
		(add-text-properties 0 (length pretty-minor-mode)
				     '(face bold) pretty-minor-mode)
		(save-excursion
		  (goto-char (point-max))
		  (princ "\n\f\n")
		  (push (point-marker) help-button-cache)
		  ;; Document the minor modes fully.
		  (insert pretty-minor-mode)
840 841 842 843
		  (princ (format " minor mode (%s):\n"
				 (if (zerop (length indicator))
				     "no indicator"
				   (format "indicator%s"
Richard M. Stallman's avatar
Richard M. Stallman committed
844
					   indicator))))
845 846 847
		  (princ (documentation mode-function)))
		(insert-button pretty-minor-mode
			       'action (car help-button-cache)
848
			       'follow-link t
849
			       'help-echo "mouse-2, RET: show full information")
850 851 852 853 854 855
		(newline)))
	    (forward-line -1)
	    (fill-paragraph nil)
	    (forward-line 1))

	  (princ "\n(Information about these minor modes follows the major mode info.)\n\n"))
856
	;; Document the major mode.
857 858
	(let ((mode mode-name))
	  (with-current-buffer standard-output
859
            (let ((start (point)))
860
              (insert (format-mode-line mode nil nil buffer))
861
              (add-text-properties start (point) '(face bold)))))
862 863 864 865 866 867 868 869 870 871 872
	(princ " mode")
	(let* ((mode major-mode)
	       (file-name (find-lisp-object-file-name mode nil)))
	  (when file-name
	    (princ (concat " defined in `" (file-name-nondirectory file-name) "'"))
	    ;; Make a hyperlink to the library.
	    (with-current-buffer standard-output
	      (save-excursion
		(re-search-backward "`\\([^`']+\\)'" nil t)
		(help-xref-button 1 'help-function-def mode file-name)))))
	(princ ":\n")
873
	(princ (documentation major-mode)))))
874
  ;; For the sake of IELM and maybe others
875
  nil)
876

877

878
(defun describe-minor-mode (minor-mode)
879 880 881
  "Display documentation of a minor mode given as MINOR-MODE.
MINOR-MODE can be a minor mode symbol or a minor mode indicator string
appeared on the mode-line."
882
  (interactive (list (completing-read
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
		      "Minor mode: "
			      (nconc
			       (describe-minor-mode-completion-table-for-symbol)
			       (describe-minor-mode-completion-table-for-indicator)
			       ))))
  (if (symbolp minor-mode)
      (setq minor-mode (symbol-name minor-mode)))
  (let ((symbols (describe-minor-mode-completion-table-for-symbol))
	(indicators (describe-minor-mode-completion-table-for-indicator)))
    (cond
     ((member minor-mode symbols)
      (describe-minor-mode-from-symbol (intern minor-mode)))
     ((member minor-mode indicators)
      (describe-minor-mode-from-indicator minor-mode))
     (t
      (error "No such minor mode: %s" minor-mode)))))

900
;; symbol
901 902 903 904
(defun describe-minor-mode-completion-table-for-symbol ()
  ;; In order to list up all minor modes, minor-mode-list
  ;; is used here instead of minor-mode-alist.
  (delq nil (mapcar 'symbol-name minor-mode-list)))
905

906 907
(defun describe-minor-mode-from-symbol (symbol)
  "Display documentation of a minor mode given as a symbol, SYMBOL"
908
  (interactive (list (intern (completing-read
909 910 911 912 913 914 915 916
			      "Minor mode symbol: "
			      (describe-minor-mode-completion-table-for-symbol)))))
  (if (fboundp symbol)
      (describe-function symbol)
    (describe-variable symbol)))

;; indicator
(defun describe-minor-mode-completion-table-for-indicator ()
917
  (delq nil
918 919 920 921 922 923
	(mapcar (lambda (x)
		  (let ((i (format-mode-line x)))
		    ;; remove first space if existed
		    (cond
		     ((= 0 (length i))
		      nil)
924
		     ((eq (aref i 0) ?\s)
925
		      (substring i 1))
926
		     (t
927 928
		      i))))
		minor-mode-alist)))
929

930
(defun describe-minor-mode-from-indicator (indicator)
931 932 933
  "Display documentation of a minor mode specified by INDICATOR.
If you call this function interactively, you can give indicator which
is currently activated with completion."
934 935
  (interactive (list
		(completing-read
936
		 "Minor mode indicator: "
937
		 (describe-minor-mode-completion-table-for-indicator))))
938 939
  (let ((minor-mode (lookup-minor-mode-from-indicator indicator)))
    (if minor-mode
940
	(describe-minor-mode-from-symbol minor-mode)
941 942 943
      (error "Cannot find minor mode for `%s'" indicator))))

(defun lookup-minor-mode-from-indicator (indicator)
944
  "Return a minor mode symbol from its indicator on the mode line."
945
  ;; remove first space if existed
946
  (if (and (< 0 (length indicator))
947
	   (eq (aref indicator 0) ?\s))
948
      (setq indicator (substring indicator 1)))
949 950 951 952
  (let ((minor-modes minor-mode-alist)
	result)
    (while minor-modes
      (let* ((minor-mode (car (car minor-modes)))
953
	     (anindicator (format-mode-line
954 955
			   (car (cdr (car minor-modes))))))
	;; remove first space if existed
956
	(if (and (stringp anindicator)
957
		 (> (length anindicator) 0)
958
		 (eq (aref anindicator 0) ?\s))
959 960
	    (setq anindicator (substring anindicator 1)))
	(if (equal indicator anindicator)
961 962 963 964
	    (setq result minor-mode
		  minor-modes nil)
	  (setq minor-modes (cdr minor-modes)))))
    result))
965 966

;;; Automatic resizing of temporary buffers.
967 968 969 970 971
(defcustom temp-buffer-max-height
  (lambda (buffer)
    (if (eq (selected-window) (frame-root-window))
	(/ (x-display-pixel-height) (frame-char-height) 2)
      (/ (- (frame-height) 2) 2)))
972
  "Maximum height of a window displaying a temporary buffer.
973
This is effective only when Temp Buffer Resize mode is enabled.
974 975 976
The value is the maximum height (in lines) which
`resize-temp-buffer-window' will give to a window displaying a
temporary buffer.  It can also be a function to be called to
Paul Eggert's avatar
Paul Eggert committed
977
choose the height for such a buffer.  It gets one argument, the
978 979
buffer, and should return a positive integer.  At the time the
function is called, the window to be resized is selected."
980 981
  :type '(choice integer function)
  :group 'help
982 983
  :version "24.2")

984
(define-minor-mode temp-buffer-resize-mode
985
  "Toggle auto-resizing temporary buffer windows (Temp Buffer Resize Mode).
986 987 988 989 990
With a prefix argument ARG, enable Temp Buffer Resize mode if ARG
is positive, and disable it otherwise.  If called from Lisp,
enable the mode if ARG is omitted or nil.

When Temp Buffer Resize mode is enabled, the windows in which we
991
show a temporary buffer are automatically resized in height to
992 993
fit the buffer's contents, but never more than
`temp-buffer-max-height' nor less than `window-min-height'.
994

995 996
A window is resized only if it has been specially created for the
buffer.  Windows that have shown another buffer before are not
997 998
resized.  A frame is resized only if `fit-frame-to-buffer' is
non-nil.
999

1000 1001
This mode is used by `help', `apropos' and `completion' buffers,
and some others."
1002
  :global t :group 'help
1003
  (if temp-buffer-resize-mode