Initial Commit
[packages] / xemacs-packages / edit-utils / man.el
1 ;;; man.el --- browse UNIX manual pages
2 ;; Keywords: help
3
4 ;; Copyright (C) 1985, 1993, 1994, 1996, 1997 Free Software Foundation, Inc.
5 ;;
6 ;; This file is part of XEmacs.
7
8 ;; XEmacs is free software; you can redistribute it and/or modify it
9 ;; under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; XEmacs is distributed in the hope that it will be useful, but
14 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 ;; General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
20 ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 ;; This file defines "manual-entry", and the remaining definitions all
23 ;; begin with "Manual-".  This makes the autocompletion on "M-x man" work.
24 ;;
25 ;; Eviscerated 26-Jun-96 by Jamie Zawinski <jwz@jwz.org>.
26 ;; All that stuff about looking at $MANPATH and building up lists of
27 ;; directories was bullshit.  Now we just invoke "man" and format the
28 ;; output, end of story.
29 ;;
30 ;; [ older changelog entries removed, since they're all about code that
31 ;;   I've deleted. ]
32
33 (defgroup man nil
34   "Browse Unix manual pages"
35   :group 'help)
36
37 (defcustom Manual-program "man" "\
38 *Name of the program to invoke in order to format the source man pages."
39   :type 'string
40   :group 'man)
41
42 (defcustom Manual-buffer-view-mode t "\
43 *Whether manual buffers should be placed in view-mode.
44 nil means leave the buffer in fundamental-mode in another window.
45 t means use `view-buffer' to display the man page in the current window.
46 Any other value means use `view-buffer-other-window'."
47   :type '(radio (const :tag "Fundamental-mode other window" nil)
48                 (const :tag "View-mode current window" t)
49                 (sexp :format "%t\n" :tag "View-mode other window" other))
50   :group 'man)
51
52 (defcustom Manual-switches nil
53   "List of switches to the man program."
54   :type '(choice (const :tag "none" nil) 
55                  (repeat (string :tag "switch"))) 
56   :group 'man)
57
58 (defcustom Manual-mode-hook nil
59   "Function or functions run on entry to Manual-mode."
60   :type 'hook
61   :group 'man)
62
63 (defvar Manual-page-history nil "\
64 A list of names of previously visited man page buffers.")
65
66 (defvar Manual-page-minibuffer-history nil "\
67 Minibuffer completion history for `manual-entry'.")
68
69 ;; New variables.
70
71 (defcustom Manual-snip-subchapter
72   (not (string-match "solaris" system-configuration))
73   "*Should man look in chapter 3 for ctime(3c)?
74 This is relevant for Solaris and, perhaps, other systems which have
75 `man -s 3' not find things in chapter 3c, or other such sub-chapters"
76   :type 'boolean
77   :group 'man)
78
79 ;;Here is information on RosettaMan, from Neal.Becker@comsat.com (Neal Becker):
80
81 ;;RosettaMan is a filter for UNIX manual pages.  It takes as input man
82 ;;pages formatted for a variety of UNIX flavors (not [tn]roff source)
83 ;;and produces as output a variety of file formats.  Currently
84 ;;RosettaMan accepts man pages as formatted by the following flavors of
85 ;;UNIX: Hewlett-Packard HP-UX, AT&T System V, SunOS, Sun Solaris, OSF/1,
86 ;;DEC Ultrix, SGI IRIX, Linux, SCO; and produces output for the following
87 ;;formats: printable ASCII only (stripping page headers and footers),
88 ;;section and subsection headers only, TkMan, [tn]roff, Ensemble, RTF,
89 ;;SGML (soon--I finally found a DTD), HTML, MIME, LaTeX, LaTeX 2e, Perl 5's pod.
90
91 ;;RosettaMan improves on other man page filters in several ways: (1) its
92 ;;analysis recognizes the structural pieces of man pages, enabling high
93 ;;quality output, (2) its modular structure permits easy augmentation of
94 ;;output formats, (3) it accepts man pages formatted with the varient
95 ;;macros of many different flavors of UNIX, and (4) it doesn't require
96 ;;modification or cooperation with any other program.
97
98 ;;RosettaMan is a rewrite of TkMan's man page filter, called bs2tk.  (If
99 ;;you haven't heard about TkMan, a hypertext man page browser, you
100 ;;should grab it via anonymous ftp from ftp.cs.berkeley.edu:
101 ;;/ucb/people/phelps/tkman.tar.Z.)  Whereas bs2tk generated output only for
102 ;;TkMan, RosettaMan generalizes the process so that the analysis can be
103 ;;leveraged to new output formats.  A single analysis engine recognizes
104 ;;section heads, subsection heads, body text, lists, references to other
105 ;;man pages, boldface, italics, bold italics, special characters (like
106 ;;bullets), tables (to a degree) and strips out page headers and
107 ;;footers.  The engine sends signals to the selected output functions so
108 ;;that an enhancement in the engine improves the quality of output of
109 ;;all of them.  Output format functions are easy to add, and thus far
110 ;;average about about 75 lines of C code each.
111
112
113
114 ;;*** NOTES ON CURRENT VERSION ***
115
116 ;;Help!  I'm looking for people to help with the following projects.
117 ;;\(1) Better RTF output format.  The current one works, but could be
118 ;;made better.  (2) Roff macros that produce text that is easily
119 ;;parsable.  RosettaMan handles a great variety, but some things, like
120 ;;H-P's tables, are intractable.  If you write an output format or
121 ;;otherwise improve RosettaMan, please send in your code so that I may
122 ;;share the wealth in future releases.
123
124 ;;This version can try to identify tables (turn this on with the -T
125 ;;switch) by looking for lines with a large amount of interword spacing,
126 ;;reasoning that this is space between columns of a table.  This
127 ;;heuristic doesn't always work and sometimes misidentifies ordinary
128 ;;text as tables.  In general I think it is impossible to perfectly
129 ;;identify tables from nroff formatted text.  However, I do think the
130 ;;heuristics can be tuned, so if you have a collection of manual pages
131 ;;with unrecognized tables, send me the lot, in formatted form (i.e.,
132 ;;after formatting with nroff -man), and uuencode them to preserve the
133 ;;control characters.  Better, if you can think of heuristics that
134 ;;distinguish tables from ordinary text, I'd like to hear them.
135
136 ;;Notes for HTML consumers: This filter does real (heuristic)
137 ;;parsing--no <PRE>!  Man page references are turned into hypertext links.
138
139 (defcustom Manual-use-rosetta-man (locate-file "rman" exec-path)
140   "If non-nil, use RosettaMan (rman) to filter man pages.
141 This makes man-page cleanup virtually instantaneous, instead of
142 potentially taking a long time."
143   :type '(choice (symbol :tag "Do not use Rosettaman" nil)
144                  (file   :tag "RosettaMan Programm"))
145   :group 'man)
146
147 (defface man-italic '((t (:italic t)))
148   "Manual italics face"
149   :group 'man)
150
151 (defface man-bold '((t (:bold t)))
152   "Manual bold face"
153   :group 'man)
154
155 (defface man-heading '((t (:bold t)))
156   "Manual headings face"
157   :group 'man)
158
159 (defface man-xref '((t (:underline t)))
160   "Manual xrefs face"
161   :group 'man)
162
163
164 (defvar Manual-mode-map
165   (let ((m (make-sparse-keymap)))
166     (set-keymap-name m 'Manual-mode-map)
167     (define-key m "l" 'Manual-last-page)
168     (define-key m 'button2 'Manual-follow-xref)
169     (define-key m 'button3 'Manual-popup-menu)
170     m))
171
172 (defvar Manual-mode-syntax-table nil
173   "Syntax table used in Manual-mode buffers")
174 (if Manual-mode-syntax-table
175     ()
176   (setq Manual-mode-syntax-table (make-syntax-table))
177   (modify-syntax-entry ?: "_" Manual-mode-syntax-table)
178   (modify-syntax-entry ?+ "." Manual-mode-syntax-table)
179   (modify-syntax-entry ?- "." Manual-mode-syntax-table)
180   (modify-syntax-entry ?/ "." Manual-mode-syntax-table)
181   (modify-syntax-entry ?* "." Manual-mode-syntax-table)
182   )
183
184 ;;;###autoload
185 (defun manual-entry (topic &optional arg silent)
186   "Display the Unix manual entry (or entries) for TOPIC.
187 If TOPIC starts with -k, then a system apropos search is performed
188 using man -k for TOPIC."
189   (interactive
190    (list (let* ((default (save-excursion
191                            (buffer-substring
192                             (progn
193                               (if (not (eobp))
194                                   (forward-char))
195                               (if (re-search-backward "\\sw\\|\\s_" nil t)
196                                   (forward-char))
197                               (re-search-backward
198                                "\\(\\sw\\|\\s_\\)([0-9]+[A-Za-z]*\\="
199                                (point-at-bol) t)
200                               (skip-syntax-backward "w_")
201                               (point))
202                             (progn
203                               (skip-syntax-forward "w_")
204                               (re-search-forward "\\=([0-9]+[A-Za-z]*)" nil t)
205                               (point) ))))
206                 (thing (read-string
207                         (if (equal default "") "Manual entry: "
208                           (concat "Manual entry: (default " default ") "))
209                         nil 'Manual-page-minibuffer-history)))
210            (if (equal thing "") default thing))
211          (prefix-numeric-value current-prefix-arg)))
212   (let (buffer)
213     (or arg (setq arg 1))
214     ;; Allow leading chapter numbers
215     (if (string-match "\\([1-9n][a-zA-Z0-9]*\\) \\(.*\\)" topic)
216         (setq topic (replace-match "\\2(\\1)" t nil topic))
217       )
218     (let (section apropos-mode)
219       (let ((case-fold-search nil))
220         (if (and (null section)
221                  (string-match
222                   "\\`[ \t]*\\([^( \t]+\\)[ \t]*(\\(.+\\))[ \t]*\\'"
223                   topic))
224             (setq section (match-string 2 topic)
225                   topic (match-string 1 topic))
226           (if (string-match "\\`[ \t]*-k[ \t]+\\([^ \t]+\\)\\'" topic)
227               (setq section "-k"
228                     topic (substring topic (match-beginning 1))))))
229
230       (when Manual-snip-subchapter
231         ;; jwz: turn section "3x11" and "3n" into "3".
232         (if (and section (string-match "\\`\\([0-9]+\\)[^0-9]" section))
233             (setq section (match-string 1 section))))
234
235       (if (or (equal section "-k") (member "-k" Manual-switches))
236           (setq apropos-mode t))
237
238       (let ((bufname (concat "Man"
239                              (when apropos-mode " apropos")
240                              ": " topic
241                              (when section (concat "(" section ")"))))
242             (temp-buffer-show-function
243              (cond ((eq 't Manual-buffer-view-mode)
244                     'view-buffer)
245                    ((eq 'nil Manual-buffer-view-mode)
246                     temp-buffer-show-function)
247                    (t
248                     'view-buffer-other-window))))
249
250         (cond ((get-buffer bufname)
251                ;; reselect an old man page buffer if it exists already.
252                (save-excursion
253                  (set-buffer (get-buffer bufname))
254                  (Manual-mode)
255                  (setq buffer (current-buffer)))
256                (if temp-buffer-show-function
257                    (funcall temp-buffer-show-function (get-buffer bufname))
258                  (display-buffer bufname)))
259               (t
260                (with-output-to-temp-buffer bufname
261                  (buffer-disable-undo standard-output)
262                  (save-excursion
263                    (set-buffer standard-output)
264                    (setq buffer-read-only nil)
265                    (erase-buffer)
266
267                    (let ((args (append Manual-switches (list topic)))
268                          args-string)
269                      (if section
270                          (setq args
271                                (if (and (eq system-type 'usg-unix-v)
272                                         (null apropos-mode))
273                                    (cons "-s" (cons section args))
274                                  (cons section args))))
275                      (setq args-string
276                            (mapconcat 'identity
277                                       (cons Manual-program args) " "))
278                      (if (string-match "\\`\\([^ \t/]*/\\)+" args-string)
279                          (setq args-string
280                                (substring args-string (match-end 0))))
281
282                      (message "%s (running...)" args-string)
283                      (apply 'call-process Manual-program nil '(t nil) nil args)
284
285                      (if (< (buffer-size) (if apropos-mode 20 200))
286                          (progn
287                            (kill-buffer (current-buffer))
288                            (error "%s not found" args-string)))
289
290                      (message "%s (cleaning...)" args-string)
291                      (Manual-nuke-nroff-bs apropos-mode)
292                      (message "%s (done.)" args-string))
293                    (set-buffer-modified-p nil)
294                    (Manual-mode)
295                    (setq buffer (current-buffer))))))
296         (let ((page (if section
297                         (concat topic "(" section ")")
298                       topic)))
299           (setq Manual-page-history
300                 (cons (buffer-name)
301                       (delete (buffer-name) Manual-page-history))
302                 Manual-page-minibuffer-history
303                 (cons page (delete page Manual-page-minibuffer-history))))))
304
305     (message nil)
306   buffer))
307
308 ;;;###autoload
309 (define-key help-map "\C-m" 'manual-entry)
310
311 (defun Manual-mode ()
312   (kill-all-local-variables)
313   (setq buffer-read-only t)
314   (use-local-map Manual-mode-map)
315   (set-syntax-table Manual-mode-syntax-table)
316   (setq major-mode 'Manual-mode
317         mode-name "Manual")
318   ;; man pages with long lines are buggy!
319   ;; This looks slightly better if they only
320   ;; overran by a couple of chars.
321   (setq truncate-lines t)
322   ;; turn off horizontal scrollbars in this buffer
323   (when (featurep 'scrollbar)
324     (set-specifier scrollbar-height (cons (current-buffer) 0)))
325   (make-local-hook 'kill-buffer-hook)
326   (add-hook 'kill-buffer-hook #'(lambda ()
327                                   (setq Manual-page-history
328                                         (delete (buffer-name)
329                                                 Manual-page-history)))
330             nil t)
331   (run-hooks 'Manual-mode-hook))
332
333 (defun Manual-last-page ()
334   (interactive)
335   (if Manual-page-history
336       (let ((page (pop Manual-page-history)))
337         (if page
338             (progn
339               (get-buffer page)
340               (cons Manual-page-history page)
341               (switch-to-buffer page))))
342     (error "No manual page buffers found. Use `M-x manual-entry'")))
343
344
345 (defmacro Manual-delete-char (n)
346   ;; in v19, delete-char is compiled as a function call, but delete-region
347   ;; is byte-coded, so it's much faster.  (We were spending 40% of our time
348   ;; in delete-char alone.)
349   `(delete-region (point) (+ (point) ,n)))
350
351 ;; Hint: BS stands for more things than "back space"
352 ;;;###autoload
353 (defun Manual-nuke-nroff-bs (&optional apropos-mode)
354   (interactive "*")
355   (if (and Manual-use-rosetta-man (not apropos-mode))
356       (call-process-region (point-min) (point-max)
357                            Manual-use-rosetta-man t t nil)
358     ;;
359     ;; turn underlining into italics
360     ;;
361     (goto-char (point-min))
362     (while (search-forward "_\b" nil t)
363       ;; searching for underscore-backspace and then comparing the
364       ;; following chars until the sequence ends turns out to be much
365       ;; faster than searching for a regexp which matches the whole
366       ;; sequence.
367       (let ((s (match-beginning 0)))
368         (goto-char s)
369         (while (and (eq (char-after) ?_)
370                     (eq (char-after (1+ (point))) ?\b))
371           (Manual-delete-char 2)
372           (forward-char 1))
373         ;; The sequence _\b_ is ambiguous - it could be either
374         ;; underlining or overstriking.  We resolve the ambiguity as
375         ;; follows: if we appear to be creating a one-character extent
376         ;; containing only an underscore, we guess that this is
377         ;; actually a case of overstriking.  Even if we guess wrong,
378         ;; e.g. if the man page contained \fI_\fP, we'll merely end up
379         ;; using the wrong face (man-bold instead of man-italic).
380         (if (and (= (1+ s) (point))
381                  (eq (char-before) ?_))
382             (progn (backward-char) (insert ?_ ?\b)) ; undo
383           (set-extent-face (make-extent s (point)) 'man-italic))))
384     ;;
385     ;; turn overstriking into bold
386     ;;
387     (goto-char (point-min))
388     (while (search-forward "\b" nil t)
389       (when (eq (char-after) (char-after (- (point) 2)))
390         (backward-char 2)
391         (let ((start (point)))
392           (while (and (eq (char-after (1+ (point))) ?\b)
393                       (eq (char-after) (char-after (+ (point) 2))))
394             (let ((c (char-after)))
395               (forward-char)
396               ;; Some systems (SGI) overstrike multiple times, eg, "M\bM\bM\bM".
397               (while (and (eq (char-after ) ?\b)
398                           (eq (char-after (1+ (point))) c))
399                 (delete-region (point) (+ 2 (point))))))
400           (set-extent-face (make-extent start (point)) 'man-bold))))
401
402     ;; Kludge to deal with Japanese nroff formatted man pages.
403     ;; Usually width of Japanese characters is the same as two ASCII
404     ;; characters on a tty.  Therefore, nroff uses two \b.
405     ;; We guess that the sequence c\b\bc is an attempt at overstriking.
406     (goto-char (point-min))
407     (while (search-forward "\b\b" nil t)
408       (backward-char 3)
409       (while (and (eq (char-after (point)) (char-after (+ 3 (point))))
410                   (eq (char-after (+ 1 (point))) ?\b)
411                   (eq (char-after (+ 2 (point))) ?\b))
412         (delete-region (point) (+ (point) 3)))
413       (set-extent-face (make-extent (1- (point)) (point)) 'man-bold))
414
415     ;;
416     ;; hack bullets: o^H+ --> +
417     (goto-char (point-min))
418     (while (search-forward "\b" nil t)
419       (Manual-delete-char -2))
420
421     (Manual-nuke-nroff-bs-footers)
422     ) ;; not Manual-use-rosetta-man
423   ;;
424   ;; turn subsection header lines into bold
425   ;;
426   (goto-char (point-min))
427   (if apropos-mode
428       (while (re-search-forward "[a-zA-Z0-9] ([0-9]" nil t)
429         (forward-char -2)
430         (delete-backward-char 1))
431
432     ;;    (while (re-search-forward "^[^ \t\n]" nil t)
433     ;;      (set-extent-face (make-extent (match-beginning 0)
434     ;;                                   (progn (end-of-line) (point)))
435     ;;                      'man-heading))
436
437     ;; boldface the first line
438     (if (looking-at "[^ \t\n].*$")
439         (set-extent-face (make-extent (match-beginning 0) (match-end 0))
440                          'man-bold))
441
442     ;; boldface subsequent title lines
443     ;; Regexp to match section headers changed to match a non-indented
444     ;; line preceded by a blank line and followed by an indented line.
445     ;; This seems to work ok for manual pages but gives better results
446     ;; with other nroff'd files
447     ;;
448     ;; Most systems have indented text the next line after a section
449     ;; header, but some (Tru64) have an extra newline in between.
450     (while (re-search-forward "\n\n\\([^ \t\n].*\\)\n\n?[ \t]+[^ \t\n]" nil t)
451       (goto-char (match-end 1))
452       ;; section headings are often highlighted by the man page
453       ;; author, but other parts of the man page are highlighted the
454       ;; same way, so make our lisp-deduced section header
455       ;; highlighting higher priority.  This also avoids having
456       ;; section headers being _random_ly highlighted alternately by
457       ;; either man-heading or man-bold, which sure looks like a bug.
458       ;; And for user interface issues, if it looks like a bug, it
459       ;; _is_ a bug.
460       (set-extent-properties (make-extent (match-beginning 1) (match-end 1))
461                        '(face man-heading priority 1))
462       (forward-line 1))
463     )
464
465   (if Manual-use-rosetta-man
466       nil
467     ;; Zap ESC7,  ESC8, and ESC9
468     ;; This is for Sun man pages like "man 1 csh"
469     (goto-char (point-min))
470     (while (re-search-forward "\e[789]" nil t)
471       (replace-match "")))
472
473   (Manual-mouseify-xrefs apropos-mode)
474   )
475
476 ;;;###autoload
477 (defalias 'nuke-nroff-bs 'Manual-nuke-nroff-bs) ; use old name
478
479
480 (defun Manual-nuke-nroff-bs-footers ()
481   "For info see comments in packages/man.el"
482   ;; Autodetect and nuke headers and footers in nroff output.
483
484   (goto-char (point-min))
485
486   ;; first lose the status output
487   (let ((case-fold-search t))
488     (if (and (not (looking-at "[^\n]*warning"))
489              (looking-at "Reformatting.*\n"))
490         (delete-region (match-beginning 0) (match-end 0))))
491
492   ;; kludge around a groff bug where it won't keep quiet about some
493   ;; warnings even with -Wall or -Ww.
494   (cond ((looking-at "grotty:")
495          (while (looking-at "grotty:")
496            (delete-region (point) (progn (forward-line 1) (point))))
497          (if (looking-at " *done\n")
498              (delete-region (point) (match-end 0)))))
499
500   ;; Some implementations of man use nroff to produce "paginated"
501   ;; output with a page size of 66 lines, of which several are devoted
502   ;; to the header and footer.  Each header and footer consists of 3
503   ;; newlines, one informational line, and either 3 additional
504   ;; newlines in the case of Solaris nroff, or 2 additional newlines
505   ;; in the case of groff.
506   ;;
507   ;; Of course, pagination is an incredibly stupid idea for online
508   ;; information presentation instead of printing to real paper, and
509   ;; so some system vendors have chosen to improve on traditional
510   ;; behavior by providing non-paginated output. We conservatively
511   ;; autodetect whether the output is in fact paginated.  Misdetection
512   ;; is still possible, but highly unlikely.  For starters, the output
513   ;; from man must accidentally be a multiple of 66 lines.
514   ;;
515   ;; Note that if nroff spits out error messages, pages will be more
516   ;; than 66 lines high, and we'll misdetect page starts.  That's ok
517   ;; because standard nroff doesn't do any diagnostics, and the
518   ;; "gnroff" wrapper for groff turns off error messages for
519   ;; compatibility.  (At least, it's supposed to.)
520   (block nuke-headers-and-footers
521     (let* ((page-starts '())
522            (solaris-pagination          ; 66 - 2 * (3 + 1 + 3) = 52
523             "\\(\n\n\n[^\n]+\n\n\n\n\\)\\([^\n]*\n\\)\\{52\\}\\(\n\n\n[^\n]+\n\n\n\n\\)")
524            (groff-pagination            ; 66 - 2 * (3 + 1 + 2) = 54
525             "\\(\n\n\n[^\n]+\n\n\n\\)\\([^\n]*\n\\)\\{54\\}\\(\n\n\n[^\n]+\n\n\n\\)")
526            (pagination solaris-pagination))
527       ;; First pass.
528       ;; Collect the page start markers in reverse order.
529       ;; It's easiest to delete backwards starting from the end of the buffer.
530       ;; `page-starts' conveniently ends up in the desired reversed order.
531       ;; Verify that each header and footer looks like "\n\n\n[^\n]+\n\n\n\n?".
532       (while (not (eobp))
533         (when (not (looking-at pagination))
534           (setq pagination groff-pagination)
535           (when (not (looking-at pagination))
536             (return-from nuke-headers-and-footers)))
537         (push (point-marker) page-starts)
538         (goto-char (match-end 0)))
539
540       ;; Second pass.
541       ;; Delete all the headers and footers, except for the first and last one,
542       ;; since they do actually contain some useful information.
543       (dolist (page-start page-starts)
544         (goto-char page-start)
545         (looking-at pagination)         ; guaranteed to match, by first pass.
546
547         ;; Delete footers, except merely trim whitespace from the last one.
548         (if (= (match-end 0) (point-max))
549             (progn
550               ;; last footer
551               ;; Leave exactly two newlines before last footer.
552               (goto-char (match-beginning 3))
553               (skip-chars-backward "\n")
554               (forward-char 2)
555               (delete-region (point) (save-excursion
556                                        (skip-chars-forward "\n")
557                                        (point))))
558           (progn
559             ;; footer with adjoining header
560             (goto-char (match-beginning 3))
561             (delete-region (point) (match-end 3)) ; nuke footer
562             ;; Note: next page's header is already nuked, because
563             ;; we're processing the buffer backwards.
564             (save-match-data
565               (skip-chars-backward "\n")
566               (cond
567                ;; Compress multiple newlines where page breaks used to be.
568                ;; These happen if the man page has a "keep" that
569                ;; cannot spill over a page break, like a table.
570                ;; We simply compress multiple newlines to one.
571                ((looking-at "\n\n\n+")
572                 (delete-region (+ 2 (match-beginning 0)) (match-end 0)))
573                ;; There is no way to tell whether the page separator
574                ;; we've removed is a logical paragraph separator, so we
575                ;; guess with a simple heuristic that gets the newlines
576                ;; correct most of the time.  Section headers and option
577                ;; descriptions get a newline separator added.
578                ((looking-at "\n\\([^ \t\n]\\|[ \t]+-\\)")
579                 (insert ?\n))))))
580
581         ;; Delete headers, except merely trim whitespace from the first one.
582         (if (= page-start (point-min))
583             ;; Leave exactly two newlines between first header and body.
584             (delete-region (match-end 1)
585                            (save-excursion (goto-char (match-end 1))
586                                            (skip-chars-backward "\n")
587                                            (+ 2 (point))))
588           ;; Completely nuke non-initial headers
589           (delete-region (match-beginning 1) (match-end 1)))
590
591         (set-marker page-start nil))))  ; block nuke-headers-and-footers
592
593   ;; Delete newlines at beginning and end of buffer, whether or not
594   ;; man is feeding us 66-line paginated output.
595   ;; Tru64 is particularly generous with trailing newlines.
596   ;;
597   ;; Leave exactly one newline at end of buffer.
598   (goto-char (point-max))
599   (skip-chars-backward "\n")
600   (if (eobp)
601       (insert ?\n)
602     (delete-region (1+ (point)) (point-max)))
603   ;; Leave exactly zero newlines at beginning of buffer.
604   (delete-region (point-min)
605                  (save-excursion (goto-char (point-min))
606                                  (skip-chars-forward "\n")
607                                  (point)))
608   )
609
610 (defun Manual-mouseify-xrefs (&optional apropos-mode)
611   (goto-char (point-min))
612   ;; skip the top line of manual pages, but not apropos listings.
613   (unless apropos-mode (forward-line 1))
614   (let ((case-fold-search nil)
615         s e name splitp extent)
616     ;; possibly it would be faster to rewrite this expression to search for
617     ;; a less common sequence first (like "([0-9]") and then back up to see
618     ;; if it's really a match.  This function is 15% of the total time, 13%
619     ;; of which is this call to re-search-forward.
620     (while (re-search-forward "[a-zA-Z_][-a-zA-Z0-9_.:]*([0-9][a-zA-Z0-9]*)"
621                               nil t)
622       (setq s (match-beginning 0)
623             e (match-end 0)
624             name (buffer-substring s e)
625             splitp nil)
626
627       (goto-char s)
628       ;; if this is a hyphenated xref, we're on the second line, 1st char now.
629       (when (progn
630               (beginning-of-line)
631               (and (looking-at (concat "^[ \t]+" (regexp-quote name)))
632                    (progn
633                      (backward-char 1)
634                      (or (equal (char-before) ?-)
635                          (equal (char-before) ?\255)))
636                    (setq s (progn
637                              (skip-chars-backward "-\255_a-zA-Z0-9")
638                              (point))
639                          name (buffer-substring s e))))
640         (setq splitp t)
641         ;; delete the spaces and dash from `name'
642         (let (i)
643           (while (setq i (string-match "[-\255 \n\t]+" name i))
644             (setq name (concat (substring name 0 i)
645                                (substring name (match-end 0)))
646                   i (1+ i)))))
647
648       ;; if there are upper case letters in the section, downcase them.
649       (if (string-match "(.*[A-Z]+.*)$" name)
650           (setq name (concat (substring name 0 (match-beginning 0))
651                              (downcase (substring name (match-beginning 0))))))
652
653       ;; if the xref was hyphenated, don't highlight the indention spaces.
654       (if splitp
655           (progn
656             (setq extent (make-extent s (progn (goto-char s) (end-of-line) (point))))
657             (set-extent-property extent 'man (list 'Manual-follow-xref name))
658             (set-extent-property extent 'highlight t)
659             (set-extent-face extent 'man-xref)
660             (goto-char e)
661             (skip-chars-backward "-_a-zA-Z0-9()")
662             (setq extent (make-extent (point) e)))
663         (setq extent (make-extent s e)))
664       (set-extent-property extent 'man (list 'Manual-follow-xref name))
665       (set-extent-property extent 'highlight t)
666       (set-extent-face extent 'man-xref)
667       (goto-char e))))
668
669 (defun Manual-follow-xref (&optional name-or-event)
670   "Invoke `manual-entry' on the cross-reference under the mouse.
671 When invoked noninteractively, the arg may be an xref string to parse instead."
672   (interactive "e")
673   (if (eventp name-or-event)
674       (let* ((p (event-point name-or-event))
675              (extent (and p (extent-at p
676                              (event-buffer name-or-event)
677                              'highlight)))
678              (data (and extent (extent-property extent 'man))))
679         (if (eq (car-safe data) 'Manual-follow-xref)
680             (eval data)
681           (error "no manual cross-reference there.")))
682     (or (manual-entry name-or-event)
683         ;; If that didn't work, maybe it's in a different section than the
684         ;; man page writer expected.  For example, man pages tend assume
685         ;; that all user programs are in section 1, but X tends to generate
686         ;; makefiles that put things in section "n" instead...
687         (and (string-match "[ \t]*([^)]+)\\'" name-or-event)
688              (progn
689                (message "No entries found for %s; checking other sections..."
690                         name-or-event)
691                (manual-entry
692                 (substring name-or-event 0 (match-beginning 0))
693                 nil t))))))
694
695 (defun Manual-popup-menu (&optional event)
696   "Pops up a menu of cross-references in this manual page.
697 If there is a cross-reference under the mouse button which invoked this
698 command, it will be the first item on the menu.  Otherwise, they are
699 on the menu in the order in which they appear in the buffer."
700   (interactive "e")
701   (let ((buffer (current-buffer))
702         (sep "---")
703         xref items)
704     (cond (event
705            (setq buffer (event-buffer event))
706            (let* ((p (event-point event))
707                   (extent (and p (extent-at p buffer 'highlight)))
708                   (data (and extent (extent-property extent 'man))))
709              (if (eq (car-safe data) 'Manual-follow-xref)
710                  (setq xref (nth 1 data))))))
711     (if xref (setq items (list sep xref)))
712     (map-extents #'(lambda (extent ignore)
713                      (let ((data (extent-property extent 'man)))
714                        (if (and (eq (car-safe data) 'Manual-follow-xref)
715                                 (not (member (nth 1 data) items)))
716                            (setq items (cons (nth 1 data) items)))
717                     nil))
718                  buffer)
719     (if (eq sep (car items)) (setq items (cdr items)))
720     (let ((popup-menu-titles t))
721       (and (null items) (setq popup-menu-titles nil))
722       (popup-menu
723        (cons "Manual Entry"
724              (mapcar #'(lambda (item)
725                          (if (eq item sep)
726                              item
727                            (vector item
728                                    (list 'Manual-follow-xref item) t)))
729                      (nreverse items)))))))
730
731 (defun pager-cleanup-hook ()
732   "cleanup man page if called via $PAGER"
733   (let ((buf-name (or buffer-file-name (buffer-name))))
734         (if (or (string-match "^/tmp/man[0-9]+" buf-name)
735                 (string-match ".*/man/\\(man\\|cat\\)[1-9a-z]/" buf-name))
736             (let (buffer manpage)
737               (require 'man)
738               (goto-char (point-min))
739               (setq buffer-read-only nil)
740               (Manual-nuke-nroff-bs)
741               (goto-char (point-min))
742               (if (re-search-forward "[^ \t]")
743                   (goto-char (- (point) 1)))
744               (if (looking-at "\\([a-zA-Z0-9]+\\)[ \t]*(")
745                   (setq manpage (buffer-substring (match-beginning 1)
746                                                   (match-end 1)))
747                 (setq manpage "???"))
748               (setq buffer
749                     (rename-buffer (generate-new-buffer-name
750                                     (concat "Man: " manpage)))
751                     buffer-file-name nil)
752               (goto-char (point-min))
753               (insert (format "%s\n" buf-name))
754               (goto-char (point-min))
755               (buffer-disable-undo buffer)
756               (set-buffer-modified-p nil)
757               (Manual-mode)
758               ))))
759
760 (add-hook 'server-visit-hook 'pager-cleanup-hook)
761 (provide 'man)