Small changes for lispref/errors.texi
[emacs.git] / lisp / man.el
blob0a7b831ca8ef73610c313aa3fc6646a4c7861598
1 ;;; man.el --- browse UNIX manual pages -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 1993-1994, 1996-1997, 2001-2012
4 ;; Free Software Foundation, Inc.
6 ;; Author: Barry A. Warsaw <bwarsaw@cen.com>
7 ;; Maintainer: FSF
8 ;; Keywords: help
9 ;; Adapted-By: ESR, pot
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; This code provides a function, `man', with which you can browse
29 ;; UNIX manual pages. Formatting is done in background so that you
30 ;; can continue to use your Emacs while processing is going on.
32 ;; The mode also supports hypertext-like following of manual page SEE
33 ;; ALSO references, and other features. See below or do `?' in a
34 ;; manual page buffer for details.
36 ;; ========== Credits and History ==========
37 ;; In mid 1991, several people posted some interesting improvements to
38 ;; man.el from the standard Emacs 18.57 distribution. I liked many of
39 ;; these, but wanted everything in one single package, so I decided
40 ;; to incorporate them into a single manual browsing mode. While
41 ;; much of the code here has been rewritten, and some features added,
42 ;; these folks deserve lots of credit for providing the initial
43 ;; excellent packages on which this one is based.
45 ;; Nick Duffek <duffek@chaos.cs.brandeis.edu>, posted a very nice
46 ;; improvement which retrieved and cleaned the manpages in a
47 ;; background process, and which correctly deciphered such options as
48 ;; man -k.
50 ;; Eric Rose <erose@jessica.stanford.edu>, submitted manual.el which
51 ;; provided a very nice manual browsing mode.
53 ;; This package was available as `superman.el' from the LCD package
54 ;; for some time before it was accepted into Emacs 19. The entry
55 ;; point and some other names have been changed to make it a drop-in
56 ;; replacement for the old man.el package.
58 ;; Francesco Potorti` <pot@cnuce.cnr.it> cleaned it up thoroughly,
59 ;; making it faster, more robust and more tolerant of different
60 ;; systems' man idiosyncrasies.
62 ;; ========== Features ==========
63 ;; + Runs "man" in the background and pipes the results through a
64 ;; series of sed and awk scripts so that all retrieving and cleaning
65 ;; is done in the background. The cleaning commands are configurable.
66 ;; + Syntax is the same as Un*x man
67 ;; + Functionality is the same as Un*x man, including "man -k" and
68 ;; "man <section>", etc.
69 ;; + Provides a manual browsing mode with keybindings for traversing
70 ;; the sections of a manpage, following references in the SEE ALSO
71 ;; section, and more.
72 ;; + Multiple manpages created with the same man command are put into
73 ;; a narrowed buffer circular list.
75 ;; ============= TODO ===========
76 ;; - Add a command for printing.
77 ;; - The awk script deletes multiple blank lines. This behavior does
78 ;; not allow to understand if there was indeed a blank line at the
79 ;; end or beginning of a page (after the header, or before the
80 ;; footer). A different algorithm should be used. It is easy to
81 ;; compute how many blank lines there are before and after the page
82 ;; headers, and after the page footer. But it is possible to compute
83 ;; the number of blank lines before the page footer by heuristics
84 ;; only. Is it worth doing?
85 ;; - Allow a user option to mean that all the manpages should go in
86 ;; the same buffer, where they can be browsed with M-n and M-p.
89 ;;; Code:
91 (eval-when-compile (require 'cl))
92 (require 'assoc)
93 (require 'button)
95 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
96 ;; empty defvars (keep the compiler quiet)
98 (defgroup man nil
99 "Browse UNIX manual pages."
100 :prefix "Man-"
101 :group 'external
102 :group 'help)
104 (defvar Man-notify)
105 (defcustom Man-filter-list nil
106 "Manpage cleaning filter command phrases.
107 This variable contains a list of the following form:
109 '((command-string phrase-string*)*)
111 Each phrase-string is concatenated onto the command-string to form a
112 command filter. The (standard) output (and standard error) of the Un*x
113 man command is piped through each command filter in the order the
114 commands appear in the association list. The final output is placed in
115 the manpage buffer."
116 :type '(repeat (list (string :tag "Command String")
117 (repeat :inline t
118 (string :tag "Phrase String"))))
119 :group 'man)
121 (defvar Man-uses-untabify-flag t
122 "Non-nil means use `untabify' instead of `Man-untabify-command'.")
123 (defvar Man-sed-script nil
124 "Script for sed to nuke backspaces and ANSI codes from manpages.")
126 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
127 ;; user variables
129 (defcustom Man-fontify-manpage-flag t
130 "Non-nil means make up the manpage with fonts."
131 :type 'boolean
132 :group 'man)
134 (defcustom Man-overstrike-face 'bold
135 "Face to use when fontifying overstrike."
136 :type 'face
137 :group 'man)
139 (defcustom Man-underline-face 'underline
140 "Face to use when fontifying underlining."
141 :type 'face
142 :group 'man)
144 (defcustom Man-reverse-face 'highlight
145 "Face to use when fontifying reverse video."
146 :type 'face
147 :group 'man)
149 ;; Use the value of the obsolete user option Man-notify, if set.
150 (defcustom Man-notify-method (if (boundp 'Man-notify) Man-notify 'friendly)
151 "Selects the behavior when manpage is ready.
152 This variable may have one of the following values, where (sf) means
153 that the frames are switched, so the manpage is displayed in the frame
154 where the man command was called from:
156 newframe -- put the manpage in its own frame (see `Man-frame-parameters')
157 pushy -- make the manpage the current buffer in the current window
158 bully -- make the manpage the current buffer and only window (sf)
159 aggressive -- make the manpage the current buffer in the other window (sf)
160 friendly -- display manpage in the other window but don't make current (sf)
161 polite -- don't display manpage, but prints message and beep when ready
162 quiet -- like `polite', but don't beep
163 meek -- make no indication that the manpage is ready
165 Any other value of `Man-notify-method' is equivalent to `meek'."
166 :type '(radio (const newframe) (const pushy) (const bully)
167 (const aggressive) (const friendly)
168 (const polite) (const quiet) (const meek))
169 :group 'man)
171 (defcustom Man-width nil
172 "Number of columns for which manual pages should be formatted.
173 If nil, the width of the window selected at the moment of man
174 invocation is used. If non-nil, the width of the frame selected
175 at the moment of man invocation is used. The value also can be a
176 positive integer."
177 :type '(choice (const :tag "Window width" nil)
178 (const :tag "Frame width" t)
179 (integer :tag "Specific width" :value 65))
180 :group 'man)
182 (defcustom Man-frame-parameters nil
183 "Frame parameter list for creating a new frame for a manual page."
184 :type 'sexp
185 :group 'man)
187 (defcustom Man-downcase-section-letters-flag t
188 "Non-nil means letters in sections are converted to lower case.
189 Some Un*x man commands can't handle uppercase letters in sections, for
190 example \"man 2V chmod\", but they are often displayed in the manpage
191 with the upper case letter. When this variable is t, the section
192 letter (e.g., \"2V\") is converted to lowercase (e.g., \"2v\") before
193 being sent to the man background process."
194 :type 'boolean
195 :group 'man)
197 (defcustom Man-circular-pages-flag t
198 "Non-nil means the manpage list is treated as circular for traversal."
199 :type 'boolean
200 :group 'man)
202 (defcustom Man-section-translations-alist
203 (list
204 '("3C++" . "3")
205 ;; Some systems have a real 3x man section, so let's comment this.
206 ;; '("3X" . "3") ; Xlib man pages
207 '("3X11" . "3")
208 '("1-UCB" . ""))
209 "Association list of bogus sections to real section numbers.
210 Some manpages (e.g. the Sun C++ 2.1 manpages) have section numbers in
211 their references which Un*x `man' does not recognize. This
212 association list is used to translate those sections, when found, to
213 the associated section number."
214 :type '(repeat (cons (string :tag "Bogus Section")
215 (string :tag "Real Section")))
216 :group 'man)
218 ;; FIXME see comments at ffap-c-path.
219 (defcustom Man-header-file-path
220 (let ((arch (with-temp-buffer
221 (when (eq 0 (ignore-errors
222 (call-process "gcc" nil '(t nil) nil
223 "-print-multiarch")))
224 (goto-char (point-min))
225 (buffer-substring (point) (line-end-position)))))
226 (base '("/usr/include" "/usr/local/include")))
227 (if (zerop (length arch))
228 base
229 (append base (list (expand-file-name arch "/usr/include")))))
230 "C Header file search path used in Man."
231 :version "24.1" ; add multiarch
232 :type '(repeat string)
233 :group 'man)
235 (defcustom Man-name-local-regexp (concat "^" (regexp-opt '("NOM" "NAME")) "$")
236 "Regexp that matches the text that precedes the command's name.
237 Used in `bookmark-set' to get the default bookmark name."
238 :version "24.1"
239 :type 'string :group 'bookmark)
241 (defvar manual-program "man"
242 "The name of the program that produces man pages.")
244 (defvar Man-untabify-command "pr"
245 "Command used for untabifying.")
247 (defvar Man-untabify-command-args (list "-t" "-e")
248 "List of arguments to be passed to `Man-untabify-command' (which see).")
250 (defvar Man-sed-command "sed"
251 "Command used for processing sed scripts.")
253 (defvar Man-awk-command "awk"
254 "Command used for processing awk scripts.")
256 (defvar Man-mode-hook nil
257 "Hook run when Man mode is enabled.")
259 (defvar Man-cooked-hook nil
260 "Hook run after removing backspaces but before `Man-mode' processing.")
262 (defvar Man-name-regexp "[-a-zA-Z0-9_­+][-a-zA-Z0-9_.:­+]*"
263 "Regular expression describing the name of a manpage (without section).")
265 (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
266 "Regular expression describing a manpage section within parentheses.")
268 (defvar Man-page-header-regexp
269 (if (string-match "-solaris2\\." system-configuration)
270 (concat "^[-A-Za-z0-9_].*[ \t]\\(" Man-name-regexp
271 "(\\(" Man-section-regexp "\\))\\)$")
272 (concat "^[ \t]*\\(" Man-name-regexp
273 "(\\(" Man-section-regexp "\\))\\).*\\1"))
274 "Regular expression describing the heading of a page.")
276 (defvar Man-heading-regexp "^\\([A-Z][A-Z0-9 /-]+\\)$"
277 "Regular expression describing a manpage heading entry.")
279 (defvar Man-see-also-regexp "SEE ALSO"
280 "Regular expression for SEE ALSO heading (or your equivalent).
281 This regexp should not start with a `^' character.")
283 ;; This used to have leading space [ \t]*, but was removed because it
284 ;; causes false page splits on an occasional NAME with leading space
285 ;; inside a manpage. And `Man-heading-regexp' doesn't have [ \t]* anyway.
286 (defvar Man-first-heading-regexp "^NAME$\\|^[ \t]*No manual entry fo.*$"
287 "Regular expression describing first heading on a manpage.
288 This regular expression should start with a `^' character.")
290 (defvar Man-reference-regexp
291 (concat "\\(" Man-name-regexp
292 "\\(\n[ \t]+" Man-name-regexp "\\)*\\)[ \t]*(\\("
293 Man-section-regexp "\\))")
294 "Regular expression describing a reference to another manpage.")
296 (defvar Man-apropos-regexp
297 (concat "\\\[\\(" Man-name-regexp "\\)\\\][ \t]*(\\(" Man-section-regexp "\\))")
298 "Regular expression describing a reference to manpages in \"man -k output\".")
300 (defvar Man-synopsis-regexp "SYNOPSIS"
301 "Regular expression for SYNOPSIS heading (or your equivalent).
302 This regexp should not start with a `^' character.")
304 (defvar Man-files-regexp "FILES\\>"
305 ;; Add \> so as not to match mount(8)'s FILESYSTEM INDEPENDENT MOUNT OPTIONS.
306 "Regular expression for FILES heading (or your equivalent).
307 This regexp should not start with a `^' character.")
309 (defvar Man-include-regexp "#[ \t]*include[ \t]*"
310 "Regular expression describing the #include (directive of cpp).")
312 (defvar Man-file-name-regexp "[^<>\", \t\n]+"
313 "Regular expression describing <> in #include line (directive of cpp).")
315 (defvar Man-normal-file-prefix-regexp "[/~$]"
316 "Regular expression describing a file path appeared in FILES section.")
318 (defvar Man-header-regexp
319 (concat "\\(" Man-include-regexp "\\)"
320 "[<\"]"
321 "\\(" Man-file-name-regexp "\\)"
322 "[>\"]")
323 "Regular expression describing references to header files.")
325 (defvar Man-normal-file-regexp
326 (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
327 "Regular expression describing references to normal files.")
329 ;; This includes the section as an optional part to catch hyphenated
330 ;; references to manpages.
331 (defvar Man-hyphenated-reference-regexp
332 (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
333 "Regular expression describing a reference in the SEE ALSO section.")
335 (defvar Man-switches ""
336 "Switches passed to the man command, as a single string.
338 If you want to be able to see all the manpages for a subject you type,
339 make -a one of the switches, if your `man' program supports it.")
341 (defvar Man-specified-section-option
342 (if (string-match "-solaris[0-9.]*$" system-configuration)
343 "-s"
345 "Option that indicates a specified a manual section name.")
347 (defvar Man-support-local-filenames 'auto-detect
348 "Internal cache for the value of the function `Man-support-local-filenames'.
349 `auto-detect' means the value is not yet determined.
350 Otherwise, the value is whatever the function
351 `Man-support-local-filenames' should return.")
353 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
354 ;; end user variables
356 ;; other variables and keymap initializations
357 (defvar Man-original-frame)
358 (make-variable-buffer-local 'Man-original-frame)
359 (defvar Man-arguments)
360 (make-variable-buffer-local 'Man-arguments)
361 (put 'Man-arguments 'permanent-local t)
363 (defvar Man-sections-alist nil)
364 (make-variable-buffer-local 'Man-sections-alist)
365 (defvar Man-refpages-alist nil)
366 (make-variable-buffer-local 'Man-refpages-alist)
367 (defvar Man-page-list nil)
368 (make-variable-buffer-local 'Man-page-list)
369 (defvar Man-current-page 0)
370 (make-variable-buffer-local 'Man-current-page)
371 (defvar Man-page-mode-string "1 of 1")
372 (make-variable-buffer-local 'Man-page-mode-string)
374 (defconst Man-sysv-sed-script "\
375 /\b/ { s/_\b//g
376 s/\b_//g
377 s/o\b+/o/g
378 s/+\bo/o/g
379 :ovstrk
380 s/\\(.\\)\b\\1/\\1/g
381 t ovstrk
383 /\e\\[[0-9][0-9]*m/ s///g"
384 "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
386 (defconst Man-berkeley-sed-script "\
387 /\b/ { s/_\b//g\\
388 s/\b_//g\\
389 s/o\b+/o/g\\
390 s/+\bo/o/g\\
391 :ovstrk\\
392 s/\\(.\\)\b\\1/\\1/g\\
393 t ovstrk\\
395 /\e\\[[0-9][0-9]*m/ s///g"
396 "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
398 (defvar Man-topic-history nil "Topic read history.")
400 (defvar man-mode-syntax-table
401 (let ((table (copy-syntax-table (standard-syntax-table))))
402 (modify-syntax-entry ?. "w" table)
403 (modify-syntax-entry ?_ "w" table)
404 (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
405 table)
406 "Syntax table used in Man mode buffers.")
408 (defvar Man-mode-map
409 (let ((map (make-sparse-keymap)))
410 (suppress-keymap map)
411 (set-keymap-parent map button-buffer-map)
413 (define-key map " " 'scroll-up-command)
414 (define-key map "\177" 'scroll-down-command)
415 (define-key map "n" 'Man-next-section)
416 (define-key map "p" 'Man-previous-section)
417 (define-key map "\en" 'Man-next-manpage)
418 (define-key map "\ep" 'Man-previous-manpage)
419 (define-key map ">" 'end-of-buffer)
420 (define-key map "<" 'beginning-of-buffer)
421 (define-key map "." 'beginning-of-buffer)
422 (define-key map "r" 'Man-follow-manual-reference)
423 (define-key map "g" 'Man-goto-section)
424 (define-key map "s" 'Man-goto-see-also-section)
425 (define-key map "k" 'Man-kill)
426 (define-key map "q" 'Man-quit)
427 (define-key map "m" 'man)
428 ;; Not all the man references get buttons currently. The text in the
429 ;; manual page can contain references to other man pages
430 (define-key map "\r" 'man-follow)
431 (define-key map "?" 'describe-mode)
432 map)
433 "Keymap for Man mode.")
435 ;; buttons
436 (define-button-type 'Man-abstract-xref-man-page
437 'follow-link t
438 'help-echo "mouse-2, RET: display this man page"
439 'func nil
440 'action #'Man-xref-button-action)
442 (defun Man-xref-button-action (button)
443 (let ((target (button-get button 'Man-target-string)))
444 (funcall
445 (button-get button 'func)
446 (cond ((null target)
447 (button-label button))
448 ((functionp target)
449 (funcall target (button-start button)))
450 (t target)))))
452 (define-button-type 'Man-xref-man-page
453 :supertype 'Man-abstract-xref-man-page
454 'func 'man-follow)
457 (define-button-type 'Man-xref-header-file
458 'action (lambda (button)
459 (let ((w (button-get button 'Man-target-string)))
460 (unless (Man-view-header-file w)
461 (error "Cannot find header file: %s" w))))
462 'follow-link t
463 'help-echo "mouse-2: display this header file")
465 (define-button-type 'Man-xref-normal-file
466 'action (lambda (button)
467 (let ((f (substitute-in-file-name
468 (button-get button 'Man-target-string))))
469 (if (file-exists-p f)
470 (if (file-readable-p f)
471 (view-file f)
472 (error "Cannot read a file: %s" f))
473 (error "Cannot find a file: %s" f))))
474 'follow-link t
475 'help-echo "mouse-2: display this file")
478 ;; ======================================================================
479 ;; utilities
481 (defun Man-init-defvars ()
482 "Used for initializing variables based on display's color support.
483 This is necessary if one wants to dump man.el with Emacs."
485 ;; Avoid possible error in call-process by using a directory that must exist.
486 (let ((default-directory "/"))
487 (setq Man-sed-script
488 (cond
489 (Man-fontify-manpage-flag
490 nil)
491 ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
492 Man-sysv-sed-script)
493 ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
494 Man-berkeley-sed-script)
496 nil))))
498 (setq Man-filter-list
499 ;; Avoid trailing nil which confuses customize.
500 (apply 'list
501 (cons
502 Man-sed-command
503 (if (eq system-type 'windows-nt)
504 ;; Windows needs ".." quoting, not '..'.
505 (list
506 "-e \"/Reformatting page. Wait/d\""
507 "-e \"/Reformatting entry. Wait/d\""
508 "-e \"/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d\""
509 "-e \"/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d\""
510 "-e \"/^Printed[ \t][0-9].*[0-9]$/d\""
511 "-e \"/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d\""
512 "-e \"/^[A-Za-z].*Last[ \t]change:/d\""
513 "-e \"/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d\""
514 "-e \"/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d\"")
515 (list
516 (if Man-sed-script
517 (concat "-e '" Man-sed-script "'")
519 "-e '/^[\001-\032][\001-\032]*$/d'"
520 "-e '/\e[789]/s///g'"
521 "-e '/Reformatting page. Wait/d'"
522 "-e '/Reformatting entry. Wait/d'"
523 "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
524 "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
525 "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
526 "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
527 "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
528 "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
529 "-e '/^[A-Za-z].*Last[ \t]change:/d'"
530 "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
531 "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
532 "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
534 ;; Windows doesn't support multi-line commands, so don't
535 ;; invoke Awk there.
536 (unless (eq system-type 'windows-nt)
537 (cons
538 Man-awk-command
539 (list
540 "'\n"
541 "BEGIN { blankline=0; anonblank=0; }\n"
542 "/^$/ { if (anonblank==0) next; }\n"
543 "{ anonblank=1; }\n"
544 "/^$/ { blankline++; next; }\n"
545 "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
548 (if (not Man-uses-untabify-flag)
549 ;; The outer list will be stripped off by apply.
550 (list (cons
551 Man-untabify-command
552 Man-untabify-command-args))
556 (defsubst Man-make-page-mode-string ()
557 "Formats part of the mode line for Man mode."
558 (format "%s page %d of %d"
559 (or (nth 2 (nth (1- Man-current-page) Man-page-list))
561 Man-current-page
562 (length Man-page-list)))
564 (defsubst Man-build-man-command ()
565 "Builds the entire background manpage and cleaning command."
566 (let ((command (concat manual-program " " Man-switches
567 (cond
568 ;; Already has %s
569 ((string-match "%s" manual-program) "")
570 ;; Stock MS-DOS shells cannot redirect stderr;
571 ;; `call-process' below sends it to /dev/null,
572 ;; so we don't need `2>' even with DOS shells
573 ;; which do support stderr redirection.
574 ((not (fboundp 'start-process)) " %s")
575 ((concat " %s 2>" null-device)))))
576 (flist Man-filter-list))
577 (while (and flist (car flist))
578 (let ((pcom (car (car flist)))
579 (pargs (cdr (car flist))))
580 (setq command
581 (concat command " | " pcom " "
582 (mapconcat (lambda (phrase)
583 (if (not (stringp phrase))
584 (error "Malformed Man-filter-list"))
585 phrase)
586 pargs " ")))
587 (setq flist (cdr flist))))
588 command))
591 (defun Man-translate-cleanup (string)
592 "Strip leading, trailing and middle spaces."
593 (when (stringp string)
594 ;; Strip leading and trailing
595 (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
596 (setq string (match-string 1 string)))
597 ;; middle spaces
598 (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
599 (setq string (replace-regexp-in-string " +" " " string))
600 string))
602 (defun Man-translate-references (ref)
603 "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
604 Leave it as is if already in that style. Possibly downcase and
605 translate the section (see the `Man-downcase-section-letters-flag'
606 and the `Man-section-translations-alist' variables)."
607 (let ((name "")
608 (section "")
609 (slist Man-section-translations-alist))
610 (setq ref (Man-translate-cleanup ref))
611 (cond
612 ;; "chmod(2V)" case ?
613 ((string-match (concat "^" Man-reference-regexp "$") ref)
614 (setq name (replace-regexp-in-string "[\n\t ]" "" (match-string 1 ref))
615 section (match-string 3 ref)))
616 ;; "2v chmod" case ?
617 ((string-match (concat "^\\(" Man-section-regexp
618 "\\) +\\(" Man-name-regexp "\\)$") ref)
619 (setq name (match-string 2 ref)
620 section (match-string 1 ref))))
621 (if (string= name "")
622 ref ; Return the reference as is
623 (if Man-downcase-section-letters-flag
624 (setq section (downcase section)))
625 (while slist
626 (let ((s1 (car (car slist)))
627 (s2 (cdr (car slist))))
628 (setq slist (cdr slist))
629 (if Man-downcase-section-letters-flag
630 (setq s1 (downcase s1)))
631 (if (not (string= s1 section)) nil
632 (setq section (if Man-downcase-section-letters-flag
633 (downcase s2)
635 slist nil))))
636 (concat Man-specified-section-option section " " name))))
638 (defun Man-support-local-filenames ()
639 "Return non-nil if the man command supports local filenames.
640 Different man programs support this feature in different ways.
641 The default Debian man program (\"man-db\") has a `--local-file'
642 \(or `-l') option for this purpose. The default Red Hat man
643 program has no such option, but interprets any name containing
644 a \"/\" as a local filename. The function returns either `man-db'
645 `man', or nil."
646 (if (eq Man-support-local-filenames 'auto-detect)
647 (setq Man-support-local-filenames
648 (with-temp-buffer
649 (let ((default-directory
650 ;; Ensure that `default-directory' exists and is readable.
651 (if (and (file-directory-p default-directory)
652 (file-readable-p default-directory))
653 default-directory
654 (expand-file-name "~/"))))
655 (ignore-errors
656 (call-process manual-program nil t nil "--help")))
657 (cond ((search-backward "--local-file" nil 'move)
658 'man-db)
659 ;; This feature seems to be present in at least ver 1.4f,
660 ;; which is about 20 years old.
661 ;; I don't know if this version has an official name?
662 ((looking-at "^man, versione? [1-9]")
663 'man))))
664 Man-support-local-filenames))
667 ;; ======================================================================
668 ;; default man entry: get word near point
670 (defun Man-default-man-entry (&optional pos)
671 "Guess default manual entry based on the text near position POS.
672 POS defaults to `point'."
673 (let (word start column distance)
674 (save-excursion
675 (when pos (goto-char pos))
676 (setq pos (point))
677 ;; The default title is the nearest entry-like object before or
678 ;; after POS.
679 (if (and (skip-chars-backward " \ta-zA-Z0-9+")
680 (not (zerop (skip-chars-backward "(")))
681 ;; Try to handle the special case where POS is on a
682 ;; section number.
683 (looking-at
684 (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
685 ;; We skipped a valid section number backwards, look at
686 ;; preceding text.
687 (or (and (skip-chars-backward ",; \t")
688 (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
689 ;; Not a valid entry, move POS after closing paren.
690 (not (setq pos (match-end 0)))))
691 ;; We have a candidate, make `start' record its starting
692 ;; position.
693 (setq start (point))
694 ;; Otherwise look at char before POS.
695 (goto-char pos)
696 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
697 ;; Our candidate is just before or around POS.
698 (setq start (point))
699 ;; Otherwise record the current column and look backwards.
700 (setq column (current-column))
701 (skip-chars-backward ",; \t")
702 ;; Record the distance traveled.
703 (setq distance (- column (current-column)))
704 (when (looking-back
705 (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)"))
706 ;; Skip section number backwards.
707 (goto-char (match-beginning 0))
708 (skip-chars-backward " \t"))
709 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
710 (progn
711 ;; We have a candidate before POS ...
712 (setq start (point))
713 (goto-char pos)
714 (if (and (skip-chars-forward ",; \t")
715 (< (- (current-column) column) distance)
716 (looking-at "[-a-zA-Z0-9._+:]"))
717 ;; ... but the one after POS is better.
718 (setq start (point))
719 ;; ... and anything after POS is worse.
720 (goto-char start)))
721 ;; No candidate before POS.
722 (goto-char pos)
723 (skip-chars-forward ",; \t")
724 (setq start (point)))))
725 ;; We have found a suitable starting point, try to skip at least
726 ;; one character.
727 (skip-chars-forward "-a-zA-Z0-9._+:")
728 (setq word (buffer-substring-no-properties start (point)))
729 ;; If there is a continuation at the end of line, check the
730 ;; following line too, eg:
731 ;; see this-
732 ;; command-here(1)
733 ;; Note: This code gets executed iff our entry is after POS.
734 (when (looking-at "[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
735 (setq word (concat word (match-string-no-properties 1)))
736 ;; Make sure the section number gets included by the code below.
737 (goto-char (match-end 1)))
738 (when (string-match "[._]+$" word)
739 (setq word (substring word 0 (match-beginning 0))))
740 ;; The following was commented out since the preceding code
741 ;; should not produce a leading "*" in the first place.
742 ;;; ;; If looking at something like *strcat(... , remove the '*'
743 ;;; (when (string-match "^*" word)
744 ;;; (setq word (substring word 1)))
745 (concat
746 word
747 (and (not (string-equal word ""))
748 ;; If looking at something like ioctl(2) or brc(1M),
749 ;; include the section number in the returned value.
750 (looking-at
751 (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
752 (format "(%s)" (match-string-no-properties 1)))))))
755 ;; ======================================================================
756 ;; Top level command and background process sentinel
758 ;; For compatibility with older versions.
759 ;;;###autoload
760 (defalias 'manual-entry 'man)
762 (defvar Man-completion-cache nil
763 ;; On my machine, "man -k" is so fast that a cache makes no sense,
764 ;; but apparently that's not the case in all cases, so let's add a cache.
765 "Cache of completion table of the form (PREFIX . TABLE).")
767 (defun Man-completion-table (string pred action)
768 (cond
769 ;; This ends up returning t for pretty much any string, and hence leads to
770 ;; spurious "complete but not unique" messages. And since `man' doesn't
771 ;; require-match anyway, there's not point being clever.
772 ;;((eq action 'lambda) (not (string-match "([^)]*\\'" string)))
773 ((equal string "-k")
774 ;; Let SPC (minibuffer-complete-word) insert the space.
775 (complete-with-action action '("-k ") string pred))
777 (let ((table (cdr Man-completion-cache))
778 (section nil)
779 (prefix string))
780 (when (string-match "\\`\\([[:digit:]].*?\\) " string)
781 (setq section (match-string 1 string))
782 (setq prefix (substring string (match-end 0))))
783 (unless (and Man-completion-cache
784 (string-prefix-p (car Man-completion-cache) prefix))
785 (with-temp-buffer
786 (setq default-directory "/") ;; in case inherited doesn't exist
787 ;; Actually for my `man' the arg is a regexp.
788 ;; POSIX says it must be ERE and "man-db" seems to agree,
789 ;; whereas under MacOSX it seems to be BRE-style and doesn't
790 ;; accept backslashes at all. Let's not bother to
791 ;; quote anything.
792 (let ((process-environment (copy-sequence process-environment)))
793 (setenv "COLUMNS" "999") ;; don't truncate long names
794 ;; manual-program might not even exist. And since it's
795 ;; run differently in Man-getpage-in-background, an error
796 ;; here may not necessarily mean that we'll also get an
797 ;; error later.
798 (ignore-errors
799 (call-process manual-program nil '(t nil) nil
800 "-k" (concat "^" prefix))))
801 (goto-char (point-min))
802 (while (re-search-forward "^\\([^ \t\n]+\\)\\(?: ?\\((.+?)\\)\\(?:[ \t]+- \\(.*\\)\\)?\\)?" nil t)
803 (push (propertize (concat (match-string 1) (match-string 2))
804 'help-echo (match-string 3))
805 table)))
806 ;; Cache the table for later reuse.
807 (setq Man-completion-cache (cons prefix table)))
808 ;; The table may contain false positives since the match is made
809 ;; by "man -k" not just on the manpage's name.
810 (if section
811 (let ((re (concat "(" (regexp-quote section) ")\\'")))
812 (dolist (comp (prog1 table (setq table nil)))
813 (if (string-match re comp)
814 (push (substring comp 0 (match-beginning 0)) table)))
815 (completion-table-with-context (concat section " ") table
816 prefix pred action))
817 ;; If the current text looks like a possible section name,
818 ;; then add a completion entry that just adds a space so SPC
819 ;; can be used to insert a space.
820 (if (string-match "\\`[[:digit:]]" string)
821 (push (concat string " ") table))
822 (let ((res (complete-with-action action table string pred)))
823 ;; In case we're completing to a single name that exists in
824 ;; several sections, the longest prefix will look like "foo(".
825 (if (and (stringp res)
826 (string-match "([^(]*\\'" res)
827 ;; In case the paren was already in `prefix', don't
828 ;; remove it.
829 (> (match-beginning 0) (length prefix)))
830 (substring res 0 (match-beginning 0))
831 res)))))))
833 ;;;###autoload
834 (defun man (man-args)
835 "Get a Un*x manual page and put it in a buffer.
836 This command is the top-level command in the man package. It
837 runs a Un*x command to retrieve and clean a manpage in the
838 background and places the results in a `Man-mode' browsing
839 buffer. See variable `Man-notify-method' for what happens when
840 the buffer is ready. If a buffer already exists for this man
841 page, it will display immediately.
843 For a manpage from a particular section, use either of the
844 following. \"cat(1)\" is how cross-references appear and is
845 passed to man as \"1 cat\".
847 cat(1)
848 1 cat
850 To see manpages from all sections related to a subject, use an
851 \"all pages\" option (which might be \"-a\" if it's not the
852 default), then step through with `Man-next-manpage' (\\<Man-mode-map>\\[Man-next-manpage]) etc.
853 Add to `Man-switches' to make this option permanent.
855 -a chmod
857 An explicit filename can be given too. Use -l if it might
858 otherwise look like a page name.
860 /my/file/name.1.gz
861 -l somefile.1
863 An \"apropos\" query with -k gives a buffer of matching page
864 names or descriptions. The pattern argument is usually an
865 \"egrep\" style regexp.
867 -k pattern"
869 (interactive
870 (list (let* ((default-entry (Man-default-man-entry))
871 ;; ignore case because that's friendly for bizarre
872 ;; caps things like the X11 function names and because
873 ;; "man" itself is case-sensitive on the command line
874 ;; so you're accustomed not to bother about the case
875 ;; ("man -k" is case-insensitive similarly, so the
876 ;; table has everything available to complete)
877 (completion-ignore-case t)
878 (input (completing-read
879 (format "Manual entry%s"
880 (if (string= default-entry "")
881 ": "
882 (format " (default %s): " default-entry)))
883 'Man-completion-table
884 nil nil nil 'Man-topic-history default-entry)))
885 (if (string= input "")
886 (error "No man args given")
887 input))))
889 ;; Possibly translate the "subject(section)" syntax into the
890 ;; "section subject" syntax and possibly downcase the section.
891 (setq man-args (Man-translate-references man-args))
893 (Man-getpage-in-background man-args))
895 ;;;###autoload
896 (defun man-follow (man-args)
897 "Get a Un*x manual page of the item under point and put it in a buffer."
898 (interactive (list (Man-default-man-entry)))
899 (if (or (not man-args)
900 (string= man-args ""))
901 (error "No item under point")
902 (man man-args)))
904 (defun Man-getpage-in-background (topic)
905 "Use TOPIC to build and fire off the manpage and cleaning command.
906 Return the buffer in which the manpage will appear."
907 (let* ((man-args topic)
908 (bufname (concat "*Man " man-args "*"))
909 (buffer (get-buffer bufname)))
910 (if buffer
911 (Man-notify-when-ready buffer)
912 (require 'env)
913 (message "Invoking %s %s in the background" manual-program man-args)
914 (setq buffer (generate-new-buffer bufname))
915 (with-current-buffer buffer
916 (setq buffer-undo-list t)
917 (setq Man-original-frame (selected-frame))
918 (setq Man-arguments man-args))
919 (let ((process-environment (copy-sequence process-environment))
920 ;; The following is so Awk script gets \n intact
921 ;; But don't prevent decoding of the outside.
922 (coding-system-for-write 'raw-text-unix)
923 ;; We must decode the output by a coding system that the
924 ;; system's locale suggests in multibyte mode.
925 (coding-system-for-read
926 (if (default-value 'enable-multibyte-characters)
927 locale-coding-system 'raw-text-unix))
928 ;; Avoid possible error by using a directory that always exists.
929 (default-directory
930 (if (and (file-directory-p default-directory)
931 (not (find-file-name-handler default-directory
932 'file-directory-p)))
933 default-directory
934 "/")))
935 ;; Prevent any attempt to use display terminal fanciness.
936 (setenv "TERM" "dumb")
937 ;; In Debian Woody, at least, we get overlong lines under X
938 ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
939 ;; a tty. man(1) says:
940 ;; MANWIDTH
941 ;; If $MANWIDTH is set, its value is used as the line
942 ;; length for which manual pages should be formatted.
943 ;; If it is not set, manual pages will be formatted
944 ;; with a line length appropriate to the current ter-
945 ;; minal (using an ioctl(2) if available, the value of
946 ;; $COLUMNS, or falling back to 80 characters if nei-
947 ;; ther is available).
948 (when (or window-system
949 (not (or (getenv "MANWIDTH") (getenv "COLUMNS"))))
950 ;; This isn't strictly correct, since we don't know how
951 ;; the page will actually be displayed, but it seems
952 ;; reasonable.
953 (setenv "COLUMNS" (number-to-string
954 (cond
955 ((and (integerp Man-width) (> Man-width 0))
956 Man-width)
957 (Man-width (frame-width))
958 ((window-width))))))
959 (setenv "GROFF_NO_SGR" "1")
960 ;; Since man-db 2.4.3-1, man writes plain text with no escape
961 ;; sequences when stdout is not a tty. In 2.5.0, the following
962 ;; env-var was added to allow control of this (see Debian Bug#340673).
963 (setenv "MAN_KEEP_FORMATTING" "1")
964 (if (fboundp 'start-process)
965 (set-process-sentinel
966 (start-process manual-program buffer
967 (if (memq system-type '(cygwin windows-nt))
968 shell-file-name
969 "sh")
970 shell-command-switch
971 (format (Man-build-man-command) man-args))
972 'Man-bgproc-sentinel)
973 (let ((exit-status
974 (call-process shell-file-name nil (list buffer nil) nil
975 shell-command-switch
976 (format (Man-build-man-command) man-args)))
977 (msg ""))
978 (or (and (numberp exit-status)
979 (= exit-status 0))
980 (and (numberp exit-status)
981 (setq msg
982 (format "exited abnormally with code %d"
983 exit-status)))
984 (setq msg exit-status))
985 (Man-bgproc-sentinel bufname msg)))))
986 buffer))
988 (defun Man-notify-when-ready (man-buffer)
989 "Notify the user when MAN-BUFFER is ready.
990 See the variable `Man-notify-method' for the different notification behaviors."
991 (let ((saved-frame (with-current-buffer man-buffer
992 Man-original-frame)))
993 (case Man-notify-method
994 (newframe
995 ;; Since we run asynchronously, perhaps while Emacs is waiting
996 ;; for input, we must not leave a different buffer current. We
997 ;; can't rely on the editor command loop to reselect the
998 ;; selected window's buffer.
999 (save-excursion
1000 (let ((frame (make-frame Man-frame-parameters)))
1001 (set-window-buffer (frame-selected-window frame) man-buffer)
1002 (set-window-dedicated-p (frame-selected-window frame) t)
1003 (or (display-multi-frame-p frame)
1004 (select-frame frame)))))
1005 (pushy
1006 (switch-to-buffer man-buffer))
1007 (bully
1008 (and (frame-live-p saved-frame)
1009 (select-frame saved-frame))
1010 (pop-to-buffer man-buffer)
1011 (delete-other-windows))
1012 (aggressive
1013 (and (frame-live-p saved-frame)
1014 (select-frame saved-frame))
1015 (pop-to-buffer man-buffer))
1016 (friendly
1017 (and (frame-live-p saved-frame)
1018 (select-frame saved-frame))
1019 (display-buffer man-buffer 'not-this-window))
1020 (polite
1021 (beep)
1022 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1023 (quiet
1024 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1025 (t ;; meek
1026 (message ""))
1029 (defun Man-softhyphen-to-minus ()
1030 ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
1031 ;; least, emit it even when not in a Latin-N locale.
1032 (unless (eq t (compare-strings "latin-" 0 nil
1033 current-language-environment 0 6 t))
1034 (goto-char (point-min))
1035 (let ((str "\255"))
1036 (if enable-multibyte-characters
1037 (setq str (string-as-multibyte str)))
1038 (while (search-forward str nil t) (replace-match "-")))))
1040 (defun Man-fontify-manpage ()
1041 "Convert overstriking and underlining to the correct fonts.
1042 Same for the ANSI bold and normal escape sequences."
1043 (interactive)
1044 (message "Please wait: formatting the %s man page..." Man-arguments)
1045 (goto-char (point-min))
1046 ;; Fontify ANSI escapes.
1047 (let ((faces nil)
1048 (buffer-undo-list t)
1049 (start (point)))
1050 ;; http://www.isthe.com/chongo/tech/comp/ansi_escapes.html
1051 ;; suggests many codes, but we only handle:
1052 ;; ESC [ 00 m reset to normal display
1053 ;; ESC [ 01 m bold
1054 ;; ESC [ 04 m underline
1055 ;; ESC [ 07 m reverse-video
1056 ;; ESC [ 22 m no-bold
1057 ;; ESC [ 24 m no-underline
1058 ;; ESC [ 27 m no-reverse-video
1059 (while (re-search-forward "\e\\[0?\\([1470]\\|2\\([247]\\)\\)m" nil t)
1060 (if faces (put-text-property start (match-beginning 0) 'face
1061 (if (cdr faces) faces (car faces))))
1062 (setq faces
1063 (cond
1064 ((match-beginning 2)
1065 (delq (case (char-after (match-beginning 2))
1066 (?2 Man-overstrike-face)
1067 (?4 Man-underline-face)
1068 (?7 Man-reverse-face))
1069 faces))
1070 ((eq (char-after (match-beginning 1)) ?0) nil)
1072 (cons (case (char-after (match-beginning 1))
1073 (?1 Man-overstrike-face)
1074 (?4 Man-underline-face)
1075 (?7 Man-reverse-face))
1076 faces))))
1077 (delete-region (match-beginning 0) (match-end 0))
1078 (setq start (point))))
1079 ;; Other highlighting.
1080 (let ((buffer-undo-list t))
1081 (if (< (buffer-size) (position-bytes (point-max)))
1082 ;; Multibyte characters exist.
1083 (progn
1084 (goto-char (point-min))
1085 (while (search-forward "__\b\b" nil t)
1086 (backward-delete-char 4)
1087 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1088 (goto-char (point-min))
1089 (while (search-forward "\b\b__" nil t)
1090 (backward-delete-char 4)
1091 (put-text-property (1- (point)) (point) 'face Man-underline-face))))
1092 (goto-char (point-min))
1093 (while (search-forward "_\b" nil t)
1094 (backward-delete-char 2)
1095 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1096 (goto-char (point-min))
1097 (while (search-forward "\b_" nil t)
1098 (backward-delete-char 2)
1099 (put-text-property (1- (point)) (point) 'face Man-underline-face))
1100 (goto-char (point-min))
1101 (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
1102 (replace-match "\\1")
1103 (put-text-property (1- (point)) (point) 'face Man-overstrike-face))
1104 (goto-char (point-min))
1105 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
1106 (replace-match "o")
1107 (put-text-property (1- (point)) (point) 'face 'bold))
1108 (goto-char (point-min))
1109 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
1110 (replace-match "+")
1111 (put-text-property (1- (point)) (point) 'face 'bold))
1112 ;; When the header is longer than the manpage name, groff tries to
1113 ;; condense it to a shorter line interspersed with ^H. Remove ^H with
1114 ;; their preceding chars (but don't put Man-overstrike-face). (Bug#5566)
1115 (goto-char (point-min))
1116 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1117 (goto-char (point-min))
1118 ;; Try to recognize common forms of cross references.
1119 (Man-highlight-references)
1120 (Man-softhyphen-to-minus)
1121 (goto-char (point-min))
1122 (while (re-search-forward Man-heading-regexp nil t)
1123 (put-text-property (match-beginning 0)
1124 (match-end 0)
1125 'face Man-overstrike-face)))
1126 (message "%s man page formatted" (Man-page-from-arguments Man-arguments)))
1128 (defun Man-highlight-references (&optional xref-man-type)
1129 "Highlight the references on mouse-over.
1130 References include items in the SEE ALSO section,
1131 header file (#include <foo.h>), and files in FILES.
1132 If optional argument XREF-MAN-TYPE is non-nil, it used as the
1133 button type for items in SEE ALSO section. If it is nil, the
1134 default type, `Man-xref-man-page' is used for the buttons."
1135 ;; `Man-highlight-references' is used from woman.el, too.
1136 ;; woman.el doesn't set `Man-arguments'.
1137 (unless Man-arguments
1138 (setq Man-arguments ""))
1139 (if (string-match "-k " Man-arguments)
1140 (progn
1141 (Man-highlight-references0 nil Man-reference-regexp 1
1142 'Man-default-man-entry
1143 (or xref-man-type 'Man-xref-man-page))
1144 (Man-highlight-references0 nil Man-apropos-regexp 1
1145 'Man-default-man-entry
1146 (or xref-man-type 'Man-xref-man-page)))
1147 (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
1148 'Man-default-man-entry
1149 (or xref-man-type 'Man-xref-man-page))
1150 (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
1151 'Man-xref-header-file)
1152 (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
1153 'Man-xref-normal-file)))
1155 (defun Man-highlight-references0 (start-section regexp button-pos target type)
1156 ;; Based on `Man-build-references-alist'
1157 (when (or (null start-section)
1158 (Man-find-section start-section))
1159 (let ((end (if start-section
1160 (progn
1161 (forward-line 1)
1162 (back-to-indentation)
1163 (save-excursion
1164 (Man-next-section 1)
1165 (point)))
1166 (goto-char (point-min))
1167 nil)))
1168 (while (re-search-forward regexp end t)
1169 ;; An overlay button is preferable because the underlying text
1170 ;; may have text property highlights (Bug#7881).
1171 (make-button
1172 (match-beginning button-pos)
1173 (match-end button-pos)
1174 'type type
1175 'Man-target-string (cond
1176 ((numberp target)
1177 (match-string target))
1178 ((functionp target)
1179 target)
1180 (t nil)))))))
1182 (defun Man-cleanup-manpage (&optional interactive)
1183 "Remove overstriking and underlining from the current buffer.
1184 Normally skip any jobs that should have been done by the sed script,
1185 but when called interactively, do those jobs even if the sed
1186 script would have done them."
1187 (interactive "p")
1188 (message "Please wait: cleaning up the %s man page..."
1189 Man-arguments)
1190 (if (or interactive (not Man-sed-script))
1191 (progn
1192 (goto-char (point-min))
1193 (while (search-forward "_\b" nil t) (backward-delete-char 2))
1194 (goto-char (point-min))
1195 (while (search-forward "\b_" nil t) (backward-delete-char 2))
1196 (goto-char (point-min))
1197 (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
1198 (replace-match "\\1"))
1199 (goto-char (point-min))
1200 (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
1201 (goto-char (point-min))
1202 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
1204 (goto-char (point-min))
1205 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
1206 ;; When the header is longer than the manpage name, groff tries to
1207 ;; condense it to a shorter line interspersed with ^H. Remove ^H with
1208 ;; their preceding chars (but don't put Man-overstrike-face). (Bug#5566)
1209 (goto-char (point-min))
1210 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1211 (Man-softhyphen-to-minus)
1212 (message "%s man page cleaned up" Man-arguments))
1214 (defun Man-bgproc-sentinel (process msg)
1215 "Manpage background process sentinel.
1216 When manpage command is run asynchronously, PROCESS is the process
1217 object for the manpage command; when manpage command is run
1218 synchronously, PROCESS is the name of the buffer where the manpage
1219 command is run. Second argument MSG is the exit message of the
1220 manpage command."
1221 (let ((Man-buffer (if (stringp process) (get-buffer process)
1222 (process-buffer process)))
1223 (delete-buff nil)
1224 (err-mess nil))
1226 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1227 (or (stringp process)
1228 (set-process-buffer process nil))
1230 (with-current-buffer Man-buffer
1231 (let ((case-fold-search nil))
1232 (goto-char (point-min))
1233 (cond ((or (looking-at "No \\(manual \\)*entry for")
1234 (looking-at "[^\n]*: nothing appropriate$"))
1235 (setq err-mess (buffer-substring (point)
1236 (progn
1237 (end-of-line) (point)))
1238 delete-buff t))
1240 ;; "-k foo", successful exit, but no output (from man-db)
1241 ;; ENHANCE-ME: share the check for -k with
1242 ;; `Man-highlight-references'. The \\s- bits here are
1243 ;; meant to allow for multiple options with -k among them.
1244 ((and (string-match "\\(\\`\\|\\s-\\)-k\\s-" Man-arguments)
1245 (eq (process-status process) 'exit)
1246 (= (process-exit-status process) 0)
1247 (= (point-min) (point-max)))
1248 (setq err-mess (format "%s: no matches" Man-arguments)
1249 delete-buff t))
1251 ((or (stringp process)
1252 (not (and (eq (process-status process) 'exit)
1253 (= (process-exit-status process) 0))))
1254 (or (zerop (length msg))
1255 (progn
1256 (setq err-mess
1257 (concat (buffer-name Man-buffer)
1258 ": process "
1259 (let ((eos (1- (length msg))))
1260 (if (= (aref msg eos) ?\n)
1261 (substring msg 0 eos) msg))))
1262 (goto-char (point-max))
1263 (insert (format "\nprocess %s" msg))))
1265 (if delete-buff
1266 (kill-buffer Man-buffer)
1267 (if Man-fontify-manpage-flag
1268 (Man-fontify-manpage)
1269 (Man-cleanup-manpage))
1271 (run-hooks 'Man-cooked-hook)
1272 (Man-mode)
1274 (if (not Man-page-list)
1275 (let ((args Man-arguments))
1276 (kill-buffer (current-buffer))
1277 (error "Can't find the %s manpage"
1278 (Man-page-from-arguments args)))
1279 (set-buffer-modified-p nil))))
1280 ;; Restore case-fold-search before calling
1281 ;; Man-notify-when-ready because it may switch buffers.
1283 (if (not delete-buff)
1284 (Man-notify-when-ready Man-buffer))
1286 (if err-mess
1287 (error "%s" err-mess))
1288 ))))
1290 (defun Man-page-from-arguments (args)
1291 ;; Skip arguments and only print the page name.
1292 (mapconcat
1293 'identity
1294 (delete nil
1295 (mapcar
1296 (lambda (elem)
1297 (and (not (string-match "^-" elem))
1298 elem))
1299 (split-string args " ")))
1300 " "))
1303 ;; ======================================================================
1304 ;; set up manual mode in buffer and build alists
1306 (defvar bookmark-make-record-function)
1308 (put 'Man-mode 'mode-class 'special)
1310 (defun Man-mode ()
1311 "A mode for browsing Un*x manual pages.
1313 The following man commands are available in the buffer. Try
1314 \"\\[describe-key] <key> RET\" for more information:
1316 \\[man] Prompt to retrieve a new manpage.
1317 \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
1318 \\[Man-next-manpage] Jump to next manpage in circular list.
1319 \\[Man-previous-manpage] Jump to previous manpage in circular list.
1320 \\[Man-next-section] Jump to next manpage section.
1321 \\[Man-previous-section] Jump to previous manpage section.
1322 \\[Man-goto-section] Go to a manpage section.
1323 \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
1324 \\[Man-quit] Deletes the manpage window, bury its buffer.
1325 \\[Man-kill] Deletes the manpage window, kill its buffer.
1326 \\[describe-mode] Prints this help text.
1328 The following variables may be of some use. Try
1329 \"\\[describe-variable] <variable-name> RET\" for more information:
1331 `Man-notify-method' What happens when manpage formatting is done.
1332 `Man-downcase-section-letters-flag' Force section letters to lower case.
1333 `Man-circular-pages-flag' Treat multiple manpage list as circular.
1334 `Man-section-translations-alist' List of section numbers and their Un*x equiv.
1335 `Man-filter-list' Background manpage filter command.
1336 `Man-mode-map' Keymap bindings for Man mode buffers.
1337 `Man-mode-hook' Normal hook run on entry to Man mode.
1338 `Man-section-regexp' Regexp describing manpage section letters.
1339 `Man-heading-regexp' Regexp describing section headers.
1340 `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
1341 `Man-first-heading-regexp' Regexp for first heading on a manpage.
1342 `Man-reference-regexp' Regexp matching a references in SEE ALSO.
1343 `Man-switches' Background `man' command switches.
1345 The following key bindings are currently in effect in the buffer:
1346 \\{Man-mode-map}"
1347 (interactive)
1348 (kill-all-local-variables)
1349 (setq major-mode 'Man-mode
1350 mode-name "Man"
1351 buffer-auto-save-file-name nil
1352 mode-line-buffer-identification
1353 (list (default-value 'mode-line-buffer-identification)
1354 " {" 'Man-page-mode-string "}")
1355 truncate-lines t
1356 buffer-read-only t)
1357 (buffer-disable-undo)
1358 (auto-fill-mode -1)
1359 (use-local-map Man-mode-map)
1360 (set-syntax-table man-mode-syntax-table)
1361 (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
1362 (set (make-local-variable 'outline-regexp) Man-heading-regexp)
1363 (set (make-local-variable 'outline-level) (lambda () 1))
1364 (set (make-local-variable 'bookmark-make-record-function)
1365 'Man-bookmark-make-record)
1366 (Man-build-page-list)
1367 (Man-strip-page-headers)
1368 (Man-unindent)
1369 (Man-goto-page 1 t)
1370 (run-mode-hooks 'Man-mode-hook))
1372 (defsubst Man-build-section-alist ()
1373 "Build the association list of manpage sections."
1374 (setq Man-sections-alist nil)
1375 (goto-char (point-min))
1376 (let ((case-fold-search nil))
1377 (while (re-search-forward Man-heading-regexp (point-max) t)
1378 (aput 'Man-sections-alist (match-string 1))
1379 (forward-line 1))))
1381 (defsubst Man-build-references-alist ()
1382 "Build the association list of references (in the SEE ALSO section)."
1383 (setq Man-refpages-alist nil)
1384 (save-excursion
1385 (if (Man-find-section Man-see-also-regexp)
1386 (let ((start (progn (forward-line 1) (point)))
1387 (end (progn
1388 (Man-next-section 1)
1389 (point)))
1390 hyphenated
1391 (runningpoint -1))
1392 (save-restriction
1393 (narrow-to-region start end)
1394 (goto-char (point-min))
1395 (back-to-indentation)
1396 (while (and (not (eobp)) (/= (point) runningpoint))
1397 (setq runningpoint (point))
1398 (if (re-search-forward Man-hyphenated-reference-regexp end t)
1399 (let* ((word (match-string 0))
1400 (len (1- (length word))))
1401 (if hyphenated
1402 (setq word (concat hyphenated word)
1403 hyphenated nil
1404 ;; Update len, in case a reference spans
1405 ;; more than two lines (paranoia).
1406 len (1- (length word))))
1407 (if (memq (aref word len) '(?- ?­))
1408 (setq hyphenated (substring word 0 len)))
1409 (if (string-match Man-reference-regexp word)
1410 (aput 'Man-refpages-alist word))))
1411 (skip-chars-forward " \t\n,"))))))
1412 (setq Man-refpages-alist (nreverse Man-refpages-alist)))
1414 (defun Man-build-page-list ()
1415 "Build the list of separate manpages in the buffer."
1416 (setq Man-page-list nil)
1417 (let ((page-start (point-min))
1418 (page-end (point-max))
1419 (header ""))
1420 (goto-char page-start)
1421 ;; (switch-to-buffer (current-buffer))(debug)
1422 (while (not (eobp))
1423 (setq header
1424 (if (looking-at Man-page-header-regexp)
1425 (match-string 1)
1426 nil))
1427 ;; Go past both the current and the next Man-first-heading-regexp
1428 (if (re-search-forward Man-first-heading-regexp nil 'move 2)
1429 (let ((p (progn (beginning-of-line) (point))))
1430 ;; We assume that the page header is delimited by blank
1431 ;; lines and that it contains at most one blank line. So
1432 ;; if we back by three blank lines we will be sure to be
1433 ;; before the page header but not before the possible
1434 ;; previous page header.
1435 (search-backward "\n\n" nil t 3)
1436 (if (re-search-forward Man-page-header-regexp p 'move)
1437 (beginning-of-line))))
1438 (setq page-end (point))
1439 (setq Man-page-list (append Man-page-list
1440 (list (list (copy-marker page-start)
1441 (copy-marker page-end)
1442 header))))
1443 (setq page-start page-end)
1446 (defun Man-strip-page-headers ()
1447 "Strip all the page headers but the first from the manpage."
1448 (let ((inhibit-read-only t)
1449 (case-fold-search nil)
1450 (header ""))
1451 (dolist (page Man-page-list)
1452 (and (nth 2 page)
1453 (goto-char (car page))
1454 (re-search-forward Man-first-heading-regexp nil t)
1455 (setq header (buffer-substring (car page) (match-beginning 0)))
1456 ;; Since the awk script collapses all successive blank
1457 ;; lines into one, and since we don't want to get rid of
1458 ;; the fast awk script, one must choose between adding
1459 ;; spare blank lines between pages when there were none and
1460 ;; deleting blank lines at page boundaries when there were
1461 ;; some. We choose the first, so we comment the following
1462 ;; line.
1463 ;; (setq header (concat "\n" header)))
1464 (while (search-forward header (nth 1 page) t)
1465 (replace-match ""))))))
1467 (defun Man-unindent ()
1468 "Delete the leading spaces that indent the manpage."
1469 (let ((inhibit-read-only t)
1470 (case-fold-search nil))
1471 (dolist (page Man-page-list)
1472 (let ((indent "")
1473 (nindent 0))
1474 (narrow-to-region (car page) (car (cdr page)))
1475 (if Man-uses-untabify-flag
1476 (untabify (point-min) (point-max)))
1477 (if (catch 'unindent
1478 (goto-char (point-min))
1479 (if (not (re-search-forward Man-first-heading-regexp nil t))
1480 (throw 'unindent nil))
1481 (beginning-of-line)
1482 (setq indent (buffer-substring (point)
1483 (progn
1484 (skip-chars-forward " ")
1485 (point))))
1486 (setq nindent (length indent))
1487 (if (zerop nindent)
1488 (throw 'unindent nil))
1489 (setq indent (concat indent "\\|$"))
1490 (goto-char (point-min))
1491 (while (not (eobp))
1492 (if (looking-at indent)
1493 (forward-line 1)
1494 (throw 'unindent nil)))
1495 (goto-char (point-min)))
1496 (while (not (eobp))
1497 (or (eolp)
1498 (delete-char nindent))
1499 (forward-line 1)))
1500 ))))
1503 ;; ======================================================================
1504 ;; Man mode commands
1506 (defun Man-next-section (n)
1507 "Move point to Nth next section (default 1)."
1508 (interactive "p")
1509 (let ((case-fold-search nil)
1510 (start (point)))
1511 (if (looking-at Man-heading-regexp)
1512 (forward-line 1))
1513 (if (re-search-forward Man-heading-regexp (point-max) t n)
1514 (beginning-of-line)
1515 (goto-char (point-max))
1516 ;; The last line doesn't belong to any section.
1517 (forward-line -1))
1518 ;; But don't move back from the starting point (can happen if `start'
1519 ;; is somewhere on the last line).
1520 (if (< (point) start) (goto-char start))))
1522 (defun Man-previous-section (n)
1523 "Move point to Nth previous section (default 1)."
1524 (interactive "p")
1525 (let ((case-fold-search nil))
1526 (if (looking-at Man-heading-regexp)
1527 (forward-line -1))
1528 (if (re-search-backward Man-heading-regexp (point-min) t n)
1529 (beginning-of-line)
1530 (goto-char (point-min)))))
1532 (defun Man-find-section (section)
1533 "Move point to SECTION if it exists, otherwise don't move point.
1534 Returns t if section is found, nil otherwise."
1535 (let ((curpos (point))
1536 (case-fold-search nil))
1537 (goto-char (point-min))
1538 (if (re-search-forward (concat "^" section) (point-max) t)
1539 (progn (beginning-of-line) t)
1540 (goto-char curpos)
1541 nil)
1544 (defun Man-goto-section ()
1545 "Query for section to move point to."
1546 (interactive)
1547 (aput 'Man-sections-alist
1548 (let* ((default (aheadsym Man-sections-alist))
1549 (completion-ignore-case t)
1550 chosen
1551 (prompt (concat "Go to section (default " default "): ")))
1552 (setq chosen (completing-read prompt Man-sections-alist))
1553 (if (or (not chosen)
1554 (string= chosen ""))
1555 default
1556 chosen)))
1557 (unless (Man-find-section (aheadsym Man-sections-alist))
1558 (error "Section not found")))
1561 (defun Man-goto-see-also-section ()
1562 "Move point to the \"SEE ALSO\" section.
1563 Actually the section moved to is described by `Man-see-also-regexp'."
1564 (interactive)
1565 (if (not (Man-find-section Man-see-also-regexp))
1566 (error "%s" (concat "No " Man-see-also-regexp
1567 " section found in the current manpage"))))
1569 (defun Man-possibly-hyphenated-word ()
1570 "Return a possibly hyphenated word at point.
1571 If the word starts at the first non-whitespace column, and the
1572 previous line ends with a hyphen, return the last word on the previous
1573 line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
1574 as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
1575 \"tcgetp-\" instead of \"grp\"."
1576 (save-excursion
1577 (skip-syntax-backward "w()")
1578 (skip-chars-forward " \t")
1579 (let ((beg (point))
1580 (word (current-word)))
1581 (when (eq beg (save-excursion
1582 (back-to-indentation)
1583 (point)))
1584 (end-of-line 0)
1585 (if (eq (char-before) ?-)
1586 (setq word (current-word))))
1587 word)))
1589 (defun Man-follow-manual-reference (reference)
1590 "Get one of the manpages referred to in the \"SEE ALSO\" section.
1591 Specify which REFERENCE to use; default is based on word at point."
1592 (interactive
1593 (if (not Man-refpages-alist)
1594 (error "There are no references in the current man page")
1595 (list
1596 (let* ((default (or
1597 (car (all-completions
1598 (let ((word
1599 (or (Man-possibly-hyphenated-word)
1600 "")))
1601 ;; strip a trailing '-':
1602 (if (string-match "-$" word)
1603 (substring word 0
1604 (match-beginning 0))
1605 word))
1606 Man-refpages-alist))
1607 (aheadsym Man-refpages-alist)))
1608 (defaults
1609 (mapcar 'substring-no-properties
1610 (delete-dups
1611 (delq nil (cons default
1612 (mapcar 'car Man-refpages-alist))))))
1613 chosen
1614 (prompt (concat "Refer to (default " default "): ")))
1615 (setq chosen (completing-read prompt Man-refpages-alist
1616 nil nil nil nil defaults))
1617 (if (or (not chosen)
1618 (string= chosen ""))
1619 default
1620 chosen)))))
1621 (if (not Man-refpages-alist)
1622 (error "Can't find any references in the current manpage")
1623 (aput 'Man-refpages-alist reference)
1624 (Man-getpage-in-background
1625 (Man-translate-references (aheadsym Man-refpages-alist)))))
1627 (defun Man-kill ()
1628 "Kill the buffer containing the manpage."
1629 (interactive)
1630 (quit-window t))
1632 (defun Man-quit ()
1633 "Bury the buffer containing the manpage."
1634 (interactive)
1635 (quit-window))
1637 (defun Man-goto-page (page &optional noerror)
1638 "Go to the manual page on page PAGE."
1639 (interactive
1640 (if (not Man-page-list)
1641 (error "Not a man page buffer")
1642 (if (= (length Man-page-list) 1)
1643 (error "You're looking at the only manpage in the buffer")
1644 (list (read-minibuffer (format "Go to manpage [1-%d]: "
1645 (length Man-page-list)))))))
1646 (if (and (not Man-page-list) (not noerror))
1647 (error "Not a man page buffer"))
1648 (when Man-page-list
1649 (if (or (< page 1)
1650 (> page (length Man-page-list)))
1651 (error "No manpage %d found" page))
1652 (let* ((page-range (nth (1- page) Man-page-list))
1653 (page-start (car page-range))
1654 (page-end (car (cdr page-range))))
1655 (setq Man-current-page page
1656 Man-page-mode-string (Man-make-page-mode-string))
1657 (widen)
1658 (goto-char page-start)
1659 (narrow-to-region page-start page-end)
1660 (Man-build-section-alist)
1661 (Man-build-references-alist)
1662 (goto-char (point-min)))))
1665 (defun Man-next-manpage ()
1666 "Find the next manpage entry in the buffer."
1667 (interactive)
1668 (if (= (length Man-page-list) 1)
1669 (error "This is the only manpage in the buffer"))
1670 (if (< Man-current-page (length Man-page-list))
1671 (Man-goto-page (1+ Man-current-page))
1672 (if Man-circular-pages-flag
1673 (Man-goto-page 1)
1674 (error "You're looking at the last manpage in the buffer"))))
1676 (defun Man-previous-manpage ()
1677 "Find the previous manpage entry in the buffer."
1678 (interactive)
1679 (if (= (length Man-page-list) 1)
1680 (error "This is the only manpage in the buffer"))
1681 (if (> Man-current-page 1)
1682 (Man-goto-page (1- Man-current-page))
1683 (if Man-circular-pages-flag
1684 (Man-goto-page (length Man-page-list))
1685 (error "You're looking at the first manpage in the buffer"))))
1687 ;; Header file support
1688 (defun Man-view-header-file (file)
1689 "View a header file specified by FILE from `Man-header-file-path'."
1690 (let ((path Man-header-file-path)
1691 complete-path)
1692 (while path
1693 (setq complete-path (expand-file-name file (car path))
1694 path (cdr path))
1695 (if (file-readable-p complete-path)
1696 (progn (view-file complete-path)
1697 (setq path nil))
1698 (setq complete-path nil)))
1699 complete-path))
1701 ;;; Bookmark Man Support
1702 (declare-function bookmark-make-record-default
1703 "bookmark" (&optional no-file no-context posn))
1704 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1705 (declare-function bookmark-default-handler "bookmark" (bmk))
1706 (declare-function bookmark-get-bookmark-record "bookmark" (bmk))
1708 (defun Man-default-bookmark-title ()
1709 "Default bookmark name for Man or WoMan pages.
1710 Uses `Man-name-local-regexp'."
1711 (save-excursion
1712 (goto-char (point-min))
1713 (when (re-search-forward Man-name-local-regexp nil t)
1714 (skip-chars-forward "\n\t ")
1715 (buffer-substring-no-properties (point) (line-end-position)))))
1717 (defun Man-bookmark-make-record ()
1718 "Make a bookmark entry for a Man buffer."
1719 `(,(Man-default-bookmark-title)
1720 ,@(bookmark-make-record-default 'no-file)
1721 (location . ,(concat "man " Man-arguments))
1722 (man-args . ,Man-arguments)
1723 (handler . Man-bookmark-jump)))
1725 ;;;###autoload
1726 (defun Man-bookmark-jump (bookmark)
1727 "Default bookmark handler for Man buffers."
1728 (let* ((man-args (bookmark-prop-get bookmark 'man-args))
1729 ;; Let bookmark.el do the window handling.
1730 ;; This let-binding needs to be active during the call to both
1731 ;; Man-getpage-in-background and accept-process-output.
1732 (Man-notify-method 'meek)
1733 (buf (Man-getpage-in-background man-args))
1734 (proc (get-buffer-process buf)))
1735 (while (and proc (eq (process-status proc) 'run))
1736 (accept-process-output proc))
1737 (bookmark-default-handler
1738 `("" (buffer . ,buf) . ,(bookmark-get-bookmark-record bookmark)))))
1741 ;; Init the man package variables, if not already done.
1742 (Man-init-defvars)
1744 (add-to-list 'debug-ignored-errors "^No manpage [0-9]* found$")
1745 (add-to-list 'debug-ignored-errors "^Can't find the .* manpage$")
1747 (provide 'man)
1749 ;;; man.el ends here