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