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