Upgrade to podlators-2.04
[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.9 2006-02-19 23:02:35 eagle Exp $
3 #
4 # Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
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.09;
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.  Pod::Simple returns a completely unuseful stringified file
823 # handle as the source_filename for input from a file handle, so we have to
824 # deal with that as well.
825 sub devise_date {
826     my ($self) = @_;
827     my $input = $self->source_filename;
828     my $time;
829     if ($input) {
830         $time = (stat $input)[9] || time;
831     } else {
832         $time = time;
833     }
834     return strftime ('%Y-%m-%d', localtime $time);
835 }
836
837 # Print out the preamble and the title.  The meaning of the arguments to .TH
838 # unfortunately vary by system; some systems consider the fourth argument to
839 # be a "source" and others use it as a version number.  Generally it's just
840 # presented as the left-side footer, though, so it doesn't matter too much if
841 # a particular system gives it another interpretation.
842 #
843 # The order of date and release used to be reversed in older versions of this
844 # module, but this order is correct for both Solaris and Linux.
845 sub preamble {
846     my ($self, $name, $section, $date) = @_;
847     my $preamble = $self->preamble_template;
848
849     # Build the index line and make sure that it will be syntactically valid.
850     my $index = "$name $section";
851     $index =~ s/\"/\"\"/g;
852
853     # If name or section contain spaces, quote them (section really never
854     # should, but we may as well be cautious).
855     for ($name, $section) {
856         if (/\s/) {
857             s/\"/\"\"/g;
858             $_ = '"' . $_ . '"';
859         }
860     }
861
862     # Double quotes in date, since it will be quoted.
863     $date =~ s/\"/\"\"/g;
864
865     # Substitute into the preamble the configuration options.
866     $preamble =~ s/\@CFONT\@/$$self{fixed}/;
867     $preamble =~ s/\@LQUOTE\@/$$self{LQUOTE}/;
868     $preamble =~ s/\@RQUOTE\@/$$self{RQUOTE}/;
869     chomp $preamble;
870
871     # Get the version information.
872     my $version = $self->version_report;
873
874     # Finally output everything.
875     $self->output (<<"----END OF HEADER----");
876 .\\" Automatically generated by $version
877 .\\"
878 .\\" Standard preamble:
879 .\\" ========================================================================
880 $preamble
881 .\\" ========================================================================
882 .\\"
883 .IX Title "$index"
884 .TH $name $section "$date" "$$self{release}" "$$self{center}"
885 ----END OF HEADER----
886     $self->output (".\\\" [End of preamble]\n") if DEBUG;
887 }
888
889 ##############################################################################
890 # Text blocks
891 ##############################################################################
892
893 # Handle a basic block of text.  The only tricky part of this is if this is
894 # the first paragraph of text after an =over, in which case we have to change
895 # indentations for *roff.
896 sub cmd_para {
897     my ($self, $attrs, $text) = @_;
898     my $line = $$attrs{start_line};
899
900     # Output the paragraph.  We also have to handle =over without =item.  If
901     # there's an =over without =item, SHIFTWAIT will be set, and we need to
902     # handle creation of the indent here.  Add the shift to SHIFTS so that it
903     # will be cleaned up on =back.
904     $self->makespace;
905     if ($$self{SHIFTWAIT}) {
906         $self->output (".RS $$self{INDENT}\n");
907         push (@{ $$self{SHIFTS} }, $$self{INDENT});
908         $$self{SHIFTWAIT} = 0;
909     }
910
911     # Add the line number for debugging, but not in the NAME section just in
912     # case the comment would confuse apropos.
913     $self->output (".\\\" [At source line $line]\n")
914         if defined ($line) && DEBUG && !$$self{IN_NAME};
915
916     # Force exactly one newline at the end and strip unwanted trailing
917     # whitespace at the end.
918     $text =~ s/\s*$/\n/;
919
920     # Output the paragraph.
921     $self->output ($self->protect ($self->textmapfonts ($text)));
922     $self->outindex;
923     $$self{NEEDSPACE} = 1;
924     return '';
925 }
926
927 # Handle a verbatim paragraph.  Put a null token at the beginning of each line
928 # to protect against commands and wrap in .Vb/.Ve (which we define in our
929 # prelude).
930 sub cmd_verbatim {
931     my ($self, $attrs, $text) = @_;
932
933     # Ignore an empty verbatim paragraph.
934     return unless $text =~ /\S/;
935
936     # Force exactly one newline at the end and strip unwanted trailing
937     # whitespace at the end.
938     $text =~ s/\s*$/\n/;
939
940     # Get a count of the number of lines before the first blank line, which
941     # we'll pass to .Vb as its parameter.  This tells *roff to keep that many
942     # lines together.  We don't want to tell *roff to keep huge blocks
943     # together.
944     my @lines = split (/\n/, $text);
945     my $unbroken = 0;
946     for (@lines) {
947         last if /^\s*$/;
948         $unbroken++;
949     }
950     $unbroken = 10 if ($unbroken > 12 && !$$self{MAGIC_VNOPAGEBREAK_LIMIT});
951
952     # Prepend a null token to each line.
953     $text =~ s/^/\\&/gm;
954
955     # Output the results.
956     $self->makespace;
957     $self->output (".Vb $unbroken\n$text.Ve\n");
958     $$self{NEEDSPACE} = 1;
959     return '';
960 }
961
962 # Handle literal text (produced by =for and similar constructs).  Just output
963 # it with the minimum of changes.
964 sub cmd_data {
965     my ($self, $attrs, $text) = @_;
966     $text =~ s/^\n+//;
967     $text =~ s/\n{0,2}$/\n/;
968     $self->output ($text);
969     return '';
970 }
971
972 ##############################################################################
973 # Headings
974 ##############################################################################
975
976 # Common code for all headings.  This is called before the actual heading is
977 # output.  It returns the cleaned up heading text (putting the heading all on
978 # one line) and may do other things, like closing bad =item blocks.
979 sub heading_common {
980     my ($self, $text, $line) = @_;
981     $text =~ s/\s+$//;
982     $text =~ s/\s*\n\s*/ /g;
983
984     # This should never happen; it means that we have a heading after =item
985     # without an intervening =back.  But just in case, handle it anyway.
986     if ($$self{ITEMS} > 1) {
987         $$self{ITEMS} = 0;
988         $self->output (".PD\n");
989     }
990
991     # Output the current source line.
992     $self->output ( ".\\\" [At source line $line]\n" )
993         if defined ($line) && DEBUG;
994     return $text;
995 }
996
997 # First level heading.  We can't output .IX in the NAME section due to a bug
998 # in some versions of catman, so don't output a .IX for that section.  .SH
999 # already uses small caps, so remove \s0 and \s-1.  Maintain IN_NAME as
1000 # appropriate.
1001 sub cmd_head1 {
1002     my ($self, $attrs, $text) = @_;
1003     $text =~ s/\\s-?\d//g;
1004     $text = $self->heading_common ($text, $$attrs{start_line});
1005     my $isname = ($text eq 'NAME' || $text =~ /\(NAME\)/);
1006     $self->output ($self->switchquotes ('.SH', $self->mapfonts ($text)));
1007     $self->outindex ('Header', $text) unless $isname;
1008     $$self{NEEDSPACE} = 0;
1009     $$self{IN_NAME} = $isname;
1010     return '';
1011 }
1012
1013 # Second level heading.
1014 sub cmd_head2 {
1015     my ($self, $attrs, $text) = @_;
1016     $text = $self->heading_common ($text, $$attrs{start_line});
1017     $self->output ($self->switchquotes ('.Sh', $self->mapfonts ($text)));
1018     $self->outindex ('Subsection', $text);
1019     $$self{NEEDSPACE} = 0;
1020     return '';
1021 }
1022
1023 # Third level heading.  *roff doesn't have this concept, so just put the
1024 # heading in italics as a normal paragraph.
1025 sub cmd_head3 {
1026     my ($self, $attrs, $text) = @_;
1027     $text = $self->heading_common ($text, $$attrs{start_line});
1028     $self->makespace;
1029     $self->output ($self->textmapfonts ('\f(IS' . $text . '\f(IE') . "\n");
1030     $self->outindex ('Subsection', $text);
1031     $$self{NEEDSPACE} = 1;
1032     return '';
1033 }
1034
1035 # Fourth level heading.  *roff doesn't have this concept, so just put the
1036 # heading as a normal paragraph.
1037 sub cmd_head4 {
1038     my ($self, $attrs, $text) = @_;
1039     $text = $self->heading_common ($text, $$attrs{start_line});
1040     $self->makespace;
1041     $self->output ($self->textmapfonts ($text) . "\n");
1042     $self->outindex ('Subsection', $text);
1043     $$self{NEEDSPACE} = 1;
1044     return '';
1045 }
1046
1047 ##############################################################################
1048 # Formatting codes
1049 ##############################################################################
1050
1051 # All of the formatting codes that aren't handled internally by the parser,
1052 # other than L<> and X<>.
1053 sub cmd_b { return '\f(BS' . $_[2] . '\f(BE' }
1054 sub cmd_i { return '\f(IS' . $_[2] . '\f(IE' }
1055 sub cmd_f { return '\f(IS' . $_[2] . '\f(IE' }
1056 sub cmd_c { return $_[0]->quote_literal ($_[2]) }
1057
1058 # Index entries are just added to the pending entries.
1059 sub cmd_x {
1060     my ($self, $attrs, $text) = @_;
1061     push (@{ $$self{INDEX} }, $text);
1062     return '';
1063 }
1064
1065 # Links reduce to the text that we're given, wrapped in angle brackets if it's
1066 # a URL.
1067 sub cmd_l {
1068     my ($self, $attrs, $text) = @_;
1069     return $$attrs{type} eq 'url' ? "<$text>" : $text;
1070 }
1071
1072 ##############################################################################
1073 # List handling
1074 ##############################################################################
1075
1076 # Handle the beginning of an =over block.  Takes the type of the block as the
1077 # first argument, and then the attr hash.  This is called by the handlers for
1078 # the four different types of lists (bullet, number, text, and block).
1079 sub over_common_start {
1080     my ($self, $type, $attrs) = @_;
1081     my $line = $$attrs{start_line};
1082     my $indent = $$attrs{indent};
1083     DEBUG > 3 and print " Starting =over $type (line $line, indent ",
1084         ($indent || '?'), "\n";
1085
1086     # Find the indentation level.
1087     unless (defined ($indent) && $indent =~ /^[-+]?\d{1,4}\s*$/) {
1088         $indent = $$self{indent};
1089     }
1090
1091     # If we've gotten multiple indentations in a row, we need to emit the
1092     # pending indentation for the last level that we saw and haven't acted on
1093     # yet.  SHIFTS is the stack of indentations that we've actually emitted
1094     # code for.
1095     if (@{ $$self{SHIFTS} } < @{ $$self{INDENTS} }) {
1096         $self->output (".RS $$self{INDENT}\n");
1097         push (@{ $$self{SHIFTS} }, $$self{INDENT});
1098     }
1099
1100     # Now, do record-keeping.  INDENTS is a stack of indentations that we've
1101     # seen so far, and INDENT is the current level of indentation.  ITEMTYPES
1102     # is a stack of list types that we've seen.
1103     push (@{ $$self{INDENTS} }, $$self{INDENT});
1104     push (@{ $$self{ITEMTYPES} }, $type);
1105     $$self{INDENT} = $indent + 0;
1106     $$self{SHIFTWAIT} = 1;
1107 }
1108
1109 # End an =over block.  Takes no options other than the class pointer.
1110 # Normally, once we close a block and therefore remove something from INDENTS,
1111 # INDENTS will now be longer than SHIFTS, indicating that we also need to emit
1112 # *roff code to close the indent.  This isn't *always* true, depending on the
1113 # circumstance.  If we're still inside an indentation, we need to emit another
1114 # .RE and then a new .RS to unconfuse *roff.
1115 sub over_common_end {
1116     my ($self) = @_;
1117     DEBUG > 3 and print " Ending =over\n";
1118     $$self{INDENT} = pop @{ $$self{INDENTS} };
1119     pop @{ $$self{ITEMTYPES} };
1120
1121     # If we emitted code for that indentation, end it.
1122     if (@{ $$self{SHIFTS} } > @{ $$self{INDENTS} }) {
1123         $self->output (".RE\n");
1124         pop @{ $$self{SHIFTS} };
1125     }
1126
1127     # If we're still in an indentation, *roff will have now lost track of the
1128     # right depth of that indentation, so fix that.
1129     if (@{ $$self{INDENTS} } > 0) {
1130         $self->output (".RE\n");
1131         $self->output (".RS $$self{INDENT}\n");
1132     }
1133     $$self{NEEDSPACE} = 1;
1134     $$self{SHIFTWAIT} = 0;
1135 }
1136
1137 # Dispatch the start and end calls as appropriate.
1138 sub start_over_bullet { my $s = shift; $s->over_common_start ('bullet', @_) }
1139 sub start_over_number { my $s = shift; $s->over_common_start ('number', @_) }
1140 sub start_over_text   { my $s = shift; $s->over_common_start ('text',   @_) }
1141 sub start_over_block  { my $s = shift; $s->over_common_start ('block',  @_) }
1142 sub end_over_bullet { $_[0]->over_common_end }
1143 sub end_over_number { $_[0]->over_common_end }
1144 sub end_over_text   { $_[0]->over_common_end }
1145 sub end_over_block  { $_[0]->over_common_end }
1146
1147 # The common handler for all item commands.  Takes the type of the item, the
1148 # attributes, and then the text of the item.
1149 #
1150 # Emit an index entry for anything that's interesting, but don't emit index
1151 # entries for things like bullets and numbers.  Newlines in an item title are
1152 # turned into spaces since *roff can't handle them embedded.
1153 sub item_common {
1154     my ($self, $type, $attrs, $text) = @_;
1155     my $line = $$attrs{start_line};
1156     DEBUG > 3 and print "  $type item (line $line): $text\n";
1157
1158     # Clean up the text.  We want to end up with two variables, one ($text)
1159     # which contains any body text after taking out the item portion, and
1160     # another ($item) which contains the actual item text.
1161     $text =~ s/\s+$//;
1162     my ($item, $index);
1163     if ($type eq 'bullet') {
1164         $item = "\\\(bu";
1165         $text =~ s/\n*$/\n/;
1166     } elsif ($type eq 'number') {
1167         $item = $$attrs{number} . '.';
1168     } else {
1169         $item = $text;
1170         $item =~ s/\s*\n\s*/ /g;
1171         $text = '';
1172         $index = $item if ($item =~ /\w/);
1173     }
1174
1175     # Take care of the indentation.  If shifts and indents are equal, close
1176     # the top shift, since we're about to create an indentation with .IP.
1177     # Also output .PD 0 to turn off spacing between items if this item is
1178     # directly following another one.  We only have to do that once for a
1179     # whole chain of items so do it for the second item in the change.  Note
1180     # that makespace is what undoes this.
1181     if (@{ $$self{SHIFTS} } == @{ $$self{INDENTS} }) {
1182         $self->output (".RE\n");
1183         pop @{ $$self{SHIFTS} };
1184     }
1185     $self->output (".PD 0\n") if ($$self{ITEMS} == 1);
1186
1187     # Now, output the item tag itself.
1188     $item = $self->textmapfonts ($item);
1189     $self->output ($self->switchquotes ('.IP', $item, $$self{INDENT}));
1190     $$self{NEEDSPACE} = 0;
1191     $$self{ITEMS}++;
1192     $$self{SHIFTWAIT} = 0;
1193
1194     # If body text for this item was included, go ahead and output that now.
1195     if ($text) {
1196         $text =~ s/\s*$/\n/;
1197         $self->makespace;
1198         $self->output ($self->protect ($self->textmapfonts ($text)));
1199         $$self{NEEDSPACE} = 1;
1200     }
1201     $self->outindex ($index ? ('Item', $index) : ());
1202 }
1203
1204 # Dispatch the item commands to the appropriate place.
1205 sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) }
1206 sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) }
1207 sub cmd_item_text   { my $self = shift; $self->item_common ('text',   @_) }
1208 sub cmd_item_block  { my $self = shift; $self->item_common ('block',  @_) }
1209
1210 ##############################################################################
1211 # Backward compatibility
1212 ##############################################################################
1213
1214 # Reset the underlying Pod::Simple object between calls to parse_from_file so
1215 # that the same object can be reused to convert multiple pages.
1216 sub parse_from_file {
1217     my $self = shift;
1218     $self->reinit;
1219     my $retval = $self->SUPER::parse_from_file (@_);
1220     my $fh = $self->output_fh ();
1221     my $oldfh = select $fh;
1222     my $oldflush = $|;
1223     $| = 1;
1224     print $fh '';
1225     $| = $oldflush;
1226     select $oldfh;
1227     return $retval;
1228 }
1229
1230 # Pod::Simple failed to provide this backward compatibility function, so
1231 # implement it ourselves.  File handles are one of the inputs that
1232 # parse_from_file supports.
1233 sub parse_from_filehandle {
1234     my $self = shift;
1235     $self->parse_from_file (@_);
1236 }
1237
1238 ##############################################################################
1239 # Translation tables
1240 ##############################################################################
1241
1242 # The following table is adapted from Tom Christiansen's pod2man.  It assumes
1243 # that the standard preamble has already been printed, since that's what
1244 # defines all of the accent marks.  We really want to do something better than
1245 # this when *roff actually supports other character sets itself, since these
1246 # results are pretty poor.
1247 #
1248 # This only works in an ASCII world.  What to do in a non-ASCII world is very
1249 # unclear.
1250 @ESCAPES{0xA0 .. 0xFF} = (
1251     "\\ ", undef, undef, undef,            undef, undef, undef, undef,
1252     undef, undef, undef, undef,            undef, "\\%", undef, undef,
1253
1254     undef, undef, undef, undef,            undef, undef, undef, undef,
1255     undef, undef, undef, undef,            undef, undef, undef, undef,
1256
1257     "A\\*`",  "A\\*'", "A\\*^", "A\\*~",   "A\\*:", "A\\*o", "\\*(AE", "C\\*,",
1258     "E\\*`",  "E\\*'", "E\\*^", "E\\*:",   "I\\*`", "I\\*'", "I\\*^",  "I\\*:",
1259
1260     "\\*(D-", "N\\*~", "O\\*`", "O\\*'",   "O\\*^", "O\\*~", "O\\*:",  undef,
1261     "O\\*/",  "U\\*`", "U\\*'", "U\\*^",   "U\\*:", "Y\\*'", "\\*(Th", "\\*8",
1262
1263     "a\\*`",  "a\\*'", "a\\*^", "a\\*~",   "a\\*:", "a\\*o", "\\*(ae", "c\\*,",
1264     "e\\*`",  "e\\*'", "e\\*^", "e\\*:",   "i\\*`", "i\\*'", "i\\*^",  "i\\*:",
1265
1266     "\\*(d-", "n\\*~", "o\\*`", "o\\*'",   "o\\*^", "o\\*~", "o\\*:",  undef,
1267     "o\\*/" , "u\\*`", "u\\*'", "u\\*^",   "u\\*:", "y\\*'", "\\*(th", "y\\*:",
1268 ) if ASCII;
1269
1270 # Make sure that at least this works even outside of ASCII.
1271 $ESCAPES{ord("\\")} = "\\e";
1272
1273 ##############################################################################
1274 # Premable
1275 ##############################################################################
1276
1277 # The following is the static preamble which starts all *roff output we
1278 # generate.  It's completely static except for the font to use as a
1279 # fixed-width font, which is designed by @CFONT@, and the left and right
1280 # quotes to use for C<> text, designated by @LQOUTE@ and @RQUOTE@.
1281 sub preamble_template {
1282     return <<'----END OF PREAMBLE----';
1283 .de Sh \" Subsection heading
1284 .br
1285 .if t .Sp
1286 .ne 5
1287 .PP
1288 \fB\\$1\fR
1289 .PP
1290 ..
1291 .de Sp \" Vertical space (when we can't use .PP)
1292 .if t .sp .5v
1293 .if n .sp
1294 ..
1295 .de Vb \" Begin verbatim text
1296 .ft @CFONT@
1297 .nf
1298 .ne \\$1
1299 ..
1300 .de Ve \" End verbatim text
1301 .ft R
1302 .fi
1303 ..
1304 .\" Set up some character translations and predefined strings.  \*(-- will
1305 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
1306 .\" double quote, and \*(R" will give a right double quote.  | will give a
1307 .\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
1308 .\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
1309 .\" expand to `' in nroff, nothing in troff, for use with C<>.
1310 .tr \(*W-|\(bv\*(Tr
1311 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
1312 .ie n \{\
1313 .    ds -- \(*W-
1314 .    ds PI pi
1315 .    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
1316 .    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
1317 .    ds L" ""
1318 .    ds R" ""
1319 .    ds C` @LQUOTE@
1320 .    ds C' @RQUOTE@
1321 'br\}
1322 .el\{\
1323 .    ds -- \|\(em\|
1324 .    ds PI \(*p
1325 .    ds L" ``
1326 .    ds R" ''
1327 'br\}
1328 .\"
1329 .\" If the F register is turned on, we'll generate index entries on stderr for
1330 .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
1331 .\" entries marked with X<> in POD.  Of course, you'll have to process the
1332 .\" output yourself in some meaningful fashion.
1333 .if \nF \{\
1334 .    de IX
1335 .    tm Index:\\$1\t\\n%\t"\\$2"
1336 ..
1337 .    nr % 0
1338 .    rr F
1339 .\}
1340 .\"
1341 .\" For nroff, turn off justification.  Always turn off hyphenation; it makes
1342 .\" way too many mistakes in technical documents.
1343 .hy 0
1344 .if n .na
1345 .\"
1346 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
1347 .\" Fear.  Run.  Save yourself.  No user-serviceable parts.
1348 .    \" fudge factors for nroff and troff
1349 .if n \{\
1350 .    ds #H 0
1351 .    ds #V .8m
1352 .    ds #F .3m
1353 .    ds #[ \f1
1354 .    ds #] \fP
1355 .\}
1356 .if t \{\
1357 .    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
1358 .    ds #V .6m
1359 .    ds #F 0
1360 .    ds #[ \&
1361 .    ds #] \&
1362 .\}
1363 .    \" simple accents for nroff and troff
1364 .if n \{\
1365 .    ds ' \&
1366 .    ds ` \&
1367 .    ds ^ \&
1368 .    ds , \&
1369 .    ds ~ ~
1370 .    ds /
1371 .\}
1372 .if t \{\
1373 .    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
1374 .    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
1375 .    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
1376 .    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
1377 .    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
1378 .    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
1379 .\}
1380 .    \" troff and (daisy-wheel) nroff accents
1381 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
1382 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
1383 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
1384 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
1385 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
1386 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
1387 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
1388 .ds ae a\h'-(\w'a'u*4/10)'e
1389 .ds Ae A\h'-(\w'A'u*4/10)'E
1390 .    \" corrections for vroff
1391 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
1392 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
1393 .    \" for low resolution devices (crt and lpr)
1394 .if \n(.H>23 .if \n(.V>19 \
1395 \{\
1396 .    ds : e
1397 .    ds 8 ss
1398 .    ds o a
1399 .    ds d- d\h'-1'\(ga
1400 .    ds D- D\h'-1'\(hy
1401 .    ds th \o'bp'
1402 .    ds Th \o'LP'
1403 .    ds ae ae
1404 .    ds Ae AE
1405 .\}
1406 .rm #[ #] #H #V #F C
1407 ----END OF PREAMBLE----
1408 #`# for cperl-mode
1409 }
1410
1411 ##############################################################################
1412 # Module return value and documentation
1413 ##############################################################################
1414
1415 1;
1416 __END__
1417
1418 =head1 NAME
1419
1420 Pod::Man - Convert POD data to formatted *roff input
1421
1422 =head1 SYNOPSIS
1423
1424     use Pod::Man;
1425     my $parser = Pod::Man->new (release => $VERSION, section => 8);
1426
1427     # Read POD from STDIN and write to STDOUT.
1428     $parser->parse_file (\*STDIN);
1429
1430     # Read POD from file.pod and write to file.1.
1431     $parser->parse_from_file ('file.pod', 'file.1');
1432
1433 =head1 DESCRIPTION
1434
1435 Pod::Man is a module to convert documentation in the POD format (the
1436 preferred language for documenting Perl) into *roff input using the man
1437 macro set.  The resulting *roff code is suitable for display on a terminal
1438 using L<nroff(1)>, normally via L<man(1)>, or printing using L<troff(1)>.
1439 It is conventionally invoked using the driver script B<pod2man>, but it can
1440 also be used directly.
1441
1442 As a derived class from Pod::Simple, Pod::Man supports the same methods and
1443 interfaces.  See L<Pod::Simple> for all the details.
1444
1445 new() can take options, in the form of key/value pairs that control the
1446 behavior of the parser.  See below for details.
1447
1448 If no options are given, Pod::Man uses the name of the input file with any
1449 trailing C<.pod>, C<.pm>, or C<.pl> stripped as the man page title, to
1450 section 1 unless the file ended in C<.pm> in which case it defaults to
1451 section 3, to a centered title of "User Contributed Perl Documentation", to
1452 a centered footer of the Perl version it is run with, and to a left-hand
1453 footer of the modification date of its input (or the current date if given
1454 STDIN for input).
1455
1456 Pod::Man assumes that your *roff formatters have a fixed-width font named
1457 CW.  If yours is called something else (like CR), use the C<fixed> option to
1458 specify it.  This generally only matters for troff output for printing.
1459 Similarly, you can set the fonts used for bold, italic, and bold italic
1460 fixed-width output.
1461
1462 Besides the obvious pod conversions, Pod::Man also takes care of formatting
1463 func(), func(3), and simple variable references like $foo or @bar so you
1464 don't have to use code escapes for them; complex expressions like
1465 C<$fred{'stuff'}> will still need to be escaped, though.  It also translates
1466 dashes that aren't used as hyphens into en dashes, makes long dashes--like
1467 this--into proper em dashes, fixes "paired quotes," makes C++ look right,
1468 puts a little space between double underbars, makes ALLCAPS a teeny bit
1469 smaller in B<troff>, and escapes stuff that *roff treats as special so that
1470 you don't have to.
1471
1472 The recognized options to new() are as follows.  All options take a single
1473 argument.
1474
1475 =over 4
1476
1477 =item center
1478
1479 Sets the centered page header to use instead of "User Contributed Perl
1480 Documentation".
1481
1482 =item date
1483
1484 Sets the left-hand footer.  By default, the modification date of the input
1485 file will be used, or the current date if stat() can't find that file (the
1486 case if the input is from STDIN), and the date will be formatted as
1487 YYYY-MM-DD.
1488
1489 =item fixed
1490
1491 The fixed-width font to use for vertabim text and code.  Defaults to CW.
1492 Some systems may want CR instead.  Only matters for B<troff> output.
1493
1494 =item fixedbold
1495
1496 Bold version of the fixed-width font.  Defaults to CB.  Only matters for
1497 B<troff> output.
1498
1499 =item fixeditalic
1500
1501 Italic version of the fixed-width font (actually, something of a misnomer,
1502 since most fixed-width fonts only have an oblique version, not an italic
1503 version).  Defaults to CI.  Only matters for B<troff> output.
1504
1505 =item fixedbolditalic
1506
1507 Bold italic (probably actually oblique) version of the fixed-width font.
1508 Pod::Man doesn't assume you have this, and defaults to CB.  Some systems
1509 (such as Solaris) have this font available as CX.  Only matters for B<troff>
1510 output.
1511
1512 =item name
1513
1514 Set the name of the manual page.  Without this option, the manual name is
1515 set to the uppercased base name of the file being converted unless the
1516 manual section is 3, in which case the path is parsed to see if it is a Perl
1517 module path.  If it is, a path like C<.../lib/Pod/Man.pm> is converted into
1518 a name like C<Pod::Man>.  This option, if given, overrides any automatic
1519 determination of the name.
1520
1521 =item quotes
1522
1523 Sets the quote marks used to surround CE<lt>> text.  If the value is a
1524 single character, it is used as both the left and right quote; if it is two
1525 characters, the first character is used as the left quote and the second as
1526 the right quoted; and if it is four characters, the first two are used as
1527 the left quote and the second two as the right quote.
1528
1529 This may also be set to the special value C<none>, in which case no quote
1530 marks are added around CE<lt>> text (but the font is still changed for troff
1531 output).
1532
1533 =item release
1534
1535 Set the centered footer.  By default, this is the version of Perl you run
1536 Pod::Man under.  Note that some system an macro sets assume that the
1537 centered footer will be a modification date and will prepend something like
1538 "Last modified: "; if this is the case, you may want to set C<release> to
1539 the last modified date and C<date> to the version number.
1540
1541 =item section
1542
1543 Set the section for the C<.TH> macro.  The standard section numbering
1544 convention is to use 1 for user commands, 2 for system calls, 3 for
1545 functions, 4 for devices, 5 for file formats, 6 for games, 7 for
1546 miscellaneous information, and 8 for administrator commands.  There is a lot
1547 of variation here, however; some systems (like Solaris) use 4 for file
1548 formats, 5 for miscellaneous information, and 7 for devices.  Still others
1549 use 1m instead of 8, or some mix of both.  About the only section numbers
1550 that are reliably consistent are 1, 2, and 3.
1551
1552 By default, section 1 will be used unless the file ends in .pm in which case
1553 section 3 will be selected.
1554
1555 =back
1556
1557 The standard Pod::Simple method parse_file() takes one argument naming the
1558 POD file to read from.  By default, the output is sent to STDOUT, but this
1559 can be changed with the output_fd() method.
1560
1561 The standard Pod::Simple method parse_from_file() takes up to two
1562 arguments, the first being the input file to read POD from and the second
1563 being the file to write the formatted output to.
1564
1565 You can also call parse_lines() to parse an array of lines or
1566 parse_string_document() to parse a document already in memory.  To put the
1567 output into a string instead of a file handle, call the output_string()
1568 method.  See L<Pod::Simple> for the specific details.
1569
1570 =head1 DIAGNOSTICS
1571
1572 =over 4
1573
1574 =item roff font should be 1 or 2 chars, not "%s"
1575
1576 (F) You specified a *roff font (using C<fixed>, C<fixedbold>, etc.) that
1577 wasn't either one or two characters.  Pod::Man doesn't support *roff fonts
1578 longer than two characters, although some *roff extensions do (the canonical
1579 versions of B<nroff> and B<troff> don't either).
1580
1581 =item Invalid quote specification "%s"
1582
1583 (F) The quote specification given (the quotes option to the constructor) was
1584 invalid.  A quote specification must be one, two, or four characters long.
1585
1586 =back
1587
1588 =head1 BUGS
1589
1590 Eight-bit input data isn't handled at all well at present.  The correct
1591 approach would be to map EE<lt>E<gt> escapes to the appropriate UTF-8
1592 characters and then do a translation pass on the output according to the
1593 user-specified output character set.  Unfortunately, we can't send eight-bit
1594 data directly to the output unless the user says this is okay, since some
1595 vendor *roff implementations can't handle eight-bit data.  If the *roff
1596 implementation can, however, that's far superior to the current hacked
1597 characters that only work under troff.
1598
1599 There is currently no way to turn off the guesswork that tries to format
1600 unmarked text appropriately, and sometimes it isn't wanted (particularly
1601 when using POD to document something other than Perl).  Most of the work
1602 towards fixing this has now been done, however, and all that's still needed
1603 is a user interface.
1604
1605 The NAME section should be recognized specially and index entries emitted
1606 for everything in that section.  This would have to be deferred until the
1607 next section, since extraneous things in NAME tends to confuse various man
1608 page processors.  Currently, no index entries are emitted for anything in
1609 NAME.
1610
1611 Pod::Man doesn't handle font names longer than two characters.  Neither do
1612 most B<troff> implementations, but GNU troff does as an extension.  It would
1613 be nice to support as an option for those who want to use it.
1614
1615 The preamble added to each output file is rather verbose, and most of it
1616 is only necessary in the presence of non-ASCII characters.  It would
1617 ideally be nice if all of those definitions were only output if needed,
1618 perhaps on the fly as the characters are used.
1619
1620 Pod::Man is excessively slow.
1621
1622 =head1 CAVEATS
1623
1624 The handling of hyphens and em dashes is somewhat fragile, and one may get
1625 the wrong one under some circumstances.  This should only matter for
1626 B<troff> output.
1627
1628 When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
1629 necessarily get it right.
1630
1631 Converting neutral double quotes to properly matched double quotes doesn't
1632 work unless there are no formatting codes between the quote marks.  This
1633 only matters for troff output.
1634
1635 =head1 AUTHOR
1636
1637 Russ Allbery <rra@stanford.edu>, based I<very> heavily on the original
1638 B<pod2man> by Tom Christiansen <tchrist@mox.perl.com>.  The modifications to
1639 work with Pod::Simple instead of Pod::Parser were originally contributed by
1640 Sean Burke (but I've since hacked them beyond recognition and all bugs are
1641 mine).
1642
1643 =head1 COPYRIGHT AND LICENSE
1644
1645 Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
1646 by Russ Allbery <rra@stanford.edu>.
1647
1648 This program is free software; you may redistribute it and/or modify it
1649 under the same terms as Perl itself.
1650
1651 =head1 SEE ALSO
1652
1653 L<Pod::Simple>, L<perlpod(1)>, L<pod2man(1)>, L<nroff(1)>, L<troff(1)>,
1654 L<man(1)>, L<man(7)>
1655
1656 Ossanna, Joseph F., and Brian W. Kernighan.  "Troff User's Manual,"
1657 Computing Science Technical Report No. 54, AT&T Bell Laboratories.  This is
1658 the best documentation of standard B<nroff> and B<troff>.  At the time of
1659 this writing, it's available at
1660 L<http://www.cs.bell-labs.com/cm/cs/cstr.html>.
1661
1662 The man page documenting the man macro set may be L<man(5)> instead of
1663 L<man(7)> on your system.  Also, please see L<pod2man(1)> for extensive
1664 documentation on writing manual pages if you've not done it before and
1665 aren't familiar with the conventions.
1666
1667 The current version of this module is always available from its web site at
1668 L<http://www.eyrie.org/~eagle/software/podlators/>.  It is also part of the
1669 Perl core distribution as of 5.6.0.
1670
1671 =cut