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