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