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 $
4 # Copyright 1999, 2000, 2001 by Russ Allbery <rra@stanford.edu>
6 # This program is free software; you may redistribute it and/or modify it
7 # under the same terms as Perl itself.
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
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.
20 ##############################################################################
21 # Modules and declarations
22 ##############################################################################
28 use Carp qw(carp croak);
32 use subs qw(makespace);
33 use vars qw(@ISA %ESCAPES $PREAMBLE $VERSION);
35 @ISA = qw(Pod::Parser);
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.
43 ##############################################################################
44 # Preamble and *roff output tables
45 ##############################################################################
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
61 .de Sp \" Vertical space (when we can't use .PP)
65 .de Vb \" Begin verbatim text
70 .de Ve \" End verbatim text
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<>.
82 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
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
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.
106 . tm Index:\\$1\t\\n%\t"\\$2"
112 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
113 .\" way too many mistakes in technical documents.
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
128 . ds #H ((1u-(\\\\n(.fu%2u))*.13m)
134 . \" simple accents for nroff and troff
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'
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 \
178 ----END OF PREAMBLE----
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.
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
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
259 ##############################################################################
260 # Static helper functions
261 ##############################################################################
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.
269 s/^([.\'\\])/\\&$1/mg;
273 # Translate a font string into an escape.
274 sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] }
277 ##############################################################################
279 ##############################################################################
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().
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{$_}");
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';
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})};
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};
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})$/);
331 $version[2] *= 10 ** (3 - length $version[2]);
332 for (@version) { $_ += 0 }
333 $$self{release} = 'perl v' . join ('.', @version);
336 # Double quotes in things that will be quoted.
337 for (qw/center date release/) {
338 $$self{$_} =~ s/\"/\"\"/g if $$self{$_};
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} =~ /^(..)(..)$/) {
352 croak qq(Invalid quote specification "$$self{quotes}");
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,
358 $$self{LQUOTE} =~ s/\"/\"\"/;
359 $$self{RQUOTE} =~ s/\"/\"\"/;
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.
366 $self->SUPER::initialize;
369 # For each document we process, output the preamble first.
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);
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.
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
404 # If $name contains spaces, quote it; this mostly comes up in the case of
406 $name = '"' . $name . '"' if ($name =~ /\s/);
408 # Modification date header. Try to use the modification time of our
410 if (!defined $$self{date}) {
411 my $time = (stat $self->input_file)[9] || time;
412 my ($day, $month, $year) = (localtime $time)[3,4,5];
415 $$self{date} = sprintf ('%4d-%02d-%02d', $year, $month, $day);
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}/;
424 print { $self->output_handle } <<"----END OF HEADER----";
425 .\\" Automatically generated by Pod::Man version $VERSION
426 .\\" @{[ scalar localtime ]}
428 .\\" Standard preamble:
429 .\\" ========================================================================
431 .\\" ========================================================================
433 .IX Title "$name $section"
434 .TH $name $section "$$self{release}" "$$self{date}" "$$self{center}"
436 ----END OF HEADER----
439 # Initialize a few per-file variables.
441 $$self{NEEDSPACE} = 0;
445 ##############################################################################
447 ##############################################################################
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.
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 (@_);
462 my ($text, $line, $paragraph) = @_;
464 ($file, $line) = $paragraph->file_line;
466 $text = " $text" if ($text =~ /^\S/);
467 warn qq($file:$line: Unknown command paragraph "=$command$text"\n);
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
478 return if $$self{EXCLUDE};
482 my $lines = tr/\n/\n/;
483 1 while s/^(.*?)(\t+)/$1 . ' ' x (length ($2) * 8 - length ($1) % 8)/me;
485 s/^(\s*\S)/'\&' . $1/gme;
487 $self->output (".Vb $lines\n$_.Ve\n");
488 $$self{NEEDSPACE} = 0;
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.
495 return if $$self{EXCLUDE};
496 $self->output ($_[0]), return if $$self{VERBATIM};
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.
503 (L< # A link of the form L</something>.
506 [:\w]+ # The item has to be a simple word...
507 (\(\))? # ...or simple function.
511 ,?\s+(and\s+)? # Allow lots of them, conjuncted.
520 s{ L< / ( [^>]+ ) > } {$1}xg;
521 my @items = split /(?:,?\s+(?:and\s+)?)/;
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);
530 $string .= ' entries elsewhere in this document';
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/;
539 $self->output (protect $self->textmapfonts ($text));
541 $$self{NEEDSPACE} = 1;
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.
549 my ($self, $seq) = @_;
550 my $command = $seq->cmd_name;
552 # Zero-width characters.
553 if ($command eq 'Z') {
554 # Workaround to generate a blessable reference, needed by 5.005.
556 return bless \ "$tmp", 'Pod::Man::String';
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);
565 # Handle E<> escapes.
566 if ($command eq 'E') {
568 return bless \ chr ($_), 'Pod::Man::String';
569 } elsif (exists $ESCAPES{$_}) {
570 return bless \ "$ESCAPES{$_}", 'Pod::Man::String';
572 carp "Unknown escape E<$1>";
573 return bless \ "E<$_>", 'Pod::Man::String';
577 # For all the other sequences, empty content produces no output.
578 return '' if $_ eq '';
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';
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';
600 # Whitespace protection replaces whitespace with "\ ".
601 if ($command eq 'S') {
603 return bless \ "$_", 'Pod::Man::String';
606 # Add an index entry to the list of ones waiting to be output.
607 if ($command eq 'X') { push (@{ $$self{INDEX} }, $_); return '' }
609 # Anything else is unknown.
610 carp "Unknown sequence $command<$_>";
614 ##############################################################################
616 ##############################################################################
618 # All command paragraphs take the paragraph and the line number.
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.
625 local $_ = $self->parse (@_);
629 if ($$self{ITEMS} > 1) {
631 $self->output (".PD\n");
633 $self->output ($self->switchquotes ('.SH', $self->mapfonts ($_)));
634 $self->outindex (($_ eq 'NAME') ? () : ('Header', $_));
635 $$self{NEEDSPACE} = 0;
638 # Second level heading.
641 local $_ = $self->parse (@_);
644 if ($$self{ITEMS} > 1) {
646 $self->output (".PD\n");
648 $self->output ($self->switchquotes ('.Sh', $self->mapfonts ($_)));
649 $self->outindex ('Subsection', $_);
650 $$self{NEEDSPACE} = 0;
653 # Third level heading.
656 local $_ = $self->parse (@_);
659 if ($$self{ITEMS} > 1) {
661 $self->output (".PD\n");
664 $self->output ($self->switchquotes ('.I', $self->mapfonts ($_)));
665 $self->outindex ('Subsection', $_);
666 $$self{NEEDSPACE} = 1;
669 # Fourth level heading.
672 local $_ = $self->parse (@_);
675 if ($$self{ITEMS} > 1) {
677 $self->output (".PD\n");
680 $self->output ($self->textmapfonts ($_) . "\n");
681 $self->outindex ('Subsection', $_);
682 $$self{NEEDSPACE} = 1;
685 # Start a list. For indents after the first, wrap the outside indent in .RS
686 # so that hanging paragraph tags will be correct.
690 unless (/^[-+]?\d+\s+$/) { $_ = $$self{indent} }
691 if (@{ $$self{INDENTS} } > 0) {
692 $self->output (".RS $$self{INDENT}\n");
694 push (@{ $$self{INDENTS} }, $$self{INDENT});
695 $$self{INDENT} = ($_ + 0);
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.
703 $$self{INDENT} = pop @{ $$self{INDENTS} };
704 unless (defined $$self{INDENT}) {
705 carp "Unmatched =back";
708 if ($$self{WEIRDINDENT}) {
709 $self->output (".RE\n");
710 $$self{WEIRDINDENT} = 0;
712 if (@{ $$self{INDENTS} } > 0) {
713 $self->output (".RE\n");
714 $self->output (".RS $$self{INDENT}\n");
715 $$self{WEIRDINDENT} = 1;
717 $$self{NEEDSPACE} = 1;
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.
727 local $_ = $self->parse (@_);
731 if (/\w/ && !/^\w[.\)]\s*$/) {
733 $index =~ s/^\s*[-*+o.]?(?:\s+|\Z)//;
735 s/^\*(\s|\Z)/\\\(bu$1/;
736 if ($$self{WEIRDINDENT}) {
737 $self->output (".RE\n");
738 $$self{WEIRDINDENT} = 0;
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;
748 # Begin a block for a particular translator. Setting VERBATIM triggers
749 # special handling in textblock().
753 my ($kind) = /^(\S+)/ or return;
754 if ($kind eq 'man' || $kind eq 'roff') {
755 $$self{VERBATIM} = 1;
761 # End a block for a particular translator. We assume that all =begin/=end
762 # pairs are properly closed.
766 $$self{VERBATIM} = 0;
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.
774 return unless s/^(?:man|roff)\b[ \t]*\n?//;
779 ##############################################################################
781 ##############################################################################
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.
789 # Smash whitespace in case we were split across multiple lines.
792 # If we were given any explicit text, just output it.
793 if (m{ ^ ([^|]+) \| }x) { return $1 }
795 # Okay, leading and trailing whitespace isn't important.
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 $_ }
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;
815 ($manpage, $section) = split (/\s*\/\s*/, $_, 2);
816 if ($manpage =~ /^[-:.\w]+(?:\(\S+\))?$/) {
817 $manpage =~ s/^([^\(]+)\(/'\f(IS' . $1 . '\f(IE\|'/e;
819 $section =~ s/^\"\s*//;
820 $section =~ s/\s*\"$//;
822 if ($manpage && $manpage !~ /\\f\(IS/) {
823 $manpage = "the $manpage manpage";
826 # Now build the actual output text.
828 if (!length ($section) && !length ($manpage)) {
829 carp "Invalid link $_";
830 } elsif (!length ($section)) {
832 } elsif ($section =~ /^[:\w]+(?:\(\))?/) {
833 $text .= 'the ' . $section . ' entry';
834 $text .= (length $manpage) ? " in $manpage"
835 : " elsewhere in this document";
837 if ($section !~ /^".*"$/) { $section = '"' . $section . '"' }
838 $text .= 'the section on ' . $section;
839 $text .= " in $manpage" if length $manpage;
845 ##############################################################################
846 # Escaping and fontification
847 ##############################################################################
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.
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.
866 my ($fixed, $bold, $italic) = (0, 0, 0);
867 my %magic = (F => \$fixed, B => \$bold, I => \$italic);
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)};
878 if ($f ne '\fR') { $sequence .= $f }
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.
895 my ($fixed, $bold, $italic) = (0, 0, 0);
896 my %magic = (F => \$fixed, B => \$bold, I => \$italic);
898 ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
899 $$self{FONTS}{($fixed && 1) . ($bold && 1) . ($italic && 1)};
905 ##############################################################################
906 # *roff-specific parsing and magic
907 ##############################################################################
909 # Called instead of parse_text, calls parse_text with the right flags.
912 $self->parse_text ({ -expand_seq => 'sequence',
913 -expand_ptree => 'collapse' }, @_);
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.
925 my ($self, $ptree, $literal) = @_;
927 return join ('', map {
932 s/-/\\-/g if $literal > 1;
933 s/__/_\\|_/g if $literal > 1;
938 return join ('', map {
939 ref ($_) ? $$_ : $self->guesswork ($_)
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.
950 # rofficate backslashes.
953 # Ensure double underbars have a tiny space between them.
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.
960 ( ^ | [\s\(\"\'\`\[\{<>] )
961 ( [A-Z] [A-Z] [/A-Z+:\d_\$&-]* )
962 (?: (?= [\s>\}\]\(\)\'\".?!,;] | -- ) | $ )
963 } { $1 . '\s-1' . $2 . '\s0' }egx;
965 # Italize functions in the form func().
969 [A-Za-z_] ([:\w]|\\s-?[01])+ \(\)
971 } { $1 . '\f(IS' . $2 . '\f(IE' }egx;
973 # func(n) is a reference to a manual page. Make it \fIfunc\fR\|(n).
976 ( [A-Za-z_] (?:[-:.\w]|\\s-?[01])+ )
980 } { $1 . '\f(IS' . $2 . '\f(IE\|' . $3 }egx;
982 # Convert simple Perl variable references to a fixed-width font.
987 } { $1 . '\f(FS' . $2 . '\f(FE'}egx;
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 '='))) {
1003 $pre . ('\-' x length $dash) . $post;
1007 # Fix up double quotes.
1008 s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx;
1010 # Make C++ into \*(C+, which is a squinched version.
1011 s{ \b C\+\+ } {\\*\(C+}gx;
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.
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 = '(?: \[.*\] | \{.*\} )?';
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.
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
1043 }xo && return '\f(FS' . $_ . '\f(FE';
1045 # If we didn't return, go ahead and quote the text.
1046 return '\f(FS\*(C`' . $_ . "\\*(C'\\f(FE";
1050 ##############################################################################
1052 ##############################################################################
1054 # Make vertical whitespace.
1057 $self->output (".PD\n") if ($$self{ITEMS} > 1);
1059 $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n")
1060 if $$self{NEEDSPACE};
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.
1067 my ($self, $section, $index) = @_;
1068 my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} };
1069 return unless ($section || @entries);
1073 my $output = '.IX Xref "'
1074 . join (' ', map { s/\"/\"\"/; $_ } @entries)
1078 $index =~ s/\"/\"\"/;
1079 $index =~ s/\\-/-/g;
1080 $index =~ s/\\(?:s-?\d|.\(..|.)//g;
1081 $output .= ".IX $section " . '"' . $index . '"' . "\n";
1083 $self->output ($output);
1086 # Output text to the output device.
1087 sub output { print { $_[0]->output_handle } $_[1] }
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.
1098 my $command = shift;
1101 s/\\\*\([LR]\"/\"/g;
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/) {
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;
1120 $nroff = qq("$nroff") . ($extra ? " $extra" : '');
1121 $troff = qq("$troff") . ($extra ? " $extra" : '');
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;
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";
1136 return "$command $nroff\n";
1139 $_ = qq("$_") . ($extra ? " $extra" : '');
1140 return "$command $_\n";
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.
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'
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 \
1168 . ds v \h'-1'\o'\(aa\(ga'
1176 ##############################################################################
1178 ##############################################################################
1182 Pod::Man - Convert POD data to formatted *roff input
1187 my $parser = Pod::Man->new (release => $VERSION, section => 8);
1189 # Read POD from STDIN and write to STDOUT.
1190 $parser->parse_from_filehandle;
1192 # Read POD from file.pod and write to file.1.
1193 $parser->parse_from_file ('file.pod', 'file.1');
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
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().
1209 new() can take options, in the form of key/value pairs that control the
1210 behavior of the parser. See below for details.
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
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
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.
1236 The recognized options to new() are as follows. All options take a single
1243 Sets the centered page header to use instead of "User Contributed Perl
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
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.
1260 Bold version of the fixed-width font. Defaults to CB. Only matters for
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.
1269 =item fixedbolditalic
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)
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.
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
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.
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.
1307 By default, section 1 will be used unless the file ends in .pm in which case
1308 section 3 will be selected.
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
1324 =item roff font should be 1 or 2 chars, not "%s"
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).
1331 =item Invalid link %s
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.
1337 =item Invalid quote specification "%s"
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.
1342 =item %s:%d: Unknown command paragraph "%s".
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.
1347 =item Unknown escape EE<lt>%sE<gt>
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.
1352 =item Unknown sequence %s
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.
1357 =item Unmatched =back
1359 (W) Pod::Man encountered a C<=back> command that didn't correspond to an
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>
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
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.
1379 When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
1380 necessarily get it right.
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.
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.
1391 Some of the automagic applied to file names assumes Unix directory
1394 Pod::Man is excessively slow.
1398 L<Pod::Parser|Pod::Parser>, perlpod(1), pod2man(1), nroff(1), troff(1),
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.
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
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>.
1416 =head1 COPYRIGHT AND LICENSE
1418 Copyright 1999, 2000, 2001 by Russ Allbery <rra@stanford.edu>.
1420 This program is free software; you may redistribute it and/or modify it
1421 under the same terms as Perl itself.