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