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