+\f
+;;; Grokking cross-reference information in doc strings and
+;;; hyperlinking it.
+
+;; This may have some scope for extension and the same or something
+;; similar should be done for widget doc strings, which currently use
+;; another mechanism.
+
+(defcustom help-highlight-p t
+ "*If non-nil, `help-make-xrefs' highlight cross-references.
+Under a window system it highlights them with face defined by
+`help-highlight-face'."
+ :group 'help
+ :version "20.3"
+ :type 'boolean)
+
+(defcustom help-highlight-face 'underline
+ "Face used by `help-make-xrefs' to highlight cross-references.
+Must be previously-defined."
+ :group 'help
+ :version "20.3"
+ :type 'face)
+
+(defvar help-back-label (purecopy "[back]")
+ "Label to use by `help-make-xrefs' for the go-back reference.")
+
+(defconst help-xref-symbol-regexp
+ (purecopy (concat "\\(\\<\\(\\(variable\\|option\\)\\|"
+ "\\(function\\|command\\)\\|"
+ "\\(face\\)\\|"
+ "\\(symbol\\)\\)\\s-+\\)?"
+ ;; Note starting with word-syntax character:
+ "`\\(\\sw\\(\\sw\\|\\s_\\)+\\)'"))
+ "Regexp matching doc string references to symbols.
+
+The words preceding the quoted symbol can be used in doc strings to
+distinguish references to variables, functions and symbols.")
+
+(defconst help-xref-info-regexp
+ (purecopy "\\<[Ii]nfo[ \t\n]+node[ \t\n]+`\\([^']+\\)'")
+ "Regexp matching doc string references to an Info node.")
+
+(defun help-setup-xref (item interactive-p)
+ "Invoked from commands using the \"*Help*\" buffer to install some xref info.
+
+ITEM is a (FUNCTION . ARGS) pair appropriate for recreating the help
+buffer after following a reference. INTERACTIVE-P is non-nil if the
+calling command was invoked interactively. In this case the stack of
+items for help buffer \"back\" buttons is cleared."
+ (if interactive-p
+ (setq help-xref-stack nil))
+ (setq help-xref-stack-item item))
+
+(defvar help-xref-following nil
+ "Non-nil when following a help cross-reference.")
+
+(defun help-make-xrefs (&optional buffer)
+ "Parse and hyperlink documentation cross-references in the given BUFFER.
+
+Find cross-reference information in a buffer and, if
+`help-highlight-p' is non-nil, highlight it with face defined by
+`help-highlight-face'; activate such cross references for selection
+with `help-follow'. Cross-references have the canonical form `...'
+and the type of reference may be disambiguated by the preceding
+word(s) used in `help-xref-symbol-regexp'.
+
+A special reference `back' is made to return back through a stack of
+help buffers. Variable `help-back-label' specifies the text for
+that."
+ (interactive "b")
+ (save-excursion
+ (set-buffer (or buffer (current-buffer)))
+ (goto-char (point-min))
+ ;; Skip the header-type info, though it might be useful to parse
+ ;; it at some stage (e.g. "function in `library'").
+ (forward-paragraph)
+ (let ((old-modified (buffer-modified-p)))
+ (let ((stab (syntax-table))
+ (case-fold-search t)
+ (inhibit-read-only t))
+ (set-syntax-table emacs-lisp-mode-syntax-table)
+ ;; The following should probably be abstracted out.
+ (unwind-protect
+ (progn
+ ;; Info references
+ (save-excursion
+ (while (re-search-forward help-xref-info-regexp nil t)
+ (let ((data (match-string 1)))
+ (save-match-data
+ (unless (string-match "^([^)]+)" data)
+ (setq data (concat "(emacs)" data))))
+ (help-xref-button 1 #'info data
+ "mouse-2, RET: read this Info node"))))
+ ;; Quoted symbols
+ (save-excursion
+ (while (re-search-forward help-xref-symbol-regexp nil t)
+ (let* ((data (match-string 7))
+ (sym (intern-soft data)))
+ (if sym
+ (cond
+ ((match-string 3) ; `variable' &c
+ (and (boundp sym) ; `variable' doesn't ensure
+ ; it's actually bound
+ (help-xref-button
+ 7 #'describe-variable sym
+ "mouse-2, RET: describe this variable")))
+ ((match-string 4) ; `function' &c
+ (and (fboundp sym) ; similarly
+ (help-xref-button
+ 7 #'describe-function sym
+ "mouse-2, RET: describe this function")))
+ ((match-string 5) ; `face'
+ (and (facep sym)
+ (help-xref-button 7 #'describe-face sym
+ "mouse-2, RET: describe this face")))
+ ((match-string 6)) ; nothing for symbol
+ ((and (boundp sym) (fboundp sym))
+ ;; We can't intuit whether to use the
+ ;; variable or function doc -- supply both.
+ (help-xref-button
+ 7 #'help-xref-interned sym
+ "mouse-2, RET: describe this symbol"))
+ ((boundp sym)
+ (help-xref-button
+ 7 #'describe-variable sym
+ "mouse-2, RET: describe this variable"))
+ ((fboundp sym)
+ (help-xref-button
+ 7 #'describe-function sym
+ "mouse-2, RET: describe this function"))
+ ((facep sym)
+ (help-xref-button
+ 7 #'describe-face sym)))))))
+ ;; An obvious case of a key substitution:
+ (save-excursion
+ (while (re-search-forward
+ ;; Assume command name is only word characters
+ ;; and dashes to get things like `use M-x foo.'.
+ "\\<M-x\\s-+\\(\\sw\\(\\sw\\|-\\)+\\)" nil t)
+ (let ((sym (intern-soft (match-string 1))))
+ (if (fboundp sym)
+ (help-xref-button
+ 1 #'describe-function sym
+ "mouse-2, RET: describe this command")))))
+ ;; Look for commands in whole keymap substitutions:
+ (save-excursion
+ ;; Make sure to find the first keymap.
+ (goto-char (point-min))
+ ;; Find a header and the column at which the command
+ ;; name will be found.
+ (while (re-search-forward "^key +binding\n\\(-+ +\\)-+\n\n"
+ nil t)
+ (let ((col (- (match-end 1) (match-beginning 1))))
+ (while
+ ;; Ignore single blank lines in table, but not
+ ;; double ones, which should terminate it.
+ (and (not (looking-at "\n\\s-*\n"))
+ (progn
+ (and (eolp) (forward-line))
+ (end-of-line)
+ (skip-chars-backward "^\t\n")
+ (if (and (>= (current-column) col)
+ (looking-at "\\(\\sw\\|-\\)+$"))
+ (let ((sym (intern-soft (match-string 0))))
+ (if (fboundp sym)
+ (help-xref-button
+ 0 #'describe-function sym
+ "mouse-2, RET: describe this function"))))
+ (zerop (forward-line)))))))))
+ (set-syntax-table stab))
+ ;; Make a back-reference in this buffer if appropriate.
+ (when (and help-xref-following help-xref-stack)
+ (goto-char (point-max))
+ (save-excursion
+ (insert "\n\n" help-back-label))
+ ;; Just to provide the match data:
+ (looking-at (concat "\n\n\\(" (regexp-quote help-back-label) "\\)"))
+ (help-xref-button 1 #'help-xref-go-back (current-buffer))))
+ ;; View mode steals RET from us.
+ (set (make-local-variable 'minor-mode-overriding-map-alist)
+ (list (cons 'view-mode
+ (let ((map (make-sparse-keymap)))
+ (set-keymap-parent map view-mode-map)
+ (define-key map "\r" 'help-follow)
+ map))))
+ (set-buffer-modified-p old-modified))))
+
+(defun help-xref-button (match-number function data &optional help-echo)
+ "Make a hyperlink for cross-reference text previously matched.
+
+MATCH-NUMBER is the subexpression of interest in the last matched
+regexp. FUNCTION is a function to invoke when the button is
+activated, applied to DATA. DATA may be a single value or a list.
+See `help-make-xrefs'.
+If optional arg HELP-ECHO is supplied, it is used as a help string."
+ ;; Don't mung properties we've added specially in some instances.
+ (unless (get-text-property (match-beginning match-number) 'help-xref)
+ (add-text-properties (match-beginning match-number)
+ (match-end match-number)
+ (list 'mouse-face 'highlight
+ 'help-xref (cons function
+ (if (listp data)
+ data
+ (list data)))))
+ (if help-echo
+ (put-text-property (match-beginning match-number)
+ (match-end match-number)
+ 'help-echo help-echo))
+ (if help-highlight-p
+ (put-text-property (match-beginning match-number)
+ (match-end match-number)
+ 'face help-highlight-face))))
+
+\f
+;; Additional functions for (re-)creating types of help buffers.
+(defun help-xref-interned (symbol)
+ "Follow a hyperlink which appeared to be an arbitrary interned SYMBOL.
+
+Both variable and function documentation are extracted into a single
+help buffer."
+ (let ((fdoc (when (fboundp symbol) (describe-function symbol)))
+ (facedoc (when (facep symbol) (describe-face symbol))))
+ (when (or (boundp symbol) (not fdoc))
+ (describe-variable symbol)
+ ;; We now have a help buffer on the variable. Insert the function
+ ;; text before it.
+ (when (or fdoc facedoc)
+ (with-current-buffer "*Help*"
+ (goto-char (point-min))
+ (let ((inhibit-read-only t))
+ (when fdoc
+ (insert fdoc "\n\n"))
+ (when facedoc
+ (insert (make-string 30 ?-) "\n\n" (symbol-name symbol)
+ " is also a " "face." "\n\n" facedoc "\n\n"))
+ (insert (make-string 30 ?-) "\n\n" (symbol-name symbol)
+ " is also a " "variable." "\n\n"))
+ (help-setup-xref (list #'help-xref-interned symbol) nil))))))
+
+(defun help-xref-mode (buffer)
+ "Do a `describe-mode' for the specified BUFFER."
+ (save-excursion
+ (set-buffer buffer)
+ (describe-mode)))
+\f
+;;; Navigation/hyperlinking with xrefs
+
+(defun help-follow-mouse (click)
+ "Follow the cross-reference that you click on."
+ (interactive "e")
+ (let* ((start (event-start click))
+ (window (car start))
+ (pos (car (cdr start))))
+ (with-current-buffer (window-buffer window)
+ (help-follow pos))))
+
+(defun help-xref-go-back (buffer)
+ "From BUFFER, go back to previous help buffer text using `help-xref-stack'."
+ (let (item position method args)
+ (with-current-buffer buffer
+ (when help-xref-stack
+ (setq help-xref-stack (cdr help-xref-stack)) ; due to help-follow
+ (setq item (pop help-xref-stack)
+ position (car item)
+ method (cadr item)
+ args (cddr item))))
+ (apply method args)
+ ;; We assume that the buffer we just recreated has the saved name,
+ ;; which might not always be true.
+ (when (get-buffer (cdr position))
+ (with-current-buffer (cdr position)
+ (goto-char (car position))))))
+
+(defun help-go-back ()
+ "Invoke the [back] button (if any) in the Help mode buffer."
+ (interactive)
+ (help-follow (1- (point-max))))
+
+(defun help-follow (&optional pos)
+ "Follow cross-reference at POS, defaulting to point.
+
+For the cross-reference format, see `help-make-xrefs'."
+ (interactive "d")
+ (unless pos
+ (setq pos (point)))
+ (let* ((help-data
+ (or (and (not (= pos (point-max)))
+ (get-text-property pos 'help-xref))
+ (and (not (= pos (point-min)))
+ (get-text-property (1- pos) 'help-xref))
+ ;; check if the symbol under point is a function or variable
+ (let ((sym
+ (intern
+ (save-excursion
+ (goto-char pos) (skip-syntax-backward "w_")
+ (buffer-substring (point)
+ (progn (skip-syntax-forward "w_")
+ (point)))))))
+ (when (or (boundp sym) (fboundp sym))
+ (list #'help-xref-interned sym)))))
+ (method (car help-data))
+ (args (cdr help-data)))
+ (when help-data
+ (setq help-xref-stack (cons (cons (cons pos (buffer-name))
+ help-xref-stack-item)
+ help-xref-stack))
+ (setq help-xref-stack-item nil)
+ ;; There is a reference at point. Follow it.
+ (let ((help-xref-following t))
+ (apply method args)))))
+
+;; For tabbing through buffer.
+(defun help-next-ref ()
+ "Find the next help cross-reference in the buffer."
+ (interactive)
+ (let (pos)
+ (while (not pos)
+ (if (get-text-property (point) 'help-xref) ; move off reference
+ (goto-char (or (next-single-property-change (point) 'help-xref)
+ (point))))
+ (cond ((setq pos (next-single-property-change (point) 'help-xref))
+ (if pos (goto-char pos)))
+ ((bobp)
+ (message "No cross references in the buffer.")
+ (setq pos t))
+ (t ; be circular
+ (goto-char (point-min)))))))
+
+(defun help-previous-ref ()
+ "Find the previous help cross-reference in the buffer."
+ (interactive)
+ (let (pos)
+ (while (not pos)
+ (if (get-text-property (point) 'help-xref) ; move off reference
+ (goto-char (or (previous-single-property-change (point) 'help-xref)
+ (point))))
+ (cond ((setq pos (previous-single-property-change (point) 'help-xref))
+ (if pos (goto-char pos)))
+ ((bobp)
+ (message "No cross references in the buffer.")
+ (setq pos t))
+ (t ; be circular
+ (goto-char (point-max)))))))
+
+\f
+;;; Automatic resizing of temporary buffers.
+
+(defcustom temp-buffer-resize-mode nil
+ "Non-nil means resize windows displaying temporary buffers.
+This makes the window the right height for its contents, but never
+more than `temp-buffer-max-height' nor less than `window-min-height'.
+This applies to `help', `apropos' and `completion' buffers, and some others.
+
+Setting this variable directly does not take effect;
+use either \\[customize] or the function `temp-buffer-resize-mode'."
+ :get (lambda (symbol)
+ (and (memq 'resize-temp-buffer-window temp-buffer-show-hook) t))
+ :set (lambda (symbol value)
+ (temp-buffer-resize-mode (if value 1 -1)))
+ :initialize 'custom-initialize-default
+ :type 'boolean
+ :group 'help
+ :version "20.4")
+
+(defcustom temp-buffer-max-height (lambda (buffer) (/ (- (frame-height) 2) 2))
+ "*Maximum height of a window displaying a temporary buffer.
+This is the maximum height (in text lines) which `resize-temp-buffer-window'
+will give to a window displaying a temporary buffer.
+It can also be a function which will be called with the object corresponding
+to the buffer to be displayed as argument and should return an integer
+positive number."
+ :type '(choice integer function)
+ :group 'help
+ :version "20.4")
+
+(defun temp-buffer-resize-mode (arg)
+ "Toggle the mode which that makes windows smaller for temporary buffers.
+With prefix argument ARG, turn the resizing of windows displaying temporary
+buffers on if ARG is positive or off otherwise.
+See the documentation of the variable `temp-buffer-resize-mode' for
+more information."
+ (interactive "P")
+ (let ((turn-it-on
+ (if (null arg)
+ (not (memq 'resize-temp-buffer-window temp-buffer-show-hook))
+ (> (prefix-numeric-value arg) 0))))
+ (if turn-it-on
+ (progn
+ ;; `help-mode-maybe' may add a `back' button and thus increase the
+ ;; text size, so `resize-temp-buffer-window' must be run *after* it.
+ (add-hook 'temp-buffer-show-hook 'resize-temp-buffer-window 'append)
+ (setq temp-buffer-resize-mode t))
+ (remove-hook 'temp-buffer-show-hook 'resize-temp-buffer-window)
+ (setq temp-buffer-resize-mode nil))))
+
+(defun resize-temp-buffer-window ()
+ "Resize the current window to fit its contents.
+Will not make it higher than `temp-buffer-max-height' nor smaller than
+`window-min-height'. Do nothing if it is the only window on its frame, if it
+is not as wide as the frame or if some of the window's contents are scrolled
+out of view."
+ (unless (or (one-window-p 'nomini)
+ (not (pos-visible-in-window-p (point-min)))
+ (/= (frame-width) (window-width)))
+ (let* ((max-height (if (functionp temp-buffer-max-height)
+ (funcall temp-buffer-max-height (current-buffer))
+ temp-buffer-max-height))
+ (win-height (1- (window-height)))
+ (min-height (1- window-min-height))
+ (text-height (count-screen-lines))
+ (new-height (max (min text-height max-height) min-height)))
+ (enlarge-window (- new-height win-height)))))
+
+;; `help-manyarg-func-alist' is defined primitively (in doc.c).
+;; New primitives with `MANY' or `UNEVALLED' arglists should be added
+;; to this alist.
+;; The parens and function name are redundant, but it's messy to add
+;; them in `documentation'.
+(defconst help-manyarg-func-alist
+ (purecopy
+ '((list . "(list &rest OBJECTS)")
+ (vector . "(vector &rest OBJECTS)")
+ (make-byte-code . "(make-byte-code &rest ELEMENTS)")
+ (call-process
+ . "(call-process PROGRAM &optional INFILE BUFFER DISPLAY &rest ARGS)")
+ (call-process-region
+ . "(call-process-region START END PROGRAM &optional DELETE BUFFER DISPLAY &rest ARGS)")
+ (string . "(string &rest CHARACTERS)")
+ (+ . "(+ &rest NUMBERS-OR-MARKERS)")
+ (- . "(- &optional NUMBER-OR-MARKER &rest MORE-NUMBERS-OR-MARKERS)")
+ (* . "(* &rest NUMBERS-OR-MARKERS)")
+ (/ . "(/ DIVIDEND DIVISOR &rest DIVISORS)")
+ (max . "(max NUMBER-OR-MARKER &rest NUMBERS-OR-MARKERS)")
+ (min . "(min NUMBER-OR-MARKER &rest NUMBERS-OR-MARKERS)")
+ (logand . "(logand &rest INTS-OR-MARKERS)")
+ (logior . "(logior &rest INTS-OR-MARKERS)")
+ (logxor . "(logxor &rest INTS-OR-MARKERS)")
+ (encode-time
+ . "(encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE)")
+ (insert . "(insert &rest ARGS)")
+ (insert-before-markers . "(insert-before-markers &rest ARGS)")
+ (message . "(message STRING &rest ARGUMENTS)")
+ (message-box . "(message-box STRING &rest ARGUMENTS)")
+ (message-or-box . "(message-or-box STRING &rest ARGUMENTS)")
+ (propertize . "(propertize STRING &rest PROPERTIES)")
+ (format . "(format STRING &rest OBJECTS)")
+ (apply . "(apply FUNCTION &rest ARGUMENTS)")
+ (run-hooks . "(run-hooks &rest HOOKS)")
+ (run-hook-with-args . "(run-hook-with-args HOOK &rest ARGS)")
+ (run-hook-with-args-until-failure
+ . "(run-hook-with-args-until-failure HOOK &rest ARGS)")
+ (run-hook-with-args-until-success
+ . "(run-hook-with-args-until-success HOOK &rest ARGS)")
+ (funcall . "(funcall FUNCTION &rest ARGUMENTS)")
+ (append . "(append &rest SEQUENCES)")
+ (concat . "(concat &rest SEQUENCES)")
+ (vconcat . "(vconcat vconcat)")
+ (nconc . "(nconc &rest LISTS)")
+ (widget-apply . "(widget-apply WIDGET PROPERTY &rest ARGS)")
+ (make-hash-table . "(make-hash-table &rest KEYWORD-ARGS)")
+ (insert-string . "(insert-string &rest ARGS)")
+ (start-process . "(start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)")
+ (setq-default . "(setq-default SYMBOL VALUE [SYMBOL VALUE...])")
+ (save-excursion . "(save-excursion &rest BODY)")
+ (save-current-buffer . "(save-current-buffer &rest BODY)")
+ (save-restriction . "(save-restriction &rest BODY)")
+ (or . "(or CONDITIONS ...)")
+ (and . "(and CONDITIONS ...)")
+ (if . "(if COND THEN ELSE...)")
+ (cond . "(cond CLAUSES...)")
+ (progn . "(progn BODY ...)")
+ (prog1 . "(prog1 FIRST BODY...)")
+ (prog2 . "(prog2 X Y BODY...)")
+ (setq . "(setq SYM VAL SYM VAL ...)")
+ (quote . "(quote ARG)")
+ (function . "(function ARG)")
+ (defun . "(defun NAME ARGLIST [DOCSTRING] BODY...)")
+ (defmacro . "(defmacro NAME ARGLIST [DOCSTRING] BODY...)")
+ (defvar . "(defvar SYMBOL [INITVALUE DOCSTRING])")
+ (defconst . "(defconst SYMBOL INITVALUE [DOCSTRING])")
+ (let* . "(let* VARLIST BODY...)")
+ (let . "(let VARLIST BODY...)")
+ (while . "(while TEST BODY...)")
+ (catch . "(catch TAG BODY...)")
+ (unwind-protect . "(unwind-protect BODYFORM UNWINDFORMS...)")
+ (condition-case . "(condition-case VAR BODYFORM HANDLERS...)")
+ (track-mouse . "(track-mouse BODY ...)")
+ (ml-if . "(ml-if COND THEN ELSE...)")
+ (ml-provide-prefix-argument . "(ml-provide-prefix-argument ARG1 ARG2)")
+ (with-output-to-temp-buffer
+ . "(with-output-to-temp-buffer BUFFNAME BODY ...)")
+ (save-window-excursion . "(save-window-excursion BODY ...)"))))
+