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