(Man-completion-table): New function.
[emacs.git] / lisp / man.el
blob5923b3909eef3a7df1bd53e0216f184bd1ec07dd
1 ;;; man.el --- browse UNIX manual pages -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 1993, 1994, 1996, 1997, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006, 2007, 2008, 2009 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.
87 ;; - Allow completion on the manpage name when calling man. This
88 ;; requires a reliable list of places where manpages can be found. The
89 ;; drawback would be that if the list is not complete, the user might
90 ;; be led to believe that the manpages in the missing directories do
91 ;; not exist.
94 ;;; Code:
96 (eval-when-compile (require 'cl))
97 (require 'assoc)
98 (require 'button)
100 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
101 ;; empty defvars (keep the compiler quiet)
103 (defgroup man nil
104 "Browse UNIX manual pages."
105 :prefix "Man-"
106 :group 'help)
109 (defvar Man-notify)
110 (defcustom Man-filter-list nil
111 "Manpage cleaning filter command phrases.
112 This variable contains a list of the following form:
114 '((command-string phrase-string*)*)
116 Each phrase-string is concatenated onto the command-string to form a
117 command filter. The (standard) output (and standard error) of the Un*x
118 man command is piped through each command filter in the order the
119 commands appear in the association list. The final output is placed in
120 the manpage buffer."
121 :type '(repeat (list (string :tag "Command String")
122 (repeat :inline t
123 (string :tag "Phrase String"))))
124 :group 'man)
126 (defvar Man-uses-untabify-flag t
127 "Non-nil means use `untabify' instead of `Man-untabify-command'.")
128 (defvar Man-sed-script nil
129 "Script for sed to nuke backspaces and ANSI codes from manpages.")
131 ;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
132 ;; user variables
134 (defcustom Man-fontify-manpage-flag t
135 "Non-nil means make up the manpage with fonts."
136 :type 'boolean
137 :group 'man)
139 (defcustom Man-overstrike-face 'bold
140 "Face to use when fontifying overstrike."
141 :type 'face
142 :group 'man)
144 (defcustom Man-underline-face 'underline
145 "Face to use when fontifying underlining."
146 :type 'face
147 :group 'man)
149 (defcustom Man-reverse-face 'highlight
150 "Face to use when fontifying reverse video."
151 :type 'face
152 :group 'man)
154 ;; Use the value of the obsolete user option Man-notify, if set.
155 (defcustom Man-notify-method (if (boundp 'Man-notify) Man-notify 'friendly)
156 "Selects the behavior when manpage is ready.
157 This variable may have one of the following values, where (sf) means
158 that the frames are switched, so the manpage is displayed in the frame
159 where the man command was called from:
161 newframe -- put the manpage in its own frame (see `Man-frame-parameters')
162 pushy -- make the manpage the current buffer in the current window
163 bully -- make the manpage the current buffer and only window (sf)
164 aggressive -- make the manpage the current buffer in the other window (sf)
165 friendly -- display manpage in the other window but don't make current (sf)
166 polite -- don't display manpage, but prints message and beep when ready
167 quiet -- like `polite', but don't beep
168 meek -- make no indication that the manpage is ready
170 Any other value of `Man-notify-method' is equivalent to `meek'."
171 :type '(radio (const newframe) (const pushy) (const bully)
172 (const aggressive) (const friendly)
173 (const polite) (const quiet) (const meek))
174 :group 'man)
176 (defcustom Man-width nil
177 "Number of columns for which manual pages should be formatted.
178 If nil, the width of the window selected at the moment of man
179 invocation is used. If non-nil, the width of the frame selected
180 at the moment of man invocation is used. The value also can be a
181 positive integer."
182 :type '(choice (const :tag "Window width" nil)
183 (const :tag "Frame width" t)
184 (integer :tag "Specific width" :value 65))
185 :group 'man)
187 (defcustom Man-frame-parameters nil
188 "Frame parameter list for creating a new frame for a manual page."
189 :type 'sexp
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 (defcustom Man-header-file-path
224 '("/usr/include" "/usr/local/include")
225 "C Header file search path used in Man."
226 :type '(repeat string)
227 :group 'man)
229 (defvar manual-program "man"
230 "The name of the program that produces man pages.")
232 (defvar Man-untabify-command "pr"
233 "Command used for untabifying.")
235 (defvar Man-untabify-command-args (list "-t" "-e")
236 "List of arguments to be passed to `Man-untabify-command' (which see).")
238 (defvar Man-sed-command "sed"
239 "Command used for processing sed scripts.")
241 (defvar Man-awk-command "awk"
242 "Command used for processing awk scripts.")
244 (defvar Man-mode-hook nil
245 "Hook run when Man mode is enabled.")
247 (defvar Man-cooked-hook nil
248 "Hook run after removing backspaces but before `Man-mode' processing.")
250 (defvar Man-name-regexp "[-a-zA-Z0-9_­+][-a-zA-Z0-9_.:­+]*"
251 "Regular expression describing the name of a manpage (without section).")
253 (defvar Man-section-regexp "[0-9][a-zA-Z0-9+]*\\|[LNln]"
254 "Regular expression describing a manpage section within parentheses.")
256 (defvar Man-page-header-regexp
257 (if (and (string-match "-solaris2\\." system-configuration)
258 (not (string-match "-solaris2\\.[123435]$" system-configuration)))
259 (concat "^[-A-Za-z0-9_].*[ \t]\\(" Man-name-regexp
260 "(\\(" Man-section-regexp "\\))\\)$")
261 (concat "^[ \t]*\\(" Man-name-regexp
262 "(\\(" Man-section-regexp "\\))\\).*\\1"))
263 "Regular expression describing the heading of a page.")
265 (defvar Man-heading-regexp "^\\([A-Z][A-Z0-9 /-]+\\)$"
266 "Regular expression describing a manpage heading entry.")
268 (defvar Man-see-also-regexp "SEE ALSO"
269 "Regular expression for SEE ALSO heading (or your equivalent).
270 This regexp should not start with a `^' character.")
272 ;; This used to have leading space [ \t]*, but was removed because it
273 ;; causes false page splits on an occasional NAME with leading space
274 ;; inside a manpage. And `Man-heading-regexp' doesn't have [ \t]* anyway.
275 (defvar Man-first-heading-regexp "^NAME$\\|^[ \t]*No manual entry fo.*$"
276 "Regular expression describing first heading on a manpage.
277 This regular expression should start with a `^' character.")
279 (defvar Man-reference-regexp
280 (concat "\\(" Man-name-regexp "\\)[ \t]*(\\(" Man-section-regexp "\\))")
281 "Regular expression describing a reference to another manpage.")
283 (defvar Man-apropos-regexp
284 (concat "\\\[\\(" Man-name-regexp "\\)\\\][ \t]*(\\(" Man-section-regexp "\\))")
285 "Regular expression describing a reference to manpages in \"man -k output\".")
287 (defvar Man-synopsis-regexp "SYNOPSIS"
288 "Regular expression for SYNOPSIS heading (or your equivalent).
289 This regexp should not start with a `^' character.")
291 (defvar Man-files-regexp "FILES"
292 "Regular expression for FILES heading (or your equivalent).
293 This regexp should not start with a `^' character.")
295 (defvar Man-include-regexp "#[ \t]*include[ \t]*"
296 "Regular expression describing the #include (directive of cpp).")
298 (defvar Man-file-name-regexp "[^<>\", \t\n]+"
299 "Regular expression describing <> in #include line (directive of cpp).")
301 (defvar Man-normal-file-prefix-regexp "[/~$]"
302 "Regular expression describing a file path appeared in FILES section.")
304 (defvar Man-header-regexp
305 (concat "\\(" Man-include-regexp "\\)"
306 "[<\"]"
307 "\\(" Man-file-name-regexp "\\)"
308 "[>\"]")
309 "Regular expression describing references to header files.")
311 (defvar Man-normal-file-regexp
312 (concat Man-normal-file-prefix-regexp Man-file-name-regexp)
313 "Regular expression describing references to normal files.")
315 ;; This includes the section as an optional part to catch hyphenated
316 ;; refernces to manpages.
317 (defvar Man-hyphenated-reference-regexp
318 (concat "\\(" Man-name-regexp "\\)\\((\\(" Man-section-regexp "\\))\\)?")
319 "Regular expression describing a reference in the SEE ALSO section.")
321 (defvar Man-switches ""
322 "Switches passed to the man command, as a single string.
324 If you want to be able to see all the manpages for a subject you type,
325 make -a one of the switches, if your `man' program supports it.")
327 (defvar Man-specified-section-option
328 (if (string-match "-solaris[0-9.]*$" system-configuration)
329 "-s"
331 "Option that indicates a specified a manual section name.")
333 (defvar Man-support-local-filenames 'auto-detect
334 "Internal cache for the value of the function `Man-support-local-filenames'.
335 `auto-detect' means the value is not yet determined.
336 Otherwise, the value is whatever the function
337 `Man-support-local-filenames' should return.")
339 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
340 ;; end user variables
342 ;; other variables and keymap initializations
343 (defvar Man-original-frame)
344 (make-variable-buffer-local 'Man-original-frame)
345 (defvar Man-arguments)
346 (make-variable-buffer-local 'Man-arguments)
347 (put 'Man-arguments 'permanent-local t)
349 (defvar Man-sections-alist nil)
350 (make-variable-buffer-local 'Man-sections-alist)
351 (defvar Man-refpages-alist nil)
352 (make-variable-buffer-local 'Man-refpages-alist)
353 (defvar Man-page-list nil)
354 (make-variable-buffer-local 'Man-page-list)
355 (defvar Man-current-page 0)
356 (make-variable-buffer-local 'Man-current-page)
357 (defvar Man-page-mode-string "1 of 1")
358 (make-variable-buffer-local 'Man-page-mode-string)
360 (defconst Man-sysv-sed-script "\
361 /\b/ { s/_\b//g
362 s/\b_//g
363 s/o\b+/o/g
364 s/+\bo/o/g
365 :ovstrk
366 s/\\(.\\)\b\\1/\\1/g
367 t ovstrk
369 /\e\\[[0-9][0-9]*m/ s///g"
370 "Script for sysV-like sed to nuke backspaces and ANSI codes from manpages.")
372 (defconst Man-berkeley-sed-script "\
373 /\b/ { s/_\b//g\\
374 s/\b_//g\\
375 s/o\b+/o/g\\
376 s/+\bo/o/g\\
377 :ovstrk\\
378 s/\\(.\\)\b\\1/\\1/g\\
379 t ovstrk\\
381 /\e\\[[0-9][0-9]*m/ s///g"
382 "Script for berkeley-like sed to nuke backspaces and ANSI codes from manpages.")
384 (defvar Man-topic-history nil "Topic read history.")
386 (defvar man-mode-syntax-table
387 (let ((table (copy-syntax-table (standard-syntax-table))))
388 (modify-syntax-entry ?. "w" table)
389 (modify-syntax-entry ?_ "w" table)
390 (modify-syntax-entry ?: "w" table) ; for PDL::Primitive in Perl man pages
391 table)
392 "Syntax table used in Man mode buffers.")
394 (defvar Man-mode-map
395 (let ((map (make-sparse-keymap)))
396 (suppress-keymap map)
397 (set-keymap-parent map button-buffer-map)
399 (define-key map " " 'scroll-up)
400 (define-key map "\177" 'scroll-down)
401 (define-key map "n" 'Man-next-section)
402 (define-key map "p" 'Man-previous-section)
403 (define-key map "\en" 'Man-next-manpage)
404 (define-key map "\ep" 'Man-previous-manpage)
405 (define-key map ">" 'end-of-buffer)
406 (define-key map "<" 'beginning-of-buffer)
407 (define-key map "." 'beginning-of-buffer)
408 (define-key map "r" 'Man-follow-manual-reference)
409 (define-key map "g" 'Man-goto-section)
410 (define-key map "s" 'Man-goto-see-also-section)
411 (define-key map "k" 'Man-kill)
412 (define-key map "q" 'Man-quit)
413 (define-key map "m" 'man)
414 ;; Not all the man references get buttons currently. The text in the
415 ;; manual page can contain references to other man pages
416 (define-key map "\r" 'man-follow)
417 (define-key map "?" 'describe-mode)
418 map)
419 "Keymap for Man mode.")
421 ;; buttons
422 (define-button-type 'Man-abstract-xref-man-page
423 'follow-link t
424 'help-echo "mouse-2, RET: display this man page"
425 'func nil
426 'action #'Man-xref-button-action)
428 (defun Man-xref-button-action (button)
429 (let ((target (button-get button 'Man-target-string)))
430 (funcall
431 (button-get button 'func)
432 (cond ((null target)
433 (button-label button))
434 ((functionp target)
435 (funcall target (button-start button)))
436 (t target)))))
438 (define-button-type 'Man-xref-man-page
439 :supertype 'Man-abstract-xref-man-page
440 'func 'man-follow)
443 (define-button-type 'Man-xref-header-file
444 'action (lambda (button)
445 (let ((w (button-get button 'Man-target-string)))
446 (unless (Man-view-header-file w)
447 (error "Cannot find header file: %s" w))))
448 'follow-link t
449 'help-echo "mouse-2: display this header file")
451 (define-button-type 'Man-xref-normal-file
452 'action (lambda (button)
453 (let ((f (substitute-in-file-name
454 (button-get button 'Man-target-string))))
455 (if (file-exists-p f)
456 (if (file-readable-p f)
457 (view-file f)
458 (error "Cannot read a file: %s" f))
459 (error "Cannot find a file: %s" f))))
460 'follow-link t
461 'help-echo "mouse-2: display this file")
464 ;; ======================================================================
465 ;; utilities
467 (defun Man-init-defvars ()
468 "Used for initializing variables based on display's color support.
469 This is necessary if one wants to dump man.el with Emacs."
471 ;; Avoid possible error in call-process by using a directory that must exist.
472 (let ((default-directory "/"))
473 (setq Man-sed-script
474 (cond
475 (Man-fontify-manpage-flag
476 nil)
477 ((eq 0 (call-process Man-sed-command nil nil nil Man-sysv-sed-script))
478 Man-sysv-sed-script)
479 ((eq 0 (call-process Man-sed-command nil nil nil Man-berkeley-sed-script))
480 Man-berkeley-sed-script)
482 nil))))
484 (setq Man-filter-list
485 ;; Avoid trailing nil which confuses customize.
486 (apply 'list
487 (cons
488 Man-sed-command
489 (if (eq system-type 'windows-nt)
490 ;; Windows needs ".." quoting, not '..'.
491 (list
492 "-e \"/Reformatting page. Wait/d\""
493 "-e \"/Reformatting entry. Wait/d\""
494 "-e \"/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d\""
495 "-e \"/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d\""
496 "-e \"/^Printed[ \t][0-9].*[0-9]$/d\""
497 "-e \"/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d\""
498 "-e \"/^[A-Za-z].*Last[ \t]change:/d\""
499 "-e \"/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d\""
500 "-e \"/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d\"")
501 (list
502 (if Man-sed-script
503 (concat "-e '" Man-sed-script "'")
505 "-e '/^[\001-\032][\001-\032]*$/d'"
506 "-e '/\e[789]/s///g'"
507 "-e '/Reformatting page. Wait/d'"
508 "-e '/Reformatting entry. Wait/d'"
509 "-e '/^[ \t]*Hewlett-Packard[ \t]Company[ \t]*-[ \t][0-9]*[ \t]-/d'"
510 "-e '/^[ \t]*Hewlett-Packard[ \t]*-[ \t][0-9]*[ \t]-.*$/d'"
511 "-e '/^[ \t][ \t]*-[ \t][0-9]*[ \t]-[ \t]*Formatted:.*[0-9]$/d'"
512 "-e '/^[ \t]*Page[ \t][0-9]*.*(printed[ \t][0-9\\/]*)$/d'"
513 "-e '/^Printed[ \t][0-9].*[0-9]$/d'"
514 "-e '/^[ \t]*X[ \t]Version[ \t]1[01].*Release[ \t][0-9]/d'"
515 "-e '/^[A-Za-z].*Last[ \t]change:/d'"
516 "-e '/^Sun[ \t]Release[ \t][0-9].*[0-9]$/d'"
517 "-e '/[ \t]*Copyright [0-9]* UNIX System Laboratories, Inc.$/d'"
518 "-e '/^[ \t]*Rev\\..*Page [0-9][0-9]*$/d'"
520 ;; Windows doesn't support multi-line commands, so don't
521 ;; invoke Awk there.
522 (unless (eq system-type 'windows-nt)
523 (cons
524 Man-awk-command
525 (list
526 "'\n"
527 "BEGIN { blankline=0; anonblank=0; }\n"
528 "/^$/ { if (anonblank==0) next; }\n"
529 "{ anonblank=1; }\n"
530 "/^$/ { blankline++; next; }\n"
531 "{ if (blankline>0) { print \"\"; blankline=0; } print $0; }\n"
534 (if (not Man-uses-untabify-flag)
535 ;; The outer list will be stripped off by apply.
536 (list (cons
537 Man-untabify-command
538 Man-untabify-command-args))
542 (defsubst Man-make-page-mode-string ()
543 "Formats part of the mode line for Man mode."
544 (format "%s page %d of %d"
545 (or (nth 2 (nth (1- Man-current-page) Man-page-list))
547 Man-current-page
548 (length Man-page-list)))
550 (defsubst Man-build-man-command ()
551 "Builds the entire background manpage and cleaning command."
552 (let ((command (concat manual-program " " Man-switches
553 (cond
554 ;; Already has %s
555 ((string-match "%s" manual-program) "")
556 ;; Stock MS-DOS shells cannot redirect stderr;
557 ;; `call-process' below sends it to /dev/null,
558 ;; so we don't need `2>' even with DOS shells
559 ;; which do support stderr redirection.
560 ((not (fboundp 'start-process)) " %s")
561 ((concat " %s 2>" null-device)))))
562 (flist Man-filter-list))
563 (while (and flist (car flist))
564 (let ((pcom (car (car flist)))
565 (pargs (cdr (car flist))))
566 (setq command
567 (concat command " | " pcom " "
568 (mapconcat (lambda (phrase)
569 (if (not (stringp phrase))
570 (error "Malformed Man-filter-list"))
571 phrase)
572 pargs " ")))
573 (setq flist (cdr flist))))
574 command))
577 (defun Man-translate-cleanup (string)
578 "Strip leading, trailing and middle spaces."
579 (when (stringp string)
580 ;; Strip leading and trailing
581 (if (string-match "^[ \t\f\r\n]*\\(.+[^ \t\f\r\n]\\)" string)
582 (setq string (match-string 1 string)))
583 ;; middle spaces
584 (setq string (replace-regexp-in-string "[\t\r\n]" " " string))
585 (setq string (replace-regexp-in-string " +" " " string))
586 string))
588 (defun Man-translate-references (ref)
589 "Translates REF from \"chmod(2V)\" to \"2v chmod\" style.
590 Leave it as is if already in that style. Possibly downcase and
591 translate the section (see the `Man-downcase-section-letters-flag'
592 and the `Man-section-translations-alist' variables)."
593 (let ((name "")
594 (section "")
595 (slist Man-section-translations-alist))
596 (setq ref (Man-translate-cleanup ref))
597 (cond
598 ;; "chmod(2V)" case ?
599 ((string-match (concat "^" Man-reference-regexp "$") ref)
600 (setq name (match-string 1 ref)
601 section (match-string 2 ref)))
602 ;; "2v chmod" case ?
603 ((string-match (concat "^\\(" Man-section-regexp
604 "\\) +\\(" Man-name-regexp "\\)$") ref)
605 (setq name (match-string 2 ref)
606 section (match-string 1 ref))))
607 (if (string= name "")
608 ref ; Return the reference as is
609 (if Man-downcase-section-letters-flag
610 (setq section (downcase section)))
611 (while slist
612 (let ((s1 (car (car slist)))
613 (s2 (cdr (car slist))))
614 (setq slist (cdr slist))
615 (if Man-downcase-section-letters-flag
616 (setq s1 (downcase s1)))
617 (if (not (string= s1 section)) nil
618 (setq section (if Man-downcase-section-letters-flag
619 (downcase s2)
621 slist nil))))
622 (concat Man-specified-section-option section " " name))))
624 (defun Man-support-local-filenames ()
625 "Check the availability of `-l' option of the man command.
626 This option allows `man' to interpret command line arguments
627 as local filenames.
628 Return the value of the variable `Man-support-local-filenames'
629 if it was set to nil or t before the call of this function.
630 If t, the man command supports `-l' option. If nil, it doesn't.
631 Otherwise, if the value of `Man-support-local-filenames'
632 is neither t nor nil, then determine a new value, set it
633 to the variable `Man-support-local-filenames' and return
634 a new value."
635 (if (or (not Man-support-local-filenames)
636 (eq Man-support-local-filenames t))
637 Man-support-local-filenames
638 (setq Man-support-local-filenames
639 (with-temp-buffer
640 (and (equal (condition-case nil
641 (let ((default-directory
642 ;; Assure that `default-directory' exists
643 ;; and is readable.
644 (if (and (file-directory-p default-directory)
645 (file-readable-p default-directory))
646 default-directory
647 (expand-file-name "~/"))))
648 (call-process manual-program nil t nil "--help"))
649 (error nil))
651 (progn
652 (goto-char (point-min))
653 (search-forward "--local-file" nil t))
654 t)))))
657 ;; ======================================================================
658 ;; default man entry: get word near point
660 (defun Man-default-man-entry (&optional pos)
661 "Guess default manual entry based on the text near position POS.
662 POS defaults to `point'."
663 (let (word start pos column distance)
664 (save-excursion
665 (when pos (goto-char pos))
666 (setq pos (point))
667 ;; The default title is the nearest entry-like object before or
668 ;; after POS.
669 (if (and (skip-chars-backward " \ta-zA-Z0-9+")
670 (not (zerop (skip-chars-backward "(")))
671 ;; Try to handle the special case where POS is on a
672 ;; section number.
673 (looking-at
674 (concat "([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
675 ;; We skipped a valid section number backwards, look at
676 ;; preceding text.
677 (or (and (skip-chars-backward ",; \t")
678 (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:"))))
679 ;; Not a valid entry, move POS after closing paren.
680 (not (setq pos (match-end 0)))))
681 ;; We have a candidate, make `start' record its starting
682 ;; position.
683 (setq start (point))
684 ;; Otherwise look at char before POS.
685 (goto-char pos)
686 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
687 ;; Our candidate is just before or around POS.
688 (setq start (point))
689 ;; Otherwise record the current column and look backwards.
690 (setq column (current-column))
691 (skip-chars-backward ",; \t")
692 ;; Record the distance travelled.
693 (setq distance (- column (current-column)))
694 (when (looking-back
695 (concat "([ \t]*\\(?:" Man-section-regexp "\\)[ \t]*)"))
696 ;; Skip section number backwards.
697 (goto-char (match-beginning 0))
698 (skip-chars-backward " \t"))
699 (if (not (zerop (skip-chars-backward "-a-zA-Z0-9._+:")))
700 (progn
701 ;; We have a candidate before POS ...
702 (setq start (point))
703 (goto-char pos)
704 (if (and (skip-chars-forward ",; \t")
705 (< (- (current-column) column) distance)
706 (looking-at "[-a-zA-Z0-9._+:]"))
707 ;; ... but the one after POS is better.
708 (setq start (point))
709 ;; ... and anything after POS is worse.
710 (goto-char start)))
711 ;; No candidate before POS.
712 (goto-char pos)
713 (skip-chars-forward ",; \t")
714 (setq start (point)))))
715 ;; We have found a suitable starting point, try to skip at least
716 ;; one character.
717 (skip-chars-forward "-a-zA-Z0-9._+:")
718 (setq word (buffer-substring-no-properties start (point)))
719 ;; If there is a continuation at the end of line, check the
720 ;; following line too, eg:
721 ;; see this-
722 ;; command-here(1)
723 ;; Note: This code gets executed iff our entry is after POS.
724 (when (looking-at "[ \t\r\n]+\\([-a-zA-Z0-9._+:]+\\)([0-9])")
725 (setq word (concat word (match-string-no-properties 1)))
726 ;; Make sure the section number gets included by the code below.
727 (goto-char (match-end 1)))
728 (when (string-match "[._]+$" word)
729 (setq word (substring word 0 (match-beginning 0))))
730 ;; The following was commented out since the preceding code
731 ;; should not produce a leading "*" in the first place.
732 ;;; ;; If looking at something like *strcat(... , remove the '*'
733 ;;; (when (string-match "^*" word)
734 ;;; (setq word (substring word 1)))
735 (concat
736 word
737 (and (not (string-equal word ""))
738 ;; If looking at something like ioctl(2) or brc(1M),
739 ;; include the section number in the returned value.
740 (looking-at
741 (concat "[ \t]*([ \t]*\\(" Man-section-regexp "\\)[ \t]*)"))
742 (format "(%s)" (match-string-no-properties 1)))))))
745 ;; ======================================================================
746 ;; Top level command and background process sentinel
748 ;; For compatibility with older versions.
749 ;;;###autoload
750 (defalias 'manual-entry 'man)
752 (defun Man-completion-table (string pred action)
753 (cond
754 ((memq action '(t nil))
755 (let ((table '()))
756 (with-temp-buffer
757 ;; Actually for my `man' the arg is a regexp. Don't know how
758 ;; standard that is. Also, it's not clear what kind of
759 ;; regexp are accepted: under GNU/Linux it seems it's ERE-style,
760 ;; whereas under MacOSX it seems to be BRE-style and
761 ;; doesn't accept backslashes at all. Let's not bother to
762 ;; quote anything.
763 (call-process "man" nil '(t nil) nil "-k" (concat "^" string))
764 (goto-char (point-min))
765 (while (re-search-forward "^[^ \t\n]+" nil t)
766 (push (match-string 0) table)))
767 ;; The table may contain false positives since the match is made
768 ;; by "man -k" not just on the manpage's name.
769 (complete-with-action action table string pred)))
770 ((eq action 'lambda) t)
771 ((eq (car-safe action) 'boundaries) nil)))
773 ;;;###autoload
774 (defun man (man-args)
775 "Get a Un*x manual page and put it in a buffer.
776 This command is the top-level command in the man package. It runs a Un*x
777 command to retrieve and clean a manpage in the background and places the
778 results in a Man mode (manpage browsing) buffer. See variable
779 `Man-notify-method' for what happens when the buffer is ready.
780 If a buffer already exists for this man page, it will display immediately.
782 To specify a man page from a certain section, type SUBJECT(SECTION) or
783 SECTION SUBJECT when prompted for a manual entry. To see manpages from
784 all sections related to a subject, put something appropriate into the
785 `Man-switches' variable, which see."
786 (interactive
787 (list (let* ((default-entry (Man-default-man-entry))
788 (input (completing-read
789 (format "Manual entry%s"
790 (if (string= default-entry "")
791 ": "
792 (format " (default %s): " default-entry)))
793 'Man-completion-table
794 nil nil nil 'Man-topic-history default-entry)))
795 (if (string= input "")
796 (error "No man args given")
797 input))))
799 ;; Possibly translate the "subject(section)" syntax into the
800 ;; "section subject" syntax and possibly downcase the section.
801 (setq man-args (Man-translate-references man-args))
803 (Man-getpage-in-background man-args))
805 ;;;###autoload
806 (defun man-follow (man-args)
807 "Get a Un*x manual page of the item under point and put it in a buffer."
808 (interactive (list (Man-default-man-entry)))
809 (if (or (not man-args)
810 (string= man-args ""))
811 (error "No item under point")
812 (man man-args)))
814 (defun Man-getpage-in-background (topic)
815 "Use TOPIC to build and fire off the manpage and cleaning command."
816 (let* ((man-args topic)
817 (bufname (concat "*Man " man-args "*"))
818 (buffer (get-buffer bufname)))
819 (if buffer
820 (Man-notify-when-ready buffer)
821 (require 'env)
822 (message "Invoking %s %s in the background" manual-program man-args)
823 (setq buffer (generate-new-buffer bufname))
824 (with-current-buffer buffer
825 (setq buffer-undo-list t)
826 (setq Man-original-frame (selected-frame))
827 (setq Man-arguments man-args))
828 (let ((process-environment (copy-sequence process-environment))
829 ;; The following is so Awk script gets \n intact
830 ;; But don't prevent decoding of the outside.
831 (coding-system-for-write 'raw-text-unix)
832 ;; We must decode the output by a coding system that the
833 ;; system's locale suggests in multibyte mode.
834 (coding-system-for-read
835 (if (default-value 'enable-multibyte-characters)
836 locale-coding-system 'raw-text-unix))
837 ;; Avoid possible error by using a directory that always exists.
838 (default-directory
839 (if (and (file-directory-p default-directory)
840 (not (find-file-name-handler default-directory
841 'file-directory-p)))
842 default-directory
843 "/")))
844 ;; Prevent any attempt to use display terminal fanciness.
845 (setenv "TERM" "dumb")
846 ;; In Debian Woody, at least, we get overlong lines under X
847 ;; unless COLUMNS or MANWIDTH is set. This isn't a problem on
848 ;; a tty. man(1) says:
849 ;; MANWIDTH
850 ;; If $MANWIDTH is set, its value is used as the line
851 ;; length for which manual pages should be formatted.
852 ;; If it is not set, manual pages will be formatted
853 ;; with a line length appropriate to the current ter-
854 ;; minal (using an ioctl(2) if available, the value of
855 ;; $COLUMNS, or falling back to 80 characters if nei-
856 ;; ther is available).
857 (unless (or (getenv "MANWIDTH") (getenv "COLUMNS"))
858 ;; This isn't strictly correct, since we don't know how
859 ;; the page will actually be displayed, but it seems
860 ;; reasonable.
861 (setenv "COLUMNS" (number-to-string
862 (cond
863 ((and (integerp Man-width) (> Man-width 0))
864 Man-width)
865 (Man-width (frame-width))
866 ((window-width))))))
867 (setenv "GROFF_NO_SGR" "1")
868 ;; Since man-db 2.4.3-1, man writes plain text with no escape
869 ;; sequences when stdout is not a tty. In 2.5.0, the following
870 ;; env-var was added to allow control of this (see Debian Bug#340673).
871 (setenv "MAN_KEEP_FORMATTING" "1")
872 (if (fboundp 'start-process)
873 (set-process-sentinel
874 (start-process manual-program buffer
875 (if (memq system-type '(cygwin windows-nt))
876 shell-file-name
877 "sh")
878 shell-command-switch
879 (format (Man-build-man-command) man-args))
880 'Man-bgproc-sentinel)
881 (let ((exit-status
882 (call-process shell-file-name nil (list buffer nil) nil
883 shell-command-switch
884 (format (Man-build-man-command) man-args)))
885 (msg ""))
886 (or (and (numberp exit-status)
887 (= exit-status 0))
888 (and (numberp exit-status)
889 (setq msg
890 (format "exited abnormally with code %d"
891 exit-status)))
892 (setq msg exit-status))
893 (Man-bgproc-sentinel bufname msg)))))))
895 (defun Man-notify-when-ready (man-buffer)
896 "Notify the user when MAN-BUFFER is ready.
897 See the variable `Man-notify-method' for the different notification behaviors."
898 (let ((saved-frame (with-current-buffer man-buffer
899 Man-original-frame)))
900 (cond
901 ((eq Man-notify-method 'newframe)
902 ;; Since we run asynchronously, perhaps while Emacs is waiting
903 ;; for input, we must not leave a different buffer current. We
904 ;; can't rely on the editor command loop to reselect the
905 ;; selected window's buffer.
906 (save-excursion
907 (let ((frame (make-frame Man-frame-parameters)))
908 (set-window-buffer (frame-selected-window frame) man-buffer)
909 (set-window-dedicated-p (frame-selected-window frame) t)
910 (or (display-multi-frame-p frame)
911 (select-frame frame)))))
912 ((eq Man-notify-method 'pushy)
913 (switch-to-buffer man-buffer))
914 ((eq Man-notify-method 'bully)
915 (and (frame-live-p saved-frame)
916 (select-frame saved-frame))
917 (pop-to-buffer man-buffer)
918 (delete-other-windows))
919 ((eq Man-notify-method 'aggressive)
920 (and (frame-live-p saved-frame)
921 (select-frame saved-frame))
922 (pop-to-buffer man-buffer))
923 ((eq Man-notify-method 'friendly)
924 (and (frame-live-p saved-frame)
925 (select-frame saved-frame))
926 (display-buffer man-buffer 'not-this-window))
927 ((eq Man-notify-method 'polite)
928 (beep)
929 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
930 ((eq Man-notify-method 'quiet)
931 (message "Manual buffer %s is ready" (buffer-name man-buffer)))
932 ((or (eq Man-notify-method 'meek)
934 (message ""))
937 (defun Man-softhyphen-to-minus ()
938 ;; \255 is SOFT HYPHEN in Latin-N. Versions of Debian man, at
939 ;; least, emit it even when not in a Latin-N locale.
940 (unless (eq t (compare-strings "latin-" 0 nil
941 current-language-environment 0 6 t))
942 (goto-char (point-min))
943 (let ((str "\255"))
944 (if enable-multibyte-characters
945 (setq str (string-as-multibyte str)))
946 (while (search-forward str nil t) (replace-match "-")))))
948 (defun Man-fontify-manpage ()
949 "Convert overstriking and underlining to the correct fonts.
950 Same for the ANSI bold and normal escape sequences."
951 (interactive)
952 (message "Please wait: formatting the %s man page..." Man-arguments)
953 (goto-char (point-min))
954 ;; Fontify ANSI escapes.
955 (let ((faces nil)
956 (buffer-undo-list t)
957 (start (point)))
958 ;; http://www.isthe.com/chongo/tech/comp/ansi_escapes.html
959 ;; suggests many codes, but we only handle:
960 ;; ESC [ 00 m reset to normal display
961 ;; ESC [ 01 m bold
962 ;; ESC [ 04 m underline
963 ;; ESC [ 07 m reverse-video
964 ;; ESC [ 22 m no-bold
965 ;; ESC [ 24 m no-underline
966 ;; ESC [ 27 m no-reverse-video
967 (while (re-search-forward "\e\\[0?\\([1470]\\|2\\([247]\\)\\)m" nil t)
968 (if faces (put-text-property start (match-beginning 0) 'face
969 (if (cdr faces) faces (car faces))))
970 (setq faces
971 (cond
972 ((match-beginning 2)
973 (delq (case (char-after (match-beginning 2))
974 (?2 Man-overstrike-face)
975 (?4 Man-underline-face)
976 (?7 Man-reverse-face))
977 faces))
978 ((eq (char-after (match-beginning 1)) ?0) nil)
980 (cons (case (char-after (match-beginning 1))
981 (?1 Man-overstrike-face)
982 (?4 Man-underline-face)
983 (?7 Man-reverse-face))
984 faces))))
985 (delete-region (match-beginning 0) (match-end 0))
986 (setq start (point))))
987 ;; Other highlighting.
988 (let ((buffer-undo-list t))
989 (if (< (buffer-size) (position-bytes (point-max)))
990 ;; Multibyte characters exist.
991 (progn
992 (goto-char (point-min))
993 (while (search-forward "__\b\b" nil t)
994 (backward-delete-char 4)
995 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
996 (goto-char (point-min))
997 (while (search-forward "\b\b__" nil t)
998 (backward-delete-char 4)
999 (put-text-property (1- (point)) (point) 'face Man-underline-face))))
1000 (goto-char (point-min))
1001 (while (search-forward "_\b" nil t)
1002 (backward-delete-char 2)
1003 (put-text-property (point) (1+ (point)) 'face Man-underline-face))
1004 (goto-char (point-min))
1005 (while (search-forward "\b_" nil t)
1006 (backward-delete-char 2)
1007 (put-text-property (1- (point)) (point) 'face Man-underline-face))
1008 (goto-char (point-min))
1009 (while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
1010 (replace-match "\\1")
1011 (put-text-property (1- (point)) (point) 'face Man-overstrike-face))
1012 (goto-char (point-min))
1013 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
1014 (replace-match "o")
1015 (put-text-property (1- (point)) (point) 'face 'bold))
1016 (goto-char (point-min))
1017 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
1018 (replace-match "+")
1019 (put-text-property (1- (point)) (point) 'face 'bold))
1020 (goto-char (point-min))
1021 ;; Try to recognize common forms of cross references.
1022 (Man-highlight-references)
1023 (Man-softhyphen-to-minus)
1024 (goto-char (point-min))
1025 (while (re-search-forward Man-heading-regexp nil t)
1026 (put-text-property (match-beginning 0)
1027 (match-end 0)
1028 'face Man-overstrike-face)))
1029 (message "%s man page formatted" Man-arguments))
1031 (defun Man-highlight-references (&optional xref-man-type)
1032 "Highlight the references on mouse-over.
1033 References include items in the SEE ALSO section,
1034 header file (#include <foo.h>), and files in FILES.
1035 If optional argument XREF-MAN-TYPE is non-nil, it used as the
1036 button type for items in SEE ALSO section. If it is nil, the
1037 default type, `Man-xref-man-page' is used for the buttons."
1038 ;; `Man-highlight-references' is used from woman.el, too.
1039 ;; woman.el doesn't set `Man-arguments'.
1040 (unless Man-arguments
1041 (setq Man-arguments ""))
1042 (if (string-match "-k " Man-arguments)
1043 (progn
1044 (Man-highlight-references0 nil Man-reference-regexp 1
1045 'Man-default-man-entry
1046 (or xref-man-type 'Man-xref-man-page))
1047 (Man-highlight-references0 nil Man-apropos-regexp 1
1048 'Man-default-man-entry
1049 (or xref-man-type 'Man-xref-man-page)))
1050 (Man-highlight-references0 Man-see-also-regexp Man-reference-regexp 1
1051 'Man-default-man-entry
1052 (or xref-man-type 'Man-xref-man-page))
1053 (Man-highlight-references0 Man-synopsis-regexp Man-header-regexp 0 2
1054 'Man-xref-header-file)
1055 (Man-highlight-references0 Man-files-regexp Man-normal-file-regexp 0 0
1056 'Man-xref-normal-file)))
1058 (defun Man-highlight-references0 (start-section regexp button-pos target type)
1059 ;; Based on `Man-build-references-alist'
1060 (when (or (null start-section)
1061 (Man-find-section start-section))
1062 (let ((end (if start-section
1063 (progn
1064 (forward-line 1)
1065 (back-to-indentation)
1066 (save-excursion
1067 (Man-next-section 1)
1068 (point)))
1069 (goto-char (point-min))
1070 nil)))
1071 (while (re-search-forward regexp end t)
1072 (make-text-button
1073 (match-beginning button-pos)
1074 (match-end button-pos)
1075 'type type
1076 'Man-target-string (cond
1077 ((numberp target)
1078 (match-string target))
1079 ((functionp target)
1080 target)
1081 (t nil)))))))
1083 (defun Man-cleanup-manpage (&optional interactive)
1084 "Remove overstriking and underlining from the current buffer.
1085 Normally skip any jobs that should have been done by the sed script,
1086 but when called interactively, do those jobs even if the sed
1087 script would have done them."
1088 (interactive "p")
1089 (message "Please wait: cleaning up the %s man page..."
1090 Man-arguments)
1091 (if (or interactive (not Man-sed-script))
1092 (progn
1093 (goto-char (point-min))
1094 (while (search-forward "_\b" nil t) (backward-delete-char 2))
1095 (goto-char (point-min))
1096 (while (search-forward "\b_" nil t) (backward-delete-char 2))
1097 (goto-char (point-min))
1098 (while (re-search-forward "\\(.\\)\\(\b\\1\\)+" nil t)
1099 (replace-match "\\1"))
1100 (goto-char (point-min))
1101 (while (re-search-forward "\e\\[[0-9]+m" nil t) (replace-match ""))
1102 (goto-char (point-min))
1103 (while (re-search-forward "o\b\\+\\|\\+\bo" nil t) (replace-match "o"))
1105 (goto-char (point-min))
1106 (while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t) (replace-match "+"))
1107 (Man-softhyphen-to-minus)
1108 (message "%s man page cleaned up" Man-arguments))
1110 (defun Man-bgproc-sentinel (process msg)
1111 "Manpage background process sentinel.
1112 When manpage command is run asynchronously, PROCESS is the process
1113 object for the manpage command; when manpage command is run
1114 synchronously, PROCESS is the name of the buffer where the manpage
1115 command is run. Second argument MSG is the exit message of the
1116 manpage command."
1117 (let ((Man-buffer (if (stringp process) (get-buffer process)
1118 (process-buffer process)))
1119 (delete-buff nil)
1120 (err-mess nil))
1122 (if (null (buffer-name Man-buffer)) ;; deleted buffer
1123 (or (stringp process)
1124 (set-process-buffer process nil))
1126 (with-current-buffer Man-buffer
1127 (let ((case-fold-search nil))
1128 (goto-char (point-min))
1129 (cond ((or (looking-at "No \\(manual \\)*entry for")
1130 (looking-at "[^\n]*: nothing appropriate$"))
1131 (setq err-mess (buffer-substring (point)
1132 (progn
1133 (end-of-line) (point)))
1134 delete-buff t))
1135 ((or (stringp process)
1136 (not (and (eq (process-status process) 'exit)
1137 (= (process-exit-status process) 0))))
1138 (or (zerop (length msg))
1139 (progn
1140 (setq err-mess
1141 (concat (buffer-name Man-buffer)
1142 ": process "
1143 (let ((eos (1- (length msg))))
1144 (if (= (aref msg eos) ?\n)
1145 (substring msg 0 eos) msg))))
1146 (goto-char (point-max))
1147 (insert (format "\nprocess %s" msg))))
1149 (if delete-buff
1150 (kill-buffer Man-buffer)
1151 (if Man-fontify-manpage-flag
1152 (Man-fontify-manpage)
1153 (Man-cleanup-manpage))
1155 (run-hooks 'Man-cooked-hook)
1156 (Man-mode)
1158 (if (not Man-page-list)
1159 (let ((args Man-arguments))
1160 (kill-buffer (current-buffer))
1161 (error "Can't find the %s manpage" args)))
1163 (set-buffer-modified-p nil)
1165 ;; Restore case-fold-search before calling
1166 ;; Man-notify-when-ready because it may switch buffers.
1168 (if (not delete-buff)
1169 (Man-notify-when-ready Man-buffer))
1171 (if err-mess
1172 (error "%s" err-mess))
1173 ))))
1176 ;; ======================================================================
1177 ;; set up manual mode in buffer and build alists
1179 (put 'Man-mode 'mode-class 'special)
1181 (defun Man-mode ()
1182 "A mode for browsing Un*x manual pages.
1184 The following man commands are available in the buffer. Try
1185 \"\\[describe-key] <key> RET\" for more information:
1187 \\[man] Prompt to retrieve a new manpage.
1188 \\[Man-follow-manual-reference] Retrieve reference in SEE ALSO section.
1189 \\[Man-next-manpage] Jump to next manpage in circular list.
1190 \\[Man-previous-manpage] Jump to previous manpage in circular list.
1191 \\[Man-next-section] Jump to next manpage section.
1192 \\[Man-previous-section] Jump to previous manpage section.
1193 \\[Man-goto-section] Go to a manpage section.
1194 \\[Man-goto-see-also-section] Jumps to the SEE ALSO manpage section.
1195 \\[Man-quit] Deletes the manpage window, bury its buffer.
1196 \\[Man-kill] Deletes the manpage window, kill its buffer.
1197 \\[describe-mode] Prints this help text.
1199 The following variables may be of some use. Try
1200 \"\\[describe-variable] <variable-name> RET\" for more information:
1202 `Man-notify-method' What happens when manpage formatting is done.
1203 `Man-downcase-section-letters-flag' Force section letters to lower case.
1204 `Man-circular-pages-flag' Treat multiple manpage list as circular.
1205 `Man-section-translations-alist' List of section numbers and their Un*x equiv.
1206 `Man-filter-list' Background manpage filter command.
1207 `Man-mode-map' Keymap bindings for Man mode buffers.
1208 `Man-mode-hook' Normal hook run on entry to Man mode.
1209 `Man-section-regexp' Regexp describing manpage section letters.
1210 `Man-heading-regexp' Regexp describing section headers.
1211 `Man-see-also-regexp' Regexp for SEE ALSO section (or your equiv).
1212 `Man-first-heading-regexp' Regexp for first heading on a manpage.
1213 `Man-reference-regexp' Regexp matching a references in SEE ALSO.
1214 `Man-switches' Background `man' command switches.
1216 The following key bindings are currently in effect in the buffer:
1217 \\{Man-mode-map}"
1218 (interactive)
1219 (kill-all-local-variables)
1220 (setq major-mode 'Man-mode
1221 mode-name "Man"
1222 buffer-auto-save-file-name nil
1223 mode-line-buffer-identification
1224 (list (default-value 'mode-line-buffer-identification)
1225 " {" 'Man-page-mode-string "}")
1226 truncate-lines t
1227 buffer-read-only t)
1228 (buffer-disable-undo)
1229 (auto-fill-mode -1)
1230 (use-local-map Man-mode-map)
1231 (set-syntax-table man-mode-syntax-table)
1232 (setq imenu-generic-expression (list (list nil Man-heading-regexp 0)))
1233 (set (make-local-variable 'outline-regexp) Man-heading-regexp)
1234 (set (make-local-variable 'outline-level) (lambda () 1))
1235 (Man-build-page-list)
1236 (Man-strip-page-headers)
1237 (Man-unindent)
1238 (Man-goto-page 1 t)
1239 (run-mode-hooks 'Man-mode-hook))
1241 (defsubst Man-build-section-alist ()
1242 "Build the association list of manpage sections."
1243 (setq Man-sections-alist nil)
1244 (goto-char (point-min))
1245 (let ((case-fold-search nil))
1246 (while (re-search-forward Man-heading-regexp (point-max) t)
1247 (aput 'Man-sections-alist (match-string 1))
1248 (forward-line 1))))
1250 (defsubst Man-build-references-alist ()
1251 "Build the association list of references (in the SEE ALSO section)."
1252 (setq Man-refpages-alist nil)
1253 (save-excursion
1254 (if (Man-find-section Man-see-also-regexp)
1255 (let ((start (progn (forward-line 1) (point)))
1256 (end (progn
1257 (Man-next-section 1)
1258 (point)))
1259 hyphenated
1260 (runningpoint -1))
1261 (save-restriction
1262 (narrow-to-region start end)
1263 (goto-char (point-min))
1264 (back-to-indentation)
1265 (while (and (not (eobp)) (/= (point) runningpoint))
1266 (setq runningpoint (point))
1267 (if (re-search-forward Man-hyphenated-reference-regexp end t)
1268 (let* ((word (match-string 0))
1269 (len (1- (length word))))
1270 (if hyphenated
1271 (setq word (concat hyphenated word)
1272 hyphenated nil
1273 ;; Update len, in case a reference spans
1274 ;; more than two lines (paranoia).
1275 len (1- (length word))))
1276 (if (memq (aref word len) '(?- ?­))
1277 (setq hyphenated (substring word 0 len)))
1278 (if (string-match Man-reference-regexp word)
1279 (aput 'Man-refpages-alist word))))
1280 (skip-chars-forward " \t\n,"))))))
1281 (setq Man-refpages-alist (nreverse Man-refpages-alist)))
1283 (defun Man-build-page-list ()
1284 "Build the list of separate manpages in the buffer."
1285 (setq Man-page-list nil)
1286 (let ((page-start (point-min))
1287 (page-end (point-max))
1288 (header ""))
1289 (goto-char page-start)
1290 ;; (switch-to-buffer (current-buffer))(debug)
1291 (while (not (eobp))
1292 (setq header
1293 (if (looking-at Man-page-header-regexp)
1294 (match-string 1)
1295 nil))
1296 ;; Go past both the current and the next Man-first-heading-regexp
1297 (if (re-search-forward Man-first-heading-regexp nil 'move 2)
1298 (let ((p (progn (beginning-of-line) (point))))
1299 ;; We assume that the page header is delimited by blank
1300 ;; lines and that it contains at most one blank line. So
1301 ;; if we back by three blank lines we will be sure to be
1302 ;; before the page header but not before the possible
1303 ;; previous page header.
1304 (search-backward "\n\n" nil t 3)
1305 (if (re-search-forward Man-page-header-regexp p 'move)
1306 (beginning-of-line))))
1307 (setq page-end (point))
1308 (setq Man-page-list (append Man-page-list
1309 (list (list (copy-marker page-start)
1310 (copy-marker page-end)
1311 header))))
1312 (setq page-start page-end)
1315 (defun Man-strip-page-headers ()
1316 "Strip all the page headers but the first from the manpage."
1317 (let ((inhibit-read-only t)
1318 (case-fold-search nil)
1319 (header ""))
1320 (dolist (page Man-page-list)
1321 (and (nth 2 page)
1322 (goto-char (car page))
1323 (re-search-forward Man-first-heading-regexp nil t)
1324 (setq header (buffer-substring (car page) (match-beginning 0)))
1325 ;; Since the awk script collapses all successive blank
1326 ;; lines into one, and since we don't want to get rid of
1327 ;; the fast awk script, one must choose between adding
1328 ;; spare blank lines between pages when there were none and
1329 ;; deleting blank lines at page boundaries when there were
1330 ;; some. We choose the first, so we comment the following
1331 ;; line.
1332 ;; (setq header (concat "\n" header)))
1333 (while (search-forward header (nth 1 page) t)
1334 (replace-match ""))))))
1336 (defun Man-unindent ()
1337 "Delete the leading spaces that indent the manpage."
1338 (let ((inhibit-read-only t)
1339 (case-fold-search nil))
1340 (dolist (page Man-page-list)
1341 (let ((indent "")
1342 (nindent 0))
1343 (narrow-to-region (car page) (car (cdr page)))
1344 (if Man-uses-untabify-flag
1345 (untabify (point-min) (point-max)))
1346 (if (catch 'unindent
1347 (goto-char (point-min))
1348 (if (not (re-search-forward Man-first-heading-regexp nil t))
1349 (throw 'unindent nil))
1350 (beginning-of-line)
1351 (setq indent (buffer-substring (point)
1352 (progn
1353 (skip-chars-forward " ")
1354 (point))))
1355 (setq nindent (length indent))
1356 (if (zerop nindent)
1357 (throw 'unindent nil))
1358 (setq indent (concat indent "\\|$"))
1359 (goto-char (point-min))
1360 (while (not (eobp))
1361 (if (looking-at indent)
1362 (forward-line 1)
1363 (throw 'unindent nil)))
1364 (goto-char (point-min)))
1365 (while (not (eobp))
1366 (or (eolp)
1367 (delete-char nindent))
1368 (forward-line 1)))
1369 ))))
1372 ;; ======================================================================
1373 ;; Man mode commands
1375 (defun Man-next-section (n)
1376 "Move point to Nth next section (default 1)."
1377 (interactive "p")
1378 (let ((case-fold-search nil)
1379 (start (point)))
1380 (if (looking-at Man-heading-regexp)
1381 (forward-line 1))
1382 (if (re-search-forward Man-heading-regexp (point-max) t n)
1383 (beginning-of-line)
1384 (goto-char (point-max))
1385 ;; The last line doesn't belong to any section.
1386 (forward-line -1))
1387 ;; But don't move back from the starting point (can happen if `start'
1388 ;; is somewhere on the last line).
1389 (if (< (point) start) (goto-char start))))
1391 (defun Man-previous-section (n)
1392 "Move point to Nth previous section (default 1)."
1393 (interactive "p")
1394 (let ((case-fold-search nil))
1395 (if (looking-at Man-heading-regexp)
1396 (forward-line -1))
1397 (if (re-search-backward Man-heading-regexp (point-min) t n)
1398 (beginning-of-line)
1399 (goto-char (point-min)))))
1401 (defun Man-find-section (section)
1402 "Move point to SECTION if it exists, otherwise don't move point.
1403 Returns t if section is found, nil otherwise."
1404 (let ((curpos (point))
1405 (case-fold-search nil))
1406 (goto-char (point-min))
1407 (if (re-search-forward (concat "^" section) (point-max) t)
1408 (progn (beginning-of-line) t)
1409 (goto-char curpos)
1410 nil)
1413 (defun Man-goto-section ()
1414 "Query for section to move point to."
1415 (interactive)
1416 (aput 'Man-sections-alist
1417 (let* ((default (aheadsym Man-sections-alist))
1418 (completion-ignore-case t)
1419 chosen
1420 (prompt (concat "Go to section (default " default "): ")))
1421 (setq chosen (completing-read prompt Man-sections-alist))
1422 (if (or (not chosen)
1423 (string= chosen ""))
1424 default
1425 chosen)))
1426 (Man-find-section (aheadsym Man-sections-alist)))
1428 (defun Man-goto-see-also-section ()
1429 "Move point to the \"SEE ALSO\" section.
1430 Actually the section moved to is described by `Man-see-also-regexp'."
1431 (interactive)
1432 (if (not (Man-find-section Man-see-also-regexp))
1433 (error "%s" (concat "No " Man-see-also-regexp
1434 " section found in the current manpage"))))
1436 (defun Man-possibly-hyphenated-word ()
1437 "Return a possibly hyphenated word at point.
1438 If the word starts at the first non-whitespace column, and the
1439 previous line ends with a hyphen, return the last word on the previous
1440 line instead. Thus, if a reference to \"tcgetpgrp(3V)\" is hyphenated
1441 as \"tcgetp-grp(3V)\", and point is at \"grp(3V)\", we return
1442 \"tcgetp-\" instead of \"grp\"."
1443 (save-excursion
1444 (skip-syntax-backward "w()")
1445 (skip-chars-forward " \t")
1446 (let ((beg (point))
1447 (word (current-word)))
1448 (when (eq beg (save-excursion
1449 (back-to-indentation)
1450 (point)))
1451 (end-of-line 0)
1452 (if (eq (char-before) ?-)
1453 (setq word (current-word))))
1454 word)))
1456 (defun Man-follow-manual-reference (reference)
1457 "Get one of the manpages referred to in the \"SEE ALSO\" section.
1458 Specify which REFERENCE to use; default is based on word at point."
1459 (interactive
1460 (if (not Man-refpages-alist)
1461 (error "There are no references in the current man page")
1462 (list
1463 (let* ((default (or
1464 (car (all-completions
1465 (let ((word
1466 (or (Man-possibly-hyphenated-word)
1467 "")))
1468 ;; strip a trailing '-':
1469 (if (string-match "-$" word)
1470 (substring word 0
1471 (match-beginning 0))
1472 word))
1473 Man-refpages-alist))
1474 (aheadsym Man-refpages-alist)))
1475 (defaults
1476 (mapcar 'substring-no-properties
1477 (delete-dups
1478 (delq nil (cons default
1479 (mapcar 'car Man-refpages-alist))))))
1480 chosen
1481 (prompt (concat "Refer to (default " default "): ")))
1482 (setq chosen (completing-read prompt Man-refpages-alist
1483 nil nil nil nil defaults))
1484 (if (or (not chosen)
1485 (string= chosen ""))
1486 default
1487 chosen)))))
1488 (if (not Man-refpages-alist)
1489 (error "Can't find any references in the current manpage")
1490 (aput 'Man-refpages-alist reference)
1491 (Man-getpage-in-background
1492 (Man-translate-references (aheadsym Man-refpages-alist)))))
1494 (defun Man-kill ()
1495 "Kill the buffer containing the manpage."
1496 (interactive)
1497 (quit-window t))
1499 (defun Man-quit ()
1500 "Bury the buffer containing the manpage."
1501 (interactive)
1502 (quit-window))
1504 (defun Man-goto-page (page &optional noerror)
1505 "Go to the manual page on page PAGE."
1506 (interactive
1507 (if (not Man-page-list)
1508 (error "Not a man page buffer")
1509 (if (= (length Man-page-list) 1)
1510 (error "You're looking at the only manpage in the buffer")
1511 (list (read-minibuffer (format "Go to manpage [1-%d]: "
1512 (length Man-page-list)))))))
1513 (if (and (not Man-page-list) (not noerror))
1514 (error "Not a man page buffer"))
1515 (when Man-page-list
1516 (if (or (< page 1)
1517 (> page (length Man-page-list)))
1518 (error "No manpage %d found" page))
1519 (let* ((page-range (nth (1- page) Man-page-list))
1520 (page-start (car page-range))
1521 (page-end (car (cdr page-range))))
1522 (setq Man-current-page page
1523 Man-page-mode-string (Man-make-page-mode-string))
1524 (widen)
1525 (goto-char page-start)
1526 (narrow-to-region page-start page-end)
1527 (Man-build-section-alist)
1528 (Man-build-references-alist)
1529 (goto-char (point-min)))))
1532 (defun Man-next-manpage ()
1533 "Find the next manpage entry in the buffer."
1534 (interactive)
1535 (if (= (length Man-page-list) 1)
1536 (error "This is the only manpage in the buffer"))
1537 (if (< Man-current-page (length Man-page-list))
1538 (Man-goto-page (1+ Man-current-page))
1539 (if Man-circular-pages-flag
1540 (Man-goto-page 1)
1541 (error "You're looking at the last manpage in the buffer"))))
1543 (defun Man-previous-manpage ()
1544 "Find the previous manpage entry in the buffer."
1545 (interactive)
1546 (if (= (length Man-page-list) 1)
1547 (error "This is the only manpage in the buffer"))
1548 (if (> Man-current-page 1)
1549 (Man-goto-page (1- Man-current-page))
1550 (if Man-circular-pages-flag
1551 (Man-goto-page (length Man-page-list))
1552 (error "You're looking at the first manpage in the buffer"))))
1554 ;; Header file support
1555 (defun Man-view-header-file (file)
1556 "View a header file specified by FILE from `Man-header-file-path'."
1557 (let ((path Man-header-file-path)
1558 complete-path)
1559 (while path
1560 (setq complete-path (expand-file-name file (car path))
1561 path (cdr path))
1562 (if (file-readable-p complete-path)
1563 (progn (view-file complete-path)
1564 (setq path nil))
1565 (setq complete-path nil)))
1566 complete-path))
1568 ;; Init the man package variables, if not already done.
1569 (Man-init-defvars)
1571 (add-to-list 'debug-ignored-errors "^No manpage [0-9]* found$")
1572 (add-to-list 'debug-ignored-errors "^Can't find the .* manpage$")
1574 (provide 'man)
1576 ;; arch-tag: 587cda76-8e23-4594-b1f3-89b6b09a0d47
1577 ;;; man.el ends here