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