Integrate changes #8659,8702,8808,8809,8810 from maintperl.
[p5sagit/p5-mst-13.2.git] / lib / Pod / Man.pm
1 # Pod::Man -- Convert POD data to formatted *roff input.
2 # $Id: Man.pm,v 1.15 2001/02/10 06:50:22 eagle Exp $
3 #
4 # Copyright 1999, 2000, 2001 by Russ Allbery <rra@stanford.edu>
5 #
6 # This program is free software; you can redistribute it and/or modify it
7 # under the same terms as Perl itself.
8 #
9 # This module is intended to be a replacement for the pod2man script
10 # distributed with versions of Perl prior to 5.6, and attempts to match its
11 # output except for some specific circumstances where other decisions seemed
12 # to produce better output.  It uses Pod::Parser and is designed to be easy
13 # to subclass.
14 #
15 # Perl core hackers, please note that this module is also separately
16 # maintained outside of the Perl core as part of the podlators.  Please send
17 # me any patches at the address above in addition to sending them to the
18 # standard Perl mailing lists.
19
20 ############################################################################
21 # Modules and declarations
22 ############################################################################
23
24 package Pod::Man;
25
26 require 5.004;
27
28 use Carp qw(carp croak);
29 use Pod::Parser ();
30
31 use strict;
32 use subs qw(makespace);
33 use vars qw(@ISA %ESCAPES $PREAMBLE $VERSION);
34
35 @ISA = qw(Pod::Parser);
36
37 # Don't use the CVS revision as the version, since this module is also in
38 # Perl core and too many things could munge CVS magic revision strings.
39 # This number should ideally be the same as the CVS revision in podlators,
40 # however.
41 $VERSION = 1.15;
42
43
44 ############################################################################
45 # Preamble and *roff output tables
46 ############################################################################
47
48 # The following is the static preamble which starts all *roff output we
49 # generate.  It's completely static except for the font to use as a
50 # fixed-width font, which is designed by @CFONT@, and the left and right
51 # quotes to use for C<> text, designated by @LQOUTE@ and @RQUOTE@.
52 # $PREAMBLE should therefore be run through s/\@CFONT\@/<font>/g before
53 # output.
54 $PREAMBLE = <<'----END OF PREAMBLE----';
55 .de Sh \" Subsection heading
56 .br
57 .if t .Sp
58 .ne 5
59 .PP
60 \fB\\$1\fR
61 .PP
62 ..
63 .de Sp \" Vertical space (when we can't use .PP)
64 .if t .sp .5v
65 .if n .sp
66 ..
67 .de Ip \" List item
68 .br
69 .ie \\n(.$>=3 .ne \\$3
70 .el .ne 3
71 .IP "\\$1" \\$2
72 ..
73 .de Vb \" Begin verbatim text
74 .ft @CFONT@
75 .nf
76 .ne \\$1
77 ..
78 .de Ve \" End verbatim text
79 .ft R
80
81 .fi
82 ..
83 .\" Set up some character translations and predefined strings.  \*(-- will
84 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
85 .\" double quote, and \*(R" will give a right double quote.  | will give a
86 .\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used
87 .\" to do unbreakable dashes and therefore won't be available.  \*(C` and
88 .\" \*(C' expand to `' in nroff, nothing in troff, for use with C<>
89 .tr \(*W-|\(bv\*(Tr
90 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
91 .ie n \{\
92 .    ds -- \(*W-
93 .    ds PI pi
94 .    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
95 .    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
96 .    ds L" ""
97 .    ds R" ""
98 .    ds C` @LQUOTE@
99 .    ds C' @RQUOTE@
100 'br\}
101 .el\{\
102 .    ds -- \|\(em\|
103 .    ds PI \(*p
104 .    ds L" ``
105 .    ds R" ''
106 'br\}
107 .\"
108 .\" If the F register is turned on, we'll generate index entries on stderr
109 .\" for titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and
110 .\" index entries marked with X<> in POD.  Of course, you'll have to process
111 .\" the output yourself in some meaningful fashion.
112 .if \nF \{\
113 .    de IX
114 .    tm Index:\\$1\t\\n%\t"\\$2"
115 ..
116 .    nr % 0
117 .    rr F
118 .\}
119 .\"
120 .\" For nroff, turn off justification.  Always turn off hyphenation; it
121 .\" makes way too many mistakes in technical documents.
122 .hy 0
123 .if n .na
124 .\"
125 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
126 .\" Fear.  Run.  Save yourself.  No user-serviceable parts.
127 .bd B 3
128 .    \" fudge factors for nroff and troff
129 .if n \{\
130 .    ds #H 0
131 .    ds #V .8m
132 .    ds #F .3m
133 .    ds #[ \f1
134 .    ds #] \fP
135 .\}
136 .if t \{\
137 .    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
138 .    ds #V .6m
139 .    ds #F 0
140 .    ds #[ \&
141 .    ds #] \&
142 .\}
143 .    \" simple accents for nroff and troff
144 .if n \{\
145 .    ds ' \&
146 .    ds ` \&
147 .    ds ^ \&
148 .    ds , \&
149 .    ds ~ ~
150 .    ds /
151 .\}
152 .if t \{\
153 .    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
154 .    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
155 .    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
156 .    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
157 .    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
158 .    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
159 .\}
160 .    \" troff and (daisy-wheel) nroff accents
161 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
162 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
163 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
164 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
165 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
166 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
167 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
168 .ds ae a\h'-(\w'a'u*4/10)'e
169 .ds Ae A\h'-(\w'A'u*4/10)'E
170 .    \" corrections for vroff
171 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
172 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
173 .    \" for low resolution devices (crt and lpr)
174 .if \n(.H>23 .if \n(.V>19 \
175 \{\
176 .    ds : e
177 .    ds 8 ss
178 .    ds o a
179 .    ds d- d\h'-1'\(ga
180 .    ds D- D\h'-1'\(hy
181 .    ds th \o'bp'
182 .    ds Th \o'LP'
183 .    ds ae ae
184 .    ds Ae AE
185 .\}
186 .rm #[ #] #H #V #F C
187 ----END OF PREAMBLE----
188 #`# for cperl-mode
189
190 # This table is taken nearly verbatim from Tom Christiansen's pod2man.  It
191 # assumes that the standard preamble has already been printed, since that's
192 # what defines all of the accent marks.  Note that some of these are quoted
193 # with double quotes since they contain embedded single quotes, so use \\
194 # uniformly for backslash for readability.
195 %ESCAPES = (
196     'amp'       =>    '&',      # ampersand
197     'lt'        =>    '<',      # left chevron, less-than
198     'gt'        =>    '>',      # right chevron, greater-than
199     'quot'      =>    '"',      # double quote
200     'sol'       =>    '/',      # solidus (forward slash)
201     'verbar'    =>    '|',      # vertical bar
202
203     'Aacute'    =>    "A\\*'",  # capital A, acute accent
204     'aacute'    =>    "a\\*'",  # small a, acute accent
205     'Acirc'     =>    'A\\*^',  # capital A, circumflex accent
206     'acirc'     =>    'a\\*^',  # small a, circumflex accent
207     'AElig'     =>    '\*(AE',  # capital AE diphthong (ligature)
208     'aelig'     =>    '\*(ae',  # small ae diphthong (ligature)
209     'Agrave'    =>    "A\\*`",  # capital A, grave accent
210     'agrave'    =>    "A\\*`",  # small a, grave accent
211     'Aring'     =>    'A\\*o',  # capital A, ring
212     'aring'     =>    'a\\*o',  # small a, ring
213     'Atilde'    =>    'A\\*~',  # capital A, tilde
214     'atilde'    =>    'a\\*~',  # small a, tilde
215     'Auml'      =>    'A\\*:',  # capital A, dieresis or umlaut mark
216     'auml'      =>    'a\\*:',  # small a, dieresis or umlaut mark
217     'Ccedil'    =>    'C\\*,',  # capital C, cedilla
218     'ccedil'    =>    'c\\*,',  # small c, cedilla
219     'Eacute'    =>    "E\\*'",  # capital E, acute accent
220     'eacute'    =>    "e\\*'",  # small e, acute accent
221     'Ecirc'     =>    'E\\*^',  # capital E, circumflex accent
222     'ecirc'     =>    'e\\*^',  # small e, circumflex accent
223     'Egrave'    =>    'E\\*`',  # capital E, grave accent
224     'egrave'    =>    'e\\*`',  # small e, grave accent
225     'ETH'       =>    '\\*(D-', # capital Eth, Icelandic
226     'eth'       =>    '\\*(d-', # small eth, Icelandic
227     'Euml'      =>    'E\\*:',  # capital E, dieresis or umlaut mark
228     'euml'      =>    'e\\*:',  # small e, dieresis or umlaut mark
229     'Iacute'    =>    "I\\*'",  # capital I, acute accent
230     'iacute'    =>    "i\\*'",  # small i, acute accent
231     'Icirc'     =>    'I\\*^',  # capital I, circumflex accent
232     'icirc'     =>    'i\\*^',  # small i, circumflex accent
233     'Igrave'    =>    'I\\*`',  # capital I, grave accent
234     'igrave'    =>    'i\\*`',  # small i, grave accent
235     'Iuml'      =>    'I\\*:',  # capital I, dieresis or umlaut mark
236     'iuml'      =>    'i\\*:',  # small i, dieresis or umlaut mark
237     'Ntilde'    =>    'N\*~',   # capital N, tilde
238     'ntilde'    =>    'n\*~',   # small n, tilde
239     'Oacute'    =>    "O\\*'",  # capital O, acute accent
240     'oacute'    =>    "o\\*'",  # small o, acute accent
241     'Ocirc'     =>    'O\\*^',  # capital O, circumflex accent
242     'ocirc'     =>    'o\\*^',  # small o, circumflex accent
243     'Ograve'    =>    'O\\*`',  # capital O, grave accent
244     'ograve'    =>    'o\\*`',  # small o, grave accent
245     'Oslash'    =>    'O\\*/',  # capital O, slash
246     'oslash'    =>    'o\\*/',  # small o, slash
247     'Otilde'    =>    'O\\*~',  # capital O, tilde
248     'otilde'    =>    'o\\*~',  # small o, tilde
249     'Ouml'      =>    'O\\*:',  # capital O, dieresis or umlaut mark
250     'ouml'      =>    'o\\*:',  # small o, dieresis or umlaut mark
251     'szlig'     =>    '\*8',    # small sharp s, German (sz ligature)
252     'THORN'     =>    '\\*(Th', # capital THORN, Icelandic
253     'thorn'     =>    '\\*(th', # small thorn, Icelandic
254     'Uacute'    =>    "U\\*'",  # capital U, acute accent
255     'uacute'    =>    "u\\*'",  # small u, acute accent
256     'Ucirc'     =>    'U\\*^',  # capital U, circumflex accent
257     'ucirc'     =>    'u\\*^',  # small u, circumflex accent
258     'Ugrave'    =>    'U\\*`',  # capital U, grave accent
259     'ugrave'    =>    'u\\*`',  # small u, grave accent
260     'Uuml'      =>    'U\\*:',  # capital U, dieresis or umlaut mark
261     'uuml'      =>    'u\\*:',  # small u, dieresis or umlaut mark
262     'Yacute'    =>    "Y\\*'",  # capital Y, acute accent
263     'yacute'    =>    "y\\*'",  # small y, acute accent
264     'yuml'      =>    'y\\*:',  # small y, dieresis or umlaut mark
265 );
266
267
268 ############################################################################
269 # Static helper functions
270 ############################################################################
271
272 # Protect leading quotes and periods against interpretation as commands.
273 # Also protect anything starting with a backslash, since it could expand
274 # or hide something that *roff would interpret as a command.  This is
275 # overkill, but it's much simpler than trying to parse *roff here.
276 sub protect {
277     local $_ = shift;
278     s/^([.\'\\])/\\&$1/mg;
279     $_;
280 }
281
282 # Translate a font string into an escape.
283 sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] }
284
285
286 ############################################################################
287 # Initialization
288 ############################################################################
289
290 # Initialize the object.  Here, we also process any additional options
291 # passed to the constructor or set up defaults if none were given.  center
292 # is the centered title, release is the version number, and date is the date
293 # for the documentation.  Note that we can't know what file name we're
294 # processing due to the architecture of Pod::Parser, so that *has* to either
295 # be passed to the constructor or set separately with Pod::Man::name().
296 sub initialize {
297     my $self = shift;
298
299     # Figure out the fixed-width font.  If user-supplied, make sure that
300     # they are the right length.
301     for (qw/fixed fixedbold fixeditalic fixedbolditalic/) {
302         if (defined $$self{$_}) {
303             if (length ($$self{$_}) < 1 || length ($$self{$_}) > 2) {
304                 croak qq(roff font should be 1 or 2 chars,)
305                     . qq( not "$$self{$_}");
306             }
307         } else {
308             $$self{$_} = '';
309         }
310     }
311
312     # Set the default fonts.  We can't be sure what fixed bold-italic is
313     # going to be called, so default to just bold.
314     $$self{fixed}           ||= 'CW';
315     $$self{fixedbold}       ||= 'CB';
316     $$self{fixeditalic}     ||= 'CI';
317     $$self{fixedbolditalic} ||= 'CB';
318
319     # Set up a table of font escapes.  First number is fixed-width, second
320     # is bold, third is italic.
321     $$self{FONTS} = { '000' => '\fR', '001' => '\fI',
322                       '010' => '\fB', '011' => '\f(BI',
323                       '100' => toescape ($$self{fixed}),
324                       '101' => toescape ($$self{fixeditalic}),
325                       '110' => toescape ($$self{fixedbold}),
326                       '111' => toescape ($$self{fixedbolditalic})};
327
328     # Extra stuff for page titles.
329     $$self{center} = 'User Contributed Perl Documentation'
330         unless defined $$self{center};
331     $$self{indent}  = 4 unless defined $$self{indent};
332
333     # We used to try first to get the version number from a local binary,
334     # but we shouldn't need that any more.  Get the version from the running
335     # Perl.  Work a little magic to handle subversions correctly under both
336     # the pre-5.6 and the post-5.6 version numbering schemes.
337     if (!defined $$self{release}) {
338         my @version = ($] =~ /^(\d+)\.(\d{3})(\d{0,3})$/);
339         $version[2] ||= 0;
340         $version[2] *= 10 ** (3 - length $version[2]);
341         for (@version) { $_ += 0 }
342         $$self{release} = 'perl v' . join ('.', @version);
343     }
344
345     # Double quotes in things that will be quoted.
346     for (qw/center date release/) {
347         $$self{$_} =~ s/\"/\"\"/g if $$self{$_};
348     }
349
350     # Figure out what quotes we'll be using for C<> text.
351     $$self{quotes} ||= '"';
352     if ($$self{quotes} eq 'none') {
353         $$self{LQUOTE} = $$self{RQUOTE} = '';
354     } elsif (length ($$self{quotes}) == 1) {
355         $$self{LQUOTE} = $$self{RQUOTE} = $$self{quotes};
356     } elsif ($$self{quotes} =~ /^(.)(.)$/
357              || $$self{quotes} =~ /^(..)(..)$/) {
358         $$self{LQUOTE} = $1;
359         $$self{RQUOTE} = $2;
360     } else {
361         croak qq(Invalid quote specification "$$self{quotes}");
362     }
363
364     # Double the first quote; note that this should not be s///g as two
365     # double quotes is represented in *roff as three double quotes, not
366     # four.  Weird, I know.
367     $$self{LQUOTE} =~ s/\"/\"\"/;
368     $$self{RQUOTE} =~ s/\"/\"\"/;
369
370     $$self{INDENT}  = 0;        # Current indentation level.
371     $$self{INDENTS} = [];       # Stack of indentations.
372     $$self{INDEX}   = [];       # Index keys waiting to be printed.
373     $$self{ITEMS}   = 0;        # The number of consecutive =items.
374
375     $self->SUPER::initialize;
376 }
377
378 # For each document we process, output the preamble first.
379 sub begin_pod {
380     my $self = shift;
381
382     # Try to figure out the name and section from the file name.
383     my $section = $$self{section} || 1;
384     my $name = $$self{name};
385     if (!defined $name) {
386         $name = $self->input_file;
387         $section = 3 if (!$$self{section} && $name =~ /\.pm\z/i);
388         $name =~ s/\.p(od|[lm])\z//i;
389         if ($section =~ /^1/) {
390             require File::Basename;
391             $name = uc File::Basename::basename ($name);
392         } else {
393             # Lose everything up to the first of
394             #     */lib/*perl*      standard or site_perl module
395             #     */*perl*/lib      from -D prefix=/opt/perl
396             #     */*perl*/         random module hierarchy
397             # which works.  Should be fixed to use File::Spec.  Also handle
398             # a leading lib/ since that's what ExtUtils::MakeMaker creates.
399             for ($name) {
400                 s%//+%/%g;
401                 if (     s%^.*?/lib/[^/]*perl[^/]*/%%si
402                       or s%^.*?/[^/]*perl[^/]*/(?:lib/)?%%si) {
403                     s%^site(_perl)?/%%s;      # site and site_perl
404                     s%^(.*-$^O|$^O-.*)/%%so;  # arch
405                     s%^\d+\.\d+%%s;           # version
406                 }
407                 s%^lib/%%;
408                 s%/%::%g;
409             }
410         }
411     }
412
413     # If $name contains spaces, quote it; this mostly comes up in the case
414     # of input from stdin.
415     $name = '"' . $name . '"' if ($name =~ /\s/);
416
417     # Modification date header.  Try to use the modification time of our
418     # input.
419     if (!defined $$self{date}) {
420         my $time = (stat $self->input_file)[9] || time;
421         my ($day, $month, $year) = (localtime $time)[3,4,5];
422         $month++;
423         $year += 1900;
424         $$self{date} = sprintf ('%4d-%02d-%02d', $year, $month, $day);
425     }
426
427     # Now, print out the preamble and the title.
428     local $_ = $PREAMBLE;
429     s/\@CFONT\@/$$self{fixed}/;
430     s/\@LQUOTE\@/$$self{LQUOTE}/;
431     s/\@RQUOTE\@/$$self{RQUOTE}/;
432     chomp $_;
433     print { $self->output_handle } <<"----END OF HEADER----";
434 .\\" Automatically generated by Pod::Man version $VERSION
435 .\\" @{[ scalar localtime ]}
436 .\\"
437 .\\" Standard preamble:
438 .\\" ======================================================================
439 $_
440 .\\" ======================================================================
441 .\\"
442 .IX Title "$name $section"
443 .TH $name $section "$$self{release}" "$$self{date}" "$$self{center}"
444 .UC
445 ----END OF HEADER----
446 #"# for cperl-mode
447
448     # Initialize a few per-file variables.
449     $$self{INDENT} = 0;
450     $$self{NEEDSPACE} = 0;
451 }
452
453
454 ############################################################################
455 # Core overrides
456 ############################################################################
457
458 # Called for each command paragraph.  Gets the command, the associated
459 # paragraph, the line number, and a Pod::Paragraph object.  Just dispatches
460 # the command to a method named the same as the command.  =cut is handled
461 # internally by Pod::Parser.
462 sub command {
463     my $self = shift;
464     my $command = shift;
465     return if $command eq 'pod';
466    return if ($$self{EXCLUDE} && $command ne 'end');
467     if ($self->can ('cmd_' . $command)) {
468         $command = 'cmd_' . $command;
469         $self->$command (@_);
470      } else {
471         my ($text, $line, $paragraph) = @_;
472         my $file;
473         ($file, $line) = $paragraph->file_line;
474         $text =~ s/\n+\z//;
475         $text = " $text" if ($text =~ /^\S/);
476         warn qq($file:$line: Unknown command paragraph "=$command$text"\n);
477         return;
478     }
479 }
480
481 # Called for a verbatim paragraph.  Gets the paragraph, the line number, and
482 # a Pod::Paragraph object.  Rofficate backslashes, untabify, put a
483 # zero-width character at the beginning of each line to protect against
484 # commands, and wrap in .Vb/.Ve.
485 sub verbatim {
486     my $self = shift;
487     return if $$self{EXCLUDE};
488     local $_ = shift;
489     return if /^\s+$/;
490     s/\s+$/\n/;
491     my $lines = tr/\n/\n/;
492     1 while s/^(.*?)(\t+)/$1 . ' ' x (length ($2) * 8 - length ($1) % 8)/me;
493     s/\\/\\e/g;
494     s/^(\s*\S)/'\&' . $1/gme;
495     $self->makespace;
496     $self->output (".Vb $lines\n$_.Ve\n");
497     $$self{NEEDSPACE} = 0;
498 }
499
500 # Called for a regular text block.  Gets the paragraph, the line number, and
501 # a Pod::Paragraph object.  Perform interpolation and output the results.
502 sub textblock {
503     my $self = shift;
504     return if $$self{EXCLUDE};
505     $self->output ($_[0]), return if $$self{VERBATIM};
506
507     # Perform a little magic to collapse multiple L<> references.  We'll
508     # just rewrite the whole thing into actual text at this part, bypassing
509     # the whole internal sequence parsing thing.
510     my $text = shift;
511     $text =~ s{
512         (L<                     # A link of the form L</something>.
513               /
514               (
515                   [:\w]+        # The item has to be a simple word...
516                   (\(\))?       # ...or simple function.
517               )
518           >
519           (
520               ,?\s+(and\s+)?    # Allow lots of them, conjuncted.
521               L<
522                   /
523                   ( [:\w]+ ( \(\) )? )
524               >
525           )+
526         )
527     } {
528         local $_ = $1;
529         s{ L< / ( [^>]+ ) > } {$1}xg;
530         my @items = split /(?:,?\s+(?:and\s+)?)/;
531         my $string = 'the ';
532         my $i;
533         for ($i = 0; $i < @items; $i++) {
534             $string .= $items[$i];
535             $string .= ', ' if @items > 2 && $i != $#items;
536             $string .= ' ' if @items == 2 && $i == 2;
537             $string .= 'and ' if ($i == $#items - 1);
538         }
539         $string .= ' entries elsewhere in this document';
540         $string;
541     }gex;
542
543     # Parse the tree and output it.  collapse knows about references to
544     # scalars as well as scalars and does the right thing with them.
545     $text = $self->parse ($text, @_);
546     $text =~ s/\n\s*$/\n/;
547     $self->makespace;
548     $self->output (protect $self->textmapfonts ($text));
549     $self->outindex;
550     $$self{NEEDSPACE} = 1;
551 }
552
553 # Called for an interior sequence.  Takes a Pod::InteriorSequence object and
554 # returns a reference to a scalar.  This scalar is the final formatted text.
555 # It's returned as a reference so that other interior sequences above us
556 # know that the text has already been processed.
557 sub sequence {
558     my ($self, $seq) = @_;
559     my $command = $seq->cmd_name;
560
561     # Zero-width characters.
562     if ($command eq 'Z') {
563         # Workaround to generate a blessable reference, needed by 5.005.
564         my $tmp = '\&';
565         return bless \ "$tmp", 'Pod::Man::String';
566     }
567
568     # C<>, L<>, X<>, and E<> don't apply guesswork to their contents.  C<>
569     # needs some additional special handling.
570     my $literal = ($command =~ /^[CELX]$/);
571     $literal++ if $command eq 'C';
572     local $_ = $self->collapse ($seq->parse_tree, $literal);
573
574     # Handle E<> escapes.
575     if ($command eq 'E') {
576         if (/^\d+$/) {
577             return bless \ chr ($_), 'Pod::Man::String';
578         } elsif (exists $ESCAPES{$_}) {
579             return bless \ "$ESCAPES{$_}", 'Pod::Man::String';
580         } else {
581             carp "Unknown escape E<$1>";
582             return bless \ "E<$_>", 'Pod::Man::String';
583         }
584     }
585
586     # For all the other sequences, empty content produces no output.
587     return '' if $_ eq '';
588
589     # Handle formatting sequences.
590     if ($command eq 'B') {
591         return bless \ ('\f(BS' . $_ . '\f(BE'), 'Pod::Man::String';
592     } elsif ($command eq 'F') {
593         return bless \ ('\f(IS' . $_ . '\f(IE'), 'Pod::Man::String';
594     } elsif ($command eq 'I') {
595         return bless \ ('\f(IS' . $_ . '\f(IE'), 'Pod::Man::String';
596     } elsif ($command eq 'C') {
597         return bless \ ('\f(FS\*(C`' . $_ . "\\*(C'\\f(FE"),
598             'Pod::Man::String';
599     }
600
601     # Handle links.
602     if ($command eq 'L') {
603         # A bug in lvalue subs in 5.6 requires the temporary variable.
604         my $tmp = $self->buildlink ($_);
605         return bless \ "$tmp", 'Pod::Man::String';
606     }
607
608     # Whitespace protection replaces whitespace with "\ ".
609     if ($command eq 'S') {
610         s/\s+/\\ /g;
611         return bless \ "$_", 'Pod::Man::String';
612     }
613
614     # Add an index entry to the list of ones waiting to be output.
615     if ($command eq 'X') { push (@{ $$self{INDEX} }, $_); return '' }
616
617     # Anything else is unknown.
618     carp "Unknown sequence $command<$_>";
619 }
620
621
622 ############################################################################
623 # Command paragraphs
624 ############################################################################
625
626 # All command paragraphs take the paragraph and the line number.
627
628 # First level heading.  We can't output .IX in the NAME section due to a bug
629 # in some versions of catman, so don't output a .IX for that section.  .SH
630 # already uses small caps, so remove any E<> sequences that would cause
631 # them.
632 sub cmd_head1 {
633     my $self = shift;
634     local $_ = $self->parse (@_);
635     s/\s+$//;
636     s/\\s-?\d//g;
637     s/\s*\n\s*/ /g;
638     if ($$self{ITEMS} > 1) {
639         $$self{ITEMS} = 0;
640         $self->output (".PD\n");
641     }
642     $self->output ($self->switchquotes ('.SH', $self->mapfonts ($_)));
643     $self->outindex (($_ eq 'NAME') ? () : ('Header', $_));
644     $$self{NEEDSPACE} = 0;
645 }
646
647 # Second level heading.
648 sub cmd_head2 {
649     my $self = shift;
650     local $_ = $self->parse (@_);
651     s/\s+$//;
652     s/\s*\n\s*/ /g;
653     if ($$self{ITEMS} > 1) {
654         $$self{ITEMS} = 0;
655         $self->output (".PD\n");
656     }
657     $self->output ($self->switchquotes ('.Sh', $self->mapfonts ($_)));
658     $self->outindex ('Subsection', $_);
659     $$self{NEEDSPACE} = 0;
660 }
661
662 # Third level heading.
663 sub cmd_head3 {
664     my $self = shift;
665     local $_ = $self->parse (@_);
666     s/\s+$//;
667     s/\s*\n\s*/ /g;
668     if ($$self{ITEMS} > 1) {
669         $$self{ITEMS} = 0;
670         $self->output (".PD\n");
671     }
672     $self->makespace;
673     $self->output ($self->switchquotes ('.I', $self->mapfonts ($_)));
674     $self->outindex ('Subsection', $_);
675     $$self{NEEDSPACE} = 1;
676 }
677
678 # Fourth level heading.
679 sub cmd_head4 {
680     my $self = shift;
681     local $_ = $self->parse (@_);
682     s/\s+$//;
683     s/\s*\n\s*/ /g;
684     if ($$self{ITEMS} > 1) {
685         $$self{ITEMS} = 0;
686         $self->output (".PD\n");
687     }
688     $self->makespace;
689     $self->output ($self->textmapfonts ($_) . "\n");
690     $self->outindex ('Subsection', $_);
691     $$self{NEEDSPACE} = 1;
692 }
693
694 # Start a list.  For indents after the first, wrap the outside indent in .RS
695 # so that hanging paragraph tags will be correct.
696 sub cmd_over {
697     my $self = shift;
698     local $_ = shift;
699     unless (/^[-+]?\d+\s+$/) { $_ = $$self{indent} }
700     if (@{ $$self{INDENTS} } > 0) {
701         $self->output (".RS $$self{INDENT}\n");
702     }
703     push (@{ $$self{INDENTS} }, $$self{INDENT});
704     $$self{INDENT} = ($_ + 0);
705 }
706
707 # End a list.  If we've closed an embedded indent, we've mangled the hanging
708 # paragraph indent, so temporarily replace it with .RS and set WEIRDINDENT.
709 # We'll close that .RS at the next =back or =item.
710 sub cmd_back {
711     my $self = shift;
712     $$self{INDENT} = pop @{ $$self{INDENTS} };
713     unless (defined $$self{INDENT}) {
714         carp "Unmatched =back";
715         $$self{INDENT} = 0;
716     }
717     if ($$self{WEIRDINDENT}) {
718         $self->output (".RE\n");
719         $$self{WEIRDINDENT} = 0;
720     }
721     if (@{ $$self{INDENTS} } > 0) {
722         $self->output (".RE\n");
723         $self->output (".RS $$self{INDENT}\n");
724         $$self{WEIRDINDENT} = 1;
725     }
726     $$self{NEEDSPACE} = 1;
727 }
728
729 # An individual list item.  Emit an index entry for anything that's
730 # interesting, but don't emit index entries for things like bullets and
731 # numbers.  rofficate bullets too while we're at it (so for nice output, use
732 # * for your lists rather than o or . or - or some other thing).  Newlines
733 # in an item title are turned into spaces since *roff can't handle them
734 # embedded.
735 sub cmd_item {
736     my $self = shift;
737     local $_ = $self->parse (@_);
738     s/\s+$//;
739     s/\s*\n\s*/ /g;
740     my $index;
741     if (/\w/ && !/^\w[.\)]\s*$/) {
742         $index = $_;
743         $index =~ s/^\s*[-*+o.]?(?:\s+|\Z)//;
744     }
745     s/^\*(\s|\Z)/\\\(bu$1/;
746     if ($$self{WEIRDINDENT}) {
747         $self->output (".RE\n");
748         $$self{WEIRDINDENT} = 0;
749     }
750     $_ = $self->textmapfonts ($_);
751     $self->output (".PD 0\n") if ($$self{ITEMS} == 1);
752     $self->output ($self->switchquotes ('.Ip', $_, $$self{INDENT}));
753     $self->outindex ($index ? ('Item', $index) : ());
754     $$self{NEEDSPACE} = 0;
755     $$self{ITEMS}++;
756 }
757
758 # Begin a block for a particular translator.  Setting VERBATIM triggers
759 # special handling in textblock().
760 sub cmd_begin {
761     my $self = shift;
762     local $_ = shift;
763     my ($kind) = /^(\S+)/ or return;
764     if ($kind eq 'man' || $kind eq 'roff') {
765         $$self{VERBATIM} = 1;
766     } else {
767         $$self{EXCLUDE} = 1;
768     }
769 }
770
771 # End a block for a particular translator.  We assume that all =begin/=end
772 # pairs are properly closed.
773 sub cmd_end {
774     my $self = shift;
775     $$self{EXCLUDE} = 0;
776     $$self{VERBATIM} = 0;
777 }
778
779 # One paragraph for a particular translator.  Ignore it unless it's intended
780 # for man or roff, in which case we output it verbatim.
781 sub cmd_for {
782     my $self = shift;
783     local $_ = shift;
784     return unless s/^(?:man|roff)\b[ \t]*\n?//;
785     $self->output ($_);
786 }
787
788
789 ############################################################################
790 # Link handling
791 ############################################################################
792
793 # Handle links.  We can't actually make real hyperlinks, so this is all to
794 # figure out what text and formatting we print out.
795 sub buildlink {
796     my $self = shift;
797     local $_ = shift;
798
799     # Smash whitespace in case we were split across multiple lines.
800     s/\s+/ /g;
801
802     # If we were given any explicit text, just output it.
803     if (m{ ^ ([^|]+) \| }x) { return $1 }
804
805     # Okay, leading and trailing whitespace isn't important.
806     s/^\s+//;
807     s/\s+$//;
808
809     # If the argument looks like a URL, return it verbatim.  This only
810     # handles URLs that use the server syntax.
811     if (m%^[a-z]+://\S+$%) { return $_ }
812
813     # Default to using the whole content of the link entry as a section
814     # name.  Note that L<manpage/> forces a manpage interpretation, as does
815     # something looking like L<manpage(section)>.  Do the same thing to
816     # L<manpage(section)> as we would to manpage(section) without the L<>;
817     # see guesswork().  If we've added italics, don't add the "manpage"
818     # text; markup is sufficient.
819     my ($manpage, $section) = ('', $_);
820     if (/^"\s*(.*?)\s*"$/) {
821         $section = '"' . $1 . '"';
822     } elsif (m{ ^ [-:.\w]+ (?: \( \S+ \) )? $ }x) {
823         ($manpage, $section) = ($_, '');
824         $manpage =~ s/^([^\(]+)\(/'\f(IS' . $1 . '\f(IE\|('/e;
825     } elsif (m%/%) {
826         ($manpage, $section) = split (/\s*\/\s*/, $_, 2);
827         if ($manpage =~ /^[-:.\w]+(?:\(\S+\))?$/) {
828             $manpage =~ s/^([^\(]+)\(/'\f(IS' . $1 . '\f(IE\|'/e;
829         }
830         $section =~ s/^\"\s*//;
831         $section =~ s/\s*\"$//;
832     }
833     if ($manpage && $manpage !~ /\\f\(IS/) {
834         $manpage = "the $manpage manpage";
835     }
836
837     # Now build the actual output text.
838     my $text = '';
839     if (!length ($section) && !length ($manpage)) {
840         carp "Invalid link $_";
841     } elsif (!length ($section)) {
842         $text = $manpage;
843     } elsif ($section =~ /^[:\w]+(?:\(\))?/) {
844         $text .= 'the ' . $section . ' entry';
845         $text .= (length $manpage) ? " in $manpage"
846                                    : " elsewhere in this document";
847     } else {
848         if ($section !~ /^".*"$/) { $section = '"' . $section . '"' }
849         $text .= 'the section on ' . $section;
850         $text .= " in $manpage" if length $manpage;
851     }
852     $text;
853 }
854
855
856 ############################################################################
857 # Escaping and fontification
858 ############################################################################
859
860 # At this point, we'll have embedded font codes of the form \f(<font>[SE]
861 # where <font> is one of B, I, or F.  Turn those into the right font start
862 # or end codes.  The old pod2man didn't get B<someI<thing> else> right;
863 # after I<> it switched back to normal text rather than bold.  We take care
864 # of this by using variables as a combined pointer to our current font
865 # sequence, and set each to the number of current nestings of start tags for
866 # that font.  Use them as a vector to look up what font sequence to use.
867 #
868 # \fP changes to the previous font, but only one previous font is kept.  We
869 # don't know what the outside level font is; normally it's R, but if we're
870 # inside a heading it could be something else.  So arrange things so that
871 # the outside font is always the "previous" font and end with \fP instead of
872 # \fR.  Idea from Zack Weinberg.
873 sub mapfonts {
874     my $self = shift;
875     local $_ = shift;
876
877     my ($fixed, $bold, $italic) = (0, 0, 0);
878     my %magic = (F => \$fixed, B => \$bold, I => \$italic);
879     my $last = '\fR';
880     s { \\f\((.)(.) } {
881         my $sequence = '';
882         my $f;
883         if ($last ne '\fR') { $sequence = '\fP' }
884         ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
885         $f = $$self{FONTS}{($fixed && 1) . ($bold && 1) . ($italic && 1)};
886         if ($f eq $last) {
887             '';
888         } else {
889             if ($f ne '\fR') { $sequence .= $f }
890             $last = $f;
891             $sequence;
892         }
893     }gxe;
894     $_;
895 }
896
897 # Unfortunately, there is a bug in Solaris 2.6 nroff (not present in GNU
898 # groff) where the sequence \fB\fP\f(CW\fP leaves the font set to B rather
899 # than R, presumably because \f(CW doesn't actually do a font change.  To
900 # work around this, use a separate textmapfonts for text blocks where the
901 # default font is always R and only use the smart mapfonts for headings.
902 sub textmapfonts {
903     my $self = shift;
904     local $_ = shift;
905
906     my ($fixed, $bold, $italic) = (0, 0, 0);
907     my %magic = (F => \$fixed, B => \$bold, I => \$italic);
908     s { \\f\((.)(.) } {
909         ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
910         $$self{FONTS}{($fixed && 1) . ($bold && 1) . ($italic && 1)};
911     }gxe;
912     $_;
913 }
914
915
916 ############################################################################
917 # *roff-specific parsing
918 ############################################################################
919
920 # Called instead of parse_text, calls parse_text with the right flags.
921 sub parse {
922     my $self = shift;
923     $self->parse_text ({ -expand_seq   => 'sequence',
924                          -expand_ptree => 'collapse' }, @_);
925 }
926
927 # Takes a parse tree and a flag saying whether or not to treat it as literal
928 # text (not call guesswork on it), and returns the concatenation of all of
929 # the text strings in that parse tree.  If the literal flag isn't true,
930 # guesswork() will be called on all plain scalars in the parse tree.
931 # Otherwise, just escape backslashes in the normal case.  If collapse is
932 # being called on a C<> sequence, literal is set to 2, and we do some
933 # additional cleanup.  Assumes that everything in the parse tree is either a
934 # scalar or a reference to a scalar.
935 sub collapse {
936     my ($self, $ptree, $literal) = @_;
937     if ($literal) {
938         return join ('', map {
939             if (ref $_) {
940                 $$_;
941             } else {
942                 s/\\/\\e/g;
943                 s/-/\\-/g    if $literal > 1;
944                 s/__/_\\|_/g if $literal > 1;
945                 $_;
946             }
947         } $ptree->children);
948     } else {
949         return join ('', map {
950             ref ($_) ? $$_ : $self->guesswork ($_)
951         } $ptree->children);
952     }
953 }
954
955 # Takes a text block to perform guesswork on; this is guaranteed not to
956 # contain any interior sequences.  Returns the text block with remapping
957 # done.
958 sub guesswork {
959     my $self = shift;
960     local $_ = shift;
961
962     # rofficate backslashes.
963     s/\\/\\e/g;
964
965     # Ensure double underbars have a tiny space between them.
966     s/__/_\\|_/g;
967
968     # Make all caps a little smaller.  Be careful here, since we don't want
969     # to make @ARGV into small caps, nor do we want to fix the MIME in
970     # MIME-Version, since it looks weird with the full-height V.
971     s{
972         ( ^ | [\s\(\"\'\`\[\{<>] )
973         ( [A-Z] [A-Z] [/A-Z+:\d_\$&-]* )
974         (?: (?= [\s>\}\]\)\'\".?!,;:] | -- ) | $ )
975     } { $1 . '\s-1' . $2 . '\s0' }egx;
976
977     # Turn PI into a pretty pi.
978     s{ (?: \\s-1 | \b ) PI (?: \\s0 | \b ) } {\\*\(PI}gx;
979
980     # Italize functions in the form func().
981     s{
982         \b
983         (
984             [:\w]+ (?:\\s-1)? \(\)
985         )
986     } { '\f(IS' . $1 . '\f(IE' }egx;
987
988     # func(n) is a reference to a manual page.  Make it \fIfunc\fR\|(n).
989     s{
990         \b
991         (\w[-:.\w]+ (?:\\s-1)?)
992         (
993             \( [^\)] \)
994         )
995     } { '\f(IS' . $1 . '\f(IE\|' . $2 }egx;
996
997     # Convert simple Perl variable references to a fixed-width font.
998     s{
999         ( \s+ )
1000         ( [\$\@%] [\w:]+ )
1001         (?! \( )
1002     } { $1 . '\f(FS' . $2 . '\f(FE'}egx;
1003
1004     # Translate -- into a real em dash if it's used like one and fix up
1005     # dashes, but keep hyphens hyphens.
1006     s{ (\G|^|.) (-+) (\b|.) } {
1007         my ($pre, $dash, $post) = ($1, $2, $3);
1008         if (length ($dash) == 1) {
1009             ($pre =~ /[a-zA-Z]/) ? "$pre-$post" : "$pre\\-$post";
1010         } elsif (length ($dash) == 2
1011                  && ((!$pre && !$post)
1012                      || ($pre =~ /\w/ && !$post)
1013                      || ($pre eq ' ' && $post eq ' ')
1014                      || ($pre eq '=' && $post ne '=')
1015                      || ($pre ne '=' && $post eq '='))) {
1016             "$pre\\*(--$post";
1017         } else {
1018             $pre . ('\-' x length $dash) . $post;
1019         }
1020     }egxs;
1021
1022     # Fix up double quotes.
1023     s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx;
1024
1025     # Make C++ into \*(C+, which is a squinched version.
1026     s{ \b C\+\+ } {\\*\(C+}gx;
1027
1028     # All done.
1029     $_;
1030 }
1031
1032
1033 ############################################################################
1034 # Output formatting
1035 ############################################################################
1036
1037 # Make vertical whitespace.
1038 sub makespace {
1039     my $self = shift;
1040     $self->output (".PD\n") if ($$self{ITEMS} > 1);
1041     $$self{ITEMS} = 0;
1042     $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n")
1043         if $$self{NEEDSPACE};
1044 }
1045
1046 # Output any pending index entries, and optionally an index entry given as
1047 # an argument.  Support multiple index entries in X<> separated by slashes,
1048 # and strip special escapes from index entries.
1049 sub outindex {
1050     my ($self, $section, $index) = @_;
1051     my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} };
1052     return unless ($section || @entries);
1053     $$self{INDEX} = [];
1054     my $output;
1055     if (@entries) {
1056         my $output = '.IX Xref "'
1057             . join (' ', map { s/\"/\"\"/; $_ } @entries)
1058             . '"' . "\n";
1059     }
1060     if ($section) {
1061         $index =~ s/\"/\"\"/;
1062         $index =~ s/\\-/-/g;
1063         $index =~ s/\\(?:s-?\d|.\(..|.)//g;
1064         $output .= ".IX $section " . '"' . $index . '"' . "\n";
1065     }
1066     $self->output ($output);
1067 }
1068
1069 # Output text to the output device.
1070 sub output { print { $_[0]->output_handle } $_[1] }
1071
1072 # Given a command and a single argument that may or may not contain double
1073 # quotes, handle double-quote formatting for it.  If there are no double
1074 # quotes, just return the command followed by the argument in double quotes.
1075 # If there are double quotes, use an if statement to test for nroff, and for
1076 # nroff output the command followed by the argument in double quotes with
1077 # embedded double quotes doubled.  For other formatters, remap paired double
1078 # quotes to LQUOTE and RQUOTE.
1079 sub switchquotes {
1080     my $self = shift;
1081     my $command = shift;
1082     local $_ = shift;
1083     my $extra = shift;
1084     s/\\\*\([LR]\"/\"/g;
1085
1086     # We also have to deal with \*C` and \*C', which are used to add the
1087     # quotes around C<> text, since they may expand to " and if they do this
1088     # confuses the .SH macros and the like no end.  Expand them ourselves.
1089     # If $extra is set, we're dealing with =item, which in most nroff macro
1090     # sets requires an extra level of quoting of double quotes.
1091     my $c_is_quote = ($$self{LQUOTE} =~ /\"/) || ($$self{RQUOTE} =~ /\"/);
1092     if (/\"/ || ($c_is_quote && /\\\*\(C[\'\`]/)) {
1093         s/\"/\"\"/g;
1094         my $troff = $_;
1095         $troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g;
1096         s/\\\*\(C\`/$$self{LQUOTE}/g;
1097         s/\\\*\(C\'/$$self{RQUOTE}/g;
1098         $troff =~ s/\\\*\(C[\'\`]//g;
1099         s/\"/\"\"/g if $extra;
1100         $troff =~ s/\"/\"\"/g if $extra;
1101         $_ = qq("$_") . ($extra ? " $extra" : '');
1102         $troff = qq("$troff") . ($extra ? " $extra" : '');
1103         return ".if n $command $_\n.el $command $troff\n";
1104     } else {
1105         $_ = qq("$_") . ($extra ? " $extra" : '');
1106         return "$command $_\n";
1107     }
1108 }
1109
1110 __END__
1111
1112 .\" These are some extra bits of roff that I don't want to lose track of
1113 .\" but that have been removed from the preamble to make it a bit shorter
1114 .\" since they're not currently being used.  They're accents and special
1115 .\" characters we don't currently have escapes for.
1116 .if n \{\
1117 .    ds ? ?
1118 .    ds ! !
1119 .    ds q
1120 .\}
1121 .if t \{\
1122 .    ds ? \s-2c\h'-\w'c'u*7/10'\u\h'\*(#H'\zi\d\s+2\h'\w'c'u*8/10'
1123 .    ds ! \s-2\(or\s+2\h'-\w'\(or'u'\v'-.8m'.\v'.8m'
1124 .    ds q o\h'-\w'o'u*8/10'\s-4\v'.4m'\z\(*i\v'-.4m'\s+4\h'\w'o'u*8/10'
1125 .\}
1126 .ds v \\k:\h'-(\\n(.wu*9/10-\*(#H)'\v'-\*(#V'\*(#[\s-4v\s0\v'\*(#V'\h'|\\n:u'\*(#]
1127 .ds _ \\k:\h'-(\\n(.wu*9/10-\*(#H+(\*(#F*2/3))'\v'-.4m'\z\(hy\v'.4m'\h'|\\n:u'
1128 .ds . \\k:\h'-(\\n(.wu*8/10)'\v'\*(#V*4/10'\z.\v'-\*(#V*4/10'\h'|\\n:u'
1129 .ds 3 \*(#[\v'.2m'\s-2\&3\s0\v'-.2m'\*(#]
1130 .ds oe o\h'-(\w'o'u*4/10)'e
1131 .ds Oe O\h'-(\w'O'u*4/10)'E
1132 .if \n(.H>23 .if \n(.V>19 \
1133 \{\
1134 .    ds v \h'-1'\o'\(aa\(ga'
1135 .    ds _ \h'-1'^
1136 .    ds . \h'-1'.
1137 .    ds 3 3
1138 .    ds oe oe
1139 .    ds Oe OE
1140 .\}
1141
1142 ############################################################################
1143 # Documentation
1144 ############################################################################
1145
1146 =head1 NAME
1147
1148 Pod::Man - Convert POD data to formatted *roff input
1149
1150 =head1 SYNOPSIS
1151
1152     use Pod::Man;
1153     my $parser = Pod::Man->new (release => $VERSION, section => 8);
1154
1155     # Read POD from STDIN and write to STDOUT.
1156     $parser->parse_from_filehandle;
1157
1158     # Read POD from file.pod and write to file.1.
1159     $parser->parse_from_file ('file.pod', 'file.1');
1160
1161 =head1 DESCRIPTION
1162
1163 Pod::Man is a module to convert documentation in the POD format (the
1164 preferred language for documenting Perl) into *roff input using the man
1165 macro set.  The resulting *roff code is suitable for display on a terminal
1166 using nroff(1), normally via man(1), or printing using troff(1).  It is
1167 conventionally invoked using the driver script B<pod2man>, but it can also
1168 be used directly.
1169
1170 As a derived class from Pod::Parser, Pod::Man supports the same methods and
1171 interfaces.  See L<Pod::Parser> for all the details; briefly, one creates a
1172 new parser with C<Pod::Man-E<gt>new()> and then calls either
1173 parse_from_filehandle() or parse_from_file().
1174
1175 new() can take options, in the form of key/value pairs that control the
1176 behavior of the parser.  See below for details.
1177
1178 If no options are given, Pod::Man uses the name of the input file with any
1179 trailing C<.pod>, C<.pm>, or C<.pl> stripped as the man page title, to
1180 section 1 unless the file ended in C<.pm> in which case it defaults to
1181 section 3, to a centered title of "User Contributed Perl Documentation", to
1182 a centered footer of the Perl version it is run with, and to a left-hand
1183 footer of the modification date of its input (or the current date if given
1184 STDIN for input).
1185
1186 Pod::Man assumes that your *roff formatters have a fixed-width font named
1187 CW.  If yours is called something else (like CR), use the C<fixed> option to
1188 specify it.  This generally only matters for troff output for printing.
1189 Similarly, you can set the fonts used for bold, italic, and bold italic
1190 fixed-width output.
1191
1192 Besides the obvious pod conversions, Pod::Man also takes care of formatting
1193 func(), func(n), and simple variable references like $foo or @bar so you
1194 don't have to use code escapes for them; complex expressions like
1195 C<$fred{'stuff'}> will still need to be escaped, though.  It also translates
1196 dashes that aren't used as hyphens into en dashes, makes long dashes--like
1197 this--into proper em dashes, fixes "paired quotes," makes C++ and PI look
1198 right, puts a little space between double underbars, makes ALLCAPS a teeny
1199 bit smaller in troff(1), and escapes stuff that *roff treats as special so
1200 that you don't have to.
1201
1202 The recognized options to new() are as follows.  All options take a single
1203 argument.
1204
1205 =over 4
1206
1207 =item center
1208
1209 Sets the centered page header to use instead of "User Contributed Perl
1210 Documentation".
1211
1212 =item date
1213
1214 Sets the left-hand footer.  By default, the modification date of the input
1215 file will be used, or the current date if stat() can't find that file (the
1216 case if the input is from STDIN), and the date will be formatted as
1217 YYYY-MM-DD.
1218
1219 =item fixed
1220
1221 The fixed-width font to use for vertabim text and code.  Defaults to CW.
1222 Some systems may want CR instead.  Only matters for troff(1) output.
1223
1224 =item fixedbold
1225
1226 Bold version of the fixed-width font.  Defaults to CB.  Only matters for
1227 troff(1) output.
1228
1229 =item fixeditalic
1230
1231 Italic version of the fixed-width font (actually, something of a misnomer,
1232 since most fixed-width fonts only have an oblique version, not an italic
1233 version).  Defaults to CI.  Only matters for troff(1) output.
1234
1235 =item fixedbolditalic
1236
1237 Bold italic (probably actually oblique) version of the fixed-width font.
1238 Pod::Man doesn't assume you have this, and defaults to CB.  Some systems
1239 (such as Solaris) have this font available as CX.  Only matters for troff(1)
1240 output.
1241
1242 =item quotes
1243
1244 Sets the quote marks used to surround CE<lt>> text.  If the value is a
1245 single character, it is used as both the left and right quote; if it is two
1246 characters, the first character is used as the left quote and the second as
1247 the right quoted; and if it is four characters, the first two are used as
1248 the left quote and the second two as the right quote.
1249
1250 This may also be set to the special value C<none>, in which case no quote
1251 marks are added around CE<lt>> text (but the font is still changed for troff
1252 output).
1253
1254 =item release
1255
1256 Set the centered footer.  By default, this is the version of Perl you run
1257 Pod::Man under.  Note that some system an macro sets assume that the
1258 centered footer will be a modification date and will prepend something like
1259 "Last modified: "; if this is the case, you may want to set C<release> to
1260 the last modified date and C<date> to the version number.
1261
1262 =item section
1263
1264 Set the section for the C<.TH> macro.  The standard section numbering
1265 convention is to use 1 for user commands, 2 for system calls, 3 for
1266 functions, 4 for devices, 5 for file formats, 6 for games, 7 for
1267 miscellaneous information, and 8 for administrator commands.  There is a lot
1268 of variation here, however; some systems (like Solaris) use 4 for file
1269 formats, 5 for miscellaneous information, and 7 for devices.  Still others
1270 use 1m instead of 8, or some mix of both.  About the only section numbers
1271 that are reliably consistent are 1, 2, and 3.
1272
1273 By default, section 1 will be used unless the file ends in .pm in which case
1274 section 3 will be selected.
1275
1276 =back
1277
1278 The standard Pod::Parser method parse_from_filehandle() takes up to two
1279 arguments, the first being the file handle to read POD from and the second
1280 being the file handle to write the formatted output to.  The first defaults
1281 to STDIN if not given, and the second defaults to STDOUT.  The method
1282 parse_from_file() is almost identical, except that its two arguments are the
1283 input and output disk files instead.  See L<Pod::Parser> for the specific
1284 details.
1285
1286 =head1 DIAGNOSTICS
1287
1288 =over 4
1289
1290 =item roff font should be 1 or 2 chars, not "%s"
1291
1292 (F) You specified a *roff font (using C<fixed>, C<fixedbold>, etc.) that
1293 wasn't either one or two characters.  Pod::Man doesn't support *roff fonts
1294 longer than two characters, although some *roff extensions do (the canonical
1295 versions of nroff(1) and troff(1) don't either).
1296
1297 =item Invalid link %s
1298
1299 (W) The POD source contained a C<LE<lt>E<gt>> sequence that Pod::Man was
1300 unable to parse.  You should never see this error message; it probably
1301 indicates a bug in Pod::Man.
1302
1303 =item Invalid quote specification "%s"
1304
1305 (F) The quote specification given (the quotes option to the constructor) was
1306 invalid.  A quote specification must be one, two, or four characters long.
1307
1308 =item %s:%d: Unknown command paragraph "%s".
1309
1310 (W) The POD source contained a non-standard command paragraph (something of
1311 the form C<=command args>) that Pod::Man didn't know about.  It was ignored.
1312
1313 =item Unknown escape EE<lt>%sE<gt>
1314
1315 (W) The POD source contained an C<EE<lt>E<gt>> escape that Pod::Man didn't
1316 know about.  C<EE<lt>%sE<gt>> was printed verbatim in the output.
1317
1318 =item Unknown sequence %s
1319
1320 (W) The POD source contained a non-standard interior sequence (something of
1321 the form C<XE<lt>E<gt>>) that Pod::Man didn't know about.  It was ignored.
1322
1323 =item %s: Unknown command paragraph "%s" on line %d.
1324
1325 (W) The POD source contained a non-standard command paragraph (something of
1326 the form C<=command args>) that Pod::Man didn't know about. It was ignored.
1327
1328 =item Unmatched =back
1329
1330 (W) Pod::Man encountered a C<=back> command that didn't correspond to an
1331 C<=over> command.
1332
1333 =back
1334
1335 =head1 BUGS
1336
1337 The lint-like features and strict POD format checking done by B<pod2man> are
1338 not yet implemented and should be, along with the corresponding C<lax>
1339 option.
1340
1341 The NAME section should be recognized specially and index entries emitted
1342 for everything in that section.  This would have to be deferred until the
1343 next section, since extraneous things in NAME tends to confuse various man
1344 page processors.
1345
1346 The handling of hyphens, en dashes, and em dashes is somewhat fragile, and
1347 one may get the wrong one under some circumstances.  This should only matter
1348 for troff(1) output.
1349
1350 When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
1351 necessarily get it right.
1352
1353 Pod::Man doesn't handle font names longer than two characters.  Neither do
1354 most troff(1) implementations, but GNU troff does as an extension.  It would
1355 be nice to support as an option for those who want to use it.
1356
1357 The preamble added to each output file is rather verbose, and most of it is
1358 only necessary in the presence of EE<lt>E<gt> escapes for non-ASCII
1359 characters.  It would ideally be nice if all of those definitions were only
1360 output if needed, perhaps on the fly as the characters are used.
1361
1362 Some of the automagic applied to file names assumes Unix directory
1363 separators.
1364
1365 Pod::Man is excessively slow.
1366
1367 =head1 SEE ALSO
1368
1369 L<Pod::Parser|Pod::Parser>, perlpod(1), pod2man(1), nroff(1), troff(1),
1370 man(1), man(7)
1371
1372 Ossanna, Joseph F., and Brian W. Kernighan.  "Troff User's Manual,"
1373 Computing Science Technical Report No. 54, AT&T Bell Laboratories.  This is
1374 the best documentation of standard nroff(1) and troff(1).  At the time of
1375 this writing, it's available at http://www.cs.bell-labs.com/cm/cs/cstr.html.
1376
1377 The man page documenting the man macro set may be man(5) instead of man(7)
1378 on your system.  Also, please see pod2man(1) for extensive documentation on
1379 writing manual pages if you've not done it before and aren't familiar with
1380 the conventions.
1381
1382 =head1 AUTHOR
1383
1384 Russ Allbery E<lt>rra@stanford.eduE<gt>, based I<very> heavily on the
1385 original B<pod2man> by Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>.
1386
1387 =cut