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