Message format spec fixes (1)
[emacs.git] / lisp / woman.el
blob315a0a3bbe5878ccb28781071d055957b49f2a2c
1 ;;; woman.el --- browse UN*X manual pages `wo (without) man'
3 ;; Copyright (C) 2000, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
5 ;; Author: Francis J. Wright <F.J.Wright@qmul.ac.uk>
6 ;; Maintainer: FSF
7 ;; Keywords: help, unix
8 ;; Adapted-By: Eli Zaretskii <eliz@gnu.org>
9 ;; Version: see `woman-version'
10 ;; URL: http://centaur.maths.qmul.ac.uk/Emacs/WoMan/
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to the
26 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
27 ;; Boston, MA 02110-1301, USA.
29 ;;; Commentary:
31 ;; WoMan implements a subset of the formatting performed by the Emacs
32 ;; `man' (or `manual-entry') command to format a UN*X manual `page'
33 ;; for display, but without calling any external programs. It is
34 ;; intended to emulate the whole of the -man macro package, plus those
35 ;; ?roff requests that are most commonly used in man pages. However,
36 ;; the emulation is modified to include the reformatting done by the
37 ;; Emacs `man' command. No hyphenation is performed.
39 ;; Advantages
41 ;; Much more direct, does not require any external programs.
42 ;; Supports completion on man page names.
44 ;; Disadvantages
46 ;; Not a complete emulation. Currently no support for eqn or tbl.
47 ;; Slightly slower for large man pages (but usually faster for
48 ;; small- and medium-size pages).
50 ;; This browser works quite well on simple well-written man files. It
51 ;; works less well on idiosyncratic files that `break the rules' or
52 ;; use the more obscure ?roff requests directly. Current test results
53 ;; are available in the file woman.status.
55 ;; WoMan supports the use of compressed man files via
56 ;; `auto-compression-mode' by turning it on if necessary. But you may
57 ;; need to adjust the user option `woman-file-compression-regexp'.
59 ;; Read on for (currently) the only documentation for WoMan!
61 ;; See also the documentation for the WoMan interactive commands and
62 ;; user option variables, all of which begin with the prefix `woman-'.
63 ;; This can be done most easily by loading WoMan and then running the
64 ;; command `woman-mini-help', or selecting the WoMan menu option `Mini
65 ;; Help' when WoMan is running.
67 ;; WoMan is still under development! Please let me know what doesn't
68 ;; work -- I am adding and improving functionality as testing shows
69 ;; that it is necessary. See below for guidance on reporting bugs.
71 ;; Recommended use
72 ;; ===============
74 ;; Put this in your .emacs:
75 ;; (autoload 'woman "woman"
76 ;; "Decode and browse a UN*X man page." t)
77 ;; (autoload 'woman-find-file "woman"
78 ;; "Find, decode and browse a specific UN*X man-page file." t)
80 ;; Then either (1 -- *RECOMMENDED*): If the `MANPATH' environment
81 ;; variable is set then WoMan will use it; otherwise you may need to
82 ;; reset the Lisp variable `woman-manpath', and you may also want to
83 ;; set the Lisp variable `woman-path'. Please see the online
84 ;; documentation for these variables. Now you can execute the
85 ;; extended command `woman', enter or select a manual entry topic,
86 ;; using completion, and if necessary select a filename, using
87 ;; completion. By default, WoMan suggests the word nearest to the
88 ;; cursor in the current buffer as the topic.
90 ;; Or (2): Execute the extended command `woman-find-file' and enter a
91 ;; filename, using completion. This mode of execution may be useful
92 ;; for temporary files outside the standard UN*X manual directory
93 ;; structure.
95 ;; Or (3): Put the next two sexpr's in your .emacs:
96 ;; (autoload 'woman-dired-find-file "woman"
97 ;; "In dired, run the WoMan man-page browser on this file." t)
98 ;; (add-hook 'dired-mode-hook
99 ;; (lambda ()
100 ;; (define-key dired-mode-map "W" 'woman-dired-find-file)))
101 ;; and open the directory containing the man page file using dired,
102 ;; put the cursor on the file, and press `W'.
104 ;; In each case, the result should (!) be a buffer in Man mode showing
105 ;; a formatted manual entry. When called from WoMan, Man mode should
106 ;; work as advertised, but modified where necessary in the context of
107 ;; WoMan. (However, `Man' will still invoke the standard Emacs
108 ;; manual-browsing facility rather than `WoMan' -- this is
109 ;; intentional!)
111 ;; (By default, WoMan will automatically define the dired keys "W" and
112 ;; "w" when it loads, but only if they are not already defined. This
113 ;; behaviour is controlled by the user option `woman-dired-keys'.
114 ;; Note that the `dired-x' (dired extra) package binds
115 ;; `dired-copy-filename-as-kill' to the key "w" (as pointed out by Jim
116 ;; Davidson), although "W" appears to be really unused. The `dired-x'
117 ;; package will over-write the WoMan binding to "w", whereas (by
118 ;; default) WoMan will not overwrite the `dired-x' binding.)
120 ;; The following is based on suggestions by Guy Gascoigne-Piggford and
121 ;; Juanma Barranquero. If you really want to square the man-woman
122 ;; circle then you might care to define the following bash function in
123 ;; .bashrc:
125 ;; man() { gnudoit -q '(raise-frame (selected-frame)) (woman' \"$1\" ')' ; }
127 ;; If you use Microsoft COMMAND.COM then you can create a file called
128 ;; man.bat somewhere in your path containing the two lines:
130 ;; @echo off
131 ;; gnudoit -q (raise-frame (selected-frame)) (woman \"%1\")
133 ;; and then (e.g. from a command prompt or the Run... option in the
134 ;; Start menu) just execute
136 ;; man man_page_name
139 ;; Using the word at point as the default topic
140 ;; ============================================
142 ;; The `woman' command uses the word nearest to point in the current
143 ;; buffer as the default topic to look up if it matches the name of a
144 ;; manual page installed on the system. The default topic can also be
145 ;; used without confirmation by setting the user-option
146 ;; `woman-use-topic-at-point' to t; thanks to Benjamin Riefenstahl for
147 ;; suggesting this functionality.
149 ;; The variable `woman-use-topic-at-point' can be rebound locally,
150 ;; which may be useful to provide special private key bindings, e.g.
152 ;; (global-set-key "\C-cw"
153 ;; (lambda ()
154 ;; (interactive)
155 ;; (let ((woman-use-topic-at-point t))
156 ;; (woman)))))
159 ;; Customization, Hooks and Imenu
160 ;; ==============================
162 ;; WoMan supports the GNU Emacs 20+ customization facility, and puts
163 ;; a customization group called `WoMan' in the `Help' group under the
164 ;; top-level `Emacs' group. In order to be able to customize WoMan
165 ;; without first loading it, add the following sexp to your .emacs:
167 ;; (defgroup woman nil
168 ;; "Browse UNIX manual pages `wo (without) man'."
169 ;; :tag "WoMan" :group 'help :load "woman")
172 ;; WoMan currently runs two hooks: `woman-pre-format-hook' immediately
173 ;; before formatting a buffer and `woman-post-format-hook' immediately
174 ;; after formatting a buffer. These hooks can be used for special
175 ;; customizations that require code to be executed, etc., although
176 ;; most customization should be possible by setting WoMan user option
177 ;; variables, e.g. in `.emacs' and should NOT require the use of the
178 ;; hooks. `woman-pre-format-hook' might be appropriate for face
179 ;; customization, whereas `woman-post-format-hook' might be
180 ;; appropriate for installing a dynamic menu using `imenu' (although
181 ;; it is better to use the built-in WoMan imenu support).
183 ;; The WoMan menu provides an option to make a contents menu for the
184 ;; current man page (using imenu). Alternatively, if you set the
185 ;; variable `woman-imenu' to `t' then WoMan will do it automatically
186 ;; for every man page. The menu title is the value of the variable
187 ;; `woman-imenu-title', which is "CONTENTS" by default. By default,
188 ;; the menu shows manual sections and subsections, but you can change
189 ;; this by changing the value of `woman-imenu-generic-expression'.
190 ;; This facility is not yet widely tested and may be fooled by obscure
191 ;; man pages that `break the rules'.
193 ;; WoMan is configured not to replace spaces in an imenu *Completion*
194 ;; buffer. For further documentation of the use of imenu, such as
195 ;; menu sorting, see the source file imenu.el, which is distributed
196 ;; with GNU Emacs.
198 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
200 ;; Howard Melman made (essentially) the following suggestions, which
201 ;; are slightly different from the expression that I currently use.
202 ;; You may prefer one of Howard's suggestions, which I think assume
203 ;; that `case-fold-search' is `t' (which it is by default):
205 ;; (setq woman-imenu-generic-expression
206 ;; '((nil "^\\( \\)?\\([A-Z][A-Z ]+[A-Z]\\)[ \t]*$" 2)))
208 ;; will give support for .SH and .SS, though it won't show the heading
209 ;; name hierarchy. If you just want .SH in the imenu then use:
211 ;; (setq woman-imenu-generic-expression
212 ;; '((nil "^\\([A-Z][A-Z ]+[A-Z]\\)[ \t]*$" 1)))
214 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
217 ;; Vertical spacing and blank lines
218 ;; ================================
220 ;; The number of consecutive blank lines in the formatted buffer
221 ;; should be either 0 or 1. A blank line should leave a space like
222 ;; .sp 1 (p. 14). Current policy is to output vertical space only
223 ;; immediately before text is output.
226 ;; Horizontal and vertical spacing and resolution
227 ;; ==============================================
229 ;; WoMan currently assumes 10 characters per inch horizontally, hence
230 ;; a horizontal resolution of 24 basic units, and 5 lines per inch
231 ;; vertically, hence a vertical resolution of 48 basic units. (nroff
232 ;; uses 240 per inch).
235 ;; The *WoMan-Log* buffer
236 ;; ======================
238 ;; This is modelled on the byte-compiler. It logs all files formatted
239 ;; by WoMan, and if WoMan finds anything that it cannot handle then it
240 ;; writes a warning to this buffer. If the variable `woman-show-log'
241 ;; is non-nil (by default it is `nil') then WoMan automatically
242 ;; displays this buffer. Many WoMan warnings can be completely
243 ;; ignored, because they are reporting the fact that WoMan has ignored
244 ;; requests that it is correct to ignore. In some future version this
245 ;; level of paranoia will be reduced, but not until WoMan is more
246 ;; reliable. At present, all warnings should be treated with some
247 ;; suspicion. Uninterpreted escape sequences are also logged (in some
248 ;; cases).
250 ;; Uninterpreted ?roff requests can optionally be left in the
251 ;; formatted buffer to indicate precisely where they occur by
252 ;; resetting the variable `woman-ignore' to `nil' (by default it is
253 ;; `t').
255 ;; Automatic initiation of woman decoding
257 ;; (Probably not a good idea. If you use it, be careful!)
259 ;; Put something like this in your .emacs. The call to
260 ;; set-visited-file-name is to avoid font-locking triggered by
261 ;; automatic major mode selection.
263 ;; (autoload 'woman-decode-region "woman")
265 ;; (setq format-alist
266 ;; (cons
267 ;; '(man "UN*X man-page source format" "\\.\\(TH\\|ig\\) "
268 ;; woman-decode-region nil nil
269 ;; (lambda (arg)
270 ;; set-visited-file-name
271 ;; (file-name-sans-extension buffer-file-name)))))
272 ;; format-alist))
275 ;; Reporting Bugs
276 ;; ==============
278 ;; If WoMan fails completely, or formats a file incorrectly
279 ;; (i.e. obviously wrongly or significantly differently from man) or
280 ;; inelegantly, then please
282 ;; (a) check that you are running the latest version of woman.el
283 ;; available from my web site (see above),
285 ;; (b) check that the problem is not already described in the file
286 ;; woman.status, also available from my web site.
288 ;; If both of the above are true then please email me the entry from
289 ;; the *WoMan-Log* buffer relating to the problem file, together with
290 ;; a brief description of the problem. Please indicate where you got
291 ;; the source file from, but do not send it to me unless I ask you to!
292 ;; Thanks. (There is at present no automated bug-reporting facility
293 ;; for WoMan.)
295 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
297 ;; NOTE:
299 ;; CASE-DEPENDENCE OF FILENAMES. By default, WoMan ignores case in
300 ;; file pathnames only when it seems appropriate. MS-Windows users
301 ;; who want complete case independence should set the NTEmacs variable
302 ;; `w32-downcase-file-names' to `t' and use all lower case when
303 ;; setting WoMan file paths.
305 ;; (1) INCOMPATIBLE CHANGE! WoMan no longer uses a persistent topic
306 ;; cache by default. (It caused too much confusion!) Explicitly set
307 ;; the variable `woman-cache-filename' to save the cache between Emacs
308 ;; sessions. This is recommended only if the command `woman' is too
309 ;; slow the first time that it is run in an Emacs session, while it
310 ;; builds its cache in main memory, which MAY be VERY slow.
312 ;; (2) The user option `woman-cache-level' controls the amount of
313 ;; information cached (in main memory and, optionally, saved to disc).
315 ;; (3) UPDATING THE CACHE. A prefix argument always causes the
316 ;; `woman' command (only) to rebuild its topic cache, and to re-save
317 ;; it to `woman-cache-filename' if this variable has a non-nil value.
318 ;; This is necessary if the NAMES (not contents) of any of the
319 ;; directories or files in the paths specified by `woman-manpath' or
320 ;; `woman-path' change. If WoMan user options that affect the cache
321 ;; are changed then WoMan will automatically update its cache file on
322 ;; disc (if one is in use) the next time it is run in a new Emacs
323 ;; session.
325 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
328 ;; TO DO
329 ;; =====
331 ;; Reconsider case sensitivity of file names.
332 ;; MUST PROCESS .if, .nr IN ORDER ENCOUNTERED IN FILE! (rcsfile, mf).
333 ;; Allow general delimiter in `\v', cf. `\h'.
334 ;; Improve major-mode documentation.
335 ;; Pre-process conditionals in macro bodies if possible for speed?
336 ;; Emulate more complete preprocessor support for tbl (.TS/.TE)
337 ;; Emulate some preprocessor support for eqn (.EQ/.EN)
338 ;; Re-write filling and adjusting code!
339 ;; Allow word wrap at comma (for long option lists)?
340 ;; Buffer list handling not quite right.
341 ;; Make 10 or 12 pitch (cpi) optional -- 12 => ll = 78
342 ;; Use unpaddable space for tabbing?
343 ;; Tidy up handling of fonts when filling and adjusting
344 ;; -- see text/text properties?
345 ;; Improve speed
346 ;; Add font-lock support (for quoted strings, etc.)?
347 ;; Optionally save large files in enriched format?
348 ;; Add apropos facility by searching NAME (?) entry in man files?
349 ;; Documentation -- optional auto-display of formatted WoMan man page?
350 ;; Implement a bug reporter?
351 ;; Support diversion and traps (to some extent) - for Tcl/tk pages?
352 ;; Add a menu of WoMan buffers?
353 ;; Fix .fc properly?
356 ;; Implementation strategy [this description is now well out of date!]
357 ;; -- three main passes, each to process respectively:
359 ;; 1) non-breaking `.' requests including font macros
360 ;; 2) \ escape sequences, mainly special characters and font changes
361 ;; 3) breaking `.' requests, mainly filling and justification
363 ;; For each pass, a control function finds and pre-processes the
364 ;; escape or request and then calls the appropriate function to
365 ;; perform the required formatting. Based originally on enriched.el
366 ;; and format.el.
368 ;; The background information that made this project possible is
369 ;; freely available courtesy of Bell Labs from
370 ;; http://cm.bell-labs.com/7thEdMan/
373 ;; Acknowledgements
374 ;; ================
376 ;; For Heather, Kathryn and Madelyn, the women in my life
377 ;; (although they will probably never use it)!
379 ;; I also thank the following for helpful suggestions, bug reports,
380 ;; code fragments, general interest, etc.:
381 ;; Jari Aalto <jari.aalto@cs.tpu.fi>
382 ;; Dean Andrews <dean@dra.com>
383 ;; Juanma Barranquero <barranquero@laley-actualidad.es>
384 ;; Karl Berry <kb@cs.umb.edu>
385 ;; Jim Chapman <jchapman@netcomuk.co.uk>
386 ;; Kin Cho <kin@neoscale.com>
387 ;; Frederic Corne <frederic.corne@erli.fr>
388 ;; Peter Craft <craft@alacritech.com>
389 ;; Charles Curley <ccurley@trib.com>
390 ;; Jim Davidson <jdavidso@teknowledge.com>
391 ;; Kevin D'Elia <Kevin.DElia@mci.com>
392 ;; John Fitch <jpff@maths.bath.ac.uk>
393 ;; Hans Frosch <jwfrosch@rish.b17c.ingr.com>
394 ;; Guy Gascoigne-Piggford <ggp@informix.com>
395 ;; Brian Gorka <gorkab@sanchez.com>
396 ;; Nicolai Henriksen <nhe@lyngso-industri.dk>
397 ;; Thomas Herchenroeder <the@software-ag.de>
398 ;; Alexander Hinds <ahinds@thegrid.net>
399 ;; Stefan Hornburg <sth@hacon.de>
400 ;; Theodore Jump <tjump@cais.com>
401 ;; David Kastrup <dak@gnu.org>
402 ;; Paul Kinnucan <paulk@mathworks.com>
403 ;; Jonas Linde <jonas@init.se>
404 ;; Andrew McRae <andrewm@optimation.co.nz>
405 ;; Howard Melman <howard@silverstream.com>
406 ;; Dennis Pixton <dennis@math.binghamton.edu>
407 ;; T. V. Raman <raman@Adobe.COM>
408 ;; Bruce Ravel <bruce.ravel@nist.gov>
409 ;; Benjamin Riefenstahl <benny@crocodial.de>
410 ;; Kevin Ruland <kruland@seistl.com>
411 ;; Tom Schutter <tom@platte.com>
412 ;; Wei-Xue Shi <wxshi@ma.neweb.ne.jp>
413 ;; Fabio Somenzi <fabio@joplin.colorado.edu>
414 ;; Karel Sprenger <ks@ic.uva.nl>
415 ;; Chris Szurgot <szurgot@itribe.net>
416 ;; Paul A. Thompson <pat@po.cwru.edu>
417 ;; Arrigo Triulzi <arrigo@maths.qmw.ac.uk>
418 ;; Geoff Voelker <voelker@cs.washington.edu>
419 ;; Eli Zaretskii <eliz@gnu.org>
422 ;;; Code:
424 (defvar woman-version "0.551 (beta)" "WoMan version information.")
426 (require 'man)
427 (eval-when-compile ; to avoid compiler warnings
428 (require 'dired)
429 (require 'apropos))
431 (defun woman-mapcan (fn x)
432 "Return concatenated list of FN applied to successive `car' elements of X.
433 FN must return a list, cons or nil. Useful for splicing into a list."
434 ;; Based on the Standard Lisp function MAPCAN but with args swapped!
435 ;; More concise implementation than the recursive one. -- dak
436 (apply #'nconc (mapcar fn x)))
438 (defun woman-parse-colon-path (paths)
439 "Explode search path string PATHS into a list of directory names.
440 Allow Cygwin colon-separated search paths on Microsoft platforms.
441 Replace null components by calling `woman-parse-man.conf'.
442 As a special case, if PATHS is nil then replace it by calling
443 `woman-parse-man.conf'."
444 ;; Based on suggestions by Jari Aalto and Eli Zaretskii.
445 ;; parse-colon-path returns nil for a null path component and
446 ;; an empty substring of MANPATH denotes the default list.
447 (if (memq system-type '(windows-nt ms-dos))
448 (cond ((null paths)
449 (mapcar 'woman-Cyg-to-Win (woman-parse-man.conf)))
450 ((string-match ";" paths)
451 ;; Assume DOS-style path-list...
452 (woman-mapcan ; splice list into list
453 (lambda (x)
454 (if x
455 (list x)
456 (mapcar 'woman-Cyg-to-Win (woman-parse-man.conf))))
457 (parse-colon-path paths)))
458 ((string-match "\\`[a-zA-Z]:" paths)
459 ;; Assume single DOS-style path...
460 paths)
462 ;; Assume UNIX/Cygwin-style path-list...
463 (woman-mapcan ; splice list into list
464 (lambda (x)
465 (mapcar 'woman-Cyg-to-Win
466 (if x (list x) (woman-parse-man.conf))))
467 (let ((path-separator ":"))
468 (parse-colon-path paths)))))
469 ;; Assume host-default-style path-list...
470 (woman-mapcan ; splice list into list
471 (lambda (x) (if x (list x) (woman-parse-man.conf)))
472 (parse-colon-path (or paths "")))))
474 (defun woman-Cyg-to-Win (file)
475 "Convert an absolute filename FILE from Cygwin to Windows form."
476 ;; Code taken from w32-symlinks.el
477 (if (eq (aref file 0) ?/)
478 ;; Try to use Cygwin mount table via `cygpath.exe'.
479 (condition-case nil
480 (with-temp-buffer
481 ;; cygpath -m file
482 (call-process "cygpath" nil t nil "-m" file)
483 (buffer-substring 1 (buffer-size)))
484 (error
485 ;; Assume no `cygpath' program available.
486 ;; Hack /cygdrive/x/ or /x/ or (obsolete) //x/ to x:/
487 (when (string-match "\\`\\(/cygdrive\\|/\\)?/./" file)
488 (if (match-string 1) ; /cygdrive/x/ or //x/ -> /x/
489 (setq file (substring file (match-end 1))))
490 (aset file 0 (aref file 1)) ; /x/ -> xx/
491 (aset file 1 ?:)) ; xx/ -> x:/
492 file))
493 file))
496 ;;; User options:
498 ;; NB: Group identifiers must be lowercase!
500 (defgroup woman nil
501 "Browse UNIX manual pages `wo (without) man'."
502 :tag "WoMan"
503 :group 'help)
505 (defcustom woman-show-log nil
506 "*If non-nil then show the *WoMan-Log* buffer if appropriate.
507 I.e. if any warning messages are written to it. Default is nil."
508 :type 'boolean
509 :group 'woman)
511 (defcustom woman-pre-format-hook nil
512 "*Hook run by WoMan immediately before formatting a buffer.
513 Change only via `Customization' or the function `add-hook'."
514 :type 'hook
515 :group 'woman)
517 (defcustom woman-post-format-hook nil
518 "*Hook run by WoMan immediately after formatting a buffer.
519 Change only via `Customization' or the function `add-hook'."
520 :type 'hook
521 :group 'woman)
524 ;; Interface options
526 (defgroup woman-interface nil
527 "Interface options for browsing UNIX manual pages `wo (without) man'."
528 :tag "WoMan Interface"
529 :group 'woman)
531 (defcustom woman-man.conf-path
532 (let ((path '("/usr/lib" "/etc")))
533 (if (eq system-type 'windows-nt)
534 (mapcar 'woman-Cyg-to-Win path)
535 path))
536 "*List of dirs to search and/or files to try for man config file.
537 A trailing separator (`/' for UNIX etc.) on directories is optional,
538 and the filename is used if a directory specified is the first to
539 contain the strings \"man\" and \".conf\" (in that order).
540 If MANPATH is not set but a config file is found then it is parsed
541 instead to provide a default value for `woman-manpath'."
542 :type '(repeat string)
543 :group 'woman-interface)
545 (defun woman-parse-man.conf ()
546 "Parse if possible configuration file for man command.
547 Used only if MANPATH is not set or contains null components.
548 Look in `woman-man.conf-path' and return a value for `woman-manpath'.
549 Concatenate data from all lines in the config file of the form
550 MANPATH /usr/man
552 MANDATORY_MANPATH /usr/man
554 OPTIONAL_MANPATH /usr/man"
555 ;; Functionality suggested by Charles Curley.
556 (let ((path woman-man.conf-path)
557 file manpath)
558 (while (and
559 path
560 (not (and
561 (file-readable-p (setq file (car path)))
562 ;; If not a file then find the file:
563 (or (not (file-directory-p file))
564 (and
565 (setq file
566 (directory-files file t "man.*\\.conf" t))
567 (file-readable-p (setq file (car file)))))
568 ;; Parse the file -- if no MANPATH data ignore it:
569 (with-temp-buffer
570 (insert-file-contents file)
571 (while (re-search-forward
572 ;; `\(?: ... \)' is a "shy group"
574 ^[ \t]*\\(?:MANDATORY_\\|OPTIONAL_\\)?MANPATH[ \t]+\\(\\S-+\\)" nil t)
575 (setq manpath (cons (match-string 1) manpath)))
576 manpath))
578 (setq path (cdr path)))
579 (nreverse manpath)))
581 (defcustom woman-manpath
582 (or (woman-parse-colon-path (getenv "MANPATH"))
583 '("/usr/man" "/usr/share/man" "/usr/local/man"))
584 "*List of DIRECTORY TREES to search for UN*X manual files.
585 Each element should be the name of a directory that contains
586 subdirectories of the form `man?', or more precisely subdirectories
587 selected by the value of `woman-manpath-man-regexp'. Non-directory
588 and unreadable files are ignored.
590 If not set then the environment variable MANPATH is used. If no such
591 environment variable is found, the default list is determined by
592 consulting the man configuration file if found, which is determined by
593 the user option `woman-man.conf-path'. An empty substring of MANPATH
594 denotes the default list.
596 Any environment variables (names must have the UN*X-style form $NAME,
597 e.g. $HOME, $EMACSDATA, $emacs_dir) are evaluated first but each
598 element must evaluate to a SINGLE directory name. Trailing `/'s are
599 ignored. (Specific directories in `woman-path' are also searched.)
601 Microsoft platforms:
602 I recommend including drive letters explicitly, e.g.
604 (\"C:/Cygwin/usr/man/\" \"C:/Cygwin/usr/local/man\").
606 The MANPATH environment variable may be set using DOS semi-colon-
607 separated or UN*X/Cygwin colon-separated syntax (but not mixed)."
608 :type '(repeat string)
609 :group 'woman-interface)
611 (defcustom woman-manpath-man-regexp "[Mm][Aa][Nn]"
612 "Regexp to match man directories UNDER `woman-manpath' directories.
613 These normally have names of the form `man?'. Its default value is
614 \"[Mm][Aa][Nn]\", which is case-insensitive mainly for the benefit of
615 Microsoft platforms. Its purpose is to avoid `cat?', `.', `..', etc."
616 ;; Based on a suggestion by Wei-Xue Shi.
617 :type 'string
618 :group 'woman-interface)
620 (defcustom woman-path
621 (if (eq system-type 'ms-dos) '("$DJDIR/info" "$DJDIR/man/cat[1-9onlp]"))
622 "*List of SPECIFIC DIRECTORIES to search for UN*X manual files.
623 For example
625 (\"/emacs/etc\").
627 These directories are searched in addition to the directory trees
628 specified in `woman-manpath'. Each element should be a directory
629 string or nil, which represents the current directory when the path is
630 expanded and cached. However, the last component (only) of each
631 directory string is treated as a regexp \(Emacs, not shell) and the
632 string is expanded into a list of matching directories. Non-directory
633 and unreadable files are ignored. The default value is nil.
635 Any environment variables (which must have the UN*X-style form $NAME,
636 e.g. $HOME, $EMACSDATA, $emacs_dir) are evaluated first but each
637 element must evaluate to a SINGLE directory name (regexp, see above).
638 For example
640 (\"$EMACSDATA\") [or equivalently (\"$emacs_dir/etc\")].
642 Trailing `/'s are discarded. (The directory trees in `woman-manpath'
643 are also searched.) On Microsoft platforms I recommend including
644 drive letters explicitly."
645 :type '(repeat (choice string (const nil)))
646 :group 'woman-interface)
648 (defcustom woman-cache-level 2
649 "*The level of topic caching.
650 1 - cache only the topic and directory lists
651 (the only level before version 0.34 - only for compatibility);
652 2 - cache also the directories for each topic
653 (faster, without using much more memory);
654 3 - cache also the actual filenames for each topic
655 (fastest, but uses twice as much memory).
656 The default value is currently 2, a good general compromise.
657 If the `woman' command is slow to find files then try 3, which may be
658 particularly beneficial with large remote-mounted man directories.
659 Run the `woman' command with a prefix argument or delete the cache
660 file `woman-cache-filename' for a change to take effect.
661 \(Values < 1 behave like 1; values > 3 behave like 3.)"
662 :type '(choice (const :tag "Minimal" 1)
663 (const :tag "Default" 2)
664 (const :tag "Maximal" 3))
665 :group 'woman-interface)
667 (defcustom woman-cache-filename nil
668 "*The full pathname of the WoMan directory and topic cache file.
669 It is used to save and restore the cache between sessions. This is
670 especially useful with remote-mounted man page files! The default
671 value of nil suppresses this action. The `standard' non-nil
672 filename is \"~/.wmncach.el\". Remember that a prefix argument forces
673 the `woman' command to update and re-write the cache."
674 :type '(choice (const :tag "None" nil)
675 (const :tag "~/.wmncach.el" "~/.wmncach.el")
676 file)
677 :group 'woman-interface)
679 (defcustom woman-dired-keys t
680 "*List of `dired' mode keys to define to run WoMan on current file.
681 E.g. '(\"w\" \"W\"), or any non-null atom to automatically define
682 \"w\" and \"W\" if they are unbound, or nil to do nothing.
683 Default is t."
684 :type '(choice (const :tag "None" nil)
685 (repeat string)
686 (other :tag "Auto" t))
687 :group 'woman-interface)
689 (defcustom woman-imenu-generic-expression
690 '((nil "\n\\([A-Z].*\\)" 1) ; SECTION, but not TITLE
691 ("*Subsections*" "^ \\([A-Z].*\\)" 1))
692 "*Imenu support for Sections and Subsections.
693 An alist with elements of the form (MENU-TITLE REGEXP INDEX) --
694 see the documentation for `imenu-generic-expression'."
695 :type 'sexp
696 :group 'woman-interface)
698 (defcustom woman-imenu nil
699 "*If non-nil then WoMan adds a Contents menu to the menubar.
700 It does this by calling `imenu-add-to-menubar'. Default is nil."
701 :type 'boolean
702 :group 'woman-interface)
704 (defcustom woman-imenu-title "CONTENTS"
705 "*The title to use if WoMan adds a Contents menu to the menubar.
706 Default is \"CONTENTS\"."
707 :type 'string
708 :group 'woman-interface)
710 (defcustom woman-use-topic-at-point-default nil
711 ;; `woman-use-topic-at-point' may be let-bound when woman is loaded,
712 ;; in which case its global value does not get defined.
713 ;; `woman-file-name' sets it to this value if it is unbound.
714 "*Default value for `woman-use-topic-at-point'."
715 :type '(choice (const :tag "Yes" t)
716 (const :tag "No" nil))
717 :group 'woman-interface)
719 (defcustom woman-use-topic-at-point woman-use-topic-at-point-default
720 "*Control use of the word at point as the default topic.
721 If non-nil the `woman' command uses the word at point automatically,
722 without interactive confirmation, if it exists as a topic."
723 :type '(choice (const :tag "Yes" t)
724 (const :tag "No" nil))
725 :group 'woman-interface)
727 (defvar woman-file-regexp nil
728 "Regexp used to select (possibly compressed) man source files, e.g.
729 \"\\.\\([0-9lmnt]\\w*\\)\\(\\.\\(g?z\\|bz2\\)\\)?\\'\".
730 Built automatically from the customizable user options
731 `woman-uncompressed-file-regexp' and `woman-file-compression-regexp'.")
733 (defvar woman-uncompressed-file-regexp) ; for the compiler
734 (defvar woman-file-compression-regexp) ; for the compiler
736 (defun set-woman-file-regexp (symbol value)
737 "Bind SYMBOL to VALUE and set `woman-file-regexp' as per user customizations.
738 Used as :set cookie by Customize when customizing the user options
739 `woman-uncompressed-file-regexp' and `woman-file-compression-regexp'."
740 (set-default symbol value)
741 (and (boundp 'woman-uncompressed-file-regexp)
742 (boundp 'woman-file-compression-regexp)
743 (setq woman-file-regexp
744 (concat woman-uncompressed-file-regexp
745 "\\("
746 (substring woman-file-compression-regexp 0 -2)
747 "\\)?\\'"))))
749 (defcustom woman-uncompressed-file-regexp
750 "\\.\\([0-9lmnt]\\w*\\)" ; disallow no extension
751 "*Do not change this unless you are sure you know what you are doing!
752 Regexp used to select man source files (ignoring any compression extension).
754 The SysV standard man pages use two character suffixes, and this is
755 becoming more common in the GNU world. For example, the man pages
756 in the ncurses package include `toe.1m', `form.3x', etc.
758 Note: an optional compression regexp will be appended, so this regexp
759 MUST NOT end with any kind of string terminator such as $ or \\'."
760 :type 'regexp
761 :set 'set-woman-file-regexp
762 :group 'woman-interface)
764 (defcustom woman-file-compression-regexp
765 "\\.\\(g?z\\|bz2\\)\\'"
766 "*Do not change this unless you are sure you know what you are doing!
767 Regexp used to match compressed man file extensions for which
768 decompressors are available and handled by auto-compression mode,
769 e.g. \"\\\\.\\\\(g?z\\\\|bz2\\\\)\\\\'\" for `gzip' or `bzip2'.
770 Should begin with \\. and end with \\' and MUST NOT be optional."
771 ;; Should be compatible with car of
772 ;; `jka-compr-file-name-handler-entry', but that is unduly
773 ;; complicated, includes an inappropriate extension (.tgz) and is
774 ;; not loaded by default!
775 :type 'regexp
776 :set 'set-woman-file-regexp
777 :group 'woman-interface)
779 (defcustom woman-use-own-frame ; window-system
780 (or (and (fboundp 'display-graphic-p) (display-graphic-p)) ; Emacs 21
781 (memq window-system '(x w32))) ; Emacs 20
782 "*If non-nil then use a dedicated frame for displaying WoMan windows.
783 Only useful when run on a graphic display such as X or MS-Windows."
784 :type 'boolean
785 :group 'woman-interface)
788 ;; Formatting options
790 (defgroup woman-formatting nil
791 "Formatting options for browsing UNIX manual pages `wo (without) man'."
792 :tag "WoMan Formatting"
793 :group 'woman)
795 (defcustom woman-fill-column 65
796 "*Right margin for formatted text -- default is 65."
797 :type 'integer
798 :group 'woman-formatting)
800 (defcustom woman-fill-frame nil
801 ;; Based loosely on a suggestion by Theodore Jump:
802 "*If non-nil then most of the window width is used."
803 :type 'boolean
804 :group 'woman-formatting)
806 (defcustom woman-default-indent 5
807 "*Default prevailing indent set by -man macros -- default is 5.
808 Set this variable to 7 to emulate GNU man formatting."
809 :type 'integer
810 :group 'woman-formatting)
812 (defcustom woman-bold-headings t
813 "*If non-nil then embolden section and subsection headings. Default is t.
814 Heading emboldening is NOT standard `man' behavior."
815 :type 'boolean
816 :group 'woman-formatting)
818 (defcustom woman-ignore t
819 "*If non-nil then unrecognized requests etc. are ignored. Default is t.
820 This gives the standard ?roff behavior. If nil then they are left in
821 the buffer, which may aid debugging."
822 :type 'boolean
823 :group 'woman-formatting)
825 (defcustom woman-preserve-ascii t
826 "*If non-nil, preserve ASCII characters in the WoMan buffer.
827 Otherwise, to save time, some backslashes and spaces may be
828 represented differently (as the values of the variables
829 `woman-escaped-escape-char' and `woman-unpadded-space-char'
830 respectively) so that the buffer content is strictly wrong even though
831 it should display correctly. This should be irrelevant unless the
832 buffer text is searched, copied or saved to a file."
833 ;; This option should probably be removed!
834 :type 'boolean
835 :group 'woman-formatting)
837 (defcustom woman-emulation 'nroff
838 "*WoMan emulation, currently either nroff or troff. Default is nroff.
839 Troff emulation is experimental and largely untested.
840 \(Add groff later?)"
841 :type '(choice (const nroff) (const troff))
842 :group 'woman-formatting)
845 ;; Faces:
847 (defgroup woman-faces nil
848 "Face options for browsing UNIX manual pages `wo (without) man'."
849 :tag "WoMan Faces"
850 :group 'woman
851 :group 'faces)
853 (defcustom woman-fontify
854 (or (and (fboundp 'display-color-p) (display-color-p))
855 (and (fboundp 'display-graphic-p) (display-graphic-p))
856 (x-display-color-p))
857 "*If non-nil then WoMan assumes that face support is available.
858 It defaults to a non-nil value if the display supports either colors
859 or different fonts."
860 :type 'boolean
861 :group 'woman-faces)
863 ;; This is overkill! Troff uses just italic; Nroff uses just underline.
864 ;; You should probably select either italic or underline as you prefer, but
865 ;; not both, although italic and underline work together perfectly well!
866 (defface woman-italic
867 `((((min-colors 88) (background light))
868 (:slant italic :underline t :foreground "red1"))
869 (((background light)) (:slant italic :underline t :foreground "red"))
870 (((background dark)) (:slant italic :underline t)))
871 "Face for italic font in man pages."
872 :group 'woman-faces)
873 ;; backward-compatibility alias
874 (put 'woman-italic-face 'face-alias 'woman-italic)
876 (defface woman-bold
877 '((((min-colors 88) (background light)) (:weight bold :foreground "blue1"))
878 (((background light)) (:weight bold :foreground "blue"))
879 (((background dark)) (:weight bold :foreground "green2")))
880 "Face for bold font in man pages."
881 :group 'woman-faces)
882 ;; backward-compatibility alias
883 (put 'woman-bold-face 'face-alias 'woman-bold)
885 ;; Brown is a good compromise: it is distinguishable from the default
886 ;; but not enough so to make font errors look terrible. (Files that use
887 ;; non-standard fonts seem to do so badly or in idiosyncratic ways!)
888 (defface woman-unknown
889 '((((background light)) (:foreground "brown"))
890 (((min-colors 88) (background dark)) (:foreground "cyan1"))
891 (((background dark)) (:foreground "cyan")))
892 "Face for all unknown fonts in man pages."
893 :group 'woman-faces)
894 ;; backward-compatibility alias
895 (put 'woman-unknown-face 'face-alias 'woman-unknown)
897 (defface woman-addition
898 '((t (:foreground "orange")))
899 "Face for all WoMan additions to man pages."
900 :group 'woman-faces)
901 ;; backward-compatibility alias
902 (put 'woman-addition-face 'face-alias 'woman-addition)
904 (defun woman-default-faces ()
905 "Set foreground colors of italic and bold faces to their default values."
906 (interactive)
907 (face-spec-set 'woman-italic (face-user-default-spec 'woman-italic))
908 (face-spec-set 'woman-bold (face-user-default-spec 'woman-bold)))
910 (defun woman-monochrome-faces ()
911 "Set foreground colors of italic and bold faces to that of the default face.
912 This is usually either black or white."
913 (interactive)
914 (set-face-foreground 'woman-italic 'unspecified)
915 (set-face-foreground 'woman-bold 'unspecified))
917 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
918 ;; Experimental font support, initially only for MS-Windows.
919 (defconst woman-font-support
920 (eq window-system 'w32) ; Support X later!
921 "If non-nil then non-ASCII characters and symbol font supported.")
923 (defun woman-select-symbol-fonts (fonts)
924 "Select symbol fonts from a list FONTS of font name strings."
925 (let (symbol-fonts)
926 ;; With NTEmacs 20.5, the PATTERN option to `x-list-fonts' does
927 ;; not seem to work and fonts may be repeated, so ...
928 (while fonts
929 (and (string-match "-Symbol-" (car fonts))
930 (not (member (car fonts) symbol-fonts))
931 (setq symbol-fonts (cons (car fonts) symbol-fonts)))
932 (setq fonts (cdr fonts)))
933 symbol-fonts))
935 (when woman-font-support
936 (make-face 'woman-symbol)
938 ;; Set the symbol font only if `woman-use-symbol-font' is true, to
939 ;; avoid unnecessarily upsetting the line spacing in NTEmacs 20.5!
941 (defcustom woman-use-extended-font t
942 "*If non-nil then may use non-ASCII characters from the default font."
943 :type 'boolean
944 :group 'woman-faces)
946 (defcustom woman-use-symbol-font nil
947 "*If non-nil then may use the symbol font.
948 It is off by default, mainly because it may change the line spacing
949 \(in NTEmacs 20.5)."
950 :type 'boolean
951 :group 'woman-faces)
953 (defconst woman-symbol-font-list
954 (or (woman-select-symbol-fonts (x-list-fonts "*" 'default))
955 (woman-select-symbol-fonts (x-list-fonts "*")))
956 "Symbol font(s), preferably same size as default when WoMan was loaded.")
958 (defcustom woman-symbol-font (car woman-symbol-font-list)
959 "*A string describing the symbol font to use for special characters.
960 It should be compatible with, and the same size as, the default text font.
961 Under MS-Windows, the default is
962 \"-*-Symbol-normal-r-*-*-*-*-96-96-p-*-ms-symbol\"."
963 :type `(choice
964 ,@(mapcar (lambda (x) (list 'const x))
965 woman-symbol-font-list)
966 string)
967 :group 'woman-faces)
971 ;; For non windows-nt ...
972 (defvar woman-use-extended-font nil)
973 (defvar woman-use-symbol-font nil)
974 (defvar woman-symbol-font nil)
975 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
978 ;;; Internal variables:
980 (defconst woman-justify-list
981 '(left right center full)
982 "Justify styles for `fill-region-as-paragraph'.")
983 (defconst woman-adjust-left 0 ; == adjust off, noadjust
984 "Adjustment indicator `l' -- adjust left margin only.")
985 (defconst woman-adjust-right 1
986 "Adjustment indicator `r' -- adjust right margin only.")
987 (defconst woman-adjust-center 2
988 "Adjustment indicator `c' -- center.")
989 (defconst woman-adjust-both 3 ; default -- adj,both
990 "Adjustment indicator `b' or `n' -- adjust both margins.")
992 (defvar woman-adjust woman-adjust-both
993 "Current adjustment number-register value.")
994 (defvar woman-adjust-previous woman-adjust
995 "Previous adjustment number-register value.")
996 (defvar woman-justify
997 (nth woman-adjust woman-justify-list) ; use vector?
998 "Current justification style for `fill-region-as-paragraph'.")
999 (defvar woman-justify-previous woman-justify
1000 "Previous justification style for `fill-region-as-paragraph'.")
1002 (defvar woman-left-margin woman-default-indent
1003 "Current left margin.")
1004 (defvar woman-prevailing-indent woman-default-indent
1005 "Current prevailing indent.")
1006 (defvar woman-interparagraph-distance 1
1007 "Interparagraph distance in lines.
1008 Set by .PD; used by .SH, .SS, .TP, .LP, .PP, .P, .IP, .HP.")
1009 (defvar woman-leave-blank-lines nil
1010 "Blank lines to leave as vertical space.")
1011 (defconst woman-tab-width 5
1012 "Default tab width set by -man macros.")
1013 (defvar woman-nofill nil
1014 "Current fill mode: nil for filling.")
1015 (defvar woman-RS-left-margin nil
1016 "Left margin stack for nested use of `.RS/.RE'.")
1017 (defvar woman-RS-prevailing-indent nil
1018 "Prevailing indent stack for nested use of `.RS/.RE'.")
1019 (defvar woman-nospace nil
1020 "Current no-space mode: nil for normal spacing.
1021 Set by `.ns' request; reset by any output or `.rs' request")
1023 (defsubst woman-reset-nospace ()
1024 "Set `woman-nospace' to nil."
1025 (setq woman-nospace nil))
1027 (defconst woman-request-regexp "^[.'][ \t]*\\(\\S +\\) *"
1028 ;; Was "^\\.[ \t]*\\([a-z0-9]+\\) *" but cvs.1 uses a macro named
1029 ;; "`" and CGI.man uses a macro named "''"!
1030 ;; CGI.man uses ' as control character in places -- it *should*
1031 ;; suppress breaks!
1032 ;; Could end with "\\( +\\|$\\)" instead of " *"
1033 "Regexp to match a ?roff request plus trailing white space.")
1035 (defvar woman-imenu-done nil
1036 "Buffer-local: set to true if function `woman-imenu' has been called.")
1037 (make-variable-buffer-local 'woman-imenu-done)
1039 ;; From imenu.el -- needed when reformatting a file in its old buffer.
1040 ;; The latest buffer index used to update the menu bar menu.
1041 (eval-when-compile
1042 (require 'imenu))
1043 (make-variable-buffer-local 'imenu--last-menubar-index-alist)
1045 (defvar woman-buffer-alist nil
1046 "An alist representing WoMan buffers that are already decoded.
1047 Each element is of the form (FILE-NAME . BUFFER-NAME).")
1049 (defvar woman-buffer-number 0
1050 "Ordinal number of current buffer entry in `woman-buffer-alist'.
1051 The ordinal numbers start from 0.")
1053 (defvar woman-if-conditions-true '(?n ?e ?o)
1054 "List of one-character built-in condition names that are true.
1055 Should include ?e, ?o (page even/odd) and either ?n (nroff) or ?t (troff).
1056 Default is '(?n ?e ?o). Set via `woman-emulation'.")
1059 ;;; Specialized utility functions:
1061 ;;; Fast deletion without saving on the kill ring (cf. simple.el):
1063 (defun woman-delete-line (&optional arg)
1064 "Delete rest of current line; if all blank then delete thru newline.
1065 With a numeric argument ARG, delete that many lines from point.
1066 Negative arguments delete lines backward."
1067 ;; This is a non-interactive version of kill-line in simple.el that
1068 ;; deletes instead of killing and assumes kill-whole-line is nil,
1069 ;; which is essential!
1070 (delete-region (point)
1071 (progn
1072 (if arg
1073 (forward-line arg)
1074 (if (eobp)
1075 (signal 'end-of-buffer nil))
1076 (if (looking-at "[ \t]*$")
1077 (forward-line 1)
1078 (end-of-line)))
1079 (point))))
1081 (defsubst woman-delete-whole-line ()
1082 "Delete current line from beginning including eol."
1083 (beginning-of-line)
1084 (woman-delete-line 1))
1086 (defsubst woman-delete-following-space ()
1087 "Delete all spaces and tabs FOLLOWING point (cf. `delete-horizontal-space')."
1088 ;; cf. delete-horizontal-space in simple.el:
1089 (delete-region (point) (progn (skip-chars-forward " \t") (point))))
1091 (defsubst woman-delete-match (subexp)
1092 "Delete subexpression SUBEXP of buffer text matched by last search."
1093 (delete-region (match-beginning subexp) (match-end subexp)))
1095 ;; delete-char does not kill by default
1096 ;; delete-backward-char does not kill by default
1097 ;; delete-horizontal-space does not kill
1098 ;; delete-blank-lines does not kill
1101 ;;; File handling:
1103 (defvar woman-expanded-directory-path nil
1104 "Expanded directory list cache. Resetting to nil forces update.")
1106 (defvar woman-topic-all-completions nil
1107 "Expanded topic alist cache. Resetting to nil forces update.")
1109 ;;;###autoload
1110 (defun woman (&optional topic re-cache)
1111 "Browse UN*X man page for TOPIC (Without using external Man program).
1112 The major browsing mode used is essentially the standard Man mode.
1113 Choose the filename for the man page using completion, based on the
1114 topic selected from the directories specified in `woman-manpath' and
1115 `woman-path'. The directory expansions and topics are cached for
1116 speed, but a non-nil interactive argument forces the caches to be
1117 updated (e.g. to re-interpret the current directory).
1119 Used non-interactively, arguments are optional: if given then TOPIC
1120 should be a topic string and non-nil RE-CACHE forces re-caching."
1121 (interactive (list nil current-prefix-arg))
1122 ;; The following test is for non-interactive calls via gnudoit etc.
1123 (if (or (not (stringp topic)) (string-match "\\S " topic))
1124 (let ((file-name (woman-file-name topic re-cache)))
1125 (if file-name
1126 (woman-find-file file-name)
1127 (message
1128 "WoMan Error: No matching manual files found in search path")
1129 (ding))
1131 (message "WoMan Error: No topic specified in non-interactive call")
1132 (ding))
1135 ;; Allow WoMan to be called via the standard Help menu:
1136 (define-key-after menu-bar-manuals-menu [woman]
1137 '(menu-item "Read Man Page (WoMan)..." woman
1138 :help "Man-page documentation Without Man") t)
1140 (defvar woman-cached-data nil
1141 "A list of cached data used to determine cache validity.
1142 Set from the cache by `woman-read-directory-cache'.")
1144 (defun woman-cached-data ()
1145 "Generate a list of data used to determine cache validity.
1146 Called both to generate and to check the cache!"
1147 ;; Must use substituted paths because values of env vars may change!
1148 (list woman-cache-level
1149 (mapcar 'substitute-in-file-name woman-manpath)
1150 (mapcar 'substitute-in-file-name woman-path)))
1152 (defun woman-read-directory-cache ()
1153 "Load the directory and topic cache.
1154 It is loaded from the file named by the variable `woman-cache-filename'.
1155 Return t if the file exists, nil otherwise."
1156 (and
1157 woman-cache-filename
1158 (load woman-cache-filename t nil t) ; file exists
1159 (equal woman-cached-data (woman-cached-data)))) ; cache valid
1161 (defun woman-write-directory-cache ()
1162 "Save the directory and topic cache.
1163 It is saved to the file named by the variable `woman-cache-filename'."
1164 (if woman-cache-filename
1165 (save-excursion ; to restore current buffer
1166 ;; Make a temporary buffer; name starting with space "hides" it.
1167 (let ((standard-output
1168 (set-buffer (generate-new-buffer "WoMan tmp buffer")))
1169 (backup-inhibited t))
1170 ;; (switch-to-buffer standard-output t) ; only for debugging
1171 (buffer-disable-undo standard-output)
1172 (princ
1173 ";;; WoMan directory and topic cache -- generated automatically\n")
1174 (print
1175 ;; For data validity check:
1176 `(setq woman-cached-data ',(woman-cached-data)))
1177 (print
1178 `(setq woman-expanded-directory-path
1179 ',woman-expanded-directory-path))
1180 (print
1181 `(setq woman-topic-all-completions
1182 ',woman-topic-all-completions))
1183 (write-file woman-cache-filename) ; write CURRENT buffer
1184 (kill-buffer standard-output)
1185 ))))
1187 (defvar woman-topic-history nil "Topic read history.")
1188 (defvar woman-file-history nil "File-name read history.")
1190 (defun woman-file-name (topic &optional re-cache)
1191 "Get the name of the UN*X man-page file describing a chosen TOPIC.
1192 When `woman' is called interactively, the word at point may be
1193 automatically used as the topic, if the value of the user option
1194 `woman-use-topic-at-point' is non-nil. Return nil if no file can
1195 be found. Optional argument RE-CACHE, if non-nil, forces the
1196 cache to be re-read."
1197 ;; Handle the caching of the directory and topic lists:
1198 (if (and (not re-cache)
1200 (and woman-expanded-directory-path woman-topic-all-completions)
1201 (woman-read-directory-cache)))
1203 (message "Building list of manual directory expansions...")
1204 (setq woman-expanded-directory-path
1205 (woman-expand-directory-path woman-manpath woman-path))
1206 (message "Building completion list of all manual topics...")
1207 (setq woman-topic-all-completions
1208 (woman-topic-all-completions woman-expanded-directory-path))
1209 (woman-write-directory-cache))
1210 ;; There is a problem in that I want to offer case-insensitive
1211 ;; completions, but to return only a case-sensitive match. This
1212 ;; does not seem to work properly by default, so I re-do the
1213 ;; completion if necessary.
1214 (let (files
1215 (default (current-word)))
1216 (or (stringp topic)
1217 (and (if (boundp 'woman-use-topic-at-point)
1218 woman-use-topic-at-point
1219 ;; Was let-bound when file loaded, so ...
1220 (setq woman-use-topic-at-point woman-use-topic-at-point-default))
1221 (setq topic (or (current-word t) "")) ; only within or adjacent to word
1222 (test-completion topic woman-topic-all-completions))
1223 (setq topic
1224 (let* ((word-at-point (current-word))
1225 (default
1226 (when (and word-at-point
1227 (test-completion
1228 word-at-point woman-topic-all-completions))
1229 word-at-point)))
1230 (completing-read
1231 (if default
1232 (format "Manual entry [default: %s]: " default)
1233 "Manual entry: ")
1234 woman-topic-all-completions nil 1
1236 'woman-topic-history
1237 default))))
1238 ;; Note that completing-read always returns a string.
1239 (if (= (length topic) 0)
1240 nil ; no topic, so no file!
1241 (cond
1242 ((setq files (woman-file-name-all-completions topic)))
1243 ;; Complete topic more carefully, i.e. use the completion
1244 ;; rather than the string entered by the user:
1245 ((setq files (all-completions topic woman-topic-all-completions))
1246 (while (/= (length topic) (length (car files)))
1247 (setq files (cdr files)))
1248 (setq files (woman-file-name-all-completions (car files)))))
1249 (cond
1250 ((null files) nil) ; no file found for topic.
1251 ((null (cdr files)) (car (car files))) ; only 1 file for topic.
1253 ;; Multiple files for topic, so must select 1.
1254 ;; Unread the command event (TAB = ?\t = 9) that runs the command
1255 ;; `minibuffer-complete' in order to automatically complete the
1256 ;; minibuffer contents as far as possible.
1257 (setq unread-command-events '(9)) ; and delete any type-ahead!
1258 (completing-read "Manual file: " files nil 1
1259 (try-completion "" files) 'woman-file-history))))))
1261 (defun woman-select (predicate list)
1262 "Select unique elements for which PREDICATE is true in LIST.
1263 \(Note that this function changes the value of LIST.)"
1264 ;; Intended to be fast by avoiding recursion and list copying.
1265 (while (and list
1267 (member (car list) (cdr list))
1268 (not (funcall predicate (car list)))))
1269 (setq list (cdr list)))
1270 (if list
1271 (let ((newlist list) cdr_list)
1272 (while (setq cdr_list (cdr list))
1273 (if (and
1274 (not (member (car cdr_list) (cdr cdr_list)))
1275 (funcall predicate (car cdr_list)))
1276 (setq list cdr_list)
1277 (setcdr list (cdr cdr_list)))
1279 newlist)))
1281 (defun woman-file-readable-p (dir)
1282 "Return t if DIR is readable, otherwise log a warning."
1283 (or (file-readable-p dir)
1284 (WoMan-warn "Ignoring unreadable `manpath' directory tree `%s'!" dir)))
1286 (defun woman-directory-files (head dir)
1287 "Return a sorted list of files in directory HEAD matching regexp in DIR.
1288 Value is a sorted list of the absolute pathnames of all the files in
1289 directory HEAD, or the current directory if HEAD is nil, that match the
1290 regexp that is the final component of DIR. Log a warning if list is empty."
1291 (or (directory-files
1292 (or head (directory-file-name default-directory)) ; was "."
1294 (file-name-nondirectory dir))
1295 (WoMan-warn "No directories match `woman-path' entry `%s'!" dir)))
1297 (defun woman-file-accessible-directory-p (dir)
1298 "Return t if DIR is accessible, otherwise log a warning."
1299 (or (file-accessible-directory-p dir)
1300 (WoMan-warn "Ignoring inaccessible `man-page' directory `%s'!" dir)))
1302 (defun woman-expand-directory-path (woman-manpath woman-path)
1303 "Expand the manual directories in WOMAN-MANPATH and WOMAN-PATH.
1304 WOMAN-MANPATH should be a list of general manual directories, while
1305 WOMAN-PATH should be a list of specific manual directory regexps.
1306 Ignore any paths that are unreadable or not directories."
1307 ;; Allow each path to be a single string or a list of strings:
1308 (if (not (listp woman-manpath)) (setq woman-manpath (list woman-manpath)))
1309 (if (not (listp woman-path)) (setq woman-path (list woman-path)))
1310 (let (dir head dirs)
1311 (while woman-manpath
1312 (setq dir (car woman-manpath)
1313 woman-manpath (cdr woman-manpath))
1314 (if (and dir (woman-file-readable-p dir))
1315 ;; NB: `parse-colon-path' creates null elements for
1316 ;; redundant (semi-)colons and trailing `/'s!
1317 ;; If does not actually matter here if dir ends with `/'.
1318 ;; Need regexp "man" here to avoid "cat?", `.', `..', etc.
1319 (setq dir (woman-canonicalize-dir dir)
1320 dirs (nconc dirs (directory-files
1321 dir t woman-manpath-man-regexp)))))
1322 (while woman-path
1323 (setq dir (car woman-path)
1324 woman-path (cdr woman-path))
1325 (if (or (null dir)
1326 (null (setq dir (woman-canonicalize-dir dir)
1327 head (file-name-directory dir)))
1328 (woman-file-readable-p head))
1329 (setq dirs
1330 (if dir
1331 (nconc dirs (woman-directory-files head dir))
1332 (cons (directory-file-name default-directory) dirs))
1333 ;; was "." -- at head of list for later filtering
1335 (woman-select 'woman-file-accessible-directory-p dirs)))
1337 (defun woman-canonicalize-dir (dir)
1338 "Canonicalize the directory name DIR.
1339 Any UN*X-style environment variables are evaluated first."
1340 (setq dir (expand-file-name (substitute-in-file-name dir)))
1341 ;; A path that ends with / matches all directories in it,
1342 ;; including `.' and `..', so remove any trailing / !!!
1343 (if (string= (substring dir -1) "/")
1344 (setq dir (substring dir 0 -1)))
1345 (if (memq system-type '(windows-nt ms-dos cygwin)) ; what else?
1346 ;; Match capitalization used by `file-name-directory':
1347 (setq dir (concat (file-name-directory dir)
1348 (file-name-nondirectory dir))))
1349 dir)
1351 (defsubst woman-not-member (dir path)
1352 "Return t if DIR is not a member of the list PATH, nil otherwise.
1353 If DIR is `.' it is first replaced by the current directory."
1354 (not (member dir path)))
1356 (defun woman-topic-all-completions (path)
1357 "Return an alist of the man files in all man directories in the list PATH.
1358 The cdr of each alist element is the path-index / filename."
1359 ;; Support 3 levels of caching: each element of the alist `files'
1360 ;; will be a list of the first `woman-cache-level' elements of the
1361 ;; following list: (topic path-index filename). This alist `files'
1362 ;; is re-processed by `woman-topic-all-completions-merge'.
1363 (let (dir files (path-index 0)) ; indexing starts at zero
1364 (while path
1365 (setq dir (pop path))
1366 (if (woman-not-member dir path) ; use each directory only once!
1367 (push (woman-topic-all-completions-1 dir path-index)
1368 files))
1369 (setq path-index (1+ path-index)))
1370 ;; Uniquefy topics:
1371 ;; Concate all lists with a single nconc call to
1372 ;; avoid retraversing the first lists repeatedly -- dak
1373 (woman-topic-all-completions-merge
1374 (apply #'nconc files))))
1376 (defun woman-topic-all-completions-1 (dir path-index)
1377 "Return an alist of the man topics in directory DIR with index PATH-INDEX.
1378 A topic is a filename sans type-related extensions.
1379 Support 3 levels of caching: each element of the alist will be a list
1380 of the first `woman-cache-level' elements from the following list:
1381 \(topic path-index filename)."
1382 ;; This function used to check that each file in the directory was
1383 ;; not itself a directory, but this is very slow and should be
1384 ;; unnecessary. So let us assume that `woman-file-regexp' will
1385 ;; filter out any directories, which probably should not be there
1386 ;; anyway, i.e. it is a user error!
1388 ;; Don't sort files: we do that when merging, anyway. -- dak
1389 (let (newlst (lst (directory-files dir nil woman-file-regexp t))
1390 ;; Make an explicit regexp for stripping extension and
1391 ;; compression extension: file-name-sans-extension is a
1392 ;; far too costly function. -- dak
1393 (ext (format "\\(\\.[^.\\/]*\\)?\\(%s\\)?\\'"
1394 woman-file-compression-regexp)))
1395 ;; Use a loop instead of mapcar in order to avoid the speed
1396 ;; penalty of binding function arguments. -- dak
1397 (dolist (file lst newlst)
1398 (push
1399 (cons
1400 (if (string-match ext file)
1401 (substring file 0 (match-beginning 0))
1402 file)
1403 (and (> woman-cache-level 1)
1404 (cons
1405 path-index
1406 (and (> woman-cache-level 2)
1407 (list file)))))
1408 newlst))))
1410 (defun woman-topic-all-completions-merge (alist)
1411 "Merge the alist ALIST so that the keys are unique.
1412 Also make each path-info component into a list.
1413 \(Note that this function changes the value of ALIST.)"
1414 ;; Replaces unreadably "optimized" O(n^2) implementation.
1415 ;; Instead we use sorting to merge stuff efficiently. -- dak
1416 (let (elt newalist)
1417 ;; Sort list into reverse order
1418 (setq alist (sort alist (lambda(x y) (string< (car y) (car x)))))
1419 ;; merge duplicate keys.
1420 (if (> woman-cache-level 1)
1421 (while alist
1422 (setq elt (pop alist))
1423 (if (equal (car elt) (caar newalist))
1424 (unless (member (cdr elt) (cdar newalist))
1425 (setcdr (car newalist) (cons (cdr elt)
1426 (cdar newalist))))
1427 (setcdr elt (list (cdr elt)))
1428 (push elt newalist)))
1429 ;; woman-cache-level = 1 => elements are single-element lists ...
1430 (while alist
1431 (setq elt (pop alist))
1432 (unless (equal (car elt) (caar newalist))
1433 (push elt newalist))))
1434 newalist))
1436 (defun woman-file-name-all-completions (topic)
1437 "Return an alist of the files in all man directories that match TOPIC."
1438 ;; Support 3 levels of caching: each element of
1439 ;; woman-topic-all-completions is a list of one of the forms:
1440 ;; (topic)
1441 ;; (topic (path-index) (path-index) ... )
1442 ;; (topic (path-index filename) (path-index filename) ... )
1443 ;; where the are no duplicates in the value lists.
1444 ;; Topic must match first `word' of filename, so ...
1445 (let ((topic-regexp
1446 (concat
1447 "\\`" (regexp-quote topic) ; first `word'
1448 "\\(\\..+\\)*" ; optional subsequent `words'
1449 woman-file-regexp)) ; extension
1450 (topics woman-topic-all-completions)
1451 (path woman-expanded-directory-path)
1452 dir files)
1453 (if (cdr (car topics))
1454 ;; Use cached path-info to locate files for each topic:
1455 (let ((path-info (cdr (assoc topic topics)))
1456 filename)
1457 (while path-info
1458 (setq dir (nth (car (car path-info)) path)
1459 filename (car (cdr (car path-info)))
1460 path-info (cdr path-info)
1461 files (nconc files
1462 ;; Find the actual file name:
1463 (if filename
1464 (list (concat dir "/" filename))
1465 (directory-files dir t topic-regexp)
1466 )))))
1467 ;; Search path for the files for each topic:
1468 (while path
1469 (setq dir (car path)
1470 path (cdr path))
1471 (if (woman-not-member dir path) ; use each directory only once!
1472 (setq files (nconc files
1473 (directory-files dir t topic-regexp))))
1475 (mapcar 'list files)
1479 ;;; dired support
1481 (defun woman-dired-define-key (key)
1482 "Bind the argument KEY to the command `woman-dired-find-file'."
1483 (define-key dired-mode-map key 'woman-dired-find-file))
1485 (defsubst woman-dired-define-key-maybe (key)
1486 "If KEY is undefined in Dired, bind it to command `woman-dired-find-file'."
1487 (if (or (eq (lookup-key dired-mode-map key) 'undefined)
1488 (null (lookup-key dired-mode-map key)))
1489 (woman-dired-define-key key)))
1491 (defun woman-dired-define-keys ()
1492 "Define dired keys to run WoMan according to `woman-dired-keys'."
1493 (if woman-dired-keys
1494 (if (listp woman-dired-keys)
1495 (mapcar 'woman-dired-define-key woman-dired-keys)
1496 (woman-dired-define-key-maybe "w")
1497 (woman-dired-define-key-maybe "W")))
1498 (define-key-after (lookup-key dired-mode-map [menu-bar immediate])
1499 [woman] '("Read Man Page (WoMan)" . woman-dired-find-file) 'view))
1501 (if (featurep 'dired)
1502 (woman-dired-define-keys)
1503 (add-hook 'dired-mode-hook 'woman-dired-define-keys))
1505 ;;;###autoload
1506 (defun woman-dired-find-file ()
1507 "In dired, run the WoMan man-page browser on this file."
1508 (interactive)
1509 ;; dired-get-filename is defined in dired.el
1510 (woman-find-file (dired-get-filename)))
1513 ;;; tar-mode support
1515 (defun woman-tar-extract-file ()
1516 "In tar mode, run the WoMan man-page browser on this file."
1517 (interactive)
1518 (or (eq major-mode 'tar-mode)
1519 (error "`woman-tar-extract-file' can be used only in `tar-mode'"))
1520 (buffer-disable-undo)
1521 (let (global-font-lock-mode)
1522 (funcall (symbol-function 'tar-extract)) ; defined in tar-mode
1523 (let ((WoMan-current-file buffer-file-name)) ; used for message logging
1524 (rename-buffer
1525 (woman-make-bufname (file-name-nondirectory buffer-file-name)))
1526 (woman-process-buffer)
1527 (goto-char (point-min)))))
1529 ;; There is currently no `tar-mode-hook' so use ...
1530 (eval-after-load "tar-mode"
1531 '(progn
1532 (define-key tar-mode-map "w" 'woman-tar-extract-file)
1533 (define-key-after (lookup-key tar-mode-map [menu-bar immediate])
1534 [woman] '("Read Man Page (WoMan)" . woman-tar-extract-file) 'view)))
1537 (defvar woman-last-file-name nil
1538 "The full pathname of the last file formatted by WoMan.")
1540 (defun woman-reformat-last-file ()
1541 "Reformat last file, e.g. after changing fill column."
1542 (interactive)
1543 (if woman-last-file-name
1544 (woman-find-file woman-last-file-name t)
1545 (call-interactively 'woman-find-file)))
1547 ;;;###autoload
1548 (defun woman-find-file (file-name &optional reformat)
1549 "Find, decode and browse a specific UN*X man-page source file FILE-NAME.
1550 Use existing buffer if possible; reformat only if prefix arg given.
1551 When called interactively, optional argument REFORMAT forces reformatting
1552 of an existing WoMan buffer formatted earlier.
1553 No external programs are used, except that `gunzip' will be used to
1554 decompress the file if appropriate. See the documentation for the
1555 `woman' command for further details."
1556 (interactive "fBrowse UN*X manual file: \nP")
1557 (setq woman-last-file-name
1558 (setq file-name (expand-file-name file-name))) ; to canonicalize
1559 (let ((alist-tail woman-buffer-alist) exists)
1560 (setq woman-buffer-number 0)
1561 (while (and alist-tail (not (string= file-name (car (car alist-tail)))))
1562 (setq alist-tail (cdr alist-tail)
1563 woman-buffer-number (1+ woman-buffer-number)))
1564 (or (and (setq exists
1565 (and alist-tail (WoMan-find-buffer))) ; buffer exists
1566 (not reformat))
1567 ;; Format new buffer or reformat current buffer:
1568 (let* ((bufname (file-name-nondirectory file-name))
1569 (case-fold-search t)
1570 (compressed
1571 (not (not (string-match woman-file-compression-regexp bufname)))))
1572 (if compressed
1573 (setq bufname (file-name-sans-extension bufname)))
1574 (setq bufname (if exists
1575 (buffer-name)
1576 (woman-make-bufname bufname)))
1577 (woman-really-find-file file-name compressed bufname)
1578 (or exists
1579 (setq woman-buffer-alist
1580 (cons (cons file-name bufname) woman-buffer-alist)
1581 woman-buffer-number 0))
1583 (Man-build-section-alist)
1584 (Man-build-references-alist)
1585 (goto-char (point-min)))
1587 (defun woman-make-bufname (bufname)
1588 "Create an unambiguous buffer name from BUFNAME."
1589 (let ((dot (string-match "\\." bufname)))
1590 (if dot (setq bufname (concat
1591 (substring bufname (1+ dot)) " "
1592 (substring bufname 0 dot))))
1593 (generate-new-buffer-name ; ensure uniqueness
1594 (concat "*WoMan " bufname "*"))))
1596 (defvar woman-frame nil
1597 "Dedicated frame used for displaying WoMan windows.")
1599 (defun woman-really-find-file (filename compressed bufname)
1600 "Find, decompress, and decode a UN*X man page FILENAME.
1601 If COMPRESSED is non-nil, turn on auto-compression mode to decompress
1602 the file if necessary. Set buffer name BUFNAME and major mode.
1603 Do not call directly!"
1604 (let ((WoMan-current-file filename)) ; used for message logging
1605 (if woman-use-own-frame
1606 (select-frame
1607 (or (and (frame-live-p woman-frame) woman-frame)
1608 (setq woman-frame (make-frame)))))
1609 (switch-to-buffer (get-buffer-create bufname))
1610 (buffer-disable-undo)
1611 (setq buffer-read-only nil)
1612 (erase-buffer) ; NEEDED for reformat
1613 (woman-insert-file-contents filename compressed)
1614 ;; Set buffer's default directory to that of the file.
1615 (setq default-directory (file-name-directory filename))
1616 (set (make-local-variable 'backup-inhibited) t)
1617 (set-visited-file-name "")
1618 (woman-process-buffer)))
1620 (defun woman-process-buffer ()
1621 "The second half of `woman-really-find-file'!"
1622 (interactive)
1623 ;; Check (crudely) that this really is likely to be in UN*X
1624 ;; man-page source format, assuming we are at point-min:
1625 (goto-char (point-min))
1626 (if (re-search-forward "^[.']" 1000 t)
1627 (woman-decode-buffer)
1628 (message
1629 "File appears to be pre-formatted -- using source file may be better.")
1630 (woman-man-buffer))
1631 (woman-mode))
1633 (defun woman-man-buffer ()
1634 "Post-process an nroff-preformatted man buffer."
1635 ;; Kill all leading whitespace:
1636 (if (looking-at "\\s-+") (woman-delete-match 0))
1637 ;; Delete all page footer/header pairs:
1638 (re-search-forward ".*") ; match header
1639 ;; Footer conventionally has page number at right, so ...
1640 (let ((regex (concat
1641 "^.*[0-9]\n\\s-*" ; footer and following blank lines
1642 (regexp-quote (match-string 0)) ; header
1643 "\\s-*\n"))) ; following blank lines
1644 (while (re-search-forward regex nil 1) ; finish at eob
1645 (woman-delete-match 0)))
1646 ;; Delete last text line (footer) and all following blank lines:
1647 (re-search-backward "\\S-")
1648 (beginning-of-line)
1649 (if (looking-at ".*[0-9]$")
1650 (delete-region (point) (point-max)))
1652 ;; Squeeze multiple blank lines:
1653 (goto-char (point-min))
1654 (while (re-search-forward "^[ \t]*\n\\([ \t]*\n\\)+" nil t)
1655 (replace-match "\n" t t))
1657 ;; CJK characters are underlined by double-sized "__".
1658 ;; (Code lifted from man.el, with trivial changes.)
1659 (if (< (buffer-size) (position-bytes (point-max)))
1660 ;; Multibyte characters exist.
1661 (progn
1662 (goto-char (point-min))
1663 (while (search-forward "__\b\b" nil t)
1664 (backward-delete-char 4)
1665 (woman-set-face (point) (1+ (point)) 'woman-italic))
1666 (goto-char (point-min))
1667 (while (search-forward "\b\b__" nil t)
1668 (backward-delete-char 4)
1669 (woman-set-face (1- (point)) (point) 'woman-italic))))
1671 ;; Interpret overprinting to indicate bold face:
1672 (goto-char (point-min))
1673 (while (re-search-forward "\\(.\\)\\(\\(\b+\\1\\)+\\)" nil t)
1674 (woman-delete-match 2)
1675 (woman-set-face (1- (point)) (point) 'woman-bold))
1677 ;; Interpret underlining to indicate italic face:
1678 ;; (Must be AFTER emboldening to interpret bold _ correctly!)
1679 (goto-char (point-min))
1680 (while (search-forward "_\b" nil t)
1681 (delete-char -2)
1682 (woman-set-face (point) (1+ (point)) 'woman-italic))
1684 ;; Leave any other uninterpreted ^H's in the buffer for now! (They
1685 ;; might indicate composite special characters, which could be
1686 ;; interpreted if I knew what to expect.)
1688 ;; Optionally embolden section and subsection headings
1689 ;; (cf. `woman-imenu-generic-expression'):
1690 (cond
1691 (woman-bold-headings
1692 (goto-char (point-min))
1693 (forward-line)
1694 (while (re-search-forward "^\\( \\)?\\([A-Z].*\\)" nil t)
1695 (woman-set-face (match-beginning 2) (match-end 2) 'woman-bold))))
1698 (defun woman-insert-file-contents (filename compressed)
1699 "Insert file FILENAME into the current buffer.
1700 If COMPRESSED is t, or is non-nil and the filename implies compression,
1701 then turn on auto-compression mode to decompress the file.
1702 Leave point at end of new text. Return length of inserted text."
1703 ;; Leaves point at end of inserted text in GNU Emacs 20.3, but at
1704 ;; start in 19.34!
1705 (save-excursion
1706 (let ((case-fold-search t))
1707 ;; Co-operate with auto-compression mode:
1708 (if (and compressed
1709 (or (eq compressed t)
1710 (string-match woman-file-compression-regexp filename))
1711 ;; (not auto-compression-mode)
1712 (not (rassq 'jka-compr-handler file-name-handler-alist)) )
1713 ;; (error "Compressed file requires Auto File Decompression turned on")
1714 (auto-compression-mode 1))
1715 (nth 1
1716 (condition-case ()
1717 (insert-file-contents filename nil)
1718 (file-error
1719 ;; Run find-file-not-found-hooks until one returns non-nil.
1720 ;; (run-hook-with-args-until-success 'find-file-not-found-hooks)
1721 (insert "\n***** File " filename " not found! *****\n\n")
1726 ;;; Major mode (Man) interface:
1728 (defvar woman-mode-map nil "Keymap for woman mode.")
1730 (unless woman-mode-map
1731 (setq woman-mode-map (make-sparse-keymap))
1732 (set-keymap-parent woman-mode-map Man-mode-map)
1734 (define-key woman-mode-map "R" 'woman-reformat-last-file)
1735 (define-key woman-mode-map "w" 'woman)
1736 (define-key woman-mode-map "\en" 'WoMan-next-manpage)
1737 (define-key woman-mode-map "\ep" 'WoMan-previous-manpage)
1738 (define-key woman-mode-map [M-mouse-2] 'woman-follow-word)
1740 ;; We don't need to call `man' when we are in `woman-mode'.
1741 (define-key woman-mode-map [remap man] 'woman))
1743 (defun woman-follow-word (event)
1744 "Run WoMan with word under mouse as topic.
1745 Argument EVENT is the invoking mouse event."
1746 (interactive "e") ; mouse event
1747 (goto-char (posn-point (event-start event)))
1748 (woman (or (current-word t) "")))
1750 ;; WoMan menu bar and pop-up menu:
1751 (easy-menu-define
1752 woman-menu ; (SYMBOL MAPS DOC MENU)
1753 ;; That comment was moved after the symbol `woman-menu' to make
1754 ;; find-function-search-for-symbol work. -- rost
1755 woman-mode-map
1756 "WoMan Menu"
1757 `("WoMan"
1758 ["WoMan..." woman t] ; [NAME CALLBACK ENABLE]
1759 "--"
1760 ["Next Section" Man-next-section t]
1761 ["Previous Section" Man-previous-section t]
1762 ["Goto Section..." Man-goto-section t]
1763 ["Goto See-Also Section" Man-goto-see-also-section t]
1764 ["Follow Reference..." Man-follow-manual-reference t]
1765 "--"
1766 ["Previous WoMan Buffer" WoMan-previous-manpage t]
1767 ["Next WoMan Buffer" WoMan-next-manpage t]
1768 ["Bury WoMan Buffer" Man-quit t]
1769 ["Kill WoMan Buffer" Man-kill t]
1770 "--"
1771 ;; ["Toggle Fill Frame Width" woman-toggle-fill-frame t]
1772 ["Use Full Frame Width" woman-toggle-fill-frame
1773 :active t :style toggle :selected woman-fill-frame]
1774 ["Reformat Last Man Page" woman-reformat-last-file t]
1775 ["Use Monochrome Main Faces" woman-monochrome-faces t]
1776 ["Use Default Main Faces" woman-default-faces t]
1777 ["Make Contents Menu" (woman-imenu t) (not woman-imenu-done)]
1778 "--"
1779 ["Describe (Wo)Man Mode" describe-mode t]
1780 ["Mini Help" woman-mini-help t]
1781 ,@(if (fboundp 'customize-group)
1782 '(["Customize..." (customize-group 'woman) t]))
1783 ["Show Version" (message "WoMan %s" woman-version) t]
1784 "--"
1785 ("Advanced"
1786 ["View Source" (view-file woman-last-file-name) woman-last-file-name]
1787 ["Show Log" (switch-to-buffer-other-window "*WoMan-Log*" t) t]
1788 ["Extended Font" woman-toggle-use-extended-font
1789 :included woman-font-support
1790 :active t :style toggle :selected woman-use-extended-font]
1791 ["Symbol Font" woman-toggle-use-symbol-font
1792 :included woman-font-support
1793 :active t :style toggle :selected woman-use-symbol-font]
1794 ["Font Map" woman-display-extended-fonts
1795 :included woman-font-support
1796 :active woman-use-symbol-font]
1797 "--"
1798 "Emulation"
1799 ["nroff" (woman-reset-emulation 'nroff)
1800 :active t :style radio :selected (eq woman-emulation 'nroff)]
1801 ["troff" (woman-reset-emulation 'troff)
1802 :active t :style radio :selected (eq woman-emulation 'troff)]
1806 (defun woman-toggle-use-extended-font ()
1807 "Toggle `woman-use-extended-font' and reformat, for menu use."
1808 (interactive)
1809 (setq woman-use-extended-font (not woman-use-extended-font))
1810 (woman-reformat-last-file))
1812 (defun woman-toggle-use-symbol-font ()
1813 "Toggle `woman-use-symbol-font' and reformat, for menu use."
1814 (interactive)
1815 (setq woman-use-symbol-font (not woman-use-symbol-font))
1816 (woman-reformat-last-file))
1818 (defun woman-reset-emulation (value)
1819 "Reset `woman-emulation' to VALUE and reformat, for menu use."
1820 (interactive)
1821 (setq woman-emulation value)
1822 (woman-reformat-last-file))
1824 (put 'woman-mode 'mode-class 'special)
1826 (defun woman-mode ()
1827 "Turn on (most of) Man mode to browse a buffer formatted by WoMan.
1828 WoMan is an ELisp emulation of much of the functionality of the Emacs
1829 `man' command running the standard UN*X man and ?roff programs.
1830 WoMan author: F.J.Wright@Maths.QMW.ac.uk
1831 WoMan version: see `woman-version'.
1832 See `Man-mode' for additional details."
1833 (let ((Man-build-page-list (symbol-function 'Man-build-page-list))
1834 (Man-strip-page-headers (symbol-function 'Man-strip-page-headers))
1835 (Man-unindent (symbol-function 'Man-unindent))
1836 (Man-goto-page (symbol-function 'Man-goto-page)))
1837 ;; Prevent inappropriate operations:
1838 (fset 'Man-build-page-list 'ignore)
1839 (fset 'Man-strip-page-headers 'ignore)
1840 (fset 'Man-unindent 'ignore)
1841 (fset 'Man-goto-page 'ignore)
1842 (unwind-protect
1843 (delay-mode-hooks (Man-mode))
1844 ;; Restore the status quo:
1845 (fset 'Man-build-page-list Man-build-page-list)
1846 (fset 'Man-strip-page-headers Man-strip-page-headers)
1847 (fset 'Man-unindent Man-unindent)
1848 (fset 'Man-goto-page Man-goto-page)))
1849 (setq major-mode 'woman-mode
1850 mode-name "WoMan")
1851 ;; Don't show page numbers like Man-mode does. (Online documents do
1852 ;; not have pages)
1853 (kill-local-variable 'mode-line-buffer-identification)
1854 (use-local-map woman-mode-map)
1855 ;; Imenu support:
1856 (set (make-local-variable 'imenu-generic-expression)
1857 ;; `make-local-variable' in case imenu not yet loaded!
1858 woman-imenu-generic-expression)
1859 (set (make-local-variable 'imenu-space-replacement) " ")
1860 ;; For reformat ...
1861 ;; necessary when reformatting a file in its old buffer:
1862 (setq imenu--last-menubar-index-alist nil)
1863 ;; necessary to avoid re-installing the same imenu:
1864 (setq woman-imenu-done nil)
1865 (if woman-imenu (woman-imenu))
1866 (let (buffer-read-only)
1867 (Man-highlight-references))
1868 (set-buffer-modified-p nil)
1869 (run-mode-hooks 'woman-mode-hook))
1871 (defun woman-imenu (&optional redraw)
1872 "Add a \"Contents\" menu to the menubar.
1873 Optional argument REDRAW, if non-nil, forces mode line to be updated."
1874 (interactive)
1875 (if woman-imenu-done
1876 ;; This is PRIMARILY to avoid a bug in imenu-add-to-menubar that
1877 ;; causes it to corrupt the menu bar if it is run more than once
1878 ;; in the same buffer.
1880 (setq woman-imenu-done t)
1881 (imenu-add-to-menubar woman-imenu-title)
1882 (if redraw (force-mode-line-update))))
1884 (defun woman-toggle-fill-frame ()
1885 "Toggle formatting to fill (most of) the width of the current frame."
1886 (interactive)
1887 (setq woman-fill-frame (not woman-fill-frame))
1888 (message "Woman fill column set to %s."
1889 (if woman-fill-frame "frame width" woman-fill-column)
1892 (defun woman-mini-help ()
1893 "Display WoMan commands and user options in an `apropos' buffer."
1894 ;; Based on apropos-command in apropos.el
1895 (interactive)
1896 (require 'apropos)
1897 (let ((message
1898 (let ((standard-output (get-buffer-create "*Apropos*")))
1899 (print-help-return-message 'identity))))
1900 (setq apropos-accumulator
1901 (apropos-internal "woman"
1902 (lambda (symbol)
1903 (or (commandp symbol)
1904 (user-variable-p symbol)))))
1905 ;; Filter out any inhibited symbols:
1906 (let ((tem apropos-accumulator))
1907 (while tem
1908 (if (get (car tem) 'apropos-inhibit)
1909 (setq apropos-accumulator (delq (car tem) apropos-accumulator)))
1910 (setq tem (cdr tem))))
1911 ;; Find documentation strings:
1912 (let ((p apropos-accumulator)
1913 doc symbol)
1914 (while p
1915 (setcar p (list ; must have 3 elements:
1916 (setq symbol (car p)) ; 1. name
1917 (if (functionp symbol) ; 2. command doc
1918 (if (setq doc (documentation symbol t))
1919 (substring doc 0 (string-match "\n" doc))
1920 "(not documented)"))
1921 (if (user-variable-p symbol) ; 3. variable doc
1922 (if (setq doc (documentation-property
1923 symbol 'variable-documentation t))
1924 (substring doc 0 (string-match "\n" doc))))))
1925 (setq p (cdr p))))
1926 ;; Output the result:
1927 (and (apropos-print t nil)
1928 message
1929 (message "%s" message))))
1932 (defun WoMan-getpage-in-background (topic)
1933 "Use TOPIC to start WoMan from `Man-follow-manual-reference'."
1934 ;; topic is a string, generally of the form "section topic"
1935 (let ((s (string-match " " topic)))
1936 (if s (setq topic (substring topic (1+ s))))
1937 (woman topic)))
1939 (defvar WoMan-Man-start-time nil
1940 "Used to record formatting time used by the `man' command.")
1942 ;; Both advices are disabled because "a file in Emacs should not put
1943 ;; advice on a function in Emacs" (see Info node "(elisp)Advising
1944 ;; Functions"). Counting the formatting time is useful for
1945 ;; developping, but less applicable for daily use. The advice for
1946 ;; `Man-getpage-in-background' can be discarded, because the
1947 ;; key-binding in `woman-mode-map' has been remapped to call `woman'
1948 ;; but `man'. Michael Albinus <michael.albinus@gmx.de>
1950 ;; (defadvice Man-getpage-in-background
1951 ;; (around Man-getpage-in-background-advice (topic) activate)
1952 ;; "Use WoMan unless invoked outside a WoMan buffer or invoked explicitly.
1953 ;; Otherwise use Man and record start of formatting time."
1954 ;; (if (and (eq major-mode 'woman-mode)
1955 ;; (not (eq (caar command-history) 'man)))
1956 ;; (WoMan-getpage-in-background topic)
1957 ;; ;; Initiates man processing
1958 ;; (setq WoMan-Man-start-time (current-time))
1959 ;; ad-do-it))
1961 ;; (defadvice Man-bgproc-sentinel
1962 ;; (after Man-bgproc-sentinel-advice activate)
1963 ;; ;; Terminates man processing
1964 ;; "Report formatting time."
1965 ;; (let* ((time (current-time))
1966 ;; (time (+ (* (- (car time) (car WoMan-Man-start-time)) 65536)
1967 ;; (- (cadr time) (cadr WoMan-Man-start-time)))))
1968 ;; (message "Man formatting done in %d seconds" time)))
1971 ;;; Buffer handling:
1973 (defun WoMan-previous-manpage ()
1974 "Find the previous WoMan buffer."
1975 ;; Assumes currently in a WoMan buffer!
1976 (interactive)
1977 (WoMan-find-buffer) ; find current existing buffer
1978 (if (null (cdr woman-buffer-alist))
1979 (error "No previous WoMan buffer"))
1980 (if (>= (setq woman-buffer-number (1+ woman-buffer-number))
1981 (length woman-buffer-alist))
1982 (setq woman-buffer-number 0))
1983 (if (WoMan-find-buffer)
1985 (if (< (setq woman-buffer-number (1- woman-buffer-number)) 0)
1986 (setq woman-buffer-number (1- (length woman-buffer-alist))))
1987 (WoMan-previous-manpage)))
1989 (defun WoMan-next-manpage ()
1990 "Find the next WoMan buffer."
1991 ;; Assumes currently in a WoMan buffer!
1992 (interactive)
1993 (WoMan-find-buffer) ; find current existing buffer
1994 (if (null (cdr woman-buffer-alist))
1995 (error "No next WoMan buffer"))
1996 (if (< (setq woman-buffer-number (1- woman-buffer-number)) 0)
1997 (setq woman-buffer-number (1- (length woman-buffer-alist))))
1998 (if (WoMan-find-buffer)
2000 (WoMan-next-manpage)))
2002 (defun WoMan-find-buffer ()
2003 "Switch to buffer corresponding to `woman-buffer-number' and return it.
2004 If such a buffer does not exist then remove its association from the
2005 alist in `woman-buffer-alist' and return nil."
2006 (if (zerop woman-buffer-number)
2007 (let ((buffer (get-buffer (cdr (car woman-buffer-alist)))))
2008 (if buffer
2009 (switch-to-buffer buffer)
2010 ;; Delete alist element:
2011 (setq woman-buffer-alist (cdr woman-buffer-alist))
2012 nil))
2013 (let* ((prev-ptr (nthcdr (1- woman-buffer-number) woman-buffer-alist))
2014 (buffer (get-buffer (cdr (car (cdr prev-ptr))))))
2015 (if buffer
2016 (switch-to-buffer buffer)
2017 ;; Delete alist element:
2018 (setcdr prev-ptr (cdr (cdr prev-ptr)))
2019 (if (>= woman-buffer-number (length woman-buffer-alist))
2020 (setq woman-buffer-number 0))
2021 nil)
2025 ;;; Syntax and display tables:
2027 (defconst woman-escaped-escape-char ?\x1c
2028 ;; An arbitrary unused control character
2029 "Internal character representation of escaped escape characters.")
2030 (defconst woman-escaped-escape-string
2031 (char-to-string woman-escaped-escape-char)
2032 "Internal string representation of escaped escape characters.")
2034 (defconst woman-unpadded-space-char ?\x1d
2035 ;; An arbitrary unused control character
2036 "Internal character representation of unpadded space characters.")
2037 (defconst woman-unpadded-space-string
2038 (char-to-string woman-unpadded-space-char)
2039 "Internal string representation of unpadded space characters.")
2041 (defvar woman-syntax-table nil
2042 "Syntax table to support special characters used internally by WoMan.")
2044 (if woman-syntax-table
2046 (setq woman-syntax-table (make-syntax-table))
2047 ;; The following internal chars must NOT have whitespace syntax:
2048 (modify-syntax-entry woman-unpadded-space-char "." woman-syntax-table)
2049 (modify-syntax-entry woman-escaped-escape-char "." woman-syntax-table)
2052 (defun woman-set-buffer-display-table ()
2053 "Set up a display table for a WoMan buffer.
2054 This display table is used for displaying internal special characters, but
2055 does not interfere with any existing display table, e.g. for displaying
2056 European characters."
2057 (setq buffer-display-table
2058 ;; The following test appears to be necessary on some
2059 ;; non-Windows platforms, e.g. Solaris 2.6 when running on a
2060 ;; tty. Thanks to T. V. Raman <raman@Adobe.COM>.
2061 ;; The MS-DOS terminal also sets standard-display-table to
2062 ;; a non-nil value.
2063 (if standard-display-table ; default is nil !!!
2064 (copy-sequence standard-display-table)
2065 (make-display-table)))
2066 ;; Display the following internal chars correctly:
2067 (aset buffer-display-table woman-unpadded-space-char [?\ ])
2068 (aset buffer-display-table woman-escaped-escape-char [?\\]))
2071 ;;; The main decoding driver:
2073 (defvar font-lock-mode) ; for the compiler
2075 (defun woman-decode-buffer ()
2076 "Decode a buffer in UN*X man-page source format.
2077 No external programs are used."
2078 (interactive) ; mainly for testing
2079 (WoMan-log-begin)
2080 (run-hooks 'woman-pre-format-hook)
2081 (and (boundp 'font-lock-mode) font-lock-mode (font-lock-mode -1))
2082 ;; (fundamental-mode)
2083 (let ((start-time (current-time)) ; (HIGH LOW MICROSEC)
2084 time) ; HIGH * 2**16 + LOW seconds
2085 (message "WoMan formatting buffer...")
2086 ; (goto-char (point-min))
2087 ; (cond
2088 ; ((re-search-forward "^\\.[ \t]*TH" nil t) ; wrong format if not found?
2089 ; (beginning-of-line)
2090 ; (delete-region (point-min) (point))) ; potentially dangerous!
2091 ; (t (message "WARNING: .TH request not found -- not man-page format?")))
2092 (woman-decode-region (point-min) (point-max))
2093 (setq time (current-time)
2094 time (+ (* (- (car time) (car start-time)) 65536)
2095 (- (cadr time) (cadr start-time))))
2096 (message "WoMan formatting buffer...done in %d seconds" time)
2097 (WoMan-log-end time))
2098 (run-hooks 'woman-post-format-hook))
2100 (defvar woman-string-alist ; rebound in woman-decode-region
2101 '(("S" . "") ("R" . "(Reg.)") ("Tm" . "(TM)")
2102 ("lq" . "\"") ("rq" . "\"")
2103 ("''" . "\"") ; needed for gcc.1
2104 (".T" . "") ; output device from -T option?
2106 "Alist of strings predefined in the -man macro package `tmac.an'.")
2108 (defvar woman-negative-vertical-space nil ; rebound in woman-decode-region
2109 "Set to t if .sp N with N < 0 encountered.")
2111 (defun woman-pre-process-region (from to)
2112 "Pre-process escapes and comments in the region of text between FROM and TO.
2113 To be called on original buffer and any .so insertions."
2114 ;; Hide escaped escapes \\ and printable escapes \e very early
2115 ;; (to be re-instated as just \ very late!):
2116 (goto-char from)
2117 ;; .eo turns off escape character processing
2118 (while (re-search-forward "\\(\\\\[\\e]\\)\\|^\\.eo" to t) ; \\
2119 (if (match-string 1)
2120 (replace-match woman-escaped-escape-string t t)
2121 (woman-delete-whole-line)
2122 ;; .ec turns on escape character processing (and sets the
2123 ;; escape character to its argument, if any, which I'm ignoring
2124 ;; for now!)
2125 (while (and (re-search-forward "\\(\\\\\\)\\|^\\.ec" to t) ; \
2126 (match-string 1))
2127 (replace-match woman-escaped-escape-string t t))
2128 ;; ***** Need test for .ec arg and warning here! *****
2129 (woman-delete-whole-line)))
2131 ;; Delete comments .\"<anything>, \"<anything> and null requests.
2132 ;; (However, should null . requests cause a break?)
2133 (goto-char from)
2134 (while (re-search-forward "^[.'][ \t]*\\(\\\\\".*\\)?\n\\|\\\\\".*" to t)
2135 (woman-delete-match 0)))
2137 (defun woman-non-underline-faces ()
2138 "Prepare non-underlined versions of underlined faces."
2139 (let ((face-list (face-list)))
2140 (while face-list
2141 (let* ((face (car face-list))
2142 (face-name (symbol-name face)))
2143 (if (and (string-match "\\`woman-" face-name)
2144 (face-underline-p face))
2145 (let ((face-no-ul (intern (concat face-name "-no-ul"))))
2146 (copy-face face face-no-ul)
2147 (set-face-underline-p face-no-ul nil))))
2148 (setq face-list (cdr face-list)))))
2150 ;; Preprocessors
2151 ;; =============
2153 ;; This information is based on documentation for the man command by
2154 ;; Graeme W. Wilford <G.Wilford@ee.surrey.ac.uk>
2156 ;; First, the environment variable $MANROFFSEQ is interrogated, and if
2157 ;; not set then the initial line of the nroff file is parsed for a
2158 ;; preprocessor string. To contain a valid preprocessor string, the
2159 ;; first line must resemble
2161 ;; '\" <string>
2163 ;; where string can be any combination of the following letters that
2164 ;; specify the sequence of preprocessors to run before nroff or
2165 ;; troff/groff. Not all installations will have a full set of
2166 ;; preprocessors. Some of the preprocessors and the letters used to
2167 ;; designate them are: eqn (e), grap (g), pic (p), tbl (t), vgrind
2168 ;; (v), refer (r). This option overrides the $MANROFFSEQ environment
2169 ;; variable. zsoelim is always run as the very first preprocessor.
2171 (defvar woman-emulate-tbl nil
2172 "True if WoMan should emulate the tbl preprocessor.
2173 This applies to text between .TE and .TS directives.
2174 Currently set only from '\" t in the first line of the source file.")
2176 (defun woman-decode-region (from to)
2177 "Decode the region between FROM and TO in UN*X man-page source format."
2178 ;; Suitable for use in format-alist.
2179 ;; But this requires care to control major mode implied font locking.
2180 ;; Must return the new end of file. See format.el for details.
2181 ;; NB: The `to' argument is bogus: it is not currently used, and if
2182 ;; it were it would need to be a marker rather than a position!
2183 ;; First force the correct environment:
2184 (let ((case-fold-search nil) ; This is necessary!
2185 (woman-string-alist woman-string-alist)
2186 (woman-fill-column woman-fill-column)
2187 woman-negative-vertical-space)
2188 (setq woman-left-margin woman-default-indent
2189 woman-prevailing-indent woman-default-indent
2190 woman-interparagraph-distance 1
2191 woman-leave-blank-lines nil
2192 woman-RS-left-margin nil
2193 woman-RS-prevailing-indent nil
2194 woman-adjust woman-adjust-both
2195 woman-justify (nth woman-adjust woman-justify-list)
2196 woman-nofill nil)
2198 (setq woman-if-conditions-true
2199 (cons (string-to-char (symbol-name woman-emulation)) '(?e ?o)))
2201 ;; Prepare non-underlined versions of underlined faces:
2202 (woman-non-underline-faces)
2203 ;; Set font of `woman-symbol' face to `woman-symbol-font' if
2204 ;; `woman-symbol-font' is well defined.
2205 (and woman-use-symbol-font
2206 (stringp woman-symbol-font)
2207 (set-face-font 'woman-symbol woman-symbol-font
2208 (and (frame-live-p woman-frame) woman-frame)))
2210 ;; Set syntax and display tables:
2211 (set-syntax-table woman-syntax-table)
2212 (woman-set-buffer-display-table)
2214 ;; Based loosely on a suggestion by Theodore Jump:
2215 (if (or woman-fill-frame
2216 (not (and (integerp woman-fill-column) (> woman-fill-column 0))))
2217 (setq woman-fill-column (- (window-width) woman-default-indent)))
2219 ;; Check for preprocessor requests:
2220 (goto-char from)
2221 (if (looking-at "'\\\\\"[ \t]*\\([a-z]+\\)")
2222 (let ((letters (append (match-string 1) nil)))
2223 (if (memq ?t letters)
2224 (setq woman-emulate-tbl t
2225 letters (delete ?t letters)))
2226 (if letters
2227 (WoMan-warn "Unhandled preprocessor request letters %s"
2228 (concat letters)))
2229 (woman-delete-line 1)))
2231 (woman-pre-process-region from nil)
2232 ;; Process ignore requests, macro definitions,
2233 ;; conditionals and switch source requests:
2234 (woman0-roff-buffer from)
2236 ;; Process \k escapes BEFORE changing tab width (?):
2237 (goto-char from)
2238 (woman-mark-horizonal-position)
2240 ;; Set buffer-local variables:
2241 (setq fill-column woman-fill-column
2242 tab-width woman-tab-width)
2244 ;; Hide unpaddable and digit-width spaces \(space) and \0:
2245 (goto-char from)
2246 (while (re-search-forward "\\\\[ 0]" nil t)
2247 (replace-match woman-unpadded-space-string t t))
2249 ;; Discard optional hyphen \%; concealed newlines \<newline>;
2250 ;; point-size change function \sN,\s+N, \s-N:
2251 (goto-char from)
2252 (while (re-search-forward "\\\\\\([%\n]\\|s[-+]?[0-9]+\\)" nil t)
2253 (woman-delete-match 0))
2255 ;; BEWARE: THIS SHOULD PROBABLY ALL BE DONE MUCH LATER!!!!!
2256 ;; Process trivial escapes \-, \`, \.
2257 ;; (\' must be done after tab processing!):
2258 (goto-char from)
2259 (while (re-search-forward "\\\\\\([-`.]\\)" nil t)
2260 (replace-match "\\1"))
2261 ;; NB: Must keep ALL zero-width characters \&, \|, and \^ until
2262 ;; ALL requests processed!
2264 ;; Process no-break requests and macros (including font-change macros):
2265 (goto-char from)
2266 (woman1-roff-buffer)
2268 ;; Process strings and special character escapes \(xx:
2269 ;; (Must do this BEFORE fontifying!)
2270 (goto-char from)
2271 (woman-strings)
2272 ;; Special chars moved after translation in
2273 ;; `woman2-process-escapes' (for pic.1):
2274 ; (goto-char from)
2275 ; (woman-special-characters)
2277 ;; Process standard font-change requests and escapes:
2278 (goto-char from)
2279 (woman-change-fonts)
2281 ;; 1/2 em vertical motion \d, \u and general local vertical motion
2282 ;; \v'+/-N' simulated using TeX ^ and _ symbols for now.
2283 (goto-char from)
2284 (let ((first t)) ; assume no nesting!
2285 (while (re-search-forward "\\\\\\([du]\\|v'[^']*'\\)" nil t)
2286 (let* ((esc (match-string 1))
2287 (repl (if (or (= (aref esc 0) ?u)
2288 (and (>= (length esc) 2) (= (aref esc 2) ?-)))
2289 "^" "_")))
2290 (cond (first
2291 (replace-match repl nil t)
2292 (put-text-property (1- (point)) (point) 'face 'woman-addition)
2293 (WoMan-warn
2294 "Initial vertical motion escape \\%s simulated" esc)
2295 (WoMan-log
2296 " by TeX `%s' in woman-addition-face!" repl))
2298 (woman-delete-match 0)
2299 (WoMan-warn
2300 "Terminal vertical motion escape \\%s ignored!" esc)))
2301 (setq first (not first))
2304 ; ;; \h'+/-N' local horizontal motion.
2305 ; ;; N may include width escape \w'...'
2306 ; ;; Implement arbitrary forward motion and non-overlapping backward
2307 ; ;; motion.
2308 ; (goto-char from)
2309 ; (while (re-search-forward
2310 ; ;; Delimiter can be a special char escape sequence \(.. or
2311 ; ;; a single normal char (usually '):
2312 ; "\\\\h\\(\\\\(..\\|.\\)\\(|\\)?"
2313 ; nil t)
2314 ; (let ((from (match-beginning 0))
2315 ; (delim (regexp-quote (match-string 1)))
2316 ; (absolute (match-string 2)) ; absolute position?
2317 ; (N (woman-parse-numeric-arg)) ; distance
2318 ; to
2319 ; msg) ; for warning
2320 ; (if (not (looking-at delim))
2321 ; ;; Warn but leave escape in buffer unprocessed:
2322 ; (WoMan-warn
2323 ; "Local horizontal motion (%s) delimiter error!"
2324 ; (buffer-substring from (1+ (point)))) ; point at end of arg
2325 ; (setq to (match-end 0)
2326 ; ;; For possible warning -- save before deleting:
2327 ; msg (buffer-substring from to))
2328 ; (delete-region from to)
2329 ; (if absolute ; make relative
2330 ; (setq N (- N (current-column))))
2331 ; (if (>= N 0)
2332 ; ;; Move forward by inserting hard spaces:
2333 ; (insert-char woman-unpadded-space-char N)
2334 ; ;; Move backwards by deleting space,
2335 ; ;; first backwards then forwards:
2336 ; (while (and
2337 ; (<= (setq N (1+ N)) 0)
2338 ; (cond ((memq (preceding-char) '(?\ ?\t))
2339 ; (delete-backward-char 1) t)
2340 ; ((memq (following-char) '(?\ ?\t))
2341 ; (delete-char 1) t)
2342 ; (t nil))))
2343 ; (if (<= N 0)
2344 ; (WoMan-warn
2345 ; "Negative horizontal motion (%s) would overwrite!" msg))))
2346 ; ))
2348 ;; Process formatting macros
2349 (goto-char from)
2350 (woman2-roff-buffer)
2352 ;; Go back and process negative vertical space if necessary:
2353 (if woman-negative-vertical-space
2354 (woman-negative-vertical-space from))
2356 (if woman-preserve-ascii
2357 ;; Re-instate escaped escapes to just `\' and unpaddable
2358 ;; spaces to just `space', without inheriting any text
2359 ;; properties. This is not necessary, UNLESS the buffer is to
2360 ;; be saved as ASCII.
2361 (progn
2362 (goto-char from)
2363 (while (search-forward woman-escaped-escape-string nil t)
2364 (delete-char -1) (insert ?\\))
2365 (goto-char from)
2366 (while (search-forward woman-unpadded-space-string nil t)
2367 (delete-char -1) (insert ?\ ))
2370 ;; Must return the new end of file if used in format-alist.
2371 (point-max)))
2373 (defun woman-horizontal-escapes (to)
2374 "Process \\h'+/-N' local horizontal motion escapes upto TO.
2375 Implements arbitrary forward and non-overlapping backward motion.
2376 Preserves location of `point'."
2377 ;; Moved from `woman-decode-region' for version 0.50.
2378 ;; N may include width escape \w'...' (but may already be processed!
2379 (let ((from (point)))
2380 (while (re-search-forward
2381 ;; Delimiter can be a special char escape sequence \(.. or
2382 ;; a single normal char (usually '):
2383 "\\\\h\\(\\\\(..\\|.\\)\\(|\\)?"
2384 to t)
2385 (let ((from (match-beginning 0))
2386 (delim (regexp-quote (match-string 1)))
2387 (absolute (match-string 2)) ; absolute position?
2388 (N (woman-parse-numeric-arg)) ; distance
2390 msg) ; for warning
2391 (if (not (looking-at delim))
2392 ;; Warn but leave escape in buffer unprocessed:
2393 (WoMan-warn
2394 "Local horizontal motion (%s) delimiter error!"
2395 (buffer-substring from (1+ (point)))) ; point at end of arg
2396 (setq to (match-end 0)
2397 ;; For possible warning -- save before deleting:
2398 msg (buffer-substring from to))
2399 (delete-region from to)
2400 (if absolute ; make relative
2401 (setq N (- N (current-column))))
2402 (if (>= N 0)
2403 ;; Move forward by inserting hard spaces:
2404 (insert-char woman-unpadded-space-char N)
2405 ;; Move backwards by deleting space,
2406 ;; first backwards then forwards:
2407 (while (and
2408 (<= (setq N (1+ N)) 0)
2409 (cond ((memq (preceding-char) '(?\ ?\t))
2410 (delete-backward-char 1) t)
2411 ((memq (following-char) '(?\ ?\t))
2412 (delete-char 1) t)
2413 (t nil))))
2414 (if (<= N 0)
2415 (WoMan-warn
2416 "Negative horizontal motion (%s) would overwrite!" msg))))
2418 (goto-char from)))
2422 ;; Process ignore requests (.ig), conditionals (.if etc.),
2423 ;; source-switch (.so), macro definitions (.de etc.) and macro
2424 ;; expansions.
2426 (defvar woman0-if-to) ; marker bound in woman0-roff-buffer
2427 (defvar woman0-macro-alist) ; bound in woman0-roff-buffer
2428 (defvar woman0-search-regex) ; bound in woman0-roff-buffer
2429 (defvar woman0-search-regex-start ; bound in woman0-roff-buffer
2430 "^[.'][ \t]*\\(ig\\|if\\|ie\\|el\\|so\\|rn\\|de\\|am")
2431 (defconst woman0-search-regex-end "\\)\\([ \t]+\\|$\\)")
2432 ;; May need other terminal characters, e.g. \, but NOT \n!
2433 ;; Alternatively, force maximal match (Posix?)
2435 (defvar woman0-rename-alist) ; bound in woman0-roff-buffer
2437 (defun woman0-roff-buffer (from)
2438 "Process conditional-type requests and user-defined macros.
2439 Start at FROM and re-scan new text as appropriate."
2440 (goto-char from)
2441 (let ((woman0-if-to (make-marker))
2442 request woman0-macro-alist
2443 (woman0-search-regex-start woman0-search-regex-start)
2444 (woman0-search-regex
2445 (concat woman0-search-regex-start woman0-search-regex-end))
2446 woman0-rename-alist)
2447 (while (re-search-forward woman0-search-regex nil t)
2448 (setq request (match-string 1))
2449 (cond ((string= request "ig") (woman0-ig))
2450 ((string= request "if") (woman0-if "if"))
2451 ((string= request "ie") (woman0-if "ie"))
2452 ((string= request "el") (woman0-el))
2453 ((string= request "so") (woman0-so))
2454 ((string= request "rn") (woman0-rn))
2455 ((string= request "de") (woman0-de))
2456 ((string= request "am") (woman0-de 'append))
2457 (t (woman0-macro request))))
2458 (set-marker woman0-if-to nil)
2459 (woman0-rename)
2460 ;; Should now re-run `woman0-roff-buffer' if any renaming was
2461 ;; done, but let's just hope this is not necessary for now!
2464 (defun woman0-ig ()
2465 ".ig yy -- Discard input up to `.yy', which defaults to `..')."
2466 ;; The terminal request MUST begin with . (not ')!
2467 (looking-at "\\(\\S +\\)?")
2468 (beginning-of-line)
2469 (let ((yy (or (match-string 1) "."))
2470 (from (point)))
2471 (if (re-search-forward
2472 (concat "^\\.[ \t]*" (regexp-quote yy) ".*\n") nil t)
2473 (delete-region from (point))
2474 (WoMan-warn
2475 "ig request ignored -- terminator `.%s' not found!" yy)
2476 (woman-delete-line 1))
2479 (defsubst woman0-process-escapes (from to)
2480 "Process escapes within an if/ie condition between FROM and TO."
2481 (woman-strings to)
2482 (goto-char from) ; necessary!
2483 ;; Strip font-change escapes:
2484 (while (re-search-forward "\\\\f\\(\\[[^]]+\\]\\|(..\\|.\\)" to t)
2485 (woman-delete-match 0))
2486 (goto-char from) ; necessary!
2487 (woman2-process-escapes to 'numeric))
2489 (defun woman0-if (request)
2490 ".if/ie c anything -- Discard unless c evaluates to true.
2491 Remember condition for use by a subsequent `.el'.
2492 REQUEST is the invoking directive without the leading dot."
2493 ;; c evaluates to a one-character built-in condition name or
2494 ;; 'string1'string2' or a number > 0, prefix ! negates.
2495 ;; \{ ... \} for multi-line use.
2496 ;; Leaves point at start of new text.
2497 (woman-delete-match 0)
2498 ;; (delete-horizontal-space)
2499 ;; Process escapes in condition:
2500 (let ((from (point)) negated n (c 0))
2501 (set-marker woman0-if-to
2502 (save-excursion (skip-syntax-forward "^ ") (point)))
2503 ;; Process condition:
2504 (if (setq negated (= (following-char) ?!)) (delete-char 1))
2505 (cond
2506 ;; ((looking-at "[no]") (setq c t)) ; accept n(roff) and o(dd page)
2507 ;; ((looking-at "[te]") (setq c nil)) ; reject t(roff) and e(ven page)
2508 ((looking-at "[ntoe]")
2509 (setq c (memq (following-char) woman-if-conditions-true)))
2510 ;; Unrecognised letter so reject:
2511 ((looking-at "[A-Za-z]") (setq c nil)
2512 (WoMan-warn "%s %s -- unrecognized condition name rejected!"
2513 request (match-string 0)))
2514 ;; Accept strings if identical:
2515 ((save-restriction
2516 (narrow-to-region from woman0-if-to)
2517 ;; String delimiter can be any non-numeric character,
2518 ;; including a special character escape:
2519 (looking-at "\\(\\\\(..\\|[^0-9]\\)\\(.*\\)\\1\\(.*\\)\\1\\'"))
2520 (let ((end1 (copy-marker (match-end 2)))) ; end of first string
2521 ;; Delete 2nd and 3rd delimiters to avoid processing them:
2522 (delete-region (match-end 3) woman0-if-to)
2523 (delete-region (match-end 2) (match-beginning 3))
2524 (goto-char (match-end 1))
2525 (woman0-process-escapes (point) woman0-if-to)
2526 (setq c (string= (buffer-substring (point) end1)
2527 (buffer-substring end1 woman0-if-to)))
2528 (set-marker end1 nil)
2529 (goto-char from)))
2530 ;; Accept numeric value if > 0:
2531 ((numberp (setq n (progn
2532 (woman0-process-escapes from woman0-if-to)
2533 (woman-parse-numeric-arg))))
2534 (setq c (> n 0))
2535 (goto-char from))
2537 (if (eq c 0)
2538 (woman-if-ignore woman0-if-to request) ; ERROR!
2539 (woman-if-body request woman0-if-to (eq c negated)))
2542 (defun woman-if-body (request to delete) ; should be reversed as `accept'?
2543 "Process if-body, including \\{ ... \\}.
2544 REQUEST is the invoking directive without the leading dot.
2545 If TO is non-nil then delete the if-body.
2546 If DELETE is non-nil then delete from point."
2547 ;; Assume concealed newlines already processed.
2548 (let ((from (point)))
2549 (if to (delete-region (point) to))
2550 (delete-horizontal-space)
2551 (cond (;;(looking-at "[^{\n]*\\\\{\\s *") ; multi-line
2552 ;; allow escaped newlines:
2553 (looking-at "[^{\n]*\\(\\\\\n\\)*\\\\{\\s *\\(\\\\\n\\)*") ; multi-line
2554 ;; including preceding .if(s) and following newline
2555 (let ((from (point)))
2556 (woman-delete-match 0)
2557 ;; Allow for nested \{ ... \} -- BUT BEWARE that this
2558 ;; algorithm only supports one level of nesting!
2559 (while
2560 (and (re-search-forward
2561 ;; "\\(\\\\{\\)\\|\\(\n[.']\\)?[ \t]*\\\\}[ \t]*"
2562 ;; Interpret bogus `el \}' as `el \{',
2563 ;; especially for Tcl/Tk man pages:
2564 "\\(\\\\{\\|el[ \t]*\\\\}\\)\\|\\(\n[.']\\)?[ \t]*\\\\}[ \t]*")
2565 (match-string 1))
2566 (re-search-forward "\\\\}"))
2567 (delete-region (if delete from (match-beginning 0)) (point))
2568 (if (looking-at "^$") (delete-char 1))
2570 (delete (woman-delete-line 1)) ; single-line
2572 ;; Process matching .el anything:
2573 (cond ((string= request "ie")
2574 ;; Discard unless previous .ie c `evaluated to false'.
2575 (cond ((re-search-forward "^[.'][ \t]*el[ \t]*" nil t)
2576 (woman-delete-match 0)
2577 (woman-if-body "el" nil (not delete)))))
2578 ;; Got here after processing a single-line `.ie' as a body
2579 ;; clause to be discarded:
2580 ((string= request "el")
2581 (cond ((re-search-forward "^[.'][ \t]*el[ \t]*" nil t)
2582 (woman-delete-match 0)
2583 (woman-if-body "el" nil t))))
2585 (goto-char from)
2588 (defun woman0-el ()
2589 "Isolated .el request -- should not happen!"
2590 (WoMan-warn "el request without matching `ie' rejected!")
2591 (cond (woman-ignore
2592 (woman-delete-match 0)
2593 (delete-horizontal-space)
2594 (woman-if-body "el" nil t))
2595 (t ; Ignore -- leave in buffer
2596 ;; This does not work too well, but it's only for debugging!
2597 (skip-chars-forward "^ \t")
2598 (if (looking-at "[ \t]*\\{") (search-forward "\\}"))
2599 (forward-line 1))))
2601 (defun woman-if-ignore (to request)
2602 "Ignore but warn about an if request ending at TO, named REQUEST."
2603 (WoMan-warn-ignored request "ignored -- condition not handled!")
2604 (if woman-ignore
2605 (woman-if-body request to t)
2606 ;; Ignore -- leave in buffer
2607 ;; This does not work too well, but it's only for debugging!
2608 (skip-chars-forward "^ \t")
2609 (if (looking-at "[ \t]*\\{") (search-forward "\\}"))
2610 (forward-line 1)))
2612 (defun woman0-so ()
2613 ".so filename -- Switch source file. `.so' requests may be nested."
2614 ;; Leaves point at start of new text.
2615 ;; (skip-chars-forward " \t")
2616 (let* ((beg (point))
2617 (end (progn (woman-forward-arg 'unquote) (point)))
2618 (name (buffer-substring beg end))
2619 (filename name))
2620 ;; If the specified file does not exist in this ...
2621 (or (file-exists-p filename)
2622 ;; or the parent directory ...
2623 (file-exists-p
2624 (setq filename (concat "../" name)))
2625 ;; then use the WoMan search mechanism to find the filename ...
2626 (setq filename
2627 (woman-file-name
2628 (file-name-sans-extension
2629 (file-name-nondirectory name))))
2630 ;; Cannot find the file, so ...
2631 (kill-buffer (current-buffer))
2632 (error "File `%s' not found" name))
2633 (beginning-of-line)
2634 (woman-delete-line 1)
2635 (let ((from (point))
2636 (to (make-marker))
2637 (length (woman-insert-file-contents filename 0)))
2638 (set-marker to (+ from length))
2639 (woman-pre-process-region from to)
2640 (set-marker to nil)
2641 (goto-char from)
2645 ;;; Process macro definitions:
2647 (defun woman0-rn ()
2648 "Process .rn xx yy -- rename macro xx to yy."
2649 ;; For now, done backwards AFTER all macro expansion.
2650 ;; Should also allow requests and strings to be renamed!
2651 (if (eolp) ; ignore if no argument
2653 (let* ((beg (point))
2654 (end (progn (woman-forward-arg 'unquote 'concat) (point)))
2655 (old (buffer-substring beg end))
2656 new)
2657 (if (eolp) ; ignore if no argument
2659 (setq beg (point)
2660 end (progn (woman-forward-arg 'unquote) (point))
2661 new (buffer-substring beg end)
2662 woman0-rename-alist (cons (cons new old) woman0-rename-alist)))
2664 (woman-delete-whole-line))
2666 (defun woman0-rename ()
2667 "Effect renaming required by .rn requests."
2668 ;; For now, do this backwards AFTER all macro expansion.
2669 (while woman0-rename-alist
2670 (let* ((new (car woman0-rename-alist))
2671 (old (cdr new))
2672 (new (car new)))
2673 (setq woman0-rename-alist (cdr woman0-rename-alist))
2674 (goto-char (point-min))
2675 (setq new (concat "^[.'][ \t]*" (regexp-quote new)))
2676 (setq old (concat "." old))
2677 (while (re-search-forward new nil t)
2678 (replace-match old nil t)))))
2680 (defconst woman-unescape-regex
2681 (concat woman-escaped-escape-string
2682 "\\(" woman-escaped-escape-string "\\)?"))
2684 (defsubst woman-unescape (macro)
2685 "Replace escape sequences in the body of MACRO.
2686 Replaces || by |, but | by \, where | denotes the internal escape."
2687 (let (start)
2688 (while (setq start (string-match woman-unescape-regex macro start))
2689 (setq macro
2690 (if (match-string 1 macro)
2691 (replace-match "" t t macro 1)
2692 (replace-match "\\" t t macro))
2693 start (1+ start)))
2694 macro))
2696 (defun woman0-de (&optional append)
2697 "Process .de/am xx yy -- (re)define/append macro xx; end at `..'.
2698 \(Should be up to call of yy, which defaults to `.')
2699 Optional argument APPEND, if non-nil, means append macro."
2700 ;; Modelled on woman-strings. BEWARE: Processing of .am is a hack!
2701 ;; Add support for .rm?
2702 ;; (skip-chars-forward " \t")
2703 (if (eolp) ; ignore if no argument
2705 (looking-at "[^ \t\n]+") ; macro name
2706 (let* ((macro (match-string 0)) from
2707 (previous (assoc macro woman0-macro-alist)))
2708 (if (not previous)
2709 (setq woman0-search-regex-start
2710 (concat woman0-search-regex-start "\\|" (regexp-quote macro))
2711 woman0-search-regex
2712 (concat woman0-search-regex-start woman0-search-regex-end)
2714 ;; Macro body runs from start of next line to line
2715 ;; beginning with `..'."
2716 ;; The terminal request MUST begin with `.' (not ')!
2717 (forward-line)
2718 (setq from (point))
2719 (re-search-forward "^\\.[ \t]*\\.")
2720 (beginning-of-line)
2721 (let ((body (woman-unescape (buffer-substring from (point)))))
2722 (if (and append previous)
2723 (setq previous (cdr previous)
2724 body (concat body (cdr previous))
2725 append (car previous)
2727 (setq macro (cons macro (cons append body))))
2728 ;; This should be an update, but consing a new string
2729 ;; onto the front of the alist has the same effect:
2730 (setq woman0-macro-alist (cons macro woman0-macro-alist))
2731 (forward-line)
2732 (delete-region from (point))
2733 (backward-char) ; return to end of .de/am line
2735 (beginning-of-line) ; delete .de/am line
2736 (woman-delete-line 1))
2738 (defun woman0-macro (request)
2739 "Process the macro call named REQUEST."
2740 ;; Leaves point at start of new text.
2741 (let ((macro (assoc request woman0-macro-alist)))
2742 (if macro
2743 (woman-interpolate-macro (cdr macro))
2744 ;; SHOULD DELETE THE UNINTERPRETED REQUEST!!!!!
2745 ;; Output this message once only per call (cf. strings)?
2746 (WoMan-warn "Undefined macro %s not interpolated!" request))))
2748 (defun woman-interpolate-macro (macro)
2749 "Interpolate (.de) or append (.am) expansion of MACRO into the buffer."
2750 ;; Could make this more efficient by checking which arguments are
2751 ;; actually used in the expansion!
2752 (skip-chars-forward " \t")
2753 ;; Process arguments:
2754 (let ((argno 0) (append (car macro))
2755 argno-string formal-arg from actual-arg start)
2756 (setq macro (cdr macro))
2757 (while (not (eolp))
2758 ;; Get next actual arg:
2759 (setq argno (1+ argno))
2760 (setq argno-string (format "%d" argno))
2761 (setq formal-arg (concat "\\\\\\$" argno-string)) ; regexp
2762 (setq from (point))
2763 (woman-forward-arg 'unquote 'noskip)
2764 (setq actual-arg (buffer-substring from (point)))
2765 (skip-chars-forward " \t") ; now skip following whitespace!
2766 ;; Replace formal arg with actual arg:
2767 (setq start nil)
2768 (while (setq start (string-match formal-arg macro start))
2769 (setq macro (replace-match actual-arg t t macro)))
2771 ;; Delete any remaining formal arguments:
2772 (setq start nil)
2773 (while
2774 (setq start (string-match "\\\\\\$." macro start))
2775 (setq macro (replace-match "" t t macro)))
2776 ;; Replace .$ number register with actual arg:
2777 ;; (Do this properly via register mechanism later!)
2778 (setq start nil)
2779 (while
2780 (setq start (string-match "\\\\n(\\.\\$" macro start)) ; regexp
2781 (setq macro (replace-match argno-string t t macro)))
2782 (if append
2783 (forward-char)
2784 (beginning-of-line)
2785 (woman-delete-line 1))
2786 (save-excursion ; leave point at start of new text
2787 (insert macro))))
2790 ;;; Process strings:
2792 (defun woman-match-name ()
2793 "Match and move over name of form: x, (xx or [xxx...].
2794 Applies to number registers, fonts, strings/macros/diversions, and
2795 special characters."
2796 (cond ((= (following-char) ?\[ )
2797 (forward-char)
2798 (re-search-forward "[^]]+")
2799 (forward-char)) ; skip closing ]
2800 ((= (following-char) ?\( )
2801 (forward-char)
2802 (re-search-forward ".."))
2803 (t (re-search-forward "."))))
2805 (defun woman-strings (&optional to)
2806 "Process ?roff string requests and escape sequences up to buffer position TO.
2807 Strings are defined/updated by `.ds xx string' requests and
2808 interpolated by `\*x' and `\*(xx' escapes."
2809 ;; Add support for .as and .rm?
2810 (while
2811 ;; Find .ds requests and \* escapes:
2812 (re-search-forward "\\(^[.'][ \t]*ds\\)\\|\\\\\\*" to t)
2813 (cond ((match-string 1) ; .ds
2814 (skip-chars-forward " \t")
2815 (if (eolp) ; ignore if no argument
2817 (re-search-forward "[^ \t\n]+")
2818 (let ((string (match-string 0)))
2819 (skip-chars-forward " \t")
2820 ; (setq string
2821 ; (cons string
2822 ; ;; hack (?) for CGI.man!
2823 ; (cond ((looking-at "\"\"") "\"")
2824 ; ((looking-at ".*") (match-string 0)))
2825 ; ))
2826 ;; Above hack causes trouble in arguments!
2827 (looking-at ".*")
2828 (setq string (cons string (match-string 0)))
2829 ;; This should be an update, but consing a new string
2830 ;; onto the front of the alist has the same effect:
2831 (setq woman-string-alist (cons string woman-string-alist))
2833 (beginning-of-line)
2834 (woman-delete-line 1))
2835 (t ; \*
2836 (let ((beg (match-beginning 0)))
2837 (woman-match-name)
2838 (let* ((stringname (match-string 0))
2839 (string (assoc stringname woman-string-alist)))
2840 (cond (string
2841 (delete-region beg (point))
2842 ;; Temporary hack in case string starts with a
2843 ;; control character:
2844 (if (bolp) (insert-before-markers "\\&"))
2845 (insert-before-markers (cdr string)))
2847 (WoMan-warn "Undefined string %s not interpolated!"
2848 stringname)
2849 (cond (woman-ignore
2850 ;; Output above message once only per call
2851 (delete-region beg (point))
2852 (setq woman-string-alist
2853 (cons (cons stringname "")
2854 woman-string-alist))))
2861 ;;; Process special character escapes \(xx:
2863 (defconst woman-special-characters
2864 ;; To be built heuristically as required!
2865 ;; MUST insert all characters as strings for correct conversion to
2866 ;; multibyte representation!
2867 '(("em" "--" "\276" . t) ; 3/4 Em dash
2868 ("bu" "*" "\267" . t) ; bullet
2869 ("fm" "'") ; foot mark
2870 ("co" "(C)" "\251") ; copyright
2872 ("pl" "+" "+" . t) ; math plus
2873 ("mi" "-" "-" . t) ; math minus
2874 ("**" "*" "*" . t) ; math star
2875 ("aa" "'" "\242" . t) ; acute accent
2876 ("ul" "_") ; underrule
2878 ("*S" "Sigma" "S" . t) ; Sigma
2880 (">=" ">=" "\263" . t) ; >=
2881 ("<=" "<=" "\243" . t) ; <=
2882 ("->" "->" "\256" . t) ; right arrow
2883 ("<-" "<-" "\254" . t) ; left arrow
2884 ("mu" " x " "\264" . t) ; multiply
2885 ("+-" "+/-" "\261" . t) ; plus-minus
2886 ("bv" "|") ; bold vertical
2888 ;; groff etc. extensions:
2889 ("lq" "\"")
2890 ("rq" "\"")
2891 ("aq" "'")
2892 ("ha" "^")
2893 ("ti" "~")
2895 "Alist of special character codes with ASCII and extended-font equivalents.
2896 Each alist elements has the form
2897 (input-string ascii-string extended-font-string . use-symbol-font)
2898 where
2899 * `\\(input-string' is the ?roff encoding,
2900 * `ascii-string' is the (multi-character) ASCII simulation,
2901 * `extended-font-string' is the single-character string representing
2902 the character position in the extended 256-character font, and
2903 * `use-symbol-font' is t to indicate use of the symbol font or nil,
2904 i.e. omitted, to indicate use of the default font.
2905 Any element may be nil. Avoid control character codes (0 to \\37, \\180
2906 to \\237) in `extended-font-string' for now, since they can be
2907 displayed only with a modified display table.
2909 Use the WoMan command `woman-display-extended-fonts' or a character
2910 map accessory to help construct this alist.")
2912 (defsubst woman-replace-match (newtext &optional face)
2913 "Replace text matched by last search with NEWTEXT and return t.
2914 Set NEWTEXT in face FACE if specified."
2915 (woman-delete-match 0)
2916 (insert-before-markers newtext)
2917 (if face (put-text-property (1- (point)) (point) 'face 'woman-symbol))
2920 (defun woman-special-characters (to)
2921 "Process special character escapes \\(xx, \\[xxx] up to buffer position TO.
2922 \(This must be done AFTER translation, which may use special characters.)"
2923 (while (re-search-forward "\\\\\\(?:(\\(..\\)\\|\\[\\([[^]]+\\)\\]\\)" to t)
2924 (let* ((name (or (match-string-no-properties 1)
2925 (match-string-no-properties 2)))
2926 (replacement (assoc name woman-special-characters)))
2927 (unless
2928 (and
2929 replacement
2930 (cond ((and (cddr replacement)
2931 (if (nthcdr 3 replacement)
2932 ;; Need symbol font:
2933 (if woman-use-symbol-font
2934 (woman-replace-match (nth 2 replacement)
2935 'woman-symbol))
2936 ;; Need extended font:
2937 (if woman-use-extended-font
2938 (woman-replace-match (nth 2 replacement))))))
2939 ((cadr replacement) ; Use ASCII simulation
2940 (woman-replace-match (cadr replacement)))))
2941 (WoMan-warn (concat "Special character "
2942 (if (match-string 1) "\\(%s" "\\[%s]")
2943 " not interpolated!") name)
2944 (if woman-ignore (woman-delete-match 0))))
2947 (defun woman-display-extended-fonts ()
2948 "Display table of glyphs of graphic characters and their octal codes.
2949 All the octal codes in the ranges [32..127] and [160..255] are displayed
2950 together with the corresponding glyphs from the default and symbol fonts.
2951 Useful for constructing the alist variable `woman-special-characters'."
2952 (interactive)
2953 (with-output-to-temp-buffer "*WoMan Extended Font Map*"
2954 (save-excursion
2955 (set-buffer standard-output)
2956 (let ((i 32))
2957 (while (< i 256)
2958 (insert (format "\\%03o " i) (string i) " " (string i))
2959 (put-text-property (1- (point)) (point)
2960 'face 'woman-symbol)
2961 (insert " ")
2962 (setq i (1+ i))
2963 (when (= i 128) (setq i 160) (insert "\n"))
2964 (if (zerop (% i 8)) (insert "\n")))
2966 (print-help-return-message)))
2969 ;;; Formatting macros that do not cause a break:
2971 (defvar request) ; Bound locally by woman1-roff-buffer
2972 (defvar unquote) ; Bound locally by woman1-roff-buffer
2974 (defun woman-unquote (to)
2975 "Delete any double-quote characters between point and TO.
2976 Leave point at TO (which should be a marker)."
2977 (let (in-quote)
2978 (while (search-forward "\"" to 1)
2979 (if (and in-quote (looking-at "\""))
2980 ;; Repeated double-quote represents single double-quote
2981 (delete-char 1)
2982 (if (or in-quote (looking-at ".*\"")) ; paired
2983 (delete-char -1))
2984 (setq in-quote (not in-quote))
2986 (if in-quote
2987 (WoMan-warn "Unpaired \" in .%s arguments." request))
2990 (defsubst woman-unquote-args ()
2991 "Delete any double-quote characters up to the end of the line."
2992 (woman-unquote (save-excursion (end-of-line) (point-marker))))
2994 (defun woman1-roff-buffer ()
2995 "Process non-breaking requests."
2996 (let ((case-fold-search t)
2997 request fn unquote)
2998 (while
2999 ;; Find next control line:
3000 (re-search-forward woman-request-regexp nil t)
3001 (cond
3002 ;; Construct woman function to call:
3003 ((setq fn (intern-soft
3004 (concat "woman1-"
3005 (setq request (match-string 1)))))
3006 (if (get fn 'notfont) ; not a font-change request
3007 (funcall fn)
3008 ;; Delete request or macro name:
3009 (woman-delete-match 0)
3010 ;; If no args then apply to next line else unquote args
3011 ;; (unquote is used by called function):
3012 (setq unquote (not (eolp)))
3013 (if (eolp) (delete-char 1))
3014 ; ;; Hide leading control character in unquoted argument:
3015 ; (cond ((memq (following-char) '(?. ?'))
3016 ; (insert "\\&")
3017 ; (beginning-of-line)))
3018 ;; Call the appropriate function:
3019 (funcall fn)
3020 ;; Hide leading control character in quoted argument (only):
3021 (if (and unquote (memq (following-char) '(?. ?')))
3022 (insert "\\&"))
3024 )))))
3026 ;;; Font-changing macros:
3028 (defun woman1-B ()
3029 ".B -- Set words of current line in bold font."
3030 (woman1-B-or-I ".ft B\n"))
3032 (defun woman1-I ()
3033 ".I -- Set words of current line in italic font."
3034 (woman1-B-or-I ".ft I\n"))
3036 (defun woman1-B-or-I (B-or-I)
3037 ".B/I -- Set words of current line in bold/italic font.
3038 B-OR-I is the appropriate complete control line."
3039 ;; Should NOT concatenate the arguments!
3040 (insert B-or-I) ; because it might be a control line
3041 ;; Return to bol to process .SM/.B, .B/.if etc.
3042 ;; or start of first arg to hide leading control char.
3043 (save-excursion
3044 (if unquote
3045 (woman-unquote-args)
3046 (while (looking-at "^[.']") (forward-line))
3047 (end-of-line)
3048 (delete-horizontal-space))
3049 (insert "\\fR")))
3051 (defun woman1-SM ()
3052 ".SM -- Set the current line in small font, i.e. IGNORE!"
3053 nil)
3055 (defalias 'woman1-SB 'woman1-B)
3056 ;; .SB -- Set the current line in small bold font, i.e. just embolden!
3057 ;; (This is what /usr/local/share/groff/tmac/tmac.an does. The
3058 ;; Linux man.7 is wrong about this!)
3060 (defun woman1-BI ()
3061 ".BI -- Join words of current line alternating bold and italic fonts."
3062 (woman1-alt-fonts (list "\\fB" "\\fI")))
3064 (defun woman1-BR ()
3065 ".BR -- Join words of current line alternating bold and Roman fonts."
3066 (woman1-alt-fonts (list "\\fB" "\\fR")))
3068 (defun woman1-IB ()
3069 ".IB -- Join words of current line alternating italic and bold fonts."
3070 (woman1-alt-fonts (list "\\fI" "\\fB")))
3072 (defun woman1-IR ()
3073 ".IR -- Join words of current line alternating italic and Roman fonts."
3074 (woman1-alt-fonts (list "\\fI" "\\fR")))
3076 (defun woman1-RB ()
3077 ".RB -- Join words of current line alternating Roman and bold fonts."
3078 (woman1-alt-fonts (list "\\fR" "\\fB")))
3080 (defun woman1-RI ()
3081 ".RI -- Join words of current line alternating Roman and italic fonts."
3082 (woman1-alt-fonts (list "\\fR" "\\fI")))
3084 (defun woman1-alt-fonts (fonts)
3085 "Join words using alternating fonts in FONTS, which MUST be a dynamic list."
3086 (nconc fonts fonts) ; circular list!
3087 (insert (car fonts))
3088 ;; Return to start of first arg to hide leading control char:
3089 (save-excursion
3090 (setq fonts (cdr fonts))
3091 (woman-forward-arg unquote 'concat) ; unquote is bound above
3092 (while (not (eolp))
3093 (insert (car fonts))
3094 (setq fonts (cdr fonts))
3095 (woman-forward-arg unquote 'concat)) ; unquote is bound above
3096 (insert "\\fR")
3099 (defun woman-forward-arg (&optional unquote concat)
3100 "Move forward over one ?roff argument, optionally unquoting and/or joining.
3101 If optional arg UNQUOTE is non-nil then delete any argument quotes.
3102 If optional arg CONCAT is non-nil then join arguments."
3103 (if (eq (following-char) ?\")
3104 (progn
3105 (if unquote (delete-char 1) (forward-char))
3106 (re-search-forward "\"\\|$")
3107 ;; Repeated double-quote represents single double-quote
3108 (while (eq (following-char) ?\") ; paired
3109 (if unquote (delete-char 1) (forward-char))
3110 (re-search-forward "\"\\|$"))
3111 (if (eq (preceding-char) ?\")
3112 (if unquote (delete-backward-char 1))
3113 (WoMan-warn "Unpaired \" in .%s arguments." request)
3115 ;; (re-search-forward "[^\\\n] \\|$") ; inconsistent
3116 (skip-syntax-forward "^ "))
3117 (cond ((null concat) (skip-chars-forward " \t")) ; don't skip eol!
3118 ((eq concat 'noskip)) ; do not skip following whitespace
3119 (t (woman-delete-following-space)))
3123 ;; The following requests are not explicit font-change requests and
3124 ;; so are flagged `notfont' to turn off automatic request deletion
3125 ;; and further processing.
3127 (put 'woman1-TP 'notfont t)
3128 (defun woman1-TP ()
3129 ".TP -- After tag line, reset font to Roman for paragraph body."
3130 ;; Same for .IP, but forward only 1 line?
3131 (save-excursion
3132 ;; May be an `irrelevant' control line in the way, so ...
3133 (forward-line)
3134 (forward-line (if (looking-at "\\.\\S-+[ \t]*$") 2 1))
3135 ;; May be looking at control line, so ...
3136 (insert ".ft R\n")))
3138 (put 'woman1-ul 'notfont t)
3139 (defun woman1-ul ()
3140 ".ul N -- Underline (italicize) the next N input lines, default N = 1."
3141 (let ((N (if (eolp) 1 (woman-parse-numeric-arg)))) ; woman-get-numeric-arg ?
3142 (woman-delete-whole-line)
3143 (insert ".ft I\n")
3144 (forward-line N)
3145 (insert ".ft R\n")
3148 ;;; Other non-breaking requests:
3150 ;; Hyphenation
3151 ;; Warnings commented out.
3153 (put 'woman1-nh 'notfont t)
3154 (defun woman1-nh ()
3155 ".nh -- No hyphenation, i.e. IGNORE!"
3156 ;; Must be handled here to avoid breaking!
3157 ;; (WoMan-log-1 ".nh request ignored -- hyphenation not supported!")
3158 (woman-delete-whole-line))
3160 (put 'woman1-hy 'notfont t)
3161 (defun woman1-hy ()
3162 ".hy N -- Set hyphenation mode to N, i.e. IGNORE!"
3163 ;; (WoMan-log-1 ".hy request ignored -- hyphenation not supported!")
3164 (woman-delete-whole-line))
3166 (put 'woman1-hc 'notfont t)
3167 (defun woman1-hc ()
3168 ".hc c -- Set hyphenation character to c, i.e. delete it!"
3169 (let ((c (char-to-string (following-char))))
3170 ;; (WoMan-log
3171 ;; "Hyphenation character %s deleted -- hyphenation not supported!" c)
3172 (woman-delete-whole-line)
3173 (setq c (concat "\\(" c "\\)\\|^[.'][ \t]*hc"))
3174 (save-excursion
3175 (while (and (re-search-forward c nil t)
3176 (match-string 1))
3177 (delete-char -1)))
3180 (put 'woman1-hw 'notfont t)
3181 (defun woman1-hw ()
3182 ".hw words -- Set hyphenation exception words, i.e. IGNORE!"
3183 ;; (WoMan-log-1 ".hw request ignored -- hyphenation not supported!")
3184 (woman-delete-whole-line))
3186 ;;; Other non-breaking requests correctly ignored by nroff:
3188 (put 'woman1-ps 'notfont t)
3189 (defalias 'woman1-ps 'woman-delete-whole-line)
3190 ;; .ps -- Point size -- IGNORE!
3192 (put 'woman1-ss 'notfont t)
3193 (defalias 'woman1-ss 'woman-delete-whole-line)
3194 ;; .ss -- Space-character size -- IGNORE!
3196 (put 'woman1-cs 'notfont t)
3197 (defalias 'woman1-cs 'woman-delete-whole-line)
3198 ;; .cs -- Constant character space (width) mode -- IGNORE!
3200 (put 'woman1-ne 'notfont t)
3201 (defalias 'woman1-ne 'woman-delete-whole-line)
3202 ;; .ne -- Need vertical space -- IGNORE!
3204 (put 'woman1-vs 'notfont t)
3205 (defalias 'woman1-vs 'woman-delete-whole-line)
3206 ;; .vs -- Vertical base line spacing -- IGNORE!
3208 (put 'woman1-bd 'notfont t)
3209 (defalias 'woman1-bd 'woman-delete-whole-line)
3210 ;; .bd -- Embolden font -- IGNORE!
3212 ;;; Non-breaking SunOS-specific macros:
3214 (defun woman1-TX ()
3215 ".TX t p -- Resolve SunOS abbrev t and join to p (usually punctuation)."
3216 (insert "SunOS ")
3217 (woman-forward-arg 'unquote 'concat))
3219 (put 'woman1-IX 'notfont t)
3220 (defalias 'woman1-IX 'woman-delete-whole-line)
3221 ;; .IX -- Index macro, for Sun internal use -- IGNORE!
3224 ;;; Direct font selection:
3226 (defconst woman-font-alist
3227 '(("R" . default)
3228 ("I" . woman-italic)
3229 ("B" . woman-bold)
3230 ("P" . previous)
3231 ("1" . default)
3232 ("2" . woman-italic)
3233 ("3" . woman-bold) ; used in bash.1
3235 "Alist of ?roff font indicators and woman font variables and names.")
3237 (defun woman-change-fonts ()
3238 "Process font changes."
3239 ;; ***** NEEDS REVISING IF IT WORKS OK *****
3240 ;; Paragraph .LP/PP/HP/IP/TP and font .B/.BI etc. macros reset font.
3241 ;; Should .SH/.SS reset font?
3242 ;; Font size setting macros (?) should reset font.
3243 (let ((font-alist woman-font-alist) ; for local updating
3244 (previous-pos (point))
3245 (previous-font 'default)
3246 (current-font 'default))
3247 (while
3248 ;; Find font requests, paragraph macros and font escapes:
3249 (re-search-forward
3250 "^[.'][ \t]*\\(\\(\\ft\\)\\|\\(.P\\)\\)\\|\\(\\\\f\\)" nil 1)
3251 (let (font beg notfont)
3252 ;; Match font indicator and leave point at end of sequence:
3253 (cond ((match-string 2)
3254 ;; .ft request found
3255 (setq beg (match-beginning 0))
3256 (skip-chars-forward " \t")
3257 (if (eolp) ; default is previous font
3258 (setq font previous-font)
3259 (looking-at "[^ \t\n]+"))
3260 (forward-line)) ; end of control line and \n
3261 ((match-string 3)
3262 ;; Macro that resets font found
3263 (setq font 'default))
3264 ((match-string 4)
3265 ;; \f escape found
3266 (setq beg (match-beginning 0))
3267 (woman-match-name))
3268 (t (setq notfont t)))
3269 (if notfont
3271 ;; Get font name:
3272 (or font
3273 (let ((fontstring (match-string 0)))
3274 (setq font (assoc fontstring font-alist)
3275 ;; NB: font-alist contains VARIABLE NAMES.
3276 font (if font
3277 (cdr font)
3278 (WoMan-warn "Unknown font %s." fontstring)
3279 ;; Output this message once only per call ...
3280 (setq font-alist
3281 (cons (cons fontstring 'woman-unknown)
3282 font-alist))
3283 'woman-unknown)
3285 ;; Delete font control line or escape sequence:
3286 (cond (beg (delete-region beg (point))
3287 (if (eq font 'previous) (setq font previous-font))))
3288 (woman-set-face previous-pos (point) current-font)
3289 (if beg
3290 ;; Explicit font control
3291 (setq previous-pos (point)
3292 previous-font current-font)
3293 ;; Macro that resets font
3294 ;; (forward-line) ; DOES NOT WORK! but unnecessary?
3295 ;; Must process font changes in any paragraph tag!
3296 (setq previous-pos (point)
3297 previous-font 'default))
3298 (setq current-font font)
3300 ;; Set font after last request up to eob:
3301 (woman-set-face previous-pos (point) current-font)
3304 (defun woman-set-face (from to face)
3305 "Set the face of the text from FROM to TO to face FACE.
3306 Ignore the default face and underline only word characters."
3307 (or (eq face 'default) ; ignore
3308 (not woman-fontify)
3309 (if (face-underline-p face)
3310 (save-excursion
3311 (let ((face-no-ul (intern (concat (symbol-name face) "-no-ul"))))
3312 (goto-char from)
3313 (while (< (point) to)
3314 (skip-syntax-forward "w" to)
3315 (put-text-property from (point) 'face face)
3316 (setq from (point))
3317 (skip-syntax-forward "^w" to)
3318 (put-text-property from (point) 'face face-no-ul)
3319 (setq from (point))
3321 (put-text-property from to 'face face))
3325 ;;; Output translation:
3327 (defvar translations nil) ; Also bound locally by woman2-roff-buffer
3328 ;; A list of the form (\"[ace]\" (a . b) (c . d) (e . ?\ )) or nil.
3330 (defun woman-get-next-char ()
3331 "Return and delete next char in buffer, including special chars."
3332 (if ;;(looking-at "\\\\(\\(..\\)")
3333 ;; Match special \(xx and strings \*[xxx], \*(xx, \*x:
3334 (looking-at "\\\\\\((..\\|\\*\\(\\[[^]]+\\]\\|(..\\|.\\)\\)")
3335 (prog1 (match-string 0)
3336 (woman-delete-match 0))
3337 (prog1 (char-to-string (following-char))
3338 (delete-char 1))))
3340 (defun woman2-tr (to)
3341 ".tr abcde -- Translate a -> b, c -> d, ..., e -> space.
3342 Format paragraphs upto TO. Supports special chars.
3343 \(Breaks, but should not.)"
3344 ;; This should be an update, but consing onto the front of the alist
3345 ;; has the same effect and match duplicates should not matter.
3346 ;; Initialize translation data structures:
3347 (let ((matches (car translations))
3348 (alist (cdr translations))
3349 a b)
3350 ;; `matches' must be a string:
3351 (setq matches
3352 (concat (if matches (substring matches 1 -1)) "]"))
3353 ;; Process .tr arguments:
3354 (while (not (eolp)) ; (looking-at "[ \t]*$") ???
3355 (setq a (woman-get-next-char))
3356 (if (eolp)
3357 (setq b " ")
3358 (setq b (woman-get-next-char)))
3359 (setq matches
3360 (if (= (length a) 1)
3361 (concat a matches)
3362 (concat matches "\\|\\" a))
3363 alist (cons (cons a b) alist)))
3364 (delete-char 1) ; no blank line
3365 ;; Rebuild translations list:
3366 (setq matches
3367 (if (= (string-to-char matches) ?\])
3368 (substring matches 3)
3369 (concat "[" matches))
3370 translations (cons matches alist))
3371 ;; Format any following text:
3372 (woman2-format-paragraphs to)
3375 (defsubst woman-translate (to)
3376 "Translate up to marker TO. Do this last of all transformations."
3377 (if translations
3378 (let ((matches (car translations))
3379 (alist (cdr translations)))
3380 (while (re-search-forward matches to t)
3381 ;; Done like this to retain text properties and
3382 ;; support translation of special characters:
3383 (insert-before-markers-and-inherit
3384 (cdr (assoc
3385 (buffer-substring-no-properties
3386 (match-beginning 0) (match-end 0))
3387 alist)))
3388 (woman-delete-match 0))
3392 ;;; Registers:
3394 (defvar woman-registers ; these are all read-only
3395 '((".H" 24) (".V" 48) ; resolution in basic units
3396 (".g" 0) ; not groff
3397 ;; (Iff emulating groff need to implement groff italic correction
3398 ;; \/, e.g. for pic.1)
3399 (".i" left-margin) ; current indent
3400 (".j" woman-adjust) ; current adjustment
3401 (".l" fill-column) ; current line length
3402 (".s" 12) ; current point size
3403 (".u" (if woman-nofill 0 1)) ; 1/0 in fill/nofill mode
3404 (".v" 48) ; current vertical line spacing
3406 "Register alist: the key is the register name as a string.
3407 Each element has the form (KEY VALUE . INC) -- inc may be nil.
3408 Also bound locally in `woman2-roff-buffer'.")
3410 (defun woman-mark-horizonal-position ()
3411 "\\kx -- Store current horizontal position in INPUT LINE in register x."
3412 (while (re-search-forward "\\\\k\\(.\\)" nil t)
3413 (goto-char (match-beginning 0))
3414 (setq woman-registers
3415 (cons (list (match-string 1) (current-column))
3416 woman-registers))
3417 (woman-delete-match 0)))
3419 (defsubst woman2-process-escapes-to-eol (&optional numeric)
3420 "Process remaining escape sequences up to eol.
3421 Handle numeric arguments specially if optional argument NUMERIC is non-nil."
3422 (woman2-process-escapes
3423 (save-excursion (end-of-line) (point-marker))
3424 numeric))
3426 (defun woman2-nr (to)
3427 ".nr R +/-N M -- Assign +/-N (wrt to previous value, if any) to register R.
3428 The increment for auto-incrementing is set to M.
3429 Format paragraphs upto TO. (Breaks, but should not!)"
3430 (let* ((name (buffer-substring
3431 (point)
3432 (progn (skip-syntax-forward "^ ") (point))))
3433 (pm (progn ; increment
3434 (skip-chars-forward " \t")
3435 (when (memq (char-after) '(?+ ?-))
3436 (forward-char) (char-before))))
3437 (value (if (eolp) ; no value
3438 nil ; to be interpreted as zero
3439 (woman2-process-escapes-to-eol 'numeric)
3440 (woman-parse-numeric-arg)))
3441 (inc (progn ; auto-increment
3442 (skip-chars-forward " \t")
3443 (if (eolp) ; no value
3444 nil ; to be interpreted as zero ???
3445 (woman-parse-numeric-arg))))
3446 (oldvalue (assoc name woman-registers)))
3447 (when oldvalue
3448 (setq oldvalue (cdr oldvalue)) ; (value . inc)
3449 (unless inc (setq inc (cdr oldvalue))))
3450 (cond ((null value)
3451 (setq value 0) ; correct?
3452 (WoMan-warn "nr %s -- null value assigned as zero!" name))
3453 ((symbolp value)
3454 (setq value (list 'quote value))))
3455 (if pm ; increment old value
3456 (setq oldvalue (if oldvalue (car oldvalue) 0)
3457 value (if (eq pm ?+)
3458 (+ oldvalue value)
3459 (- oldvalue value))))
3460 (setq woman-registers
3461 (cons (cons name (cons value inc)) woman-registers))
3462 (woman-delete-whole-line)
3463 (woman2-format-paragraphs to)))
3466 ;;; Numeric (and "non-text") request arguments:
3468 (defsubst woman-get-numeric-arg ()
3469 "Get the value of a numeric argument at or after point.
3470 The argument can include the width function and scale indicators.
3471 Assumes 10 characters per inch. Does not move point."
3472 (woman2-process-escapes-to-eol 'numeric)
3473 (save-excursion (woman-parse-numeric-arg)))
3475 (defun woman-parse-numeric-arg ()
3476 "Get the value of a numeric expression at or after point.
3477 Unlike `woman-get-numeric-arg', leaves point after the argument.
3478 The expression may be an argument in quotes."
3479 (if (= (following-char) ?\") (forward-char))
3480 ;; Allow leading +/-:
3481 (let ((value (if (looking-at "[+-]") 0 (woman-parse-numeric-value)))
3483 (while (cond
3484 ((looking-at "[+-/*%]") ; arithmetic operators
3485 (forward-char)
3486 (setq op (intern-soft (match-string 0)))
3487 (setq value (funcall op value (woman-parse-numeric-value))))
3488 ((looking-at "[<=>]=?") ; relational operators
3489 (goto-char (match-end 0))
3490 (setq op (or (intern-soft (match-string 0))
3491 (intern-soft "=")))
3492 (setq value (if (funcall op value (woman-parse-numeric-value))
3493 1 0)))
3494 ((memq (setq op (following-char)) '(?& ?:)) ; Boolean and / or
3495 (forward-char)
3496 (setq value
3497 ;; and / or are special forms, not functions, in ELisp
3498 (if (eq op ?&)
3499 ;; and
3500 (if (> value 0)
3501 (if (> (woman-parse-numeric-value) 0) 1 0)
3502 ;; skip second operand
3503 (prog1 0 (woman-parse-numeric-value)))
3504 ;; or
3505 (if (> value 0)
3506 ;; skip second operand
3507 (prog1 1 (woman-parse-numeric-value))
3508 (if (> (woman-parse-numeric-value) 0) 1 0))
3511 ; (if (looking-at "[ \t\nRC\)\"]") ; R, C are tab types
3512 ; ()
3513 ; (WoMan-warn "Unimplemented numerical operator `%c' in %s"
3514 ; (following-char)
3515 ; (buffer-substring
3516 ; (save-excursion (beginning-of-line) (point))
3517 ; (save-excursion (end-of-line) (point))))
3518 ; (skip-syntax-forward "^ "))
3519 value
3522 (defun woman-parse-numeric-value ()
3523 "Get a single numeric value at or after point.
3524 The value can be a number register or width function (which assumes 10
3525 characters per inch) and can include scale indicators. It may be an
3526 expression in parentheses. Leaves point after the value."
3527 ;; Must replace every \' by some different single character first
3528 ;; before calling this function by calling
3529 ;; (woman2-process-escapes-to-eol 'numeric)
3530 (if (eq (following-char) ?\()
3531 ;; Treat parenthesized expression as a single value.
3532 (let (n)
3533 (forward-char)
3534 (setq n (woman-parse-numeric-arg))
3535 (skip-syntax-forward " ")
3536 (if (eq (following-char) ?\))
3537 (forward-char)
3538 (WoMan-warn "Parenthesis confusion in numeric expression!"))
3540 (let ((n (cond ((looking-at "[-+]?[.0-9]+") ; single number
3541 ;; currently needed to set match-end, even though
3542 ;; string-to-number returns 0 if number not parsed.
3543 (string-to-number (match-string 0)))
3544 ((looking-at "\\\\n\\([-+]\\)?\\(?:\
3545 \\[\\([^]]+\\)\\]\\|\(\\(..\\)\\|\\(.\\)\\)")
3546 ;; interpolate number register, maybe auto-incremented
3547 (let* ((pm (match-string-no-properties 1))
3548 (name (or (match-string-no-properties 2)
3549 (match-string-no-properties 3)
3550 (match-string-no-properties 4)))
3551 (value (assoc name woman-registers)))
3552 (if value
3553 (let (inc)
3554 (setq value (cdr value) ; (value . inc)
3555 inc (cdr value)
3556 ;; eval internal (.X) registers
3557 ;; stored as lisp variable names:
3558 value (eval (car value)))
3559 (if (and pm inc) ; auto-increment
3560 (setq value
3561 (funcall (intern-soft pm) value inc)
3562 woman-registers
3563 (cons (cons name (cons value inc))
3564 woman-registers)))
3565 value)
3566 (WoMan-warn "Undefined register %s defaulted to 0."
3567 name)
3568 0) ; default to zero
3570 ((re-search-forward
3571 ;; Delimiter can be special char escape \[xxx],
3572 ;; \(xx or single normal char (usually '):
3573 "\\=\\\\w\\(\\\\\\[[^]]+\\]\\|\\\\(..\\|.\\)" nil t)
3574 (let ((from (match-end 0))
3575 (delim (regexp-quote (match-string 1))))
3576 (if (re-search-forward delim nil t)
3577 ;; Return width of string:
3578 (- (match-beginning 0) from)
3579 (WoMan-warn "Width escape delimiter error!"))))
3581 (if (null n)
3582 ;; ERROR -- should handle this better!
3583 (progn
3584 (WoMan-warn "Numeric/register argument error: %s"
3585 (buffer-substring
3586 (point)
3587 (save-excursion (end-of-line) (point))))
3588 (skip-syntax-forward "^ ")
3590 (goto-char (match-end 0))
3591 ;; Check for scale factor:
3593 (cond
3594 ((looking-at "\\s ") nil) ; stay put!
3595 ((looking-at "[mnuv]")) ; ignore for now
3596 ((looking-at "i") (setq n (* n 10))) ; inch
3597 ((looking-at "c") (setq n (* n 3.9))) ; cm
3598 ((looking-at "P") (setq n (* n 1.7))) ; Pica
3599 ((looking-at "p") (setq n (* n 0.14))) ; point
3600 ;; NB: May be immediately followed by + or -, etc.,
3601 ;; in which case do nothing and return nil.
3603 (goto-char (match-end 0)))
3604 (if (numberp n) (round n) n))
3608 ;;; VERTICAL FORMATTING -- Formatting macros that cause a break:
3610 ;; Vertical spacing philosophy:
3611 ;; Delete all vertical space as it is encountered. Then insert
3612 ;; vertical space only before text, as required.
3614 (defun woman2-roff-buffer ()
3615 "Process breaks. Format paragraphs and headings."
3616 (let ((case-fold-search t)
3617 (to (make-marker))
3618 (canonically-space-region
3619 (symbol-function 'canonically-space-region))
3620 (insert-and-inherit (symbol-function 'insert-and-inherit))
3621 (set-text-properties (symbol-function 'set-text-properties))
3622 (woman-registers woman-registers)
3623 fn request translations
3624 tab-stop-list)
3625 ;; ?roff does not squeeze multiple spaces, but does fill, so...
3626 (fset 'canonically-space-region 'ignore)
3627 ;; Try to avoid spaces inheriting underlines from preceding text!
3628 (fset 'insert-and-inherit (symbol-function 'insert))
3629 (fset 'set-text-properties 'ignore)
3630 (unwind-protect
3631 (while
3632 ;; Find next control line:
3633 (re-search-forward woman-request-regexp nil t)
3634 (cond
3635 ;; Construct woman function to call:
3636 ((setq fn (intern-soft
3637 (concat "woman2-"
3638 (setq request (match-string 1)))))
3639 ;; Delete request or macro name:
3640 (woman-delete-match 0))
3641 ;; Unrecognised request:
3642 ((prog1 nil
3643 ;; (WoMan-warn ".%s request ignored!" request)
3644 (WoMan-warn-ignored request "ignored!")
3645 ;; (setq fn 'woman2-LP)
3646 ;; AVOID LEAVING A BLANK LINE!
3647 ;; (setq fn 'woman2-format-paragraphs)
3649 ;; .LP assumes it is at eol and leaves a (blank) line,
3650 ;; so leave point at end of line before paragraph:
3651 ((or (looking-at "[ \t]*$") ; no argument
3652 woman-ignore) ; ignore all
3653 ;; (beginning-of-line) (kill-line)
3654 ;; AVOID LEAVING A BLANK LINE!
3655 (beginning-of-line) (woman-delete-line 1))
3656 (t (end-of-line) (insert ?\n))
3658 (if (not (or fn
3659 (and (not (memq (following-char) '(?. ?')))
3660 (setq fn 'woman2-format-paragraphs))))
3662 ;; Find next control line:
3663 (set-marker to (woman-find-next-control-line))
3664 ;; Call the appropriate function:
3665 (funcall fn to)))
3666 (if (not (eobp)) ; This should not happen, but ...
3667 (woman2-format-paragraphs (point-max-marker) woman-left-margin))
3668 (fset 'canonically-space-region canonically-space-region)
3669 (fset 'set-text-properties set-text-properties)
3670 (fset 'insert-and-inherit insert-and-inherit)
3671 (set-marker to nil))))
3673 (defun woman-find-next-control-line ()
3674 "Find and return start of next control line."
3675 ; (let ((to (save-excursion
3676 ; (re-search-forward "^\\." nil t))))
3677 ; (if to (1- to) (point-max)))
3678 (let (to)
3679 (save-excursion
3680 ;; Must handle
3681 ;; ...\c
3682 ;; .br (and other requests?)
3683 ;; by deleting both the \c and the following request.
3684 ;; BEWARE THAT THIS CODE MAY BE UNRELIABLE!!!!!
3685 (while
3686 (and
3687 (setq to (re-search-forward "\\(\\\\c\\)?\n[.']" nil t))
3688 (match-string 1)
3689 (looking-at "br"))
3690 (goto-char (match-beginning 0))
3691 (woman-delete-line 2)))
3692 (if to (1- to) (point-max))))
3694 (defun woman2-PD (to)
3695 ".PD d -- Set the interparagraph distance to d.
3696 Round to whole lines, default 1 line. Format paragraphs upto TO.
3697 \(Breaks, but should not.)"
3698 ;; .ie \\n[.$] .nr PD (v;\\$1)
3699 ;; .el .nr PD .4v>?\n[.V]
3700 (woman-set-interparagraph-distance)
3701 (woman2-format-paragraphs to))
3703 (defun woman-set-interparagraph-distance ()
3704 "Set the interparagraph distance from a .PD request at point."
3705 (setq woman-interparagraph-distance
3706 (if (eolp) 1 (woman-get-numeric-arg)))
3707 ;; Should allow .PD 0 to set zero line spacing
3708 (woman-delete-line 1)) ; ignore remaining args
3710 (defsubst woman-interparagraph-space ()
3711 "Set variable `woman-leave-blank-lines' from `woman-interparagraph-distance'."
3712 ; (if (> woman-interparagraph-distance 0)
3713 ; (forward-line 1) ; leave 1 blank line
3714 ; (woman-delete-line 1)) ; do not leave blank line
3715 (setq woman-leave-blank-lines woman-interparagraph-distance)
3718 (defun woman2-TH (to)
3719 ".TH n c x v m -- Begin a man page. Format paragraphs upto TO.
3720 n is the name of the page in chapter c\; x is extra commentary\;
3721 v alters page foot left; m alters page head center.
3722 \(Should set prevailing indent and tabs to 5.)"
3723 (woman-forward-arg 'unquote 'concat)
3724 (insert ?\()
3725 (woman-forward-arg 'unquote 'concat)
3726 (insert ?\))
3727 (let ((start (point)) here)
3728 (while (not (eolp))
3729 (cond ((looking-at "\"\"[ \t]")
3730 (delete-char 2)
3731 ;; (delete-horizontal-space)
3733 (delete-horizontal-space)
3734 (setq here (point))
3735 (insert " -- ")
3736 (woman-forward-arg 'unquote 'concat)
3737 ;; Delete repeated arguments:
3738 (if (string-match (buffer-substring here (point))
3739 (buffer-substring start here))
3740 (delete-region here (point)))
3742 ;; Embolden heading (point is at end of heading):
3743 (woman-set-face
3744 (save-excursion (beginning-of-line) (point)) (point) 'woman-bold)
3745 (forward-line)
3746 (delete-blank-lines)
3747 (setq woman-left-margin woman-default-indent)
3748 (setq woman-prevailing-indent woman-default-indent)
3749 (woman2-format-paragraphs to woman-left-margin))
3751 (defun woman2-SH (to)
3752 ".SH -- Sub-head. Leave blank line and subhead.
3753 Format paragraphs upto TO. Set prevailing indent to 5."
3754 (if (eolp) ; If no args then
3755 (delete-char 1) ; apply to next line
3756 (woman-unquote-args) ; else unquote to end of heading
3757 (beginning-of-line))
3758 (woman2-process-escapes-to-eol)
3759 (woman-leave-blank-lines woman-interparagraph-distance)
3760 (setq woman-leave-blank-lines nil)
3761 ;; Optionally embolden heading (point is at beginning of heading):
3762 (if woman-bold-headings
3763 (woman-set-face
3764 (point) (save-excursion (end-of-line) (point)) 'woman-bold))
3765 (forward-line)
3766 (setq woman-left-margin woman-default-indent
3767 woman-nofill nil) ; fill output lines
3768 (setq woman-prevailing-indent woman-default-indent)
3769 (woman2-format-paragraphs to woman-left-margin))
3771 (defun woman2-SS (to)
3772 ".SS -- Sub-sub-head. Like .SH but indent heading 3 spaces.
3773 Format paragraphs upto TO."
3774 (if (eolp) ; If no args then
3775 (delete-char 1)) ; apply to next line.
3776 (insert " ")
3777 (beginning-of-line)
3778 (woman2-SH to))
3780 (defun woman2-LP (to)
3781 ".LP,.PP -- Begin paragraph. Set prevailing indent to 5.
3782 Leave 1 blank line. Format paragraphs upto TO."
3783 (woman-delete-line 1) ; ignore any arguments
3784 (woman-interparagraph-space)
3785 (setq woman-prevailing-indent woman-default-indent)
3786 (woman2-format-paragraphs to woman-left-margin))
3788 (defalias 'woman2-PP 'woman2-LP)
3789 (defalias 'woman2-P 'woman2-LP)
3791 (defun woman2-ns (to)
3792 ".ns -- Turn on no-space mode. Format paragraphs upto TO."
3793 ;; Should not cause a break!
3794 (woman-delete-line 1) ; ignore argument(s)
3795 (setq woman-nospace t)
3796 (woman2-format-paragraphs to))
3798 (defun woman2-rs (to)
3799 ".rs -- Turn off no-space mode. Format paragraphs upto TO."
3800 ;; Should not cause a break!
3801 (woman-delete-line 1) ; ignore argument(s)
3802 (setq woman-nospace nil)
3803 (woman2-format-paragraphs to))
3805 (defun woman2-sp (to)
3806 ".sp N -- If N > 0 then leave 1 blank line. Format paragraphs upto TO."
3807 (let ((N (if (eolp) 1 (woman-get-numeric-arg))))
3808 (if (>= N 0)
3809 (woman-delete-line 1) ; ignore argument(s)
3810 (setq woman-negative-vertical-space t)
3811 (insert ".sp ")
3812 (forward-line))
3813 (setq woman-leave-blank-lines N)
3814 (woman2-format-paragraphs to)))
3816 (defun woman-negative-vertical-space (from)
3817 ".sp N with N < 0 => overlap following with preceding lines at FROM."
3818 ;; Run by woman-decode-region if necessary -- not usually required.
3819 (WoMan-warn "Negative vertical spacing support is experimental!")
3820 (goto-char from)
3821 (while
3822 ;; Find next control line:
3823 (re-search-forward "^\\.sp " nil t)
3824 (let ((N (woman-get-numeric-arg))
3825 overlap overwritten)
3826 (woman-delete-whole-line)
3827 (setq from (point)
3828 overlap (buffer-substring from
3829 (progn (forward-line (- N)) (point))))
3830 (delete-region from (point))
3831 (forward-line N)
3832 (let ((imax (length overlap))
3833 (i 0) c)
3834 (while (< i imax)
3835 (setq c (aref overlap i))
3836 (cond ((eq c ?\n) ; skip
3837 (forward-line))
3838 ((eolp) ; extend line
3839 ;; Insert character INCLUDING TEXT PROPERTIES:
3840 ;; (insert (substring overlap i (1+ i)))
3841 (let ((eol (string-match "\n" overlap i)))
3842 (insert (substring overlap i eol))
3843 (setq i (or eol imax)))
3845 ((eq c ?\ ) ; skip
3846 (forward-char))
3847 ((eq c ?\t) ; skip
3848 (if (eq (following-char) ?\t)
3849 (forward-char) ; both tabs, just skip
3850 (let ((i woman-tab-width))
3851 (while (> i 0)
3852 (if (eolp)
3853 (insert ?\ ) ; extend line
3854 (forward-char)) ; skip
3855 (setq i (1- i)))
3858 (if (or (eq (following-char) ?\ ) ; overwrite OK
3859 overwritten) ; warning only once per ".sp -"
3861 (setq overwritten t)
3862 (WoMan-warn
3863 "Character(s) overwritten by negative vertical spacing in line %d"
3864 (count-lines 1 (point))))
3865 (delete-char 1) (insert (substring overlap i (1+ i)))))
3866 (setq i (1+ i))
3871 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3872 ;; The following function should probably do ALL width and number
3873 ;; register interpolation.
3874 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3876 (defun woman2-process-escapes (to &optional numeric)
3877 "Process remaining escape sequences up to marker TO, preserving point.
3878 Optional argument NUMERIC, if non-nil, means the argument is numeric."
3879 ;; The first two cases below could be merged (maybe)!
3880 (let ((from (point)))
3881 ;; Discard zero width filler character used to hide leading dots
3882 ;; and zero width characters \|, \^:
3883 (while (re-search-forward "\\\\[&|^]" to t)
3884 (woman-delete-match 0))
3885 (goto-char from)
3886 ;; Interrupt text processing -- CONTINUE current text with the
3887 ;; next text line (after any control lines, unless processing to
3888 ;; eol):
3889 (while (re-search-forward "\\\\c.*\n?" to t)
3890 (woman-delete-match 0))
3891 ;; but do not delete the final newline ...
3892 (if (and (or (eobp) (= (point) to)) (not (bolp)))
3893 (insert-before-markers ?\n))
3894 (goto-char from)
3895 (woman-translate to)
3896 (goto-char from)
3897 (woman-special-characters to)
3898 (goto-char from)
3899 ;; Printable version of the current escape character, ASSUMED to be `\'
3900 ;; This must be done LAST of all escape processing!
3901 ;; Done like this to preserve any text properties of the `\'
3902 (while (search-forward "\\" to t)
3903 (let ((c (following-char)))
3904 (cond ((eq c ?') ; \' -> '
3905 (delete-char -1)
3906 (cond (numeric ; except in numeric args, \' -> `
3907 (delete-char 1)
3908 (insert ?`))))
3909 ((eq c ?\( )) ; uninterpreted special character
3910 ; \(.. -- do nothing
3911 ((eq c ?t) ; non-interpreted tab \t
3912 (delete-char 1)
3913 (delete-char -1)
3914 (insert "\t"))
3915 ((and numeric
3916 (memq c '(?w ?n ?h)))) ; leave \w, \n, \h (?????)
3917 ((eq c ?l) (woman-horizontal-line))
3919 ;; \? -> ? where ? is any remaining character
3920 (WoMan-warn "Escape ignored: \\%c -> %c" c c)
3921 (delete-char -1))
3923 (goto-char from)
3924 ;; Process non-default tab settings:
3925 (cond (tab-stop-list
3926 (while (search-forward "\t" to t)
3927 (woman-tab-to-tab-stop))
3928 (goto-char from)))
3930 ;; Must replace \' by something before processing \w, done above.
3932 ;; Replace all `\w' and `\n' escapes:
3933 ;; (This may be a bit too recursive!)
3934 (while (re-search-forward "\\\\[nw]" to t)
3935 (let ((from (match-beginning 0)) N)
3936 (goto-char from)
3937 (setq N (woman-parse-numeric-value))
3938 (delete-region from (point))
3939 ;; Interpolate value:
3940 (insert-before-markers (number-to-string N))))
3941 (goto-char from)))
3943 (defun woman-horizontal-line ()
3944 "\\l'Nc' -- Draw a horizontal line of length N using character c, default _."
3945 (delete-char -1)
3946 (delete-char 1)
3947 (looking-at "\\(.\\)\\(.*\\)\\1")
3948 (let ((to (make-marker)) from N c)
3949 (set-marker to (match-end 2))
3950 (delete-char 1)
3951 (setq from (point)
3952 N (woman-parse-numeric-arg))
3953 (setq c (if (< (point) to) (following-char) ?_))
3954 (delete-region from to)
3955 (delete-char 1)
3956 (set-marker to nil)
3957 (insert (make-string N c))
3960 ;;; 4. Text Filling, Adjusting, and Centering
3962 (defun woman2-br (to)
3963 ".br -- Break. Leave no blank line. Format paragraphs upto TO."
3964 (woman-delete-line 1) ; ignore any arguments
3965 (woman2-format-paragraphs to))
3967 (defun woman2-fi (to)
3968 ".fi -- Fill subsequent output lines. Leave no blank line.
3969 Format paragraphs upto TO."
3970 (setq woman-nofill nil)
3971 (woman-delete-line 1) ; ignore any arguments
3972 ;; Preserve any final blank line in the nofill region:
3973 (save-excursion
3974 (forward-line -1)
3975 (if (looking-at "[ \t]*$") (setq woman-leave-blank-lines 1)))
3976 (woman2-format-paragraphs to))
3978 (defun woman2-nf (to)
3979 ".nf -- Nofill. Subsequent lines are neither filled nor adjusted.
3980 Input text lines are copied directly to output lines without regard
3981 for the current line length. Format paragraphs upto TO."
3982 (setq woman-nofill t)
3983 (woman-delete-line 1) ; ignore any arguments
3984 (woman2-format-paragraphs to))
3986 (defun woman2-ad (to)
3987 ".ad c -- Line adjustment is begun (once fill mode is on).
3988 Set justification mode to c if specified.
3989 Format paragraphs upto TO. (Breaks, but should not.)"
3990 ;; c = l -- left, r -- right, c -- center, b or n -- both,
3991 ;; absent -- unchanged. Initial mode adj,both.
3992 (setq woman-adjust
3993 (cond ((eolp) woman-adjust-previous)
3994 ((eq (following-char) ?l) woman-adjust-left)
3995 ((eq (following-char) ?r) woman-adjust-right)
3996 ((eq (following-char) ?c) woman-adjust-center)
3997 ((memq (following-char) '(?b ?n)) woman-adjust-both)
3998 (t (woman-get-numeric-arg))
4000 woman-justify (nth woman-adjust woman-justify-list))
4001 (woman-delete-line 1) ; ignore any remaining arguments
4002 (woman2-format-paragraphs to))
4004 (defun woman2-na (to)
4005 ".na -- No adjusting. Format paragraphs upto TO.
4006 \(Breaks, but should not.)"
4007 (setq woman-adjust-previous woman-adjust
4008 woman-justify-previous woman-justify
4009 woman-adjust woman-adjust-left ; fill but do not adjust
4010 woman-justify (nth woman-adjust woman-justify-list))
4011 (woman-delete-line 1) ; ignore any arguments
4012 (woman2-format-paragraphs to))
4014 ;;; The main formatting functions:
4016 (defun woman-leave-blank-lines (&optional leave)
4017 "Delete all blank lines around point.
4018 Leave one blank line if optional argument LEAVE is non-nil and
4019 non-zero, or if LEAVE is nil and variable `woman-leave-blank-lines' is
4020 non-nil and non-zero."
4021 ;; ***** It may suffice to delete only lines ABOVE point! *****
4022 ;; NOTE: Function arguments are evaluated left to right
4023 ;; (*note (elisp)Function Forms::.).
4024 (delete-region
4025 (save-excursion
4026 (if (not (eq (skip-syntax-backward " ") 0))
4027 (forward-line)) ; forward-char ?
4028 (point))
4029 (progn (skip-syntax-forward " ")
4030 (beginning-of-line)
4031 (point)))
4032 (if woman-nospace
4034 (if (or (null leave) (eq leave 0))
4035 ;; output any `pending' vertical space ...
4036 (setq leave woman-leave-blank-lines))
4037 (if (and leave (> leave 0)) (insert-before-markers ?\n))
4039 (setq woman-leave-blank-lines nil)
4042 ;; `fill-region-as-paragraph' in `fill.el' appears to be the principal
4043 ;; text filling function, so that is what I use here.
4045 (defvar woman-temp-indent nil)
4047 (defun woman2-format-paragraphs (to &optional new-left)
4048 "Indent, fill and adjust paragraphs upto TO to current left margin.
4049 If optional arg NEW-LEFT is non-nil then reset current left margin.
4050 If `woman-nofill' is non-nil then indent without filling or adjusting."
4051 ;; Blank space should only ever be output before text.
4052 (if new-left (setq left-margin new-left))
4053 (if (looking-at "^\\s *$")
4054 ;; A blank line should leave a space like .sp 1 (p. 14).
4055 (setq woman-leave-blank-lines 1))
4056 (skip-syntax-forward " ")
4057 ;; Successive control lines are sufficiently common to be worth a
4058 ;; special case (maybe):
4059 (if (>= (point) to) ; >= as a precaution!
4061 ;; (woman-leave-blank-lines)
4062 (woman-reset-nospace)
4063 ;; (woman2-process-escapes to) ; 7 October 1999
4064 (woman2-process-escapes to 'numeric)
4065 (if woman-nofill
4066 ;; Indent without filling or adjusting ...
4067 (progn
4068 (woman-leave-blank-lines)
4069 (cond (woman-temp-indent
4070 (indent-to woman-temp-indent)
4071 (forward-line)))
4072 (indent-rigidly (point) to left-margin)
4073 (woman-horizontal-escapes to)) ; 7 October 1999
4074 ;; Fill and justify ...
4075 ;; Blank lines and initial spaces cause a break.
4076 ; (cond ((and (= (point) to) (not (looking-at ".nf"))) ; Yuk!!!
4077 ; ;; No text after a request that caused a break, so delete
4078 ; ;; any spurious blank line left:
4079 ; (forward-line -1)
4080 ; (if (looking-at "^\\s *$") (kill-line) (forward-line))))
4081 (while (< (point) to)
4082 (woman-leave-blank-lines)
4083 (let ((from (point)))
4084 ;; Indent first lin of paragraph:
4085 (indent-to (or woman-temp-indent left-margin))
4086 (woman-horizontal-escapes to) ; 7 October 1999
4087 ;; Find the beginning of the next paragraph:
4088 (forward-line)
4089 ; (if (re-search-forward "\\(^\\s *$\\)\\|\\(^\\s +\\)" to 1)
4090 ; ;; A blank line should leave a space like .sp 1 (p. 14).
4091 ; (if (eolp)
4092 ; (progn
4093 ; (skip-syntax-forward " ")
4094 ; (setq woman-leave-blank-lines 1))
4095 ; (setq woman-leave-blank-lines nil)))
4096 (and (re-search-forward "\\(^\\s *$\\)\\|\\(^\\s +\\)" to 1)
4097 ;; A blank line should leave a space like .sp 1 (p. 14).
4098 (eolp)
4099 (skip-syntax-forward " ")
4100 (setq woman-leave-blank-lines 1))
4101 (beginning-of-line)
4102 ;; If a single short line then just leave it.
4103 ;; This is necessary to preserve some table layouts.
4104 ;; PROBABLY NOT NECESSARY WITH SQUEEZE MODIFICATION !!!!!
4105 (if (or (> (count-lines from (point)) 1)
4106 (save-excursion
4107 (backward-char)
4108 (> (current-column) fill-column)))
4109 ;; ?roff does not squeeze multiple spaces
4110 ;; (fill-region-as-paragraph from (point) woman-justify t)
4111 ;; NOSQUEEZE has no effect if JUSTIFY is full, so
4112 ;; redefine canonically-space-region, see above.
4113 (progn
4114 ;; Needs a re-write of the paragraph formatter to
4115 ;; avoid this nonsense to handle temporary indents!
4116 (if (and woman-temp-indent (< woman-temp-indent left-margin))
4117 (let ((left-margin woman-temp-indent))
4118 (fill-region-as-paragraph from (point) woman-justify)
4119 (save-excursion
4120 (goto-char from)
4121 (forward-line)
4122 (setq from (point)))))
4123 (fill-region-as-paragraph from (point) woman-justify))
4125 ;; A blank line should leave a space like .sp 1 (p. 14).
4126 ;; Delete all but 1 trailing blank lines:
4127 ;;(woman-leave-blank-lines 1)
4130 (setq woman-temp-indent nil)
4131 ;; Non-white-space text has been processed, so ...
4132 ;;(setq woman-leave-blank-lines nil)
4136 ;;; Tagged, indented and hanging paragraphs:
4138 (defun woman2-TP (to)
4139 ".TP i -- Set prevailing indent to i. Format paragraphs upto TO.
4140 Begin indented paragraph with hanging tag given by next text line.
4141 If tag doesn't fit, place it on a separate line."
4142 (let ((i (woman2-get-prevailing-indent)))
4143 (woman-leave-blank-lines woman-interparagraph-distance)
4144 (woman2-tagged-paragraph to i)))
4146 (defun woman2-IP (to)
4147 ".IP x i -- Same as .TP with tag x. Format paragraphs upto TO."
4148 (woman-interparagraph-space)
4149 (if (eolp) ; no args
4150 ;; Like LP without resetting prevailing indent
4151 (woman2-format-paragraphs to (+ woman-left-margin
4152 woman-prevailing-indent))
4153 (woman-forward-arg 'unquote)
4154 (let ((i (woman2-get-prevailing-indent 'leave-eol)))
4155 (beginning-of-line)
4156 (woman-leave-blank-lines) ; must be here,
4157 (woman2-tagged-paragraph to i))))
4159 (defun woman-find-next-control-line-carefully ()
4160 "Find and return start of next control line, even if already there!"
4161 (if (looking-at "^[.']")
4162 (point)
4163 (woman-find-next-control-line)))
4165 (defun woman2-tagged-paragraph (to i)
4166 "Begin indented paragraph with hanging tag given by current text line.
4167 If tag doesn't fit, leave it on separate line.
4168 Format paragraphs upto TO. Set prevailing indent to I."
4169 (if (not (looking-at "\\s *$")) ; non-empty tag
4170 (setq woman-leave-blank-lines nil))
4172 ;; Temporary hack for bash.1 and groff_mmse.7 until code is revised
4173 ;; to process all requests uniformly:
4174 (cond ((and (= (point) to) (looking-at "^[.'][ \t]*\\(PD\\|br\\|ta\\) *"))
4175 (if (string= (match-string 1) "br")
4176 (woman-delete-line 1)
4177 (woman-delete-match 0)
4178 (if (string= (match-string 1) "ta") ; for GetInt.3
4179 (woman2-ta to)
4180 (woman-set-interparagraph-distance)))
4181 (set-marker to (woman-find-next-control-line-carefully))
4184 (let ((tag (point)))
4185 (woman-reset-nospace)
4186 ;; Format the tag:
4187 (woman2-process-escapes-to-eol)
4188 ;; TIDY UP THE FOLLOWING CODE
4189 ;; (indent-to woman-left-margin)
4190 (setq left-margin woman-left-margin)
4191 (forward-line)
4192 (fill-region-as-paragraph (save-excursion (forward-line -1) (point))
4193 (point) woman-justify)
4195 ;; Temporary hack for bash.1 until all requests processed uniformly:
4196 (cond ((and (= (point) to) (looking-at "^[.'][ \t]*PD *"))
4197 (woman-delete-match 0)
4198 (woman-set-interparagraph-distance)
4199 (set-marker to (woman-find-next-control-line-carefully))
4202 ;; Format the paragraph body, if there is one! Set indented left
4203 ;; margin anyway, because the paragraph body may begin with a
4204 ;; control line:
4205 (setq left-margin (+ woman-left-margin i))
4206 (cond ((< (point) to)
4207 (woman2-format-paragraphs to)
4208 (goto-char tag) (end-of-line)
4209 (cond ((> (setq i (- left-margin (current-column))) 0)
4210 (delete-char 1)
4211 (delete-horizontal-space)
4212 ;; Necessary to avoid spaces inheriting underlines.
4213 ;; Cannot simply delete (current-column) whitespace
4214 ;; characters because some may be tabs!
4215 (while (> i 0) (insert ? ) (setq i (1- i)))))
4216 (goto-char to) ; necessary ???
4220 (defun woman2-HP (to)
4221 ".HP i -- Set prevailing indent to i. Format paragraphs upto TO.
4222 Begin paragraph with hanging indent."
4223 (let ((i (woman2-get-prevailing-indent)))
4224 (woman-interparagraph-space)
4225 (setq woman-temp-indent woman-left-margin)
4226 (woman2-format-paragraphs to (+ woman-left-margin i))
4229 (defun woman2-get-prevailing-indent (&optional leave-eol)
4230 "Set prevailing indent to integer argument at point, and return it.
4231 If no argument then return the existing prevailing indent.
4232 Delete line from point and eol unless LEAVE-EOL is non-nil."
4233 (if (eolp)
4234 (or leave-eol (delete-char 1))
4235 (let ((i (woman-get-numeric-arg)))
4236 (woman-delete-line) (or leave-eol (delete-char 1))
4237 ;; i = 0 if the argument was not a number
4238 (if (> i 0) (setq woman-prevailing-indent i))))
4239 woman-prevailing-indent)
4241 (defmacro woman-push (value stack)
4242 "Push VALUE onto STACK."
4243 `(setq ,stack (cons ,value ,stack)))
4245 (defmacro woman-pop (variable stack)
4246 "Pop into VARIABLE the value at the top of STACK.
4247 Allow for mismatched requests!"
4248 `(if ,stack
4249 (setq ,variable (car ,stack)
4250 ,stack (cdr ,stack))))
4252 (defun woman2-RS (to)
4253 ".RS i -- Start relative indent, move left margin in distance i.
4254 Set prevailing indent to 5 for nested indents. Format paragraphs upto TO."
4255 (woman-push woman-left-margin woman-RS-left-margin)
4256 (woman-push woman-prevailing-indent woman-RS-prevailing-indent)
4257 (setq woman-left-margin (+ woman-left-margin
4258 (woman2-get-prevailing-indent))
4259 woman-prevailing-indent woman-default-indent)
4260 (woman2-format-paragraphs to woman-left-margin))
4262 (defun woman2-RE (to)
4263 ".RE -- End of relative indent. Format paragraphs upto TO.
4264 Set prevailing indent to amount of starting .RS."
4265 (woman-pop woman-left-margin woman-RS-left-margin)
4266 (woman-pop woman-prevailing-indent woman-RS-prevailing-indent)
4267 (woman-delete-line 1) ; ignore any arguments
4268 (woman2-format-paragraphs to woman-left-margin))
4271 ;;; Line Length and Indenting:
4273 (defun woman-set-arg (arg &optional previous)
4274 "Reset, increment or decrement argument ARG, which must be quoted.
4275 If no argument then use value of optional arg PREVIOUS if non-nil,
4276 otherwise set PREVIOUS. Delete the whole remaining control line."
4277 (if (eolp) ; space already skipped
4278 (set arg (if previous (eval previous) 0))
4279 (if previous (set previous (eval arg)))
4280 (woman2-process-escapes-to-eol 'numeric)
4281 (let ((pm (if (looking-at "[+-]")
4282 (prog1 (following-char)
4283 (forward-char 1))))
4284 (i (woman-parse-numeric-arg)))
4285 (cond ((null pm) (set arg i))
4286 ((= pm ?+) (set arg (+ (eval arg) i)))
4287 ((= pm ?-) (set arg (- (eval arg) i)))
4289 (beginning-of-line))
4290 (woman-delete-line 1)) ; ignore any remaining arguments
4292 ;; NEED TO RATIONALIZE NAMES FOR PREVIOUS VALUES!
4293 (defvar woman-ll-fill-column woman-fill-column)
4294 (defvar woman-in-left-margin woman-left-margin)
4296 (defun woman2-ll (to)
4297 ".ll +/-N -- Set, increment or decrement line length.
4298 Format paragraphs upto TO. (Breaks, but should not.)"
4299 (woman-set-arg 'fill-column 'woman-ll-fill-column)
4300 (woman2-format-paragraphs to))
4302 (defun woman2-in (to)
4303 ".in +/-N -- Set, increment or decrement the indent.
4304 Format paragraphs upto TO."
4305 (woman-set-arg 'left-margin 'woman-in-left-margin)
4306 (woman2-format-paragraphs to))
4308 (defun woman2-ti (to)
4309 ".ti +/-N -- Temporary indent. Format paragraphs upto TO."
4310 ;; Ignore if no argument.
4311 ;; Indent next output line only wrt current indent.
4312 ;; Current indent is not changed.
4313 (setq woman-temp-indent left-margin)
4314 (woman-set-arg 'woman-temp-indent)
4315 (woman2-format-paragraphs to nil))
4318 ;;; Tabs, Leaders, and Fields:
4320 (defun woman2-ta (to)
4321 ".ta Nt ... -- Set tabs, left type, unless t=R(right), C(centered).
4322 \(Breaks, but should not.) The tab stops are separated by spaces\;
4323 a value preceded by + represents an increment to the previous stop value.
4324 Format paragraphs upto TO."
4325 (setq tab-stop-list nil)
4326 (woman2-process-escapes-to-eol 'numeric)
4327 (save-excursion
4328 (let ((tab-stop 0))
4329 (while (not (eolp))
4330 (let ((plus (cond ((eq (following-char) ?+) (forward-char 1) t)))
4331 (i (woman-parse-numeric-arg)))
4332 (setq tab-stop (if plus (+ tab-stop i) i)))
4333 (if (memq (following-char) '(?R ?C))
4334 (setq tab-stop (cons tab-stop (following-char))))
4335 (setq tab-stop-list (cons tab-stop tab-stop-list))
4336 (skip-syntax-forward "^ ") ; skip following R, C, `;', etc.
4337 (skip-chars-forward " \t")
4339 (woman-delete-line 1) ; ignore any remaining arguments
4340 (setq tab-stop-list (reverse tab-stop-list))
4341 (woman2-format-paragraphs to))
4343 (defsubst woman-get-tab-stop (tab-stop-list)
4344 "If TAB-STOP-LIST is a cons, return its car, else return TAB-STOP-LIST."
4345 (if (consp tab-stop-list) (car tab-stop-list) tab-stop-list))
4347 (defun woman-tab-to-tab-stop ()
4348 "Insert spaces to next defined tab-stop column.
4349 The variable `tab-stop-list' is a list whose elements are either left
4350 tab stop columns or pairs (COLUMN . TYPE) where TYPE is R or C."
4351 ;; Based on tab-to-tab-stop in indent.el.
4352 ;; R & C tabs probably not quite right!
4353 (delete-backward-char 1)
4354 (let ((tabs tab-stop-list))
4355 (while (and tabs (>= (current-column)
4356 (woman-get-tab-stop (car tabs))))
4357 (setq tabs (cdr tabs)))
4358 (if tabs
4359 (let* ((tab (car tabs))
4360 (type (and (consp tab) (cdr tab)))
4361 eol n)
4362 (if type
4363 (setq tab (woman-get-tab-stop tab)
4364 eol (save-excursion (end-of-line) (point))
4365 n (save-excursion
4366 (search-forward "\t" eol t))
4367 n (- (if n (1- n) eol) (point))
4368 tab (- tab (if (eq type ?C) (/ n 2) n))) )
4369 (setq n (- tab (current-column)))
4370 (while (> n 0)
4371 (insert ?\ )
4372 (setq n (1- n))))
4373 (insert ?\ ))))
4375 (defun woman2-DT (to)
4376 ".DT -- Restore default tabs. Format paragraphs upto TO.
4377 \(Breaks, but should not.)"
4378 ;; Currently just terminates special tab processing.
4379 (setq tab-stop-list nil)
4380 (woman-delete-line 1) ; ignore any arguments
4381 (woman2-format-paragraphs to))
4383 (defun woman2-fc (to)
4384 ".fc a b -- Set field delimiter a and pad character b.
4385 Format paragraphs upto TO.
4386 A VERY FIRST ATTEMPT to make fields at least readable!
4387 Needs doing properly!"
4388 (if (eolp)
4389 (woman-delete-whole-line) ; ignore!
4390 (let ((delim (following-char))
4391 (pad ?\ ) end) ; pad defaults to space
4392 (forward-char)
4393 (skip-chars-forward " \t")
4394 (or (eolp) (setq pad (following-char)))
4395 (woman-delete-whole-line)
4396 (save-excursion
4397 (if (re-search-forward "^[.'][ \t]*fc\\s " nil t)
4398 (setq end (match-beginning 0))))
4399 ;; A field is contained between a pair of field delimiter
4400 ;; characters and consists of sub-strings separated by padding
4401 ;; indicator characters:
4402 (setq delim (string delim ?[ ?^ delim ?] ?* delim))
4403 (save-excursion
4404 (while (re-search-forward delim end t)
4405 (goto-char (match-beginning 0))
4406 (delete-char 1)
4407 (insert woman-unpadded-space-char)
4408 (goto-char (match-end 0))
4409 (delete-backward-char 1)
4410 (insert-before-markers woman-unpadded-space-char)
4411 (subst-char-in-region
4412 (match-beginning 0) (match-end 0)
4413 pad woman-unpadded-space-char t)
4416 (woman2-format-paragraphs to))
4419 ;;; Preliminary table support (.TS/.TE)
4421 (defun woman2-TS (to)
4422 ".TS -- Start of table code for the tbl processor.
4423 Format paragraphs upto TO."
4424 ;; This is a preliminary hack that seems to suffice for lilo.8.
4425 (woman-delete-line 1) ; ignore any arguments
4426 (when woman-emulate-tbl
4427 ;; Assumes column separator is \t and intercolumn spacing is 3.
4428 ;; The first line may optionally be a list of options terminated by
4429 ;; a semicolon. Currently, just delete it:
4430 (if (looking-at ".*;[ \t]*$") (woman-delete-line 1)) ;
4431 ;; The following lines must specify the format of each line of the
4432 ;; table and end with a period. Currently, just delete them:
4433 (while (not (looking-at ".*\\.[ \t]*$")) (woman-delete-line 1))
4434 (woman-delete-line 1)
4435 ;; For each column, find its width and align it:
4436 (let ((start (point)) (col 1))
4437 (while (prog1 (search-forward "\t" to t) (goto-char start))
4438 ;; Find current column width:
4439 (while (< (point) to)
4440 (when (search-forward "\t" to t)
4441 (backward-char)
4442 (if (> (current-column) col) (setq col (current-column))))
4443 (forward-line))
4444 ;; Align current column:
4445 (goto-char start)
4446 (setq col (+ col 3)) ; intercolumn space
4447 (while (< (point) to)
4448 (when (search-forward "\t" to t)
4449 (delete-char -1)
4450 (insert-char ?\ (- col (current-column))))
4451 (forward-line))
4452 (goto-char start))))
4453 ;; Format table with no filling or adjusting (cf. woman2-nf):
4454 (setq woman-nofill t)
4455 (woman2-format-paragraphs to))
4457 (defalias 'woman2-TE 'woman2-fi)
4458 ;; ".TE -- End of table code for the tbl processor."
4459 ;; Turn filling and adjusting back on.
4462 ;;; WoMan message logging:
4464 ;; The basis for this logging code was shamelessly pirated from bytecomp.el
4465 ;; by Jamie Zawinski <jwz@lucid.com> & Hallvard Furuseth <hbf@ulrik.uio.no>
4467 (defvar WoMan-current-file nil) ; bound in woman-really-find-file
4468 (defvar WoMan-Log-header-point-max nil)
4470 (defun WoMan-log-begin ()
4471 "Log the beginning of formatting in *WoMan-Log*."
4472 (let ((WoMan-current-buffer (buffer-name)))
4473 (save-excursion
4474 (set-buffer (get-buffer-create "*WoMan-Log*"))
4475 (or (eq major-mode 'view-mode) (view-mode 1))
4476 (setq buffer-read-only nil)
4477 (goto-char (point-max))
4478 (insert "\n\^L\nFormatting "
4479 (if (stringp WoMan-current-file)
4480 (concat "file " WoMan-current-file)
4481 (concat "buffer " WoMan-current-buffer))
4482 " at " (current-time-string) "\n")
4483 (setq WoMan-Log-header-point-max (point-max))
4486 (defun WoMan-log (format &rest args)
4487 "Log a message out of FORMAT control string and optional ARGS."
4488 (WoMan-log-1 (apply 'format format args)))
4490 (defun WoMan-warn (format &rest args)
4491 "Log a warning message out of FORMAT control string and optional ARGS."
4492 (setq format (apply 'format format args))
4493 (WoMan-log-1 (concat "** " format)))
4495 (defun WoMan-warn-ignored (request ignored)
4496 "Log a warning message about ignored directive REQUEST.
4497 IGNORED is a string appended to the log message."
4498 (let ((tail
4499 (buffer-substring (point)
4500 (save-excursion (end-of-line) (point)))))
4501 (if (and (> (length tail) 0)
4502 (/= (string-to-char tail) ?\ ))
4503 (setq tail (concat " " tail)))
4504 (WoMan-log-1
4505 (concat "** " request tail " request " ignored))))
4507 (defun WoMan-log-end (time)
4508 "Log the end of formatting in *WoMan-Log*.
4509 TIME specifies the time it took to format the man page, to be printed
4510 with the message."
4511 (WoMan-log-1 (format "Formatting time %d seconds." time) 'end))
4513 (defun WoMan-log-1 (string &optional end)
4514 "Log a message STRING in *WoMan-Log*.
4515 If optional argument END is non-nil then make buffer read-only after
4516 logging the message."
4517 (save-excursion
4518 (set-buffer (get-buffer-create "*WoMan-Log*"))
4519 (setq buffer-read-only nil)
4520 (goto-char (point-max))
4521 (or end (insert " ")) (insert string "\n")
4522 (if end
4523 (setq buffer-read-only t)
4524 (if woman-show-log
4525 (select-window ; to return to
4526 (prog1 (selected-window) ; WoMan window
4527 (select-window (display-buffer (current-buffer)))
4528 (cond (WoMan-Log-header-point-max
4529 (goto-char WoMan-Log-header-point-max)
4530 (forward-line -1)
4531 (recenter 0)))
4532 )))))
4533 nil) ; for woman-file-readable-p etc.
4535 (provide 'woman)
4537 ;;; arch-tag: eea35e90-552f-4712-a94b-d9ffd3db7651
4538 ;;; woman.el ends here