Remove timestamp and related local variables from table.el.
[emacs.git] / lisp / man.el
blob88d1aa7c604f88ae77e6c9d1c94e98d4ece92cd1
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 'external
102 :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 (defcustom Man-name-local-regexp (concat "^" (regexp-opt '("NOM" "NAME")) "$")
225 "Regexp that matches the text that precedes the command's name.
226 Used in `bookmark-set' to get the default bookmark name."
227 :type 'string :group 'bookmark)
229 (defvar manual-program "man"
230 "The name of the program that produces man pages.")
232 (defvar Man-untabify-command "pr"
233 "Command used for untabifying.")
235 (defvar Man-untabify-command-args (list "-t" "-e")
236 "List of arguments to be passed to `Man-untabify-command' (which see).")
238 (defvar Man-sed-command "sed"
239 "Command used for processing sed scripts.")
241 (defvar Man-awk-command "awk"
242 "Command used for processing awk scripts.")
244 (defvar Man-mode-hook nil
245 "Hook run when Man mode is enabled.")
247 (defvar Man-cooked-hook nil
248 "Hook run after removing backspaces but before `Man-mode' processing.")
250 (defvar Man-name-regexp "[-a-zA-Z0-9_­+][-a-zA-Z0-9_.:­+]*"
251 "Regular expression describing the name of a manpage (without section).")
253 (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
254 "Regular expression describing a manpage section within parentheses.")
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.")
265 (defvar Man-heading-regexp "^\\([A-Z][A-Z0-9 /-]+\\)$"
266 "Regular expression describing a manpage heading entry.")
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.")
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.")
279 (defvar Man-reference-regexp
280 (concat "\\(" Man-name-regexp "\\)[ \t]*(\\(" Man-section-regexp "\\))")
281 "Regular expression describing a reference to another manpage.")
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\".")
287 (defvar Man-synopsis-regexp "SYNOPSIS"
288 "Regular expression for SYNOPSIS heading (or your equivalent).
289 This regexp should not start with a `^' character.")
291 (defvar Man-files-regexp "FILES\\>"
292 ;; Add \> so as not to match mount(8)'s FILESYSTEM INDEPENDENT MOUNT OPTIONS.
293 "Regular expression for FILES heading (or your equivalent).
294 This regexp should not start with a `^' character.")
296 (defvar Man-include-regexp "#[ \t]*include[ \t]*"
297 "Regular expression describing the #include (directive of cpp).")
299 (defvar Man-file-name-regexp "[^<>\", \t\n]+"
300 "Regular expression describing <> in #include line (directive of cpp).")
302 (defvar Man-normal-file-prefix-regexp "[/~$]"
303 "Regular expression describing a file path appeared in FILES section.")
305 (defvar Man-header-regexp
306 (concat "\\(" Man-include-regexp "\\)"
307 "[<\"]"
308 "\\(" Man-file-name-regexp "\\)"
309 "[>\"]")
310 "Regular expression describing references to header files.")
312 (defvar Man-normal-file-regexp
313 (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
314 "Regular expression describing references to normal files.")
316 ;; This includes the section as an optional part to catch hyphenated
317 ;; refernces to manpages.
318 (defvar Man-hyphenated-reference-regexp
319 (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
320 "Regular expression describing a reference in the SEE ALSO section.")
322 (defvar Man-switches ""
323 "Switches passed to the man command, as a single string.
325 If you want to be able to see all the manpages for a subject you type,
326 make -a one of the switches, if your `man' program supports it.")
328 (defvar Man-specified-section-option
329 (if (string-match "-solaris[0-9.]*$" system-configuration)
330 "-s"
332 "Option that indicates a specified a manual section name.")
334 (defvar Man-support-local-filenames 'auto-detect
335 "Internal cache for the value of the function `Man-support-local-filenames'.
336 `auto-detect' means the value is not yet determined.
337 Otherwise, the value is whatever the function
338 `Man-support-local-filenames' should return.")
340 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
341 ;; end user variables
343 ;; other variables and keymap initializations
344 (defvar Man-original-frame)
345 (make-variable-buffer-local 'Man-original-frame)
346 (defvar Man-arguments)
347 (make-variable-buffer-local 'Man-arguments)
348 (put 'Man-arguments 'permanent-local t)
350 (defvar Man-sections-alist nil)
351 (make-variable-buffer-local 'Man-sections-alist)
352 (defvar Man-refpages-alist nil)
353 (make-variable-buffer-local 'Man-refpages-alist)
354 (defvar Man-page-list nil)
355 (make-variable-buffer-local 'Man-page-list)
356 (defvar Man-current-page 0)
357 (make-variable-buffer-local 'Man-current-page)
358 (defvar Man-page-mode-string "1 of 1")
359 (make-variable-buffer-local 'Man-page-mode-string)
361 (defconst Man-sysv-sed-script "\
362 /\b/ { s/_\b//g
363 s/\b_//g
364 s/o\b+/o/g
365 s/+\bo/o/g
366 :ovstrk
367 s/\\(.\\)\b\\1/\\1/g
368 t ovstrk
370 /\e\\[[0-9][0-9]*m/ s///g"
371 "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
373 (defconst Man-berkeley-sed-script "\
374 /\b/ { s/_\b//g\\
375 s/\b_//g\\
376 s/o\b+/o/g\\
377 s/+\bo/o/g\\
378 :ovstrk\\
379 s/\\(.\\)\b\\1/\\1/g\\
380 t ovstrk\\
382 /\e\\[[0-9][0-9]*m/ s///g"
383 "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
385 (defvar Man-topic-history nil "Topic read history.")
387 (defvar man-mode-syntax-table
388 (let ((table (copy-syntax-table (standard-syntax-table))))
389 (modify-syntax-entry ?. "w" table)
390 (modify-syntax-entry ?_ "w" table)
391 (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
392 table)
393 "Syntax table used in Man mode buffers.")
395 (defvar Man-mode-map
396 (let ((map (make-sparse-keymap)))
397 (suppress-keymap map)
398 (set-keymap-parent map button-buffer-map)
400 (define-key map " " 'scroll-up)
401 (define-key map "\177" 'scroll-down)
402 (define-key map "n" 'Man-next-section)
403 (define-key map "p" 'Man-previous-section)
404 (define-key map "\en" 'Man-next-manpage)
405 (define-key map "\ep" 'Man-previous-manpage)
406 (define-key map ">" 'end-of-buffer)
407 (define-key map "<" 'beginning-of-buffer)
408 (define-key map "." 'beginning-of-buffer)
409 (define-key map "r" 'Man-follow-manual-reference)
410 (define-key map "g" 'Man-goto-section)
411 (define-key map "s" 'Man-goto-see-also-section)
412 (define-key map "k" 'Man-kill)
413 (define-key map "q" 'Man-quit)
414 (define-key map "m" 'man)
415 ;; Not all the man references get buttons currently. The text in the
416 ;; manual page can contain references to other man pages
417 (define-key map "\r" 'man-follow)
418 (define-key map "?" 'describe-mode)
419 map)
420 "Keymap for Man mode.")
422 ;; buttons
423 (define-button-type 'Man-abstract-xref-man-page
424 'follow-link t
425 'help-echo "mouse-2, RET: display this man page"
426 'func nil
427 'action #'Man-xref-button-action)
429 (defun Man-xref-button-action (button)
430 (let ((target (button-get button 'Man-target-string)))
431 (funcall
432 (button-get button 'func)
433 (cond ((null target)
434 (button-label button))
435 ((functionp target)
436 (funcall target (button-start button)))
437 (t target)))))
439 (define-button-type 'Man-xref-man-page
440 :supertype 'Man-abstract-xref-man-page
441 'func 'man-follow)
444 (define-button-type 'Man-xref-header-file
445 'action (lambda (button)
446 (let ((w (button-get button 'Man-target-string)))
447 (unless (Man-view-header-file w)
448 (error "Cannot find header file: %s" w))))
449 'follow-link t
450 'help-echo "mouse-2: display this header file")
452 (define-button-type 'Man-xref-normal-file
453 'action (lambda (button)
454 (let ((f (substitute-in-file-name
455 (button-get button 'Man-target-string))))
456 (if (file-exists-p f)
457 (if (file-readable-p f)
458 (view-file f)
459 (error "Cannot read a file: %s" f))
460 (error "Cannot find a file: %s" f))))
461 'follow-link t
462 'help-echo "mouse-2: display this file")
465 ;; ======================================================================
466 ;; utilities
468 (defun Man-init-defvars ()
469 "Used for initializing variables based on display's color support.
470 This is necessary if one wants to dump man.el with Emacs."
472 ;; Avoid possible error in call-process by using a directory that must exist.
473 (let ((default-directory "/"))
474 (setq Man-sed-script
475 (cond
476 (Man-fontify-manpage-flag
477 nil)
478 ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
479 Man-sysv-sed-script)
480 ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
481 Man-berkeley-sed-script)
483 nil))))
485 (setq Man-filter-list
486 ;; Avoid trailing nil which confuses customize.
487 (apply 'list
488 (cons
489 Man-sed-command
490 (if (eq system-type 'windows-nt)
491 ;; Windows needs ".." quoting, not '..'.
492 (list
493 "-e \"/Reformatting page. Wait/d\""
494 "-e \"/Reformatting entry. Wait/d\""
495 "-e \"/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d\""
496 "-e \"/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d\""
497 "-e \"/^Printed[ \t][0-9].*[0-9]$/d\""
498 "-e \"/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d\""
499 "-e \"/^[A-Za-z].*Last[ \t]change:/d\""
500 "-e \"/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d\""
501 "-e \"/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d\"")
502 (list
503 (if Man-sed-script
504 (concat "-e '" Man-sed-script "'")
506 "-e '/^[\001-\032][\001-\032]*$/d'"
507 "-e '/\e[789]/s///g'"
508 "-e '/Reformatting page. Wait/d'"
509 "-e '/Reformatting entry. Wait/d'"
510 "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
511 "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
512 "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
513 "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
514 "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
515 "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
516 "-e '/^[A-Za-z].*Last[ \t]change:/d'"
517 "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
518 "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
519 "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
521 ;; Windows doesn't support multi-line commands, so don't
522 ;; invoke Awk there.
523 (unless (eq system-type 'windows-nt)
524 (cons
525 Man-awk-command
526 (list
527 "'\n"
528 "BEGIN { blankline=0; anonblank=0; }\n"
529 "/^$/ { if (anonblank==0) next; }\n"
530 "{ anonblank=1; }\n"
531 "/^$/ { blankline++; next; }\n"
532 "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
535 (if (not Man-uses-untabify-flag)
536 ;; The outer list will be stripped off by apply.
537 (list (cons
538 Man-untabify-command
539 Man-untabify-command-args))
543 (defsubst Man-make-page-mode-string ()
544 "Formats part of the mode line for Man mode."
545 (format "%s page %d of %d"
546 (or (nth 2 (nth (1- Man-current-page) Man-page-list))
548 Man-current-page
549 (length Man-page-list)))
551 (defsubst Man-build-man-command ()
552 "Builds the entire background manpage and cleaning command."
553 (let ((command (concat manual-program " " Man-switches
554 (cond
555 ;; Already has %s
556 ((string-match "%s" manual-program) "")
557 ;; Stock MS-DOS shells cannot redirect stderr;
558 ;; `call-process' below sends it to /dev/null,
559 ;; so we don't need `2>' even with DOS shells
560 ;; which do support stderr redirection.
561 ((not (fboundp 'start-process)) " %s")
562 ((concat " %s 2>" null-device)))))
563 (flist Man-filter-list))
564 (while (and flist (car flist))
565 (let ((pcom (car (car flist)))
566 (pargs (cdr (car flist))))
567 (setq command
568 (concat command " | " pcom " "
569 (mapconcat (lambda (phrase)
570 (if (not (stringp phrase))
571 (error "Malformed Man-filter-list"))
572 phrase)
573 pargs " ")))
574 (setq flist (cdr flist))))
575 command))
578 (defun Man-translate-cleanup (string)
579 "Strip leading, trailing and middle spaces."
580 (when (stringp string)
581 ;; Strip leading and trailing
582 (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
583 (setq string (match-string 1 string)))
584 ;; middle spaces
585 (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
586 (setq string (replace-regexp-in-string " +" " " string))
587 string))
589 (defun Man-translate-references (ref)
590 "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
591 Leave it as is if already in that style. Possibly downcase and
592 translate the section (see the `Man-downcase-section-letters-flag'
593 and the `Man-section-translations-alist' variables)."
594 (let ((name "")
595 (section "")
596 (slist Man-section-translations-alist))
597 (setq ref (Man-translate-cleanup ref))
598 (cond
599 ;; "chmod(2V)" case ?
600 ((string-match (concat "^" Man-reference-regexp "$") ref)
601 (setq name (match-string 1 ref)
602 section (match-string 2 ref)))
603 ;; "2v chmod" case ?
604 ((string-match (concat "^\\(" Man-section-regexp
605 "\\) +\\(" Man-name-regexp "\\)$") ref)
606 (setq name (match-string 2 ref)
607 section (match-string 1 ref))))
608 (if (string= name "")
609 ref ; Return the reference as is
610 (if Man-downcase-section-letters-flag
611 (setq section (downcase section)))
612 (while slist
613 (let ((s1 (car (car slist)))
614 (s2 (cdr (car slist))))
615 (setq slist (cdr slist))
616 (if Man-downcase-section-letters-flag
617 (setq s1 (downcase s1)))
618 (if (not (string= s1 section)) nil
619 (setq section (if Man-downcase-section-letters-flag
620 (downcase s2)
622 slist nil))))
623 (concat Man-specified-section-option section " " name))))
625 (defun Man-support-local-filenames ()
626 "Check the availability of `-l' option of the man command.
627 This option allows `man' to interpret command line arguments
628 as local filenames.
629 Return the value of the variable `Man-support-local-filenames'
630 if it was set to nil or t before the call of this function.
631 If t, the man command supports `-l' option. If nil, it doesn't.
632 Otherwise, if the value of `Man-support-local-filenames'
633 is neither t nor nil, then determine a new value, set it
634 to the variable `Man-support-local-filenames' and return
635 a new value."
636 (if (or (not Man-support-local-filenames)
637 (eq Man-support-local-filenames t))
638 Man-support-local-filenames
639 (setq Man-support-local-filenames
640 (with-temp-buffer
641 (and (equal (condition-case nil
642 (let ((default-directory
643 ;; Assure that `default-directory' exists
644 ;; and is readable.
645 (if (and (file-directory-p default-directory)
646 (file-readable-p default-directory))
647 default-directory
648 (expand-file-name "~/"))))
649 (call-process manual-program nil t nil "--help"))
650 (error nil))
652 (progn
653 (goto-char (point-min))
654 (search-forward "--local-file" nil t))
655 t)))))
658 ;; ======================================================================
659 ;; default man entry: get word near point
661 (defun Man-default-man-entry (&optional pos)
662 "Guess default manual entry based on the text near position POS.
663 POS defaults to `point'."
664 (let (word start column distance)
665 (save-excursion
666 (when pos (goto-char pos))
667 (setq pos (point))
668 ;; The default title is the nearest entry-like object before or
669 ;; after POS.
670 (if (and (skip-chars-backward " \ta-zA-Z0-9+")
671 (not (zerop (skip-chars-backward "(")))
672 ;; Try to handle the special case where POS is on a
673 ;; section number.
674 (looking-at
675 (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
676 ;; We skipped a valid section number backwards, look at
677 ;; preceding text.
678 (or (and (skip-chars-backward ",; \t")
679 (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
680 ;; Not a valid entry, move POS after closing paren.
681 (not (setq pos (match-end 0)))))
682 ;; We have a candidate, make `start' record its starting
683 ;; position.
684 (setq start (point))
685 ;; Otherwise look at char before POS.
686 (goto-char pos)
687 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
688 ;; Our candidate is just before or around POS.
689 (setq start (point))
690 ;; Otherwise record the current column and look backwards.
691 (setq column (current-column))
692 (skip-chars-backward ",; \t")
693 ;; Record the distance travelled.
694 (setq distance (- column (current-column)))
695 (when (looking-back
696 (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)"))
697 ;; Skip section number backwards.
698 (goto-char (match-beginning 0))
699 (skip-chars-backward " \t"))
700 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
701 (progn
702 ;; We have a candidate before POS ...
703 (setq start (point))
704 (goto-char pos)
705 (if (and (skip-chars-forward ",; \t")
706 (< (- (current-column) column) distance)
707 (looking-at "[-a-zA-Z0-9._+:]"))
708 ;; ... but the one after POS is better.
709 (setq start (point))
710 ;; ... and anything after POS is worse.
711 (goto-char start)))
712 ;; No candidate before POS.
713 (goto-char pos)
714 (skip-chars-forward ",; \t")
715 (setq start (point)))))
716 ;; We have found a suitable starting point, try to skip at least
717 ;; one character.
718 (skip-chars-forward "-a-zA-Z0-9._+:")
719 (setq word (buffer-substring-no-properties start (point)))
720 ;; If there is a continuation at the end of line, check the
721 ;; following line too, eg:
722 ;; see this-
723 ;; command-here(1)
724 ;; Note: This code gets executed iff our entry is after POS.
725 (when (looking-at "[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
726 (setq word (concat word (match-string-no-properties 1)))
727 ;; Make sure the section number gets included by the code below.
728 (goto-char (match-end 1)))
729 (when (string-match "[._]+$" word)
730 (setq word (substring word 0 (match-beginning 0))))
731 ;; The following was commented out since the preceding code
732 ;; should not produce a leading "*" in the first place.
733 ;;; ;; If looking at something like *strcat(... , remove the '*'
734 ;;; (when (string-match "^*" word)
735 ;;; (setq word (substring word 1)))
736 (concat
737 word
738 (and (not (string-equal word ""))
739 ;; If looking at something like ioctl(2) or brc(1M),
740 ;; include the section number in the returned value.
741 (looking-at
742 (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
743 (format "(%s)" (match-string-no-properties 1)))))))
746 ;; ======================================================================
747 ;; Top level command and background process sentinel
749 ;; For compatibility with older versions.
750 ;;;###autoload
751 (defalias 'manual-entry 'man)
753 (defvar Man-completion-cache nil
754 ;; On my machine, "man -k" is so fast that a cache makes no sense,
755 ;; but apparently that's not the case in all cases, so let's add a cache.
756 "Cache of completion table of the form (PREFIX . TABLE).")
758 (defun Man-completion-table (string pred action)
759 (cond
760 ((eq action 'lambda)
761 (not (string-match "([^)]*\\'" string)))
762 ((equal string "-k")
763 ;; Let SPC (minibuffer-complete-word) insert the space.
764 (complete-with-action action '("-k ") string pred))
766 (let ((table (cdr Man-completion-cache))
767 (section nil)
768 (prefix string))
769 (when (string-match "\\`\\([[:digit:]].*?\\) " string)
770 (setq section (match-string 1 string))
771 (setq prefix (substring string (match-end 0))))
772 (unless (and Man-completion-cache
773 (string-prefix-p (car Man-completion-cache) prefix))
774 (with-temp-buffer
775 (setq default-directory "/") ;; in case inherited doesn't exist
776 ;; Actually for my `man' the arg is a regexp.
777 ;; POSIX says it must be ERE and "man-db" seems to agree,
778 ;; whereas under MacOSX it seems to be BRE-style and doesn't
779 ;; accept backslashes at all. Let's not bother to
780 ;; quote anything.
781 (let ((process-environment (copy-sequence process-environment)))
782 (setenv "COLUMNS" "999") ;; don't truncate long names
783 ;; manual-program might not even exist. And since it's
784 ;; run differently in Man-getpage-in-background, an error
785 ;; here may not necessarily mean that we'll also get an
786 ;; error later.
787 (ignore-errors
788 (call-process manual-program nil '(t nil) nil
789 "-k" (concat "^" prefix))))
790 (goto-char (point-min))
791 (while (re-search-forward "^\\([^ \t\n]+\\)\\(?: ?\\((.+?)\\)\\(?:[ \t]+- \\(.*\\)\\)?\\)?" nil t)
792 (push (propertize (concat (match-string 1) (match-string 2))
793 'help-echo (match-string 3))
794 table)))
795 ;; Cache the table for later reuse.
796 (setq Man-completion-cache (cons prefix table)))
797 ;; The table may contain false positives since the match is made
798 ;; by "man -k" not just on the manpage's name.
799 (if section
800 (let ((re (concat "(" (regexp-quote section) ")\\'")))
801 (dolist (comp (prog1 table (setq table nil)))
802 (if (string-match re comp)
803 (push (substring comp 0 (match-beginning 0)) table)))
804 (completion-table-with-context (concat section " ") table
805 prefix pred action))
806 ;; If the current text looks like a possible section name,
807 ;; then add a completion entry that just adds a space so SPC
808 ;; can be used to insert a space.
809 (if (string-match "\\`[[:digit:]]" string)
810 (push (concat string " ") table))
811 (let ((res (complete-with-action action table string pred)))
812 ;; In case we're completing to a single name that exists in
813 ;; several sections, the longest prefix will look like "foo(".
814 (if (and (stringp res)
815 (string-match "([^(]*\\'" res)
816 ;; In case the paren was already in `prefix', don't
817 ;; remove it.
818 (> (match-beginning 0) (length prefix)))
819 (substring res 0 (match-beginning 0))
820 res)))))))
822 ;;;###autoload
823 (defun man (man-args)
824 "Get a Un*x manual page and put it in a buffer.
825 This command is the top-level command in the man package. It
826 runs a Un*x command to retrieve and clean a manpage in the
827 background and places the results in a `Man-mode' browsing
828 buffer. See variable `Man-notify-method' for what happens when
829 the buffer is ready. If a buffer already exists for this man
830 page, it will display immediately.
832 For a manpage from a particular section, use either of the
833 following. \"cat(1)\" is how cross-references appear and is
834 passed to man as \"1 cat\".
836 cat(1)
837 1 cat
839 To see manpages from all sections related to a subject, use an
840 \"all pages\" option (which might be \"-a\" if it's not the
841 default), then step through with `Man-next-manpage' (\\<Man-mode-map>\\[Man-next-manpage]) etc.
842 Add to `Man-switches' to make this option permanent.
844 -a chmod
846 An explicit filename can be given too. Use -l if it might
847 otherwise look like a page name.
849 /my/file/name.1.gz
850 -l somefile.1
852 An \"apropos\" query with -k gives a buffer of matching page
853 names or descriptions. The pattern argument is usually an
854 \"egrep\" style regexp.
856 -k pattern"
858 (interactive
859 (list (let* ((default-entry (Man-default-man-entry))
860 ;; ignore case because that's friendly for bizarre
861 ;; caps things like the X11 function names and because
862 ;; "man" itself is case-sensitive on the command line
863 ;; so you're accustomed not to bother about the case
864 ;; ("man -k" is case-insensitive similarly, so the
865 ;; table has everything available to complete)
866 (completion-ignore-case t)
867 (input (completing-read
868 (format "Manual entry%s"
869 (if (string= default-entry "")
870 ": "
871 (format " (default %s): " default-entry)))
872 'Man-completion-table
873 nil nil nil 'Man-topic-history default-entry)))
874 (if (string= input "")
875 (error "No man args given")
876 input))))
878 ;; Possibly translate the "subject(section)" syntax into the
879 ;; "section subject" syntax and possibly downcase the section.
880 (setq man-args (Man-translate-references man-args))
882 (Man-getpage-in-background man-args))
884 ;;;###autoload
885 (defun man-follow (man-args)
886 "Get a Un*x manual page of the item under point and put it in a buffer."
887 (interactive (list (Man-default-man-entry)))
888 (if (or (not man-args)
889 (string= man-args ""))
890 (error "No item under point")
891 (man man-args)))
893 (defun Man-getpage-in-background (topic)
894 "Use TOPIC to build and fire off the manpage and cleaning command.
895 Return the buffer in which the manpage will appear."
896 (let* ((man-args topic)
897 (bufname (concat "*Man " man-args "*"))
898 (buffer (get-buffer bufname)))
899 (if buffer
900 (Man-notify-when-ready buffer)
901 (require 'env)
902 (message "Invoking %s %s in the background" manual-program man-args)
903 (setq buffer (generate-new-buffer bufname))
904 (with-current-buffer buffer
905 (setq buffer-undo-list t)
906 (setq Man-original-frame (selected-frame))
907 (setq Man-arguments man-args))
908 (let ((process-environment (copy-sequence process-environment))
909 ;; The following is so Awk script gets \n intact
910 ;; But don't prevent decoding of the outside.
911 (coding-system-for-write 'raw-text-unix)
912 ;; We must decode the output by a coding system that the
913 ;; system's locale suggests in multibyte mode.
914 (coding-system-for-read
915 (if (default-value 'enable-multibyte-characters)
916 locale-coding-system 'raw-text-unix))
917 ;; Avoid possible error by using a directory that always exists.
918 (default-directory
919 (if (and (file-directory-p default-directory)
920 (not (find-file-name-handler default-directory
921 'file-directory-p)))
922 default-directory
923 "/")))
924 ;; Prevent any attempt to use display terminal fanciness.
925 (setenv "TERM" "dumb")
926 ;; In Debian Woody, at least, we get overlong lines under X
927 ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
928 ;; a tty. man(1) says:
929 ;; MANWIDTH
930 ;; If $MANWIDTH is set, its value is used as the line
931 ;; length for which manual pages should be formatted.
932 ;; If it is not set, manual pages will be formatted
933 ;; with a line length appropriate to the current ter-
934 ;; minal (using an ioctl(2) if available, the value of
935 ;; $COLUMNS, or falling back to 80 characters if nei-
936 ;; ther is available).
937 (unless (or (getenv "MANWIDTH") (getenv "COLUMNS"))
938 ;; This isn't strictly correct, since we don't know how
939 ;; the page will actually be displayed, but it seems
940 ;; reasonable.
941 (setenv "COLUMNS" (number-to-string
942 (cond
943 ((and (integerp Man-width) (> Man-width 0))
944 Man-width)
945 (Man-width (frame-width))
946 ((window-width))))))
947 (setenv "GROFF_NO_SGR" "1")
948 ;; Since man-db 2.4.3-1, man writes plain text with no escape
949 ;; sequences when stdout is not a tty. In 2.5.0, the following
950 ;; env-var was added to allow control of this (see Debian Bug#340673).
951 (setenv "MAN_KEEP_FORMATTING" "1")
952 (if (fboundp 'start-process)
953 (set-process-sentinel
954 (start-process manual-program buffer
955 (if (memq system-type '(cygwin windows-nt))
956 shell-file-name
957 "sh")
958 shell-command-switch
959 (format (Man-build-man-command) man-args))
960 'Man-bgproc-sentinel)
961 (let ((exit-status
962 (call-process shell-file-name nil (list buffer nil) nil
963 shell-command-switch
964 (format (Man-build-man-command) man-args)))
965 (msg ""))
966 (or (and (numberp exit-status)
967 (= exit-status 0))
968 (and (numberp exit-status)
969 (setq msg
970 (format "exited abnormally with code %d"
971 exit-status)))
972 (setq msg exit-status))
973 (Man-bgproc-sentinel bufname msg)))))
974 buffer))
976 (defun Man-notify-when-ready (man-buffer)
977 "Notify the user when MAN-BUFFER is ready.
978 See the variable `Man-notify-method' for the different notification behaviors."
979 (let ((saved-frame (with-current-buffer man-buffer
980 Man-original-frame)))
981 (case Man-notify-method
982 (newframe
983 ;; Since we run asynchronously, perhaps while Emacs is waiting
984 ;; for input, we must not leave a different buffer current. We
985 ;; can't rely on the editor command loop to reselect the
986 ;; selected window's buffer.
987 (save-excursion
988 (let ((frame (make-frame Man-frame-parameters)))
989 (set-window-buffer (frame-selected-window frame) man-buffer)
990 (set-window-dedicated-p (frame-selected-window frame) t)
991 (or (display-multi-frame-p frame)
992 (select-frame frame)))))
993 (pushy
994 (switch-to-buffer man-buffer))
995 (bully
996 (and (frame-live-p saved-frame)
997 (select-frame saved-frame))
998 (pop-to-buffer man-buffer)
999 (delete-other-windows))
1000 (aggressive
1001 (and (frame-live-p saved-frame)
1002 (select-frame saved-frame))
1003 (pop-to-buffer man-buffer))
1004 (friendly
1005 (and (frame-live-p saved-frame)
1006 (select-frame saved-frame))
1007 (display-buffer man-buffer 'not-this-window))
1008 (polite
1009 (beep)
1010 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1011 (quiet
1012 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1013 (t ;; meek
1014 (message ""))
1017 (defun Man-softhyphen-to-minus ()
1018 ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
1019 ;; least, emit it even when not in a Latin-N locale.
1020 (unless (eq t (compare-strings "latin-" 0 nil
1021 current-language-environment 0 6 t))
1022 (goto-char (point-min))
1023 (let ((str "\255"))
1024 (if enable-multibyte-characters
1025 (setq str (string-as-multibyte str)))
1026 (while (search-forward str nil t) (replace-match "-")))))
1028 (defun Man-fontify-manpage ()
1029 "Convert overstriking and underlining to the correct fonts.
1030 Same for the ANSI bold and normal escape sequences."
1031 (interactive)
1032 (message "Please wait: formatting the %s man page..." Man-arguments)
1033 (goto-char (point-min))
1034 ;; Fontify ANSI escapes.
1035 (let ((faces nil)
1036 (buffer-undo-list t)
1037 (start (point)))
1038 ;; http://www.isthe.com/chongo/tech/comp/ansi_escapes.html
1039 ;; suggests many codes, but we only handle:
1040 ;; ESC [ 00 m reset to normal display
1041 ;; ESC [ 01 m bold
1042 ;; ESC [ 04 m underline
1043 ;; ESC [ 07 m reverse-video
1044 ;; ESC [ 22 m no-bold
1045 ;; ESC [ 24 m no-underline
1046 ;; ESC [ 27 m no-reverse-video
1047 (while (re-search-forward "\e\\[0?\\([1470]\\|2\\([247]\\)\\)m" nil t)
1048 (if faces (put-text-property start (match-beginning 0) 'face
1049 (if (cdr faces) faces (car faces))))
1050 (setq faces
1051 (cond
1052 ((match-beginning 2)
1053 (delq (case (char-after (match-beginning 2))
1054 (?2 Man-overstrike-face)
1055 (?4 Man-underline-face)
1056 (?7 Man-reverse-face))
1057 faces))
1058 ((eq (char-after (match-beginning 1)) ?0) nil)
1060 (cons (case (char-after (match-beginning 1))
1061 (?1 Man-overstrike-face)
1062 (?4 Man-underline-face)
1063 (?7 Man-reverse-face))
1064 faces))))
1065 (delete-region (match-beginning 0) (match-end 0))
1066 (setq start (point))))
1067 ;; Other highlighting.
1068 (let ((buffer-undo-list t))
1069 (if (< (buffer-size) (position-bytes (point-max)))
1070 ;; Multibyte characters exist.
1071 (progn
1072 (goto-char (point-min))
1073 (while (search-forward "__\b\b" nil t)
1074 (backward-delete-char 4)
1075 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1076 (goto-char (point-min))
1077 (while (search-forward "\b\b__" nil t)
1078 (backward-delete-char 4)
1079 (put-text-property (1- (point)) (point) 'face Man-underline-face))))
1080 (goto-char (point-min))
1081 (while (search-forward "_\b" nil t)
1082 (backward-delete-char 2)
1083 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1084 (goto-char (point-min))
1085 (while (search-forward "\b_" nil t)
1086 (backward-delete-char 2)
1087 (put-text-property (1- (point)) (point) 'face Man-underline-face))
1088 (goto-char (point-min))
1089 (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
1090 (replace-match "\\1")
1091 (put-text-property (1- (point)) (point) 'face Man-overstrike-face))
1092 (goto-char (point-min))
1093 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
1094 (replace-match "o")
1095 (put-text-property (1- (point)) (point) 'face 'bold))
1096 (goto-char (point-min))
1097 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
1098 (replace-match "+")
1099 (put-text-property (1- (point)) (point) 'face 'bold))
1100 ;; When the header is longer than the manpage name, groff tries to
1101 ;; condense it to a shorter line interspered with ^H. Remove ^H with
1102 ;; their preceding chars (but don't put Man-overstrike-face). (Bug#5566)
1103 (goto-char (point-min))
1104 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1105 (goto-char (point-min))
1106 ;; Try to recognize common forms of cross references.
1107 (Man-highlight-references)
1108 (Man-softhyphen-to-minus)
1109 (goto-char (point-min))
1110 (while (re-search-forward Man-heading-regexp nil t)
1111 (put-text-property (match-beginning 0)
1112 (match-end 0)
1113 'face Man-overstrike-face)))
1114 (message "%s man page formatted" Man-arguments))
1116 (defun Man-highlight-references (&optional xref-man-type)
1117 "Highlight the references on mouse-over.
1118 References include items in the SEE ALSO section,
1119 header file (#include <foo.h>), and files in FILES.
1120 If optional argument XREF-MAN-TYPE is non-nil, it used as the
1121 button type for items in SEE ALSO section. If it is nil, the
1122 default type, `Man-xref-man-page' is used for the buttons."
1123 ;; `Man-highlight-references' is used from woman.el, too.
1124 ;; woman.el doesn't set `Man-arguments'.
1125 (unless Man-arguments
1126 (setq Man-arguments ""))
1127 (if (string-match "-k " Man-arguments)
1128 (progn
1129 (Man-highlight-references0 nil Man-reference-regexp 1
1130 'Man-default-man-entry
1131 (or xref-man-type 'Man-xref-man-page))
1132 (Man-highlight-references0 nil Man-apropos-regexp 1
1133 'Man-default-man-entry
1134 (or xref-man-type 'Man-xref-man-page)))
1135 (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
1136 'Man-default-man-entry
1137 (or xref-man-type 'Man-xref-man-page))
1138 (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
1139 'Man-xref-header-file)
1140 (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
1141 'Man-xref-normal-file)))
1143 (defun Man-highlight-references0 (start-section regexp button-pos target type)
1144 ;; Based on `Man-build-references-alist'
1145 (when (or (null start-section)
1146 (Man-find-section start-section))
1147 (let ((end (if start-section
1148 (progn
1149 (forward-line 1)
1150 (back-to-indentation)
1151 (save-excursion
1152 (Man-next-section 1)
1153 (point)))
1154 (goto-char (point-min))
1155 nil)))
1156 (while (re-search-forward regexp end t)
1157 (make-text-button
1158 (match-beginning button-pos)
1159 (match-end button-pos)
1160 'type type
1161 'Man-target-string (cond
1162 ((numberp target)
1163 (match-string target))
1164 ((functionp target)
1165 target)
1166 (t nil)))))))
1168 (defun Man-cleanup-manpage (&optional interactive)
1169 "Remove overstriking and underlining from the current buffer.
1170 Normally skip any jobs that should have been done by the sed script,
1171 but when called interactively, do those jobs even if the sed
1172 script would have done them."
1173 (interactive "p")
1174 (message "Please wait: cleaning up the %s man page..."
1175 Man-arguments)
1176 (if (or interactive (not Man-sed-script))
1177 (progn
1178 (goto-char (point-min))
1179 (while (search-forward "_\b" nil t) (backward-delete-char 2))
1180 (goto-char (point-min))
1181 (while (search-forward "\b_" nil t) (backward-delete-char 2))
1182 (goto-char (point-min))
1183 (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
1184 (replace-match "\\1"))
1185 (goto-char (point-min))
1186 (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
1187 (goto-char (point-min))
1188 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
1190 (goto-char (point-min))
1191 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
1192 ;; When the header is longer than the manpage name, groff tries to
1193 ;; condense it to a shorter line interspered with ^H. Remove ^H with
1194 ;; their preceding chars (but don't put Man-overstrike-face). (Bug#5566)
1195 (goto-char (point-min))
1196 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1197 (Man-softhyphen-to-minus)
1198 (message "%s man page cleaned up" Man-arguments))
1200 (defun Man-bgproc-sentinel (process msg)
1201 "Manpage background process sentinel.
1202 When manpage command is run asynchronously, PROCESS is the process
1203 object for the manpage command; when manpage command is run
1204 synchronously, PROCESS is the name of the buffer where the manpage
1205 command is run. Second argument MSG is the exit message of the
1206 manpage command."
1207 (let ((Man-buffer (if (stringp process) (get-buffer process)
1208 (process-buffer process)))
1209 (delete-buff nil)
1210 (err-mess nil))
1212 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1213 (or (stringp process)
1214 (set-process-buffer process nil))
1216 (with-current-buffer Man-buffer
1217 (let ((case-fold-search nil))
1218 (goto-char (point-min))
1219 (cond ((or (looking-at "No \\(manual \\)*entry for")
1220 (looking-at "[^\n]*: nothing appropriate$"))
1221 (setq err-mess (buffer-substring (point)
1222 (progn
1223 (end-of-line) (point)))
1224 delete-buff t))
1226 ;; "-k foo", successful exit, but no output (from man-db)
1227 ;; ENHANCE-ME: share the check for -k with
1228 ;; `Man-highlight-references'. The \\s- bits here are
1229 ;; meant to allow for multiple options with -k among them.
1230 ((and (string-match "\\(\\`\\|\\s-\\)-k\\s-" Man-arguments)
1231 (eq (process-status process) 'exit)
1232 (= (process-exit-status process) 0)
1233 (= (point-min) (point-max)))
1234 (setq err-mess (format "%s: no matches" Man-arguments)
1235 delete-buff t))
1237 ((or (stringp process)
1238 (not (and (eq (process-status process) 'exit)
1239 (= (process-exit-status process) 0))))
1240 (or (zerop (length msg))
1241 (progn
1242 (setq err-mess
1243 (concat (buffer-name Man-buffer)
1244 ": process "
1245 (let ((eos (1- (length msg))))
1246 (if (= (aref msg eos) ?\n)
1247 (substring msg 0 eos) msg))))
1248 (goto-char (point-max))
1249 (insert (format "\nprocess %s" msg))))
1251 (if delete-buff
1252 (kill-buffer Man-buffer)
1253 (if Man-fontify-manpage-flag
1254 (Man-fontify-manpage)
1255 (Man-cleanup-manpage))
1257 (run-hooks 'Man-cooked-hook)
1258 (Man-mode)
1260 (if (not Man-page-list)
1261 (let ((args Man-arguments))
1262 (kill-buffer (current-buffer))
1263 (error "Can't find the %s manpage" args)))
1265 (set-buffer-modified-p nil)
1267 ;; Restore case-fold-search before calling
1268 ;; Man-notify-when-ready because it may switch buffers.
1270 (if (not delete-buff)
1271 (Man-notify-when-ready Man-buffer))
1273 (if err-mess
1274 (error "%s" err-mess))
1275 ))))
1278 ;; ======================================================================
1279 ;; set up manual mode in buffer and build alists
1281 (defvar bookmark-make-record-function)
1283 (put 'Man-mode 'mode-class 'special)
1285 (defun Man-mode ()
1286 "A mode for browsing Un*x manual pages.
1288 The following man commands are available in the buffer. Try
1289 \"\\[describe-key] <key> RET\" for more information:
1291 \\[man] Prompt to retrieve a new manpage.
1292 \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
1293 \\[Man-next-manpage] Jump to next manpage in circular list.
1294 \\[Man-previous-manpage] Jump to previous manpage in circular list.
1295 \\[Man-next-section] Jump to next manpage section.
1296 \\[Man-previous-section] Jump to previous manpage section.
1297 \\[Man-goto-section] Go to a manpage section.
1298 \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
1299 \\[Man-quit] Deletes the manpage window, bury its buffer.
1300 \\[Man-kill] Deletes the manpage window, kill its buffer.
1301 \\[describe-mode] Prints this help text.
1303 The following variables may be of some use. Try
1304 \"\\[describe-variable] <variable-name> RET\" for more information:
1306 `Man-notify-method' What happens when manpage formatting is done.
1307 `Man-downcase-section-letters-flag' Force section letters to lower case.
1308 `Man-circular-pages-flag' Treat multiple manpage list as circular.
1309 `Man-section-translations-alist' List of section numbers and their Un*x equiv.
1310 `Man-filter-list' Background manpage filter command.
1311 `Man-mode-map' Keymap bindings for Man mode buffers.
1312 `Man-mode-hook' Normal hook run on entry to Man mode.
1313 `Man-section-regexp' Regexp describing manpage section letters.
1314 `Man-heading-regexp' Regexp describing section headers.
1315 `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
1316 `Man-first-heading-regexp' Regexp for first heading on a manpage.
1317 `Man-reference-regexp' Regexp matching a references in SEE ALSO.
1318 `Man-switches' Background `man' command switches.
1320 The following key bindings are currently in effect in the buffer:
1321 \\{Man-mode-map}"
1322 (interactive)
1323 (kill-all-local-variables)
1324 (setq major-mode 'Man-mode
1325 mode-name "Man"
1326 buffer-auto-save-file-name nil
1327 mode-line-buffer-identification
1328 (list (default-value 'mode-line-buffer-identification)
1329 " {" 'Man-page-mode-string "}")
1330 truncate-lines t
1331 buffer-read-only t)
1332 (buffer-disable-undo)
1333 (auto-fill-mode -1)
1334 (use-local-map Man-mode-map)
1335 (set-syntax-table man-mode-syntax-table)
1336 (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
1337 (set (make-local-variable 'outline-regexp) Man-heading-regexp)
1338 (set (make-local-variable 'outline-level) (lambda () 1))
1339 (set (make-local-variable 'bookmark-make-record-function)
1340 'Man-bookmark-make-record)
1341 (Man-build-page-list)
1342 (Man-strip-page-headers)
1343 (Man-unindent)
1344 (Man-goto-page 1 t)
1345 (run-mode-hooks 'Man-mode-hook))
1347 (defsubst Man-build-section-alist ()
1348 "Build the association list of manpage sections."
1349 (setq Man-sections-alist nil)
1350 (goto-char (point-min))
1351 (let ((case-fold-search nil))
1352 (while (re-search-forward Man-heading-regexp (point-max) t)
1353 (aput 'Man-sections-alist (match-string 1))
1354 (forward-line 1))))
1356 (defsubst Man-build-references-alist ()
1357 "Build the association list of references (in the SEE ALSO section)."
1358 (setq Man-refpages-alist nil)
1359 (save-excursion
1360 (if (Man-find-section Man-see-also-regexp)
1361 (let ((start (progn (forward-line 1) (point)))
1362 (end (progn
1363 (Man-next-section 1)
1364 (point)))
1365 hyphenated
1366 (runningpoint -1))
1367 (save-restriction
1368 (narrow-to-region start end)
1369 (goto-char (point-min))
1370 (back-to-indentation)
1371 (while (and (not (eobp)) (/= (point) runningpoint))
1372 (setq runningpoint (point))
1373 (if (re-search-forward Man-hyphenated-reference-regexp end t)
1374 (let* ((word (match-string 0))
1375 (len (1- (length word))))
1376 (if hyphenated
1377 (setq word (concat hyphenated word)
1378 hyphenated nil
1379 ;; Update len, in case a reference spans
1380 ;; more than two lines (paranoia).
1381 len (1- (length word))))
1382 (if (memq (aref word len) '(?- ?­))
1383 (setq hyphenated (substring word 0 len)))
1384 (if (string-match Man-reference-regexp word)
1385 (aput 'Man-refpages-alist word))))
1386 (skip-chars-forward " \t\n,"))))))
1387 (setq Man-refpages-alist (nreverse Man-refpages-alist)))
1389 (defun Man-build-page-list ()
1390 "Build the list of separate manpages in the buffer."
1391 (setq Man-page-list nil)
1392 (let ((page-start (point-min))
1393 (page-end (point-max))
1394 (header ""))
1395 (goto-char page-start)
1396 ;; (switch-to-buffer (current-buffer))(debug)
1397 (while (not (eobp))
1398 (setq header
1399 (if (looking-at Man-page-header-regexp)
1400 (match-string 1)
1401 nil))
1402 ;; Go past both the current and the next Man-first-heading-regexp
1403 (if (re-search-forward Man-first-heading-regexp nil 'move 2)
1404 (let ((p (progn (beginning-of-line) (point))))
1405 ;; We assume that the page header is delimited by blank
1406 ;; lines and that it contains at most one blank line. So
1407 ;; if we back by three blank lines we will be sure to be
1408 ;; before the page header but not before the possible
1409 ;; previous page header.
1410 (search-backward "\n\n" nil t 3)
1411 (if (re-search-forward Man-page-header-regexp p 'move)
1412 (beginning-of-line))))
1413 (setq page-end (point))
1414 (setq Man-page-list (append Man-page-list
1415 (list (list (copy-marker page-start)
1416 (copy-marker page-end)
1417 header))))
1418 (setq page-start page-end)
1421 (defun Man-strip-page-headers ()
1422 "Strip all the page headers but the first from the manpage."
1423 (let ((inhibit-read-only t)
1424 (case-fold-search nil)
1425 (header ""))
1426 (dolist (page Man-page-list)
1427 (and (nth 2 page)
1428 (goto-char (car page))
1429 (re-search-forward Man-first-heading-regexp nil t)
1430 (setq header (buffer-substring (car page) (match-beginning 0)))
1431 ;; Since the awk script collapses all successive blank
1432 ;; lines into one, and since we don't want to get rid of
1433 ;; the fast awk script, one must choose between adding
1434 ;; spare blank lines between pages when there were none and
1435 ;; deleting blank lines at page boundaries when there were
1436 ;; some. We choose the first, so we comment the following
1437 ;; line.
1438 ;; (setq header (concat "\n" header)))
1439 (while (search-forward header (nth 1 page) t)
1440 (replace-match ""))))))
1442 (defun Man-unindent ()
1443 "Delete the leading spaces that indent the manpage."
1444 (let ((inhibit-read-only t)
1445 (case-fold-search nil))
1446 (dolist (page Man-page-list)
1447 (let ((indent "")
1448 (nindent 0))
1449 (narrow-to-region (car page) (car (cdr page)))
1450 (if Man-uses-untabify-flag
1451 (untabify (point-min) (point-max)))
1452 (if (catch 'unindent
1453 (goto-char (point-min))
1454 (if (not (re-search-forward Man-first-heading-regexp nil t))
1455 (throw 'unindent nil))
1456 (beginning-of-line)
1457 (setq indent (buffer-substring (point)
1458 (progn
1459 (skip-chars-forward " ")
1460 (point))))
1461 (setq nindent (length indent))
1462 (if (zerop nindent)
1463 (throw 'unindent nil))
1464 (setq indent (concat indent "\\|$"))
1465 (goto-char (point-min))
1466 (while (not (eobp))
1467 (if (looking-at indent)
1468 (forward-line 1)
1469 (throw 'unindent nil)))
1470 (goto-char (point-min)))
1471 (while (not (eobp))
1472 (or (eolp)
1473 (delete-char nindent))
1474 (forward-line 1)))
1475 ))))
1478 ;; ======================================================================
1479 ;; Man mode commands
1481 (defun Man-next-section (n)
1482 "Move point to Nth next section (default 1)."
1483 (interactive "p")
1484 (let ((case-fold-search nil)
1485 (start (point)))
1486 (if (looking-at Man-heading-regexp)
1487 (forward-line 1))
1488 (if (re-search-forward Man-heading-regexp (point-max) t n)
1489 (beginning-of-line)
1490 (goto-char (point-max))
1491 ;; The last line doesn't belong to any section.
1492 (forward-line -1))
1493 ;; But don't move back from the starting point (can happen if `start'
1494 ;; is somewhere on the last line).
1495 (if (< (point) start) (goto-char start))))
1497 (defun Man-previous-section (n)
1498 "Move point to Nth previous section (default 1)."
1499 (interactive "p")
1500 (let ((case-fold-search nil))
1501 (if (looking-at Man-heading-regexp)
1502 (forward-line -1))
1503 (if (re-search-backward Man-heading-regexp (point-min) t n)
1504 (beginning-of-line)
1505 (goto-char (point-min)))))
1507 (defun Man-find-section (section)
1508 "Move point to SECTION if it exists, otherwise don't move point.
1509 Returns t if section is found, nil otherwise."
1510 (let ((curpos (point))
1511 (case-fold-search nil))
1512 (goto-char (point-min))
1513 (if (re-search-forward (concat "^" section) (point-max) t)
1514 (progn (beginning-of-line) t)
1515 (goto-char curpos)
1516 nil)
1519 (defun Man-goto-section ()
1520 "Query for section to move point to."
1521 (interactive)
1522 (aput 'Man-sections-alist
1523 (let* ((default (aheadsym Man-sections-alist))
1524 (completion-ignore-case t)
1525 chosen
1526 (prompt (concat "Go to section (default " default "): ")))
1527 (setq chosen (completing-read prompt Man-sections-alist))
1528 (if (or (not chosen)
1529 (string= chosen ""))
1530 default
1531 chosen)))
1532 (unless (Man-find-section (aheadsym Man-sections-alist))
1533 (error "Section not found")))
1536 (defun Man-goto-see-also-section ()
1537 "Move point to the \"SEE ALSO\" section.
1538 Actually the section moved to is described by `Man-see-also-regexp'."
1539 (interactive)
1540 (if (not (Man-find-section Man-see-also-regexp))
1541 (error "%s" (concat "No " Man-see-also-regexp
1542 " section found in the current manpage"))))
1544 (defun Man-possibly-hyphenated-word ()
1545 "Return a possibly hyphenated word at point.
1546 If the word starts at the first non-whitespace column, and the
1547 previous line ends with a hyphen, return the last word on the previous
1548 line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
1549 as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
1550 \"tcgetp-\" instead of \"grp\"."
1551 (save-excursion
1552 (skip-syntax-backward "w()")
1553 (skip-chars-forward " \t")
1554 (let ((beg (point))
1555 (word (current-word)))
1556 (when (eq beg (save-excursion
1557 (back-to-indentation)
1558 (point)))
1559 (end-of-line 0)
1560 (if (eq (char-before) ?-)
1561 (setq word (current-word))))
1562 word)))
1564 (defun Man-follow-manual-reference (reference)
1565 "Get one of the manpages referred to in the \"SEE ALSO\" section.
1566 Specify which REFERENCE to use; default is based on word at point."
1567 (interactive
1568 (if (not Man-refpages-alist)
1569 (error "There are no references in the current man page")
1570 (list
1571 (let* ((default (or
1572 (car (all-completions
1573 (let ((word
1574 (or (Man-possibly-hyphenated-word)
1575 "")))
1576 ;; strip a trailing '-':
1577 (if (string-match "-$" word)
1578 (substring word 0
1579 (match-beginning 0))
1580 word))
1581 Man-refpages-alist))
1582 (aheadsym Man-refpages-alist)))
1583 (defaults
1584 (mapcar 'substring-no-properties
1585 (delete-dups
1586 (delq nil (cons default
1587 (mapcar 'car Man-refpages-alist))))))
1588 chosen
1589 (prompt (concat "Refer to (default " default "): ")))
1590 (setq chosen (completing-read prompt Man-refpages-alist
1591 nil nil nil nil defaults))
1592 (if (or (not chosen)
1593 (string= chosen ""))
1594 default
1595 chosen)))))
1596 (if (not Man-refpages-alist)
1597 (error "Can't find any references in the current manpage")
1598 (aput 'Man-refpages-alist reference)
1599 (Man-getpage-in-background
1600 (Man-translate-references (aheadsym Man-refpages-alist)))))
1602 (defun Man-kill ()
1603 "Kill the buffer containing the manpage."
1604 (interactive)
1605 (quit-window t))
1607 (defun Man-quit ()
1608 "Bury the buffer containing the manpage."
1609 (interactive)
1610 (quit-window))
1612 (defun Man-goto-page (page &optional noerror)
1613 "Go to the manual page on page PAGE."
1614 (interactive
1615 (if (not Man-page-list)
1616 (error "Not a man page buffer")
1617 (if (= (length Man-page-list) 1)
1618 (error "You're looking at the only manpage in the buffer")
1619 (list (read-minibuffer (format "Go to manpage [1-%d]: "
1620 (length Man-page-list)))))))
1621 (if (and (not Man-page-list) (not noerror))
1622 (error "Not a man page buffer"))
1623 (when Man-page-list
1624 (if (or (< page 1)
1625 (> page (length Man-page-list)))
1626 (error "No manpage %d found" page))
1627 (let* ((page-range (nth (1- page) Man-page-list))
1628 (page-start (car page-range))
1629 (page-end (car (cdr page-range))))
1630 (setq Man-current-page page
1631 Man-page-mode-string (Man-make-page-mode-string))
1632 (widen)
1633 (goto-char page-start)
1634 (narrow-to-region page-start page-end)
1635 (Man-build-section-alist)
1636 (Man-build-references-alist)
1637 (goto-char (point-min)))))
1640 (defun Man-next-manpage ()
1641 "Find the next manpage entry in the buffer."
1642 (interactive)
1643 (if (= (length Man-page-list) 1)
1644 (error "This is the only manpage in the buffer"))
1645 (if (< Man-current-page (length Man-page-list))
1646 (Man-goto-page (1+ Man-current-page))
1647 (if Man-circular-pages-flag
1648 (Man-goto-page 1)
1649 (error "You're looking at the last manpage in the buffer"))))
1651 (defun Man-previous-manpage ()
1652 "Find the previous manpage entry in the buffer."
1653 (interactive)
1654 (if (= (length Man-page-list) 1)
1655 (error "This is the only manpage in the buffer"))
1656 (if (> Man-current-page 1)
1657 (Man-goto-page (1- Man-current-page))
1658 (if Man-circular-pages-flag
1659 (Man-goto-page (length Man-page-list))
1660 (error "You're looking at the first manpage in the buffer"))))
1662 ;; Header file support
1663 (defun Man-view-header-file (file)
1664 "View a header file specified by FILE from `Man-header-file-path'."
1665 (let ((path Man-header-file-path)
1666 complete-path)
1667 (while path
1668 (setq complete-path (expand-file-name file (car path))
1669 path (cdr path))
1670 (if (file-readable-p complete-path)
1671 (progn (view-file complete-path)
1672 (setq path nil))
1673 (setq complete-path nil)))
1674 complete-path))
1676 ;;; Bookmark Man Support
1677 (declare-function bookmark-make-record-default
1678 "bookmark" (&optional no-file no-context posn))
1679 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1680 (declare-function bookmark-default-handler "bookmark" (bmk))
1681 (declare-function bookmark-get-bookmark-record "bookmark" (bmk))
1683 (defun Man-default-bookmark-title ()
1684 "Default bookmark name for Man or WoMan pages.
1685 Uses `Man-name-local-regexp'."
1686 (save-excursion
1687 (goto-char (point-min))
1688 (when (re-search-forward Man-name-local-regexp nil t)
1689 (skip-chars-forward "\n\t ")
1690 (buffer-substring-no-properties (point) (line-end-position)))))
1692 (defun Man-bookmark-make-record ()
1693 "Make a bookmark entry for a Man buffer."
1694 `(,(Man-default-bookmark-title)
1695 ,@(bookmark-make-record-default 'no-file)
1696 (location . ,(concat "man " Man-arguments))
1697 (man-args . ,Man-arguments)
1698 (handler . Man-bookmark-jump)))
1700 ;;;###autoload
1701 (defun Man-bookmark-jump (bookmark)
1702 "Default bookmark handler for Man buffers."
1703 (let* ((man-args (bookmark-prop-get bookmark 'man-args))
1704 ;; Let bookmark.el do the window handling.
1705 ;; This let-binding needs to be active during the call to both
1706 ;; Man-getpage-in-background and accept-process-output.
1707 (Man-notify-method 'meek)
1708 (buf (Man-getpage-in-background man-args))
1709 (proc (get-buffer-process buf)))
1710 (while (and proc (eq (process-status proc) 'run))
1711 (accept-process-output proc))
1712 (bookmark-default-handler
1713 `("" (buffer . ,buf) . ,(bookmark-get-bookmark-record bookmark)))))
1716 ;; Init the man package variables, if not already done.
1717 (Man-init-defvars)
1719 (add-to-list 'debug-ignored-errors "^No manpage [0-9]* found$")
1720 (add-to-list 'debug-ignored-errors "^Can't find the .* manpage$")
1722 (provide 'man)
1724 ;; arch-tag: 587cda76-8e23-4594-b1f3-89b6b09a0d47
1725 ;;; man.el ends here