Allow 'browse-url-emacs' to fetch URL in the selected window
[emacs.git] / lisp / man.el
blob1a6eda13b7fcd26b10d25f53ca90fcf36e35a0a2
1 ;;; man.el --- browse UNIX manual pages -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993-1994, 1996-1997, 2001-2018 Free Software
4 ;; Foundation, Inc.
6 ;; Author: Barry A. Warsaw <bwarsaw@cen.com>
7 ;; Maintainer: emacs-devel@gnu.org
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 <https://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 Potortì <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 one 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 'cl-lib)
93 (require 'button)
95 (defgroup man nil
96 "Browse UNIX manual pages."
97 :prefix "Man-"
98 :group 'external
99 :group 'help)
101 (defvar Man-notify)
103 (defcustom Man-filter-list nil
104 "Manpage cleaning filter command phrases.
105 This variable contains a list of the following form:
107 ((command-string phrase-string*)*)
109 Each phrase-string is concatenated onto the command-string to form a
110 command filter. The (standard) output (and standard error) of the Un*x
111 man command is piped through each command filter in the order the
112 commands appear in the association list. The final output is placed in
113 the manpage buffer."
114 :type '(repeat (list (string :tag "Command String")
115 (repeat :inline t
116 (string :tag "Phrase String"))))
117 :group 'man)
119 (defvar Man-uses-untabify-flag t
120 "Non-nil means use `untabify' instead of `Man-untabify-command'.")
121 (defvar Man-sed-script nil
122 "Script for sed to nuke backspaces and ANSI codes from manpages.")
124 (defcustom Man-fontify-manpage-flag t
125 "Non-nil means make up the manpage with fonts."
126 :type 'boolean
127 :group 'man)
129 (defface Man-overstrike
130 '((t (:inherit bold)))
131 "Face to use when fontifying overstrike."
132 :group 'man
133 :version "24.3")
135 (defface Man-underline
136 '((t (:inherit underline)))
137 "Face to use when fontifying underlining."
138 :group 'man
139 :version "24.3")
141 (defface Man-reverse
142 '((t (:inherit highlight)))
143 "Face to use when fontifying reverse video."
144 :group 'man
145 :version "24.3")
147 (defvar Man-ansi-color-map (let ((ansi-color-faces-vector
148 [ default Man-overstrike default Man-underline
149 Man-underline default default Man-reverse ]))
150 (ansi-color-make-color-map))
151 "The value used here for `ansi-color-map'.")
153 ;; Use the value of the obsolete user option Man-notify, if set.
154 (defcustom Man-notify-method (if (boundp 'Man-notify) Man-notify 'friendly)
155 "Selects the behavior when manpage is ready.
156 This variable may have one of the following values, where (sf) means
157 that the frames are switched, so the manpage is displayed in the frame
158 where the man command was called from:
160 newframe -- put the manpage in its own frame (see `Man-frame-parameters')
161 pushy -- make the manpage the current buffer in the current window
162 bully -- make the manpage the current buffer and only window (sf)
163 aggressive -- make the manpage the current buffer in the other window (sf)
164 friendly -- display manpage in the other window but don't make current (sf)
165 polite -- don't display manpage, but prints message and beep when ready
166 quiet -- like `polite', but don't beep
167 meek -- make no indication that the manpage is ready
169 Any other value of `Man-notify-method' is equivalent to `meek'."
170 :type '(radio (const newframe) (const pushy) (const bully)
171 (const aggressive) (const friendly)
172 (const polite) (const quiet) (const meek))
173 :group 'man)
175 (defcustom Man-width nil
176 "Number of columns for which manual pages should be formatted.
177 If nil, use the width of the window where the manpage is displayed.
178 If non-nil, use the width of the frame where the manpage is displayed.
179 The value also can be a positive integer for a fixed width."
180 :type '(choice (const :tag "Window width" nil)
181 (const :tag "Frame width" t)
182 (integer :tag "Fixed 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 '(repeat (cons :format "%v"
188 (symbol :tag "Parameter")
189 (sexp :tag "Value")))
190 :group 'man)
192 (defcustom Man-downcase-section-letters-flag t
193 "Non-nil means letters in sections are converted to lower case.
194 Some Un*x man commands can't handle uppercase letters in sections, for
195 example \"man 2V chmod\", but they are often displayed in the manpage
196 with the upper case letter. When this variable is t, the section
197 letter (e.g., \"2V\") is converted to lowercase (e.g., \"2v\") before
198 being sent to the man background process."
199 :type 'boolean
200 :group 'man)
202 (defcustom Man-circular-pages-flag t
203 "Non-nil means the manpage list is treated as circular for traversal."
204 :type 'boolean
205 :group 'man)
207 (defcustom Man-section-translations-alist
208 (list
209 '("3C++" . "3")
210 ;; Some systems have a real 3x man section, so let's comment this.
211 ;; '("3X" . "3") ; Xlib man pages
212 '("3X11" . "3")
213 '("1-UCB" . ""))
214 "Association list of bogus sections to real section numbers.
215 Some manpages (e.g. the Sun C++ 2.1 manpages) have section numbers in
216 their references which Un*x `man' does not recognize. This
217 association list is used to translate those sections, when found, to
218 the associated section number."
219 :type '(repeat (cons (string :tag "Bogus Section")
220 (string :tag "Real Section")))
221 :group 'man)
223 ;; FIXME see comments at ffap-c-path.
224 (defcustom Man-header-file-path
225 (let ((arch (with-temp-buffer
226 (when (eq 0 (ignore-errors
227 (call-process "gcc" nil '(t nil) nil
228 "-print-multiarch")))
229 (goto-char (point-min))
230 (buffer-substring (point) (line-end-position)))))
231 (base '("/usr/include" "/usr/local/include")))
232 (if (zerop (length arch))
233 base
234 (append base (list (expand-file-name arch "/usr/include")))))
235 "C Header file search path used in Man."
236 :version "24.1" ; add multiarch
237 :type '(repeat string)
238 :group 'man)
240 (defcustom Man-name-local-regexp (concat "^" (regexp-opt '("NOM" "NAME")) "$")
241 "Regexp that matches the text that precedes the command's name.
242 Used in `bookmark-set' to get the default bookmark name."
243 :version "24.1"
244 :type 'string :group 'bookmark)
246 (defcustom manual-program "man"
247 "Program used by `man' to produce man pages."
248 :type 'string
249 :group 'man)
251 (defcustom Man-untabify-command "pr"
252 "Program used by `man' for untabifying."
253 :type 'string
254 :group 'man)
256 (defcustom Man-untabify-command-args (list "-t" "-e")
257 "List of arguments to be passed to `Man-untabify-command' (which see)."
258 :type '(repeat string)
259 :group 'man)
261 (defcustom Man-sed-command "sed"
262 "Program used by `man' to process sed scripts."
263 :type 'string
264 :group 'man)
266 (defcustom Man-awk-command "awk"
267 "Program used by `man' to process awk scripts."
268 :type 'string
269 :group 'man)
271 ;; This is for people who have UTF-8 encoded man pages in non-UTF-8
272 ;; locales, or who use Cygwin 'man' command from a native MS-Windows
273 ;; build of Emacs.
274 (defcustom Man-coding-system nil
275 "Coding-system to decode output from the commands run by `man'.
276 If this is nil, `man' will use `locale-coding-system'."
277 :type 'coding-system
278 :group 'man
279 :version "26.1")
281 (defcustom Man-mode-hook nil
282 "Hook run when Man mode is enabled."
283 :type 'hook
284 :group 'man)
286 (defcustom Man-cooked-hook nil
287 "Hook run after removing backspaces but before `Man-mode' processing."
288 :type 'hook
289 :group 'man)
291 (defvar Man-name-regexp "[-[:alnum:]_­+][-[:alnum:]_.:­+]*"
292 "Regular expression describing the name of a manpage (without section).")
294 (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
295 "Regular expression describing a manpage section within parentheses.")
297 (defvar Man-page-header-regexp
298 (if (string-match "-solaris2\\." system-configuration)
299 (concat "^[-[:alnum:]_].*[ \t]\\(" Man-name-regexp
300 "(\\(" Man-section-regexp "\\))\\)$")
301 (concat "^[ \t]*\\(" Man-name-regexp
302 "(\\(" Man-section-regexp "\\))\\).*\\1"))
303 "Regular expression describing the heading of a page.")
305 (defvar Man-heading-regexp "^\\([[:upper:]][[:upper:]0-9 /-]+\\)$"
306 "Regular expression describing a manpage heading entry.")
308 (defvar Man-see-also-regexp "\\(SEE ALSO\\|VOIR AUSSI\\|SIEHE AUCH\\|VÉASE TAMBIÉN\\|VEJA TAMBÉM\\|VEDERE ANCHE\\|ZOBACZ TAKŻE\\|İLGİLİ BELGELER\\|参照\\|参见 SEE ALSO\\|參見 SEE ALSO\\)"
309 "Regular expression for SEE ALSO heading (or your equivalent).
310 This regexp should not start with a `^' character.")
312 ;; This used to have leading space [ \t]*, but was removed because it
313 ;; causes false page splits on an occasional NAME with leading space
314 ;; inside a manpage. And `Man-heading-regexp' doesn't have [ \t]* anyway.
315 (defvar Man-first-heading-regexp "^NAME$\\|^[ \t]*No manual entry fo.*$"
316 "Regular expression describing first heading on a manpage.
317 This regular expression should start with a `^' character.")
319 (defvar Man-reference-regexp
320 (concat "\\(" Man-name-regexp
321 "\\(‐?\n[ \t]+" Man-name-regexp "\\)*\\)[ \t]*(\\("
322 Man-section-regexp "\\))")
323 "Regular expression describing a reference to another manpage.")
325 (defvar Man-apropos-regexp
326 (concat "\\[\\(" Man-name-regexp "\\)\\][ \t]*(\\(" Man-section-regexp "\\))")
327 "Regular expression describing a reference to manpages in \"man -k output\".")
329 (defvar Man-synopsis-regexp "SYNOPSIS"
330 "Regular expression for SYNOPSIS heading (or your equivalent).
331 This regexp should not start with a `^' character.")
333 (defvar Man-files-regexp "FILES\\>"
334 ;; Add \> so as not to match mount(8)'s FILESYSTEM INDEPENDENT MOUNT OPTIONS.
335 "Regular expression for FILES heading (or your equivalent).
336 This regexp should not start with a `^' character.")
338 (defvar Man-include-regexp "#[ \t]*include[ \t]*"
339 "Regular expression describing the #include (directive of cpp).")
341 (defvar Man-file-name-regexp "[^<>\", \t\n]+"
342 "Regular expression describing <> in #include line (directive of cpp).")
344 (defvar Man-normal-file-prefix-regexp "[/~$]"
345 "Regular expression describing a file path appeared in FILES section.")
347 (defvar Man-header-regexp
348 (concat "\\(" Man-include-regexp "\\)"
349 "[<\"]"
350 "\\(" Man-file-name-regexp "\\)"
351 "[>\"]")
352 "Regular expression describing references to header files.")
354 (defvar Man-normal-file-regexp
355 (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
356 "Regular expression describing references to normal files.")
358 ;; This includes the section as an optional part to catch hyphenated
359 ;; references to manpages.
360 (defvar Man-hyphenated-reference-regexp
361 (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
362 "Regular expression describing a reference in the SEE ALSO section.")
364 (defcustom Man-switches ""
365 "Switches passed to the man command, as a single string.
366 For example, the -a switch lets you see all the manpages for a
367 specified subject, if your `man' program supports it."
368 :type 'string
369 :group 'man)
371 (defvar Man-specified-section-option
372 (if (string-match "-solaris[0-9.]*$" system-configuration)
373 "-s"
375 "Option that indicates a specified a manual section name.")
377 (defvar Man-support-local-filenames 'auto-detect
378 "Internal cache for the value of the function `Man-support-local-filenames'.
379 `auto-detect' means the value is not yet determined.
380 Otherwise, the value is whatever the function
381 `Man-support-local-filenames' should return.")
383 (defcustom man-imenu-title "Contents"
384 "The title to use if man adds a Contents menu to the menubar."
385 :version "24.4"
386 :type 'string
387 :group 'man)
390 ;; other variables and keymap initializations
391 (defvar Man-original-frame)
392 (make-variable-buffer-local 'Man-original-frame)
393 (defvar Man-arguments)
394 (make-variable-buffer-local 'Man-arguments)
395 (put 'Man-arguments 'permanent-local t)
397 (defvar Man--sections nil)
398 (make-variable-buffer-local 'Man--sections)
399 (defvar Man--refpages nil)
400 (make-variable-buffer-local 'Man--refpages)
401 (defvar Man-page-list nil)
402 (make-variable-buffer-local 'Man-page-list)
403 (defvar Man-current-page 0)
404 (make-variable-buffer-local 'Man-current-page)
405 (defvar Man-page-mode-string "1 of 1")
406 (make-variable-buffer-local 'Man-page-mode-string)
408 (defconst Man-sysv-sed-script "\
409 /\b/ { s/_\b//g
410 s/\b_//g
411 s/o\b+/o/g
412 s/+\bo/o/g
413 :ovstrk
414 s/\\(.\\)\b\\1/\\1/g
415 t ovstrk
417 /\e\\[[0-9][0-9]*m/ s///g"
418 "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
420 (defconst Man-berkeley-sed-script "\
421 /\b/ { s/_\b//g\\
422 s/\b_//g\\
423 s/o\b+/o/g\\
424 s/+\bo/o/g\\
425 :ovstrk\\
426 s/\\(.\\)\b\\1/\\1/g\\
427 t ovstrk\\
429 /\e\\[[0-9][0-9]*m/ s///g"
430 "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
432 (defvar Man-topic-history nil "Topic read history.")
434 (defvar Man-mode-syntax-table
435 (let ((table (copy-syntax-table (standard-syntax-table))))
436 (modify-syntax-entry ?. "w" table)
437 (modify-syntax-entry ?_ "w" table)
438 (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
439 table)
440 "Syntax table used in Man mode buffers.")
442 (defvar Man-mode-map
443 (let ((map (make-sparse-keymap)))
444 (suppress-keymap map)
445 (set-keymap-parent map
446 (make-composed-keymap button-buffer-map special-mode-map))
448 (define-key map "n" 'Man-next-section)
449 (define-key map "p" 'Man-previous-section)
450 (define-key map "\en" 'Man-next-manpage)
451 (define-key map "\ep" 'Man-previous-manpage)
452 (define-key map "." 'beginning-of-buffer)
453 (define-key map "r" 'Man-follow-manual-reference)
454 (define-key map "g" 'Man-goto-section)
455 (define-key map "s" 'Man-goto-see-also-section)
456 (define-key map "k" 'Man-kill)
457 (define-key map "u" 'Man-update-manpage)
458 (define-key map "m" 'man)
459 ;; Not all the man references get buttons currently. The text in the
460 ;; manual page can contain references to other man pages
461 (define-key map "\r" 'man-follow)
463 (easy-menu-define nil map
464 "`Man-mode' menu."
465 '("Man"
466 ["Next Section" Man-next-section t]
467 ["Previous Section" Man-previous-section t]
468 ["Go To Section..." Man-goto-section t]
469 ["Go To \"SEE ALSO\" Section" Man-goto-see-also-section
470 :active (cl-member Man-see-also-regexp Man--sections
471 :test #'string-match-p)]
472 ["Follow Reference..." Man-follow-manual-reference
473 :active Man--refpages
474 :help "Go to a manpage referred to in the \"SEE ALSO\" section"]
475 "--"
476 ["Next Manpage" Man-next-manpage
477 :active (> (length Man-page-list) 1)]
478 ["Previous Manpage" Man-previous-manpage
479 :active (> (length Man-page-list) 1)]
480 "--"
481 ["Man..." man t]
482 ["Kill Buffer" Man-kill t]
483 ["Quit" quit-window t]))
484 map)
485 "Keymap for Man mode.")
487 ;; buttons
488 (define-button-type 'Man-abstract-xref-man-page
489 'follow-link t
490 'help-echo "mouse-2, RET: display this man page"
491 'func nil
492 'action #'Man-xref-button-action)
494 (defun Man-xref-button-action (button)
495 (let ((target (button-get button 'Man-target-string)))
496 (funcall
497 (button-get button 'func)
498 (cond ((null target)
499 (button-label button))
500 ((functionp target)
501 (funcall target (button-start button)))
502 (t target)))))
504 (define-button-type 'Man-xref-man-page
505 :supertype 'Man-abstract-xref-man-page
506 'func 'man-follow)
509 (define-button-type 'Man-xref-header-file
510 'action (lambda (button)
511 (let ((w (button-get button 'Man-target-string)))
512 (unless (Man-view-header-file w)
513 (error "Cannot find header file: %s" w))))
514 'follow-link t
515 'help-echo "mouse-2: display this header file")
517 (define-button-type 'Man-xref-normal-file
518 'action (lambda (button)
519 (let ((f (substitute-in-file-name
520 (button-get button 'Man-target-string))))
521 (if (file-exists-p f)
522 (if (file-readable-p f)
523 (view-file f)
524 (error "Cannot read a file: %s" f))
525 (error "Cannot find a file: %s" f))))
526 'follow-link t
527 'help-echo "mouse-2: display this file")
530 ;; ======================================================================
531 ;; utilities
533 (defun Man-init-defvars ()
534 "Used for initializing variables based on display's color support.
535 This is necessary if one wants to dump man.el with Emacs."
537 ;; Avoid possible error in call-process by using a directory that must exist.
538 (let ((default-directory "/"))
539 (setq Man-sed-script
540 (cond
541 (Man-fontify-manpage-flag
542 nil)
543 ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
544 Man-sysv-sed-script)
545 ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
546 Man-berkeley-sed-script)
548 nil))))
550 (setq Man-filter-list
551 ;; Avoid trailing nil which confuses customize.
552 (apply 'list
553 (cons
554 Man-sed-command
555 (if (eq system-type 'windows-nt)
556 ;; Windows needs ".." quoting, not '..'.
557 (list
558 "-e \"/Reformatting page. Wait/d\""
559 "-e \"/Reformatting entry. Wait/d\""
560 "-e \"/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d\""
561 "-e \"/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d\""
562 "-e \"/^Printed[ \t][0-9].*[0-9]$/d\""
563 "-e \"/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d\""
564 "-e \"/^[A-Za-z].*Last[ \t]change:/d\""
565 "-e \"/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d\""
566 "-e \"/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d\"")
567 (list
568 (if Man-sed-script
569 (concat "-e '" Man-sed-script "'")
571 "-e '/^[\001-\032][\001-\032]*$/d'"
572 "-e '/\e[789]/s///g'"
573 "-e '/Reformatting page. Wait/d'"
574 "-e '/Reformatting entry. Wait/d'"
575 "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
576 "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
577 "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
578 "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
579 "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
580 "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
581 "-e '/^[A-Za-z].*Last[ \t]change:/d'"
582 "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
583 "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
584 "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
586 ;; Windows doesn't support multi-line commands, so don't
587 ;; invoke Awk there.
588 (unless (eq system-type 'windows-nt)
589 (cons
590 Man-awk-command
591 (list
592 "'\n"
593 "BEGIN { blankline=0; anonblank=0; }\n"
594 "/^$/ { if (anonblank==0) next; }\n"
595 "{ anonblank=1; }\n"
596 "/^$/ { blankline++; next; }\n"
597 "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
600 (if (not Man-uses-untabify-flag)
601 ;; The outer list will be stripped off by apply.
602 (list (cons
603 Man-untabify-command
604 Man-untabify-command-args))
608 (defsubst Man-make-page-mode-string ()
609 "Formats part of the mode line for Man mode."
610 (format "%s page %d of %d"
611 (or (nth 2 (nth (1- Man-current-page) Man-page-list))
613 Man-current-page
614 (length Man-page-list)))
616 (defsubst Man-build-man-command ()
617 "Builds the entire background manpage and cleaning command."
618 (let ((command (concat manual-program " " Man-switches
619 (cond
620 ;; Already has %s
621 ((string-match "%s" manual-program) "")
622 ;; Stock MS-DOS shells cannot redirect stderr;
623 ;; `call-process' below sends it to /dev/null,
624 ;; so we don't need `2>' even with DOS shells
625 ;; which do support stderr redirection.
626 ((not (fboundp 'make-process)) " %s")
627 ((concat " %s 2>" null-device)))))
628 (flist Man-filter-list))
629 (while (and flist (car flist))
630 (let ((pcom (car (car flist)))
631 (pargs (cdr (car flist))))
632 (setq command
633 (concat command " | " pcom " "
634 (mapconcat (lambda (phrase)
635 (if (not (stringp phrase))
636 (error "Malformed Man-filter-list"))
637 phrase)
638 pargs " ")))
639 (setq flist (cdr flist))))
640 command))
643 (defun Man-translate-cleanup (string)
644 "Strip leading, trailing and middle spaces."
645 (when (stringp string)
646 ;; Strip leading and trailing
647 (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
648 (setq string (match-string 1 string)))
649 ;; middle spaces
650 (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
651 (setq string (replace-regexp-in-string " +" " " string))
652 string))
654 (defun Man-translate-references (ref)
655 "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
656 Leave it as is if already in that style. Possibly downcase and
657 translate the section (see the `Man-downcase-section-letters-flag'
658 and the `Man-section-translations-alist' variables)."
659 (let ((name "")
660 (section "")
661 (slist Man-section-translations-alist))
662 (setq ref (Man-translate-cleanup ref))
663 (cond
664 ;; "chmod(2V)" case ?
665 ((string-match (concat "^" Man-reference-regexp "$") ref)
666 (setq name (replace-regexp-in-string "[\n\t ]" "" (match-string 1 ref))
667 section (match-string 3 ref)))
668 ;; "2v chmod" case ?
669 ((string-match (concat "^\\(" Man-section-regexp
670 "\\) +\\(" Man-name-regexp "\\)$") ref)
671 (setq name (match-string 2 ref)
672 section (match-string 1 ref))))
673 (if (string= name "")
674 ref ; Return the reference as is
675 (if Man-downcase-section-letters-flag
676 (setq section (downcase section)))
677 (while slist
678 (let ((s1 (car (car slist)))
679 (s2 (cdr (car slist))))
680 (setq slist (cdr slist))
681 (if Man-downcase-section-letters-flag
682 (setq s1 (downcase s1)))
683 (if (not (string= s1 section)) nil
684 (setq section (if Man-downcase-section-letters-flag
685 (downcase s2)
687 slist nil))))
688 (concat Man-specified-section-option section " " name))))
690 (defun Man-support-local-filenames ()
691 "Return non-nil if the man command supports local filenames.
692 Different man programs support this feature in different ways.
693 The default Debian man program (\"man-db\") has a `--local-file'
694 \(or `-l') option for this purpose. The default Red Hat man
695 program has no such option, but interprets any name containing
696 a \"/\" as a local filename. The function returns either `man-db'
697 `man', or nil."
698 (if (eq Man-support-local-filenames 'auto-detect)
699 (setq Man-support-local-filenames
700 (with-temp-buffer
701 (let ((default-directory
702 ;; Ensure that `default-directory' exists and is readable.
703 (if (file-accessible-directory-p default-directory)
704 default-directory
705 (expand-file-name "~/"))))
706 (ignore-errors
707 (call-process manual-program nil t nil "--help")))
708 (cond ((search-backward "--local-file" nil 'move)
709 'man-db)
710 ;; This feature seems to be present in at least ver 1.4f,
711 ;; which is about 20 years old.
712 ;; I don't know if this version has an official name?
713 ((looking-at "^man, versione? [1-9]")
714 'man))))
715 Man-support-local-filenames))
718 ;; ======================================================================
719 ;; default man entry: get word near point
721 (defun Man-default-man-entry (&optional pos)
722 "Guess default manual entry based on the text near position POS.
723 POS defaults to `point'."
724 (let (word start column distance)
725 (save-excursion
726 (when pos (goto-char pos))
727 (setq pos (point))
728 ;; The default title is the nearest entry-like object before or
729 ;; after POS.
730 (if (and (skip-chars-backward " \ta-zA-Z0-9+")
731 (not (zerop (skip-chars-backward "(")))
732 ;; Try to handle the special case where POS is on a
733 ;; section number.
734 (looking-at
735 (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
736 ;; We skipped a valid section number backwards, look at
737 ;; preceding text.
738 (or (and (skip-chars-backward ",; \t")
739 (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
740 ;; Not a valid entry, move POS after closing paren.
741 (not (setq pos (match-end 0)))))
742 ;; We have a candidate, make `start' record its starting
743 ;; position.
744 (setq start (point))
745 ;; Otherwise look at char before POS.
746 (goto-char pos)
747 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
748 ;; Our candidate is just before or around POS.
749 (setq start (point))
750 ;; Otherwise record the current column and look backwards.
751 (setq column (current-column))
752 (skip-chars-backward ",; \t")
753 ;; Record the distance traveled.
754 (setq distance (- column (current-column)))
755 (when (looking-back
756 (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)")
757 (line-beginning-position))
758 ;; Skip section number backwards.
759 (goto-char (match-beginning 0))
760 (skip-chars-backward " \t"))
761 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
762 (progn
763 ;; We have a candidate before POS ...
764 (setq start (point))
765 (goto-char pos)
766 (if (and (skip-chars-forward ",; \t")
767 (< (- (current-column) column) distance)
768 (looking-at "[-a-zA-Z0-9._+:]"))
769 ;; ... but the one after POS is better.
770 (setq start (point))
771 ;; ... and anything after POS is worse.
772 (goto-char start)))
773 ;; No candidate before POS.
774 (goto-char pos)
775 (skip-chars-forward ",; \t")
776 (setq start (point)))))
777 ;; We have found a suitable starting point, try to skip at least
778 ;; one character.
779 (skip-chars-forward "-a-zA-Z0-9._+:")
780 (setq word (buffer-substring-no-properties start (point)))
781 ;; If there is a continuation at the end of line, check the
782 ;; following line too, eg:
783 ;; see this-
784 ;; command-here(1)
785 ;; Note: This code gets executed iff our entry is after POS.
786 (when (looking-at "‐?[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
787 (setq word (concat word (match-string-no-properties 1)))
788 ;; Make sure the section number gets included by the code below.
789 (goto-char (match-end 1)))
790 (when (string-match "[-._]+$" word)
791 (setq word (substring word 0 (match-beginning 0))))
792 ;; The following was commented out since the preceding code
793 ;; should not produce a leading "*" in the first place.
794 ;;; ;; If looking at something like *strcat(... , remove the '*'
795 ;;; (when (string-match "^*" word)
796 ;;; (setq word (substring word 1)))
797 (concat
798 word
799 (and (not (string-equal word ""))
800 ;; If looking at something like ioctl(2) or brc(1M),
801 ;; include the section number in the returned value.
802 (looking-at
803 (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
804 (format "(%s)" (match-string-no-properties 1)))))))
807 ;; ======================================================================
808 ;; Top level command and background process sentinel
810 ;; For compatibility with older versions.
811 ;;;###autoload
812 (defalias 'manual-entry 'man)
814 (defvar Man-completion-cache nil
815 ;; On my machine, "man -k" is so fast that a cache makes no sense,
816 ;; but apparently that's not the case in all cases, so let's add a cache.
817 "Cache of completion table of the form (PREFIX . TABLE).")
819 (defvar Man-man-k-use-anchor
820 ;; man-db or man-1.*
821 (memq system-type '(gnu gnu/linux gnu/kfreebsd))
822 "If non-nil prepend ^ to the prefix passed to \"man -k\" for completion.
823 The value should be nil if \"man -k ^PREFIX\" may omit some man
824 pages whose names start with PREFIX.
826 Currently, the default value depends on `system-type' and is
827 non-nil where the standard man programs are known to behave
828 properly. Setting the value to nil always gives correct results
829 but computing the list of completions may take a bit longer.")
831 (defun Man-parse-man-k ()
832 "Parse \"man -k\" output and return the list of page names.
834 The current buffer should contain the output of a command of the
835 form \"man -k keyword\", which is traditionally also available with
836 apropos(1).
838 While POSIX man(1p) is a bit vague about what to expect here,
839 this function tries to parse some commonly used formats, which
840 can be described in the following informal way, with square brackets
841 indicating optional parts and whitespace being interpreted
842 somewhat loosely.
844 foo[, bar [, ...]] [other stuff] (sec) - description
845 foo(sec)[, bar(sec) [, ...]] [other stuff] - description"
846 (goto-char (point-min))
847 ;; See man-tests for data about which systems use which format (hopefully we
848 ;; will be able to simplify the code if/when some of those formats aren't
849 ;; used any more).
850 (let (table)
851 (while (search-forward-regexp "^\\([^ \t,\n]+\\)\\(.*?\\)\
852 \\(?:[ \t]\\(([^ \t,\n]+?)\\)\\)?\\(?:[ \t]+- ?\\(.*\\)\\)?$" nil t)
853 (let ((section (match-string 3))
854 (description (match-string 4))
855 (bound (match-end 2)))
856 (goto-char (match-end 1))
857 (while
858 (progn
859 ;; The first regexp grouping may already match the section
860 ;; tacked on to the name, which is ok since for the formats we
861 ;; claim to support the third (non-shy) grouping does not
862 ;; match in this case, i.e., section is nil.
863 (push (propertize (concat (match-string 1) section)
864 'help-echo description)
865 table)
866 (search-forward-regexp "\\=, *\\([^ \t,]+\\)" bound t)))))
867 (nreverse table)))
869 (defun Man-completion-table (string pred action)
870 (cond
871 ;; This ends up returning t for pretty much any string, and hence leads to
872 ;; spurious "complete but not unique" messages. And since `man' doesn't
873 ;; require-match anyway, there's not point being clever.
874 ;;((eq action 'lambda) (not (string-match "([^)]*\\'" string)))
875 ((equal string "-k")
876 ;; Let SPC (minibuffer-complete-word) insert the space.
877 (complete-with-action action '("-k ") string pred))
879 (let ((table (cdr Man-completion-cache))
880 (section nil)
881 (prefix string))
882 (when (string-match "\\`\\([[:digit:]].*?\\) " string)
883 (setq section (match-string 1 string))
884 (setq prefix (substring string (match-end 0))))
885 (unless (and Man-completion-cache
886 (string-prefix-p (car Man-completion-cache) prefix))
887 (with-temp-buffer
888 (setq default-directory "/") ;; in case inherited doesn't exist
889 ;; Actually for my `man' the arg is a regexp.
890 ;; POSIX says it must be ERE and "man-db" seems to agree,
891 ;; whereas under macOS it seems to be BRE-style and doesn't
892 ;; accept backslashes at all. Let's not bother to
893 ;; quote anything.
894 (let ((process-environment (copy-sequence process-environment)))
895 (setenv "COLUMNS" "999") ;; don't truncate long names
896 ;; manual-program might not even exist. And since it's
897 ;; run differently in Man-getpage-in-background, an error
898 ;; here may not necessarily mean that we'll also get an
899 ;; error later.
900 (ignore-errors
901 (call-process manual-program nil '(t nil) nil
902 "-k" (concat (when (or Man-man-k-use-anchor
903 (string-equal prefix ""))
904 "^")
905 prefix))))
906 (setq table (Man-parse-man-k)))
907 ;; Cache the table for later reuse.
908 (setq Man-completion-cache (cons prefix table)))
909 ;; The table may contain false positives since the match is made
910 ;; by "man -k" not just on the manpage's name.
911 (if section
912 (let ((re (concat "(" (regexp-quote section) ")\\'")))
913 (dolist (comp (prog1 table (setq table nil)))
914 (if (string-match re comp)
915 (push (substring comp 0 (match-beginning 0)) table)))
916 (completion-table-with-context (concat section " ") table
917 prefix pred action))
918 ;; If the current text looks like a possible section name,
919 ;; then add a completion entry that just adds a space so SPC
920 ;; can be used to insert a space.
921 (if (string-match "\\`[[:digit:]]" string)
922 (push (concat string " ") table))
923 (let ((res (complete-with-action action table string pred)))
924 ;; In case we're completing to a single name that exists in
925 ;; several sections, the longest prefix will look like "foo(".
926 (if (and (stringp res)
927 (string-match "([^(]*\\'" res)
928 ;; In case the paren was already in `prefix', don't
929 ;; remove it.
930 (> (match-beginning 0) (length prefix)))
931 (substring res 0 (match-beginning 0))
932 res)))))))
934 ;;;###autoload
935 (defun man (man-args)
936 "Get a Un*x manual page and put it in a buffer.
937 This command is the top-level command in the man package.
938 It runs a Un*x command to retrieve and clean a manpage in the
939 background and places the results in a `Man-mode' browsing
940 buffer. The variable `Man-width' defines the number of columns in
941 formatted manual pages. The buffer is displayed immediately.
942 The variable `Man-notify-method' defines how the buffer is displayed.
943 If a buffer already exists for this man page, it will be displayed
944 without running the man command.
946 For a manpage from a particular section, use either of the
947 following. \"cat(1)\" is how cross-references appear and is
948 passed to man as \"1 cat\".
950 cat(1)
951 1 cat
953 To see manpages from all sections related to a subject, use an
954 \"all pages\" option (which might be \"-a\" if it's not the
955 default), then step through with `Man-next-manpage' (\\<Man-mode-map>\\[Man-next-manpage]) etc.
956 Add to `Man-switches' to make this option permanent.
958 -a chmod
960 An explicit filename can be given too. Use -l if it might
961 otherwise look like a page name.
963 /my/file/name.1.gz
964 -l somefile.1
966 An \"apropos\" query with -k gives a buffer of matching page
967 names or descriptions. The pattern argument is usually an
968 \"grep -E\" style regexp.
970 -k pattern"
972 (interactive
973 (list (let* ((default-entry (Man-default-man-entry))
974 ;; ignore case because that's friendly for bizarre
975 ;; caps things like the X11 function names and because
976 ;; "man" itself is case-insensitive on the command line
977 ;; so you're accustomed not to bother about the case
978 ;; ("man -k" is case-insensitive similarly, so the
979 ;; table has everything available to complete)
980 (completion-ignore-case t)
981 Man-completion-cache ;Don't cache across calls.
982 (input (completing-read
983 (format "Manual entry%s"
984 (if (string= default-entry "")
985 ": "
986 (format " (default %s): " default-entry)))
987 'Man-completion-table
988 nil nil nil 'Man-topic-history default-entry)))
989 (if (string= input "")
990 (error "No man args given")
991 input))))
993 ;; Possibly translate the "subject(section)" syntax into the
994 ;; "section subject" syntax and possibly downcase the section.
995 (setq man-args (Man-translate-references man-args))
997 (Man-getpage-in-background man-args))
999 ;;;###autoload
1000 (defun man-follow (man-args)
1001 "Get a Un*x manual page of the item under point and put it in a buffer."
1002 (interactive (list (Man-default-man-entry)))
1003 (if (or (not man-args)
1004 (string= man-args ""))
1005 (error "No item under point")
1006 (man man-args)))
1008 (defmacro Man-start-calling (&rest body)
1009 "Start the man command in `body' after setting up the environment"
1010 `(let ((process-environment (copy-sequence process-environment))
1011 ;; The following is so Awk script gets \n intact
1012 ;; But don't prevent decoding of the outside.
1013 (coding-system-for-write 'raw-text-unix)
1014 ;; We must decode the output by a coding system that the
1015 ;; system's locale suggests in multibyte mode.
1016 (coding-system-for-read
1017 (or coding-system-for-read ; allow overriding with "C-x RET c"
1018 Man-coding-system
1019 locale-coding-system))
1020 ;; Avoid possible error by using a directory that always exists.
1021 (default-directory
1022 (if (and (file-directory-p default-directory)
1023 (not (find-file-name-handler default-directory
1024 'file-directory-p)))
1025 default-directory
1026 "/")))
1027 ;; Prevent any attempt to use display terminal fanciness.
1028 (setenv "TERM" "dumb")
1029 ;; In Debian Woody, at least, we get overlong lines under X
1030 ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
1031 ;; a tty. man(1) says:
1032 ;; MANWIDTH
1033 ;; If $MANWIDTH is set, its value is used as the line
1034 ;; length for which manual pages should be formatted.
1035 ;; If it is not set, manual pages will be formatted
1036 ;; with a line length appropriate to the current ter-
1037 ;; minal (using an ioctl(2) if available, the value of
1038 ;; $COLUMNS, or falling back to 80 characters if nei-
1039 ;; ther is available).
1040 (when (or window-system
1041 (not (or (getenv "MANWIDTH") (getenv "COLUMNS"))))
1042 ;; Since the page buffer is displayed beforehand,
1043 ;; we can select its window and get the window/frame width.
1044 (setenv "COLUMNS" (number-to-string
1045 (cond
1046 ((and (integerp Man-width) (> Man-width 0))
1047 Man-width)
1048 (Man-width
1049 (if (window-live-p (get-buffer-window (current-buffer) t))
1050 (with-selected-window (get-buffer-window (current-buffer) t)
1051 (frame-width))
1052 (frame-width)))
1054 (if (window-live-p (get-buffer-window (current-buffer) t))
1055 (with-selected-window (get-buffer-window (current-buffer) t)
1056 (window-width))
1057 (window-width)))))))
1058 ;; Since man-db 2.4.3-1, man writes plain text with no escape
1059 ;; sequences when stdout is not a tty. In 2.5.0, the following
1060 ;; env-var was added to allow control of this (see Debian Bug#340673).
1061 (setenv "MAN_KEEP_FORMATTING" "1")
1062 ,@body))
1064 (defun Man-getpage-in-background (topic)
1065 "Use TOPIC to build and fire off the manpage and cleaning command.
1066 Return the buffer in which the manpage will appear."
1067 (let* ((man-args topic)
1068 (bufname (concat "*Man " man-args "*"))
1069 (buffer (get-buffer bufname)))
1070 (if buffer
1071 (Man-notify-when-ready buffer)
1072 (require 'env)
1073 (message "Invoking %s %s in the background" manual-program man-args)
1074 (setq buffer (generate-new-buffer bufname))
1075 (with-current-buffer buffer
1076 (Man-notify-when-ready buffer)
1077 (setq buffer-undo-list t)
1078 (setq Man-original-frame (selected-frame))
1079 (setq Man-arguments man-args)
1080 (Man-mode)
1081 (setq mode-line-process
1082 (concat " " (propertize (if Man-fontify-manpage-flag
1083 "[formatting...]"
1084 "[cleaning...]")
1085 'face 'mode-line-emphasis)))
1086 (Man-start-calling
1087 (if (fboundp 'make-process)
1088 (let ((proc (start-process
1089 manual-program buffer
1090 (if (memq system-type '(cygwin windows-nt))
1091 shell-file-name
1092 "sh")
1093 shell-command-switch
1094 (format (Man-build-man-command) man-args))))
1095 (set-process-sentinel proc 'Man-bgproc-sentinel)
1096 (set-process-filter proc 'Man-bgproc-filter))
1097 (let* ((inhibit-read-only t)
1098 (exit-status
1099 (call-process shell-file-name nil (list buffer nil) nil
1100 shell-command-switch
1101 (format (Man-build-man-command) man-args)))
1102 (msg ""))
1103 (or (and (numberp exit-status)
1104 (= exit-status 0))
1105 (and (numberp exit-status)
1106 (setq msg
1107 (format "exited abnormally with code %d"
1108 exit-status)))
1109 (setq msg exit-status))
1110 (if Man-fontify-manpage-flag
1111 (Man-fontify-manpage)
1112 (Man-cleanup-manpage))
1113 (Man-bgproc-sentinel bufname msg))))))
1114 buffer))
1116 (defun Man-update-manpage ()
1117 "Reformat current manpage by calling the man command again synchronously."
1118 (interactive)
1119 (when (eq Man-arguments nil)
1120 ;;this shouldn't happen unless it is not in a Man buffer."
1121 (error "Man-arguments not initialized"))
1122 (let ((old-pos (point))
1123 (text (current-word))
1124 (old-size (buffer-size))
1125 (inhibit-read-only t)
1126 (buffer-read-only nil))
1127 (erase-buffer)
1128 (Man-start-calling
1129 (call-process shell-file-name nil (list (current-buffer) nil) nil
1130 shell-command-switch
1131 (format (Man-build-man-command) Man-arguments)))
1132 (if Man-fontify-manpage-flag
1133 (Man-fontify-manpage)
1134 (Man-cleanup-manpage))
1135 (goto-char old-pos)
1136 ;;restore the point, not strictly right.
1137 (unless (or (eq text nil) (= old-size (buffer-size)))
1138 (let ((case-fold-search nil))
1139 (if (> old-size (buffer-size))
1140 (search-backward text nil t))
1141 (search-forward text nil t)))))
1143 (defun Man-notify-when-ready (man-buffer)
1144 "Notify the user when MAN-BUFFER is ready.
1145 See the variable `Man-notify-method' for the different notification behaviors."
1146 (let ((saved-frame (with-current-buffer man-buffer
1147 Man-original-frame)))
1148 (pcase Man-notify-method
1149 (`newframe
1150 ;; Since we run asynchronously, perhaps while Emacs is waiting
1151 ;; for input, we must not leave a different buffer current. We
1152 ;; can't rely on the editor command loop to reselect the
1153 ;; selected window's buffer.
1154 (save-excursion
1155 (let ((frame (make-frame Man-frame-parameters)))
1156 (set-window-buffer (frame-selected-window frame) man-buffer)
1157 (set-window-dedicated-p (frame-selected-window frame) t)
1158 (or (display-multi-frame-p frame)
1159 (select-frame frame)))))
1160 (`pushy
1161 (switch-to-buffer man-buffer))
1162 (`bully
1163 (and (frame-live-p saved-frame)
1164 (select-frame saved-frame))
1165 (pop-to-buffer man-buffer)
1166 (delete-other-windows))
1167 (`aggressive
1168 (and (frame-live-p saved-frame)
1169 (select-frame saved-frame))
1170 (pop-to-buffer man-buffer))
1171 (`friendly
1172 (and (frame-live-p saved-frame)
1173 (select-frame saved-frame))
1174 (display-buffer man-buffer 'not-this-window))
1175 (`polite
1176 (beep)
1177 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1178 (`quiet
1179 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
1180 (_ ;; meek
1181 (message ""))
1184 (defun Man-softhyphen-to-minus ()
1185 ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
1186 ;; least, emit it even when not in a Latin-N locale.
1187 (unless (eq t (compare-strings "latin-" 0 nil
1188 current-language-environment 0 6 t))
1189 (goto-char (point-min))
1190 (while (search-forward "­" nil t) (replace-match "-"))))
1192 (defun Man-fontify-manpage ()
1193 "Convert overstriking and underlining to the correct fonts.
1194 Same for the ANSI bold and normal escape sequences."
1195 (interactive)
1196 (goto-char (point-min))
1197 ;; Fontify ANSI escapes.
1198 (let ((ansi-color-apply-face-function
1199 (lambda (beg end face)
1200 (when face
1201 (put-text-property beg end 'face face))))
1202 (ansi-color-map Man-ansi-color-map))
1203 (ansi-color-apply-on-region (point-min) (point-max)))
1204 ;; Other highlighting.
1205 (let ((buffer-undo-list t))
1206 (if (< (buffer-size) (position-bytes (point-max)))
1207 ;; Multibyte characters exist.
1208 (progn
1209 (goto-char (point-min))
1210 (while (and (search-forward "__\b\b" nil t) (not (eobp)))
1211 (backward-delete-char 4)
1212 (put-text-property (point) (1+ (point)) 'face 'Man-underline))
1213 (goto-char (point-min))
1214 (while (search-forward "\b\b__" nil t)
1215 (backward-delete-char 4)
1216 (put-text-property (1- (point)) (point) 'face 'Man-underline))))
1217 (goto-char (point-min))
1218 (while (and (search-forward "_\b" nil t) (not (eobp)))
1219 (backward-delete-char 2)
1220 (put-text-property (point) (1+ (point)) 'face 'Man-underline))
1221 (goto-char (point-min))
1222 (while (search-forward "\b_" nil t)
1223 (backward-delete-char 2)
1224 (put-text-property (1- (point)) (point) 'face 'Man-underline))
1225 (goto-char (point-min))
1226 (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
1227 (replace-match "\\1")
1228 (put-text-property (1- (point)) (point) 'face 'Man-overstrike))
1229 (goto-char (point-min))
1230 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
1231 (replace-match "o")
1232 (put-text-property (1- (point)) (point) 'face 'bold))
1233 (goto-char (point-min))
1234 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
1235 (replace-match "+")
1236 (put-text-property (1- (point)) (point) 'face 'bold))
1237 ;; When the header is longer than the manpage name, groff tries to
1238 ;; condense it to a shorter line interspersed with ^H. Remove ^H with
1239 ;; their preceding chars (but don't put Man-overstrike). (Bug#5566)
1240 (goto-char (point-min))
1241 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1242 (goto-char (point-min))
1243 ;; Try to recognize common forms of cross references.
1244 (Man-highlight-references)
1245 (Man-softhyphen-to-minus)
1246 (goto-char (point-min))
1247 (while (re-search-forward Man-heading-regexp nil t)
1248 (put-text-property (match-beginning 0)
1249 (match-end 0)
1250 'face 'Man-overstrike))))
1252 (defun Man-highlight-references (&optional xref-man-type)
1253 "Highlight the references on mouse-over.
1254 References include items in the SEE ALSO section,
1255 header file (#include <foo.h>), and files in FILES.
1256 If optional argument XREF-MAN-TYPE is non-nil, it used as the
1257 button type for items in SEE ALSO section. If it is nil, the
1258 default type, `Man-xref-man-page' is used for the buttons."
1259 ;; `Man-highlight-references' is used from woman.el, too.
1260 ;; woman.el doesn't set `Man-arguments'.
1261 (unless Man-arguments
1262 (setq Man-arguments ""))
1263 (if (string-match "-k " Man-arguments)
1264 (progn
1265 (Man-highlight-references0 nil Man-reference-regexp 1
1266 'Man-default-man-entry
1267 (or xref-man-type 'Man-xref-man-page))
1268 (Man-highlight-references0 nil Man-apropos-regexp 1
1269 'Man-default-man-entry
1270 (or xref-man-type 'Man-xref-man-page)))
1271 (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
1272 'Man-default-man-entry
1273 (or xref-man-type 'Man-xref-man-page))
1274 (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
1275 'Man-xref-header-file)
1276 (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
1277 'Man-xref-normal-file)))
1279 (defun Man-highlight-references0 (start-section regexp button-pos target type)
1280 ;; Based on `Man-build-references-alist'
1281 (when (or (null start-section)
1282 (Man-find-section start-section))
1283 (let ((end (if start-section
1284 (progn
1285 (forward-line 1)
1286 (back-to-indentation)
1287 (save-excursion
1288 (Man-next-section 1)
1289 (point)))
1290 (goto-char (point-min))
1291 nil)))
1292 (while (re-search-forward regexp end t)
1293 ;; An overlay button is preferable because the underlying text
1294 ;; may have text property highlights (Bug#7881).
1295 (make-button
1296 (match-beginning button-pos)
1297 (match-end button-pos)
1298 'type type
1299 'Man-target-string (cond
1300 ((numberp target)
1301 (match-string target))
1302 ((functionp target)
1303 target)
1304 (t nil)))))))
1306 (defun Man-cleanup-manpage (&optional interactive)
1307 "Remove overstriking and underlining from the current buffer.
1308 Normally skip any jobs that should have been done by the sed script,
1309 but when called interactively, do those jobs even if the sed
1310 script would have done them."
1311 (interactive "p")
1312 (if (or interactive (not Man-sed-script))
1313 (progn
1314 (goto-char (point-min))
1315 (while (search-forward "_\b" nil t) (backward-delete-char 2))
1316 (goto-char (point-min))
1317 (while (search-forward "\b_" nil t) (backward-delete-char 2))
1318 (goto-char (point-min))
1319 (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
1320 (replace-match "\\1"))
1321 (goto-char (point-min))
1322 (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
1323 (goto-char (point-min))
1324 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
1326 (goto-char (point-min))
1327 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
1328 ;; When the header is longer than the manpage name, groff tries to
1329 ;; condense it to a shorter line interspersed with ^H. Remove ^H with
1330 ;; their preceding chars (but don't put Man-overstrike). (Bug#5566)
1331 (goto-char (point-min))
1332 (while (re-search-forward ".\b" nil t) (backward-delete-char 2))
1333 (Man-softhyphen-to-minus))
1335 (defun Man-bgproc-filter (process string)
1336 "Manpage background process filter.
1337 When manpage command is run asynchronously, PROCESS is the process
1338 object for the manpage command; when manpage command is run
1339 synchronously, PROCESS is the name of the buffer where the manpage
1340 command is run. Second argument STRING is the entire string of output."
1341 (save-excursion
1342 (let ((Man-buffer (process-buffer process)))
1343 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1344 (set-process-buffer process nil)
1346 (with-current-buffer Man-buffer
1347 (let ((inhibit-read-only t)
1348 (beg (marker-position (process-mark process))))
1349 (save-excursion
1350 (goto-char beg)
1351 (insert string)
1352 (save-restriction
1353 (narrow-to-region
1354 (save-excursion
1355 (goto-char beg)
1356 (line-beginning-position))
1357 (point))
1358 (if Man-fontify-manpage-flag
1359 (Man-fontify-manpage)
1360 (Man-cleanup-manpage)))
1361 (set-marker (process-mark process) (point-max)))))))))
1363 (defun Man-bgproc-sentinel (process msg)
1364 "Manpage background process sentinel.
1365 When manpage command is run asynchronously, PROCESS is the process
1366 object for the manpage command; when manpage command is run
1367 synchronously, PROCESS is the name of the buffer where the manpage
1368 command is run. Second argument MSG is the exit message of the
1369 manpage command."
1370 (let ((Man-buffer (if (stringp process) (get-buffer process)
1371 (process-buffer process)))
1372 (delete-buff nil)
1373 (err-mess nil))
1375 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1376 (or (stringp process)
1377 (set-process-buffer process nil))
1379 (with-current-buffer Man-buffer
1380 (save-excursion
1381 (let ((case-fold-search nil))
1382 (goto-char (point-min))
1383 (cond ((or (looking-at "No \\(manual \\)*entry for")
1384 (looking-at "[^\n]*: nothing appropriate$"))
1385 (setq err-mess (buffer-substring (point)
1386 (progn
1387 (end-of-line) (point)))
1388 delete-buff t))
1390 ;; "-k foo", successful exit, but no output (from man-db)
1391 ;; ENHANCE-ME: share the check for -k with
1392 ;; `Man-highlight-references'. The \\s- bits here are
1393 ;; meant to allow for multiple options with -k among them.
1394 ((and (string-match "\\(\\`\\|\\s-\\)-k\\s-" Man-arguments)
1395 (eq (process-status process) 'exit)
1396 (= (process-exit-status process) 0)
1397 (= (point-min) (point-max)))
1398 (setq err-mess (format "%s: no matches" Man-arguments)
1399 delete-buff t))
1401 ((or (stringp process)
1402 (not (and (eq (process-status process) 'exit)
1403 (= (process-exit-status process) 0))))
1404 (or (zerop (length msg))
1405 (progn
1406 (setq err-mess
1407 (concat (buffer-name Man-buffer)
1408 ": process "
1409 (let ((eos (1- (length msg))))
1410 (if (= (aref msg eos) ?\n)
1411 (substring msg 0 eos) msg))))
1412 (goto-char (point-max))
1413 (insert (format "\nprocess %s" msg))))
1415 (if delete-buff
1416 (if (window-live-p (get-buffer-window Man-buffer t))
1417 (quit-restore-window
1418 (get-buffer-window Man-buffer t) 'kill)
1419 (kill-buffer Man-buffer))
1421 (run-hooks 'Man-cooked-hook)
1423 (Man-build-page-list)
1424 (Man-strip-page-headers)
1425 (Man-unindent)
1426 (Man-goto-page 1 t)
1428 (if (not Man-page-list)
1429 (let ((args Man-arguments))
1430 (if (window-live-p (get-buffer-window (current-buffer) t))
1431 (quit-restore-window
1432 (get-buffer-window (current-buffer) t) 'kill)
1433 (kill-buffer (current-buffer)))
1434 ;; Entries hyphenated due to the window's width
1435 ;; won't be found in the man database, so remove
1436 ;; the hyphenation -- assuming Groff hyphenates
1437 ;; either with hyphen-minus (ASCII 45, #x2d),
1438 ;; hyphen (#x2010) or soft hyphen (#xad) -- and
1439 ;; look again.
1440 (if (string-match "[-‐­]" args)
1441 (let ((str (replace-match "" nil nil args)))
1442 (Man-getpage-in-background str))
1443 (message "Can't find the %s manpage"
1444 (Man-page-from-arguments args))))
1446 (if Man-fontify-manpage-flag
1447 (message "%s man page formatted"
1448 (Man-page-from-arguments Man-arguments))
1449 (message "%s man page cleaned up"
1450 (Man-page-from-arguments Man-arguments)))
1451 (unless (and (processp process)
1452 (not (eq (process-status process) 'exit)))
1453 (setq mode-line-process nil))
1454 (set-buffer-modified-p nil)))))
1456 (if err-mess
1457 (message "%s" err-mess))
1458 ))))
1460 (defun Man-page-from-arguments (args)
1461 ;; Skip arguments and only print the page name.
1462 (mapconcat
1463 'identity
1464 (delete nil
1465 (mapcar
1466 (lambda (elem)
1467 (and (not (string-match "^-" elem))
1468 elem))
1469 (split-string args " ")))
1470 " "))
1473 ;; ======================================================================
1474 ;; set up manual mode in buffer and build alists
1476 (defvar bookmark-make-record-function)
1478 (define-derived-mode Man-mode special-mode "Man"
1479 "A mode for browsing Un*x manual pages.
1481 The following man commands are available in the buffer. Try
1482 \"\\[describe-key] <key> RET\" for more information:
1484 \\[man] Prompt to retrieve a new manpage.
1485 \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
1486 \\[Man-next-manpage] Jump to next manpage in circular list.
1487 \\[Man-previous-manpage] Jump to previous manpage in circular list.
1488 \\[Man-next-section] Jump to next manpage section.
1489 \\[Man-previous-section] Jump to previous manpage section.
1490 \\[Man-goto-section] Go to a manpage section.
1491 \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
1492 \\[quit-window] Deletes the manpage window, bury its buffer.
1493 \\[Man-kill] Deletes the manpage window, kill its buffer.
1494 \\[describe-mode] Prints this help text.
1496 The following variables may be of some use. Try
1497 \"\\[describe-variable] <variable-name> RET\" for more information:
1499 `Man-notify-method' What happens when manpage is ready to display.
1500 `Man-downcase-section-letters-flag' Force section letters to lower case.
1501 `Man-circular-pages-flag' Treat multiple manpage list as circular.
1502 `Man-section-translations-alist' List of section numbers and their Un*x equiv.
1503 `Man-filter-list' Background manpage filter command.
1504 `Man-mode-map' Keymap bindings for Man mode buffers.
1505 `Man-mode-hook' Normal hook run on entry to Man mode.
1506 `Man-section-regexp' Regexp describing manpage section letters.
1507 `Man-heading-regexp' Regexp describing section headers.
1508 `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
1509 `Man-first-heading-regexp' Regexp for first heading on a manpage.
1510 `Man-reference-regexp' Regexp matching a references in SEE ALSO.
1511 `Man-switches' Background `man' command switches.
1513 The following key bindings are currently in effect in the buffer:
1514 \\{Man-mode-map}"
1515 (setq buffer-auto-save-file-name nil
1516 mode-line-buffer-identification
1517 (list (default-value 'mode-line-buffer-identification)
1518 " {" 'Man-page-mode-string "}")
1519 truncate-lines t)
1520 (buffer-disable-undo)
1521 (auto-fill-mode -1)
1522 (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
1523 (imenu-add-to-menubar man-imenu-title)
1524 (set (make-local-variable 'outline-regexp) Man-heading-regexp)
1525 (set (make-local-variable 'outline-level) (lambda () 1))
1526 (set (make-local-variable 'bookmark-make-record-function)
1527 'Man-bookmark-make-record))
1529 (defun Man-build-section-list ()
1530 "Build the list of manpage sections."
1531 (setq Man--sections ())
1532 (goto-char (point-min))
1533 (let ((case-fold-search nil))
1534 (while (re-search-forward Man-heading-regexp nil t)
1535 (let ((section (match-string 1)))
1536 (unless (member section Man--sections)
1537 (push section Man--sections)))
1538 (forward-line)))
1539 (setq Man--sections (nreverse Man--sections)))
1541 (defsubst Man-build-references-alist ()
1542 "Build the list of references (in the SEE ALSO section)."
1543 (setq Man--refpages nil)
1544 (save-excursion
1545 (if (Man-find-section Man-see-also-regexp)
1546 (let ((start (progn (forward-line 1) (point)))
1547 (end (progn
1548 (Man-next-section 1)
1549 (point)))
1550 hyphenated
1551 (runningpoint -1))
1552 (save-restriction
1553 (narrow-to-region start end)
1554 (goto-char (point-min))
1555 (back-to-indentation)
1556 (while (and (not (eobp)) (/= (point) runningpoint))
1557 (setq runningpoint (point))
1558 (if (re-search-forward Man-hyphenated-reference-regexp end t)
1559 (let* ((word (match-string 0))
1560 (len (1- (length word))))
1561 (if hyphenated
1562 (setq word (concat hyphenated word)
1563 hyphenated nil
1564 ;; Update len, in case a reference spans
1565 ;; more than two lines (paranoia).
1566 len (1- (length word))))
1567 (if (memq (aref word len) '(?- ?­))
1568 (setq hyphenated (substring word 0 len)))
1569 (and (string-match Man-reference-regexp word)
1570 (not (member word Man--refpages))
1571 (push word Man--refpages))))
1572 (skip-chars-forward " \t\n,"))))))
1573 (setq Man--refpages (nreverse Man--refpages)))
1575 (defun Man-build-page-list ()
1576 "Build the list of separate manpages in the buffer."
1577 (setq Man-page-list nil)
1578 (let ((page-start (point-min))
1579 (page-end (point-max))
1580 (header ""))
1581 (goto-char page-start)
1582 (while (not (eobp))
1583 (setq header
1584 (if (looking-at Man-page-header-regexp)
1585 (match-string 1)
1586 nil))
1587 ;; Go past both the current and the next Man-first-heading-regexp
1588 (if (re-search-forward Man-first-heading-regexp nil 'move 2)
1589 (let ((p (progn (beginning-of-line) (point))))
1590 ;; We assume that the page header is delimited by blank
1591 ;; lines and that it contains at most one blank line. So
1592 ;; if we back by three blank lines we will be sure to be
1593 ;; before the page header but not before the possible
1594 ;; previous page header.
1595 (search-backward "\n\n" nil t 3)
1596 (if (re-search-forward Man-page-header-regexp p 'move)
1597 (beginning-of-line))))
1598 (setq page-end (point))
1599 (setq Man-page-list (append Man-page-list
1600 (list (list (copy-marker page-start)
1601 (copy-marker page-end)
1602 header))))
1603 (setq page-start page-end)
1606 (defun Man-strip-page-headers ()
1607 "Strip all the page headers but the first from the manpage."
1608 (let ((inhibit-read-only t)
1609 (case-fold-search nil)
1610 (header ""))
1611 (dolist (page Man-page-list)
1612 (and (nth 2 page)
1613 (goto-char (car page))
1614 (re-search-forward Man-first-heading-regexp nil t)
1615 (setq header (buffer-substring (car page) (match-beginning 0)))
1616 ;; Since the awk script collapses all successive blank
1617 ;; lines into one, and since we don't want to get rid of
1618 ;; the fast awk script, one must choose between adding
1619 ;; spare blank lines between pages when there were none and
1620 ;; deleting blank lines at page boundaries when there were
1621 ;; some. We choose the first, so we comment the following
1622 ;; line.
1623 ;; (setq header (concat "\n" header)))
1624 (while (search-forward header (nth 1 page) t)
1625 (replace-match ""))))))
1627 (defun Man-unindent ()
1628 "Delete the leading spaces that indent the manpage."
1629 (let ((inhibit-read-only t)
1630 (case-fold-search nil))
1631 (dolist (page Man-page-list)
1632 (let ((indent "")
1633 (nindent 0))
1634 (narrow-to-region (car page) (car (cdr page)))
1635 (if Man-uses-untabify-flag
1636 ;; The space characters inserted by `untabify' inherit
1637 ;; sticky text properties, which is unnecessary and looks
1638 ;; ugly with underlining (Bug#11408).
1639 (let ((text-property-default-nonsticky
1640 (cons '(face . t) text-property-default-nonsticky)))
1641 (untabify (point-min) (point-max))))
1642 (if (catch 'unindent
1643 (goto-char (point-min))
1644 (if (not (re-search-forward Man-first-heading-regexp nil t))
1645 (throw 'unindent nil))
1646 (beginning-of-line)
1647 (setq indent (buffer-substring (point)
1648 (progn
1649 (skip-chars-forward " ")
1650 (point))))
1651 (setq nindent (length indent))
1652 (if (zerop nindent)
1653 (throw 'unindent nil))
1654 (setq indent (concat indent "\\|$"))
1655 (goto-char (point-min))
1656 (while (not (eobp))
1657 (if (looking-at indent)
1658 (forward-line 1)
1659 (throw 'unindent nil)))
1660 (goto-char (point-min)))
1661 (while (not (eobp))
1662 (or (eolp)
1663 (delete-char nindent))
1664 (forward-line 1)))
1665 ))))
1668 ;; ======================================================================
1669 ;; Man mode commands
1671 (defun Man-next-section (n)
1672 "Move point to Nth next section (default 1)."
1673 (interactive "p")
1674 (let ((case-fold-search nil)
1675 (start (point)))
1676 (if (looking-at Man-heading-regexp)
1677 (forward-line 1))
1678 (if (re-search-forward Man-heading-regexp (point-max) t n)
1679 (beginning-of-line)
1680 (goto-char (point-max))
1681 ;; The last line doesn't belong to any section.
1682 (forward-line -1))
1683 ;; But don't move back from the starting point (can happen if `start'
1684 ;; is somewhere on the last line).
1685 (if (< (point) start) (goto-char start))))
1687 (defun Man-previous-section (n)
1688 "Move point to Nth previous section (default 1)."
1689 (interactive "p")
1690 (let ((case-fold-search nil))
1691 (if (looking-at Man-heading-regexp)
1692 (forward-line -1))
1693 (if (re-search-backward Man-heading-regexp (point-min) t n)
1694 (beginning-of-line)
1695 (goto-char (point-min)))))
1697 (defun Man-find-section (section)
1698 "Move point to SECTION if it exists, otherwise don't move point.
1699 Returns t if section is found, nil otherwise."
1700 (let ((curpos (point))
1701 (case-fold-search nil))
1702 (goto-char (point-min))
1703 (if (re-search-forward (concat "^" section) (point-max) t)
1704 (progn (beginning-of-line) t)
1705 (goto-char curpos)
1706 nil)
1709 (defvar Man--last-section nil)
1711 (defun Man-goto-section (section)
1712 "Move point to SECTION."
1713 (interactive
1714 (let* ((default (if (member Man--last-section Man--sections)
1715 Man--last-section
1716 (car Man--sections)))
1717 (completion-ignore-case t)
1718 (prompt (concat "Go to section (default " default "): "))
1719 (chosen (completing-read prompt Man--sections
1720 nil nil nil nil default)))
1721 (list chosen)))
1722 (setq Man--last-section section)
1723 (unless (Man-find-section section)
1724 (error "Section %s not found" section)))
1727 (defun Man-goto-see-also-section ()
1728 "Move point to the \"SEE ALSO\" section.
1729 Actually the section moved to is described by `Man-see-also-regexp'."
1730 (interactive)
1731 (if (not (Man-find-section Man-see-also-regexp))
1732 (error "%s" (concat "No " Man-see-also-regexp
1733 " section found in the current manpage"))))
1735 (defun Man-possibly-hyphenated-word ()
1736 "Return a possibly hyphenated word at point.
1737 If the word starts at the first non-whitespace column, and the
1738 previous line ends with a hyphen, return the last word on the previous
1739 line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
1740 as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
1741 \"tcgetp-\" instead of \"grp\"."
1742 (save-excursion
1743 (skip-syntax-backward "w()")
1744 (skip-chars-forward " \t")
1745 (let ((beg (point))
1746 (word (current-word)))
1747 (when (eq beg (save-excursion
1748 (back-to-indentation)
1749 (point)))
1750 (end-of-line 0)
1751 (if (eq (char-before) ?-)
1752 (setq word (current-word))))
1753 word)))
1755 (defvar Man--last-refpage nil)
1757 (defun Man-follow-manual-reference (reference)
1758 "Get one of the manpages referred to in the \"SEE ALSO\" section.
1759 Specify which REFERENCE to use; default is based on word at point."
1760 (interactive
1761 (if (not Man--refpages)
1762 (error "There are no references in the current man page")
1763 (list
1764 (let* ((default (or
1765 (car (all-completions
1766 (let ((word
1767 (or (Man-possibly-hyphenated-word)
1768 "")))
1769 ;; strip a trailing '-':
1770 (if (string-match "-$" word)
1771 (substring word 0
1772 (match-beginning 0))
1773 word))
1774 Man--refpages))
1775 (if (member Man--last-refpage Man--refpages)
1776 Man--last-refpage
1777 (car Man--refpages))))
1778 (defaults
1779 (mapcar 'substring-no-properties
1780 (cons default Man--refpages)))
1781 (prompt (concat "Refer to (default " default "): "))
1782 (chosen (completing-read prompt Man--refpages
1783 nil nil nil nil defaults)))
1784 chosen))))
1785 (if (not Man--refpages)
1786 (error "Can't find any references in the current manpage")
1787 (setq Man--last-refpage reference)
1788 (Man-getpage-in-background
1789 (Man-translate-references reference))))
1791 (defun Man-kill ()
1792 "Kill the buffer containing the manpage."
1793 (interactive)
1794 (quit-window t))
1796 (defun Man-goto-page (page &optional noerror)
1797 "Go to the manual page on page PAGE."
1798 (interactive
1799 (if (not Man-page-list)
1800 (error "Not a man page buffer")
1801 (if (= (length Man-page-list) 1)
1802 (error "You're looking at the only manpage in the buffer")
1803 (list (read-minibuffer (format "Go to manpage [1-%d]: "
1804 (length Man-page-list)))))))
1805 (if (and (not Man-page-list) (not noerror))
1806 (error "Not a man page buffer"))
1807 (when Man-page-list
1808 (if (or (< page 1)
1809 (> page (length Man-page-list)))
1810 (user-error "No manpage %d found" page))
1811 (let* ((page-range (nth (1- page) Man-page-list))
1812 (page-start (car page-range))
1813 (page-end (car (cdr page-range))))
1814 (setq Man-current-page page
1815 Man-page-mode-string (Man-make-page-mode-string))
1816 (widen)
1817 (goto-char page-start)
1818 (narrow-to-region page-start page-end)
1819 (Man-build-section-list)
1820 (Man-build-references-alist)
1821 (goto-char (point-min)))))
1824 (defun Man-next-manpage ()
1825 "Find the next manpage entry in the buffer."
1826 (interactive)
1827 (if (= (length Man-page-list) 1)
1828 (error "This is the only manpage in the buffer"))
1829 (if (< Man-current-page (length Man-page-list))
1830 (Man-goto-page (1+ Man-current-page))
1831 (if Man-circular-pages-flag
1832 (Man-goto-page 1)
1833 (error "You're looking at the last manpage in the buffer"))))
1835 (defun Man-previous-manpage ()
1836 "Find the previous manpage entry in the buffer."
1837 (interactive)
1838 (if (= (length Man-page-list) 1)
1839 (error "This is the only manpage in the buffer"))
1840 (if (> Man-current-page 1)
1841 (Man-goto-page (1- Man-current-page))
1842 (if Man-circular-pages-flag
1843 (Man-goto-page (length Man-page-list))
1844 (error "You're looking at the first manpage in the buffer"))))
1846 ;; Header file support
1847 (defun Man-view-header-file (file)
1848 "View a header file specified by FILE from `Man-header-file-path'."
1849 (let ((path Man-header-file-path)
1850 complete-path)
1851 (while path
1852 (setq complete-path (expand-file-name file (car path))
1853 path (cdr path))
1854 (if (file-readable-p complete-path)
1855 (progn (view-file complete-path)
1856 (setq path nil))
1857 (setq complete-path nil)))
1858 complete-path))
1860 ;;; Bookmark Man Support
1861 (declare-function bookmark-make-record-default
1862 "bookmark" (&optional no-file no-context posn))
1863 (declare-function bookmark-prop-get "bookmark" (bookmark prop))
1864 (declare-function bookmark-default-handler "bookmark" (bmk))
1865 (declare-function bookmark-get-bookmark-record "bookmark" (bmk))
1867 (defun Man-default-bookmark-title ()
1868 "Default bookmark name for Man or WoMan pages.
1869 Uses `Man-name-local-regexp'."
1870 (save-excursion
1871 (goto-char (point-min))
1872 (when (re-search-forward Man-name-local-regexp nil t)
1873 (skip-chars-forward "\n\t ")
1874 (buffer-substring-no-properties (point) (line-end-position)))))
1876 (defun Man-bookmark-make-record ()
1877 "Make a bookmark entry for a Man buffer."
1878 `(,(Man-default-bookmark-title)
1879 ,@(bookmark-make-record-default 'no-file)
1880 (location . ,(concat "man " Man-arguments))
1881 (man-args . ,Man-arguments)
1882 (handler . Man-bookmark-jump)))
1884 ;;;###autoload
1885 (defun Man-bookmark-jump (bookmark)
1886 "Default bookmark handler for Man buffers."
1887 (let* ((man-args (bookmark-prop-get bookmark 'man-args))
1888 ;; Let bookmark.el do the window handling.
1889 ;; This let-binding needs to be active during the call to both
1890 ;; Man-getpage-in-background and accept-process-output.
1891 (Man-notify-method 'meek)
1892 (buf (Man-getpage-in-background man-args))
1893 (proc (get-buffer-process buf)))
1894 (while (and proc (eq (process-status proc) 'run))
1895 (accept-process-output proc))
1896 (bookmark-default-handler
1897 `("" (buffer . ,buf) . ,(bookmark-get-bookmark-record bookmark)))))
1900 ;; Init the man package variables, if not already done.
1901 (Man-init-defvars)
1903 (provide 'man)
1905 ;;; man.el ends here