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