(while-no-input): Don't splice BODY directly into the `or' form.
[emacs.git] / lisp / man.el
blob67d745347c08911e003152165944c194e76fe50e
1 ;;; man.el --- browse UNIX manual pages -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 1993, 1994, 1996, 1997, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: Barry A. Warsaw <bwarsaw@cen.com>
7 ;; Maintainer: FSF
8 ;; Keywords: help
9 ;; Adapted-By: ESR, pot
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; 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.
28 ;;; Commentary:
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.
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.
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.
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.
52 ;; Eric Rose <erose@jessica.stanford.edu>, submitted manual.el which
53 ;; provided a very nice manual browsing mode.
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.
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.
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.
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.
96 ;;; Code:
98 (eval-when-compile (require 'cl))
99 (require 'assoc)
100 (require 'button)
102 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
103 ;; empty defvars (keep the compiler quiet)
105 (defgroup man nil
106 "Browse UNIX manual pages."
107 :prefix "Man-"
108 :group 'help)
111 (defvar Man-notify)
112 (defcustom Man-filter-list nil
113 "*Manpage cleaning filter command phrases.
114 This variable contains a list of the following form:
116 '((command-string phrase-string*)*)
118 Each phrase-string is concatenated onto the command-string to form a
119 command filter. The (standard) output (and standard error) of the Un*x
120 man command is piped through each command filter in the order the
121 commands appear in the association list. The final output is placed in
122 the manpage buffer."
123 :type '(repeat (list (string :tag "Command String")
124 (repeat :inline t
125 (string :tag "Phrase String"))))
126 :group 'man)
128 (defvar Man-uses-untabify-flag t
129 "Non-nil means use `untabify' instead of `Man-untabify-command'.")
130 (defvar Man-sed-script nil
131 "Script for sed to nuke backspaces and ANSI codes from manpages.")
133 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
134 ;; user variables
136 (defcustom Man-fontify-manpage-flag t
137 "Non-nil means make up the manpage with fonts."
138 :type 'boolean
139 :group 'man)
141 (defcustom Man-overstrike-face 'bold
142 "Face to use when fontifying overstrike."
143 :type 'face
144 :group 'man)
146 (defcustom Man-underline-face 'underline
147 "Face to use when fontifying underlining."
148 :type 'face
149 :group 'man)
151 (defcustom Man-reverse-face 'highlight
152 "Face to use when fontifying reverse video."
153 :type 'face
154 :group 'man)
156 ;; Use the value of the obsolete user option Man-notify, if set.
157 (defcustom Man-notify-method (if (boundp 'Man-notify) Man-notify 'friendly)
158 "Selects the behavior when manpage is ready.
159 This variable may have one of the following values, where (sf) means
160 that the frames are switched, so the manpage is displayed in the frame
161 where the man command was called from:
163 newframe -- put the manpage in its own frame (see `Man-frame-parameters')
164 pushy -- make the manpage the current buffer in the current window
165 bully -- make the manpage the current buffer and only window (sf)
166 aggressive -- make the manpage the current buffer in the other window (sf)
167 friendly -- display manpage in the other window but don't make current (sf)
168 polite -- don't display manpage, but prints message and beep when ready
169 quiet -- like `polite', but don't beep
170 meek -- make no indication that the manpage is ready
172 Any other value of `Man-notify-method' is equivalent to `meek'."
173 :type '(radio (const newframe) (const pushy) (const bully)
174 (const aggressive) (const friendly)
175 (const polite) (const quiet) (const meek))
176 :group 'man)
178 (defcustom Man-width nil
179 "Number of columns for which manual pages should be formatted.
180 If nil, the width of the window selected at the moment of man
181 invocation is used. If non-nil, the width of the frame selected
182 at the moment of man invocation is used. The value also can be a
183 positive integer."
184 :type '(choice (const :tag "Window width" nil)
185 (const :tag "Frame width" t)
186 (integer :tag "Specific width" :value 65))
187 :group 'man)
189 (defcustom Man-frame-parameters nil
190 "Frame parameter list for creating a new frame for a manual page."
191 :type 'sexp
192 :group 'man)
194 (defcustom Man-downcase-section-letters-flag t
195 "Non-nil means letters in sections are converted to lower case.
196 Some Un*x man commands can't handle uppercase letters in sections, for
197 example \"man 2V chmod\", but they are often displayed in the manpage
198 with the upper case letter. When this variable is t, the section
199 letter (e.g., \"2V\") is converted to lowercase (e.g., \"2v\") before
200 being sent to the man background process."
201 :type 'boolean
202 :group 'man)
204 (defcustom Man-circular-pages-flag t
205 "Non-nil means the manpage list is treated as circular for traversal."
206 :type 'boolean
207 :group 'man)
209 (defcustom Man-section-translations-alist
210 (list
211 '("3C++" . "3")
212 ;; Some systems have a real 3x man section, so let's comment this.
213 ;; '("3X" . "3") ; Xlib man pages
214 '("3X11" . "3")
215 '("1-UCB" . ""))
216 "Association list of bogus sections to real section numbers.
217 Some manpages (e.g. the Sun C++ 2.1 manpages) have section numbers in
218 their references which Un*x `man' does not recognize. This
219 association list is used to translate those sections, when found, to
220 the associated section number."
221 :type '(repeat (cons (string :tag "Bogus Section")
222 (string :tag "Real Section")))
223 :group 'man)
225 (defcustom Man-header-file-path
226 '("/usr/include" "/usr/local/include")
227 "C Header file search path used in Man."
228 :type '(repeat string)
229 :group 'man)
231 (defvar manual-program "man"
232 "The name of the program that produces man pages.")
234 (defvar Man-untabify-command "pr"
235 "Command used for untabifying.")
237 (defvar Man-untabify-command-args (list "-t" "-e")
238 "List of arguments to be passed to `Man-untabify-command' (which see).")
240 (defvar Man-sed-command "sed"
241 "Command used for processing sed scripts.")
243 (defvar Man-awk-command "awk"
244 "Command used for processing awk scripts.")
246 (defvar Man-mode-hook nil
247 "Hook run when Man mode is enabled.")
249 (defvar Man-cooked-hook nil
250 "Hook run after removing backspaces but before `Man-mode' processing.")
252 (defvar Man-name-regexp "[-a-zA-Z0-9_­+][-a-zA-Z0-9_.:­+]*"
253 "Regular expression describing the name of a manpage (without section).")
255 (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
256 "Regular expression describing a manpage section within parentheses.")
258 (defvar Man-page-header-regexp
259 (if (and (string-match "-solaris2\\." system-configuration)
260 (not (string-match "-solaris2\\.[123435]$" system-configuration)))
261 (concat "^[-A-Za-z0-9_].*[ \t]\\(" Man-name-regexp
262 "(\\(" Man-section-regexp "\\))\\)$")
263 (concat "^[ \t]*\\(" Man-name-regexp
264 "(\\(" Man-section-regexp "\\))\\).*\\1"))
265 "Regular expression describing the heading of a page.")
267 (defvar Man-heading-regexp "^\\([A-Z][A-Z0-9 /-]+\\)$"
268 "Regular expression describing a manpage heading entry.")
270 (defvar Man-see-also-regexp "SEE ALSO"
271 "Regular expression for SEE ALSO heading (or your equivalent).
272 This regexp should not start with a `^' character.")
274 ;; This used to have leading space [ \t]*, but was removed because it
275 ;; causes false page splits on an occasional NAME with leading space
276 ;; inside a manpage. And `Man-heading-regexp' doesn't have [ \t]* anyway.
277 (defvar Man-first-heading-regexp "^NAME$\\|^[ \t]*No manual entry fo.*$"
278 "Regular expression describing first heading on a manpage.
279 This regular expression should start with a `^' character.")
281 (defvar Man-reference-regexp
282 (concat "\\(" Man-name-regexp "\\)[ \t]*(\\(" Man-section-regexp "\\))")
283 "Regular expression describing a reference to another manpage.")
285 (defvar Man-apropos-regexp
286 (concat "\\\[\\(" Man-name-regexp "\\)\\\][ \t]*(\\(" Man-section-regexp "\\))")
287 "Regular expression describing a reference to manpages in \"man -k output\".")
289 (defvar Man-synopsis-regexp "SYNOPSIS"
290 "Regular expression for SYNOPSIS heading (or your equivalent).
291 This regexp should not start with a `^' character.")
293 (defvar Man-files-regexp "FILES"
294 "Regular expression for FILES heading (or your equivalent).
295 This regexp should not start with a `^' character.")
297 (defvar Man-include-regexp "#[ \t]*include[ \t]*"
298 "Regular expression describing the #include (directive of cpp).")
300 (defvar Man-file-name-regexp "[^<>\", \t\n]+"
301 "Regular expression describing <> in #include line (directive of cpp).")
303 (defvar Man-normal-file-prefix-regexp "[/~$]"
304 "Regular expression describing a file path appeared in FILES section.")
306 (defvar Man-header-regexp
307 (concat "\\(" Man-include-regexp "\\)"
308 "[<\"]"
309 "\\(" Man-file-name-regexp "\\)"
310 "[>\"]")
311 "Regular expression describing references to header files.")
313 (defvar Man-normal-file-regexp
314 (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
315 "Regular expression describing references to normal files.")
317 ;; This includes the section as an optional part to catch hyphenated
318 ;; refernces to manpages.
319 (defvar Man-hyphenated-reference-regexp
320 (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
321 "Regular expression describing a reference in the SEE ALSO section.")
323 (defvar Man-switches ""
324 "Switches passed to the man command, as a single string.
326 If you want to be able to see all the manpages for a subject you type,
327 make -a one of the switches, if your `man' program supports it.")
329 (defvar Man-specified-section-option
330 (if (string-match "-solaris[0-9.]*$" system-configuration)
331 "-s"
333 "Option that indicates a specified a manual section name.")
335 (defvar Man-support-local-filenames 'auto-detect
336 "Internal cache for the value of the function `Man-support-local-filenames'.
337 `auto-detect' means the value is not yet determined.
338 Otherwise, the value is whatever the function
339 `Man-support-local-filenames' should return.")
341 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
342 ;; end user variables
344 ;; other variables and keymap initializations
345 (defvar Man-original-frame)
346 (make-variable-buffer-local 'Man-original-frame)
347 (defvar Man-arguments)
348 (make-variable-buffer-local 'Man-arguments)
349 (put 'Man-arguments 'permanent-local t)
351 (defvar Man-sections-alist nil)
352 (make-variable-buffer-local 'Man-sections-alist)
353 (defvar Man-refpages-alist nil)
354 (make-variable-buffer-local 'Man-refpages-alist)
355 (defvar Man-page-list nil)
356 (make-variable-buffer-local 'Man-page-list)
357 (defvar Man-current-page 0)
358 (make-variable-buffer-local 'Man-current-page)
359 (defvar Man-page-mode-string "1 of 1")
360 (make-variable-buffer-local 'Man-page-mode-string)
362 (defconst Man-sysv-sed-script "\
363 /\b/ { s/_\b//g
364 s/\b_//g
365 s/o\b+/o/g
366 s/+\bo/o/g
367 :ovstrk
368 s/\\(.\\)\b\\1/\\1/g
369 t ovstrk
371 /\e\\[[0-9][0-9]*m/ s///g"
372 "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
374 (defconst Man-berkeley-sed-script "\
375 /\b/ { s/_\b//g\\
376 s/\b_//g\\
377 s/o\b+/o/g\\
378 s/+\bo/o/g\\
379 :ovstrk\\
380 s/\\(.\\)\b\\1/\\1/g\\
381 t ovstrk\\
383 /\e\\[[0-9][0-9]*m/ s///g"
384 "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
386 (defvar Man-topic-history nil "Topic read history.")
388 (defvar man-mode-syntax-table
389 (let ((table (copy-syntax-table (standard-syntax-table))))
390 (modify-syntax-entry ?. "w" table)
391 (modify-syntax-entry ?_ "w" table)
392 (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
393 table)
394 "Syntax table used in Man mode buffers.")
396 (defvar Man-mode-map
397 (let ((map (make-sparse-keymap)))
398 (suppress-keymap map)
399 (set-keymap-parent map button-buffer-map)
401 (define-key map " " 'scroll-up)
402 (define-key map "\177" 'scroll-down)
403 (define-key map "n" 'Man-next-section)
404 (define-key map "p" 'Man-previous-section)
405 (define-key map "\en" 'Man-next-manpage)
406 (define-key map "\ep" 'Man-previous-manpage)
407 (define-key map ">" 'end-of-buffer)
408 (define-key map "<" 'beginning-of-buffer)
409 (define-key map "." 'beginning-of-buffer)
410 (define-key map "r" 'Man-follow-manual-reference)
411 (define-key map "g" 'Man-goto-section)
412 (define-key map "s" 'Man-goto-see-also-section)
413 (define-key map "k" 'Man-kill)
414 (define-key map "q" 'Man-quit)
415 (define-key map "m" 'man)
416 ;; Not all the man references get buttons currently. The text in the
417 ;; manual page can contain references to other man pages
418 (define-key map "\r" 'man-follow)
419 (define-key map "?" 'describe-mode)
420 map)
421 "Keymap for Man mode.")
423 ;; buttons
424 (define-button-type 'Man-abstract-xref-man-page
425 'follow-link t
426 'help-echo "mouse-2, RET: display this man page"
427 'func nil
428 'action #'Man-xref-button-action)
430 (defun Man-xref-button-action (button)
431 (let ((target (button-get button 'Man-target-string)))
432 (funcall
433 (button-get button 'func)
434 (cond ((null target)
435 (button-label button))
436 ((functionp target)
437 (funcall target (button-start button)))
438 (t target)))))
440 (define-button-type 'Man-xref-man-page
441 :supertype 'Man-abstract-xref-man-page
442 'func 'man-follow)
445 (define-button-type 'Man-xref-header-file
446 'action (lambda (button)
447 (let ((w (button-get button 'Man-target-string)))
448 (unless (Man-view-header-file w)
449 (error "Cannot find header file: %s" w))))
450 'follow-link t
451 'help-echo "mouse-2: display this header file")
453 (define-button-type 'Man-xref-normal-file
454 'action (lambda (button)
455 (let ((f (substitute-in-file-name
456 (button-get button 'Man-target-string))))
457 (if (file-exists-p f)
458 (if (file-readable-p f)
459 (view-file f)
460 (error "Cannot read a file: %s" f))
461 (error "Cannot find a file: %s" f))))
462 'follow-link t
463 'help-echo "mouse-2: display this file")
466 ;; ======================================================================
467 ;; utilities
469 (defun Man-init-defvars ()
470 "Used for initializing variables based on display's color support.
471 This is necessary if one wants to dump man.el with Emacs."
473 ;; Avoid possible error in call-process by using a directory that must exist.
474 (let ((default-directory "/"))
475 (setq Man-sed-script
476 (cond
477 (Man-fontify-manpage-flag
478 nil)
479 ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
480 Man-sysv-sed-script)
481 ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
482 Man-berkeley-sed-script)
484 nil))))
486 (setq Man-filter-list
487 ;; Avoid trailing nil which confuses customize.
488 (apply 'list
489 (cons
490 Man-sed-command
491 (list
492 (if Man-sed-script
493 (concat "-e '" Man-sed-script "'")
495 "-e '/^[\001-\032][\001-\032]*$/d'"
496 "-e '/\e[789]/s///g'"
497 "-e '/Reformatting page. Wait/d'"
498 "-e '/Reformatting entry. Wait/d'"
499 "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
500 "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
501 "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
502 "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
503 "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
504 "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
505 "-e '/^[A-Za-z].*Last[ \t]change:/d'"
506 "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
507 "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
508 "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
510 (cons
511 Man-awk-command
512 (list
513 "'\n"
514 "BEGIN { blankline=0; anonblank=0; }\n"
515 "/^$/ { if (anonblank==0) next; }\n"
516 "{ anonblank=1; }\n"
517 "/^$/ { blankline++; next; }\n"
518 "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
521 (if (not Man-uses-untabify-flag)
522 ;; The outer list will be stripped off by apply.
523 (list (cons
524 Man-untabify-command
525 Man-untabify-command-args))
529 (defsubst Man-make-page-mode-string ()
530 "Formats part of the mode line for Man mode."
531 (format "%s page %d of %d"
532 (or (nth 2 (nth (1- Man-current-page) Man-page-list))
534 Man-current-page
535 (length Man-page-list)))
537 (defsubst Man-build-man-command ()
538 "Builds the entire background manpage and cleaning command."
539 (let ((command (concat manual-program " " Man-switches
540 (cond
541 ;; Already has %s
542 ((string-match "%s" manual-program) "")
543 ;; Stock MS-DOS shells cannot redirect stderr;
544 ;; `call-process' below sends it to /dev/null,
545 ;; so we don't need `2>' even with DOS shells
546 ;; which do support stderr redirection.
547 ((not (fboundp 'start-process)) " %s")
548 ((concat " %s 2>" null-device)))))
549 (flist Man-filter-list))
550 (while (and flist (car flist))
551 (let ((pcom (car (car flist)))
552 (pargs (cdr (car flist))))
553 (setq command
554 (concat command " | " pcom " "
555 (mapconcat (lambda (phrase)
556 (if (not (stringp phrase))
557 (error "Malformed Man-filter-list"))
558 phrase)
559 pargs " ")))
560 (setq flist (cdr flist))))
561 command))
564 (defun Man-translate-cleanup (string)
565 "Strip leading, trailing and middle spaces."
566 (when (stringp string)
567 ;; Strip leading and trailing
568 (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
569 (setq string (match-string 1 string)))
570 ;; middle spaces
571 (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
572 (setq string (replace-regexp-in-string " +" " " string))
573 string))
575 (defun Man-translate-references (ref)
576 "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
577 Leave it as is if already in that style. Possibly downcase and
578 translate the section (see the `Man-downcase-section-letters-flag'
579 and the `Man-section-translations-alist' variables)."
580 (let ((name "")
581 (section "")
582 (slist Man-section-translations-alist))
583 (setq ref (Man-translate-cleanup ref))
584 (cond
585 ;; "chmod(2V)" case ?
586 ((string-match (concat "^" Man-reference-regexp "$") ref)
587 (setq name (match-string 1 ref)
588 section (match-string 2 ref)))
589 ;; "2v chmod" case ?
590 ((string-match (concat "^\\(" Man-section-regexp
591 "\\) +\\(" Man-name-regexp "\\)$") ref)
592 (setq name (match-string 2 ref)
593 section (match-string 1 ref))))
594 (if (string= name "")
595 ref ; Return the reference as is
596 (if Man-downcase-section-letters-flag
597 (setq section (downcase section)))
598 (while slist
599 (let ((s1 (car (car slist)))
600 (s2 (cdr (car slist))))
601 (setq slist (cdr slist))
602 (if Man-downcase-section-letters-flag
603 (setq s1 (downcase s1)))
604 (if (not (string= s1 section)) nil
605 (setq section (if Man-downcase-section-letters-flag
606 (downcase s2)
608 slist nil))))
609 (concat Man-specified-section-option section " " name))))
611 (defun Man-support-local-filenames ()
612 "Check the availability of `-l' option of the man command.
613 This option allows `man' to interpret command line arguments
614 as local filenames.
615 Return the value of the variable `Man-support-local-filenames'
616 if it was set to nil or t before the call of this function.
617 If t, the man command supports `-l' option. If nil, it doesn't.
618 Otherwise, if the value of `Man-support-local-filenames'
619 is neither t nor nil, then determine a new value, set it
620 to the variable `Man-support-local-filenames' and return
621 a new value."
622 (if (or (not Man-support-local-filenames)
623 (eq Man-support-local-filenames t))
624 Man-support-local-filenames
625 (setq Man-support-local-filenames
626 (with-temp-buffer
627 (and (equal (condition-case nil
628 (let ((default-directory
629 ;; Assure that `default-directory' exists
630 ;; and is readable.
631 (if (and (file-directory-p default-directory)
632 (file-readable-p default-directory))
633 default-directory
634 (expand-file-name "~/"))))
635 (call-process manual-program nil t nil "--help"))
636 (error nil))
638 (progn
639 (goto-char (point-min))
640 (search-forward "--local-file" nil t))
641 t)))))
644 ;; ======================================================================
645 ;; default man entry: get word near point
647 (defun Man-default-man-entry (&optional pos)
648 "Guess default manual entry based on the text near position POS.
649 POS defaults to `point'."
650 (let (word start pos column distance)
651 (save-excursion
652 (when pos (goto-char pos))
653 (setq pos (point))
654 ;; The default title is the nearest entry-like object before or
655 ;; after POS.
656 (if (and (skip-chars-backward " \ta-zA-Z0-9+")
657 (not (zerop (skip-chars-backward "(")))
658 ;; Try to handle the special case where POS is on a
659 ;; section number.
660 (looking-at
661 (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
662 ;; We skipped a valid section number backwards, look at
663 ;; preceding text.
664 (or (and (skip-chars-backward ",; \t")
665 (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
666 ;; Not a valid entry, move POS after closing paren.
667 (not (setq pos (match-end 0)))))
668 ;; We have a candidate, make `start' record its starting
669 ;; position.
670 (setq start (point))
671 ;; Otherwise look at char before POS.
672 (goto-char pos)
673 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
674 ;; Our candidate is just before or around POS.
675 (setq start (point))
676 ;; Otherwise record the current column and look backwards.
677 (setq column (current-column))
678 (skip-chars-backward ",; \t")
679 ;; Record the distance travelled.
680 (setq distance (- column (current-column)))
681 (when (looking-back
682 (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)"))
683 ;; Skip section number backwards.
684 (goto-char (match-beginning 0))
685 (skip-chars-backward " \t"))
686 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
687 (progn
688 ;; We have a candidate before POS ...
689 (setq start (point))
690 (goto-char pos)
691 (if (and (skip-chars-forward ",; \t")
692 (< (- (current-column) column) distance)
693 (looking-at "[-a-zA-Z0-9._+:]"))
694 ;; ... but the one after POS is better.
695 (setq start (point))
696 ;; ... and anything after POS is worse.
697 (goto-char start)))
698 ;; No candidate before POS.
699 (goto-char pos)
700 (skip-chars-forward ",; \t")
701 (setq start (point)))))
702 ;; We have found a suitable starting point, try to skip at least
703 ;; one character.
704 (skip-chars-forward "-a-zA-Z0-9._+:")
705 (setq word (buffer-substring-no-properties start (point)))
706 ;; If there is a continuation at the end of line, check the
707 ;; following line too, eg:
708 ;; see this-
709 ;; command-here(1)
710 ;; Note: This code gets executed iff our entry is after POS.
711 (when (looking-at "[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
712 (setq word (concat word (match-string-no-properties 1)))
713 ;; Make sure the section number gets included by the code below.
714 (goto-char (match-end 1)))
715 (when (string-match "[._]+$" word)
716 (setq word (substring word 0 (match-beginning 0))))
717 ;; The following was commented out since the preceding code
718 ;; should not produce a leading "*" in the first place.
719 ;;; ;; If looking at something like *strcat(... , remove the '*'
720 ;;; (when (string-match "^*" word)
721 ;;; (setq word (substring word 1)))
722 (concat
723 word
724 (and (not (string-equal word ""))
725 ;; If looking at something like ioctl(2) or brc(1M),
726 ;; include the section number in the returned value.
727 (looking-at
728 (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
729 (format "(%s)" (match-string-no-properties 1)))))))
732 ;; ======================================================================
733 ;; Top level command and background process sentinel
735 ;; For compatibility with older versions.
736 ;;;###autoload
737 (defalias 'manual-entry 'man)
740 ;;;###autoload
741 (defun man (man-args)
742 "Get a Un*x manual page and put it in a buffer.
743 This command is the top-level command in the man package. It runs a Un*x
744 command to retrieve and clean a manpage in the background and places the
745 results in a Man mode (manpage browsing) buffer. See variable
746 `Man-notify-method' for what happens when the buffer is ready.
747 If a buffer already exists for this man page, it will display immediately.
749 To specify a man page from a certain section, type SUBJECT(SECTION) or
750 SECTION SUBJECT when prompted for a manual entry. To see manpages from
751 all sections related to a subject, put something appropriate into the
752 `Man-switches' variable, which see."
753 (interactive
754 (list (let* ((default-entry (Man-default-man-entry))
755 (input (read-string
756 (format "Manual entry%s"
757 (if (string= default-entry "")
758 ": "
759 (format " (default %s): " default-entry)))
760 nil 'Man-topic-history default-entry)))
761 (if (string= input "")
762 (error "No man args given")
763 input))))
765 ;; Possibly translate the "subject(section)" syntax into the
766 ;; "section subject" syntax and possibly downcase the section.
767 (setq man-args (Man-translate-references man-args))
769 (Man-getpage-in-background man-args))
771 ;;;###autoload
772 (defun man-follow (man-args)
773 "Get a Un*x manual page of the item under point and put it in a buffer."
774 (interactive (list (Man-default-man-entry)))
775 (if (or (not man-args)
776 (string= man-args ""))
777 (error "No item under point")
778 (man man-args)))
780 (defun Man-getpage-in-background (topic)
781 "Use TOPIC to build and fire off the manpage and cleaning command."
782 (let* ((man-args topic)
783 (bufname (concat "*Man " man-args "*"))
784 (buffer (get-buffer bufname)))
785 (if buffer
786 (Man-notify-when-ready buffer)
787 (require 'env)
788 (message "Invoking %s %s in the background" manual-program man-args)
789 (setq buffer (generate-new-buffer bufname))
790 (with-current-buffer buffer
791 (setq buffer-undo-list t)
792 (setq Man-original-frame (selected-frame))
793 (setq Man-arguments man-args))
794 (let ((process-environment (copy-sequence process-environment))
795 ;; The following is so Awk script gets \n intact
796 ;; But don't prevent decoding of the outside.
797 (coding-system-for-write 'raw-text-unix)
798 ;; We must decode the output by a coding system that the
799 ;; system's locale suggests in multibyte mode.
800 (coding-system-for-read
801 (if default-enable-multibyte-characters
802 locale-coding-system 'raw-text-unix))
803 ;; Avoid possible error by using a directory that always exists.
804 (default-directory
805 (if (and (file-directory-p default-directory)
806 (not (find-file-name-handler default-directory
807 'file-directory-p)))
808 default-directory
809 "/")))
810 ;; Prevent any attempt to use display terminal fanciness.
811 (setenv "TERM" "dumb")
812 ;; In Debian Woody, at least, we get overlong lines under X
813 ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
814 ;; a tty. man(1) says:
815 ;; MANWIDTH
816 ;; If $MANWIDTH is set, its value is used as the line
817 ;; length for which manual pages should be formatted.
818 ;; If it is not set, manual pages will be formatted
819 ;; with a line length appropriate to the current ter-
820 ;; minal (using an ioctl(2) if available, the value of
821 ;; $COLUMNS, or falling back to 80 characters if nei-
822 ;; ther is available).
823 (unless (or (getenv "MANWIDTH") (getenv "COLUMNS"))
824 ;; This isn't strictly correct, since we don't know how
825 ;; the page will actually be displayed, but it seems
826 ;; reasonable.
827 (setenv "COLUMNS" (number-to-string
828 (cond
829 ((and (integerp Man-width) (> Man-width 0))
830 Man-width)
831 (Man-width (frame-width))
832 ((window-width))))))
833 (setenv "GROFF_NO_SGR" "1")
834 (if (fboundp 'start-process)
835 (set-process-sentinel
836 (start-process manual-program buffer
837 (if (memq system-type '(cygwin windows-nt))
838 shell-file-name
839 "sh")
840 shell-command-switch
841 (format (Man-build-man-command) man-args))
842 'Man-bgproc-sentinel)
843 (let ((exit-status
844 (call-process shell-file-name nil (list buffer nil) nil
845 shell-command-switch
846 (format (Man-build-man-command) man-args)))
847 (msg ""))
848 (or (and (numberp exit-status)
849 (= exit-status 0))
850 (and (numberp exit-status)
851 (setq msg
852 (format "exited abnormally with code %d"
853 exit-status)))
854 (setq msg exit-status))
855 (Man-bgproc-sentinel bufname msg)))))))
857 (defun Man-notify-when-ready (man-buffer)
858 "Notify the user when MAN-BUFFER is ready.
859 See the variable `Man-notify-method' for the different notification behaviors."
860 (let ((saved-frame (with-current-buffer man-buffer
861 Man-original-frame)))
862 (cond
863 ((eq Man-notify-method 'newframe)
864 ;; Since we run asynchronously, perhaps while Emacs is waiting
865 ;; for input, we must not leave a different buffer current. We
866 ;; can't rely on the editor command loop to reselect the
867 ;; selected window's buffer.
868 (save-excursion
869 (let ((frame (make-frame Man-frame-parameters)))
870 (set-window-buffer (frame-selected-window frame) man-buffer)
871 (set-window-dedicated-p (frame-selected-window frame) t)
872 (or (display-multi-frame-p frame)
873 (select-frame frame)))))
874 ((eq Man-notify-method 'pushy)
875 (switch-to-buffer man-buffer))
876 ((eq Man-notify-method 'bully)
877 (and (frame-live-p saved-frame)
878 (select-frame saved-frame))
879 (pop-to-buffer man-buffer)
880 (delete-other-windows))
881 ((eq Man-notify-method 'aggressive)
882 (and (frame-live-p saved-frame)
883 (select-frame saved-frame))
884 (pop-to-buffer man-buffer))
885 ((eq Man-notify-method 'friendly)
886 (and (frame-live-p saved-frame)
887 (select-frame saved-frame))
888 (display-buffer man-buffer 'not-this-window))
889 ((eq Man-notify-method 'polite)
890 (beep)
891 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
892 ((eq Man-notify-method 'quiet)
893 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
894 ((or (eq Man-notify-method 'meek)
896 (message ""))
899 (defun Man-softhyphen-to-minus ()
900 ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
901 ;; least, emit it even when not in a Latin-N locale.
902 (unless (eq t (compare-strings "latin-" 0 nil
903 current-language-environment 0 6 t))
904 (goto-char (point-min))
905 (let ((str "\255"))
906 (if enable-multibyte-characters
907 (setq str (string-as-multibyte str)))
908 (while (search-forward str nil t) (replace-match "-")))))
910 (defun Man-fontify-manpage ()
911 "Convert overstriking and underlining to the correct fonts.
912 Same for the ANSI bold and normal escape sequences."
913 (interactive)
914 (message "Please wait: formatting the %s man page..." Man-arguments)
915 (goto-char (point-min))
916 ;; Fontify ANSI escapes.
917 (let ((faces nil)
918 (buffer-undo-list t)
919 (start (point)))
920 ;; http://www.isthe.com/chongo/tech/comp/ansi_escapes.html
921 ;; suggests many codes, but we only handle:
922 ;; ESC [ 00 m reset to normal display
923 ;; ESC [ 01 m bold
924 ;; ESC [ 04 m underline
925 ;; ESC [ 07 m reverse-video
926 ;; ESC [ 22 m no-bold
927 ;; ESC [ 24 m no-underline
928 ;; ESC [ 27 m no-reverse-video
929 (while (re-search-forward "\e\\[0?\\([1470]\\|2\\([247]\\)\\)m" nil t)
930 (if faces (put-text-property start (match-beginning 0) 'face
931 (if (cdr faces) faces (car faces))))
932 (setq faces
933 (cond
934 ((match-beginning 2)
935 (delq (case (char-after (match-beginning 2))
936 (?2 Man-overstrike-face)
937 (?4 Man-underline-face)
938 (?7 Man-reverse-face))
939 faces))
940 ((eq (char-after (match-beginning 1)) ?0) nil)
942 (cons (case (char-after (match-beginning 1))
943 (?1 Man-overstrike-face)
944 (?4 Man-underline-face)
945 (?7 Man-reverse-face))
946 faces))))
947 (delete-region (match-beginning 0) (match-end 0))
948 (setq start (point))))
949 ;; Other highlighting.
950 (let ((buffer-undo-list t))
951 (if (< (buffer-size) (position-bytes (point-max)))
952 ;; Multibyte characters exist.
953 (progn
954 (goto-char (point-min))
955 (while (search-forward "__\b\b" nil t)
956 (backward-delete-char 4)
957 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
958 (goto-char (point-min))
959 (while (search-forward "\b\b__" nil t)
960 (backward-delete-char 4)
961 (put-text-property (1- (point)) (point) 'face Man-underline-face))))
962 (goto-char (point-min))
963 (while (search-forward "_\b" nil t)
964 (backward-delete-char 2)
965 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
966 (goto-char (point-min))
967 (while (search-forward "\b_" nil t)
968 (backward-delete-char 2)
969 (put-text-property (1- (point)) (point) 'face Man-underline-face))
970 (goto-char (point-min))
971 (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
972 (replace-match "\\1")
973 (put-text-property (1- (point)) (point) 'face Man-overstrike-face))
974 (goto-char (point-min))
975 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
976 (replace-match "o")
977 (put-text-property (1- (point)) (point) 'face 'bold))
978 (goto-char (point-min))
979 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
980 (replace-match "+")
981 (put-text-property (1- (point)) (point) 'face 'bold))
982 (goto-char (point-min))
983 ;; Try to recognize common forms of cross references.
984 (Man-highlight-references)
985 (Man-softhyphen-to-minus)
986 (goto-char (point-min))
987 (while (re-search-forward Man-heading-regexp nil t)
988 (put-text-property (match-beginning 0)
989 (match-end 0)
990 'face Man-overstrike-face)))
991 (message "%s man page formatted" Man-arguments))
993 (defun Man-highlight-references (&optional xref-man-type)
994 "Highlight the references on mouse-over.
995 References include items in the SEE ALSO section,
996 header file (#include <foo.h>), and files in FILES.
997 If optional argument XREF-MAN-TYPE is non-nil, it used as the
998 button type for items in SEE ALSO section. If it is nil, the
999 default type, `Man-xref-man-page' is used for the buttons."
1000 ;; `Man-highlight-references' is used from woman.el, too.
1001 ;; woman.el doesn't set `Man-arguments'.
1002 (unless Man-arguments
1003 (setq Man-arguments ""))
1004 (if (string-match "-k " Man-arguments)
1005 (progn
1006 (Man-highlight-references0 nil Man-reference-regexp 1
1007 'Man-default-man-entry
1008 (or xref-man-type 'Man-xref-man-page))
1009 (Man-highlight-references0 nil Man-apropos-regexp 1
1010 'Man-default-man-entry
1011 (or xref-man-type 'Man-xref-man-page)))
1012 (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
1013 'Man-default-man-entry
1014 (or xref-man-type 'Man-xref-man-page))
1015 (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
1016 'Man-xref-header-file)
1017 (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
1018 'Man-xref-normal-file)))
1020 (defun Man-highlight-references0 (start-section regexp button-pos target type)
1021 ;; Based on `Man-build-references-alist'
1022 (when (or (null start-section)
1023 (Man-find-section start-section))
1024 (let ((end (if start-section
1025 (progn
1026 (forward-line 1)
1027 (back-to-indentation)
1028 (save-excursion
1029 (Man-next-section 1)
1030 (point)))
1031 (goto-char (point-min))
1032 nil)))
1033 (while (re-search-forward regexp end t)
1034 (make-text-button
1035 (match-beginning button-pos)
1036 (match-end button-pos)
1037 'type type
1038 'Man-target-string (cond
1039 ((numberp target)
1040 (match-string target))
1041 ((functionp target)
1042 target)
1043 (t nil)))))))
1045 (defun Man-cleanup-manpage (&optional interactive)
1046 "Remove overstriking and underlining from the current buffer.
1047 Normally skip any jobs that should have been done by the sed script,
1048 but when called interactively, do those jobs even if the sed
1049 script would have done them."
1050 (interactive "p")
1051 (message "Please wait: cleaning up the %s man page..."
1052 Man-arguments)
1053 (if (or interactive (not Man-sed-script))
1054 (progn
1055 (goto-char (point-min))
1056 (while (search-forward "_\b" nil t) (backward-delete-char 2))
1057 (goto-char (point-min))
1058 (while (search-forward "\b_" nil t) (backward-delete-char 2))
1059 (goto-char (point-min))
1060 (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
1061 (replace-match "\\1"))
1062 (goto-char (point-min))
1063 (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
1064 (goto-char (point-min))
1065 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
1067 (goto-char (point-min))
1068 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
1069 (Man-softhyphen-to-minus)
1070 (message "%s man page cleaned up" Man-arguments))
1072 (defun Man-bgproc-sentinel (process msg)
1073 "Manpage background process sentinel.
1074 When manpage command is run asynchronously, PROCESS is the process
1075 object for the manpage command; when manpage command is run
1076 synchronously, PROCESS is the name of the buffer where the manpage
1077 command is run. Second argument MSG is the exit message of the
1078 manpage command."
1079 (let ((Man-buffer (if (stringp process) (get-buffer process)
1080 (process-buffer process)))
1081 (delete-buff nil)
1082 (err-mess nil))
1084 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1085 (or (stringp process)
1086 (set-process-buffer process nil))
1088 (with-current-buffer Man-buffer
1089 (let ((case-fold-search nil))
1090 (goto-char (point-min))
1091 (cond ((or (looking-at "No \\(manual \\)*entry for")
1092 (looking-at "[^\n]*: nothing appropriate$"))
1093 (setq err-mess (buffer-substring (point)
1094 (progn
1095 (end-of-line) (point)))
1096 delete-buff t))
1097 ((or (stringp process)
1098 (not (and (eq (process-status process) 'exit)
1099 (= (process-exit-status process) 0))))
1100 (or (zerop (length msg))
1101 (progn
1102 (setq err-mess
1103 (concat (buffer-name Man-buffer)
1104 ": process "
1105 (let ((eos (1- (length msg))))
1106 (if (= (aref msg eos) ?\n)
1107 (substring msg 0 eos) msg))))
1108 (goto-char (point-max))
1109 (insert (format "\nprocess %s" msg))))
1111 (if delete-buff
1112 (kill-buffer Man-buffer)
1113 (if Man-fontify-manpage-flag
1114 (Man-fontify-manpage)
1115 (Man-cleanup-manpage))
1117 (run-hooks 'Man-cooked-hook)
1118 (Man-mode)
1120 (if (not Man-page-list)
1121 (let ((args Man-arguments))
1122 (kill-buffer (current-buffer))
1123 (error "Can't find the %s manpage" args)))
1125 (set-buffer-modified-p nil)
1127 ;; Restore case-fold-search before calling
1128 ;; Man-notify-when-ready because it may switch buffers.
1130 (if (not delete-buff)
1131 (Man-notify-when-ready Man-buffer))
1133 (if err-mess
1134 (error "%s" err-mess))
1135 ))))
1138 ;; ======================================================================
1139 ;; set up manual mode in buffer and build alists
1141 (put 'Man-mode 'mode-class 'special)
1143 (defun Man-mode ()
1144 "A mode for browsing Un*x manual pages.
1146 The following man commands are available in the buffer. Try
1147 \"\\[describe-key] <key> RET\" for more information:
1149 \\[man] Prompt to retrieve a new manpage.
1150 \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
1151 \\[Man-next-manpage] Jump to next manpage in circular list.
1152 \\[Man-previous-manpage] Jump to previous manpage in circular list.
1153 \\[Man-next-section] Jump to next manpage section.
1154 \\[Man-previous-section] Jump to previous manpage section.
1155 \\[Man-goto-section] Go to a manpage section.
1156 \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
1157 \\[Man-quit] Deletes the manpage window, bury its buffer.
1158 \\[Man-kill] Deletes the manpage window, kill its buffer.
1159 \\[describe-mode] Prints this help text.
1161 The following variables may be of some use. Try
1162 \"\\[describe-variable] <variable-name> RET\" for more information:
1164 `Man-notify-method' What happens when manpage formatting is done.
1165 `Man-downcase-section-letters-flag' Force section letters to lower case.
1166 `Man-circular-pages-flag' Treat multiple manpage list as circular.
1167 `Man-section-translations-alist' List of section numbers and their Un*x equiv.
1168 `Man-filter-list' Background manpage filter command.
1169 `Man-mode-map' Keymap bindings for Man mode buffers.
1170 `Man-mode-hook' Normal hook run on entry to Man mode.
1171 `Man-section-regexp' Regexp describing manpage section letters.
1172 `Man-heading-regexp' Regexp describing section headers.
1173 `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
1174 `Man-first-heading-regexp' Regexp for first heading on a manpage.
1175 `Man-reference-regexp' Regexp matching a references in SEE ALSO.
1176 `Man-switches' Background `man' command switches.
1178 The following key bindings are currently in effect in the buffer:
1179 \\{Man-mode-map}"
1180 (interactive)
1181 (kill-all-local-variables)
1182 (setq major-mode 'Man-mode
1183 mode-name "Man"
1184 buffer-auto-save-file-name nil
1185 mode-line-buffer-identification
1186 (list (default-value 'mode-line-buffer-identification)
1187 " {" 'Man-page-mode-string "}")
1188 truncate-lines t
1189 buffer-read-only t)
1190 (buffer-disable-undo)
1191 (auto-fill-mode -1)
1192 (use-local-map Man-mode-map)
1193 (set-syntax-table man-mode-syntax-table)
1194 (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
1195 (set (make-local-variable 'outline-regexp) Man-heading-regexp)
1196 (set (make-local-variable 'outline-level) (lambda () 1))
1197 (Man-build-page-list)
1198 (Man-strip-page-headers)
1199 (Man-unindent)
1200 (Man-goto-page 1 t)
1201 (run-mode-hooks 'Man-mode-hook))
1203 (defsubst Man-build-section-alist ()
1204 "Build the association list of manpage sections."
1205 (setq Man-sections-alist nil)
1206 (goto-char (point-min))
1207 (let ((case-fold-search nil))
1208 (while (re-search-forward Man-heading-regexp (point-max) t)
1209 (aput 'Man-sections-alist (match-string 1))
1210 (forward-line 1))))
1212 (defsubst Man-build-references-alist ()
1213 "Build the association list of references (in the SEE ALSO section)."
1214 (setq Man-refpages-alist nil)
1215 (save-excursion
1216 (if (Man-find-section Man-see-also-regexp)
1217 (let ((start (progn (forward-line 1) (point)))
1218 (end (progn
1219 (Man-next-section 1)
1220 (point)))
1221 hyphenated
1222 (runningpoint -1))
1223 (save-restriction
1224 (narrow-to-region start end)
1225 (goto-char (point-min))
1226 (back-to-indentation)
1227 (while (and (not (eobp)) (/= (point) runningpoint))
1228 (setq runningpoint (point))
1229 (if (re-search-forward Man-hyphenated-reference-regexp end t)
1230 (let* ((word (match-string 0))
1231 (len (1- (length word))))
1232 (if hyphenated
1233 (setq word (concat hyphenated word)
1234 hyphenated nil
1235 ;; Update len, in case a reference spans
1236 ;; more than two lines (paranoia).
1237 len (1- (length word))))
1238 (if (memq (aref word len) '(?- ?­))
1239 (setq hyphenated (substring word 0 len)))
1240 (if (string-match Man-reference-regexp word)
1241 (aput 'Man-refpages-alist word))))
1242 (skip-chars-forward " \t\n,"))))))
1243 (setq Man-refpages-alist (nreverse Man-refpages-alist)))
1245 (defun Man-build-page-list ()
1246 "Build the list of separate manpages in the buffer."
1247 (setq Man-page-list nil)
1248 (let ((page-start (point-min))
1249 (page-end (point-max))
1250 (header ""))
1251 (goto-char page-start)
1252 ;; (switch-to-buffer (current-buffer))(debug)
1253 (while (not (eobp))
1254 (setq header
1255 (if (looking-at Man-page-header-regexp)
1256 (match-string 1)
1257 nil))
1258 ;; Go past both the current and the next Man-first-heading-regexp
1259 (if (re-search-forward Man-first-heading-regexp nil 'move 2)
1260 (let ((p (progn (beginning-of-line) (point))))
1261 ;; We assume that the page header is delimited by blank
1262 ;; lines and that it contains at most one blank line. So
1263 ;; if we back by three blank lines we will be sure to be
1264 ;; before the page header but not before the possible
1265 ;; previous page header.
1266 (search-backward "\n\n" nil t 3)
1267 (if (re-search-forward Man-page-header-regexp p 'move)
1268 (beginning-of-line))))
1269 (setq page-end (point))
1270 (setq Man-page-list (append Man-page-list
1271 (list (list (copy-marker page-start)
1272 (copy-marker page-end)
1273 header))))
1274 (setq page-start page-end)
1277 (defun Man-strip-page-headers ()
1278 "Strip all the page headers but the first from the manpage."
1279 (let ((inhibit-read-only t)
1280 (case-fold-search nil)
1281 (header ""))
1282 (dolist (page Man-page-list)
1283 (and (nth 2 page)
1284 (goto-char (car page))
1285 (re-search-forward Man-first-heading-regexp nil t)
1286 (setq header (buffer-substring (car page) (match-beginning 0)))
1287 ;; Since the awk script collapses all successive blank
1288 ;; lines into one, and since we don't want to get rid of
1289 ;; the fast awk script, one must choose between adding
1290 ;; spare blank lines between pages when there were none and
1291 ;; deleting blank lines at page boundaries when there were
1292 ;; some. We choose the first, so we comment the following
1293 ;; line.
1294 ;; (setq header (concat "\n" header)))
1295 (while (search-forward header (nth 1 page) t)
1296 (replace-match ""))))))
1298 (defun Man-unindent ()
1299 "Delete the leading spaces that indent the manpage."
1300 (let ((inhibit-read-only t)
1301 (case-fold-search nil))
1302 (dolist (page Man-page-list)
1303 (let ((indent "")
1304 (nindent 0))
1305 (narrow-to-region (car page) (car (cdr page)))
1306 (if Man-uses-untabify-flag
1307 (untabify (point-min) (point-max)))
1308 (if (catch 'unindent
1309 (goto-char (point-min))
1310 (if (not (re-search-forward Man-first-heading-regexp nil t))
1311 (throw 'unindent nil))
1312 (beginning-of-line)
1313 (setq indent (buffer-substring (point)
1314 (progn
1315 (skip-chars-forward " ")
1316 (point))))
1317 (setq nindent (length indent))
1318 (if (zerop nindent)
1319 (throw 'unindent nil))
1320 (setq indent (concat indent "\\|$"))
1321 (goto-char (point-min))
1322 (while (not (eobp))
1323 (if (looking-at indent)
1324 (forward-line 1)
1325 (throw 'unindent nil)))
1326 (goto-char (point-min)))
1327 (while (not (eobp))
1328 (or (eolp)
1329 (delete-char nindent))
1330 (forward-line 1)))
1331 ))))
1334 ;; ======================================================================
1335 ;; Man mode commands
1337 (defun Man-next-section (n)
1338 "Move point to Nth next section (default 1)."
1339 (interactive "p")
1340 (let ((case-fold-search nil)
1341 (start (point)))
1342 (if (looking-at Man-heading-regexp)
1343 (forward-line 1))
1344 (if (re-search-forward Man-heading-regexp (point-max) t n)
1345 (beginning-of-line)
1346 (goto-char (point-max))
1347 ;; The last line doesn't belong to any section.
1348 (forward-line -1))
1349 ;; But don't move back from the starting point (can happen if `start'
1350 ;; is somewhere on the last line).
1351 (if (< (point) start) (goto-char start))))
1353 (defun Man-previous-section (n)
1354 "Move point to Nth previous section (default 1)."
1355 (interactive "p")
1356 (let ((case-fold-search nil))
1357 (if (looking-at Man-heading-regexp)
1358 (forward-line -1))
1359 (if (re-search-backward Man-heading-regexp (point-min) t n)
1360 (beginning-of-line)
1361 (goto-char (point-min)))))
1363 (defun Man-find-section (section)
1364 "Move point to SECTION if it exists, otherwise don't move point.
1365 Returns t if section is found, nil otherwise."
1366 (let ((curpos (point))
1367 (case-fold-search nil))
1368 (goto-char (point-min))
1369 (if (re-search-forward (concat "^" section) (point-max) t)
1370 (progn (beginning-of-line) t)
1371 (goto-char curpos)
1372 nil)
1375 (defun Man-goto-section ()
1376 "Query for section to move point to."
1377 (interactive)
1378 (aput 'Man-sections-alist
1379 (let* ((default (aheadsym Man-sections-alist))
1380 (completion-ignore-case t)
1381 chosen
1382 (prompt (concat "Go to section (default " default "): ")))
1383 (setq chosen (completing-read prompt Man-sections-alist))
1384 (if (or (not chosen)
1385 (string= chosen ""))
1386 default
1387 chosen)))
1388 (Man-find-section (aheadsym Man-sections-alist)))
1390 (defun Man-goto-see-also-section ()
1391 "Move point to the \"SEE ALSO\" section.
1392 Actually the section moved to is described by `Man-see-also-regexp'."
1393 (interactive)
1394 (if (not (Man-find-section Man-see-also-regexp))
1395 (error "%s" (concat "No " Man-see-also-regexp
1396 " section found in the current manpage"))))
1398 (defun Man-possibly-hyphenated-word ()
1399 "Return a possibly hyphenated word at point.
1400 If the word starts at the first non-whitespace column, and the
1401 previous line ends with a hyphen, return the last word on the previous
1402 line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
1403 as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
1404 \"tcgetp-\" instead of \"grp\"."
1405 (save-excursion
1406 (skip-syntax-backward "w()")
1407 (skip-chars-forward " \t")
1408 (let ((beg (point))
1409 (word (current-word)))
1410 (when (eq beg (save-excursion
1411 (back-to-indentation)
1412 (point)))
1413 (end-of-line 0)
1414 (if (eq (char-before) ?-)
1415 (setq word (current-word))))
1416 word)))
1418 (defun Man-follow-manual-reference (reference)
1419 "Get one of the manpages referred to in the \"SEE ALSO\" section.
1420 Specify which REFERENCE to use; default is based on word at point."
1421 (interactive
1422 (if (not Man-refpages-alist)
1423 (error "There are no references in the current man page")
1424 (list
1425 (let* ((default (or
1426 (car (all-completions
1427 (let ((word
1428 (or (Man-possibly-hyphenated-word)
1429 "")))
1430 ;; strip a trailing '-':
1431 (if (string-match "-$" word)
1432 (substring word 0
1433 (match-beginning 0))
1434 word))
1435 Man-refpages-alist))
1436 (aheadsym Man-refpages-alist)))
1437 (defaults
1438 (mapcar 'substring-no-properties
1439 (delete-dups
1440 (delq nil (cons default
1441 (mapcar 'car Man-refpages-alist))))))
1442 chosen
1443 (prompt (concat "Refer to (default " default "): ")))
1444 (setq chosen (completing-read prompt Man-refpages-alist
1445 nil nil nil nil defaults))
1446 (if (or (not chosen)
1447 (string= chosen ""))
1448 default
1449 chosen)))))
1450 (if (not Man-refpages-alist)
1451 (error "Can't find any references in the current manpage")
1452 (aput 'Man-refpages-alist reference)
1453 (Man-getpage-in-background
1454 (Man-translate-references (aheadsym Man-refpages-alist)))))
1456 (defun Man-kill ()
1457 "Kill the buffer containing the manpage."
1458 (interactive)
1459 (quit-window t))
1461 (defun Man-quit ()
1462 "Bury the buffer containing the manpage."
1463 (interactive)
1464 (quit-window))
1466 (defun Man-goto-page (page &optional noerror)
1467 "Go to the manual page on page PAGE."
1468 (interactive
1469 (if (not Man-page-list)
1470 (error "Not a man page buffer")
1471 (if (= (length Man-page-list) 1)
1472 (error "You're looking at the only manpage in the buffer")
1473 (list (read-minibuffer (format "Go to manpage [1-%d]: "
1474 (length Man-page-list)))))))
1475 (if (and (not Man-page-list) (not noerror))
1476 (error "Not a man page buffer"))
1477 (when Man-page-list
1478 (if (or (< page 1)
1479 (> page (length Man-page-list)))
1480 (error "No manpage %d found" page))
1481 (let* ((page-range (nth (1- page) Man-page-list))
1482 (page-start (car page-range))
1483 (page-end (car (cdr page-range))))
1484 (setq Man-current-page page
1485 Man-page-mode-string (Man-make-page-mode-string))
1486 (widen)
1487 (goto-char page-start)
1488 (narrow-to-region page-start page-end)
1489 (Man-build-section-alist)
1490 (Man-build-references-alist)
1491 (goto-char (point-min)))))
1494 (defun Man-next-manpage ()
1495 "Find the next manpage entry in the buffer."
1496 (interactive)
1497 (if (= (length Man-page-list) 1)
1498 (error "This is the only manpage in the buffer"))
1499 (if (< Man-current-page (length Man-page-list))
1500 (Man-goto-page (1+ Man-current-page))
1501 (if Man-circular-pages-flag
1502 (Man-goto-page 1)
1503 (error "You're looking at the last manpage in the buffer"))))
1505 (defun Man-previous-manpage ()
1506 "Find the previous manpage entry in the buffer."
1507 (interactive)
1508 (if (= (length Man-page-list) 1)
1509 (error "This is the only manpage in the buffer"))
1510 (if (> Man-current-page 1)
1511 (Man-goto-page (1- Man-current-page))
1512 (if Man-circular-pages-flag
1513 (Man-goto-page (length Man-page-list))
1514 (error "You're looking at the first manpage in the buffer"))))
1516 ;; Header file support
1517 (defun Man-view-header-file (file)
1518 "View a header file specified by FILE from `Man-header-file-path'."
1519 (let ((path Man-header-file-path)
1520 complete-path)
1521 (while path
1522 (setq complete-path (expand-file-name file (car path))
1523 path (cdr path))
1524 (if (file-readable-p complete-path)
1525 (progn (view-file complete-path)
1526 (setq path nil))
1527 (setq complete-path nil)))
1528 complete-path))
1530 ;; Init the man package variables, if not already done.
1531 (Man-init-defvars)
1533 (add-to-list 'debug-ignored-errors "^No manpage [0-9]* found$")
1534 (add-to-list 'debug-ignored-errors "^Can't find the .* manpage$")
1536 (provide 'man)
1538 ;; arch-tag: 587cda76-8e23-4594-b1f3-89b6b09a0d47
1539 ;;; man.el ends here