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