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