make the minibuffer mutex recursive.
[emacs.git] / lisp / man.el
blob8eb5f73e2450c9d7d960fee8469f47b807f18e85
1 ;;; man.el --- browse UNIX manual pages -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 1993, 1994, 1996, 1997, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006, 2007, 2008, 2009, 2010 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 (defcustom Man-header-file-path
219 '("/usr/include" "/usr/local/include")
220 "C Header file search path used in Man."
221 :type '(repeat string)
222 :group 'man)
224 (defvar manual-program "man"
225 "The name of the program that produces man pages.")
227 (defvar Man-untabify-command "pr"
228 "Command used for untabifying.")
230 (defvar Man-untabify-command-args (list "-t" "-e")
231 "List of arguments to be passed to `Man-untabify-command' (which see).")
233 (defvar Man-sed-command "sed"
234 "Command used for processing sed scripts.")
236 (defvar Man-awk-command "awk"
237 "Command used for processing awk scripts.")
239 (defvar Man-mode-hook nil
240 "Hook run when Man mode is enabled.")
242 (defvar Man-cooked-hook nil
243 "Hook run after removing backspaces but before `Man-mode' processing.")
245 (defvar Man-name-regexp "[-a-zA-Z0-9_­+][-a-zA-Z0-9_.:­+]*"
246 "Regular expression describing the name of a manpage (without section).")
248 (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
249 "Regular expression describing a manpage section within parentheses.")
251 (defvar Man-page-header-regexp
252 (if (and (string-match "-solaris2\\." system-configuration)
253 (not (string-match "-solaris2\\.[123435]$" system-configuration)))
254 (concat "^[-A-Za-z0-9_].*[ \t]\\(" Man-name-regexp
255 "(\\(" Man-section-regexp "\\))\\)$")
256 (concat "^[ \t]*\\(" Man-name-regexp
257 "(\\(" Man-section-regexp "\\))\\).*\\1"))
258 "Regular expression describing the heading of a page.")
260 (defvar Man-heading-regexp "^\\([A-Z][A-Z0-9 /-]+\\)$"
261 "Regular expression describing a manpage heading entry.")
263 (defvar Man-see-also-regexp "SEE ALSO"
264 "Regular expression for SEE ALSO heading (or your equivalent).
265 This regexp should not start with a `^' character.")
267 ;; This used to have leading space [ \t]*, but was removed because it
268 ;; causes false page splits on an occasional NAME with leading space
269 ;; inside a manpage. And `Man-heading-regexp' doesn't have [ \t]* anyway.
270 (defvar Man-first-heading-regexp "^NAME$\\|^[ \t]*No manual entry fo.*$"
271 "Regular expression describing first heading on a manpage.
272 This regular expression should start with a `^' character.")
274 (defvar Man-reference-regexp
275 (concat "\\(" Man-name-regexp "\\)[ \t]*(\\(" Man-section-regexp "\\))")
276 "Regular expression describing a reference to another manpage.")
278 (defvar Man-apropos-regexp
279 (concat "\\\[\\(" Man-name-regexp "\\)\\\][ \t]*(\\(" Man-section-regexp "\\))")
280 "Regular expression describing a reference to manpages in \"man -k output\".")
282 (defvar Man-synopsis-regexp "SYNOPSIS"
283 "Regular expression for SYNOPSIS heading (or your equivalent).
284 This regexp should not start with a `^' character.")
286 (defvar Man-files-regexp "FILES\\>"
287 ;; Add \> so as not to match mount(8)'s FILESYSTEM INDEPENDENT MOUNT OPTIONS.
288 "Regular expression for FILES heading (or your equivalent).
289 This regexp should not start with a `^' character.")
291 (defvar Man-include-regexp "#[ \t]*include[ \t]*"
292 "Regular expression describing the #include (directive of cpp).")
294 (defvar Man-file-name-regexp "[^<>\", \t\n]+"
295 "Regular expression describing <> in #include line (directive of cpp).")
297 (defvar Man-normal-file-prefix-regexp "[/~$]"
298 "Regular expression describing a file path appeared in FILES section.")
300 (defvar Man-header-regexp
301 (concat "\\(" Man-include-regexp "\\)"
302 "[<\"]"
303 "\\(" Man-file-name-regexp "\\)"
304 "[>\"]")
305 "Regular expression describing references to header files.")
307 (defvar Man-normal-file-regexp
308 (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
309 "Regular expression describing references to normal files.")
311 ;; This includes the section as an optional part to catch hyphenated
312 ;; refernces to manpages.
313 (defvar Man-hyphenated-reference-regexp
314 (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
315 "Regular expression describing a reference in the SEE ALSO section.")
317 (defvar Man-switches ""
318 "Switches passed to the man command, as a single string.
320 If you want to be able to see all the manpages for a subject you type,
321 make -a one of the switches, if your `man' program supports it.")
323 (defvar Man-specified-section-option
324 (if (string-match "-solaris[0-9.]*$" system-configuration)
325 "-s"
327 "Option that indicates a specified a manual section name.")
329 (defvar Man-support-local-filenames 'auto-detect
330 "Internal cache for the value of the function `Man-support-local-filenames'.
331 `auto-detect' means the value is not yet determined.
332 Otherwise, the value is whatever the function
333 `Man-support-local-filenames' should return.")
335 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336 ;; end user variables
338 ;; other variables and keymap initializations
339 (defvar Man-original-frame)
340 (make-variable-buffer-local 'Man-original-frame)
341 (defvar Man-arguments)
342 (make-variable-buffer-local 'Man-arguments)
343 (put 'Man-arguments 'permanent-local t)
345 (defvar Man-sections-alist nil)
346 (make-variable-buffer-local 'Man-sections-alist)
347 (defvar Man-refpages-alist nil)
348 (make-variable-buffer-local 'Man-refpages-alist)
349 (defvar Man-page-list nil)
350 (make-variable-buffer-local 'Man-page-list)
351 (defvar Man-current-page 0)
352 (make-variable-buffer-local 'Man-current-page)
353 (defvar Man-page-mode-string "1 of 1")
354 (make-variable-buffer-local 'Man-page-mode-string)
356 (defconst Man-sysv-sed-script "\
357 /\b/ { s/_\b//g
358 s/\b_//g
359 s/o\b+/o/g
360 s/+\bo/o/g
361 :ovstrk
362 s/\\(.\\)\b\\1/\\1/g
363 t ovstrk
365 /\e\\[[0-9][0-9]*m/ s///g"
366 "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
368 (defconst Man-berkeley-sed-script "\
369 /\b/ { s/_\b//g\\
370 s/\b_//g\\
371 s/o\b+/o/g\\
372 s/+\bo/o/g\\
373 :ovstrk\\
374 s/\\(.\\)\b\\1/\\1/g\\
375 t ovstrk\\
377 /\e\\[[0-9][0-9]*m/ s///g"
378 "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
380 (defvar Man-topic-history nil "Topic read history.")
382 (defvar man-mode-syntax-table
383 (let ((table (copy-syntax-table (standard-syntax-table))))
384 (modify-syntax-entry ?. "w" table)
385 (modify-syntax-entry ?_ "w" table)
386 (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
387 table)
388 "Syntax table used in Man mode buffers.")
390 (defvar Man-mode-map
391 (let ((map (make-sparse-keymap)))
392 (suppress-keymap map)
393 (set-keymap-parent map button-buffer-map)
395 (define-key map " " 'scroll-up)
396 (define-key map "\177" 'scroll-down)
397 (define-key map "n" 'Man-next-section)
398 (define-key map "p" 'Man-previous-section)
399 (define-key map "\en" 'Man-next-manpage)
400 (define-key map "\ep" 'Man-previous-manpage)
401 (define-key map ">" 'end-of-buffer)
402 (define-key map "<" 'beginning-of-buffer)
403 (define-key map "." 'beginning-of-buffer)
404 (define-key map "r" 'Man-follow-manual-reference)
405 (define-key map "g" 'Man-goto-section)
406 (define-key map "s" 'Man-goto-see-also-section)
407 (define-key map "k" 'Man-kill)
408 (define-key map "q" 'Man-quit)
409 (define-key map "m" 'man)
410 ;; Not all the man references get buttons currently. The text in the
411 ;; manual page can contain references to other man pages
412 (define-key map "\r" 'man-follow)
413 (define-key map "?" 'describe-mode)
414 map)
415 "Keymap for Man mode.")
417 ;; buttons
418 (define-button-type 'Man-abstract-xref-man-page
419 'follow-link t
420 'help-echo "mouse-2, RET: display this man page"
421 'func nil
422 'action #'Man-xref-button-action)
424 (defun Man-xref-button-action (button)
425 (let ((target (button-get button 'Man-target-string)))
426 (funcall
427 (button-get button 'func)
428 (cond ((null target)
429 (button-label button))
430 ((functionp target)
431 (funcall target (button-start button)))
432 (t target)))))
434 (define-button-type 'Man-xref-man-page
435 :supertype 'Man-abstract-xref-man-page
436 'func 'man-follow)
439 (define-button-type 'Man-xref-header-file
440 'action (lambda (button)
441 (let ((w (button-get button 'Man-target-string)))
442 (unless (Man-view-header-file w)
443 (error "Cannot find header file: %s" w))))
444 'follow-link t
445 'help-echo "mouse-2: display this header file")
447 (define-button-type 'Man-xref-normal-file
448 'action (lambda (button)
449 (let ((f (substitute-in-file-name
450 (button-get button 'Man-target-string))))
451 (if (file-exists-p f)
452 (if (file-readable-p f)
453 (view-file f)
454 (error "Cannot read a file: %s" f))
455 (error "Cannot find a file: %s" f))))
456 'follow-link t
457 'help-echo "mouse-2: display this file")
460 ;; ======================================================================
461 ;; utilities
463 (defun Man-init-defvars ()
464 "Used for initializing variables based on display's color support.
465 This is necessary if one wants to dump man.el with Emacs."
467 ;; Avoid possible error in call-process by using a directory that must exist.
468 (let ((default-directory "/"))
469 (setq Man-sed-script
470 (cond
471 (Man-fontify-manpage-flag
472 nil)
473 ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
474 Man-sysv-sed-script)
475 ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
476 Man-berkeley-sed-script)
478 nil))))
480 (setq Man-filter-list
481 ;; Avoid trailing nil which confuses customize.
482 (apply 'list
483 (cons
484 Man-sed-command
485 (if (eq system-type 'windows-nt)
486 ;; Windows needs ".." quoting, not '..'.
487 (list
488 "-e \"/Reformatting page. Wait/d\""
489 "-e \"/Reformatting entry. Wait/d\""
490 "-e \"/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d\""
491 "-e \"/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d\""
492 "-e \"/^Printed[ \t][0-9].*[0-9]$/d\""
493 "-e \"/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d\""
494 "-e \"/^[A-Za-z].*Last[ \t]change:/d\""
495 "-e \"/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d\""
496 "-e \"/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d\"")
497 (list
498 (if Man-sed-script
499 (concat "-e '" Man-sed-script "'")
501 "-e '/^[\001-\032][\001-\032]*$/d'"
502 "-e '/\e[789]/s///g'"
503 "-e '/Reformatting page. Wait/d'"
504 "-e '/Reformatting entry. Wait/d'"
505 "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
506 "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
507 "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
508 "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
509 "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
510 "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
511 "-e '/^[A-Za-z].*Last[ \t]change:/d'"
512 "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
513 "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
514 "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
516 ;; Windows doesn't support multi-line commands, so don't
517 ;; invoke Awk there.
518 (unless (eq system-type 'windows-nt)
519 (cons
520 Man-awk-command
521 (list
522 "'\n"
523 "BEGIN { blankline=0; anonblank=0; }\n"
524 "/^$/ { if (anonblank==0) next; }\n"
525 "{ anonblank=1; }\n"
526 "/^$/ { blankline++; next; }\n"
527 "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
530 (if (not Man-uses-untabify-flag)
531 ;; The outer list will be stripped off by apply.
532 (list (cons
533 Man-untabify-command
534 Man-untabify-command-args))
538 (defsubst Man-make-page-mode-string ()
539 "Formats part of the mode line for Man mode."
540 (format "%s page %d of %d"
541 (or (nth 2 (nth (1- Man-current-page) Man-page-list))
543 Man-current-page
544 (length Man-page-list)))
546 (defsubst Man-build-man-command ()
547 "Builds the entire background manpage and cleaning command."
548 (let ((command (concat manual-program " " Man-switches
549 (cond
550 ;; Already has %s
551 ((string-match "%s" manual-program) "")
552 ;; Stock MS-DOS shells cannot redirect stderr;
553 ;; `call-process' below sends it to /dev/null,
554 ;; so we don't need `2>' even with DOS shells
555 ;; which do support stderr redirection.
556 ((not (fboundp 'start-process)) " %s")
557 ((concat " %s 2>" null-device)))))
558 (flist Man-filter-list))
559 (while (and flist (car flist))
560 (let ((pcom (car (car flist)))
561 (pargs (cdr (car flist))))
562 (setq command
563 (concat command " | " pcom " "
564 (mapconcat (lambda (phrase)
565 (if (not (stringp phrase))
566 (error "Malformed Man-filter-list"))
567 phrase)
568 pargs " ")))
569 (setq flist (cdr flist))))
570 command))
573 (defun Man-translate-cleanup (string)
574 "Strip leading, trailing and middle spaces."
575 (when (stringp string)
576 ;; Strip leading and trailing
577 (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
578 (setq string (match-string 1 string)))
579 ;; middle spaces
580 (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
581 (setq string (replace-regexp-in-string " +" " " string))
582 string))
584 (defun Man-translate-references (ref)
585 "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
586 Leave it as is if already in that style. Possibly downcase and
587 translate the section (see the `Man-downcase-section-letters-flag'
588 and the `Man-section-translations-alist' variables)."
589 (let ((name "")
590 (section "")
591 (slist Man-section-translations-alist))
592 (setq ref (Man-translate-cleanup ref))
593 (cond
594 ;; "chmod(2V)" case ?
595 ((string-match (concat "^" Man-reference-regexp "$") ref)
596 (setq name (match-string 1 ref)
597 section (match-string 2 ref)))
598 ;; "2v chmod" case ?
599 ((string-match (concat "^\\(" Man-section-regexp
600 "\\) +\\(" Man-name-regexp "\\)$") ref)
601 (setq name (match-string 2 ref)
602 section (match-string 1 ref))))
603 (if (string= name "")
604 ref ; Return the reference as is
605 (if Man-downcase-section-letters-flag
606 (setq section (downcase section)))
607 (while slist
608 (let ((s1 (car (car slist)))
609 (s2 (cdr (car slist))))
610 (setq slist (cdr slist))
611 (if Man-downcase-section-letters-flag
612 (setq s1 (downcase s1)))
613 (if (not (string= s1 section)) nil
614 (setq section (if Man-downcase-section-letters-flag
615 (downcase s2)
617 slist nil))))
618 (concat Man-specified-section-option section " " name))))
620 (defun Man-support-local-filenames ()
621 "Check the availability of `-l' option of the man command.
622 This option allows `man' to interpret command line arguments
623 as local filenames.
624 Return the value of the variable `Man-support-local-filenames'
625 if it was set to nil or t before the call of this function.
626 If t, the man command supports `-l' option. If nil, it doesn't.
627 Otherwise, if the value of `Man-support-local-filenames'
628 is neither t nor nil, then determine a new value, set it
629 to the variable `Man-support-local-filenames' and return
630 a new value."
631 (if (or (not Man-support-local-filenames)
632 (eq Man-support-local-filenames t))
633 Man-support-local-filenames
634 (setq Man-support-local-filenames
635 (with-temp-buffer
636 (and (equal (condition-case nil
637 (let ((default-directory
638 ;; Assure that `default-directory' exists
639 ;; and is readable.
640 (if (and (file-directory-p default-directory)
641 (file-readable-p default-directory))
642 default-directory
643 (expand-file-name "~/"))))
644 (call-process manual-program nil t nil "--help"))
645 (error nil))
647 (progn
648 (goto-char (point-min))
649 (search-forward "--local-file" nil t))
650 t)))))
653 ;; ======================================================================
654 ;; default man entry: get word near point
656 (defun Man-default-man-entry (&optional pos)
657 "Guess default manual entry based on the text near position POS.
658 POS defaults to `point'."
659 (let (word start column distance)
660 (save-excursion
661 (when pos (goto-char pos))
662 (setq pos (point))
663 ;; The default title is the nearest entry-like object before or
664 ;; after POS.
665 (if (and (skip-chars-backward " \ta-zA-Z0-9+")
666 (not (zerop (skip-chars-backward "(")))
667 ;; Try to handle the special case where POS is on a
668 ;; section number.
669 (looking-at
670 (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
671 ;; We skipped a valid section number backwards, look at
672 ;; preceding text.
673 (or (and (skip-chars-backward ",; \t")
674 (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
675 ;; Not a valid entry, move POS after closing paren.
676 (not (setq pos (match-end 0)))))
677 ;; We have a candidate, make `start' record its starting
678 ;; position.
679 (setq start (point))
680 ;; Otherwise look at char before POS.
681 (goto-char pos)
682 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
683 ;; Our candidate is just before or around POS.
684 (setq start (point))
685 ;; Otherwise record the current column and look backwards.
686 (setq column (current-column))
687 (skip-chars-backward ",; \t")
688 ;; Record the distance travelled.
689 (setq distance (- column (current-column)))
690 (when (looking-back
691 (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)"))
692 ;; Skip section number backwards.
693 (goto-char (match-beginning 0))
694 (skip-chars-backward " \t"))
695 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
696 (progn
697 ;; We have a candidate before POS ...
698 (setq start (point))
699 (goto-char pos)
700 (if (and (skip-chars-forward ",; \t")
701 (< (- (current-column) column) distance)
702 (looking-at "[-a-zA-Z0-9._+:]"))
703 ;; ... but the one after POS is better.
704 (setq start (point))
705 ;; ... and anything after POS is worse.
706 (goto-char start)))
707 ;; No candidate before POS.
708 (goto-char pos)
709 (skip-chars-forward ",; \t")
710 (setq start (point)))))
711 ;; We have found a suitable starting point, try to skip at least
712 ;; one character.
713 (skip-chars-forward "-a-zA-Z0-9._+:")
714 (setq word (buffer-substring-no-properties start (point)))
715 ;; If there is a continuation at the end of line, check the
716 ;; following line too, eg:
717 ;; see this-
718 ;; command-here(1)
719 ;; Note: This code gets executed iff our entry is after POS.
720 (when (looking-at "[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
721 (setq word (concat word (match-string-no-properties 1)))
722 ;; Make sure the section number gets included by the code below.
723 (goto-char (match-end 1)))
724 (when (string-match "[._]+$" word)
725 (setq word (substring word 0 (match-beginning 0))))
726 ;; The following was commented out since the preceding code
727 ;; should not produce a leading "*" in the first place.
728 ;;; ;; If looking at something like *strcat(... , remove the '*'
729 ;;; (when (string-match "^*" word)
730 ;;; (setq word (substring word 1)))
731 (concat
732 word
733 (and (not (string-equal word ""))
734 ;; If looking at something like ioctl(2) or brc(1M),
735 ;; include the section number in the returned value.
736 (looking-at
737 (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
738 (format "(%s)" (match-string-no-properties 1)))))))
741 ;; ======================================================================
742 ;; Top level command and background process sentinel
744 ;; For compatibility with older versions.
745 ;;;###autoload
746 (defalias 'manual-entry 'man)
748 (defvar Man-completion-cache nil
749 ;; On my machine, "man -k" is so fast that a cache makes no sense,
750 ;; but apparently that's not the case in all cases, so let's add a cache.
751 "Cache of completion table of the form (PREFIX . TABLE).")
753 (defun Man-completion-table (string pred action)
754 (cond
755 ((eq action 'lambda)
756 (not (string-match "([^)]*\\'" string)))
758 (let ((table (cdr Man-completion-cache))
759 (section nil)
760 (prefix string))
761 (when (string-match "\\`\\([[:digit:]].*?\\) " string)
762 (setq section (match-string 1 string))
763 (setq prefix (substring string (match-end 0))))
764 (unless (and Man-completion-cache
765 (string-prefix-p (car Man-completion-cache) prefix))
766 (with-temp-buffer
767 (setq default-directory "/") ;; in case inherited doesn't exist
768 ;; Actually for my `man' the arg is a regexp.
769 ;; POSIX says it must be ERE and "man-db" seems to agree,
770 ;; whereas under MacOSX it seems to be BRE-style and doesn't
771 ;; accept backslashes at all. Let's not bother to
772 ;; quote anything.
773 (let ((process-environment (copy-sequence process-environment)))
774 (setenv "COLUMNS" "999") ;; don't truncate long names
775 ;; manual-program might not even exist. And since it's
776 ;; run differently in Man-getpage-in-background, an error
777 ;; here may not necessarily mean that we'll also get an
778 ;; error later.
779 (ignore-errors
780 (call-process manual-program nil '(t nil) nil
781 "-k" (concat "^" prefix))))
782 (goto-char (point-min))
783 (while (re-search-forward "^\\([^ \t\n]+\\)\\(?: ?\\((.+?)\\)\\(?:[ \t]+- \\(.*\\)\\)?\\)?" nil t)
784 (push (propertize (concat (match-string 1) (match-string 2))
785 'help-echo (match-string 3))
786 table)))
787 ;; Cache the table for later reuse.
788 (setq Man-completion-cache (cons prefix table)))
789 ;; The table may contain false positives since the match is made
790 ;; by "man -k" not just on the manpage's name.
791 (if section
792 (let ((re (concat "(" (regexp-quote section) ")\\'")))
793 (dolist (comp (prog1 table (setq table nil)))
794 (if (string-match re comp)
795 (push (substring comp 0 (match-beginning 0)) table)))
796 (completion-table-with-context (concat section " ") table
797 prefix pred action))
798 ;; If the current text looks like a possible section name,
799 ;; then add a completion entry that just adds a space so SPC
800 ;; can be used to insert a space.
801 (if (string-match "\\`[[:digit:]]" string)
802 (push (concat string " ") table))
803 (let ((res (complete-with-action action table string pred)))
804 ;; In case we're completing to a single name that exists in
805 ;; several sections, the longest prefix will look like "foo(".
806 (if (and (stringp res)
807 (string-match "([^(]*\\'" res)
808 ;; In case the paren was already in `prefix', don't
809 ;; remove it.
810 (> (match-beginning 0) (length prefix)))
811 (substring res 0 (match-beginning 0))
812 res)))))))
814 ;;;###autoload
815 (defun man (man-args)
816 "Get a Un*x manual page and put it in a buffer.
817 This command is the top-level command in the man package. It
818 runs a Un*x command to retrieve and clean a manpage in the
819 background and places the results in a `Man-mode' browsing
820 buffer. See variable `Man-notify-method' for what happens when
821 the buffer is ready. If a buffer already exists for this man
822 page, it will display immediately.
824 For a manpage from a particular section, use either of the
825 following. \"cat(1)\" is how cross-references appear and is
826 passed to man as \"1 cat\".
828 cat(1)
829 1 cat
831 To see manpages from all sections related to a subject, use an
832 \"all pages\" option (which might be \"-a\" if it's not the
833 default), then step through with `Man-next-manpage' (\\<Man-mode-map>\\[Man-next-manpage]) etc.
834 Add to `Man-switches' to make this option permanent.
836 -a chmod
838 An explicit filename can be given too. Use -l if it might
839 otherwise look like a page name.
841 /my/file/name.1.gz
842 -l somefile.1
844 An \"apropos\" query with -k gives a buffer of matching page
845 names or descriptions. The pattern argument is usually an
846 \"egrep\" style regexp.
848 -k pattern"
850 (interactive
851 (list (let* ((default-entry (Man-default-man-entry))
852 ;; ignore case because that's friendly for bizarre
853 ;; caps things like the X11 function names and because
854 ;; "man" itself is case-sensitive on the command line
855 ;; so you're accustomed not to bother about the case
856 ;; ("man -k" is case-insensitive similarly, so the
857 ;; table has everything available to complete)
858 (completion-ignore-case t)
859 (input (completing-read
860 (format "Manual entry%s"
861 (if (string= default-entry "")
862 ": "
863 (format " (default %s): " default-entry)))
864 'Man-completion-table
865 nil nil nil 'Man-topic-history default-entry)))
866 (if (string= input "")
867 (error "No man args given")
868 input))))
870 ;; Possibly translate the "subject(section)" syntax into the
871 ;; "section subject" syntax and possibly downcase the section.
872 (setq man-args (Man-translate-references man-args))
874 (Man-getpage-in-background man-args))
876 ;;;###autoload
877 (defun man-follow (man-args)
878 "Get a Un*x manual page of the item under point and put it in a buffer."
879 (interactive (list (Man-default-man-entry)))
880 (if (or (not man-args)
881 (string= man-args ""))
882 (error "No item under point")
883 (man man-args)))
885 (defun Man-getpage-in-background (topic)
886 "Use TOPIC to build and fire off the manpage and cleaning command."
887 (let* ((man-args topic)
888 (bufname (concat "*Man " man-args "*"))
889 (buffer (get-buffer bufname)))
890 (if buffer
891 (Man-notify-when-ready buffer)
892 (require 'env)
893 (message "Invoking %s %s in the background" manual-program man-args)
894 (setq buffer (generate-new-buffer bufname))
895 (with-current-buffer buffer
896 (setq buffer-undo-list t)
897 (setq Man-original-frame (selected-frame))
898 (setq Man-arguments man-args))
899 (let ((process-environment (copy-sequence process-environment))
900 ;; The following is so Awk script gets \n intact
901 ;; But don't prevent decoding of the outside.
902 (coding-system-for-write 'raw-text-unix)
903 ;; We must decode the output by a coding system that the
904 ;; system's locale suggests in multibyte mode.
905 (coding-system-for-read
906 (if (default-value 'enable-multibyte-characters)
907 locale-coding-system 'raw-text-unix))
908 ;; Avoid possible error by using a directory that always exists.
909 (default-directory
910 (if (and (file-directory-p default-directory)
911 (not (find-file-name-handler default-directory
912 'file-directory-p)))
913 default-directory
914 "/")))
915 ;; Prevent any attempt to use display terminal fanciness.
916 (setenv "TERM" "dumb")
917 ;; In Debian Woody, at least, we get overlong lines under X
918 ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
919 ;; a tty. man(1) says:
920 ;; MANWIDTH
921 ;; If $MANWIDTH is set, its value is used as the line
922 ;; length for which manual pages should be formatted.
923 ;; If it is not set, manual pages will be formatted
924 ;; with a line length appropriate to the current ter-
925 ;; minal (using an ioctl(2) if available, the value of
926 ;; $COLUMNS, or falling back to 80 characters if nei-
927 ;; ther is available).
928 (unless (or (getenv "MANWIDTH") (getenv "COLUMNS"))
929 ;; This isn't strictly correct, since we don't know how
930 ;; the page will actually be displayed, but it seems
931 ;; reasonable.
932 (setenv "COLUMNS" (number-to-string
933 (cond
934 ((and (integerp Man-width) (> Man-width 0))
935 Man-width)
936 (Man-width (frame-width))
937 ((window-width))))))
938 (setenv "GROFF_NO_SGR" "1")
939 ;; Since man-db 2.4.3-1, man writes plain text with no escape
940 ;; sequences when stdout is not a tty. In 2.5.0, the following
941 ;; env-var was added to allow control of this (see Debian Bug#340673).
942 (setenv "MAN_KEEP_FORMATTING" "1")
943 (if (fboundp 'start-process)
944 (set-process-sentinel
945 (start-process manual-program buffer
946 (if (memq system-type '(cygwin windows-nt))
947 shell-file-name
948 "sh")
949 shell-command-switch
950 (format (Man-build-man-command) man-args))
951 'Man-bgproc-sentinel)
952 (let ((exit-status
953 (call-process shell-file-name nil (list buffer nil) nil
954 shell-command-switch
955 (format (Man-build-man-command) man-args)))
956 (msg ""))
957 (or (and (numberp exit-status)
958 (= exit-status 0))
959 (and (numberp exit-status)
960 (setq msg
961 (format "exited abnormally with code %d"
962 exit-status)))
963 (setq msg exit-status))
964 (Man-bgproc-sentinel bufname msg)))))))
966 (defun Man-notify-when-ready (man-buffer)
967 "Notify the user when MAN-BUFFER is ready.
968 See the variable `Man-notify-method' for the different notification behaviors."
969 (let ((saved-frame (with-current-buffer man-buffer
970 Man-original-frame)))
971 (cond
972 ((eq Man-notify-method 'newframe)
973 ;; Since we run asynchronously, perhaps while Emacs is waiting
974 ;; for input, we must not leave a different buffer current. We
975 ;; can't rely on the editor command loop to reselect the
976 ;; selected window's buffer.
977 (save-excursion
978 (let ((frame (make-frame Man-frame-parameters)))
979 (set-window-buffer (frame-selected-window frame) man-buffer)
980 (set-window-dedicated-p (frame-selected-window frame) t)
981 (or (display-multi-frame-p frame)
982 (select-frame frame)))))
983 ((eq Man-notify-method 'pushy)
984 (switch-to-buffer man-buffer))
985 ((eq Man-notify-method 'bully)
986 (and (frame-live-p saved-frame)
987 (select-frame saved-frame))
988 (pop-to-buffer man-buffer)
989 (delete-other-windows))
990 ((eq Man-notify-method 'aggressive)
991 (and (frame-live-p saved-frame)
992 (select-frame saved-frame))
993 (pop-to-buffer man-buffer))
994 ((eq Man-notify-method 'friendly)
995 (and (frame-live-p saved-frame)
996 (select-frame saved-frame))
997 (display-buffer man-buffer 'not-this-window))
998 ((eq Man-notify-method 'polite)
999 (beep)
1000 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1001 ((eq Man-notify-method 'quiet)
1002 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1003 ((or (eq Man-notify-method 'meek)
1005 (message ""))
1008 (defun Man-softhyphen-to-minus ()
1009 ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
1010 ;; least, emit it even when not in a Latin-N locale.
1011 (unless (eq t (compare-strings "latin-" 0 nil
1012 current-language-environment 0 6 t))
1013 (goto-char (point-min))
1014 (let ((str "\255"))
1015 (if enable-multibyte-characters
1016 (setq str (string-as-multibyte str)))
1017 (while (search-forward str nil t) (replace-match "-")))))
1019 (defun Man-fontify-manpage ()
1020 "Convert overstriking and underlining to the correct fonts.
1021 Same for the ANSI bold and normal escape sequences."
1022 (interactive)
1023 (message "Please wait: formatting the %s man page..." Man-arguments)
1024 (goto-char (point-min))
1025 ;; Fontify ANSI escapes.
1026 (let ((faces nil)
1027 (buffer-undo-list t)
1028 (start (point)))
1029 ;; http://www.isthe.com/chongo/tech/comp/ansi_escapes.html
1030 ;; suggests many codes, but we only handle:
1031 ;; ESC [ 00 m reset to normal display
1032 ;; ESC [ 01 m bold
1033 ;; ESC [ 04 m underline
1034 ;; ESC [ 07 m reverse-video
1035 ;; ESC [ 22 m no-bold
1036 ;; ESC [ 24 m no-underline
1037 ;; ESC [ 27 m no-reverse-video
1038 (while (re-search-forward "\e\\[0?\\([1470]\\|2\\([247]\\)\\)m" nil t)
1039 (if faces (put-text-property start (match-beginning 0) 'face
1040 (if (cdr faces) faces (car faces))))
1041 (setq faces
1042 (cond
1043 ((match-beginning 2)
1044 (delq (case (char-after (match-beginning 2))
1045 (?2 Man-overstrike-face)
1046 (?4 Man-underline-face)
1047 (?7 Man-reverse-face))
1048 faces))
1049 ((eq (char-after (match-beginning 1)) ?0) nil)
1051 (cons (case (char-after (match-beginning 1))
1052 (?1 Man-overstrike-face)
1053 (?4 Man-underline-face)
1054 (?7 Man-reverse-face))
1055 faces))))
1056 (delete-region (match-beginning 0) (match-end 0))
1057 (setq start (point))))
1058 ;; Other highlighting.
1059 (let ((buffer-undo-list t))
1060 (if (< (buffer-size) (position-bytes (point-max)))
1061 ;; Multibyte characters exist.
1062 (progn
1063 (goto-char (point-min))
1064 (while (search-forward "__\b\b" nil t)
1065 (backward-delete-char 4)
1066 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1067 (goto-char (point-min))
1068 (while (search-forward "\b\b__" nil t)
1069 (backward-delete-char 4)
1070 (put-text-property (1- (point)) (point) 'face Man-underline-face))))
1071 (goto-char (point-min))
1072 (while (search-forward "_\b" nil t)
1073 (backward-delete-char 2)
1074 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1075 (goto-char (point-min))
1076 (while (search-forward "\b_" nil t)
1077 (backward-delete-char 2)
1078 (put-text-property (1- (point)) (point) 'face Man-underline-face))
1079 (goto-char (point-min))
1080 (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
1081 (replace-match "\\1")
1082 (put-text-property (1- (point)) (point) 'face Man-overstrike-face))
1083 (goto-char (point-min))
1084 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
1085 (replace-match "o")
1086 (put-text-property (1- (point)) (point) 'face 'bold))
1087 (goto-char (point-min))
1088 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
1089 (replace-match "+")
1090 (put-text-property (1- (point)) (point) 'face 'bold))
1091 ;; When the header is longer than the manpage name, groff tries to
1092 ;; condense it to a shorter line interspered with ^H. Remove ^H with
1093 ;; their preceding chars (but don't put Man-overstrike-face). (Bug#5566)
1094 (goto-char (point-min))
1095 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1096 (goto-char (point-min))
1097 ;; Try to recognize common forms of cross references.
1098 (Man-highlight-references)
1099 (Man-softhyphen-to-minus)
1100 (goto-char (point-min))
1101 (while (re-search-forward Man-heading-regexp nil t)
1102 (put-text-property (match-beginning 0)
1103 (match-end 0)
1104 'face Man-overstrike-face)))
1105 (message "%s man page formatted" Man-arguments))
1107 (defun Man-highlight-references (&optional xref-man-type)
1108 "Highlight the references on mouse-over.
1109 References include items in the SEE ALSO section,
1110 header file (#include <foo.h>), and files in FILES.
1111 If optional argument XREF-MAN-TYPE is non-nil, it used as the
1112 button type for items in SEE ALSO section. If it is nil, the
1113 default type, `Man-xref-man-page' is used for the buttons."
1114 ;; `Man-highlight-references' is used from woman.el, too.
1115 ;; woman.el doesn't set `Man-arguments'.
1116 (unless Man-arguments
1117 (setq Man-arguments ""))
1118 (if (string-match "-k " Man-arguments)
1119 (progn
1120 (Man-highlight-references0 nil Man-reference-regexp 1
1121 'Man-default-man-entry
1122 (or xref-man-type 'Man-xref-man-page))
1123 (Man-highlight-references0 nil Man-apropos-regexp 1
1124 'Man-default-man-entry
1125 (or xref-man-type 'Man-xref-man-page)))
1126 (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
1127 'Man-default-man-entry
1128 (or xref-man-type 'Man-xref-man-page))
1129 (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
1130 'Man-xref-header-file)
1131 (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
1132 'Man-xref-normal-file)))
1134 (defun Man-highlight-references0 (start-section regexp button-pos target type)
1135 ;; Based on `Man-build-references-alist'
1136 (when (or (null start-section)
1137 (Man-find-section start-section))
1138 (let ((end (if start-section
1139 (progn
1140 (forward-line 1)
1141 (back-to-indentation)
1142 (save-excursion
1143 (Man-next-section 1)
1144 (point)))
1145 (goto-char (point-min))
1146 nil)))
1147 (while (re-search-forward regexp end t)
1148 (make-text-button
1149 (match-beginning button-pos)
1150 (match-end button-pos)
1151 'type type
1152 'Man-target-string (cond
1153 ((numberp target)
1154 (match-string target))
1155 ((functionp target)
1156 target)
1157 (t nil)))))))
1159 (defun Man-cleanup-manpage (&optional interactive)
1160 "Remove overstriking and underlining from the current buffer.
1161 Normally skip any jobs that should have been done by the sed script,
1162 but when called interactively, do those jobs even if the sed
1163 script would have done them."
1164 (interactive "p")
1165 (message "Please wait: cleaning up the %s man page..."
1166 Man-arguments)
1167 (if (or interactive (not Man-sed-script))
1168 (progn
1169 (goto-char (point-min))
1170 (while (search-forward "_\b" nil t) (backward-delete-char 2))
1171 (goto-char (point-min))
1172 (while (search-forward "\b_" nil t) (backward-delete-char 2))
1173 (goto-char (point-min))
1174 (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
1175 (replace-match "\\1"))
1176 (goto-char (point-min))
1177 (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
1178 (goto-char (point-min))
1179 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
1181 (goto-char (point-min))
1182 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
1183 ;; When the header is longer than the manpage name, groff tries to
1184 ;; condense it to a shorter line interspered with ^H. Remove ^H with
1185 ;; their preceding chars (but don't put Man-overstrike-face). (Bug#5566)
1186 (goto-char (point-min))
1187 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1188 (Man-softhyphen-to-minus)
1189 (message "%s man page cleaned up" Man-arguments))
1191 (defun Man-bgproc-sentinel (process msg)
1192 "Manpage background process sentinel.
1193 When manpage command is run asynchronously, PROCESS is the process
1194 object for the manpage command; when manpage command is run
1195 synchronously, PROCESS is the name of the buffer where the manpage
1196 command is run. Second argument MSG is the exit message of the
1197 manpage command."
1198 (let ((Man-buffer (if (stringp process) (get-buffer process)
1199 (process-buffer process)))
1200 (delete-buff nil)
1201 (err-mess nil))
1203 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1204 (or (stringp process)
1205 (set-process-buffer process nil))
1207 (with-current-buffer Man-buffer
1208 (let ((case-fold-search nil))
1209 (goto-char (point-min))
1210 (cond ((or (looking-at "No \\(manual \\)*entry for")
1211 (looking-at "[^\n]*: nothing appropriate$"))
1212 (setq err-mess (buffer-substring (point)
1213 (progn
1214 (end-of-line) (point)))
1215 delete-buff t))
1217 ;; "-k foo", successful exit, but no output (from man-db)
1218 ;; ENHANCE-ME: share the check for -k with
1219 ;; `Man-highlight-references'. The \\s- bits here are
1220 ;; meant to allow for multiple options with -k among them.
1221 ((and (string-match "\\(\\`\\|\\s-\\)-k\\s-" Man-arguments)
1222 (eq (process-status process) 'exit)
1223 (= (process-exit-status process) 0)
1224 (= (point-min) (point-max)))
1225 (setq err-mess (format "%s: no matches" Man-arguments)
1226 delete-buff t))
1228 ((or (stringp process)
1229 (not (and (eq (process-status process) 'exit)
1230 (= (process-exit-status process) 0))))
1231 (or (zerop (length msg))
1232 (progn
1233 (setq err-mess
1234 (concat (buffer-name Man-buffer)
1235 ": process "
1236 (let ((eos (1- (length msg))))
1237 (if (= (aref msg eos) ?\n)
1238 (substring msg 0 eos) msg))))
1239 (goto-char (point-max))
1240 (insert (format "\nprocess %s" msg))))
1242 (if delete-buff
1243 (kill-buffer Man-buffer)
1244 (if Man-fontify-manpage-flag
1245 (Man-fontify-manpage)
1246 (Man-cleanup-manpage))
1248 (run-hooks 'Man-cooked-hook)
1249 (Man-mode)
1251 (if (not Man-page-list)
1252 (let ((args Man-arguments))
1253 (kill-buffer (current-buffer))
1254 (error "Can't find the %s manpage" args)))
1256 (set-buffer-modified-p nil)
1258 ;; Restore case-fold-search before calling
1259 ;; Man-notify-when-ready because it may switch buffers.
1261 (if (not delete-buff)
1262 (Man-notify-when-ready Man-buffer))
1264 (if err-mess
1265 (error "%s" err-mess))
1266 ))))
1269 ;; ======================================================================
1270 ;; set up manual mode in buffer and build alists
1272 (put 'Man-mode 'mode-class 'special)
1274 (defun Man-mode ()
1275 "A mode for browsing Un*x manual pages.
1277 The following man commands are available in the buffer. Try
1278 \"\\[describe-key] <key> RET\" for more information:
1280 \\[man] Prompt to retrieve a new manpage.
1281 \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
1282 \\[Man-next-manpage] Jump to next manpage in circular list.
1283 \\[Man-previous-manpage] Jump to previous manpage in circular list.
1284 \\[Man-next-section] Jump to next manpage section.
1285 \\[Man-previous-section] Jump to previous manpage section.
1286 \\[Man-goto-section] Go to a manpage section.
1287 \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
1288 \\[Man-quit] Deletes the manpage window, bury its buffer.
1289 \\[Man-kill] Deletes the manpage window, kill its buffer.
1290 \\[describe-mode] Prints this help text.
1292 The following variables may be of some use. Try
1293 \"\\[describe-variable] <variable-name> RET\" for more information:
1295 `Man-notify-method' What happens when manpage formatting is done.
1296 `Man-downcase-section-letters-flag' Force section letters to lower case.
1297 `Man-circular-pages-flag' Treat multiple manpage list as circular.
1298 `Man-section-translations-alist' List of section numbers and their Un*x equiv.
1299 `Man-filter-list' Background manpage filter command.
1300 `Man-mode-map' Keymap bindings for Man mode buffers.
1301 `Man-mode-hook' Normal hook run on entry to Man mode.
1302 `Man-section-regexp' Regexp describing manpage section letters.
1303 `Man-heading-regexp' Regexp describing section headers.
1304 `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
1305 `Man-first-heading-regexp' Regexp for first heading on a manpage.
1306 `Man-reference-regexp' Regexp matching a references in SEE ALSO.
1307 `Man-switches' Background `man' command switches.
1309 The following key bindings are currently in effect in the buffer:
1310 \\{Man-mode-map}"
1311 (interactive)
1312 (kill-all-local-variables)
1313 (setq major-mode 'Man-mode
1314 mode-name "Man"
1315 buffer-auto-save-file-name nil
1316 mode-line-buffer-identification
1317 (list (default-value 'mode-line-buffer-identification)
1318 " {" 'Man-page-mode-string "}")
1319 truncate-lines t
1320 buffer-read-only t)
1321 (buffer-disable-undo)
1322 (auto-fill-mode -1)
1323 (use-local-map Man-mode-map)
1324 (set-syntax-table man-mode-syntax-table)
1325 (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
1326 (set (make-local-variable 'outline-regexp) Man-heading-regexp)
1327 (set (make-local-variable 'outline-level) (lambda () 1))
1328 (Man-build-page-list)
1329 (Man-strip-page-headers)
1330 (Man-unindent)
1331 (Man-goto-page 1 t)
1332 (run-mode-hooks 'Man-mode-hook))
1334 (defsubst Man-build-section-alist ()
1335 "Build the association list of manpage sections."
1336 (setq Man-sections-alist nil)
1337 (goto-char (point-min))
1338 (let ((case-fold-search nil))
1339 (while (re-search-forward Man-heading-regexp (point-max) t)
1340 (aput 'Man-sections-alist (match-string 1))
1341 (forward-line 1))))
1343 (defsubst Man-build-references-alist ()
1344 "Build the association list of references (in the SEE ALSO section)."
1345 (setq Man-refpages-alist nil)
1346 (save-excursion
1347 (if (Man-find-section Man-see-also-regexp)
1348 (let ((start (progn (forward-line 1) (point)))
1349 (end (progn
1350 (Man-next-section 1)
1351 (point)))
1352 hyphenated
1353 (runningpoint -1))
1354 (save-restriction
1355 (narrow-to-region start end)
1356 (goto-char (point-min))
1357 (back-to-indentation)
1358 (while (and (not (eobp)) (/= (point) runningpoint))
1359 (setq runningpoint (point))
1360 (if (re-search-forward Man-hyphenated-reference-regexp end t)
1361 (let* ((word (match-string 0))
1362 (len (1- (length word))))
1363 (if hyphenated
1364 (setq word (concat hyphenated word)
1365 hyphenated nil
1366 ;; Update len, in case a reference spans
1367 ;; more than two lines (paranoia).
1368 len (1- (length word))))
1369 (if (memq (aref word len) '(?- ?­))
1370 (setq hyphenated (substring word 0 len)))
1371 (if (string-match Man-reference-regexp word)
1372 (aput 'Man-refpages-alist word))))
1373 (skip-chars-forward " \t\n,"))))))
1374 (setq Man-refpages-alist (nreverse Man-refpages-alist)))
1376 (defun Man-build-page-list ()
1377 "Build the list of separate manpages in the buffer."
1378 (setq Man-page-list nil)
1379 (let ((page-start (point-min))
1380 (page-end (point-max))
1381 (header ""))
1382 (goto-char page-start)
1383 ;; (switch-to-buffer (current-buffer))(debug)
1384 (while (not (eobp))
1385 (setq header
1386 (if (looking-at Man-page-header-regexp)
1387 (match-string 1)
1388 nil))
1389 ;; Go past both the current and the next Man-first-heading-regexp
1390 (if (re-search-forward Man-first-heading-regexp nil 'move 2)
1391 (let ((p (progn (beginning-of-line) (point))))
1392 ;; We assume that the page header is delimited by blank
1393 ;; lines and that it contains at most one blank line. So
1394 ;; if we back by three blank lines we will be sure to be
1395 ;; before the page header but not before the possible
1396 ;; previous page header.
1397 (search-backward "\n\n" nil t 3)
1398 (if (re-search-forward Man-page-header-regexp p 'move)
1399 (beginning-of-line))))
1400 (setq page-end (point))
1401 (setq Man-page-list (append Man-page-list
1402 (list (list (copy-marker page-start)
1403 (copy-marker page-end)
1404 header))))
1405 (setq page-start page-end)
1408 (defun Man-strip-page-headers ()
1409 "Strip all the page headers but the first from the manpage."
1410 (let ((inhibit-read-only t)
1411 (case-fold-search nil)
1412 (header ""))
1413 (dolist (page Man-page-list)
1414 (and (nth 2 page)
1415 (goto-char (car page))
1416 (re-search-forward Man-first-heading-regexp nil t)
1417 (setq header (buffer-substring (car page) (match-beginning 0)))
1418 ;; Since the awk script collapses all successive blank
1419 ;; lines into one, and since we don't want to get rid of
1420 ;; the fast awk script, one must choose between adding
1421 ;; spare blank lines between pages when there were none and
1422 ;; deleting blank lines at page boundaries when there were
1423 ;; some. We choose the first, so we comment the following
1424 ;; line.
1425 ;; (setq header (concat "\n" header)))
1426 (while (search-forward header (nth 1 page) t)
1427 (replace-match ""))))))
1429 (defun Man-unindent ()
1430 "Delete the leading spaces that indent the manpage."
1431 (let ((inhibit-read-only t)
1432 (case-fold-search nil))
1433 (dolist (page Man-page-list)
1434 (let ((indent "")
1435 (nindent 0))
1436 (narrow-to-region (car page) (car (cdr page)))
1437 (if Man-uses-untabify-flag
1438 (untabify (point-min) (point-max)))
1439 (if (catch 'unindent
1440 (goto-char (point-min))
1441 (if (not (re-search-forward Man-first-heading-regexp nil t))
1442 (throw 'unindent nil))
1443 (beginning-of-line)
1444 (setq indent (buffer-substring (point)
1445 (progn
1446 (skip-chars-forward " ")
1447 (point))))
1448 (setq nindent (length indent))
1449 (if (zerop nindent)
1450 (throw 'unindent nil))
1451 (setq indent (concat indent "\\|$"))
1452 (goto-char (point-min))
1453 (while (not (eobp))
1454 (if (looking-at indent)
1455 (forward-line 1)
1456 (throw 'unindent nil)))
1457 (goto-char (point-min)))
1458 (while (not (eobp))
1459 (or (eolp)
1460 (delete-char nindent))
1461 (forward-line 1)))
1462 ))))
1465 ;; ======================================================================
1466 ;; Man mode commands
1468 (defun Man-next-section (n)
1469 "Move point to Nth next section (default 1)."
1470 (interactive "p")
1471 (let ((case-fold-search nil)
1472 (start (point)))
1473 (if (looking-at Man-heading-regexp)
1474 (forward-line 1))
1475 (if (re-search-forward Man-heading-regexp (point-max) t n)
1476 (beginning-of-line)
1477 (goto-char (point-max))
1478 ;; The last line doesn't belong to any section.
1479 (forward-line -1))
1480 ;; But don't move back from the starting point (can happen if `start'
1481 ;; is somewhere on the last line).
1482 (if (< (point) start) (goto-char start))))
1484 (defun Man-previous-section (n)
1485 "Move point to Nth previous section (default 1)."
1486 (interactive "p")
1487 (let ((case-fold-search nil))
1488 (if (looking-at Man-heading-regexp)
1489 (forward-line -1))
1490 (if (re-search-backward Man-heading-regexp (point-min) t n)
1491 (beginning-of-line)
1492 (goto-char (point-min)))))
1494 (defun Man-find-section (section)
1495 "Move point to SECTION if it exists, otherwise don't move point.
1496 Returns t if section is found, nil otherwise."
1497 (let ((curpos (point))
1498 (case-fold-search nil))
1499 (goto-char (point-min))
1500 (if (re-search-forward (concat "^" section) (point-max) t)
1501 (progn (beginning-of-line) t)
1502 (goto-char curpos)
1503 nil)
1506 (defun Man-goto-section ()
1507 "Query for section to move point to."
1508 (interactive)
1509 (aput 'Man-sections-alist
1510 (let* ((default (aheadsym Man-sections-alist))
1511 (completion-ignore-case t)
1512 chosen
1513 (prompt (concat "Go to section (default " default "): ")))
1514 (setq chosen (completing-read prompt Man-sections-alist))
1515 (if (or (not chosen)
1516 (string= chosen ""))
1517 default
1518 chosen)))
1519 (unless (Man-find-section (aheadsym Man-sections-alist))
1520 (error "Section not found")))
1523 (defun Man-goto-see-also-section ()
1524 "Move point to the \"SEE ALSO\" section.
1525 Actually the section moved to is described by `Man-see-also-regexp'."
1526 (interactive)
1527 (if (not (Man-find-section Man-see-also-regexp))
1528 (error "%s" (concat "No " Man-see-also-regexp
1529 " section found in the current manpage"))))
1531 (defun Man-possibly-hyphenated-word ()
1532 "Return a possibly hyphenated word at point.
1533 If the word starts at the first non-whitespace column, and the
1534 previous line ends with a hyphen, return the last word on the previous
1535 line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
1536 as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
1537 \"tcgetp-\" instead of \"grp\"."
1538 (save-excursion
1539 (skip-syntax-backward "w()")
1540 (skip-chars-forward " \t")
1541 (let ((beg (point))
1542 (word (current-word)))
1543 (when (eq beg (save-excursion
1544 (back-to-indentation)
1545 (point)))
1546 (end-of-line 0)
1547 (if (eq (char-before) ?-)
1548 (setq word (current-word))))
1549 word)))
1551 (defun Man-follow-manual-reference (reference)
1552 "Get one of the manpages referred to in the \"SEE ALSO\" section.
1553 Specify which REFERENCE to use; default is based on word at point."
1554 (interactive
1555 (if (not Man-refpages-alist)
1556 (error "There are no references in the current man page")
1557 (list
1558 (let* ((default (or
1559 (car (all-completions
1560 (let ((word
1561 (or (Man-possibly-hyphenated-word)
1562 "")))
1563 ;; strip a trailing '-':
1564 (if (string-match "-$" word)
1565 (substring word 0
1566 (match-beginning 0))
1567 word))
1568 Man-refpages-alist))
1569 (aheadsym Man-refpages-alist)))
1570 (defaults
1571 (mapcar 'substring-no-properties
1572 (delete-dups
1573 (delq nil (cons default
1574 (mapcar 'car Man-refpages-alist))))))
1575 chosen
1576 (prompt (concat "Refer to (default " default "): ")))
1577 (setq chosen (completing-read prompt Man-refpages-alist
1578 nil nil nil nil defaults))
1579 (if (or (not chosen)
1580 (string= chosen ""))
1581 default
1582 chosen)))))
1583 (if (not Man-refpages-alist)
1584 (error "Can't find any references in the current manpage")
1585 (aput 'Man-refpages-alist reference)
1586 (Man-getpage-in-background
1587 (Man-translate-references (aheadsym Man-refpages-alist)))))
1589 (defun Man-kill ()
1590 "Kill the buffer containing the manpage."
1591 (interactive)
1592 (quit-window t))
1594 (defun Man-quit ()
1595 "Bury the buffer containing the manpage."
1596 (interactive)
1597 (quit-window))
1599 (defun Man-goto-page (page &optional noerror)
1600 "Go to the manual page on page PAGE."
1601 (interactive
1602 (if (not Man-page-list)
1603 (error "Not a man page buffer")
1604 (if (= (length Man-page-list) 1)
1605 (error "You're looking at the only manpage in the buffer")
1606 (list (read-minibuffer (format "Go to manpage [1-%d]: "
1607 (length Man-page-list)))))))
1608 (if (and (not Man-page-list) (not noerror))
1609 (error "Not a man page buffer"))
1610 (when Man-page-list
1611 (if (or (< page 1)
1612 (> page (length Man-page-list)))
1613 (error "No manpage %d found" page))
1614 (let* ((page-range (nth (1- page) Man-page-list))
1615 (page-start (car page-range))
1616 (page-end (car (cdr page-range))))
1617 (setq Man-current-page page
1618 Man-page-mode-string (Man-make-page-mode-string))
1619 (widen)
1620 (goto-char page-start)
1621 (narrow-to-region page-start page-end)
1622 (Man-build-section-alist)
1623 (Man-build-references-alist)
1624 (goto-char (point-min)))))
1627 (defun Man-next-manpage ()
1628 "Find the next manpage entry in the buffer."
1629 (interactive)
1630 (if (= (length Man-page-list) 1)
1631 (error "This is the only manpage in the buffer"))
1632 (if (< Man-current-page (length Man-page-list))
1633 (Man-goto-page (1+ Man-current-page))
1634 (if Man-circular-pages-flag
1635 (Man-goto-page 1)
1636 (error "You're looking at the last manpage in the buffer"))))
1638 (defun Man-previous-manpage ()
1639 "Find the previous manpage entry in the buffer."
1640 (interactive)
1641 (if (= (length Man-page-list) 1)
1642 (error "This is the only manpage in the buffer"))
1643 (if (> Man-current-page 1)
1644 (Man-goto-page (1- Man-current-page))
1645 (if Man-circular-pages-flag
1646 (Man-goto-page (length Man-page-list))
1647 (error "You're looking at the first manpage in the buffer"))))
1649 ;; Header file support
1650 (defun Man-view-header-file (file)
1651 "View a header file specified by FILE from `Man-header-file-path'."
1652 (let ((path Man-header-file-path)
1653 complete-path)
1654 (while path
1655 (setq complete-path (expand-file-name file (car path))
1656 path (cdr path))
1657 (if (file-readable-p complete-path)
1658 (progn (view-file complete-path)
1659 (setq path nil))
1660 (setq complete-path nil)))
1661 complete-path))
1663 ;; Init the man package variables, if not already done.
1664 (Man-init-defvars)
1666 (add-to-list 'debug-ignored-errors "^No manpage [0-9]* found$")
1667 (add-to-list 'debug-ignored-errors "^Can't find the .* manpage$")
1669 (provide 'man)
1671 ;; arch-tag: 587cda76-8e23-4594-b1f3-89b6b09a0d47
1672 ;;; man.el ends here