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