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