s/Nullhv/NULL/g;
[p5sagit/p5-mst-13.2.git] / lib / Pod / Man.pm
1 # Pod::Man -- Convert POD data to formatted *roff input.
2 # $Id: Man.pm,v 2.4 2005/03/19 19:40:01 eagle Exp $
3 #
4 # Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005
5 #     Russ Allbery <rra@stanford.edu>
6 # Substantial contributions by Sean Burke <sburke@cpan.org>
7 #
8 # This program is free software; you may redistribute it and/or modify it
9 # under the same terms as Perl itself.
10 #
11 # This module translates POD documentation into *roff markup using the man
12 # macro set, and is intended for converting POD documents written as Unix
13 # manual pages to manual pages that can be read by the man(1) command.  It is
14 # a replacement for the pod2man command distributed with versions of Perl
15 # prior to 5.6.
16 #
17 # Perl core hackers, please note that this module is also separately
18 # maintained outside of the Perl core as part of the podlators.  Please send
19 # me any patches at the address above in addition to sending them to the
20 # standard Perl mailing lists.
21
22 ##############################################################################
23 # Modules and declarations
24 ##############################################################################
25
26 package Pod::Man;
27
28 require 5.005;
29
30 use strict;
31 use subs qw(makespace);
32 use vars qw(@ISA %ESCAPES $PREAMBLE $VERSION);
33
34 use Carp qw(croak);
35 use Pod::Simple ();
36 use POSIX qw(strftime);
37
38 @ISA = qw(Pod::Simple);
39
40 # Don't use the CVS revision as the version, since this module is also in Perl
41 # core and too many things could munge CVS magic revision strings.  This
42 # number should ideally be the same as the CVS revision in podlators, however.
43 $VERSION = 2.04;
44
45 # Set the debugging level.  If someone has inserted a debug function into this
46 # class already, use that.  Otherwise, use any Pod::Simple debug function
47 # that's defined, and failing that, define a debug level of 10.
48 BEGIN {
49     my $parent = defined (&Pod::Simple::DEBUG) ? \&Pod::Simple::DEBUG : undef;
50     unless (defined &DEBUG) {
51         *DEBUG = $parent || sub () { 10 };
52     }
53 }
54
55 # Import the ASCII constant from Pod::Simple.  This is true iff we're in an
56 # ASCII-based universe (including such things as ISO 8859-1 and UTF-8), and is
57 # generally only false for EBCDIC.
58 BEGIN { *ASCII = \&Pod::Simple::ASCII }
59
60 # Pretty-print a data structure.  Only used for debugging.
61 BEGIN { *pretty = \&Pod::Simple::pretty }
62
63 ##############################################################################
64 # Object initialization
65 ##############################################################################
66
67 # Initialize the object and set various Pod::Simple options that we need.
68 # Here, we also process any additional options passed to the constructor or
69 # set up defaults if none were given.  Note that all internal object keys are
70 # in all-caps, reserving all lower-case object keys for Pod::Simple and user
71 # arguments.
72 sub new {
73     my $class = shift;
74     my $self = $class->SUPER::new;
75
76     # Tell Pod::Simple to handle S<> by automatically inserting &nbsp;.
77     $self->nbsp_for_S (1);
78
79     # Tell Pod::Simple to keep whitespace whenever possible.
80     if ($self->can ('preserve_whitespace')) {
81         $self->preserve_whitespace (1);
82     } else {
83         $self->fullstop_space_harden (1);
84     }
85
86     # The =for and =begin targets that we accept.
87     $self->accept_targets (qw/man MAN roff ROFF/);
88
89     # Ensure that contiguous blocks of code are merged together.  Otherwise,
90     # some of the guesswork heuristics don't work right.
91     $self->merge_text (1);
92
93     # Pod::Simple doesn't do anything useful with our arguments, but we want
94     # to put them in our object as hash keys and values.  This could cause
95     # problems if we ever clash with Pod::Simple's own internal class
96     # variables.
97     %$self = (%$self, @_);
98
99     # Initialize various other internal constants based on our arguments.
100     $self->init_fonts;
101     $self->init_quotes;
102     $self->init_page;
103
104     # For right now, default to turning on all of the magic.
105     $$self{MAGIC_CPP}       = 1;
106     $$self{MAGIC_EMDASH}    = 1;
107     $$self{MAGIC_FUNC}      = 1;
108     $$self{MAGIC_MANREF}    = 1;
109     $$self{MAGIC_SMALLCAPS} = 1;
110     $$self{MAGIC_VARS}      = 1;
111
112     return $self;
113 }
114
115 # Translate a font string into an escape.
116 sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] }
117
118 # Determine which fonts the user wishes to use and store them in the object.
119 # Regular, italic, bold, and bold-italic are constants, but the fixed width
120 # fonts may be set by the user.  Sets the internal hash key FONTS which is
121 # used to map our internal font escapes to actual *roff sequences later.
122 sub init_fonts {
123     my ($self) = @_;
124
125     # Figure out the fixed-width font.  If user-supplied, make sure that they
126     # are the right length.
127     for (qw/fixed fixedbold fixeditalic fixedbolditalic/) {
128         my $font = $$self{$_};
129         if (defined ($font) && (length ($font) < 1 || length ($font) > 2)) {
130             croak qq(roff font should be 1 or 2 chars, not "$font");
131         }
132     }
133
134     # Set the default fonts.  We can't be sure portably across different
135     # implementations what fixed bold-italic may be called (if it's even
136     # available), so default to just bold.
137     $$self{fixed}           ||= 'CW';
138     $$self{fixedbold}       ||= 'CB';
139     $$self{fixeditalic}     ||= 'CI';
140     $$self{fixedbolditalic} ||= 'CB';
141
142     # Set up a table of font escapes.  First number is fixed-width, second is
143     # bold, third is italic.
144     $$self{FONTS} = { '000' => '\fR', '001' => '\fI',
145                       '010' => '\fB', '011' => '\f(BI',
146                       '100' => toescape ($$self{fixed}),
147                       '101' => toescape ($$self{fixeditalic}),
148                       '110' => toescape ($$self{fixedbold}),
149                       '111' => toescape ($$self{fixedbolditalic}) };
150 }
151
152 # Initialize the quotes that we'll be using for C<> text.  This requires some
153 # special handling, both to parse the user parameter if given and to make sure
154 # that the quotes will be safe against *roff.  Sets the internal hash keys
155 # LQUOTE and RQUOTE.
156 sub init_quotes {
157     my ($self) = (@_);
158
159     $$self{quotes} ||= '"';
160     if ($$self{quotes} eq 'none') {
161         $$self{LQUOTE} = $$self{RQUOTE} = '';
162     } elsif (length ($$self{quotes}) == 1) {
163         $$self{LQUOTE} = $$self{RQUOTE} = $$self{quotes};
164     } elsif ($$self{quotes} =~ /^(.)(.)$/
165              || $$self{quotes} =~ /^(..)(..)$/) {
166         $$self{LQUOTE} = $1;
167         $$self{RQUOTE} = $2;
168     } else {
169         croak(qq(Invalid quote specification "$$self{quotes}"))
170     }
171
172     # Double the first quote; note that this should not be s///g as two double
173     # quotes is represented in *roff as three double quotes, not four.  Weird,
174     # I know.
175     $$self{LQUOTE} =~ s/\"/\"\"/;
176     $$self{RQUOTE} =~ s/\"/\"\"/;
177 }
178
179 # Initialize the page title information and indentation from our arguments.
180 sub init_page {
181     my ($self) = @_;
182
183     # We used to try first to get the version number from a local binary, but
184     # we shouldn't need that any more.  Get the version from the running Perl.
185     # Work a little magic to handle subversions correctly under both the
186     # pre-5.6 and the post-5.6 version numbering schemes.
187     my @version = ($] =~ /^(\d+)\.(\d{3})(\d{0,3})$/);
188     $version[2] ||= 0;
189     $version[2] *= 10 ** (3 - length $version[2]);
190     for (@version) { $_ += 0 }
191     my $version = join ('.', @version);
192
193     # Set the defaults for page titles and indentation if the user didn't
194     # override anything.
195     $$self{center} = 'User Contributed Perl Documentation'
196         unless defined $$self{center};
197     $$self{release} = 'perl v' . $version
198         unless defined $$self{release};
199     $$self{indent} = 4
200         unless defined $$self{indent};
201
202     # Double quotes in things that will be quoted.
203     for (qw/center release/) {
204         $$self{$_} =~ s/\"/\"\"/g if $$self{$_};
205     }
206 }
207
208 ##############################################################################
209 # Core parsing
210 ##############################################################################
211
212 # This is the glue that connects the code below with Pod::Simple itself.  The
213 # goal is to convert the event stream coming from the POD parser into method
214 # calls to handlers once the complete content of a tag has been seen.  Each
215 # paragraph or POD command will have textual content associated with it, and
216 # as soon as all of a paragraph or POD command has been seen, that content
217 # will be passed in to the corresponding method for handling that type of
218 # object.  The exceptions are handlers for lists, which have opening tag
219 # handlers and closing tag handlers that will be called right away.
220 #
221 # The internal hash key PENDING is used to store the contents of a tag until
222 # all of it has been seen.  It holds a stack of open tags, each one
223 # represented by a tuple of the attributes hash for the tag, formatting
224 # options for the tag (which are inherited), and the contents of the tag.
225
226 # Add a block of text to the contents of the current node, formatting it
227 # according to the current formatting instructions as we do.
228 sub _handle_text {
229     my ($self, $text) = @_;
230     DEBUG > 3 and print "== $text\n";
231     my $tag = $$self{PENDING}[-1];
232     $$tag[2] .= $self->format_text ($$tag[1], $text);
233 }
234
235 # Given an element name, get the corresponding method name.
236 sub method_for_element {
237     my ($self, $element) = @_;
238     $element =~ tr/-/_/;
239     $element =~ tr/A-Z/a-z/;
240     $element =~ tr/_a-z0-9//cd;
241     return $element;
242 }
243
244 # Handle the start of a new element.  If cmd_element is defined, assume that
245 # we need to collect the entire tree for this element before passing it to the
246 # element method, and create a new tree into which we'll collect blocks of
247 # text and nested elements.  Otherwise, if start_element is defined, call it.
248 sub _handle_element_start {
249     my ($self, $element, $attrs) = @_;
250     DEBUG > 3 and print "++ $element (<", join ('> <', %$attrs), ">)\n";
251     my $method = $self->method_for_element ($element);
252
253     # If we have a command handler, we need to accumulate the contents of the
254     # tag before calling it.  Turn off IN_NAME for any command other than
255     # <Para> so that IN_NAME isn't still set for the first heading after the
256     # NAME heading.
257     if ($self->can ("cmd_$method")) {
258         DEBUG > 2 and print "<$element> starts saving a tag\n";
259         $$self{IN_NAME} = 0 if ($element ne 'Para');
260
261         # How we're going to format embedded text blocks depends on the tag
262         # and also depends on our parent tags.  Thankfully, inside tags that
263         # turn off guesswork and reformatting, nothing else can turn it back
264         # on, so this can be strictly inherited.
265         my $formatting = $$self{PENDING}[-1][1];
266         $formatting = $self->formatting ($formatting, $element);
267         push (@{ $$self{PENDING} }, [ $attrs, $formatting, '' ]);
268         DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n";
269     } elsif ($self->can ("start_$method")) {
270         my $method = 'start_' . $method;
271         $self->$method ($attrs, '');
272     } else {
273         DEBUG > 2 and print "No $method start method, skipping\n";
274     }
275 }
276
277 # Handle the end of an element.  If we had a cmd_ method for this element,
278 # this is where we pass along the tree that we built.  Otherwise, if we have
279 # an end_ method for the element, call that.
280 sub _handle_element_end {
281     my ($self, $element) = @_;
282     DEBUG > 3 and print "-- $element\n";
283     my $method = $self->method_for_element ($element);
284
285     # If we have a command handler, pull off the pending text and pass it to
286     # the handler along with the saved attribute hash.
287     if ($self->can ("cmd_$method")) {
288         DEBUG > 2 and print "</$element> stops saving a tag\n";
289         my $tag = pop @{ $$self{PENDING} };
290         DEBUG > 4 and print "Popped: [", pretty ($tag), "]\n";
291         DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n";
292         my $method = 'cmd_' . $method;
293         my $text = $self->$method ($$tag[0], $$tag[2]);
294         if (defined $text) {
295             if (@{ $$self{PENDING} } > 1) {
296                 $$self{PENDING}[-1][2] .= $text;
297             } else {
298                 $self->output ($text);
299             }
300         }
301     } elsif ($self->can ("end_$method")) {
302         my $method = 'end_' . $method;
303         $self->$method;
304     } else {
305         DEBUG > 2 and print "No $method end method, skipping\n";
306     }
307 }
308
309 ##############################################################################
310 # General formatting
311 ##############################################################################
312
313 # Return formatting instructions for a new block.  Takes the current
314 # formatting and the new element.  Formatting inherits negatively, in the
315 # sense that if the parent has turned off guesswork, all child elements should
316 # leave it off.  We therefore return a copy of the same formatting
317 # instructions but possibly with more things turned off depending on the
318 # element.
319 sub formatting {
320     my ($self, $current, $element) = @_;
321     my %options;
322     if ($current) {
323         %options = %$current;
324     } else {
325         %options = (guesswork => 1, cleanup => 1, convert => 1);
326     }
327     if ($element eq 'Data') {
328         $options{guesswork} = 0;
329         $options{cleanup} = 0;
330         $options{convert} = 0;
331     } elsif ($element eq 'X') {
332         $options{guesswork} = 0;
333         $options{cleanup} = 0;
334     } elsif ($element eq 'Verbatim' || $element eq 'C') {
335         $options{guesswork} = 0;
336     }
337     return \%options;
338 }
339
340 # Format a text block.  Takes a hash of formatting options and the text to
341 # format.  Currently, the only formatting options are guesswork, cleanup, and
342 # convert, all of which are boolean.
343 sub format_text {
344     my ($self, $options, $text) = @_;
345     my $guesswork = $$options{guesswork} && !$$self{IN_NAME};
346     my $cleanup = $$options{cleanup};
347     my $convert = $$options{convert};
348
349     # Normally we do character translation, but we won't even do that in
350     # <Data> blocks.
351     if ($convert) {
352         if (ASCII) {
353             $text =~ s/(\\|[^\x00-\x7F])/$ESCAPES{ord ($1)} || "X"/eg;
354         } else {
355             $text =~ s/(\\)/$ESCAPES{ord ($1)} || "X"/eg;
356         }
357     }
358
359     # Cleanup just tidies up a few things, telling *roff that the hyphens are
360     # hard and putting a bit of space between consecutive underscores.
361     if ($cleanup) {
362         $text =~ s/-/\\-/g;
363         $text =~ s/_(?=_)/_\\|/g;
364     }
365
366     # If guesswork is asked for, do that.  This involves more substantial
367     # formatting based on various heuristics that may only be appropriate for
368     # particular documents.
369     if ($guesswork) {
370         $text = $self->guesswork ($text);
371     }
372
373     return $text;
374 }
375
376 # Handles C<> text, deciding whether to put \*C` around it or not.  This is a
377 # whole bunch of messy heuristics to try to avoid overquoting, originally from
378 # Barrie Slaymaker.  This largely duplicates similar code in Pod::Text.
379 sub quote_literal {
380     my $self = shift;
381     local $_ = shift;
382
383     # A regex that matches the portion of a variable reference that's the
384     # array or hash index, separated out just because we want to use it in
385     # several places in the following regex.
386     my $index = '(?: \[.*\] | \{.*\} )?';
387
388     # Check for things that we don't want to quote, and if we find any of
389     # them, return the string with just a font change and no quoting.
390     m{
391       ^\s*
392       (?:
393          ( [\'\`\"] ) .* \1                             # already quoted
394        | \` .* \'                                       # `quoted'
395        | \$+ [\#^]? \S $index                           # special ($^Foo, $")
396        | [\$\@%&*]+ \#? [:\'\w]+ $index                 # plain var or func
397        | [\$\@%&*]* [:\'\w]+ (?: -> )? \(\s*[^\s,]\s*\) # 0/1-arg func call
398        | [-+]? ( \d[\d.]* | \.\d+ ) (?: [eE][-+]?\d+ )? # a number
399        | 0x [a-fA-F\d]+                                 # a hex constant
400       )
401       \s*\z
402      }xso and return '\f(FS' . $_ . '\f(FE';
403
404     # If we didn't return, go ahead and quote the text.
405     return '\f(FS\*(C`' . $_ . "\\*(C'\\f(FE";
406 }
407
408 # Takes a text block to perform guesswork on.  Returns the text block with
409 # formatting codes added.  This is the code that marks up various Perl
410 # constructs and things commonly used in man pages without requiring the user
411 # to add any explicit markup, and is applied to all non-literal text.  We're
412 # guaranteed that the text we're applying guesswork to does not contain any
413 # *roff formatting codes.  Note that the inserted font sequences must be
414 # treated later with mapfonts or textmapfonts.
415 #
416 # This method is very fragile, both in the regular expressions it uses and in
417 # the ordering of those modifications.  Care and testing is required when
418 # modifying it.
419 sub guesswork {
420     my $self = shift;
421     local $_ = shift;
422     DEBUG > 5 and print "   Guesswork called on [$_]\n";
423
424     # By the time we reach this point, all hypens will be escaped by adding a
425     # backslash.  We want to do that escaping if they're part of regular words
426     # and there's only a single dash, since that's a real hyphen that *roff
427     # gets to consider a possible break point.  Make sure that a dash after
428     # the first character of a word stays non-breaking, however.
429     #
430     # Note that this is not user-controllable; we pretty much have to do this
431     # transformation or *roff will mangle the output in unacceptable ways.
432     s{
433         ( (?:\G|^|\s) [a-zA-Z] ) ( \\- )?
434         ( (?: [a-zA-Z]+ \\-)+ )
435         ( [a-zA-Z]+ ) (?=\s|\Z|\\\ )
436         \b
437     } {
438         my ($prefix, $hyphen, $main, $suffix) = ($1, $2, $3, $4);
439         $hyphen ||= '';
440         $main =~ s/\\-/-/g;
441         $prefix . $hyphen . $main . $suffix;
442     }egx;
443
444     # Translate "--" into a real em-dash if it's used like one.  This means
445     # that it's either surrounded by whitespace, it follows a regular word, or
446     # it occurs between two regular words.
447     if ($$self{MAGIC_EMDASH}) {
448         s{          (\s) \\-\\- (\s)                } { $1 . '\*(--' . $2 }egx;
449         s{ (\b[a-zA-Z]+) \\-\\- (\s|\Z|[a-zA-Z]+\b) } { $1 . '\*(--' . $2 }egx;
450     }
451
452     # Make words in all-caps a little bit smaller; they look better that way.
453     # However, we don't want to change Perl code (like @ARGV), nor do we want
454     # to fix the MIME in MIME-Version since it looks weird with the
455     # full-height V.
456     #
457     # We change only a string of all caps (2) either at the beginning of the
458     # line or following regular punctuation (like quotes) or whitespace (1),
459     # and followed by either similar punctuation, an em-dash, or the end of
460     # the line (3).
461     if ($$self{MAGIC_SMALLCAPS}) {
462         s{
463             ( ^ | [\s\(\"\'\`\[\{<>] | \\\  )                   # (1)
464             ( [A-Z] [A-Z] (?: [/A-Z+:\d_\$&] | \\- )* )         # (2)
465             (?= [\s>\}\]\(\)\'\".?!,;] | \\*\(-- | \\\  | $ )   # (3)
466         } {
467             $1 . '\s-1' . $2 . '\s0'
468         }egx;
469     }
470
471     # Note that from this point forward, we have to adjust for \s-1 and \s-0
472     # strings inserted around things that we've made small-caps if later
473     # transforms should work on those strings.
474
475     # Italize functions in the form func(), including functions that are in
476     # all capitals, but don't italize if there's anything between the parens.
477     # The function must start with an alphabetic character or underscore and
478     # then consist of word characters or colons.
479     if ($$self{MAGIC_FUNC}) {
480         s{
481             ( \b | \\s-1 )
482             ( [A-Za-z_] ([:\w] | \\s-?[01])+ \(\) )
483         } {
484             $1 . '\f(IS' . $2 . '\f(IE'
485         }egx;
486     }
487
488     # Change references to manual pages to put the page name in italics but
489     # the number in the regular font, with a thin space between the name and
490     # the number.  Only recognize func(n) where func starts with an alphabetic
491     # character or underscore and contains only word characters, periods (for
492     # configuration file man pages), or colons, and n is a single digit,
493     # optionally followed by some number of lowercase letters.  Note that this
494     # does not recognize man page references like perl(l) or socket(3SOCKET).
495     if ($$self{MAGIC_MANREF}) {
496         s{
497             ( \b | \\s-1 )
498             ( [A-Za-z_] (?:[.:\w] | \\- | \\s-?[01])+ )
499             ( \( \d [a-z]* \) )
500         } {
501             $1 . '\f(IS' . $2 . '\f(IE\|' . $3
502         }egx;
503     }
504
505     # Convert simple Perl variable references to a fixed-width font.  Be
506     # careful not to convert functions, though; there are too many subtleties
507     # with them to want to perform this transformation.
508     if ($$self{MAGIC_VARS}) {
509         s{
510            ( ^ | \s+ )
511            ( [\$\@%] [\w:]+ )
512            (?! \( )
513         } {
514             $1 . '\f(FS' . $2 . '\f(FE'
515         }egx;
516     }
517
518     # Fix up double quotes.  Unfortunately, we miss this transformation if the
519     # quoted text contains any code with formatting codes and there's not much
520     # we can effectively do about that, which makes it somewhat unclear if
521     # this is really a good idea.
522     s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx;
523
524     # Make C++ into \*(C+, which is a squinched version.
525     if ($$self{MAGIC_CPP}) {
526         s{ \b C\+\+ } {\\*\(C+}gx;
527     }
528
529     # Done.
530     DEBUG > 5 and print "   Guesswork returning [$_]\n";
531     return $_;
532 }
533
534 ##############################################################################
535 # Output
536 ##############################################################################
537
538 # When building up the *roff code, we don't use real *roff fonts.  Instead, we
539 # embed font codes of the form \f(<font>[SE] where <font> is one of B, I, or
540 # F, S stands for start, and E stands for end.  This method turns these into
541 # the right start and end codes.
542 #
543 # We add this level of complexity because the old pod2man didn't get code like
544 # B<someI<thing> else> right; after I<> it switched back to normal text rather
545 # than bold.  We take care of this by using variables that state whether bold,
546 # italic, or fixed are turned on as a combined pointer to our current font
547 # sequence, and set each to the number of current nestings of start tags for
548 # that font.
549 #
550 # \fP changes to the previous font, but only one previous font is kept.  We
551 # don't know what the outside level font is; normally it's R, but if we're
552 # inside a heading it could be something else.  So arrange things so that the
553 # outside font is always the "previous" font and end with \fP instead of \fR.
554 # Idea from Zack Weinberg.
555 sub mapfonts {
556     my ($self, $text) = @_;
557     my ($fixed, $bold, $italic) = (0, 0, 0);
558     my %magic = (F => \$fixed, B => \$bold, I => \$italic);
559     my $last = '\fR';
560     $text =~ s<
561         \\f\((.)(.)
562     > <
563         my $sequence = '';
564         my $f;
565         if ($last ne '\fR') { $sequence = '\fP' }
566         ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
567         $f = $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) };
568         if ($f eq $last) {
569             '';
570         } else {
571             if ($f ne '\fR') { $sequence .= $f }
572             $last = $f;
573             $sequence;
574         }
575     >gxe;
576     return $text;
577 }
578
579 # Unfortunately, there is a bug in Solaris 2.6 nroff (not present in GNU
580 # groff) where the sequence \fB\fP\f(CW\fP leaves the font set to B rather
581 # than R, presumably because \f(CW doesn't actually do a font change.  To work
582 # around this, use a separate textmapfonts for text blocks where the default
583 # font is always R and only use the smart mapfonts for headings.
584 sub textmapfonts {
585     my ($self, $text) = @_;
586     my ($fixed, $bold, $italic) = (0, 0, 0);
587     my %magic = (F => \$fixed, B => \$bold, I => \$italic);
588     $text =~ s<
589         \\f\((.)(.)
590     > <
591         ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
592         $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) };
593     >gxe;
594     return $text;
595 }
596
597 # Given a command and a single argument that may or may not contain double
598 # quotes, handle double-quote formatting for it.  If there are no double
599 # quotes, just return the command followed by the argument in double quotes.
600 # If there are double quotes, use an if statement to test for nroff, and for
601 # nroff output the command followed by the argument in double quotes with
602 # embedded double quotes doubled.  For other formatters, remap paired double
603 # quotes to LQUOTE and RQUOTE.
604 sub switchquotes {
605     my ($self, $command, $text, $extra) = @_;
606     $text =~ s/\\\*\([LR]\"/\"/g;
607
608     # We also have to deal with \*C` and \*C', which are used to add the
609     # quotes around C<> text, since they may expand to " and if they do this
610     # confuses the .SH macros and the like no end.  Expand them ourselves.
611     # Also separate troff from nroff if there are any fixed-width fonts in use
612     # to work around problems with Solaris nroff.
613     my $c_is_quote = ($$self{LQUOTE} =~ /\"/) || ($$self{RQUOTE} =~ /\"/);
614     my $fixedpat = join '|', @{ $$self{FONTS} }{'100', '101', '110', '111'};
615     $fixedpat =~ s/\\/\\\\/g;
616     $fixedpat =~ s/\(/\\\(/g;
617     if ($text =~ m/\"/ || $text =~ m/$fixedpat/) {
618         $text =~ s/\"/\"\"/g;
619         my $nroff = $text;
620         my $troff = $text;
621         $troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g;
622         if ($c_is_quote and $text =~ m/\\\*\(C[\'\`]/) {
623             $nroff =~ s/\\\*\(C\`/$$self{LQUOTE}/g;
624             $nroff =~ s/\\\*\(C\'/$$self{RQUOTE}/g;
625             $troff =~ s/\\\*\(C[\'\`]//g;
626         }
627         $nroff = qq("$nroff") . ($extra ? " $extra" : '');
628         $troff = qq("$troff") . ($extra ? " $extra" : '');
629
630         # Work around the Solaris nroff bug where \f(CW\fP leaves the font set
631         # to Roman rather than the actual previous font when used in headings.
632         # troff output may still be broken, but at least we can fix nroff by
633         # just switching the font changes to the non-fixed versions.
634         $nroff =~ s/\Q$$self{FONTS}{100}\E(.*)\\f[PR]/$1/g;
635         $nroff =~ s/\Q$$self{FONTS}{101}\E(.*)\\f([PR])/\\fI$1\\f$2/g;
636         $nroff =~ s/\Q$$self{FONTS}{110}\E(.*)\\f([PR])/\\fB$1\\f$2/g;
637         $nroff =~ s/\Q$$self{FONTS}{111}\E(.*)\\f([PR])/\\f\(BI$1\\f$2/g;
638
639         # Now finally output the command.  Bother with .ie only if the nroff
640         # and troff output aren't the same.
641         if ($nroff ne $troff) {
642             return ".ie n $command $nroff\n.el $command $troff\n";
643         } else {
644             return "$command $nroff\n";
645         }
646     } else {
647         $text = qq("$text") . ($extra ? " $extra" : '');
648         return "$command $text\n";
649     }
650 }
651
652 # Protect leading quotes and periods against interpretation as commands.  Also
653 # protect anything starting with a backslash, since it could expand or hide
654 # something that *roff would interpret as a command.  This is overkill, but
655 # it's much simpler than trying to parse *roff here.
656 sub protect {
657     my ($self, $text) = @_;
658     $text =~ s/^([.\'\\])/\\&$1/mg;
659     return $text;
660 }
661
662 # Make vertical whitespace if NEEDSPACE is set, appropriate to the indentation
663 # level the situation.  This function is needed since in *roff one has to
664 # create vertical whitespace after paragraphs and between some things, but
665 # other macros create their own whitespace.  Also close out a sequence of
666 # repeated =items, since calling makespace means we're about to begin the item
667 # body.
668 sub makespace {
669     my ($self) = @_;
670     $self->output (".PD\n") if $$self{ITEMS} > 1;
671     $$self{ITEMS} = 0;
672     $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n")
673         if $$self{NEEDSPACE};
674 }
675
676 # Output any pending index entries, and optionally an index entry given as an
677 # argument.  Support multiple index entries in X<> separated by slashes, and
678 # strip special escapes from index entries.
679 sub outindex {
680     my ($self, $section, $index) = @_;
681     my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} };
682     return unless ($section || @entries);
683
684     # We're about to output all pending entries, so clear our pending queue.
685     $$self{INDEX} = [];
686
687     # Build the output.  Regular index entries are marked Xref, and headings
688     # pass in their own section.  Undo some *roff formatting on headings.
689     my @output;
690     if (@entries) {
691         push @output, [ 'Xref', join (' ', @entries) ];
692     }
693     if ($section) {
694         $index =~ s/\\-/-/g;
695         $index =~ s/\\(?:s-?\d|.\(..|.)//g;
696         push @output, [ $section, $index ];
697     }
698
699     # Print out the .IX commands.
700     for (@output) {
701         my ($type, $entry) = @$_;
702         $entry =~ s/\"/\"\"/g;
703         $self->output (".IX $type " . '"' . $entry . '"' . "\n");
704     }
705 }
706
707 # Output some text, without any additional changes.
708 sub output {
709     my ($self, @text) = @_;
710     print { $$self{output_fh} } @text;
711 }
712
713 ##############################################################################
714 # Document initialization
715 ##############################################################################
716
717 # Handle the start of the document.  Here we handle empty documents, as well
718 # as setting up our basic macros in a preamble and building the page title.
719 sub start_document {
720     my ($self, $attrs) = @_;
721     if ($$attrs{contentless} && !$$self{ALWAYS_EMIT_SOMETHING}) {
722         DEBUG and print "Document is contentless\n";
723         $$self{CONTENTLESS} = 1;
724         return;
725     }
726
727     # Determine information for the preamble and then output it.
728     my ($name, $section);
729     if (defined $$self{name}) {
730         $name = $$self{name};
731         $section = $$self{section} || 1;
732     } else {
733         ($name, $section) = $self->devise_title;
734     }
735     my $date = $$self{date} || $self->devise_date;
736     $self->preamble ($name, $section, $date)
737         unless $self->bare_output or DEBUG > 9;
738
739     # Initialize a few per-document variables.
740     $$self{INDENT}    = 0;      # Current indentation level.
741     $$self{INDENTS}   = [];     # Stack of indentations.
742     $$self{INDEX}     = [];     # Index keys waiting to be printed.
743     $$self{IN_NAME}   = 0;      # Whether processing the NAME section.
744     $$self{ITEMS}     = 0;      # The number of consecutive =items.
745     $$self{ITEMTYPES} = [];     # Stack of =item types, one per list.
746     $$self{SHIFTWAIT} = 0;      # Whether there is a shift waiting.
747     $$self{SHIFTS}    = [];     # Stack of .RS shifts.
748     $$self{PENDING}   = [[]];   # Pending output.
749 }
750
751 # Handle the end of the document.  This does nothing but print out a final
752 # comment at the end of the document under debugging.
753 sub end_document {
754     my ($self) = @_;
755     return if $self->bare_output;
756     return if ($$self{CONTENTLESS} && !$$self{ALWAYS_EMIT_SOMETHING});
757     $self->output (q(.\" [End document]) . "\n") if DEBUG;
758 }
759
760 # Try to figure out the name and section from the file name and return them as
761 # a list, returning an empty name and section 1 if we can't find any better
762 # information.  Uses File::Basename and File::Spec as necessary.
763 sub devise_title {
764     my ($self) = @_;
765     my $name = $self->source_filename || '';
766     my $section = $$self{section} || 1;
767     $section = 3 if (!$$self{section} && $name =~ /\.pm\z/i);
768     $name =~ s/\.p(od|[lm])\z//i;
769
770     # If the section isn't 3, then the name defaults to just the basename of
771     # the file.  Otherwise, assume we're dealing with a module.  We want to
772     # figure out the full module name from the path to the file, but we don't
773     # want to include too much of the path into the module name.  Lose
774     # anything up to the first off:
775     #
776     #     */lib/*perl*/         standard or site_perl module
777     #     */*perl*/lib/         from -Dprefix=/opt/perl
778     #     */*perl*/             random module hierarchy
779     #
780     # which works.  Also strip off a leading site, site_perl, or vendor_perl
781     # component, any OS-specific component, and any version number component,
782     # and strip off an initial component of "lib" or "blib/lib" since that's
783     # what ExtUtils::MakeMaker creates.  splitdir requires at least File::Spec
784     # 0.8.
785     if ($section !~ /^3/) {
786         require File::Basename;
787         $name = uc File::Basename::basename ($name);
788     } else {
789         require File::Spec;
790         my ($volume, $dirs, $file) = File::Spec->splitpath ($name);
791         my @dirs = File::Spec->splitdir ($dirs);
792         my $cut = 0;
793         my $i;
794         for ($i = 0; $i < scalar @dirs; $i++) {
795             if ($dirs[$i] eq 'lib' && $dirs[$i + 1] =~ /perl/) {
796                 $cut = $i + 2;
797                 last;
798             } elsif ($dirs[$i] =~ /perl/) {
799                 $cut = $i + 1;
800                 $cut++ if $dirs[$i + 1] eq 'lib';
801                 last;
802             }
803         }
804         if ($cut > 0) {
805             splice (@dirs, 0, $cut);
806             shift @dirs if ($dirs[0] =~ /^(site|vendor)(_perl)?$/);
807             shift @dirs if ($dirs[0] =~ /^[\d.]+$/);
808             shift @dirs if ($dirs[0] =~ /^(.*-$^O|$^O-.*|$^O)$/);
809         }
810         shift @dirs if $dirs[0] eq 'lib';
811         splice (@dirs, 0, 2) if ($dirs[0] eq 'blib' && $dirs[1] eq 'lib');
812
813         # Remove empty directories when building the module name; they
814         # occur too easily on Unix by doubling slashes.
815         $name = join ('::', (grep { $_ ? $_ : () } @dirs), $file);
816     }
817     return ($name, $section);
818 }
819
820 # Determine the modification date and return that, properly formatted in ISO
821 # format.  If we can't get the modification date of the input, instead use the
822 # current time.
823 sub devise_date {
824     my ($self) = @_;
825     my $input = $self->source_filename;
826     my $time = ($input ? (stat $input)[9] : time);
827     return strftime ('%Y-%m-%d', localtime $time);
828 }
829
830 # Print out the preamble and the title.  The meaning of the arguments to .TH
831 # unfortunately vary by system; some systems consider the fourth argument to
832 # be a "source" and others use it as a version number.  Generally it's just
833 # presented as the left-side footer, though, so it doesn't matter too much if
834 # a particular system gives it another interpretation.
835 #
836 # The order of date and release used to be reversed in older versions of this
837 # module, but this order is correct for both Solaris and Linux.
838 sub preamble {
839     my ($self, $name, $section, $date) = @_;
840     my $preamble = $self->preamble_template;
841
842     # Build the index line and make sure that it will be syntactically valid.
843     my $index = "$name $section";
844     $index =~ s/\"/\"\"/g;
845
846     # If name or section contain spaces, quote them (section really never
847     # should, but we may as well be cautious).
848     for ($name, $section) {
849         if (/\s/) {
850             s/\"/\"\"/g;
851             $_ = '"' . $_ . '"';
852         }
853     }
854
855     # Double quotes in date, since it will be quoted.
856     $date =~ s/\"/\"\"/g;
857
858     # Substitute into the preamble the configuration options.
859     $preamble =~ s/\@CFONT\@/$$self{fixed}/;
860     $preamble =~ s/\@LQUOTE\@/$$self{LQUOTE}/;
861     $preamble =~ s/\@RQUOTE\@/$$self{RQUOTE}/;
862     chomp $preamble;
863
864     # Get the version information.
865     my $version = $self->version_report;
866
867     # Finally output everything.
868     $self->output (<<"----END OF HEADER----");
869 .\\" Automatically generated by $version
870 .\\"
871 .\\" Standard preamble:
872 .\\" ========================================================================
873 $preamble
874 .\\" ========================================================================
875 .\\"
876 .IX Title "$index"
877 .TH $name $section "$date" "$$self{release}" "$$self{center}"
878 ----END OF HEADER----
879     $self->output (".\\\" [End of preamble]\n") if DEBUG;
880 }
881
882 ##############################################################################
883 # Text blocks
884 ##############################################################################
885
886 # Handle a basic block of text.  The only tricky part of this is if this is
887 # the first paragraph of text after an =over, in which case we have to change
888 # indentations for *roff.
889 sub cmd_para {
890     my ($self, $attrs, $text) = @_;
891     my $line = $$attrs{start_line};
892
893     # Output the paragraph.  We also have to handle =over without =item.  If
894     # there's an =over without =item, SHIFTWAIT will be set, and we need to
895     # handle creation of the indent here.  Add the shift to SHIFTS so that it
896     # will be cleaned up on =back.
897     $self->makespace;
898     if ($$self{SHIFTWAIT}) {
899         $self->output (".RS $$self{INDENT}\n");
900         push (@{ $$self{SHIFTS} }, $$self{INDENT});
901         $$self{SHIFTWAIT} = 0;
902     }
903
904     # Add the line number for debugging, but not in the NAME section just in
905     # case the comment would confuse apropos.
906     $self->output (".\\\" [At source line $line]\n")
907         if defined ($line) && DEBUG && !$$self{IN_NAME};
908
909     # Force exactly one newline at the end and strip unwanted trailing
910     # whitespace at the end.
911     $text =~ s/\s*$/\n/;
912
913     # Output the paragraph.
914     $self->output ($self->protect ($self->textmapfonts ($text)));
915     $self->outindex;
916     $$self{NEEDSPACE} = 1;
917     return '';
918 }
919
920 # Handle a verbatim paragraph.  Put a null token at the beginning of each line
921 # to protect against commands and wrap in .Vb/.Ve (which we define in our
922 # prelude).
923 sub cmd_verbatim {
924     my ($self, $attrs, $text) = @_;
925
926     # Ignore an empty verbatim paragraph.
927     return unless $text =~ /\S/;
928
929     # Force exactly one newline at the end and strip unwanted trailing
930     # whitespace at the end.
931     $text =~ s/\s*$/\n/;
932
933     # Get a count of the number of lines before the first blank line, which
934     # we'll pass to .Vb as its parameter.  This tells *roff to keep that many
935     # lines together.  We don't want to tell *roff to keep huge blocks
936     # together.
937     my @lines = split (/\n/, $text);
938     my $unbroken = 0;
939     for (@lines) {
940         last if /^\s*$/;
941         $unbroken++;
942     }
943     $unbroken = 10 if ($unbroken > 12 && !$$self{MAGIC_VNOPAGEBREAK_LIMIT});
944
945     # Prepend a null token to each line.
946     $text =~ s/^/\\&/gm;
947
948     # Output the results.
949     $self->makespace;
950     $self->output (".Vb $unbroken\n$text.Ve\n");
951     $$self{NEEDSPACE} = 1;
952     return '';
953 }
954
955 # Handle literal text (produced by =for and similar constructs).  Just output
956 # it with the minimum of changes.
957 sub cmd_data {
958     my ($self, $attrs, $text) = @_;
959     $text =~ s/^\n+//;
960     $text =~ s/\n{0,2}$/\n/;
961     $self->output ($text);
962     return '';
963 }
964
965 ##############################################################################
966 # Headings
967 ##############################################################################
968
969 # Common code for all headings.  This is called before the actual heading is
970 # output.  It returns the cleaned up heading text (putting the heading all on
971 # one line) and may do other things, like closing bad =item blocks.
972 sub heading_common {
973     my ($self, $text, $line) = @_;
974     $text =~ s/\s+$//;
975     $text =~ s/\s*\n\s*/ /g;
976
977     # This should never happen; it means that we have a heading after =item
978     # without an intervening =back.  But just in case, handle it anyway.
979     if ($$self{ITEMS} > 1) {
980         $$self{ITEMS} = 0;
981         $self->output (".PD\n");
982     }
983
984     # Output the current source line.
985     $self->output ( ".\\\" [At source line $line]\n" )
986         if defined ($line) && DEBUG;
987     return $text;
988 }
989
990 # First level heading.  We can't output .IX in the NAME section due to a bug
991 # in some versions of catman, so don't output a .IX for that section.  .SH
992 # already uses small caps, so remove \s0 and \s-1.  Maintain IN_NAME as
993 # appropriate.
994 sub cmd_head1 {
995     my ($self, $attrs, $text) = @_;
996     $text =~ s/\\s-?\d//g;
997     $text = $self->heading_common ($text, $$attrs{start_line});
998     my $isname = ($text eq 'NAME' || $text =~ /\(NAME\)/);
999     $self->output ($self->switchquotes ('.SH', $self->mapfonts ($text)));
1000     $self->outindex ('Header', $text) unless $isname;
1001     $$self{NEEDSPACE} = 0;
1002     $$self{IN_NAME} = $isname;
1003     return '';
1004 }
1005
1006 # Second level heading.
1007 sub cmd_head2 {
1008     my ($self, $attrs, $text) = @_;
1009     $text = $self->heading_common ($text, $$attrs{start_line});
1010     $self->output ($self->switchquotes ('.Sh', $self->mapfonts ($text)));
1011     $self->outindex ('Subsection', $text);
1012     $$self{NEEDSPACE} = 0;
1013     return '';
1014 }
1015
1016 # Third level heading.  *roff doesn't have this concept, so just put the
1017 # heading in italics as a normal paragraph.
1018 sub cmd_head3 {
1019     my ($self, $attrs, $text) = @_;
1020     $text = $self->heading_common ($text, $$attrs{start_line});
1021     $self->makespace;
1022     $self->output ($self->textmapfonts ('\f(IS' . $text . '\f(IE') . "\n");
1023     $self->outindex ('Subsection', $text);
1024     $$self{NEEDSPACE} = 1;
1025     return '';
1026 }
1027
1028 # Fourth level heading.  *roff doesn't have this concept, so just put the
1029 # heading as a normal paragraph.
1030 sub cmd_head4 {
1031     my ($self, $attrs, $text) = @_;
1032     $text = $self->heading_common ($text, $$attrs{start_line});
1033     $self->makespace;
1034     $self->output ($self->textmapfonts ($text) . "\n");
1035     $self->outindex ('Subsection', $text);
1036     $$self{NEEDSPACE} = 1;
1037     return '';
1038 }
1039
1040 ##############################################################################
1041 # Formatting codes
1042 ##############################################################################
1043
1044 # All of the formatting codes that aren't handled internally by the parser,
1045 # other than L<> and X<>.
1046 sub cmd_b { return '\f(BS' . $_[2] . '\f(BE' }
1047 sub cmd_i { return '\f(IS' . $_[2] . '\f(IE' }
1048 sub cmd_f { return '\f(IS' . $_[2] . '\f(IE' }
1049 sub cmd_c { return $_[0]->quote_literal ($_[2]) }
1050
1051 # Index entries are just added to the pending entries.
1052 sub cmd_x {
1053     my ($self, $attrs, $text) = @_;
1054     push (@{ $$self{INDEX} }, $text);
1055     return '';
1056 }
1057
1058 # Links reduce to the text that we're given, wrapped in angle brackets if it's
1059 # a URL.
1060 sub cmd_l {
1061     my ($self, $attrs, $text) = @_;
1062     return $$attrs{type} eq 'url' ? "<$text>" : $text;
1063 }
1064
1065 ##############################################################################
1066 # List handling
1067 ##############################################################################
1068
1069 # Handle the beginning of an =over block.  Takes the type of the block as the
1070 # first argument, and then the attr hash.  This is called by the handlers for
1071 # the four different types of lists (bullet, number, text, and block).
1072 sub over_common_start {
1073     my ($self, $type, $attrs) = @_;
1074     my $line = $$attrs{start_line};
1075     my $indent = $$attrs{indent};
1076     DEBUG > 3 and print " Starting =over $type (line $line, indent ",
1077         ($indent || '?'), "\n";
1078
1079     # Find the indentation level.
1080     unless (defined ($indent) && $indent =~ /^[-+]?\d{1,4}\s*$/) {
1081         $indent = $$self{indent};
1082     }
1083
1084     # If we've gotten multiple indentations in a row, we need to emit the
1085     # pending indentation for the last level that we saw and haven't acted on
1086     # yet.  SHIFTS is the stack of indentations that we've actually emitted
1087     # code for.
1088     if (@{ $$self{SHIFTS} } < @{ $$self{INDENTS} }) {
1089         $self->output (".RS $$self{INDENT}\n");
1090         push (@{ $$self{SHIFTS} }, $$self{INDENT});
1091     }
1092
1093     # Now, do record-keeping.  INDENTS is a stack of indentations that we've
1094     # seen so far, and INDENT is the current level of indentation.  ITEMTYPES
1095     # is a stack of list types that we've seen.
1096     push (@{ $$self{INDENTS} }, $$self{INDENT});
1097     push (@{ $$self{ITEMTYPES} }, $type);
1098     $$self{INDENT} = $indent + 0;
1099     $$self{SHIFTWAIT} = 1;
1100 }
1101
1102 # End an =over block.  Takes no options other than the class pointer.
1103 # Normally, once we close a block and therefore remove something from INDENTS,
1104 # INDENTS will now be longer than SHIFTS, indicating that we also need to emit
1105 # *roff code to close the indent.  This isn't *always* true, depending on the
1106 # circumstance.  If we're still inside an indentation, we need to emit another
1107 # .RE and then a new .RS to unconfuse *roff.
1108 sub over_common_end {
1109     my ($self) = @_;
1110     DEBUG > 3 and print " Ending =over\n";
1111     $$self{INDENT} = pop @{ $$self{INDENTS} };
1112     pop @{ $$self{ITEMTYPES} };
1113
1114     # If we emitted code for that indentation, end it.
1115     if (@{ $$self{SHIFTS} } > @{ $$self{INDENTS} }) {
1116         $self->output (".RE\n");
1117         pop @{ $$self{SHIFTS} };
1118     }
1119
1120     # If we're still in an indentation, *roff will have now lost track of the
1121     # right depth of that indentation, so fix that.
1122     if (@{ $$self{INDENTS} } > 0) {
1123         $self->output (".RE\n");
1124         $self->output (".RS $$self{INDENT}\n");
1125     }
1126     $$self{NEEDSPACE} = 1;
1127     $$self{SHIFTWAIT} = 0;
1128 }
1129
1130 # Dispatch the start and end calls as appropriate.
1131 sub start_over_bullet { my $s = shift; $s->over_common_start ('bullet', @_) }
1132 sub start_over_number { my $s = shift; $s->over_common_start ('number', @_) }
1133 sub start_over_text   { my $s = shift; $s->over_common_start ('text',   @_) }
1134 sub start_over_block  { my $s = shift; $s->over_common_start ('block',  @_) }
1135 sub end_over_bullet { $_[0]->over_common_end }
1136 sub end_over_number { $_[0]->over_common_end }
1137 sub end_over_text   { $_[0]->over_common_end }
1138 sub end_over_block  { $_[0]->over_common_end }
1139
1140 # The common handler for all item commands.  Takes the type of the item, the
1141 # attributes, and then the text of the item.
1142 #
1143 # Emit an index entry for anything that's interesting, but don't emit index
1144 # entries for things like bullets and numbers.  Newlines in an item title are
1145 # turned into spaces since *roff can't handle them embedded.
1146 sub item_common {
1147     my ($self, $type, $attrs, $text) = @_;
1148     my $line = $$attrs{start_line};
1149     DEBUG > 3 and print "  $type item (line $line): $text\n";
1150
1151     # Clean up the text.  We want to end up with two variables, one ($text)
1152     # which contains any body text after taking out the item portion, and
1153     # another ($item) which contains the actual item text.
1154     $text =~ s/\s+$//;
1155     my ($item, $index);
1156     if ($type eq 'bullet') {
1157         $item = "\\\(bu";
1158         $text =~ s/\n*$/\n/;
1159     } elsif ($type eq 'number') {
1160         $item = $$attrs{number} . '.';
1161     } else {
1162         $item = $text;
1163         $item =~ s/\s*\n\s*/ /g;
1164         $text = '';
1165         $index = $item if ($item =~ /\w/);
1166     }
1167
1168     # Take care of the indentation.  If shifts and indents are equal, close
1169     # the top shift, since we're about to create an indentation with .IP.
1170     # Also output .PD 0 to turn off spacing between items if this item is
1171     # directly following another one.  We only have to do that once for a
1172     # whole chain of items so do it for the second item in the change.  Note
1173     # that makespace is what undoes this.
1174     if (@{ $$self{SHIFTS} } == @{ $$self{INDENTS} }) {
1175         $self->output (".RE\n");
1176         pop @{ $$self{SHIFTS} };
1177     }
1178     $self->output (".PD 0\n") if ($$self{ITEMS} == 1);
1179
1180     # Now, output the item tag itself.
1181     $item = $self->textmapfonts ($item);
1182     $self->output ($self->switchquotes ('.IP', $item, $$self{INDENT}));
1183     $$self{NEEDSPACE} = 0;
1184     $$self{ITEMS}++;
1185     $$self{SHIFTWAIT} = 0;
1186
1187     # If body text for this item was included, go ahead and output that now.
1188     if ($text) {
1189         $text =~ s/\s*$/\n/;
1190         $self->makespace;
1191         $self->output ($self->protect ($self->textmapfonts ($text)));
1192         $$self{NEEDSPACE} = 1;
1193     }
1194     $self->outindex ($index ? ('Item', $index) : ());
1195 }
1196
1197 # Dispatch the item commands to the appropriate place.
1198 sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) }
1199 sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) }
1200 sub cmd_item_text   { my $self = shift; $self->item_common ('text',   @_) }
1201 sub cmd_item_block  { my $self = shift; $self->item_common ('block',  @_) }
1202
1203 ##############################################################################
1204 # Translation tables
1205 ##############################################################################
1206
1207 # The following table is adapted from Tom Christiansen's pod2man.  It assumes
1208 # that the standard preamble has already been printed, since that's what
1209 # defines all of the accent marks.  We really want to do something better than
1210 # this when *roff actually supports other character sets itself, since these
1211 # results are pretty poor.
1212 #
1213 # This only works in an ASCII world.  What to do in a non-ASCII world is very
1214 # unclear.
1215 @ESCAPES{0xA0 .. 0xFF} = (
1216     "\\ ", undef, undef, undef,            undef, undef, undef, undef,
1217     undef, undef, undef, undef,            undef, "\\%", undef, undef,
1218
1219     undef, undef, undef, undef,            undef, undef, undef, undef,
1220     undef, undef, undef, undef,            undef, undef, undef, undef,
1221
1222     "A\\*`",  "A\\*'", "A\\*^", "A\\*~",   "A\\*:", "A\\*o", "\\*(AE", "C\\*,",
1223     "E\\*`",  "E\\*'", "E\\*^", "E\\*:",   "I\\*`", "I\\*'", "I\\*^",  "I\\*:",
1224
1225     "\\*(D-", "N\\*~", "O\\*`", "O\\*'",   "O\\*^", "O\\*~", "O\\*:",  undef,
1226     "O\\*/",  "U\\*`", "U\\*'", "U\\*^",   "U\\*:", "Y\\*'", "\\*(Th", "\\*8",
1227
1228     "a\\*`",  "a\\*'", "a\\*^", "a\\*~",   "a\\*:", "a\\*o", "\\*(ae", "c\\*,",
1229     "e\\*`",  "e\\*'", "e\\*^", "e\\*:",   "i\\*`", "i\\*'", "i\\*^",  "i\\*:",
1230
1231     "\\*(d-", "n\\*~", "o\\*`", "o\\*'",   "o\\*^", "o\\*~", "o\\*:",  undef,
1232     "o\\*/" , "u\\*`", "u\\*'", "u\\*^",   "u\\*:", "y\\*'", "\\*(th", "y\\*:",
1233 ) if ASCII;
1234
1235 # Make sure that at least this works even outside of ASCII.
1236 $ESCAPES{ord("\\")} = "\\e";
1237
1238 ##############################################################################
1239 # Premable
1240 ##############################################################################
1241
1242 # The following is the static preamble which starts all *roff output we
1243 # generate.  It's completely static except for the font to use as a
1244 # fixed-width font, which is designed by @CFONT@, and the left and right
1245 # quotes to use for C<> text, designated by @LQOUTE@ and @RQUOTE@.
1246 sub preamble_template {
1247     return <<'----END OF PREAMBLE----';
1248 .de Sh \" Subsection heading
1249 .br
1250 .if t .Sp
1251 .ne 5
1252 .PP
1253 \fB\\$1\fR
1254 .PP
1255 ..
1256 .de Sp \" Vertical space (when we can't use .PP)
1257 .if t .sp .5v
1258 .if n .sp
1259 ..
1260 .de Vb \" Begin verbatim text
1261 .ft @CFONT@
1262 .nf
1263 .ne \\$1
1264 ..
1265 .de Ve \" End verbatim text
1266 .ft R
1267 .fi
1268 ..
1269 .\" Set up some character translations and predefined strings.  \*(-- will
1270 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
1271 .\" double quote, and \*(R" will give a right double quote.  | will give a
1272 .\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
1273 .\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
1274 .\" expand to `' in nroff, nothing in troff, for use with C<>.
1275 .tr \(*W-|\(bv\*(Tr
1276 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
1277 .ie n \{\
1278 .    ds -- \(*W-
1279 .    ds PI pi
1280 .    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
1281 .    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
1282 .    ds L" ""
1283 .    ds R" ""
1284 .    ds C` @LQUOTE@
1285 .    ds C' @RQUOTE@
1286 'br\}
1287 .el\{\
1288 .    ds -- \|\(em\|
1289 .    ds PI \(*p
1290 .    ds L" ``
1291 .    ds R" ''
1292 'br\}
1293 .\"
1294 .\" If the F register is turned on, we'll generate index entries on stderr for
1295 .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
1296 .\" entries marked with X<> in POD.  Of course, you'll have to process the
1297 .\" output yourself in some meaningful fashion.
1298 .if \nF \{\
1299 .    de IX
1300 .    tm Index:\\$1\t\\n%\t"\\$2"
1301 ..
1302 .    nr % 0
1303 .    rr F
1304 .\}
1305 .\"
1306 .\" For nroff, turn off justification.  Always turn off hyphenation; it makes
1307 .\" way too many mistakes in technical documents.
1308 .hy 0
1309 .if n .na
1310 .\"
1311 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
1312 .\" Fear.  Run.  Save yourself.  No user-serviceable parts.
1313 .    \" fudge factors for nroff and troff
1314 .if n \{\
1315 .    ds #H 0
1316 .    ds #V .8m
1317 .    ds #F .3m
1318 .    ds #[ \f1
1319 .    ds #] \fP
1320 .\}
1321 .if t \{\
1322 .    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
1323 .    ds #V .6m
1324 .    ds #F 0
1325 .    ds #[ \&
1326 .    ds #] \&
1327 .\}
1328 .    \" simple accents for nroff and troff
1329 .if n \{\
1330 .    ds ' \&
1331 .    ds ` \&
1332 .    ds ^ \&
1333 .    ds , \&
1334 .    ds ~ ~
1335 .    ds /
1336 .\}
1337 .if t \{\
1338 .    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
1339 .    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
1340 .    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
1341 .    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
1342 .    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
1343 .    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
1344 .\}
1345 .    \" troff and (daisy-wheel) nroff accents
1346 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
1347 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
1348 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
1349 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
1350 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
1351 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
1352 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
1353 .ds ae a\h'-(\w'a'u*4/10)'e
1354 .ds Ae A\h'-(\w'A'u*4/10)'E
1355 .    \" corrections for vroff
1356 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
1357 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
1358 .    \" for low resolution devices (crt and lpr)
1359 .if \n(.H>23 .if \n(.V>19 \
1360 \{\
1361 .    ds : e
1362 .    ds 8 ss
1363 .    ds o a
1364 .    ds d- d\h'-1'\(ga
1365 .    ds D- D\h'-1'\(hy
1366 .    ds th \o'bp'
1367 .    ds Th \o'LP'
1368 .    ds ae ae
1369 .    ds Ae AE
1370 .\}
1371 .rm #[ #] #H #V #F C
1372 ----END OF PREAMBLE----
1373 #`# for cperl-mode
1374 }
1375
1376 ##############################################################################
1377 # Module return value and documentation
1378 ##############################################################################
1379
1380 1;
1381 __END__
1382
1383 =head1 NAME
1384
1385 Pod::Man - Convert POD data to formatted *roff input
1386
1387 =head1 SYNOPSIS
1388
1389     use Pod::Man;
1390     my $parser = Pod::Man->new (release => $VERSION, section => 8);
1391
1392     # Read POD from STDIN and write to STDOUT.
1393     $parser->parse_file (\*STDIN);
1394
1395     # Read POD from file.pod and write to file.1.
1396     $parser->parse_from_file ('file.pod', 'file.1');
1397
1398 =head1 DESCRIPTION
1399
1400 Pod::Man is a module to convert documentation in the POD format (the
1401 preferred language for documenting Perl) into *roff input using the man
1402 macro set.  The resulting *roff code is suitable for display on a terminal
1403 using L<nroff(1)>, normally via L<man(1)>, or printing using L<troff(1)>.
1404 It is conventionally invoked using the driver script B<pod2man>, but it can
1405 also be used directly.
1406
1407 As a derived class from Pod::Simple, Pod::Man supports the same methods and
1408 interfaces.  See L<Pod::Simple> for all the details.
1409
1410 new() can take options, in the form of key/value pairs that control the
1411 behavior of the parser.  See below for details.
1412
1413 If no options are given, Pod::Man uses the name of the input file with any
1414 trailing C<.pod>, C<.pm>, or C<.pl> stripped as the man page title, to
1415 section 1 unless the file ended in C<.pm> in which case it defaults to
1416 section 3, to a centered title of "User Contributed Perl Documentation", to
1417 a centered footer of the Perl version it is run with, and to a left-hand
1418 footer of the modification date of its input (or the current date if given
1419 STDIN for input).
1420
1421 Pod::Man assumes that your *roff formatters have a fixed-width font named
1422 CW.  If yours is called something else (like CR), use the C<fixed> option to
1423 specify it.  This generally only matters for troff output for printing.
1424 Similarly, you can set the fonts used for bold, italic, and bold italic
1425 fixed-width output.
1426
1427 Besides the obvious pod conversions, Pod::Man also takes care of formatting
1428 func(), func(3), and simple variable references like $foo or @bar so you
1429 don't have to use code escapes for them; complex expressions like
1430 C<$fred{'stuff'}> will still need to be escaped, though.  It also translates
1431 dashes that aren't used as hyphens into en dashes, makes long dashes--like
1432 this--into proper em dashes, fixes "paired quotes," makes C++ look right,
1433 puts a little space between double underbars, makes ALLCAPS a teeny bit
1434 smaller in B<troff>, and escapes stuff that *roff treats as special so that
1435 you don't have to.
1436
1437 The recognized options to new() are as follows.  All options take a single
1438 argument.
1439
1440 =over 4
1441
1442 =item center
1443
1444 Sets the centered page header to use instead of "User Contributed Perl
1445 Documentation".
1446
1447 =item date
1448
1449 Sets the left-hand footer.  By default, the modification date of the input
1450 file will be used, or the current date if stat() can't find that file (the
1451 case if the input is from STDIN), and the date will be formatted as
1452 YYYY-MM-DD.
1453
1454 =item fixed
1455
1456 The fixed-width font to use for vertabim text and code.  Defaults to CW.
1457 Some systems may want CR instead.  Only matters for B<troff> output.
1458
1459 =item fixedbold
1460
1461 Bold version of the fixed-width font.  Defaults to CB.  Only matters for
1462 B<troff> output.
1463
1464 =item fixeditalic
1465
1466 Italic version of the fixed-width font (actually, something of a misnomer,
1467 since most fixed-width fonts only have an oblique version, not an italic
1468 version).  Defaults to CI.  Only matters for B<troff> output.
1469
1470 =item fixedbolditalic
1471
1472 Bold italic (probably actually oblique) version of the fixed-width font.
1473 Pod::Man doesn't assume you have this, and defaults to CB.  Some systems
1474 (such as Solaris) have this font available as CX.  Only matters for B<troff>
1475 output.
1476
1477 =item name
1478
1479 Set the name of the manual page.  Without this option, the manual name is
1480 set to the uppercased base name of the file being converted unless the
1481 manual section is 3, in which case the path is parsed to see if it is a Perl
1482 module path.  If it is, a path like C<.../lib/Pod/Man.pm> is converted into
1483 a name like C<Pod::Man>.  This option, if given, overrides any automatic
1484 determination of the name.
1485
1486 =item quotes
1487
1488 Sets the quote marks used to surround CE<lt>> text.  If the value is a
1489 single character, it is used as both the left and right quote; if it is two
1490 characters, the first character is used as the left quote and the second as
1491 the right quoted; and if it is four characters, the first two are used as
1492 the left quote and the second two as the right quote.
1493
1494 This may also be set to the special value C<none>, in which case no quote
1495 marks are added around CE<lt>> text (but the font is still changed for troff
1496 output).
1497
1498 =item release
1499
1500 Set the centered footer.  By default, this is the version of Perl you run
1501 Pod::Man under.  Note that some system an macro sets assume that the
1502 centered footer will be a modification date and will prepend something like
1503 "Last modified: "; if this is the case, you may want to set C<release> to
1504 the last modified date and C<date> to the version number.
1505
1506 =item section
1507
1508 Set the section for the C<.TH> macro.  The standard section numbering
1509 convention is to use 1 for user commands, 2 for system calls, 3 for
1510 functions, 4 for devices, 5 for file formats, 6 for games, 7 for
1511 miscellaneous information, and 8 for administrator commands.  There is a lot
1512 of variation here, however; some systems (like Solaris) use 4 for file
1513 formats, 5 for miscellaneous information, and 7 for devices.  Still others
1514 use 1m instead of 8, or some mix of both.  About the only section numbers
1515 that are reliably consistent are 1, 2, and 3.
1516
1517 By default, section 1 will be used unless the file ends in .pm in which case
1518 section 3 will be selected.
1519
1520 =back
1521
1522 The standard Pod::Simple method parse_file() takes one argument naming the
1523 POD file to read from.  By default, the output is sent to STDOUT, but this
1524 can be changed with the output_fd() method.
1525
1526 The standard Pod::Simple method parse_from_file() takes up to two
1527 arguments, the first being the input file to read POD from and the second
1528 being the file to write the formatted output to.
1529
1530 You can also call parse_lines() to parse an array of lines or
1531 parse_string_document() to parse a document already in memory.  To put the
1532 output into a string instead of a file handle, call the output_string()
1533 method.  See L<Pod::Simple> for the specific details.
1534
1535 =head1 DIAGNOSTICS
1536
1537 =over 4
1538
1539 =item roff font should be 1 or 2 chars, not "%s"
1540
1541 (F) You specified a *roff font (using C<fixed>, C<fixedbold>, etc.) that
1542 wasn't either one or two characters.  Pod::Man doesn't support *roff fonts
1543 longer than two characters, although some *roff extensions do (the canonical
1544 versions of B<nroff> and B<troff> don't either).
1545
1546 =item Invalid quote specification "%s"
1547
1548 (F) The quote specification given (the quotes option to the constructor) was
1549 invalid.  A quote specification must be one, two, or four characters long.
1550
1551 =back
1552
1553 =head1 BUGS
1554
1555 Eight-bit input data isn't handled at all well at present.  The correct
1556 approach would be to map EE<lt>E<gt> escapes to the appropriate UTF-8
1557 characters and then do a translation pass on the output according to the
1558 user-specified output character set.  Unfortunately, we can't send eight-bit
1559 data directly to the output unless the user says this is okay, since some
1560 vendor *roff implementations can't handle eight-bit data.  If the *roff
1561 implementation can, however, that's far superior to the current hacked
1562 characters that only work under troff.
1563
1564 There is currently no way to turn off the guesswork that tries to format
1565 unmarked text appropriately, and sometimes it isn't wanted (particularly
1566 when using POD to document something other than Perl).  Most of the work
1567 towards fixing this has now been done, however, and all that's still needed
1568 is a user interface.
1569
1570 The NAME section should be recognized specially and index entries emitted
1571 for everything in that section.  This would have to be deferred until the
1572 next section, since extraneous things in NAME tends to confuse various man
1573 page processors.  Currently, no index entries are emitted for anything in
1574 NAME.
1575
1576 Pod::Man doesn't handle font names longer than two characters.  Neither do
1577 most B<troff> implementations, but GNU troff does as an extension.  It would
1578 be nice to support as an option for those who want to use it.
1579
1580 The preamble added to each output file is rather verbose, and most of it
1581 is only necessary in the presence of non-ASCII characters.  It would
1582 ideally be nice if all of those definitions were only output if needed,
1583 perhaps on the fly as the characters are used.
1584
1585 Pod::Man is excessively slow.
1586
1587 =head1 CAVEATS
1588
1589 The handling of hyphens and em dashes is somewhat fragile, and one may get
1590 the wrong one under some circumstances.  This should only matter for
1591 B<troff> output.
1592
1593 When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
1594 necessarily get it right.
1595
1596 Converting neutral double quotes to properly matched double quotes doesn't
1597 work unless there are no formatting codes between the quote marks.  This
1598 only matters for troff output.
1599
1600 =head1 AUTHOR
1601
1602 Russ Allbery <rra@stanford.edu>, based I<very> heavily on the original
1603 B<pod2man> by Tom Christiansen <tchrist@mox.perl.com>.  The modifications to
1604 work with Pod::Simple instead of Pod::Parser were originally contributed by
1605 Sean Burke (but I've since hacked them beyond recognition and all bugs are
1606 mine).
1607
1608 =head1 COPYRIGHT AND LICENSE
1609
1610 Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005
1611 by Russ Allbery <rra@stanford.edu>.
1612
1613 This program is free software; you may redistribute it and/or modify it
1614 under the same terms as Perl itself.
1615
1616 =head1 SEE ALSO
1617
1618 L<Pod::Simple>, L<perlpod(1)>, L<pod2man(1)>, L<nroff(1)>, L<troff(1)>,
1619 L<man(1)>, L<man(7)>
1620
1621 Ossanna, Joseph F., and Brian W. Kernighan.  "Troff User's Manual,"
1622 Computing Science Technical Report No. 54, AT&T Bell Laboratories.  This is
1623 the best documentation of standard B<nroff> and B<troff>.  At the time of
1624 this writing, it's available at
1625 L<http://www.cs.bell-labs.com/cm/cs/cstr.html>.
1626
1627 The man page documenting the man macro set may be L<man(5)> instead of
1628 L<man(7)> on your system.  Also, please see L<pod2man(1)> for extensive
1629 documentation on writing manual pages if you've not done it before and
1630 aren't familiar with the conventions.
1631
1632 The current version of this module is always available from its web site at
1633 L<http://www.eyrie.org/~eagle/software/podlators/>.  It is also part of the
1634 Perl core distribution as of 5.6.0.
1635
1636 =cut