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