1 # Pod::Man -- Convert POD data to formatted *roff input.
2 # $Id: Man.pm,v 1.1 2000/03/16 22:00:36 eagle Exp $
4 # Copyright 1999, 2000 by Russ Allbery <rra@stanford.edu>
6 # This program is free software; you can 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
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
38 # Perl core and too many things could munge CVS magic revision strings.
39 # This number should ideally be the same as the CVS revision in podlators,
44 ############################################################################
45 # Preamble and *roff output tables
46 ############################################################################
48 # The following is the static preamble which starts all *roff output we
49 # generate. It's completely static except for the font to use as a
50 # fixed-width font, which is designed by @CFONT@. $PREAMBLE should
51 # 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)
67 .ie \\n(.$>=3 .ne \\$3
71 .de Vb \" Begin verbatim text
76 .de Ve \" End verbatim text
81 .\" Set up some character translations and predefined strings. \*(-- will
82 .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
83 .\" double quote, and \*(R" will give a right double quote. | will give a
84 .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used
85 .\" to do unbreakable dashes and therefore won't be available. \*(C` and
86 .\" \*(C' expand to `' in nroff, nothing in troff, for use with C<>
88 .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
92 . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
93 . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
106 .\" If the F register is turned on, we'll generate index entries on stderr
107 .\" for titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and
108 .\" index entries marked with X<> in POD. Of course, you'll have to process
109 .\" the output yourself in some meaningful fashion.
112 . tm Index:\\$1\t\\n%\t"\\$2"
118 .\" For nroff, turn off justification. Always turn off hyphenation; it
119 .\" makes way too many mistakes in technical documents.
123 .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
124 .\" Fear. Run. Save yourself. No user-serviceable parts.
126 . \" fudge factors for nroff and troff
135 . ds #H ((1u-(\\\\n(.fu%2u))*.13m)
141 . \" simple accents for nroff and troff
151 . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
152 . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
153 . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
154 . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
155 . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
156 . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
158 . \" troff and (daisy-wheel) nroff accents
159 .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
160 .ds 8 \h'\*(#H'\(*b\h'-\*(#H'
161 .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
162 .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
163 .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
164 .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
165 .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
166 .ds ae a\h'-(\w'a'u*4/10)'e
167 .ds Ae A\h'-(\w'A'u*4/10)'E
168 . \" corrections for vroff
169 .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
170 .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
171 . \" for low resolution devices (crt and lpr)
172 .if \n(.H>23 .if \n(.V>19 \
185 ----END OF PREAMBLE----
187 # This table is taken nearly verbatim from Tom Christiansen's pod2man. It
188 # assumes that the standard preamble has already been printed, since that's
189 # what defines all of the accent marks. Note that some of these are quoted
190 # with double quotes since they contain embedded single quotes, so use \\
191 # uniformly for backslash for readability.
193 'amp' => '&', # ampersand
194 'lt' => '<', # left chevron, less-than
195 'gt' => '>', # right chevron, greater-than
196 'quot' => '"', # double quote
198 'Aacute' => "A\\*'", # capital A, acute accent
199 'aacute' => "a\\*'", # small a, acute accent
200 'Acirc' => 'A\\*^', # capital A, circumflex accent
201 'acirc' => 'a\\*^', # small a, circumflex accent
202 'AElig' => '\*(AE', # capital AE diphthong (ligature)
203 'aelig' => '\*(ae', # small ae diphthong (ligature)
204 'Agrave' => "A\\*`", # capital A, grave accent
205 'agrave' => "A\\*`", # small a, grave accent
206 'Aring' => 'A\\*o', # capital A, ring
207 'aring' => 'a\\*o', # small a, ring
208 'Atilde' => 'A\\*~', # capital A, tilde
209 'atilde' => 'a\\*~', # small a, tilde
210 'Auml' => 'A\\*:', # capital A, dieresis or umlaut mark
211 'auml' => 'a\\*:', # small a, dieresis or umlaut mark
212 'Ccedil' => 'C\\*,', # capital C, cedilla
213 'ccedil' => 'c\\*,', # small c, cedilla
214 'Eacute' => "E\\*'", # capital E, acute accent
215 'eacute' => "e\\*'", # small e, acute accent
216 'Ecirc' => 'E\\*^', # capital E, circumflex accent
217 'ecirc' => 'e\\*^', # small e, circumflex accent
218 'Egrave' => 'E\\*`', # capital E, grave accent
219 'egrave' => 'e\\*`', # small e, grave accent
220 'ETH' => '\\*(D-', # capital Eth, Icelandic
221 'eth' => '\\*(d-', # small eth, Icelandic
222 'Euml' => 'E\\*:', # capital E, dieresis or umlaut mark
223 'euml' => 'e\\*:', # small e, dieresis or umlaut mark
224 'Iacute' => "I\\*'", # capital I, acute accent
225 'iacute' => "i\\*'", # small i, acute accent
226 'Icirc' => 'I\\*^', # capital I, circumflex accent
227 'icirc' => 'i\\*^', # small i, circumflex accent
228 'Igrave' => 'I\\*`', # capital I, grave accent
229 'igrave' => 'i\\*`', # small i, grave accent
230 'Iuml' => 'I\\*:', # capital I, dieresis or umlaut mark
231 'iuml' => 'i\\*:', # small i, dieresis or umlaut mark
232 'Ntilde' => 'N\*~', # capital N, tilde
233 'ntilde' => 'n\*~', # small n, tilde
234 'Oacute' => "O\\*'", # capital O, acute accent
235 'oacute' => "o\\*'", # small o, acute accent
236 'Ocirc' => 'O\\*^', # capital O, circumflex accent
237 'ocirc' => 'o\\*^', # small o, circumflex accent
238 'Ograve' => 'O\\*`', # capital O, grave accent
239 'ograve' => 'o\\*`', # small o, grave accent
240 'Oslash' => 'O\\*/', # capital O, slash
241 'oslash' => 'o\\*/', # small o, slash
242 'Otilde' => 'O\\*~', # capital O, tilde
243 'otilde' => 'o\\*~', # small o, tilde
244 'Ouml' => 'O\\*:', # capital O, dieresis or umlaut mark
245 'ouml' => 'o\\*:', # small o, dieresis or umlaut mark
246 'szlig' => '\*8', # small sharp s, German (sz ligature)
247 'THORN' => '\\*(Th', # capital THORN, Icelandic
248 'thorn' => '\\*(th', # small thorn, Icelandic
249 'Uacute' => "U\\*'", # capital U, acute accent
250 'uacute' => "u\\*'", # small u, acute accent
251 'Ucirc' => 'U\\*^', # capital U, circumflex accent
252 'ucirc' => 'u\\*^', # small u, circumflex accent
253 'Ugrave' => 'U\\*`', # capital U, grave accent
254 'ugrave' => 'u\\*`', # small u, grave accent
255 'Uuml' => 'U\\*:', # capital U, dieresis or umlaut mark
256 'uuml' => 'u\\*:', # small u, dieresis or umlaut mark
257 'Yacute' => "Y\\*'", # capital Y, acute accent
258 'yacute' => "y\\*'", # small y, acute accent
259 'yuml' => 'y\\*:', # small y, dieresis or umlaut mark
263 ############################################################################
264 # Static helper functions
265 ############################################################################
267 # Protect leading quotes and periods against interpretation as commands.
268 # Also protect anything starting with a backslash, since it could expand
269 # or hide something that *roff would interpret as a command. This is
270 # overkill, but it's much simpler than trying to parse *roff here.
273 s/^([.\'\\])/\\&$1/mg;
277 # Given a command and a single argument that may or may not contain double
278 # quotes, handle double-quote formatting for it. If there are no double
279 # quotes, just return the command followed by the argument in double quotes.
280 # If there are double quotes, use an if statement to test for nroff, and for
281 # nroff output the command followed by the argument in double quotes with
282 # embedded double quotes doubled. For other formatters, remap paired double
283 # quotes to `` and ''.
292 $troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g;
293 s/\"/\"\"/g if $extra;
294 $troff =~ s/\"/\"\"/g if $extra;
295 $_ = qq("$_") . ($extra ? " $extra" : '');
296 $troff = qq("$troff") . ($extra ? " $extra" : '');
297 return ".if n $command $_\n.el $command $troff\n";
299 $_ = qq("$_") . ($extra ? " $extra" : '');
300 return "$command $_\n";
304 # Translate a font string into an escape.
305 sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] }
308 ############################################################################
310 ############################################################################
312 # Initialize the object. Here, we also process any additional options
313 # passed to the constructor or set up defaults if none were given. center
314 # is the centered title, release is the version number, and date is the date
315 # for the documentation. Note that we can't know what file name we're
316 # processing due to the architecture of Pod::Parser, so that *has* to either
317 # be passed to the constructor or set separately with Pod::Man::name().
321 # Figure out the fixed-width font. If user-supplied, make sure that
322 # they are the right length.
323 for (qw/fixed fixedbold fixeditalic fixedbolditalic/) {
324 if (defined $$self{$_}) {
325 if (length ($$self{$_}) < 1 || length ($$self{$_}) > 2) {
326 croak "roff font should be 1 or 2 chars, not `$$self{$_}'";
333 # Set the default fonts. We can't be sure what fixed bold-italic is
334 # going to be called, so default to just bold.
335 $$self{fixed} ||= 'CW';
336 $$self{fixedbold} ||= 'CB';
337 $$self{fixeditalic} ||= 'CI';
338 $$self{fixedbolditalic} ||= 'CB';
340 # Set up a table of font escapes. First number is fixed-width, second
341 # is bold, third is italic.
342 $$self{FONTS} = { '000' => '\fR', '001' => '\fI',
343 '010' => '\fB', '011' => '\f(BI',
344 '100' => toescape ($$self{fixed}),
345 '101' => toescape ($$self{fixeditalic}),
346 '110' => toescape ($$self{fixedbold}),
347 '111' => toescape ($$self{fixedbolditalic})};
349 # Extra stuff for page titles.
350 $$self{center} = 'User Contributed Perl Documentation'
351 unless defined $$self{center};
352 $$self{indent} = 4 unless defined $$self{indent};
354 # We used to try first to get the version number from a local binary,
355 # but we shouldn't need that any more. Get the version from the running
356 # Perl. Work a little magic to handle subversions correctly under both
357 # the pre-5.6 and the post-5.6 version numbering schemes.
358 if (!defined $$self{release}) {
359 my @version = ($] =~ /^(\d+)\.(\d{3})(\d{0,3})$/);
361 $version[2] *= 10 ** (3 - length $version[2]);
362 for (@version) { $_ += 0 }
363 $$self{release} = 'perl v' . join ('.', @version);
366 # Double quotes in things that will be quoted.
367 for (qw/center date release/) {
368 $$self{$_} =~ s/\"/\"\"/g if $$self{$_};
371 $$self{INDENT} = 0; # Current indentation level.
372 $$self{INDENTS} = []; # Stack of indentations.
373 $$self{INDEX} = []; # Index keys waiting to be printed.
375 $self->SUPER::initialize;
378 # For each document we process, output the preamble first. Note that the
379 # fixed width font is a global default; once we interpolate it into the
380 # PREAMBLE, it ain't ever changing. Maybe fix this later.
384 # Try to figure out the name and section from the file name.
385 my $section = $$self{section} || 1;
386 my $name = $$self{name};
387 if (!defined $name) {
388 $name = $self->input_file;
389 $section = 3 if (!$$self{section} && $name =~ /\.pm\z/i);
390 $name =~ s/\.p(od|[lm])\z//i;
391 if ($section =~ /^1/) {
392 require File::Basename;
393 $name = uc File::Basename::basename ($name);
395 # Lose everything up to the first of
396 # */lib/*perl* standard or site_perl module
397 # */*perl*/lib from -D prefix=/opt/perl
398 # */*perl*/ random module hierarchy
399 # which works. Should be fixed to use File::Spec.
402 if ( s%^.*?/lib/[^/]*perl[^/]*/%%si
403 or s%^.*?/[^/]*perl[^/]*/(?:lib/)?%%si) {
404 s%^site(_perl)?/%%s; # site and site_perl
405 s%^(.*-$^O|$^O-.*)/%%so; # arch
406 s%^\d+\.\d+%%s; # version
413 # Modification date header. Try to use the modification time of our
415 if (!defined $$self{date}) {
416 my $time = (stat $self->input_file)[9] || time;
417 my ($day, $month, $year) = (localtime $time)[3,4,5];
420 $$self{date} = sprintf ('%4d-%02d-%02d', $year, $month, $day);
423 # Now, print out the preamble and the title.
424 $PREAMBLE =~ s/\@CFONT\@/$$self{fixed}/;
426 print { $self->output_handle } <<"----END OF HEADER----";
427 .\\" Automatically generated by Pod::Man version $VERSION
428 .\\" @{[ scalar localtime ]}
430 .\\" Standard preamble:
431 .\\" ======================================================================
433 .\\" ======================================================================
435 .IX Title "$name $section"
436 .TH $name $section "$$self{release}" "$$self{date}" "$$self{center}"
438 ----END OF HEADER----
441 # Initialize a few per-file variables.
443 $$self{NEEDSPACE} = 0;
447 ############################################################################
449 ############################################################################
451 # Called for each command paragraph. Gets the command, the associated
452 # paragraph, the line number, and a Pod::Paragraph object. Just dispatches
453 # the command to a method named the same as the command. =cut is handled
454 # internally by Pod::Parser.
458 return if $command eq 'pod';
459 return if ($$self{EXCLUDE} && $command ne 'end');
460 $command = 'cmd_' . $command;
461 $self->$command (@_);
464 # Called for a verbatim paragraph. Gets the paragraph, the line number, and
465 # a Pod::Paragraph object. Rofficate backslashes, untabify, put a
466 # zero-width character at the beginning of each line to protect against
467 # commands, and wrap in .Vb/.Ve.
470 return if $$self{EXCLUDE};
474 my $lines = tr/\n/\n/;
475 1 while s/^(.*?)(\t+)/$1 . ' ' x (length ($2) * 8 - length ($1) % 8)/me;
477 s/^(\s*\S)/'\&' . $1/gme;
478 $self->makespace if $$self{NEEDSPACE};
479 $self->output (".Vb $lines\n$_.Ve\n");
480 $$self{NEEDSPACE} = 0;
483 # Called for a regular text block. Gets the paragraph, the line number, and
484 # a Pod::Paragraph object. Perform interpolation and output the results.
487 return if $$self{EXCLUDE};
488 $self->output ($_[0]), return if $$self{VERBATIM};
490 # Perform a little magic to collapse multiple L<> references. We'll
491 # just rewrite the whole thing into actual text at this part, bypassing
492 # the whole internal sequence parsing thing.
495 (L< # A link of the form L</something>.
498 [:\w]+ # The item has to be a simple word...
499 (\(\))? # ...or simple function.
503 ,?\s+(and\s+)? # Allow lots of them, conjuncted.
512 s{ L< / ( [^>]+ ) > } {$1}xg;
513 my @items = split /(?:,?\s+(?:and\s+)?)/;
516 for ($i = 0; $i < @items; $i++) {
517 $string .= $items[$i];
518 $string .= ', ' if @items > 2 && $i != $#items;
519 $string .= ' ' if @items == 2 && $i == 2;
520 $string .= 'and ' if ($i == $#items - 1);
522 $string .= ' entries elsewhere in this document';
526 # Parse the tree and output it. collapse knows about references to
527 # scalars as well as scalars and does the right thing with them.
528 $text = $self->parse ($text, @_);
529 $text =~ s/\n\s*$/\n/;
530 $self->makespace if $$self{NEEDSPACE};
531 $self->output (protect $self->mapfonts ($text));
533 $$self{NEEDSPACE} = 1;
536 # Called for an interior sequence. Takes a Pod::InteriorSequence object and
537 # returns a reference to a scalar. This scalar is the final formatted text.
538 # It's returned as a reference so that other interior sequences above us
539 # know that the text has already been processed.
541 my ($self, $seq) = @_;
542 my $command = $seq->cmd_name;
544 # Zero-width characters.
545 if ($command eq 'Z') {
546 # Workaround to generate a blessable reference, needed by 5.005.
548 return bless \ "$tmp", 'Pod::Man::String';
551 # C<>, L<>, X<>, and E<> don't apply guesswork to their contents.
552 local $_ = $self->collapse ($seq->parse_tree, $command =~ /^[CELX]$/);
554 # Handle E<> escapes.
555 if ($command eq 'E') {
557 return bless \ chr ($_), 'Pod::Man::String';
558 } elsif (exists $ESCAPES{$_}) {
559 return bless \ "$ESCAPES{$_}", 'Pod::Man::String';
561 carp "Unknown escape E<$1>";
562 return bless \ "E<$_>", 'Pod::Man::String';
566 # For all the other sequences, empty content produces no output.
567 return '' if $_ eq '';
569 # Handle formatting sequences.
570 if ($command eq 'B') {
571 return bless \ ('\f(BS' . $_ . '\f(BE'), 'Pod::Man::String';
572 } elsif ($command eq 'F') {
573 return bless \ ('\f(IS' . $_ . '\f(IE'), 'Pod::Man::String';
574 } elsif ($command eq 'I') {
575 return bless \ ('\f(IS' . $_ . '\f(IE'), 'Pod::Man::String';
576 } elsif ($command eq 'C') {
579 return bless \ ('\f(FS\*(C`' . $_ . "\\*(C'\\f(FE"),
584 if ($command eq 'L') {
585 # A bug in lvalue subs in 5.6 requires the temporary variable.
586 my $tmp = $self->buildlink ($_);
587 return bless \ "$tmp", 'Pod::Man::String';
590 # Whitespace protection replaces whitespace with "\ ".
591 if ($command eq 'S') {
593 return bless \ "$_", 'Pod::Man::String';
596 # Add an index entry to the list of ones waiting to be output.
597 if ($command eq 'X') { push (@{ $$self{INDEX} }, $_); return '' }
599 # Anything else is unknown.
600 carp "Unknown sequence $command<$_>";
604 ############################################################################
606 ############################################################################
608 # All command paragraphs take the paragraph and the line number.
610 # First level heading. We can't output .IX in the NAME section due to a bug
611 # in some versions of catman, so don't output a .IX for that section. .SH
612 # already uses small caps, so remove any E<> sequences that would cause
616 local $_ = $self->parse (@_);
619 $self->output (switchquotes ('.SH', $self->mapfonts ($_)));
620 $self->outindex (($_ eq 'NAME') ? () : ('Header', $_));
621 $$self{NEEDSPACE} = 0;
624 # Second level heading.
627 local $_ = $self->parse (@_);
629 $self->output (switchquotes ('.Sh', $self->mapfonts ($_)));
630 $self->outindex ('Subsection', $_);
631 $$self{NEEDSPACE} = 0;
634 # Start a list. For indents after the first, wrap the outside indent in .RS
635 # so that hanging paragraph tags will be correct.
639 unless (/^[-+]?\d+\s+$/) { $_ = $$self{indent} }
640 if (@{ $$self{INDENTS} } > 0) {
641 $self->output (".RS $$self{INDENT}\n");
643 push (@{ $$self{INDENTS} }, $$self{INDENT});
644 $$self{INDENT} = ($_ + 0);
647 # End a list. If we've closed an embedded indent, we've mangled the hanging
648 # paragraph indent, so temporarily replace it with .RS and set WEIRDINDENT.
649 # We'll close that .RS at the next =back or =item.
652 $$self{INDENT} = pop @{ $$self{INDENTS} };
653 unless (defined $$self{INDENT}) {
654 carp "Unmatched =back";
657 if ($$self{WEIRDINDENT}) {
658 $self->output (".RE\n");
659 $$self{WEIRDINDENT} = 0;
661 if (@{ $$self{INDENTS} } > 0) {
662 $self->output (".RE\n");
663 $self->output (".RS $$self{INDENT}\n");
664 $$self{WEIRDINDENT} = 1;
666 $$self{NEEDSPACE} = 1;
669 # An individual list item. Emit an index entry for anything that's
670 # interesting, but don't emit index entries for things like bullets and
671 # numbers. rofficate bullets too while we're at it (so for nice output, use
672 # * for your lists rather than o or . or - or some other thing). Newlines
673 # in an item title are turned into spaces since *roff can't handle them
677 local $_ = $self->parse (@_);
681 if (/\w/ && !/^\w[.\)]\s*$/) {
683 $index =~ s/^\s*[-*+o.]?\s*//;
685 s/^\*(\s|\Z)/\\\(bu$1/;
686 if ($$self{WEIRDINDENT}) {
687 $self->output (".RE\n");
688 $$self{WEIRDINDENT} = 0;
690 $_ = $self->mapfonts ($_);
691 $self->output (switchquotes ('.Ip', $_, $$self{INDENT}));
692 $self->outindex ($index ? ('Item', $index) : ());
693 $$self{NEEDSPACE} = 0;
696 # Begin a block for a particular translator. Setting VERBATIM triggers
697 # special handling in textblock().
701 my ($kind) = /^(\S+)/ or return;
702 if ($kind eq 'man' || $kind eq 'roff') {
703 $$self{VERBATIM} = 1;
709 # End a block for a particular translator. We assume that all =begin/=end
710 # pairs are properly closed.
714 $$self{VERBATIM} = 0;
717 # One paragraph for a particular translator. Ignore it unless it's intended
718 # for man or roff, in which case we output it verbatim.
722 return unless s/^(?:man|roff)\b[ \t]*\n?//;
727 ############################################################################
729 ############################################################################
731 # Handle links. We can't actually make real hyperlinks, so this is all to
732 # figure out what text and formatting we print out.
737 # Smash whitespace in case we were split across multiple lines.
740 # If we were given any explicit text, just output it.
741 if (m{ ^ ([^|]+) \| }x) { return $1 }
743 # Okay, leading and trailing whitespace isn't important.
747 # Default to using the whole content of the link entry as a section
748 # name. Note that L<manpage/> forces a manpage interpretation, as does
749 # something looking like L<manpage(section)>. Do the same thing to
750 # L<manpage(section)> as we would to manpage(section) without the L<>;
751 # see guesswork(). If we've added italics, don't add the "manpage"
752 # text; markup is sufficient.
753 my ($manpage, $section) = ('', $_);
754 if (/^"\s*(.*?)\s*"$/) {
755 $section = '"' . $1 . '"';
756 } elsif (m{ ^ [-:.\w]+ (?: \( \S+ \) )? $ }x) {
757 ($manpage, $section) = ($_, '');
758 $manpage =~ s/^([^\(]+)\(/'\f(IS' . $1 . '\f(IE\|('/e;
760 ($manpage, $section) = split (/\s*\/\s*/, $_, 2);
761 if ($manpage =~ /^[-:.\w]+(?:\(\S+\))?$/) {
762 $manpage =~ s/^([^\(]+)\(/'\f(IS' . $1 . '\f(IE\|'/e;
764 $section =~ s/^\"\s*//;
765 $section =~ s/\s*\"$//;
767 if ($manpage && $manpage !~ /\\f\(IS/) {
768 $manpage = "the $manpage manpage";
771 # Now build the actual output text.
773 if (!length ($section) && !length ($manpage)) {
774 carp "Invalid link $_";
775 } elsif (!length ($section)) {
777 } elsif ($section =~ /^[:\w]+(?:\(\))?/) {
778 $text .= 'the ' . $section . ' entry';
779 $text .= (length $manpage) ? " in $manpage"
780 : " elsewhere in this document";
782 if ($section !~ /^".*"$/) { $section = '"' . $section . '"' }
783 $text .= 'the section on ' . $section;
784 $text .= " in $manpage" if length $manpage;
790 ############################################################################
791 # Escaping and fontification
792 ############################################################################
794 # At this point, we'll have embedded font codes of the form \f(<font>[SE]
795 # where <font> is one of B, I, or F. Turn those into the right font start
796 # or end codes. B<someI<thing> else> should map to \fBsome\f(BIthing\fB
797 # else\fR. The old pod2man didn't get this right; the second \fB was \fR,
798 # so nested sequences didn't work right. We take care of this by using
799 # variables as a combined pointer to our current font sequence, and set each
800 # to the number of current nestings of start tags for that font. Use them
801 # as a vector to look up what font sequence to use.
806 my ($fixed, $bold, $italic) = (0, 0, 0);
807 my %magic = (F => \$fixed, B => \$bold, I => \$italic);
809 ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1;
810 $$self{FONTS}{($fixed && 1) . ($bold && 1) . ($italic && 1)};
816 ############################################################################
817 # *roff-specific parsing
818 ############################################################################
820 # Called instead of parse_text, calls parse_text with the right flags.
823 $self->parse_text ({ -expand_seq => 'sequence',
824 -expand_ptree => 'collapse' }, @_);
827 # Takes a parse tree and a flag saying whether or not to treat it as literal
828 # text (not call guesswork on it), and returns the concatenation of all of
829 # the text strings in that parse tree. If the literal flag isn't true,
830 # guesswork() will be called on all plain scalars in the parse tree.
831 # Assumes that everything in the parse tree is either a scalar or a
832 # reference to a scalar.
834 my ($self, $ptree, $literal) = @_;
836 return join ('', map {
845 return join ('', map {
846 ref ($_) ? $$_ : $self->guesswork ($_)
851 # Takes a text block to perform guesswork on; this is guaranteed not to
852 # contain any interior sequences. Returns the text block with remapping
858 # rofficate backslashes.
861 # Ensure double underbars have a tiny space between them.
864 # Make all caps a little smaller. Be careful here, since we don't want
865 # to make @ARGV into small caps, nor do we want to fix the MIME in
866 # MIME-Version, since it looks weird with the full-height V.
868 ( ^ | [\s\(\"\'\`\[\{<>] )
869 ( [A-Z] [A-Z] [/A-Z+:\d_\$&-]* )
870 (?: (?= [\s>\}\]\)\'\".?!,;:] | -- ) | $ )
871 } { $1 . '\s-1' . $2 . '\s0' }egx;
873 # Turn PI into a pretty pi.
874 s{ (?: \\s-1 | \b ) PI (?: \\s0 | \b ) } {\\*\(PI}gx;
876 # Italize functions in the form func().
880 [:\w]+ (?:\\s-1)? \(\)
882 } { '\f(IS' . $1 . '\f(IE' }egx;
884 # func(n) is a reference to a manual page. Make it \fIfunc\fR\|(n).
887 (\w[-:.\w]+ (?:\\s-1)?)
891 } { '\f(IS' . $1 . '\f(IE\|' . $2 }egx;
893 # Convert simple Perl variable references to a fixed-width font.
898 } { $1 . '\f(FS' . $2 . '\f(FE'}egx;
900 # Translate -- into a real em dash if it's used like one and fix up
901 # dashes, but keep hyphens hyphens.
902 s{ (\G|^|.) (-+) (\b|.) } {
903 my ($pre, $dash, $post) = ($1, $2, $3);
904 if (length ($dash) == 1) {
905 ($pre =~ /[a-zA-Z]/) ? "$pre-$post" : "$pre\\-$post";
906 } elsif (length ($dash) == 2
907 && ((!$pre && !$post)
908 || ($pre =~ /\w/ && !$post)
909 || ($pre eq ' ' && $post eq ' ')
910 || ($pre eq '=' && $post ne '=')
911 || ($pre ne '=' && $post eq '='))) {
914 $pre . ('\-' x length $dash) . $post;
918 # Fix up double quotes.
919 s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx;
921 # Make C++ into \*(C+, which is a squinched version.
922 s{ \b C\+\+ } {\\*\(C+}gx;
929 ############################################################################
931 ############################################################################
933 # Make vertical whitespace.
936 $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n");
939 # Output any pending index entries, and optionally an index entry given as
940 # an argument. Support multiple index entries in X<> separated by slashes,
941 # and strip special escapes from index entries.
943 my ($self, $section, $index) = @_;
944 my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} };
945 return unless ($section || @entries);
949 my $output = '.IX Xref "'
950 . join (' ', map { s/\"/\"\"/; $_ } @entries)
954 $index =~ s/\"/\"\"/;
956 $index =~ s/\\(?:s-?\d|.\(..|.)//g;
957 $output .= ".IX $section " . '"' . $index . '"' . "\n";
959 $self->output ($output);
962 # Output text to the output device.
963 sub output { print { $_[0]->output_handle } $_[1] }
967 .\" These are some extra bits of roff that I don't want to lose track of
968 .\" but that have been removed from the preamble to make it a bit shorter
969 .\" since they're not currently being used. They're accents and special
970 .\" characters we don't currently have escapes for.
977 . ds ? \s-2c\h'-\w'c'u*7/10'\u\h'\*(#H'\zi\d\s+2\h'\w'c'u*8/10'
978 . ds ! \s-2\(or\s+2\h'-\w'\(or'u'\v'-.8m'.\v'.8m'
979 . 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'
981 .ds v \\k:\h'-(\\n(.wu*9/10-\*(#H)'\v'-\*(#V'\*(#[\s-4v\s0\v'\*(#V'\h'|\\n:u'\*(#]
982 .ds _ \\k:\h'-(\\n(.wu*9/10-\*(#H+(\*(#F*2/3))'\v'-.4m'\z\(hy\v'.4m'\h'|\\n:u'
983 .ds . \\k:\h'-(\\n(.wu*8/10)'\v'\*(#V*4/10'\z.\v'-\*(#V*4/10'\h'|\\n:u'
984 .ds 3 \*(#[\v'.2m'\s-2\&3\s0\v'-.2m'\*(#]
985 .ds oe o\h'-(\w'o'u*4/10)'e
986 .ds Oe O\h'-(\w'O'u*4/10)'E
987 .if \n(.H>23 .if \n(.V>19 \
989 . ds v \h'-1'\o'\(aa\(ga'
997 ############################################################################
999 ############################################################################
1003 Pod::Man - Convert POD data to formatted *roff input
1008 my $parser = Pod::Man->new (release => $VERSION, section => 8);
1010 # Read POD from STDIN and write to STDOUT.
1011 $parser->parse_from_filehandle;
1013 # Read POD from file.pod and write to file.1.
1014 $parser->parse_from_file ('file.pod', 'file.1');
1018 Pod::Man is a module to convert documentation in the POD format (the
1019 preferred language for documenting Perl) into *roff input using the man
1020 macro set. The resulting *roff code is suitable for display on a terminal
1021 using nroff(1), normally via man(1), or printing using troff(1). It is
1022 conventionally invoked using the driver script B<pod2man>, but it can also
1025 As a derived class from Pod::Parser, Pod::Man supports the same methods and
1026 interfaces. See L<Pod::Parser> for all the details; briefly, one creates a
1027 new parser with C<Pod::Man-E<gt>new()> and then calls either
1028 parse_from_filehandle() or parse_from_file().
1030 new() can take options, in the form of key/value pairs that control the
1031 behavior of the parser. See below for details.
1033 If no options are given, Pod::Man uses the name of the input file with any
1034 trailing C<.pod>, C<.pm>, or C<.pl> stripped as the man page title, to
1035 section 1 unless the file ended in C<.pm> in which case it defaults to
1036 section 3, to a centered title of "User Contributed Perl Documentation", to
1037 a centered footer of the Perl version it is run with, and to a left-hand
1038 footer of the modification date of its input (or the current date if given
1041 Pod::Man assumes that your *roff formatters have a fixed-width font named
1042 CW. If yours is called something else (like CR), use the C<fixed> option to
1043 specify it. This generally only matters for troff output for printing.
1044 Similarly, you can set the fonts used for bold, italic, and bold italic
1047 Besides the obvious pod conversions, Pod::Man also takes care of formatting
1048 func(), func(n), and simple variable references like $foo or @bar so you
1049 don't have to use code escapes for them; complex expressions like
1050 C<$fred{'stuff'}> will still need to be escaped, though. It also translates
1051 dashes that aren't used as hyphens into en dashes, makes long dashes--like
1052 this--into proper em dashes, fixes "paired quotes," makes C++ and PI look
1053 right, puts a little space between double underbars, makes ALLCAPS a teeny
1054 bit smaller in troff(1), and escapes stuff that *roff treats as special so
1055 that you don't have to.
1057 The recognized options to new() are as follows. All options take a single
1064 Sets the centered page header to use instead of "User Contributed Perl
1069 Sets the left-hand footer. By default, the modification date of the input
1070 file will be used, or the current date if stat() can't find that file (the
1071 case if the input is from STDIN), and the date will be formatted as
1076 The fixed-width font to use for vertabim text and code. Defaults to CW.
1077 Some systems may want CR instead. Only matters for troff(1) output.
1081 Bold version of the fixed-width font. Defaults to CB. Only matters for
1086 Italic version of the fixed-width font (actually, something of a misnomer,
1087 since most fixed-width fonts only have an oblique version, not an italic
1088 version). Defaults to CI. Only matters for troff(1) output.
1090 =item fixedbolditalic
1092 Bold italic (probably actually oblique) version of the fixed-width font.
1093 Pod::Man doesn't assume you have this, and defaults to CB. Some systems
1094 (such as Solaris) have this font available as CX. Only matters for troff(1)
1099 Set the centered footer. By default, this is the version of Perl you run
1100 Pod::Man under. Note that some system an macro sets assume that the
1101 centered footer will be a modification date and will prepend something like
1102 "Last modified: "; if this is the case, you may want to set C<release> to
1103 the last modified date and C<date> to the version number.
1107 Set the section for the C<.TH> macro. The standard section numbering
1108 convention is to use 1 for user commands, 2 for system calls, 3 for
1109 functions, 4 for devices, 5 for file formats, 6 for games, 7 for
1110 miscellaneous information, and 8 for administrator commands. There is a lot
1111 of variation here, however; some systems (like Solaris) use 4 for file
1112 formats, 5 for miscellaneous information, and 7 for devices. Still others
1113 use 1m instead of 8, or some mix of both. About the only section numbers
1114 that are reliably consistent are 1, 2, and 3.
1116 By default, section 1 will be used unless the file ends in .pm in which case
1117 section 3 will be selected.
1121 The standard Pod::Parser method parse_from_filehandle() takes up to two
1122 arguments, the first being the file handle to read POD from and the second
1123 being the file handle to write the formatted output to. The first defaults
1124 to STDIN if not given, and the second defaults to STDOUT. The method
1125 parse_from_file() is almost identical, except that its two arguments are the
1126 input and output disk files instead. See L<Pod::Parser> for the specific
1133 =item roff font should be 1 or 2 chars, not `%s'
1135 (F) You specified a *roff font (using C<fixed>, C<fixedbold>, etc.) that
1136 wasn't either one or two characters. Pod::Man doesn't support *roff fonts
1137 longer than two characters, although some *roff extensions do (the canonical
1138 versions of nroff(1) and troff(1) don't either).
1140 =item Invalid link %s
1142 (W) The POD source contained a C<LE<lt>E<gt>> sequence that Pod::Man was
1143 unable to parse. You should never see this error message; it probably
1144 indicates a bug in Pod::Man.
1146 =item Unknown escape EE<lt>%sE<gt>
1148 (W) The POD source contained an C<EE<lt>E<gt>> escape that Pod::Man didn't
1149 know about. C<EE<lt>%sE<gt>> was printed verbatim in the output.
1151 =item Unknown sequence %s
1153 (W) The POD source contained a non-standard interior sequence (something of
1154 the form C<XE<lt>E<gt>>) that Pod::Man didn't know about. It was ignored.
1156 =item Unmatched =back
1158 (W) Pod::Man encountered a C<=back> command that didn't correspond to an
1165 The lint-like features and strict POD format checking done by B<pod2man> are
1166 not yet implemented and should be, along with the corresponding C<lax>
1169 The NAME section should be recognized specially and index entries emitted
1170 for everything in that section. This would have to be deferred until the
1171 next section, since extraneous things in NAME tends to confuse various man
1174 The handling of hyphens, en dashes, and em dashes is somewhat fragile, and
1175 one may get the wrong one under some circumstances. This should only matter
1176 for troff(1) output.
1178 When and whether to use small caps is somewhat tricky, and Pod::Man doesn't
1179 necessarily get it right.
1181 Pod::Man doesn't handle font names longer than two characters. Neither do
1182 most troff(1) implementations, but GNU troff does as an extension. It would
1183 be nice to support as an option for those who want to use it.
1185 The preamble added to each output file is rather verbose, and most of it is
1186 only necessary in the presence of EE<lt>E<gt> escapes for non-ASCII
1187 characters. It would ideally be nice if all of those definitions were only
1188 output if needed, perhaps on the fly as the characters are used.
1190 Some of the automagic applied to file names assumes Unix directory
1193 Pod::Man is excessively slow.
1197 L<Pod::Parser|Pod::Parser>, perlpod(1), pod2man(1), nroff(1), troff(1),
1200 Ossanna, Joseph F., and Brian W. Kernighan. "Troff User's Manual,"
1201 Computing Science Technical Report No. 54, AT&T Bell Laboratories. This is
1202 the best documentation of standard nroff(1) and troff(1). At the time of
1203 this writing, it's available at http://www.cs.bell-labs.com/cm/cs/cstr.html.
1205 The man page documenting the man macro set may be man(5) instead of man(7)
1206 on your system. Also, please see pod2man(1) for extensive documentation on
1207 writing manual pages if you've not done it before and aren't familiar with
1212 Russ Allbery E<lt>rra@stanford.eduE<gt>, based I<very> heavily on the
1213 original B<pod2man> by Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>.