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