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