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