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