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