From: Steve Peters Date: Wed, 7 Dec 2005 12:36:59 +0000 (+0000) Subject: Upgrade to podlators-2.00 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=b7ae008f237ac1d94314836a23dc578e678c9243;p=p5sagit%2Fp5-mst-13.2.git Upgrade to podlators-2.00 p4raw-id: //depot/perl@26292 --- diff --git a/MANIFEST b/MANIFEST index 0e2601f..ddb52b6 100644 --- a/MANIFEST +++ b/MANIFEST @@ -2077,6 +2077,7 @@ lib/Pod/t/basic.ovr podlators test lib/Pod/t/basic.pod podlators test lib/Pod/t/basic.t podlators test lib/Pod/t/basic.txt podlators test +lib/Pod/t/color.t podlators test lib/Pod/t/contains_pod.t Pod-Parser test lib/Pod/t/eol.t end of line agnosticism lib/Pod/Text/Color.pm Convert POD data to color ASCII text @@ -2096,7 +2097,7 @@ lib/Pod/t/parselink.t podlators test lib/Pod/t/pod2html-lib.pl pod2html testing library lib/Pod/t/pod2latex.t See if Pod::LaTeX works lib/Pod/t/Select.t See if Pod::Select works -lib/Pod/t/text-errors.t podlators test +lib/Pod/t/termcap.t podlators test lib/Pod/t/text-options.t podlators test lib/Pod/t/text.t podlators test lib/Pod/t/Usage.t See if Pod::Usage works diff --git a/lib/Pod/Man.pm b/lib/Pod/Man.pm index 2cf1b40..0ccbfbe 100644 --- a/lib/Pod/Man.pm +++ b/lib/Pod/Man.pm @@ -1,7 +1,9 @@ # Pod::Man -- Convert POD data to formatted *roff input. -# $Id: Man.pm,v 1.37 2003/03/30 22:34:11 eagle Exp $ +# $Id: Man.pm,v 2.4 2005/03/19 19:40:01 eagle Exp $ # -# Copyright 1999, 2000, 2001, 2002, 2003 by Russ Allbery +# Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005 +# Russ Allbery +# Substantial contributions by Sean Burke # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -25,287 +27,113 @@ package Pod::Man; require 5.005; -use Carp qw(carp croak); -use Pod::ParseLink qw(parselink); -use Pod::Parser (); - use strict; use subs qw(makespace); use vars qw(@ISA %ESCAPES $PREAMBLE $VERSION); -@ISA = qw(Pod::Parser); +use Carp qw(croak); +use Pod::Simple (); +use POSIX qw(strftime); + +@ISA = qw(Pod::Simple); # Don't use the CVS revision as the version, since this module is also in Perl # core and too many things could munge CVS magic revision strings. This # number should ideally be the same as the CVS revision in podlators, however. -$VERSION = 1.37; - - -############################################################################## -# Preamble and *roff output tables -############################################################################## - -# The following is the static preamble which starts all *roff output we -# generate. It's completely static except for the font to use as a -# fixed-width font, which is designed by @CFONT@, and the left and right -# quotes to use for C<> text, designated by @LQOUTE@ and @RQUOTE@. $PREAMBLE -# should therefore be run through s/\@CFONT\@//g before output. -$PREAMBLE = <<'----END OF PREAMBLE----'; -.de Sh \" Subsection heading -.br -.if t .Sp -.ne 5 -.PP -\fB\\$1\fR -.PP -.. -.de Sp \" Vertical space (when we can't use .PP) -.if t .sp .5v -.if n .sp -.. -.de Vb \" Begin verbatim text -.ft @CFONT@ -.nf -.ne \\$1 -.. -.de Ve \" End verbatim text -.ft R -.fi -.. -.\" Set up some character translations and predefined strings. \*(-- will -.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left -.\" double quote, and \*(R" will give a right double quote. | will give a -.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to -.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' -.\" expand to `' in nroff, nothing in troff, for use with C<>. -.tr \(*W-|\(bv\*(Tr -.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' -.ie n \{\ -. ds -- \(*W- -. ds PI pi -. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch -. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch -. ds L" "" -. ds R" "" -. ds C` @LQUOTE@ -. ds C' @RQUOTE@ -'br\} -.el\{\ -. ds -- \|\(em\| -. ds PI \(*p -. ds L" `` -. ds R" '' -'br\} -.\" -.\" If the F register is turned on, we'll generate index entries on stderr for -.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index -.\" entries marked with X<> in POD. Of course, you'll have to process the -.\" output yourself in some meaningful fashion. -.if \nF \{\ -. de IX -. tm Index:\\$1\t\\n%\t"\\$2" -.. -. nr % 0 -. rr F -.\} -.\" -.\" For nroff, turn off justification. Always turn off hyphenation; it makes -.\" way too many mistakes in technical documents. -.hy 0 -.if n .na -.\" -.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). -.\" Fear. Run. Save yourself. No user-serviceable parts. -. \" fudge factors for nroff and troff -.if n \{\ -. ds #H 0 -. ds #V .8m -. ds #F .3m -. ds #[ \f1 -. ds #] \fP -.\} -.if t \{\ -. ds #H ((1u-(\\\\n(.fu%2u))*.13m) -. ds #V .6m -. ds #F 0 -. ds #[ \& -. ds #] \& -.\} -. \" simple accents for nroff and troff -.if n \{\ -. ds ' \& -. ds ` \& -. ds ^ \& -. ds , \& -. ds ~ ~ -. ds / -.\} -.if t \{\ -. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" -. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' -. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' -. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' -. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' -. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' -.\} -. \" troff and (daisy-wheel) nroff accents -.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' -.ds 8 \h'\*(#H'\(*b\h'-\*(#H' -.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] -.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' -.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' -.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] -.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] -.ds ae a\h'-(\w'a'u*4/10)'e -.ds Ae A\h'-(\w'A'u*4/10)'E -. \" corrections for vroff -.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' -.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' -. \" for low resolution devices (crt and lpr) -.if \n(.H>23 .if \n(.V>19 \ -\{\ -. ds : e -. ds 8 ss -. ds o a -. ds d- d\h'-1'\(ga -. ds D- D\h'-1'\(hy -. ds th \o'bp' -. ds Th \o'LP' -. ds ae ae -. ds Ae AE -.\} -.rm #[ #] #H #V #F C -----END OF PREAMBLE---- -#`# for cperl-mode +$VERSION = 2.04; + +# Set the debugging level. If someone has inserted a debug function into this +# class already, use that. Otherwise, use any Pod::Simple debug function +# that's defined, and failing that, define a debug level of 10. +BEGIN { + my $parent = defined (&Pod::Simple::DEBUG) ? \&Pod::Simple::DEBUG : undef; + unless (defined &DEBUG) { + *DEBUG = $parent || sub () { 10 }; + } +} -# This table is taken nearly verbatim from Tom Christiansen's pod2man. It -# assumes that the standard preamble has already been printed, since that's -# what defines all of the accent marks. Note that some of these are quoted -# with double quotes since they contain embedded single quotes, so use \\ -# uniformly for backslash for readability. -%ESCAPES = ( - 'amp' => '&', # ampersand - 'apos' => "'", # apostrophe - 'lt' => '<', # left chevron, less-than - 'gt' => '>', # right chevron, greater-than - 'quot' => '"', # double quote - 'sol' => '/', # solidus (forward slash) - 'verbar' => '|', # vertical bar - - 'Aacute' => "A\\*'", # capital A, acute accent - 'aacute' => "a\\*'", # small a, acute accent - 'Acirc' => 'A\\*^', # capital A, circumflex accent - 'acirc' => 'a\\*^', # small a, circumflex accent - 'AElig' => '\*(AE', # capital AE diphthong (ligature) - 'aelig' => '\*(ae', # small ae diphthong (ligature) - 'Agrave' => "A\\*`", # capital A, grave accent - 'agrave' => "A\\*`", # small a, grave accent - 'Aring' => 'A\\*o', # capital A, ring - 'aring' => 'a\\*o', # small a, ring - 'Atilde' => 'A\\*~', # capital A, tilde - 'atilde' => 'a\\*~', # small a, tilde - 'Auml' => 'A\\*:', # capital A, dieresis or umlaut mark - 'auml' => 'a\\*:', # small a, dieresis or umlaut mark - 'Ccedil' => 'C\\*,', # capital C, cedilla - 'ccedil' => 'c\\*,', # small c, cedilla - 'Eacute' => "E\\*'", # capital E, acute accent - 'eacute' => "e\\*'", # small e, acute accent - 'Ecirc' => 'E\\*^', # capital E, circumflex accent - 'ecirc' => 'e\\*^', # small e, circumflex accent - 'Egrave' => 'E\\*`', # capital E, grave accent - 'egrave' => 'e\\*`', # small e, grave accent - 'ETH' => '\\*(D-', # capital Eth, Icelandic - 'eth' => '\\*(d-', # small eth, Icelandic - 'Euml' => 'E\\*:', # capital E, dieresis or umlaut mark - 'euml' => 'e\\*:', # small e, dieresis or umlaut mark - 'Iacute' => "I\\*'", # capital I, acute accent - 'iacute' => "i\\*'", # small i, acute accent - 'Icirc' => 'I\\*^', # capital I, circumflex accent - 'icirc' => 'i\\*^', # small i, circumflex accent - 'Igrave' => 'I\\*`', # capital I, grave accent - 'igrave' => 'i\\*`', # small i, grave accent - 'Iuml' => 'I\\*:', # capital I, dieresis or umlaut mark - 'iuml' => 'i\\*:', # small i, dieresis or umlaut mark - 'Ntilde' => 'N\*~', # capital N, tilde - 'ntilde' => 'n\*~', # small n, tilde - 'Oacute' => "O\\*'", # capital O, acute accent - 'oacute' => "o\\*'", # small o, acute accent - 'Ocirc' => 'O\\*^', # capital O, circumflex accent - 'ocirc' => 'o\\*^', # small o, circumflex accent - 'Ograve' => 'O\\*`', # capital O, grave accent - 'ograve' => 'o\\*`', # small o, grave accent - 'Oslash' => 'O\\*/', # capital O, slash - 'oslash' => 'o\\*/', # small o, slash - 'Otilde' => 'O\\*~', # capital O, tilde - 'otilde' => 'o\\*~', # small o, tilde - 'Ouml' => 'O\\*:', # capital O, dieresis or umlaut mark - 'ouml' => 'o\\*:', # small o, dieresis or umlaut mark - 'szlig' => '\*8', # small sharp s, German (sz ligature) - 'THORN' => '\\*(Th', # capital THORN, Icelandic - 'thorn' => '\\*(th', # small thorn, Icelandic - 'Uacute' => "U\\*'", # capital U, acute accent - 'uacute' => "u\\*'", # small u, acute accent - 'Ucirc' => 'U\\*^', # capital U, circumflex accent - 'ucirc' => 'u\\*^', # small u, circumflex accent - 'Ugrave' => 'U\\*`', # capital U, grave accent - 'ugrave' => 'u\\*`', # small u, grave accent - 'Uuml' => 'U\\*:', # capital U, dieresis or umlaut mark - 'uuml' => 'u\\*:', # small u, dieresis or umlaut mark - 'Yacute' => "Y\\*'", # capital Y, acute accent - 'yacute' => "y\\*'", # small y, acute accent - 'yuml' => 'y\\*:', # small y, dieresis or umlaut mark - - 'nbsp' => '\\ ', # non-breaking space - 'shy' => '', # soft (discretionary) hyphen -); +# Import the ASCII constant from Pod::Simple. This is true iff we're in an +# ASCII-based universe (including such things as ISO 8859-1 and UTF-8), and is +# generally only false for EBCDIC. +BEGIN { *ASCII = \&Pod::Simple::ASCII } +# Pretty-print a data structure. Only used for debugging. +BEGIN { *pretty = \&Pod::Simple::pretty } ############################################################################## -# Static helper functions +# Object initialization ############################################################################## -# Protect leading quotes and periods against interpretation as commands. Also -# protect anything starting with a backslash, since it could expand or hide -# something that *roff would interpret as a command. This is overkill, but -# it's much simpler than trying to parse *roff here. -sub protect { - local $_ = shift; - s/^([.\'\\])/\\&$1/mg; - $_; +# Initialize the object and set various Pod::Simple options that we need. +# Here, we also process any additional options passed to the constructor or +# set up defaults if none were given. Note that all internal object keys are +# in all-caps, reserving all lower-case object keys for Pod::Simple and user +# arguments. +sub new { + my $class = shift; + my $self = $class->SUPER::new; + + # Tell Pod::Simple to handle S<> by automatically inserting  . + $self->nbsp_for_S (1); + + # Tell Pod::Simple to keep whitespace whenever possible. + if ($self->can ('preserve_whitespace')) { + $self->preserve_whitespace (1); + } else { + $self->fullstop_space_harden (1); + } + + # The =for and =begin targets that we accept. + $self->accept_targets (qw/man MAN roff ROFF/); + + # Ensure that contiguous blocks of code are merged together. Otherwise, + # some of the guesswork heuristics don't work right. + $self->merge_text (1); + + # Pod::Simple doesn't do anything useful with our arguments, but we want + # to put them in our object as hash keys and values. This could cause + # problems if we ever clash with Pod::Simple's own internal class + # variables. + %$self = (%$self, @_); + + # Initialize various other internal constants based on our arguments. + $self->init_fonts; + $self->init_quotes; + $self->init_page; + + # For right now, default to turning on all of the magic. + $$self{MAGIC_CPP} = 1; + $$self{MAGIC_EMDASH} = 1; + $$self{MAGIC_FUNC} = 1; + $$self{MAGIC_MANREF} = 1; + $$self{MAGIC_SMALLCAPS} = 1; + $$self{MAGIC_VARS} = 1; + + return $self; } # Translate a font string into an escape. sub toescape { (length ($_[0]) > 1 ? '\f(' : '\f') . $_[0] } - -############################################################################## -# Initialization -############################################################################## - -# Initialize the object. Here, we also process any additional options passed -# to the constructor or set up defaults if none were given. center is the -# centered title, release is the version number, and date is the date for the -# documentation. Note that we can't know what file name we're processing due -# to the architecture of Pod::Parser, so that *has* to either be passed to the -# constructor or set separately with Pod::Man::name(). -sub initialize { - my $self = shift; +# Determine which fonts the user wishes to use and store them in the object. +# Regular, italic, bold, and bold-italic are constants, but the fixed width +# fonts may be set by the user. Sets the internal hash key FONTS which is +# used to map our internal font escapes to actual *roff sequences later. +sub init_fonts { + my ($self) = @_; # Figure out the fixed-width font. If user-supplied, make sure that they # are the right length. for (qw/fixed fixedbold fixeditalic fixedbolditalic/) { - if (defined $$self{$_}) { - if (length ($$self{$_}) < 1 || length ($$self{$_}) > 2) { - croak qq(roff font should be 1 or 2 chars,) - . qq( not "$$self{$_}"); - } - } else { - $$self{$_} = ''; + my $font = $$self{$_}; + if (defined ($font) && (length ($font) < 1 || length ($font) > 2)) { + croak qq(roff font should be 1 or 2 chars, not "$font"); } } - # Set the default fonts. We can't be sure what fixed bold-italic is going - # to be called, so default to just bold. + # Set the default fonts. We can't be sure portably across different + # implementations what fixed bold-italic may be called (if it's even + # available), so default to just bold. $$self{fixed} ||= 'CW'; $$self{fixedbold} ||= 'CB'; $$self{fixeditalic} ||= 'CI'; @@ -318,31 +146,16 @@ sub initialize { '100' => toescape ($$self{fixed}), '101' => toescape ($$self{fixeditalic}), '110' => toescape ($$self{fixedbold}), - '111' => toescape ($$self{fixedbolditalic})}; - - # Extra stuff for page titles. - $$self{center} = 'User Contributed Perl Documentation' - unless defined $$self{center}; - $$self{indent} = 4 unless defined $$self{indent}; - - # We used to try first to get the version number from a local binary, but - # we shouldn't need that any more. Get the version from the running Perl. - # Work a little magic to handle subversions correctly under both the - # pre-5.6 and the post-5.6 version numbering schemes. - if (!defined $$self{release}) { - my @version = ($] =~ /^(\d+)\.(\d{3})(\d{0,3})$/); - $version[2] ||= 0; - $version[2] *= 10 ** (3 - length $version[2]); - for (@version) { $_ += 0 } - $$self{release} = 'perl v' . join ('.', @version); - } + '111' => toescape ($$self{fixedbolditalic}) }; +} - # Double quotes in things that will be quoted. - for (qw/center date release/) { - $$self{$_} =~ s/\"/\"\"/g if $$self{$_}; - } +# Initialize the quotes that we'll be using for C<> text. This requires some +# special handling, both to parse the user parameter if given and to make sure +# that the quotes will be safe against *roff. Sets the internal hash keys +# LQUOTE and RQUOTE. +sub init_quotes { + my ($self) = (@_); - # Figure out what quotes we'll be using for C<> text. $$self{quotes} ||= '"'; if ($$self{quotes} eq 'none') { $$self{LQUOTE} = $$self{RQUOTE} = ''; @@ -353,119 +166,577 @@ sub initialize { $$self{LQUOTE} = $1; $$self{RQUOTE} = $2; } else { - croak qq(Invalid quote specification "$$self{quotes}"); + croak(qq(Invalid quote specification "$$self{quotes}")) } - # Double the first quote; note that this should not be s///g as two double - # quotes is represented in *roff as three double quotes, not four. Weird, - # I know. - $$self{LQUOTE} =~ s/\"/\"\"/; - $$self{RQUOTE} =~ s/\"/\"\"/; + # Double the first quote; note that this should not be s///g as two double + # quotes is represented in *roff as three double quotes, not four. Weird, + # I know. + $$self{LQUOTE} =~ s/\"/\"\"/; + $$self{RQUOTE} =~ s/\"/\"\"/; +} + +# Initialize the page title information and indentation from our arguments. +sub init_page { + my ($self) = @_; + + # We used to try first to get the version number from a local binary, but + # we shouldn't need that any more. Get the version from the running Perl. + # Work a little magic to handle subversions correctly under both the + # pre-5.6 and the post-5.6 version numbering schemes. + my @version = ($] =~ /^(\d+)\.(\d{3})(\d{0,3})$/); + $version[2] ||= 0; + $version[2] *= 10 ** (3 - length $version[2]); + for (@version) { $_ += 0 } + my $version = join ('.', @version); + + # Set the defaults for page titles and indentation if the user didn't + # override anything. + $$self{center} = 'User Contributed Perl Documentation' + unless defined $$self{center}; + $$self{release} = 'perl v' . $version + unless defined $$self{release}; + $$self{indent} = 4 + unless defined $$self{indent}; + + # Double quotes in things that will be quoted. + for (qw/center release/) { + $$self{$_} =~ s/\"/\"\"/g if $$self{$_}; + } +} + +############################################################################## +# Core parsing +############################################################################## + +# This is the glue that connects the code below with Pod::Simple itself. The +# goal is to convert the event stream coming from the POD parser into method +# calls to handlers once the complete content of a tag has been seen. Each +# paragraph or POD command will have textual content associated with it, and +# as soon as all of a paragraph or POD command has been seen, that content +# will be passed in to the corresponding method for handling that type of +# object. The exceptions are handlers for lists, which have opening tag +# handlers and closing tag handlers that will be called right away. +# +# The internal hash key PENDING is used to store the contents of a tag until +# all of it has been seen. It holds a stack of open tags, each one +# represented by a tuple of the attributes hash for the tag, formatting +# options for the tag (which are inherited), and the contents of the tag. + +# Add a block of text to the contents of the current node, formatting it +# according to the current formatting instructions as we do. +sub _handle_text { + my ($self, $text) = @_; + DEBUG > 3 and print "== $text\n"; + my $tag = $$self{PENDING}[-1]; + $$tag[2] .= $self->format_text ($$tag[1], $text); +} + +# Given an element name, get the corresponding method name. +sub method_for_element { + my ($self, $element) = @_; + $element =~ tr/-/_/; + $element =~ tr/A-Z/a-z/; + $element =~ tr/_a-z0-9//cd; + return $element; +} + +# Handle the start of a new element. If cmd_element is defined, assume that +# we need to collect the entire tree for this element before passing it to the +# element method, and create a new tree into which we'll collect blocks of +# text and nested elements. Otherwise, if start_element is defined, call it. +sub _handle_element_start { + my ($self, $element, $attrs) = @_; + DEBUG > 3 and print "++ $element (<", join ('> <', %$attrs), ">)\n"; + my $method = $self->method_for_element ($element); + + # If we have a command handler, we need to accumulate the contents of the + # tag before calling it. Turn off IN_NAME for any command other than + # so that IN_NAME isn't still set for the first heading after the + # NAME heading. + if ($self->can ("cmd_$method")) { + DEBUG > 2 and print "<$element> starts saving a tag\n"; + $$self{IN_NAME} = 0 if ($element ne 'Para'); + + # How we're going to format embedded text blocks depends on the tag + # and also depends on our parent tags. Thankfully, inside tags that + # turn off guesswork and reformatting, nothing else can turn it back + # on, so this can be strictly inherited. + my $formatting = $$self{PENDING}[-1][1]; + $formatting = $self->formatting ($formatting, $element); + push (@{ $$self{PENDING} }, [ $attrs, $formatting, '' ]); + DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n"; + } elsif ($self->can ("start_$method")) { + my $method = 'start_' . $method; + $self->$method ($attrs, ''); + } else { + DEBUG > 2 and print "No $method start method, skipping\n"; + } +} + +# Handle the end of an element. If we had a cmd_ method for this element, +# this is where we pass along the tree that we built. Otherwise, if we have +# an end_ method for the element, call that. +sub _handle_element_end { + my ($self, $element) = @_; + DEBUG > 3 and print "-- $element\n"; + my $method = $self->method_for_element ($element); + + # If we have a command handler, pull off the pending text and pass it to + # the handler along with the saved attribute hash. + if ($self->can ("cmd_$method")) { + DEBUG > 2 and print " stops saving a tag\n"; + my $tag = pop @{ $$self{PENDING} }; + DEBUG > 4 and print "Popped: [", pretty ($tag), "]\n"; + DEBUG > 4 and print "Pending: [", pretty ($$self{PENDING}), "]\n"; + my $method = 'cmd_' . $method; + my $text = $self->$method ($$tag[0], $$tag[2]); + if (defined $text) { + if (@{ $$self{PENDING} } > 1) { + $$self{PENDING}[-1][2] .= $text; + } else { + $self->output ($text); + } + } + } elsif ($self->can ("end_$method")) { + my $method = 'end_' . $method; + $self->$method; + } else { + DEBUG > 2 and print "No $method end method, skipping\n"; + } +} + +############################################################################## +# General formatting +############################################################################## + +# Return formatting instructions for a new block. Takes the current +# formatting and the new element. Formatting inherits negatively, in the +# sense that if the parent has turned off guesswork, all child elements should +# leave it off. We therefore return a copy of the same formatting +# instructions but possibly with more things turned off depending on the +# element. +sub formatting { + my ($self, $current, $element) = @_; + my %options; + if ($current) { + %options = %$current; + } else { + %options = (guesswork => 1, cleanup => 1, convert => 1); + } + if ($element eq 'Data') { + $options{guesswork} = 0; + $options{cleanup} = 0; + $options{convert} = 0; + } elsif ($element eq 'X') { + $options{guesswork} = 0; + $options{cleanup} = 0; + } elsif ($element eq 'Verbatim' || $element eq 'C') { + $options{guesswork} = 0; + } + return \%options; +} + +# Format a text block. Takes a hash of formatting options and the text to +# format. Currently, the only formatting options are guesswork, cleanup, and +# convert, all of which are boolean. +sub format_text { + my ($self, $options, $text) = @_; + my $guesswork = $$options{guesswork} && !$$self{IN_NAME}; + my $cleanup = $$options{cleanup}; + my $convert = $$options{convert}; + + # Normally we do character translation, but we won't even do that in + # blocks. + if ($convert) { + if (ASCII) { + $text =~ s/(\\|[^\x00-\x7F])/$ESCAPES{ord ($1)} || "X"/eg; + } else { + $text =~ s/(\\)/$ESCAPES{ord ($1)} || "X"/eg; + } + } + + # Cleanup just tidies up a few things, telling *roff that the hyphens are + # hard and putting a bit of space between consecutive underscores. + if ($cleanup) { + $text =~ s/-/\\-/g; + $text =~ s/_(?=_)/_\\|/g; + } + + # If guesswork is asked for, do that. This involves more substantial + # formatting based on various heuristics that may only be appropriate for + # particular documents. + if ($guesswork) { + $text = $self->guesswork ($text); + } + + return $text; +} + +# Handles C<> text, deciding whether to put \*C` around it or not. This is a +# whole bunch of messy heuristics to try to avoid overquoting, originally from +# Barrie Slaymaker. This largely duplicates similar code in Pod::Text. +sub quote_literal { + my $self = shift; + local $_ = shift; + + # A regex that matches the portion of a variable reference that's the + # array or hash index, separated out just because we want to use it in + # several places in the following regex. + my $index = '(?: \[.*\] | \{.*\} )?'; + + # Check for things that we don't want to quote, and if we find any of + # them, return the string with just a font change and no quoting. + m{ + ^\s* + (?: + ( [\'\`\"] ) .* \1 # already quoted + | \` .* \' # `quoted' + | \$+ [\#^]? \S $index # special ($^Foo, $") + | [\$\@%&*]+ \#? [:\'\w]+ $index # plain var or func + | [\$\@%&*]* [:\'\w]+ (?: -> )? \(\s*[^\s,]\s*\) # 0/1-arg func call + | [-+]? ( \d[\d.]* | \.\d+ ) (?: [eE][-+]?\d+ )? # a number + | 0x [a-fA-F\d]+ # a hex constant + ) + \s*\z + }xso and return '\f(FS' . $_ . '\f(FE'; + + # If we didn't return, go ahead and quote the text. + return '\f(FS\*(C`' . $_ . "\\*(C'\\f(FE"; +} + +# Takes a text block to perform guesswork on. Returns the text block with +# formatting codes added. This is the code that marks up various Perl +# constructs and things commonly used in man pages without requiring the user +# to add any explicit markup, and is applied to all non-literal text. We're +# guaranteed that the text we're applying guesswork to does not contain any +# *roff formatting codes. Note that the inserted font sequences must be +# treated later with mapfonts or textmapfonts. +# +# This method is very fragile, both in the regular expressions it uses and in +# the ordering of those modifications. Care and testing is required when +# modifying it. +sub guesswork { + my $self = shift; + local $_ = shift; + DEBUG > 5 and print " Guesswork called on [$_]\n"; + + # By the time we reach this point, all hypens will be escaped by adding a + # backslash. We want to do that escaping if they're part of regular words + # and there's only a single dash, since that's a real hyphen that *roff + # gets to consider a possible break point. Make sure that a dash after + # the first character of a word stays non-breaking, however. + # + # Note that this is not user-controllable; we pretty much have to do this + # transformation or *roff will mangle the output in unacceptable ways. + s{ + ( (?:\G|^|\s) [a-zA-Z] ) ( \\- )? + ( (?: [a-zA-Z]+ \\-)+ ) + ( [a-zA-Z]+ ) (?=\s|\Z|\\\ ) + \b + } { + my ($prefix, $hyphen, $main, $suffix) = ($1, $2, $3, $4); + $hyphen ||= ''; + $main =~ s/\\-/-/g; + $prefix . $hyphen . $main . $suffix; + }egx; + + # Translate "--" into a real em-dash if it's used like one. This means + # that it's either surrounded by whitespace, it follows a regular word, or + # it occurs between two regular words. + if ($$self{MAGIC_EMDASH}) { + s{ (\s) \\-\\- (\s) } { $1 . '\*(--' . $2 }egx; + s{ (\b[a-zA-Z]+) \\-\\- (\s|\Z|[a-zA-Z]+\b) } { $1 . '\*(--' . $2 }egx; + } + + # Make words in all-caps a little bit smaller; they look better that way. + # However, we don't want to change Perl code (like @ARGV), nor do we want + # to fix the MIME in MIME-Version since it looks weird with the + # full-height V. + # + # We change only a string of all caps (2) either at the beginning of the + # line or following regular punctuation (like quotes) or whitespace (1), + # and followed by either similar punctuation, an em-dash, or the end of + # the line (3). + if ($$self{MAGIC_SMALLCAPS}) { + s{ + ( ^ | [\s\(\"\'\`\[\{<>] | \\\ ) # (1) + ( [A-Z] [A-Z] (?: [/A-Z+:\d_\$&] | \\- )* ) # (2) + (?= [\s>\}\]\(\)\'\".?!,;] | \\*\(-- | \\\ | $ ) # (3) + } { + $1 . '\s-1' . $2 . '\s0' + }egx; + } + + # Note that from this point forward, we have to adjust for \s-1 and \s-0 + # strings inserted around things that we've made small-caps if later + # transforms should work on those strings. + + # Italize functions in the form func(), including functions that are in + # all capitals, but don't italize if there's anything between the parens. + # The function must start with an alphabetic character or underscore and + # then consist of word characters or colons. + if ($$self{MAGIC_FUNC}) { + s{ + ( \b | \\s-1 ) + ( [A-Za-z_] ([:\w] | \\s-?[01])+ \(\) ) + } { + $1 . '\f(IS' . $2 . '\f(IE' + }egx; + } + + # Change references to manual pages to put the page name in italics but + # the number in the regular font, with a thin space between the name and + # the number. Only recognize func(n) where func starts with an alphabetic + # character or underscore and contains only word characters, periods (for + # configuration file man pages), or colons, and n is a single digit, + # optionally followed by some number of lowercase letters. Note that this + # does not recognize man page references like perl(l) or socket(3SOCKET). + if ($$self{MAGIC_MANREF}) { + s{ + ( \b | \\s-1 ) + ( [A-Za-z_] (?:[.:\w] | \\- | \\s-?[01])+ ) + ( \( \d [a-z]* \) ) + } { + $1 . '\f(IS' . $2 . '\f(IE\|' . $3 + }egx; + } + + # Convert simple Perl variable references to a fixed-width font. Be + # careful not to convert functions, though; there are too many subtleties + # with them to want to perform this transformation. + if ($$self{MAGIC_VARS}) { + s{ + ( ^ | \s+ ) + ( [\$\@%] [\w:]+ ) + (?! \( ) + } { + $1 . '\f(FS' . $2 . '\f(FE' + }egx; + } + + # Fix up double quotes. Unfortunately, we miss this transformation if the + # quoted text contains any code with formatting codes and there's not much + # we can effectively do about that, which makes it somewhat unclear if + # this is really a good idea. + s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx; + + # Make C++ into \*(C+, which is a squinched version. + if ($$self{MAGIC_CPP}) { + s{ \b C\+\+ } {\\*\(C+}gx; + } + + # Done. + DEBUG > 5 and print " Guesswork returning [$_]\n"; + return $_; +} + +############################################################################## +# Output +############################################################################## + +# When building up the *roff code, we don't use real *roff fonts. Instead, we +# embed font codes of the form \f([SE] where is one of B, I, or +# F, S stands for start, and E stands for end. This method turns these into +# the right start and end codes. +# +# We add this level of complexity because the old pod2man didn't get code like +# B else> right; after I<> it switched back to normal text rather +# than bold. We take care of this by using variables that state whether bold, +# italic, or fixed are turned on as a combined pointer to our current font +# sequence, and set each to the number of current nestings of start tags for +# that font. +# +# \fP changes to the previous font, but only one previous font is kept. We +# don't know what the outside level font is; normally it's R, but if we're +# inside a heading it could be something else. So arrange things so that the +# outside font is always the "previous" font and end with \fP instead of \fR. +# Idea from Zack Weinberg. +sub mapfonts { + my ($self, $text) = @_; + my ($fixed, $bold, $italic) = (0, 0, 0); + my %magic = (F => \$fixed, B => \$bold, I => \$italic); + my $last = '\fR'; + $text =~ s< + \\f\((.)(.) + > < + my $sequence = ''; + my $f; + if ($last ne '\fR') { $sequence = '\fP' } + ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1; + $f = $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) }; + if ($f eq $last) { + ''; + } else { + if ($f ne '\fR') { $sequence .= $f } + $last = $f; + $sequence; + } + >gxe; + return $text; +} + +# Unfortunately, there is a bug in Solaris 2.6 nroff (not present in GNU +# groff) where the sequence \fB\fP\f(CW\fP leaves the font set to B rather +# than R, presumably because \f(CW doesn't actually do a font change. To work +# around this, use a separate textmapfonts for text blocks where the default +# font is always R and only use the smart mapfonts for headings. +sub textmapfonts { + my ($self, $text) = @_; + my ($fixed, $bold, $italic) = (0, 0, 0); + my %magic = (F => \$fixed, B => \$bold, I => \$italic); + $text =~ s< + \\f\((.)(.) + > < + ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1; + $$self{FONTS}{ ($fixed && 1) . ($bold && 1) . ($italic && 1) }; + >gxe; + return $text; +} + +# Given a command and a single argument that may or may not contain double +# quotes, handle double-quote formatting for it. If there are no double +# quotes, just return the command followed by the argument in double quotes. +# If there are double quotes, use an if statement to test for nroff, and for +# nroff output the command followed by the argument in double quotes with +# embedded double quotes doubled. For other formatters, remap paired double +# quotes to LQUOTE and RQUOTE. +sub switchquotes { + my ($self, $command, $text, $extra) = @_; + $text =~ s/\\\*\([LR]\"/\"/g; + + # We also have to deal with \*C` and \*C', which are used to add the + # quotes around C<> text, since they may expand to " and if they do this + # confuses the .SH macros and the like no end. Expand them ourselves. + # Also separate troff from nroff if there are any fixed-width fonts in use + # to work around problems with Solaris nroff. + my $c_is_quote = ($$self{LQUOTE} =~ /\"/) || ($$self{RQUOTE} =~ /\"/); + my $fixedpat = join '|', @{ $$self{FONTS} }{'100', '101', '110', '111'}; + $fixedpat =~ s/\\/\\\\/g; + $fixedpat =~ s/\(/\\\(/g; + if ($text =~ m/\"/ || $text =~ m/$fixedpat/) { + $text =~ s/\"/\"\"/g; + my $nroff = $text; + my $troff = $text; + $troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g; + if ($c_is_quote and $text =~ m/\\\*\(C[\'\`]/) { + $nroff =~ s/\\\*\(C\`/$$self{LQUOTE}/g; + $nroff =~ s/\\\*\(C\'/$$self{RQUOTE}/g; + $troff =~ s/\\\*\(C[\'\`]//g; + } + $nroff = qq("$nroff") . ($extra ? " $extra" : ''); + $troff = qq("$troff") . ($extra ? " $extra" : ''); + + # Work around the Solaris nroff bug where \f(CW\fP leaves the font set + # to Roman rather than the actual previous font when used in headings. + # troff output may still be broken, but at least we can fix nroff by + # just switching the font changes to the non-fixed versions. + $nroff =~ s/\Q$$self{FONTS}{100}\E(.*)\\f[PR]/$1/g; + $nroff =~ s/\Q$$self{FONTS}{101}\E(.*)\\f([PR])/\\fI$1\\f$2/g; + $nroff =~ s/\Q$$self{FONTS}{110}\E(.*)\\f([PR])/\\fB$1\\f$2/g; + $nroff =~ s/\Q$$self{FONTS}{111}\E(.*)\\f([PR])/\\f\(BI$1\\f$2/g; + + # Now finally output the command. Bother with .ie only if the nroff + # and troff output aren't the same. + if ($nroff ne $troff) { + return ".ie n $command $nroff\n.el $command $troff\n"; + } else { + return "$command $nroff\n"; + } + } else { + $text = qq("$text") . ($extra ? " $extra" : ''); + return "$command $text\n"; + } +} + +# Protect leading quotes and periods against interpretation as commands. Also +# protect anything starting with a backslash, since it could expand or hide +# something that *roff would interpret as a command. This is overkill, but +# it's much simpler than trying to parse *roff here. +sub protect { + my ($self, $text) = @_; + $text =~ s/^([.\'\\])/\\&$1/mg; + return $text; +} + +# Make vertical whitespace if NEEDSPACE is set, appropriate to the indentation +# level the situation. This function is needed since in *roff one has to +# create vertical whitespace after paragraphs and between some things, but +# other macros create their own whitespace. Also close out a sequence of +# repeated =items, since calling makespace means we're about to begin the item +# body. +sub makespace { + my ($self) = @_; + $self->output (".PD\n") if $$self{ITEMS} > 1; + $$self{ITEMS} = 0; + $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n") + if $$self{NEEDSPACE}; +} + +# Output any pending index entries, and optionally an index entry given as an +# argument. Support multiple index entries in X<> separated by slashes, and +# strip special escapes from index entries. +sub outindex { + my ($self, $section, $index) = @_; + my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} }; + return unless ($section || @entries); + + # We're about to output all pending entries, so clear our pending queue. + $$self{INDEX} = []; + + # Build the output. Regular index entries are marked Xref, and headings + # pass in their own section. Undo some *roff formatting on headings. + my @output; + if (@entries) { + push @output, [ 'Xref', join (' ', @entries) ]; + } + if ($section) { + $index =~ s/\\-/-/g; + $index =~ s/\\(?:s-?\d|.\(..|.)//g; + push @output, [ $section, $index ]; + } - $self->SUPER::initialize; + # Print out the .IX commands. + for (@output) { + my ($type, $entry) = @$_; + $entry =~ s/\"/\"\"/g; + $self->output (".IX $type " . '"' . $entry . '"' . "\n"); + } } -# For each document we process, output the preamble first. -sub begin_pod { - my $self = shift; +# Output some text, without any additional changes. +sub output { + my ($self, @text) = @_; + print { $$self{output_fh} } @text; +} - # Try to figure out the name and section from the file name. - my $section = $$self{section} || 1; - my $name = $$self{name}; - if (!defined $name) { - $name = $self->input_file; - $section = 3 if (!$$self{section} && $name =~ /\.pm\z/i); - $name =~ s/\.p(od|[lm])\z//i; - if ($section !~ /^3/) { - require File::Basename; - $name = uc File::Basename::basename ($name); - } else { - # Assume that we're dealing with a module. We want to figure out - # the full module name from the path to the file, but we don't - # want to include too much of the path into the module name. Lose - # everything up to the first of: - # - # */lib/*perl*/ standard or site_perl module - # */*perl*/lib/ from -Dprefix=/opt/perl - # */*perl*/ random module hierarchy - # - # which works. Also strip off a leading site or site_perl - # component, any OS-specific component, and any version number - # component, and strip off an initial component of "lib" or - # "blib/lib" since that's what ExtUtils::MakeMaker creates. - # splitdir requires at least File::Spec 0.8. - require File::Spec; - my ($volume, $dirs, $file) = File::Spec->splitpath ($name); - my @dirs = File::Spec->splitdir ($dirs); - my $cut = 0; - my $i; - for ($i = 0; $i < scalar @dirs; $i++) { - if ($dirs[$i] eq 'lib' && $dirs[$i + 1] =~ /perl/) { - $cut = $i + 2; - last; - } elsif ($dirs[$i] =~ /perl/) { - $cut = $i + 1; - $cut++ if $dirs[$i + 1] eq 'lib'; - last; - } - } - if ($cut > 0) { - splice (@dirs, 0, $cut); - shift @dirs if ($dirs[0] =~ /^site(_perl)?$/); - shift @dirs if ($dirs[0] =~ /^[\d.]+$/); - shift @dirs if ($dirs[0] =~ /^(.*-$^O|$^O-.*|$^O)$/); - } - shift @dirs if $dirs[0] eq 'lib'; - splice (@dirs, 0, 2) if ($dirs[0] eq 'blib' && $dirs[1] eq 'lib'); +############################################################################## +# Document initialization +############################################################################## - # Remove empty directories when building the module name; they - # occur too easily on Unix by doubling slashes. - $name = join ('::', (grep { $_ ? $_ : () } @dirs), $file); - } +# Handle the start of the document. Here we handle empty documents, as well +# as setting up our basic macros in a preamble and building the page title. +sub start_document { + my ($self, $attrs) = @_; + if ($$attrs{contentless} && !$$self{ALWAYS_EMIT_SOMETHING}) { + DEBUG and print "Document is contentless\n"; + $$self{CONTENTLESS} = 1; + return; } - # If $name contains spaces, quote it; this mostly comes up in the case of - # input from stdin. - $name = '"' . $name . '"' if ($name =~ /\s/); - - # Modification date header. Try to use the modification time of our - # input. - if (!defined $$self{date}) { - my $time = (stat $self->input_file)[9] || time; - my ($day, $month, $year) = (localtime $time)[3,4,5]; - $month++; - $year += 1900; - $$self{date} = sprintf ('%4d-%02d-%02d', $year, $month, $day); + # Determine information for the preamble and then output it. + my ($name, $section); + if (defined $$self{name}) { + $name = $$self{name}; + $section = $$self{section} || 1; + } else { + ($name, $section) = $self->devise_title; } + my $date = $$self{date} || $self->devise_date; + $self->preamble ($name, $section, $date) + unless $self->bare_output or DEBUG > 9; - # Now, print out the preamble and the title. The meaning of the arguments - # to .TH unfortunately vary by system; some systems consider the fourth - # argument to be a "source" and others use it as a version number. - # Generally it's just presented as the left-side footer, though, so it - # doesn't matter too much if a particular system gives it another - # interpretation. - # - # The order of date and release used to be reversed in older versions of - # this module, but this order is correct for both Solaris and Linux. - local $_ = $PREAMBLE; - s/\@CFONT\@/$$self{fixed}/; - s/\@LQUOTE\@/$$self{LQUOTE}/; - s/\@RQUOTE\@/$$self{RQUOTE}/; - chomp $_; - my $pversion = $Pod::Parser::VERSION; - print { $self->output_handle } <<"----END OF HEADER----"; -.\\" Automatically generated by Pod::Man v$VERSION, Pod::Parser v$pversion -.\\" -.\\" Standard preamble: -.\\" ======================================================================== -$_ -.\\" ======================================================================== -.\\" -.IX Title "$name $section" -.TH $name $section "$$self{date}" "$$self{release}" "$$self{center}" -----END OF HEADER---- - - # Initialize a few per-file variables. + # Initialize a few per-document variables. $$self{INDENT} = 0; # Current indentation level. $$self{INDENTS} = []; # Stack of indentations. $$self{INDEX} = []; # Index keys waiting to be printed. @@ -474,68 +745,150 @@ $_ $$self{ITEMTYPES} = []; # Stack of =item types, one per list. $$self{SHIFTWAIT} = 0; # Whether there is a shift waiting. $$self{SHIFTS} = []; # Stack of .RS shifts. + $$self{PENDING} = [[]]; # Pending output. } +# Handle the end of the document. This does nothing but print out a final +# comment at the end of the document under debugging. +sub end_document { + my ($self) = @_; + return if $self->bare_output; + return if ($$self{CONTENTLESS} && !$$self{ALWAYS_EMIT_SOMETHING}); + $self->output (q(.\" [End document]) . "\n") if DEBUG; +} -############################################################################## -# Core overrides -############################################################################## - -# Called for each command paragraph. Gets the command, the associated -# paragraph, the line number, and a Pod::Paragraph object. Just dispatches -# the command to a method named the same as the command. =cut is handled -# internally by Pod::Parser. -sub command { - my $self = shift; - my $command = shift; - return if $command eq 'pod'; - return if ($$self{EXCLUDE} && $command ne 'end'); - if ($self->can ('cmd_' . $command)) { - $command = 'cmd_' . $command; - $self->$command (@_); +# Try to figure out the name and section from the file name and return them as +# a list, returning an empty name and section 1 if we can't find any better +# information. Uses File::Basename and File::Spec as necessary. +sub devise_title { + my ($self) = @_; + my $name = $self->source_filename || ''; + my $section = $$self{section} || 1; + $section = 3 if (!$$self{section} && $name =~ /\.pm\z/i); + $name =~ s/\.p(od|[lm])\z//i; + + # If the section isn't 3, then the name defaults to just the basename of + # the file. Otherwise, assume we're dealing with a module. We want to + # figure out the full module name from the path to the file, but we don't + # want to include too much of the path into the module name. Lose + # anything up to the first off: + # + # */lib/*perl*/ standard or site_perl module + # */*perl*/lib/ from -Dprefix=/opt/perl + # */*perl*/ random module hierarchy + # + # which works. Also strip off a leading site, site_perl, or vendor_perl + # component, any OS-specific component, and any version number component, + # and strip off an initial component of "lib" or "blib/lib" since that's + # what ExtUtils::MakeMaker creates. splitdir requires at least File::Spec + # 0.8. + if ($section !~ /^3/) { + require File::Basename; + $name = uc File::Basename::basename ($name); } else { - my ($text, $line, $paragraph) = @_; - my $file; - ($file, $line) = $paragraph->file_line; - $text =~ s/\n+\z//; - $text = " $text" if ($text =~ /^\S/); - warn qq($file:$line: Unknown command paragraph "=$command$text"\n); - return; + require File::Spec; + my ($volume, $dirs, $file) = File::Spec->splitpath ($name); + my @dirs = File::Spec->splitdir ($dirs); + my $cut = 0; + my $i; + for ($i = 0; $i < scalar @dirs; $i++) { + if ($dirs[$i] eq 'lib' && $dirs[$i + 1] =~ /perl/) { + $cut = $i + 2; + last; + } elsif ($dirs[$i] =~ /perl/) { + $cut = $i + 1; + $cut++ if $dirs[$i + 1] eq 'lib'; + last; + } + } + if ($cut > 0) { + splice (@dirs, 0, $cut); + shift @dirs if ($dirs[0] =~ /^(site|vendor)(_perl)?$/); + shift @dirs if ($dirs[0] =~ /^[\d.]+$/); + shift @dirs if ($dirs[0] =~ /^(.*-$^O|$^O-.*|$^O)$/); + } + shift @dirs if $dirs[0] eq 'lib'; + splice (@dirs, 0, 2) if ($dirs[0] eq 'blib' && $dirs[1] eq 'lib'); + + # Remove empty directories when building the module name; they + # occur too easily on Unix by doubling slashes. + $name = join ('::', (grep { $_ ? $_ : () } @dirs), $file); } + return ($name, $section); } -# Called for a verbatim paragraph. Gets the paragraph, the line number, and a -# Pod::Paragraph object. Rofficate backslashes, untabify, put a zero-width -# character at the beginning of each line to protect against commands, and -# wrap in .Vb/.Ve. -sub verbatim { - my $self = shift; - return if $$self{EXCLUDE}; - local $_ = shift; - return if /^\s+$/; - s/\s+$/\n/; - my $lines = tr/\n/\n/; - 1 while s/^(.*?)(\t+)/$1 . ' ' x (length ($2) * 8 - length ($1) % 8)/me; - s/\\/\\e/g; - s/^(\s*\S)/'\&' . $1/gme; - $self->makespace; - $self->output (".Vb $lines\n$_.Ve\n"); - $$self{NEEDSPACE} = 1; +# Determine the modification date and return that, properly formatted in ISO +# format. If we can't get the modification date of the input, instead use the +# current time. +sub devise_date { + my ($self) = @_; + my $input = $self->source_filename; + my $time = ($input ? (stat $input)[9] : time); + return strftime ('%Y-%m-%d', localtime $time); } -# Called for a regular text block. Gets the paragraph, the line number, and a -# Pod::Paragraph object. Perform interpolation and output the results. -sub textblock { - my $self = shift; - return if $$self{EXCLUDE}; - $self->output ($_[0]), return if $$self{VERBATIM}; +# Print out the preamble and the title. The meaning of the arguments to .TH +# unfortunately vary by system; some systems consider the fourth argument to +# be a "source" and others use it as a version number. Generally it's just +# presented as the left-side footer, though, so it doesn't matter too much if +# a particular system gives it another interpretation. +# +# The order of date and release used to be reversed in older versions of this +# module, but this order is correct for both Solaris and Linux. +sub preamble { + my ($self, $name, $section, $date) = @_; + my $preamble = $self->preamble_template; + + # Build the index line and make sure that it will be syntactically valid. + my $index = "$name $section"; + $index =~ s/\"/\"\"/g; + + # If name or section contain spaces, quote them (section really never + # should, but we may as well be cautious). + for ($name, $section) { + if (/\s/) { + s/\"/\"\"/g; + $_ = '"' . $_ . '"'; + } + } + + # Double quotes in date, since it will be quoted. + $date =~ s/\"/\"\"/g; + + # Substitute into the preamble the configuration options. + $preamble =~ s/\@CFONT\@/$$self{fixed}/; + $preamble =~ s/\@LQUOTE\@/$$self{LQUOTE}/; + $preamble =~ s/\@RQUOTE\@/$$self{RQUOTE}/; + chomp $preamble; + + # Get the version information. + my $version = $self->version_report; + + # Finally output everything. + $self->output (<<"----END OF HEADER----"); +.\\" Automatically generated by $version +.\\" +.\\" Standard preamble: +.\\" ======================================================================== +$preamble +.\\" ======================================================================== +.\\" +.IX Title "$index" +.TH $name $section "$date" "$$self{release}" "$$self{center}" +----END OF HEADER---- + $self->output (".\\\" [End of preamble]\n") if DEBUG; +} + +############################################################################## +# Text blocks +############################################################################## - # Parse the tree. collapse knows about references to scalars as well as - # scalars and does the right thing with them. Tidy up any trailing - # whitespace. - my $text = shift; - $text = $self->parse ($text, @_); - $text =~ s/\n\s*$/\n/; +# Handle a basic block of text. The only tricky part of this is if this is +# the first paragraph of text after an =over, in which case we have to change +# indentations for *roff. +sub cmd_para { + my ($self, $attrs, $text) = @_; + my $line = $$attrs{start_line}; # Output the paragraph. We also have to handle =over without =item. If # there's an =over without =item, SHIFTWAIT will be set, and we need to @@ -547,199 +900,225 @@ sub textblock { push (@{ $$self{SHIFTS} }, $$self{INDENT}); $$self{SHIFTWAIT} = 0; } - $self->output (protect $self->textmapfonts ($text)); - $self->outindex; - $$self{NEEDSPACE} = 1; -} - -# Called for a formatting code. Takes a Pod::InteriorSequence object and -# returns a reference to a scalar. This scalar is the final formatted text. -# It's returned as a reference to an array so that other formatting codes -# above us know that the text has already been processed. -sub sequence { - my ($self, $seq) = @_; - my $command = $seq->cmd_name; - - # We have to defer processing of the inside of an L<> formatting code. If - # this code is nested inside an L<> code, return the literal raw text of - # it. - my $parent = $seq->nested; - while (defined $parent) { - return $seq->raw_text if ($parent->cmd_name eq 'L'); - $parent = $parent->nested; - } - - # Zero-width characters. - return [ '\&' ] if ($command eq 'Z'); - - # C<>, L<>, X<>, and E<> don't apply guesswork to their contents. C<> - # needs some additional special handling. - my $literal = ($command =~ /^[CELX]$/); - local $_ = $self->collapse ($seq->parse_tree, $literal, $command eq 'C'); - - # Handle E<> escapes. Numeric escapes that match one of the supported ISO - # 8859-1 characters don't work at present. - if ($command eq 'E') { - if (/^\d+$/) { - return [ chr ($_) ]; - } elsif (exists $ESCAPES{$_}) { - return [ $ESCAPES{$_} ]; - } else { - my ($file, $line) = $seq->file_line; - warn "$file:$line: Unknown escape E<$_>\n"; - return [ "E<$_>" ]; - } - } - # For all the other codes, empty content produces no output. - return '' if $_ eq ''; + # Add the line number for debugging, but not in the NAME section just in + # case the comment would confuse apropos. + $self->output (".\\\" [At source line $line]\n") + if defined ($line) && DEBUG && !$$self{IN_NAME}; - # Handle simple formatting codes. - if ($command eq 'B') { - return [ '\f(BS' . $_ . '\f(BE' ]; - } elsif ($command eq 'F' || $command eq 'I') { - return [ '\f(IS' . $_ . '\f(IE' ]; - } elsif ($command eq 'C') { - return [ $self->quote_literal ($_) ]; - } + # Force exactly one newline at the end and strip unwanted trailing + # whitespace at the end. + $text =~ s/\s*$/\n/; - # Handle links. - if ($command eq 'L') { - my ($text, $type) = (parselink ($_))[1,4]; - return '' unless $text; - my ($file, $line) = $seq->file_line; - $text = $self->parse ($text, $line); - $text = '<' . $text . '>' if $type eq 'url'; - return [ $text ]; - } + # Output the paragraph. + $self->output ($self->protect ($self->textmapfonts ($text))); + $self->outindex; + $$self{NEEDSPACE} = 1; + return ''; +} - # Whitespace protection replaces whitespace with "\ ". - if ($command eq 'S') { - s/\s+/\\ /g; - return [ $_ ]; +# Handle a verbatim paragraph. Put a null token at the beginning of each line +# to protect against commands and wrap in .Vb/.Ve (which we define in our +# prelude). +sub cmd_verbatim { + my ($self, $attrs, $text) = @_; + + # Ignore an empty verbatim paragraph. + return unless $text =~ /\S/; + + # Force exactly one newline at the end and strip unwanted trailing + # whitespace at the end. + $text =~ s/\s*$/\n/; + + # Get a count of the number of lines before the first blank line, which + # we'll pass to .Vb as its parameter. This tells *roff to keep that many + # lines together. We don't want to tell *roff to keep huge blocks + # together. + my @lines = split (/\n/, $text); + my $unbroken = 0; + for (@lines) { + last if /^\s*$/; + $unbroken++; } + $unbroken = 10 if ($unbroken > 12 && !$$self{MAGIC_VNOPAGEBREAK_LIMIT}); - # Add an index entry to the list of ones waiting to be output. - if ($command eq 'X') { - push (@{ $$self{INDEX} }, $_); - return ''; - } + # Prepend a null token to each line. + $text =~ s/^/\\&/gm; - # Anything else is unknown. - my ($file, $line) = $seq->file_line; - warn "$file:$line: Unknown formatting code $command<$_>\n"; + # Output the results. + $self->makespace; + $self->output (".Vb $unbroken\n$text.Ve\n"); + $$self{NEEDSPACE} = 1; + return ''; } +# Handle literal text (produced by =for and similar constructs). Just output +# it with the minimum of changes. +sub cmd_data { + my ($self, $attrs, $text) = @_; + $text =~ s/^\n+//; + $text =~ s/\n{0,2}$/\n/; + $self->output ($text); + return ''; +} ############################################################################## -# Command paragraphs +# Headings ############################################################################## -# All command paragraphs take the paragraph and the line number. +# Common code for all headings. This is called before the actual heading is +# output. It returns the cleaned up heading text (putting the heading all on +# one line) and may do other things, like closing bad =item blocks. +sub heading_common { + my ($self, $text, $line) = @_; + $text =~ s/\s+$//; + $text =~ s/\s*\n\s*/ /g; -# First level heading. We can't output .IX in the NAME section due to a bug -# in some versions of catman, so don't output a .IX for that section. .SH -# already uses small caps, so remove \s1 and \s-1. Maintain IN_NAME as -# appropriate, but don't leave it set while calling parse() so as to not -# override guesswork on section headings after NAME. -sub cmd_head1 { - my $self = shift; - $$self{IN_NAME} = 0; - local $_ = $self->parse (@_); - s/\s+$//; - s/\\s-?\d//g; - s/\s*\n\s*/ /g; + # This should never happen; it means that we have a heading after =item + # without an intervening =back. But just in case, handle it anyway. if ($$self{ITEMS} > 1) { $$self{ITEMS} = 0; $self->output (".PD\n"); } - $self->output ($self->switchquotes ('.SH', $self->mapfonts ($_))); - $self->outindex (($_ eq 'NAME') ? () : ('Header', $_)); + + # Output the current source line. + $self->output ( ".\\\" [At source line $line]\n" ) + if defined ($line) && DEBUG; + return $text; +} + +# First level heading. We can't output .IX in the NAME section due to a bug +# in some versions of catman, so don't output a .IX for that section. .SH +# already uses small caps, so remove \s0 and \s-1. Maintain IN_NAME as +# appropriate. +sub cmd_head1 { + my ($self, $attrs, $text) = @_; + $text =~ s/\\s-?\d//g; + $text = $self->heading_common ($text, $$attrs{start_line}); + my $isname = ($text eq 'NAME' || $text =~ /\(NAME\)/); + $self->output ($self->switchquotes ('.SH', $self->mapfonts ($text))); + $self->outindex ('Header', $text) unless $isname; $$self{NEEDSPACE} = 0; - $$self{IN_NAME} = ($_ eq 'NAME'); + $$self{IN_NAME} = $isname; + return ''; } # Second level heading. sub cmd_head2 { - my $self = shift; - local $_ = $self->parse (@_); - s/\s+$//; - s/\s*\n\s*/ /g; - if ($$self{ITEMS} > 1) { - $$self{ITEMS} = 0; - $self->output (".PD\n"); - } - $self->output ($self->switchquotes ('.Sh', $self->mapfonts ($_))); - $self->outindex ('Subsection', $_); + my ($self, $attrs, $text) = @_; + $text = $self->heading_common ($text, $$attrs{start_line}); + $self->output ($self->switchquotes ('.Sh', $self->mapfonts ($text))); + $self->outindex ('Subsection', $text); $$self{NEEDSPACE} = 0; + return ''; } -# Third level heading. +# Third level heading. *roff doesn't have this concept, so just put the +# heading in italics as a normal paragraph. sub cmd_head3 { - my $self = shift; - local $_ = $self->parse (@_); - s/\s+$//; - s/\s*\n\s*/ /g; - if ($$self{ITEMS} > 1) { - $$self{ITEMS} = 0; - $self->output (".PD\n"); - } + my ($self, $attrs, $text) = @_; + $text = $self->heading_common ($text, $$attrs{start_line}); $self->makespace; - $self->output ($self->textmapfonts ('\f(IS' . $_ . '\f(IE') . "\n"); - $self->outindex ('Subsection', $_); + $self->output ($self->textmapfonts ('\f(IS' . $text . '\f(IE') . "\n"); + $self->outindex ('Subsection', $text); $$self{NEEDSPACE} = 1; + return ''; } -# Fourth level heading. +# Fourth level heading. *roff doesn't have this concept, so just put the +# heading as a normal paragraph. sub cmd_head4 { - my $self = shift; - local $_ = $self->parse (@_); - s/\s+$//; - s/\s*\n\s*/ /g; - if ($$self{ITEMS} > 1) { - $$self{ITEMS} = 0; - $self->output (".PD\n"); - } + my ($self, $attrs, $text) = @_; + $text = $self->heading_common ($text, $$attrs{start_line}); $self->makespace; - $self->output ($self->textmapfonts ($_) . "\n"); - $self->outindex ('Subsection', $_); + $self->output ($self->textmapfonts ($text) . "\n"); + $self->outindex ('Subsection', $text); $$self{NEEDSPACE} = 1; + return ''; } -# Start a list. For indents after the first, wrap the outside indent in .RS -# so that hanging paragraph tags will be correct. -sub cmd_over { - my $self = shift; - local $_ = shift; - unless (/^[-+]?\d+\s+$/) { $_ = $$self{indent} } +############################################################################## +# Formatting codes +############################################################################## + +# All of the formatting codes that aren't handled internally by the parser, +# other than L<> and X<>. +sub cmd_b { return '\f(BS' . $_[2] . '\f(BE' } +sub cmd_i { return '\f(IS' . $_[2] . '\f(IE' } +sub cmd_f { return '\f(IS' . $_[2] . '\f(IE' } +sub cmd_c { return $_[0]->quote_literal ($_[2]) } + +# Index entries are just added to the pending entries. +sub cmd_x { + my ($self, $attrs, $text) = @_; + push (@{ $$self{INDEX} }, $text); + return ''; +} + +# Links reduce to the text that we're given, wrapped in angle brackets if it's +# a URL. +sub cmd_l { + my ($self, $attrs, $text) = @_; + return $$attrs{type} eq 'url' ? "<$text>" : $text; +} + +############################################################################## +# List handling +############################################################################## + +# Handle the beginning of an =over block. Takes the type of the block as the +# first argument, and then the attr hash. This is called by the handlers for +# the four different types of lists (bullet, number, text, and block). +sub over_common_start { + my ($self, $type, $attrs) = @_; + my $line = $$attrs{start_line}; + my $indent = $$attrs{indent}; + DEBUG > 3 and print " Starting =over $type (line $line, indent ", + ($indent || '?'), "\n"; + + # Find the indentation level. + unless (defined ($indent) && $indent =~ /^[-+]?\d{1,4}\s*$/) { + $indent = $$self{indent}; + } + + # If we've gotten multiple indentations in a row, we need to emit the + # pending indentation for the last level that we saw and haven't acted on + # yet. SHIFTS is the stack of indentations that we've actually emitted + # code for. if (@{ $$self{SHIFTS} } < @{ $$self{INDENTS} }) { $self->output (".RS $$self{INDENT}\n"); push (@{ $$self{SHIFTS} }, $$self{INDENT}); } + + # Now, do record-keeping. INDENTS is a stack of indentations that we've + # seen so far, and INDENT is the current level of indentation. ITEMTYPES + # is a stack of list types that we've seen. push (@{ $$self{INDENTS} }, $$self{INDENT}); - push (@{ $$self{ITEMTYPES} }, 'unknown'); - $$self{INDENT} = ($_ + 0); + push (@{ $$self{ITEMTYPES} }, $type); + $$self{INDENT} = $indent + 0; $$self{SHIFTWAIT} = 1; } -# End a list. If we've closed an embedded indent, we've mangled the hanging -# paragraph indent, so temporarily replace it with .RS and set WEIRDINDENT. -# We'll close that .RS at the next =back or =item. -sub cmd_back { - my $self = shift; +# End an =over block. Takes no options other than the class pointer. +# Normally, once we close a block and therefore remove something from INDENTS, +# INDENTS will now be longer than SHIFTS, indicating that we also need to emit +# *roff code to close the indent. This isn't *always* true, depending on the +# circumstance. If we're still inside an indentation, we need to emit another +# .RE and then a new .RS to unconfuse *roff. +sub over_common_end { + my ($self) = @_; + DEBUG > 3 and print " Ending =over\n"; $$self{INDENT} = pop @{ $$self{INDENTS} }; - if (defined $$self{INDENT}) { - pop @{ $$self{ITEMTYPES} }; - } else { - my ($file, $line, $paragraph) = @_; - ($file, $line) = $paragraph->file_line; - warn "$file:$line: Unmatched =back\n"; - $$self{INDENT} = 0; - } + pop @{ $$self{ITEMTYPES} }; + + # If we emitted code for that indentation, end it. if (@{ $$self{SHIFTS} } > @{ $$self{INDENTS} }) { $self->output (".RE\n"); pop @{ $$self{SHIFTS} }; } + + # If we're still in an indentation, *roff will have now lost track of the + # right depth of that indentation, so fix that. if (@{ $$self{INDENTS} } > 0) { $self->output (".RE\n"); $self->output (".RS $$self{INDENT}\n"); @@ -748,391 +1127,250 @@ sub cmd_back { $$self{SHIFTWAIT} = 0; } -# An individual list item. Emit an index entry for anything that's -# interesting, but don't emit index entries for things like bullets and -# numbers. rofficate bullets too while we're at it (so for nice output, use * -# for your lists rather than o or . or - or some other thing). Newlines in an -# item title are turned into spaces since *roff can't handle them embedded. -sub cmd_item { - my $self = shift; - local $_ = $self->parse (@_); - s/\s+$//; - s/\s*\n\s*/ /g; - my $index; - if (/\w/ && !/^\w[.\)]\s*$/) { - $index = $_; - $index =~ s/^\s*[-*+o.]?(?:\s+|\Z)//; - } - $_ = '*' unless length ($_) > 0; - my $type = $$self{ITEMTYPES}[0]; - unless (defined $type) { - my ($file, $line, $paragraph) = @_; - ($file, $line) = $paragraph->file_line; - $type = 'unknown'; - } - if ($type eq 'unknown') { - $type = /^\*\s*\Z/ ? 'bullet' : 'text'; - $$self{ITEMTYPES}[0] = $type if $$self{ITEMTYPES}[0]; +# Dispatch the start and end calls as appropriate. +sub start_over_bullet { my $s = shift; $s->over_common_start ('bullet', @_) } +sub start_over_number { my $s = shift; $s->over_common_start ('number', @_) } +sub start_over_text { my $s = shift; $s->over_common_start ('text', @_) } +sub start_over_block { my $s = shift; $s->over_common_start ('block', @_) } +sub end_over_bullet { $_[0]->over_common_end } +sub end_over_number { $_[0]->over_common_end } +sub end_over_text { $_[0]->over_common_end } +sub end_over_block { $_[0]->over_common_end } + +# The common handler for all item commands. Takes the type of the item, the +# attributes, and then the text of the item. +# +# Emit an index entry for anything that's interesting, but don't emit index +# entries for things like bullets and numbers. Newlines in an item title are +# turned into spaces since *roff can't handle them embedded. +sub item_common { + my ($self, $type, $attrs, $text) = @_; + my $line = $$attrs{start_line}; + DEBUG > 3 and print " $type item (line $line): $text\n"; + + # Clean up the text. We want to end up with two variables, one ($text) + # which contains any body text after taking out the item portion, and + # another ($item) which contains the actual item text. + $text =~ s/\s+$//; + my ($item, $index); + if ($type eq 'bullet') { + $item = "\\\(bu"; + $text =~ s/\n*$/\n/; + } elsif ($type eq 'number') { + $item = $$attrs{number} . '.'; + } else { + $item = $text; + $item =~ s/\s*\n\s*/ /g; + $text = ''; + $index = $item if ($item =~ /\w/); } - s/^\*\s*\Z/\\\(bu/ if $type eq 'bullet'; + + # Take care of the indentation. If shifts and indents are equal, close + # the top shift, since we're about to create an indentation with .IP. + # Also output .PD 0 to turn off spacing between items if this item is + # directly following another one. We only have to do that once for a + # whole chain of items so do it for the second item in the change. Note + # that makespace is what undoes this. if (@{ $$self{SHIFTS} } == @{ $$self{INDENTS} }) { $self->output (".RE\n"); pop @{ $$self{SHIFTS} }; - } - $_ = $self->textmapfonts ($_); - $self->output (".PD 0\n") if ($$self{ITEMS} == 1); - $self->output ($self->switchquotes ('.IP', $_, $$self{INDENT})); - $self->outindex ($index ? ('Item', $index) : ()); - $$self{NEEDSPACE} = 0; - $$self{ITEMS}++; - $$self{SHIFTWAIT} = 0; -} - -# Begin a block for a particular translator. Setting VERBATIM triggers -# special handling in textblock(). -sub cmd_begin { - my $self = shift; - local $_ = shift; - my ($kind) = /^(\S+)/ or return; - if ($kind eq 'man' || $kind eq 'roff') { - $$self{VERBATIM} = 1; - } else { - $$self{EXCLUDE} = 1; - } -} - -# End a block for a particular translator. We assume that all =begin/=end -# pairs are properly closed. -sub cmd_end { - my $self = shift; - $$self{EXCLUDE} = 0; - $$self{VERBATIM} = 0; -} - -# One paragraph for a particular translator. Ignore it unless it's intended -# for man or roff, in which case we output it verbatim. -sub cmd_for { - my $self = shift; - local $_ = shift; - return unless s/^(?:man|roff)\b[ \t]*\n?//; - $self->output ($_); -} - - -############################################################################## -# Escaping and fontification -############################################################################## - -# At this point, we'll have embedded font codes of the form \f([SE] -# where is one of B, I, or F. Turn those into the right font start or -# end codes. The old pod2man didn't get B else> right; after I<> -# it switched back to normal text rather than bold. We take care of this by -# using variables as a combined pointer to our current font sequence, and set -# each to the number of current nestings of start tags for that font. Use -# them as a vector to look up what font sequence to use. -# -# \fP changes to the previous font, but only one previous font is kept. We -# don't know what the outside level font is; normally it's R, but if we're -# inside a heading it could be something else. So arrange things so that the -# outside font is always the "previous" font and end with \fP instead of \fR. -# Idea from Zack Weinberg. -sub mapfonts { - my $self = shift; - local $_ = shift; - - my ($fixed, $bold, $italic) = (0, 0, 0); - my %magic = (F => \$fixed, B => \$bold, I => \$italic); - my $last = '\fR'; - s { \\f\((.)(.) } { - my $sequence = ''; - my $f; - if ($last ne '\fR') { $sequence = '\fP' } - ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1; - $f = $$self{FONTS}{($fixed && 1) . ($bold && 1) . ($italic && 1)}; - if ($f eq $last) { - ''; - } else { - if ($f ne '\fR') { $sequence .= $f } - $last = $f; - $sequence; - } - }gxe; - $_; -} - -# Unfortunately, there is a bug in Solaris 2.6 nroff (not present in GNU -# groff) where the sequence \fB\fP\f(CW\fP leaves the font set to B rather -# than R, presumably because \f(CW doesn't actually do a font change. To work -# around this, use a separate textmapfonts for text blocks where the default -# font is always R and only use the smart mapfonts for headings. -sub textmapfonts { - my $self = shift; - local $_ = shift; - - my ($fixed, $bold, $italic) = (0, 0, 0); - my %magic = (F => \$fixed, B => \$bold, I => \$italic); - s { \\f\((.)(.) } { - ${ $magic{$1} } += ($2 eq 'S') ? 1 : -1; - $$self{FONTS}{($fixed && 1) . ($bold && 1) . ($italic && 1)}; - }gxe; - $_; -} - - -############################################################################## -# *roff-specific parsing and magic -############################################################################## - -# Called instead of parse_text, calls parse_text with the right flags. -sub parse { - my $self = shift; - $self->parse_text ({ -expand_seq => 'sequence', - -expand_ptree => 'collapse' }, @_); -} - -# Takes a parse tree, a flag saying whether or not to treat it as literal text -# (not call guesswork on it), and a flag saying whether or not to clean some -# things up for *roff, and returns the concatenation of all of the text -# strings in that parse tree. If the literal flag isn't true, guesswork() -# will be called on all plain scalars in the parse tree. Otherwise, if -# collapse is being called on a C<> code, $cleanup should be set to true and -# some additional cleanup will be done. Assumes that everything in the parse -# tree is either a scalar or a reference to a scalar. -sub collapse { - my ($self, $ptree, $literal, $cleanup) = @_; - - # If we're processing the NAME section, don't do normal guesswork. This - # is because NAME lines are often extracted by utilities like catman that - # require plain text and don't understand *roff markup. We still need to - # escape backslashes and hyphens for *roff (and catman expects \- instead - # of -). - if ($$self{IN_NAME}) { - $literal = 1; - $cleanup = 1; - } - - # Do the collapse of the parse tree as described above. - return join ('', map { - if (ref $_) { - join ('', @$_); - } elsif ($literal) { - if ($cleanup) { - s/\\/\\e/g; - s/-/\\-/g; - s/__/_\\|_/g; - } - $_; - } else { - $self->guesswork ($_); - } - } $ptree->children); -} - -# Takes a text block to perform guesswork on; this is guaranteed not to -# contain any formatting codes. Returns the text block with remapping done. -sub guesswork { - my $self = shift; - local $_ = shift; - - # rofficate backslashes. - s/\\/\\e/g; - - # Ensure double underbars have a tiny space between them. - s/__/_\\|_/g; - - # Leave hyphens only if they're part of regular words and there is only - # one dash at a time. Leave a dash after the first character as a regular - # non-breaking dash, but don't let it mark the rest of the word invalid - # for hyphenation. - s/-/\\-/g; - s{ - ( (?:\G|^|\s) [a-zA-Z] ) ( \\- )? - ( (?: [a-zA-Z]+ \\-)+ ) - ( [a-zA-Z]+ ) (?=\s|\Z) - \b - } { - my ($prefix, $hyphen, $main, $suffix) = ($1, $2, $3, $4); - $hyphen ||= ''; - $main =~ s/\\-/-/g; - $prefix . $hyphen . $main . $suffix; - }egx; - - # Translate -- into a real em dash if it's used like one. - s{ (\s) \\-\\- (\s) } { $1 . '\*(--' . $2 }egx; - s{ (\b[a-zA-Z]+) \\-\\- (\s|\Z|[a-zA-Z]+\b) } { $1 . '\*(--' . $2 }egx; - - # Make all caps a little smaller. Be careful here, since we don't want to - # make @ARGV into small caps, nor do we want to fix the MIME in - # MIME-Version, since it looks weird with the full-height V. - s{ - ( ^ | [\s\(\"\'\`\[\{<>] ) - ( [A-Z] [A-Z] (?: [/A-Z+:\d_\$&] | \\- )* ) - (?= [\s>\}\]\(\)\'\".?!,;] | \\*\(-- | $ ) - } { $1 . '\s-1' . $2 . '\s0' }egx; - - # Italize functions in the form func(). - s{ - ( \b | \\s-1 ) - ( - [A-Za-z_] ([:\w]|\\s-?[01])+ \(\) - ) - } { $1 . '\f(IS' . $2 . '\f(IE' }egx; - - # func(n) is a reference to a manual page. Make it \fIfunc\fR\|(n). - s{ - ( \b | \\s-1 ) - ( [A-Za-z_] (?:[.:\w]|\\-|\\s-?[01])+ ) - ( - \( \d [a-z]* \) - ) - } { $1 . '\f(IS' . $2 . '\f(IE\|' . $3 }egx; - - # Convert simple Perl variable references to a fixed-width font. - s{ - ( \s+ ) - ( [\$\@%] [\w:]+ ) - (?! \( ) - } { $1 . '\f(FS' . $2 . '\f(FE'}egx; - - # Fix up double quotes. - s{ \" ([^\"]+) \" } { '\*(L"' . $1 . '\*(R"' }egx; - - # Make C++ into \*(C+, which is a squinched version. - s{ \b C\+\+ } {\\*\(C+}gx; - - # All done. - $_; -} - -# Handles C<> text, deciding whether to put \*C` around it or not. This is a -# whole bunch of messy heuristics to try to avoid overquoting, originally from -# Barrie Slaymaker. This largely duplicates similar code in Pod::Text. -sub quote_literal { - my $self = shift; - local $_ = shift; - - # A regex that matches the portion of a variable reference that's the - # array or hash index, separated out just because we want to use it in - # several places in the following regex. - my $index = '(?: \[.*\] | \{.*\} )?'; + } + $self->output (".PD 0\n") if ($$self{ITEMS} == 1); - # Check for things that we don't want to quote, and if we find any of - # them, return the string with just a font change and no quoting. - m{ - ^\s* - (?: - ( [\'\`\"] ) .* \1 # already quoted - | \` .* \' # `quoted' - | \$+ [\#^]? \S $index # special ($^Foo, $") - | [\$\@%&*]+ \#? [:\'\w]+ $index # plain var or func - | [\$\@%&*]* [:\'\w]+ (?: -> )? \(\s*[^\s,]\s*\) # 0/1-arg func call - | [+-]? ( \d[\d.]* | \.\d+ ) (?: [eE][+-]?\d+ )? # a number - | 0x [a-fA-F\d]+ # a hex constant - ) - \s*\z - }xo && return '\f(FS' . $_ . '\f(FE'; + # Now, output the item tag itself. + $item = $self->textmapfonts ($item); + $self->output ($self->switchquotes ('.IP', $item, $$self{INDENT})); + $$self{NEEDSPACE} = 0; + $$self{ITEMS}++; + $$self{SHIFTWAIT} = 0; - # If we didn't return, go ahead and quote the text. - return '\f(FS\*(C`' . $_ . "\\*(C'\\f(FE"; + # If body text for this item was included, go ahead and output that now. + if ($text) { + $text =~ s/\s*$/\n/; + $self->makespace; + $self->output ($self->protect ($self->textmapfonts ($text))); + $$self{NEEDSPACE} = 1; + } + $self->outindex ($index ? ('Item', $index) : ()); } +# Dispatch the item commands to the appropriate place. +sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) } +sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) } +sub cmd_item_text { my $self = shift; $self->item_common ('text', @_) } +sub cmd_item_block { my $self = shift; $self->item_common ('block', @_) } ############################################################################## -# Output formatting +# Translation tables ############################################################################## -# Make vertical whitespace. -sub makespace { - my $self = shift; - $self->output (".PD\n") if ($$self{ITEMS} > 1); - $$self{ITEMS} = 0; - $self->output ($$self{INDENT} > 0 ? ".Sp\n" : ".PP\n") - if $$self{NEEDSPACE}; -} +# The following table is adapted from Tom Christiansen's pod2man. It assumes +# that the standard preamble has already been printed, since that's what +# defines all of the accent marks. We really want to do something better than +# this when *roff actually supports other character sets itself, since these +# results are pretty poor. +# +# This only works in an ASCII world. What to do in a non-ASCII world is very +# unclear. +@ESCAPES{0xA0 .. 0xFF} = ( + "\\ ", undef, undef, undef, undef, undef, undef, undef, + undef, undef, undef, undef, undef, "\\%", undef, undef, -# Output any pending index entries, and optionally an index entry given as an -# argument. Support multiple index entries in X<> separated by slashes, and -# strip special escapes from index entries. -sub outindex { - my ($self, $section, $index) = @_; - my @entries = map { split m%\s*/\s*% } @{ $$self{INDEX} }; - return unless ($section || @entries); - $$self{INDEX} = []; - my @output; - if (@entries) { - push (@output, [ 'Xref', join (' ', @entries) ]); - } - if ($section) { - $index =~ s/\\-/-/g; - $index =~ s/\\(?:s-?\d|.\(..|.)//g; - push (@output, [ $section, $index ]); - } - for (@output) { - my ($type, $entry) = @$_; - $entry =~ s/\"/\"\"/g; - $self->output (".IX $type " . '"' . $entry . '"' . "\n"); - } -} + undef, undef, undef, undef, undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, undef, undef, -# Output text to the output device. -sub output { print { $_[0]->output_handle } $_[1] } + "A\\*`", "A\\*'", "A\\*^", "A\\*~", "A\\*:", "A\\*o", "\\*(AE", "C\\*,", + "E\\*`", "E\\*'", "E\\*^", "E\\*:", "I\\*`", "I\\*'", "I\\*^", "I\\*:", -# Given a command and a single argument that may or may not contain double -# quotes, handle double-quote formatting for it. If there are no double -# quotes, just return the command followed by the argument in double quotes. -# If there are double quotes, use an if statement to test for nroff, and for -# nroff output the command followed by the argument in double quotes with -# embedded double quotes doubled. For other formatters, remap paired double -# quotes to LQUOTE and RQUOTE. -sub switchquotes { - my $self = shift; - my $command = shift; - local $_ = shift; - my $extra = shift; - s/\\\*\([LR]\"/\"/g; + "\\*(D-", "N\\*~", "O\\*`", "O\\*'", "O\\*^", "O\\*~", "O\\*:", undef, + "O\\*/", "U\\*`", "U\\*'", "U\\*^", "U\\*:", "Y\\*'", "\\*(Th", "\\*8", - # We also have to deal with \*C` and \*C', which are used to add the - # quotes around C<> text, since they may expand to " and if they do this - # confuses the .SH macros and the like no end. Expand them ourselves. - # Also separate troff from nroff if there are any fixed-width fonts in use - # to work around problems with Solaris nroff. - my $c_is_quote = ($$self{LQUOTE} =~ /\"/) || ($$self{RQUOTE} =~ /\"/); - my $fixedpat = join ('|', @{ $$self{FONTS} }{'100', '101', '110', '111'}); - $fixedpat =~ s/\\/\\\\/g; - $fixedpat =~ s/\(/\\\(/g; - if (/\"/ || /$fixedpat/) { - s/\"/\"\"/g; - my $nroff = $_; - my $troff = $_; - $troff =~ s/\"\"([^\"]*)\"\"/\`\`$1\'\'/g; - if ($c_is_quote && /\\\*\(C[\'\`]/) { - $nroff =~ s/\\\*\(C\`/$$self{LQUOTE}/g; - $nroff =~ s/\\\*\(C\'/$$self{RQUOTE}/g; - $troff =~ s/\\\*\(C[\'\`]//g; - } - $nroff = qq("$nroff") . ($extra ? " $extra" : ''); - $troff = qq("$troff") . ($extra ? " $extra" : ''); + "a\\*`", "a\\*'", "a\\*^", "a\\*~", "a\\*:", "a\\*o", "\\*(ae", "c\\*,", + "e\\*`", "e\\*'", "e\\*^", "e\\*:", "i\\*`", "i\\*'", "i\\*^", "i\\*:", - # Work around the Solaris nroff bug where \f(CW\fP leaves the font set - # to Roman rather than the actual previous font when used in headings. - # troff output may still be broken, but at least we can fix nroff by - # just switching the font changes to the non-fixed versions. - $nroff =~ s/\Q$$self{FONTS}{100}\E(.*)\\f[PR]/$1/g; - $nroff =~ s/\Q$$self{FONTS}{101}\E(.*)\\f([PR])/\\fI$1\\f$2/g; - $nroff =~ s/\Q$$self{FONTS}{110}\E(.*)\\f([PR])/\\fB$1\\f$2/g; - $nroff =~ s/\Q$$self{FONTS}{111}\E(.*)\\f([PR])/\\f\(BI$1\\f$2/g; + "\\*(d-", "n\\*~", "o\\*`", "o\\*'", "o\\*^", "o\\*~", "o\\*:", undef, + "o\\*/" , "u\\*`", "u\\*'", "u\\*^", "u\\*:", "y\\*'", "\\*(th", "y\\*:", +) if ASCII; - # Now finally output the command. Only bother with .ie if the nroff - # and troff output isn't the same. - if ($nroff ne $troff) { - return ".ie n $command $nroff\n.el $command $troff\n"; - } else { - return "$command $nroff\n"; - } - } else { - $_ = qq("$_") . ($extra ? " $extra" : ''); - return "$command $_\n"; - } +# Make sure that at least this works even outside of ASCII. +$ESCAPES{ord("\\")} = "\\e"; + +############################################################################## +# Premable +############################################################################## + +# The following is the static preamble which starts all *roff output we +# generate. It's completely static except for the font to use as a +# fixed-width font, which is designed by @CFONT@, and the left and right +# quotes to use for C<> text, designated by @LQOUTE@ and @RQUOTE@. +sub preamble_template { + return <<'----END OF PREAMBLE----'; +.de Sh \" Subsection heading +.br +.if t .Sp +.ne 5 +.PP +\fB\\$1\fR +.PP +.. +.de Sp \" Vertical space (when we can't use .PP) +.if t .sp .5v +.if n .sp +.. +.de Vb \" Begin verbatim text +.ft @CFONT@ +.nf +.ne \\$1 +.. +.de Ve \" End verbatim text +.ft R +.fi +.. +.\" Set up some character translations and predefined strings. \*(-- will +.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left +.\" double quote, and \*(R" will give a right double quote. | will give a +.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to +.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' +.\" expand to `' in nroff, nothing in troff, for use with C<>. +.tr \(*W-|\(bv\*(Tr +.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' +.ie n \{\ +. ds -- \(*W- +. ds PI pi +. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch +. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch +. ds L" "" +. ds R" "" +. ds C` @LQUOTE@ +. ds C' @RQUOTE@ +'br\} +.el\{\ +. ds -- \|\(em\| +. ds PI \(*p +. ds L" `` +. ds R" '' +'br\} +.\" +.\" If the F register is turned on, we'll generate index entries on stderr for +.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index +.\" entries marked with X<> in POD. Of course, you'll have to process the +.\" output yourself in some meaningful fashion. +.if \nF \{\ +. de IX +. tm Index:\\$1\t\\n%\t"\\$2" +.. +. nr % 0 +. rr F +.\} +.\" +.\" For nroff, turn off justification. Always turn off hyphenation; it makes +.\" way too many mistakes in technical documents. +.hy 0 +.if n .na +.\" +.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). +.\" Fear. Run. Save yourself. No user-serviceable parts. +. \" fudge factors for nroff and troff +.if n \{\ +. ds #H 0 +. ds #V .8m +. ds #F .3m +. ds #[ \f1 +. ds #] \fP +.\} +.if t \{\ +. ds #H ((1u-(\\\\n(.fu%2u))*.13m) +. ds #V .6m +. ds #F 0 +. ds #[ \& +. ds #] \& +.\} +. \" simple accents for nroff and troff +.if n \{\ +. ds ' \& +. ds ` \& +. ds ^ \& +. ds , \& +. ds ~ ~ +. ds / +.\} +.if t \{\ +. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" +. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' +. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' +. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' +. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' +. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' +.\} +. \" troff and (daisy-wheel) nroff accents +.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' +.ds 8 \h'\*(#H'\(*b\h'-\*(#H' +.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] +.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' +.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' +.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] +.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] +.ds ae a\h'-(\w'a'u*4/10)'e +.ds Ae A\h'-(\w'A'u*4/10)'E +. \" corrections for vroff +.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' +.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' +. \" for low resolution devices (crt and lpr) +.if \n(.H>23 .if \n(.V>19 \ +\{\ +. ds : e +. ds 8 ss +. ds o a +. ds d- d\h'-1'\(ga +. ds D- D\h'-1'\(hy +. ds th \o'bp' +. ds Th \o'LP' +. ds ae ae +. ds Ae AE +.\} +.rm #[ #] #H #V #F C +----END OF PREAMBLE---- +#`# for cperl-mode } ############################################################################## @@ -1152,7 +1390,7 @@ Pod::Man - Convert POD data to formatted *roff input my $parser = Pod::Man->new (release => $VERSION, section => 8); # Read POD from STDIN and write to STDOUT. - $parser->parse_from_filehandle; + $parser->parse_file (\*STDIN); # Read POD from file.pod and write to file.1. $parser->parse_from_file ('file.pod', 'file.1'); @@ -1166,10 +1404,8 @@ using L, normally via L, or printing using L. It is conventionally invoked using the driver script B, but it can also be used directly. -As a derived class from Pod::Parser, Pod::Man supports the same methods and -interfaces. See L for all the details; briefly, one creates a -new parser with C<< Pod::Man->new() >> and then calls either -parse_from_filehandle() or parse_from_file(). +As a derived class from Pod::Simple, Pod::Man supports the same methods and +interfaces. See L for all the details. new() can take options, in the form of key/value pairs that control the behavior of the parser. See below for details. @@ -1283,13 +1519,18 @@ section 3 will be selected. =back -The standard Pod::Parser method parse_from_filehandle() takes up to two -arguments, the first being the file handle to read POD from and the second -being the file handle to write the formatted output to. The first defaults -to STDIN if not given, and the second defaults to STDOUT. The method -parse_from_file() is almost identical, except that its two arguments are the -input and output disk files instead. See L for the specific -details. +The standard Pod::Simple method parse_file() takes one argument naming the +POD file to read from. By default, the output is sent to STDOUT, but this +can be changed with the output_fd() method. + +The standard Pod::Simple method parse_from_file() takes up to two +arguments, the first being the input file to read POD from and the second +being the file to write the formatted output to. + +You can also call parse_lines() to parse an array of lines or +parse_string_document() to parse a document already in memory. To put the +output into a string instead of a file handle, call the output_string() +method. See L for the specific details. =head1 DIAGNOSTICS @@ -1302,37 +1543,11 @@ wasn't either one or two characters. Pod::Man doesn't support *roff fonts longer than two characters, although some *roff extensions do (the canonical versions of B and B don't either). -=item Invalid link %s - -(W) The POD source contained a CE> formatting code that -Pod::Man was unable to parse. You should never see this error message; it -probably indicates a bug in Pod::Man. - =item Invalid quote specification "%s" (F) The quote specification given (the quotes option to the constructor) was invalid. A quote specification must be one, two, or four characters long. -=item %s:%d: Unknown command paragraph "%s". - -(W) The POD source contained a non-standard command paragraph (something of -the form C<=command args>) that Pod::Man didn't know about. It was ignored. - -=item %s:%d: Unknown escape EE%sE - -(W) The POD source contained an CE> escape that Pod::Man didn't -know about. C%sE> was printed verbatim in the output. - -=item %s:%d: Unknown formatting code %s - -(W) The POD source contained a non-standard formatting code (something of -the form CE>) that Pod::Man didn't know about. It was ignored. - -=item %s:%d: Unmatched =back - -(W) Pod::Man encountered a C<=back> command that didn't correspond to an -C<=over> command. - =back =head1 BUGS @@ -1348,21 +1563,24 @@ characters that only work under troff. There is currently no way to turn off the guesswork that tries to format unmarked text appropriately, and sometimes it isn't wanted (particularly -when using POD to document something other than Perl). +when using POD to document something other than Perl). Most of the work +towards fixing this has now been done, however, and all that's still needed +is a user interface. The NAME section should be recognized specially and index entries emitted for everything in that section. This would have to be deferred until the next section, since extraneous things in NAME tends to confuse various man -page processors. +page processors. Currently, no index entries are emitted for anything in +NAME. Pod::Man doesn't handle font names longer than two characters. Neither do most B implementations, but GNU troff does as an extension. It would be nice to support as an option for those who want to use it. -The preamble added to each output file is rather verbose, and most of it is -only necessary in the presence of EEE escapes for non-ASCII -characters. It would ideally be nice if all of those definitions were only -output if needed, perhaps on the fly as the characters are used. +The preamble added to each output file is rather verbose, and most of it +is only necessary in the presence of non-ASCII characters. It would +ideally be nice if all of those definitions were only output if needed, +perhaps on the fly as the characters are used. Pod::Man is excessively slow. @@ -1375,9 +1593,29 @@ B output. When and whether to use small caps is somewhat tricky, and Pod::Man doesn't necessarily get it right. +Converting neutral double quotes to properly matched double quotes doesn't +work unless there are no formatting codes between the quote marks. This +only matters for troff output. + +=head1 AUTHOR + +Russ Allbery , based I heavily on the original +B by Tom Christiansen . The modifications to +work with Pod::Simple instead of Pod::Parser were originally contributed by +Sean Burke (but I've since hacked them beyond recognition and all bugs are +mine). + +=head1 COPYRIGHT AND LICENSE + +Copyright 1999, 2000, 2001, 2002, 2003, 2004, 2005 +by Russ Allbery . + +This program is free software; you may redistribute it and/or modify it +under the same terms as Perl itself. + =head1 SEE ALSO -L, L, L, L, L, +L, L, L, L, L, L, L Ossanna, Joseph F., and Brian W. Kernighan. "Troff User's Manual," @@ -1395,16 +1633,4 @@ The current version of this module is always available from its web site at L. It is also part of the Perl core distribution as of 5.6.0. -=head1 AUTHOR - -Russ Allbery , based I heavily on the original -B by Tom Christiansen . - -=head1 COPYRIGHT AND LICENSE - -Copyright 1999, 2000, 2001, 2002, 2003 by Russ Allbery . - -This program is free software; you may redistribute it and/or modify it -under the same terms as Perl itself. - =cut diff --git a/lib/Pod/Text.pm b/lib/Pod/Text.pm index 1028f2e..70db15f 100644 --- a/lib/Pod/Text.pm +++ b/lib/Pod/Text.pm @@ -1,7 +1,7 @@ # Pod::Text -- Convert POD data to formatted ASCII text. -# $Id: Text.pm,v 2.21 2002/08/04 03:34:58 eagle Exp $ +# $Id: Text.pm,v 3.1 2005/03/19 19:40:01 eagle Exp $ # -# Copyright 1999, 2000, 2001, 2002 by Russ Allbery +# Copyright 1999, 2000, 2001, 2002, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -25,17 +25,14 @@ package Pod::Text; require 5.004; -use Carp qw(carp croak); -use Exporter (); -use Pod::ParseLink qw(parselink); -use Pod::Select (); - use strict; use vars qw(@ISA @EXPORT %ESCAPES $VERSION); -# We inherit from Pod::Select instead of Pod::Parser so that we can be used by -# Pod::Usage. -@ISA = qw(Pod::Select Exporter); +use Carp qw(carp croak); +use Exporter (); +use Pod::Simple (); + +@ISA = qw(Pod::Simple Exporter); # We have to export pod2text for backward compatibility. @EXPORT = qw(pod2text); @@ -43,410 +40,467 @@ use vars qw(@ISA @EXPORT %ESCAPES $VERSION); # Don't use the CVS revision as the version, since this module is also in Perl # core and too many things could munge CVS magic revision strings. This # number should ideally be the same as the CVS revision in podlators, however. -$VERSION = 2.21; - - -############################################################################## -# Table of supported E<> escapes -############################################################################## - -# This table is taken near verbatim from Pod::PlainText in Pod::Parser, which -# got it near verbatim from the original Pod::Text. It is therefore credited -# to Tom Christiansen, and I'm glad I didn't have to write it. :) "iexcl" to -# "divide" added by Tim Jenness. -%ESCAPES = ( - 'amp' => '&', # ampersand - 'apos' => "'", # apostrophe - 'lt' => '<', # left chevron, less-than - 'gt' => '>', # right chevron, greater-than - 'quot' => '"', # double quote - 'sol' => '/', # solidus (forward slash) - 'verbar' => '|', # vertical bar - - "Aacute" => "\xC1", # capital A, acute accent - "aacute" => "\xE1", # small a, acute accent - "Acirc" => "\xC2", # capital A, circumflex accent - "acirc" => "\xE2", # small a, circumflex accent - "AElig" => "\xC6", # capital AE diphthong (ligature) - "aelig" => "\xE6", # small ae diphthong (ligature) - "Agrave" => "\xC0", # capital A, grave accent - "agrave" => "\xE0", # small a, grave accent - "Aring" => "\xC5", # capital A, ring - "aring" => "\xE5", # small a, ring - "Atilde" => "\xC3", # capital A, tilde - "atilde" => "\xE3", # small a, tilde - "Auml" => "\xC4", # capital A, dieresis or umlaut mark - "auml" => "\xE4", # small a, dieresis or umlaut mark - "Ccedil" => "\xC7", # capital C, cedilla - "ccedil" => "\xE7", # small c, cedilla - "Eacute" => "\xC9", # capital E, acute accent - "eacute" => "\xE9", # small e, acute accent - "Ecirc" => "\xCA", # capital E, circumflex accent - "ecirc" => "\xEA", # small e, circumflex accent - "Egrave" => "\xC8", # capital E, grave accent - "egrave" => "\xE8", # small e, grave accent - "ETH" => "\xD0", # capital Eth, Icelandic - "eth" => "\xF0", # small eth, Icelandic - "Euml" => "\xCB", # capital E, dieresis or umlaut mark - "euml" => "\xEB", # small e, dieresis or umlaut mark - "Iacute" => "\xCD", # capital I, acute accent - "iacute" => "\xED", # small i, acute accent - "Icirc" => "\xCE", # capital I, circumflex accent - "icirc" => "\xEE", # small i, circumflex accent - "Igrave" => "\xCC", # capital I, grave accent - "igrave" => "\xEC", # small i, grave accent - "Iuml" => "\xCF", # capital I, dieresis or umlaut mark - "iuml" => "\xEF", # small i, dieresis or umlaut mark - "Ntilde" => "\xD1", # capital N, tilde - "ntilde" => "\xF1", # small n, tilde - "Oacute" => "\xD3", # capital O, acute accent - "oacute" => "\xF3", # small o, acute accent - "Ocirc" => "\xD4", # capital O, circumflex accent - "ocirc" => "\xF4", # small o, circumflex accent - "Ograve" => "\xD2", # capital O, grave accent - "ograve" => "\xF2", # small o, grave accent - "Oslash" => "\xD8", # capital O, slash - "oslash" => "\xF8", # small o, slash - "Otilde" => "\xD5", # capital O, tilde - "otilde" => "\xF5", # small o, tilde - "Ouml" => "\xD6", # capital O, dieresis or umlaut mark - "ouml" => "\xF6", # small o, dieresis or umlaut mark - "szlig" => "\xDF", # small sharp s, German (sz ligature) - "THORN" => "\xDE", # capital THORN, Icelandic - "thorn" => "\xFE", # small thorn, Icelandic - "Uacute" => "\xDA", # capital U, acute accent - "uacute" => "\xFA", # small u, acute accent - "Ucirc" => "\xDB", # capital U, circumflex accent - "ucirc" => "\xFB", # small u, circumflex accent - "Ugrave" => "\xD9", # capital U, grave accent - "ugrave" => "\xF9", # small u, grave accent - "Uuml" => "\xDC", # capital U, dieresis or umlaut mark - "uuml" => "\xFC", # small u, dieresis or umlaut mark - "Yacute" => "\xDD", # capital Y, acute accent - "yacute" => "\xFD", # small y, acute accent - "yuml" => "\xFF", # small y, dieresis or umlaut mark - - "laquo" => "\xAB", # left pointing double angle quotation mark - "lchevron" => "\xAB", # synonym (backwards compatibility) - "raquo" => "\xBB", # right pointing double angle quotation mark - "rchevron" => "\xBB", # synonym (backwards compatibility) - - "iexcl" => "\xA1", # inverted exclamation mark - "cent" => "\xA2", # cent sign - "pound" => "\xA3", # (UK) pound sign - "curren" => "\xA4", # currency sign - "yen" => "\xA5", # yen sign - "brvbar" => "\xA6", # broken vertical bar - "sect" => "\xA7", # section sign - "uml" => "\xA8", # diaresis - "copy" => "\xA9", # Copyright symbol - "ordf" => "\xAA", # feminine ordinal indicator - "not" => "\xAC", # not sign - "shy" => '', # soft (discretionary) hyphen - "reg" => "\xAE", # registered trademark - "macr" => "\xAF", # macron, overline - "deg" => "\xB0", # degree sign - "plusmn" => "\xB1", # plus-minus sign - "sup2" => "\xB2", # superscript 2 - "sup3" => "\xB3", # superscript 3 - "acute" => "\xB4", # acute accent - "micro" => "\xB5", # micro sign - "para" => "\xB6", # pilcrow sign = paragraph sign - "middot" => "\xB7", # middle dot = Georgian comma - "cedil" => "\xB8", # cedilla - "sup1" => "\xB9", # superscript 1 - "ordm" => "\xBA", # masculine ordinal indicator - "frac14" => "\xBC", # vulgar fraction one quarter - "frac12" => "\xBD", # vulgar fraction one half - "frac34" => "\xBE", # vulgar fraction three quarters - "iquest" => "\xBF", # inverted question mark - "times" => "\xD7", # multiplication sign - "divide" => "\xF7", # division sign - - "nbsp" => "\x01", # non-breaking space -); - +$VERSION = 3.01; ############################################################################## # Initialization ############################################################################## -# Initialize the object. Must be sure to call our parent initializer. -sub initialize { - my $self = shift; +# This function handles code blocks. It's registered as a callback to +# Pod::Simple and therefore doesn't work as a regular method call, but all it +# does is call output_code with the line. +sub handle_code { + my ($line, $number, $parser) = @_; + $parser->output_code ($line . "\n"); +} + +# Initialize the object and set various Pod::Simple options that we need. +# Here, we also process any additional options passed to the constructor or +# set up defaults if none were given. Note that all internal object keys are +# in all-caps, reserving all lower-case object keys for Pod::Simple and user +# arguments. +sub new { + my $class = shift; + my $self = $class->SUPER::new; + + # Tell Pod::Simple to handle S<> by automatically inserting  . + $self->nbsp_for_S (1); + + # Tell Pod::Simple to keep whitespace whenever possible. + if ($self->can ('preserve_whitespace')) { + $self->preserve_whitespace (1); + } else { + $self->fullstop_space_harden (1); + } - $$self{alt} = 0 unless defined $$self{alt}; - $$self{indent} = 4 unless defined $$self{indent}; - $$self{margin} = 0 unless defined $$self{margin}; - $$self{loose} = 0 unless defined $$self{loose}; - $$self{sentence} = 0 unless defined $$self{sentence}; - $$self{width} = 76 unless defined $$self{width}; + # The =for and =begin targets that we accept. + $self->accept_targets (qw/text TEXT/); + + # Ensure that contiguous blocks of code are merged together. Otherwise, + # some of the guesswork heuristics don't work right. + $self->merge_text (1); + + # Pod::Simple doesn't do anything useful with our arguments, but we want + # to put them in our object as hash keys and values. This could cause + # problems if we ever clash with Pod::Simple's own internal class + # variables. + my %opts = @_; + my @opts = map { ("opt_$_", $opts{$_}) } keys %opts; + %$self = (%$self, @opts); + + # Initialize various things from our parameters. + $$self{opt_alt} = 0 unless defined $$self{opt_alt}; + $$self{opt_indent} = 4 unless defined $$self{opt_indent}; + $$self{opt_margin} = 0 unless defined $$self{opt_margin}; + $$self{opt_loose} = 0 unless defined $$self{opt_loose}; + $$self{opt_sentence} = 0 unless defined $$self{opt_sentence}; + $$self{opt_width} = 76 unless defined $$self{opt_width}; # Figure out what quotes we'll be using for C<> text. - $$self{quotes} ||= '"'; - if ($$self{quotes} eq 'none') { + $$self{opt_quotes} ||= '"'; + if ($$self{opt_quotes} eq 'none') { $$self{LQUOTE} = $$self{RQUOTE} = ''; - } elsif (length ($$self{quotes}) == 1) { - $$self{LQUOTE} = $$self{RQUOTE} = $$self{quotes}; - } elsif ($$self{quotes} =~ /^(.)(.)$/ - || $$self{quotes} =~ /^(..)(..)$/) { + } elsif (length ($$self{opt_quotes}) == 1) { + $$self{LQUOTE} = $$self{RQUOTE} = $$self{opt_quotes}; + } elsif ($$self{opt_quotes} =~ /^(.)(.)$/ + || $$self{opt_quotes} =~ /^(..)(..)$/) { $$self{LQUOTE} = $1; $$self{RQUOTE} = $2; } else { - croak qq(Invalid quote specification "$$self{quotes}"); + croak qq(Invalid quote specification "$$self{opt_quotes}"); } - # Stack of indentations. - $$self{INDENTS} = []; + # If requested, do something with the non-POD text. + $self->code_handler (\&handle_code) if $$self{opt_code}; - # Current left margin. - $$self{MARGIN} = $$self{indent} + $$self{margin}; + # Return the created object. + return $self; +} - $self->SUPER::initialize; +############################################################################## +# Core parsing +############################################################################## - # Tell Pod::Parser that we want the non-POD stuff too if code was set. - $self->parseopts ('-want_nonPODs' => 1) if $$self{code}; +# This is the glue that connects the code below with Pod::Simple itself. The +# goal is to convert the event stream coming from the POD parser into method +# calls to handlers once the complete content of a tag has been seen. Each +# paragraph or POD command will have textual content associated with it, and +# as soon as all of a paragraph or POD command has been seen, that content +# will be passed in to the corresponding method for handling that type of +# object. The exceptions are handlers for lists, which have opening tag +# handlers and closing tag handlers that will be called right away. +# +# The internal hash key PENDING is used to store the contents of a tag until +# all of it has been seen. It holds a stack of open tags, each one +# represented by a tuple of the attributes hash for the tag and the contents +# of the tag. + +# Add a block of text to the contents of the current node, formatting it +# according to the current formatting instructions as we do. +sub _handle_text { + my ($self, $text) = @_; + my $tag = $$self{PENDING}[-1]; + $$tag[1] .= $text; } +# Given an element name, get the corresponding method name. +sub method_for_element { + my ($self, $element) = @_; + $element =~ tr/-/_/; + $element =~ tr/A-Z/a-z/; + $element =~ tr/_a-z0-9//cd; + return $element; +} -############################################################################## -# Core overrides -############################################################################## +# Handle the start of a new element. If cmd_element is defined, assume that +# we need to collect the entire tree for this element before passing it to the +# element method, and create a new tree into which we'll collect blocks of +# text and nested elements. Otherwise, if start_element is defined, call it. +sub _handle_element_start { + my ($self, $element, $attrs) = @_; + my $method = $self->method_for_element ($element); + + # If we have a command handler, we need to accumulate the contents of the + # tag before calling it. + if ($self->can ("cmd_$method")) { + push (@{ $$self{PENDING} }, [ $attrs, '' ]); + } elsif ($self->can ("start_$method")) { + my $method = 'start_' . $method; + $self->$method ($attrs, ''); + } +} -# Called for each command paragraph. Gets the command, the associated -# paragraph, the line number, and a Pod::Paragraph object. Just dispatches -# the command to a method named the same as the command. =cut is handled -# internally by Pod::Parser. -sub command { - my $self = shift; - my $command = shift; - return if $command eq 'pod'; - return if ($$self{EXCLUDE} && $command ne 'end'); - if ($self->can ('cmd_' . $command)) { - $command = 'cmd_' . $command; - $self->$command (@_); - } else { - my ($text, $line, $paragraph) = @_; - my $file; - ($file, $line) = $paragraph->file_line; - $text =~ s/\n+\z//; - $text = " $text" if ($text =~ /^\S/); - warn qq($file:$line: Unknown command paragraph: =$command$text\n); - return; +# Handle the end of an element. If we had a cmd_ method for this element, +# this is where we pass along the text that we've accumulated. Otherwise, if +# we have an end_ method for the element, call that. +sub _handle_element_end { + my ($self, $element) = @_; + my $method = $self->method_for_element ($element); + + # If we have a command handler, pull off the pending text and pass it to + # the handler along with the saved attribute hash. + if ($self->can ("cmd_$method")) { + my $tag = pop @{ $$self{PENDING} }; + my $method = 'cmd_' . $method; + my $text = $self->$method (@$tag); + if (defined $text) { + if (@{ $$self{PENDING} } > 1) { + $$self{PENDING}[-1][1] .= $text; + } else { + $self->output ($text); + } + } + } elsif ($self->can ("end_$method")) { + my $method = 'end_' . $method; + $self->$method; } } -# Called for a verbatim paragraph. Gets the paragraph, the line number, and a -# Pod::Paragraph object. Just output it verbatim, but with tabs converted to -# spaces. -sub verbatim { +############################################################################## +# Output formatting +############################################################################## + +# Wrap a line, indenting by the current left margin. We can't use Text::Wrap +# because it plays games with tabs. We can't use formline, even though we'd +# really like to, because it screws up non-printing characters. So we have to +# do the wrapping ourselves. +sub wrap { my $self = shift; - return if $$self{EXCLUDE}; - $self->item if defined $$self{ITEM}; local $_ = shift; - return if /^\s*$/; - s/^(\s*\S+)/(' ' x $$self{MARGIN}) . $1/gme; - $self->output ($_); + my $output = ''; + my $spaces = ' ' x $$self{MARGIN}; + my $width = $$self{opt_width} - $$self{MARGIN}; + while (length > $width) { + if (s/^([^\n]{0,$width})\s+// || s/^([^\n]{$width})//) { + $output .= $spaces . $1 . "\n"; + } else { + last; + } + } + $output .= $spaces . $_; + $output =~ s/\s+$/\n\n/; + return $output; } -# Called for a regular text block. Gets the paragraph, the line number, and a -# Pod::Paragraph object. Perform interpolation and output the results. -sub textblock { +# Reformat a paragraph of text for the current margin. Takes the text to +# reformat and returns the formatted text. +sub reformat { my $self = shift; - return if $$self{EXCLUDE}; - $self->output ($_[0]), return if $$self{VERBATIM}; local $_ = shift; - my $line = shift; - # Interpolate and output the paragraph. - $_ = $self->interpolate ($_, $line); - s/\s+$/\n/; - if (defined $$self{ITEM}) { - $self->item ($_ . "\n"); + # If we're trying to preserve two spaces after sentences, do some munging + # to support that. Otherwise, smash all repeated whitespace. + if ($$self{opt_sentence}) { + s/ +$//mg; + s/\.\n/. \n/g; + s/\n/ /g; + s/ +/ /g; } else { - $self->output ($self->reformat ($_ . "\n")); + s/\s+/ /g; } + return $self->wrap ($_); } -# Called for a formatting code. Gets the command, argument, and a -# Pod::InteriorSequence object and is expected to return the resulting text. -# Calls methods for code, bold, italic, file, and link to handle those types -# of codes, and handles S<>, E<>, X<>, and Z<> directly. -sub interior_sequence { - local $_; - my ($self, $command, $seq); - ($self, $command, $_, $seq) = @_; - - # We have to defer processing of the inside of an L<> formatting code. If - # this code is nested inside an L<> code, return the literal raw text of - # it. - my $parent = $seq->nested; - while (defined $parent) { - return $seq->raw_text if ($parent->cmd_name eq 'L'); - $parent = $parent->nested; - } +# Output text to the output device. +sub output { + my ($self, $text) = @_; + $text =~ tr/\240\255/ /d; + print { $$self{output_fh} } $text; +} - # Index entries are ignored in plain text. - return '' if ($command eq 'X' || $command eq 'Z'); +# Output a block of code (something that isn't part of the POD text). Called +# by preprocess_paragraph only if we were given the code option. Exists here +# only so that it can be overridden by subclasses. +sub output_code { $_[0]->output ($_[1]) } - # Expand escapes into the actual character now, warning if invalid. - if ($command eq 'E') { - if (/^\d+$/) { - return chr; - } else { - return $ESCAPES{$_} if defined $ESCAPES{$_}; - my ($file, $line) = $seq->file_line; - warn "$file:$line: Unknown escape: E<$_>\n"; - return "E<$_>"; - } +############################################################################## +# Document initialization +############################################################################## + +# Set up various things that have to be initialized on a per-document basis. +sub start_document { + my $self = shift; + my $margin = $$self{opt_indent} + $$self{opt_margin}; + + # Initialize a few per-document variables. + $$self{INDENTS} = []; # Stack of indentations. + $$self{MARGIN} = $margin; # Default left margin. + $$self{PENDING} = [[]]; # Pending output. + + return ''; +} + +############################################################################## +# Text blocks +############################################################################## + +# This method is called whenever an =item command is complete (in other words, +# we've seen its associated paragraph or know for certain that it doesn't have +# one). It gets the paragraph associated with the item as an argument. If +# that argument is empty, just output the item tag; if it contains a newline, +# output the item tag followed by the newline. Otherwise, see if there's +# enough room for us to output the item tag in the margin of the text or if we +# have to put it on a separate line. +sub item { + my ($self, $text) = @_; + my $tag = $$self{ITEM}; + unless (defined $tag) { + carp "Item called without tag"; + return; } + undef $$self{ITEM}; - # For all the other formatting codes, empty content produces no output. - return if $_ eq ''; + # Calculate the indentation and margin. $fits is set to true if the tag + # will fit into the margin of the paragraph given our indentation level. + my $indent = $$self{INDENTS}[-1]; + $indent = $$self{opt_indent} unless defined $indent; + my $margin = ' ' x $$self{opt_margin}; + my $fits = ($$self{MARGIN} - $indent >= length ($tag) + 1); - # For S<>, compress all internal whitespace and then map spaces to \01. - # When we output the text, we'll map this back. - if ($command eq 'S') { - s/\s+/ /g; - tr/ /\01/; - return $_; + # If the tag doesn't fit, or if we have no associated text, print out the + # tag separately. Otherwise, put the tag in the margin of the paragraph. + if (!$text || $text =~ /^\s+$/ || !$fits) { + my $realindent = $$self{MARGIN}; + $$self{MARGIN} = $indent; + my $output = $self->reformat ($tag); + $output =~ s/^$margin /$margin:/ if ($$self{opt_alt} && $indent > 0); + $output =~ s/\n*$/\n/; + + # If the text is just whitespace, we have an empty item paragraph; + # this can result from =over/=item/=back without any intermixed + # paragraphs. Insert some whitespace to keep the =item from merging + # into the next paragraph. + $output .= "\n" if $text && $text =~ /^\s*$/; + + $self->output ($output); + $$self{MARGIN} = $realindent; + $self->output ($self->reformat ($text)) if ($text && $text =~ /\S/); + } else { + my $space = ' ' x $indent; + $space =~ s/^$margin /$margin:/ if $$self{opt_alt}; + $text = $self->reformat ($text); + $text =~ s/^$margin /$margin:/ if ($$self{opt_alt} && $indent > 0); + my $tagspace = ' ' x length $tag; + $text =~ s/^($space)$tagspace/$1$tag/ or warn "Bizarre space in item"; + $self->output ($text); } +} - # Anything else needs to get dispatched to another method. - if ($command eq 'B') { return $self->seq_b ($_) } - elsif ($command eq 'C') { return $self->seq_c ($_) } - elsif ($command eq 'F') { return $self->seq_f ($_) } - elsif ($command eq 'I') { return $self->seq_i ($_) } - elsif ($command eq 'L') { return $self->seq_l ($_, $seq) } - else { - my ($file, $line) = $seq->file_line; - warn "$file:$line: Unknown formatting code: $command<$_>\n"; +# Handle a basic block of text. The only tricky thing here is that if there +# is a pending item tag, we need to format this as an item paragraph. +sub cmd_para { + my ($self, $attrs, $text) = @_; + $text =~ s/\s+$/\n/; + if (defined $$self{ITEM}) { + $self->item ($text . "\n"); + } else { + $self->output ($self->reformat ($text . "\n")); } + return ''; } -# Called for each paragraph that's actually part of the POD. We take -# advantage of this opportunity to untabify the input. Also, if given the -# code option, we may see paragraphs that aren't part of the POD and need to -# output them directly. -sub preprocess_paragraph { - my $self = shift; - local $_ = shift; - 1 while s/^(.*?)(\t+)/$1 . ' ' x (length ($2) * 8 - length ($1) % 8)/me; - $self->output_code ($_) if $self->cutting; - $_; +# Handle a verbatim paragraph. Just print it out, but indent it according to +# our margin. +sub cmd_verbatim { + my ($self, $attrs, $text) = @_; + $self->item if defined $$self{ITEM}; + return if $text =~ /^\s*$/; + $text =~ s/^(\n*)(\s*\S+)/$1 . (' ' x $$self{MARGIN}) . $2/gme; + $text =~ s/\s*$/\n\n/; + $self->output ($text); + return ''; } +# Handle literal text (produced by =for and similar constructs). Just output +# it with the minimum of changes. +sub cmd_data { + my ($self, $attrs, $text) = @_; + $text =~ s/^\n+//; + $text =~ s/\n{0,2}$/\n/; + $self->output ($text); + return ''; +} ############################################################################## -# Command paragraphs +# Headings ############################################################################## -# All command paragraphs take the paragraph and the line number. +# The common code for handling all headers. Takes the header text, the +# indentation, and the surrounding marker for the alt formatting method. +sub heading { + my ($self, $text, $indent, $marker) = @_; + $self->item ("\n\n") if defined $$self{ITEM}; + $text =~ s/\s+$//; + if ($$self{opt_alt}) { + my $closemark = reverse (split (//, $marker)); + my $margin = ' ' x $$self{opt_margin}; + $self->output ("\n" . "$margin$marker $text $closemark" . "\n\n"); + } else { + $text .= "\n" if $$self{opt_loose}; + my $margin = ' ' x ($$self{opt_margin} + $indent); + $self->output ($margin . $text . "\n"); + } + return ''; +} # First level heading. sub cmd_head1 { - my ($self, $text, $line) = @_; - $self->heading ($text, $line, 0, '===='); + my ($self, $attrs, $text) = @_; + $self->heading ($text, 0, '===='); } # Second level heading. sub cmd_head2 { - my ($self, $text, $line) = @_; - $self->heading ($text, $line, $$self{indent} / 2, '== '); + my ($self, $attrs, $text) = @_; + $self->heading ($text, $$self{opt_indent} / 2, '== '); } # Third level heading. sub cmd_head3 { - my ($self, $text, $line) = @_; - $self->heading ($text, $line, $$self{indent} * 2 / 3 + 0.5, '= '); + my ($self, $attrs, $text) = @_; + $self->heading ($text, $$self{opt_indent} * 2 / 3 + 0.5, '= '); } -# Third level heading. +# Fourth level heading. sub cmd_head4 { - my ($self, $text, $line) = @_; - $self->heading ($text, $line, $$self{indent} * 3 / 4 + 0.5, '- '); + my ($self, $attrs, $text) = @_; + $self->heading ($text, $$self{opt_indent} * 3 / 4 + 0.5, '- '); } -# Start a list. -sub cmd_over { - my $self = shift; - local $_ = shift; +############################################################################## +# List handling +############################################################################## + +# Handle the beginning of an =over block. Takes the type of the block as the +# first argument, and then the attr hash. This is called by the handlers for +# the four different types of lists (bullet, number, text, and block). +sub over_common_start { + my ($self, $attrs) = @_; $self->item ("\n\n") if defined $$self{ITEM}; - unless (/^[-+]?\d+\s+$/) { $_ = $$self{indent} } + + # Find the indentation level. + my $indent = $$attrs{indent}; + unless (defined ($indent) && $indent =~ /^\s*[-+]?\d{1,4}\s*$/) { + $indent = $$self{opt_indent}; + } + + # Add this to our stack of indents and increase our current margin. push (@{ $$self{INDENTS} }, $$self{MARGIN}); - $$self{MARGIN} += ($_ + 0); + $$self{MARGIN} += ($indent + 0); + return ''; } -# End a list. -sub cmd_back { - my ($self, $text, $line, $paragraph) = @_; +# End an =over block. Takes no options other than the class pointer. Output +# any pending items and then pop one level of indentation. +sub over_common_end { + my ($self) = @_; $self->item ("\n\n") if defined $$self{ITEM}; $$self{MARGIN} = pop @{ $$self{INDENTS} }; - unless (defined $$self{MARGIN}) { - my $file; - ($file, $line) = $paragraph->file_line; - warn "$file:$line: Unmatched =back\n"; - $$self{MARGIN} = $$self{indent}; - } + return ''; } -# An individual list item. -sub cmd_item { - my $self = shift; - if (defined $$self{ITEM}) { $self->item } - local $_ = shift; - s/\s+$//; - $$self{ITEM} = $_ ? $self->interpolate ($_) : '*'; -} +# Dispatch the start and end calls as appropriate. +sub start_over_bullet { $_[0]->over_common_start ($_[1]) } +sub start_over_number { $_[0]->over_common_start ($_[1]) } +sub start_over_text { $_[0]->over_common_start ($_[1]) } +sub start_over_block { $_[0]->over_common_start ($_[1]) } +sub end_over_bullet { $_[0]->over_common_end } +sub end_over_number { $_[0]->over_common_end } +sub end_over_text { $_[0]->over_common_end } +sub end_over_block { $_[0]->over_common_end } + +# The common handler for all item commands. Takes the type of the item, the +# attributes, and then the text of the item. +sub item_common { + my ($self, $type, $attrs, $text) = @_; + $self->item if defined $$self{ITEM}; -# Begin a block for a particular translator. Setting VERBATIM triggers -# special handling in textblock(). -sub cmd_begin { - my $self = shift; - local $_ = shift; - my ($kind) = /^(\S+)/ or return; - if ($kind eq 'text') { - $$self{VERBATIM} = 1; + # Clean up the text. We want to end up with two variables, one ($text) + # which contains any body text after taking out the item portion, and + # another ($item) which contains the actual item text. Note the use of + # the internal Pod::Simple attribute here; that's a potential land mine. + $text =~ s/\s+$//; + my ($item, $index); + if ($type eq 'bullet') { + $item = '*'; + } elsif ($type eq 'number') { + $item = $$attrs{'~orig_content'}; } else { - $$self{EXCLUDE} = 1; + $item = $text; + $item =~ s/\s*\n\s*/ /g; + $text = ''; } -} - -# End a block for a particular translator. We assume that all =begin/=end -# pairs are properly closed. -sub cmd_end { - my $self = shift; - $$self{EXCLUDE} = 0; - $$self{VERBATIM} = 0; -} + $$self{ITEM} = $item; -# One paragraph for a particular translator. Ignore it unless it's intended -# for text, in which case we treat it as a verbatim text block. -sub cmd_for { - my $self = shift; - local $_ = shift; - my $line = shift; - return unless s/^text\b[ \t]*\n?//; - $self->verbatim ($_, $line); + # If body text for this item was included, go ahead and output that now. + if ($text) { + $text =~ s/\s*$/\n/; + $self->item ($text); + } + return ''; } +# Dispatch the item commands to the appropriate place. +sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) } +sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) } +sub cmd_item_text { my $self = shift; $self->item_common ('text', @_) } +sub cmd_item_block { my $self = shift; $self->item_common ('block', @_) } ############################################################################## # Formatting codes ############################################################################## -# The simple ones. These are here mostly so that subclasses can override them -# and do more complicated things. -sub seq_b { return $_[0]{alt} ? "``$_[1]''" : $_[1] } -sub seq_f { return $_[0]{alt} ? "\"$_[1]\"" : $_[1] } -sub seq_i { return '*' . $_[1] . '*' } +# The simple ones. +sub cmd_b { return $_[0]{alt} ? "``$_[2]''" : $_[2] } +sub cmd_f { return $_[0]{alt} ? "\"$_[2]\"" : $_[2] } +sub cmd_i { return '*' . $_[2] . '*' } +sub cmd_x { return '' } # Apply a whole bunch of messy heuristics to not quote things that don't # benefit from being quoted. These originally come from Barrie Slaymaker and # largely duplicate code in Pod::Man. -sub seq_c { - my $self = shift; - local $_ = shift; +sub cmd_c { + my ($self, $attrs, $text) = @_; # A regex that matches the portion of a variable reference that's the # array or hash index, separated out just because we want to use it in @@ -455,7 +509,7 @@ sub seq_c { # Check for things that we don't want to quote, and if we find any of # them, return the string with just a font change and no quoting. - m{ + $text =~ m{ ^\s* (?: ( [\'\`\"] ) .* \1 # already quoted @@ -467,154 +521,21 @@ sub seq_c { | 0x [a-fA-F\d]+ # a hex constant ) \s*\z - }xo && return $_; + }xo && return $text; # If we didn't return, go ahead and quote the text. - return $$self{alt} ? "``$_''" : "$$self{LQUOTE}$_$$self{RQUOTE}"; -} - -# Handle links. Since this is plain text, we can't actually make any real -# links, so this is all to figure out what text we print out. Most of the -# work is done by Pod::ParseLink. -sub seq_l { - my ($self, $link, $seq) = @_; - my ($text, $type) = (parselink ($link))[1,4]; - my ($file, $line) = $seq->file_line; - $text = $self->interpolate ($text, $line); - $text = '<' . $text . '>' if $type eq 'url'; - return $text || ''; + return $$self{opt_alt} + ? "``$text''" + : "$$self{LQUOTE}$text$$self{RQUOTE}"; } - -############################################################################## -# Header handling -############################################################################## - -# The common code for handling all headers. Takes the interpolated header -# text, the line number, the indentation, and the surrounding marker for the -# alt formatting method. -sub heading { - my ($self, $text, $line, $indent, $marker) = @_; - $self->item ("\n\n") if defined $$self{ITEM}; - $text =~ s/\s+$//; - $text = $self->interpolate ($text, $line); - if ($$self{alt}) { - my $closemark = reverse (split (//, $marker)); - my $margin = ' ' x $$self{margin}; - $self->output ("\n" . "$margin$marker $text $closemark" . "\n\n"); - } else { - $text .= "\n" if $$self{loose}; - my $margin = ' ' x ($$self{margin} + $indent); - $self->output ($margin . $text . "\n"); - } +# Links reduce to the text that we're given, wrapped in angle brackets if it's +# a URL. +sub cmd_l { + my ($self, $attrs, $text) = @_; + return $$attrs{type} eq 'url' ? "<$text>" : $text; } - -############################################################################## -# List handling -############################################################################## - -# This method is called whenever an =item command is complete (in other words, -# we've seen its associated paragraph or know for certain that it doesn't have -# one). It gets the paragraph associated with the item as an argument. If -# that argument is empty, just output the item tag; if it contains a newline, -# output the item tag followed by the newline. Otherwise, see if there's -# enough room for us to output the item tag in the margin of the text or if we -# have to put it on a separate line. -sub item { - my $self = shift; - local $_ = shift; - my $tag = $$self{ITEM}; - unless (defined $tag) { - carp "Item called without tag"; - return; - } - undef $$self{ITEM}; - my $indent = $$self{INDENTS}[-1]; - unless (defined $indent) { $indent = $$self{indent} } - my $margin = ' ' x $$self{margin}; - if (!$_ || /^\s+$/ || ($$self{MARGIN} - $indent < length ($tag) + 1)) { - my $realindent = $$self{MARGIN}; - $$self{MARGIN} = $indent; - my $output = $self->reformat ($tag); - $output =~ s/^$margin /$margin:/ if ($$self{alt} && $indent > 0); - $output =~ s/\n*$/\n/; - - # If the text is just whitespace, we have an empty item paragraph; - # this can result from =over/=item/=back without any intermixed - # paragraphs. Insert some whitespace to keep the =item from merging - # into the next paragraph. - $output .= "\n" if $_ && $_ =~ /^\s*$/; - - $self->output ($output); - $$self{MARGIN} = $realindent; - $self->output ($self->reformat ($_)) if $_ && /\S/; - } else { - my $space = ' ' x $indent; - $space =~ s/^$margin /$margin:/ if $$self{alt}; - $_ = $self->reformat ($_); - s/^$margin /$margin:/ if ($$self{alt} && $indent > 0); - my $tagspace = ' ' x length $tag; - s/^($space)$tagspace/$1$tag/ or warn "Bizarre space in item"; - $self->output ($_); - } -} - - -############################################################################## -# Output formatting -############################################################################## - -# Wrap a line, indenting by the current left margin. We can't use Text::Wrap -# because it plays games with tabs. We can't use formline, even though we'd -# really like to, because it screws up non-printing characters. So we have to -# do the wrapping ourselves. -sub wrap { - my $self = shift; - local $_ = shift; - my $output = ''; - my $spaces = ' ' x $$self{MARGIN}; - my $width = $$self{width} - $$self{MARGIN}; - while (length > $width) { - if (s/^([^\n]{0,$width})\s+// || s/^([^\n]{$width})//) { - $output .= $spaces . $1 . "\n"; - } else { - last; - } - } - $output .= $spaces . $_; - $output =~ s/\s+$/\n\n/; - $output; -} - -# Reformat a paragraph of text for the current margin. Takes the text to -# reformat and returns the formatted text. -sub reformat { - my $self = shift; - local $_ = shift; - - # If we're trying to preserve two spaces after sentences, do some munging - # to support that. Otherwise, smash all repeated whitespace. - if ($$self{sentence}) { - s/ +$//mg; - s/\.\n/. \n/g; - s/\n/ /g; - s/ +/ /g; - } else { - s/\s+/ /g; - } - $self->wrap ($_); -} - -# Output text to the output device. -sub output { $_[1] =~ tr/\01/ /; print { $_[0]->output_handle } $_[1] } - -# Output a block of code (something that isn't part of the POD text). Called -# by preprocess_paragraph only if we were given the code option. Exists here -# only so that it can be overridden by subclasses. -sub output_code { $_[0]->output ($_[1]) } - - ############################################################################## # Backwards compatibility ############################################################################## @@ -652,13 +573,12 @@ sub pod2text { return; } $fhs[0] = \*IN; - return $parser->parse_from_filehandle (@fhs); + return $parser->parse_file (@fhs); } else { - return $parser->parse_from_file (@_); + return $parser->parse_file (@_); } } - ############################################################################## # Module return value and documentation ############################################################################## @@ -688,10 +608,9 @@ preferred language for documenting Perl) into formatted ASCII. It uses no special formatting controls or codes whatsoever, and its output is therefore suitable for nearly any device. -As a derived class from Pod::Parser, Pod::Text supports the same methods and -interfaces. See L for all the details; briefly, one creates a -new parser with C<< Pod::Text->new() >> and then calls either -parse_from_filehandle() or parse_from_file(). +As a derived class from Pod::Simple, Pod::Text supports the same methods and +interfaces. See L for all the details; briefly, one creates a +new parser with C<< Pod::Text->new() >> and then normally calls parse_file(). new() can take options, in the form of key/value pairs, that control the behavior of the parser. The currently recognized options are: @@ -755,13 +674,10 @@ The column at which to wrap text on the right-hand side. Defaults to 76. =back -The standard Pod::Parser method parse_from_filehandle() takes up to two -arguments, the first being the file handle to read POD from and the second -being the file handle to write the formatted output to. The first defaults -to STDIN if not given, and the second defaults to STDOUT. The method -parse_from_file() is almost identical, except that its two arguments are the -input and output disk files instead. See L for the specific -details. +The standard Pod::Simple method parse_file() takes one argument, the file or +file handle to read from, and writes output to standard output unless that +has been changed with the output_fh() method. See L for the +specific details and for other alternative interfaces. =head1 DIAGNOSTICS @@ -784,37 +700,12 @@ and the input file it was given could not be opened. (F) The quote specification given (the quotes option to the constructor) was invalid. A quote specification must be one, two, or four characters long. -=item %s:%d: Unknown command paragraph: %s - -(W) The POD source contained a non-standard command paragraph (something of -the form C<=command args>) that Pod::Man didn't know about. It was ignored. - -=item %s:%d: Unknown escape: %s - -(W) The POD source contained an CE> escape that Pod::Text didn't -know about. - -=item %s:%d: Unknown formatting code: %s - -(W) The POD source contained a non-standard formatting code (something of -the form CE>) that Pod::Text didn't know about. - -=item %s:%d: Unmatched =back - -(W) Pod::Text encountered a C<=back> command that didn't correspond to an -C<=over> command. - =back -=head1 RESTRICTIONS - -Embedded Ctrl-As (octal 001) in the input will be mapped to spaces on -output, due to an internal implementation detail. - =head1 NOTES This is a replacement for an earlier Pod::Text module written by Tom -Christiansen. It has a revamped interface, since it now uses Pod::Parser, +Christiansen. It has a revamped interface, since it now uses Pod::Simple, but an interface roughly compatible with the old Pod::Text::pod2text() function is still available. Please change to the new calling convention, though. @@ -826,7 +717,7 @@ subclass of it does. Look for L. =head1 SEE ALSO -L, L, L +L, L, L The current version of this module is always available from its web site at L. It is also part of the @@ -836,11 +727,13 @@ Perl core distribution as of 5.6.0. Russ Allbery , based I heavily on the original Pod::Text by Tom Christiansen and its conversion to -Pod::Parser by Brad Appleton . +Pod::Parser by Brad Appleton . Sean Burke's initial +conversion of Pod::Man to use Pod::Simple provided much-needed guidance on +how to use Pod::Simple. =head1 COPYRIGHT AND LICENSE -Copyright 1999, 2000, 2001, 2002 by Russ Allbery . +Copyright 1999, 2000, 2001, 2002, 2004 by Russ Allbery . This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Pod/Text/Color.pm b/lib/Pod/Text/Color.pm index 2ba3136..68de203 100644 --- a/lib/Pod/Text/Color.pm +++ b/lib/Pod/Text/Color.pm @@ -1,7 +1,7 @@ # Pod::Text::Color -- Convert POD data to formatted color ASCII text -# $Id: Color.pm,v 1.4 2002/07/15 05:46:00 eagle Exp $ +# $Id: Color.pm,v 2.1 2004/12/31 21:50:00 eagle Exp $ # -# Copyright 1999, 2001 by Russ Allbery +# Copyright 1999, 2001, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -29,8 +29,7 @@ use vars qw(@ISA $VERSION); # Don't use the CVS revision as the version, since this module is also in Perl # core and too many things could munge CVS magic revision strings. This # number should ideally be the same as the CVS revision in podlators, however. -$VERSION = 1.04; - +$VERSION = 2.01; ############################################################################## # Overrides @@ -38,24 +37,22 @@ $VERSION = 1.04; # Make level one headings bold. sub cmd_head1 { - my $self = shift; - local $_ = shift; - s/\s+$//; - $self->SUPER::cmd_head1 (colored ($_, 'bold')); + my ($self, $attrs, $text) = @_; + $text =~ s/\s+$//; + $self->SUPER::cmd_head1 ($attrs, colored ($text, 'bold')); } # Make level two headings bold. sub cmd_head2 { - my $self = shift; - local $_ = shift; - s/\s+$//; - $self->SUPER::cmd_head2 (colored ($_, 'bold')); + my ($self, $attrs, $text) = @_; + $text =~ s/\s+$//; + $self->SUPER::cmd_head2 ($attrs, colored ($text, 'bold')); } # Fix the various formatting codes. -sub seq_b { return colored ($_[1], 'bold') } -sub seq_f { return colored ($_[1], 'cyan') } -sub seq_i { return colored ($_[1], 'yellow') } +sub cmd_b { return colored ($_[2], 'bold') } +sub cmd_f { return colored ($_[2], 'cyan') } +sub cmd_i { return colored ($_[2], 'yellow') } # Output any included code in green. sub output_code { @@ -71,10 +68,10 @@ sub wrap { local $_ = shift; my $output = ''; my $spaces = ' ' x $$self{MARGIN}; - my $width = $$self{width} - $$self{MARGIN}; + my $width = $$self{opt_width} - $$self{MARGIN}; + my $char = '(?:(?:\e\[[\d;]+m)*[^\n])'; while (length > $width) { - if (s/^((?:(?:\e\[[\d;]+m)?[^\n]){0,$width})\s+// - || s/^((?:(?:\e\[[\d;]+m)?[^\n]){$width})//) { + if (s/^(${char}{0,$width})\s+// || s/^(${char}{$width})//) { $output .= $spaces . $1 . "\n"; } else { last; @@ -125,7 +122,7 @@ B should be taught about those. =head1 SEE ALSO -L, L +L, L The current version of this module is always available from its web site at L. It is also part of the @@ -137,7 +134,7 @@ Russ Allbery . =head1 COPYRIGHT AND LICENSE -Copyright 1999, 2001 by Russ Allbery . +Copyright 1999, 2001, 2004 by Russ Allbery . This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Pod/Text/Overstrike.pm b/lib/Pod/Text/Overstrike.pm index 8ba9183..4ec2fc0 100644 --- a/lib/Pod/Text/Overstrike.pm +++ b/lib/Pod/Text/Overstrike.pm @@ -1,5 +1,5 @@ # Pod::Text::Overstrike -- Convert POD data to formatted overstrike text -# $Id: Overstrike.pm,v 1.10 2002/08/04 03:35:01 eagle Exp $ +# $Id: Overstrike.pm,v 2.0 2004/06/09 04:51:20 eagle Exp $ # # Created by Joe Smith 30-Nov-2000 # (based on Pod::Text::Color by Russ Allbery ) @@ -36,8 +36,7 @@ use vars qw(@ISA $VERSION); # Don't use the CVS revision as the version, since this module is also in Perl # core and too many things could munge CVS magic revision strings. This # number should ideally be the same as the CVS revision in podlators, however. -$VERSION = 1.10; - +$VERSION = 2.00; ############################################################################## # Overrides @@ -45,54 +44,55 @@ $VERSION = 1.10; # Make level one headings bold, overridding any existing formatting. sub cmd_head1 { - my ($self, $text, $line) = @_; + my ($self, $attrs, $text) = @_; $text =~ s/\s+$//; - $text = $self->strip_format ($self->interpolate ($text, $line)); + $text = $self->strip_format ($text); $text =~ s/(.)/$1\b$1/g; - $self->SUPER::cmd_head1 ($text); + return $self->SUPER::cmd_head1 ($attrs, $text); } # Make level two headings bold, overriding any existing formatting. sub cmd_head2 { - my ($self, $text, $line) = @_; + my ($self, $attrs, $text) = @_; $text =~ s/\s+$//; - $text = $self->strip_format ($self->interpolate ($text, $line)); + $text = $self->strip_format ($text); $text =~ s/(.)/$1\b$1/g; - $self->SUPER::cmd_head2 ($text); + return $self->SUPER::cmd_head2 ($attrs, $text); } # Make level three headings underscored, overriding any existing formatting. sub cmd_head3 { - my ($self, $text, $line) = @_; + my ($self, $attrs, $text) = @_; $text =~ s/\s+$//; - $text = $self->strip_format ($self->interpolate ($text, $line)); + $text = $self->strip_format ($text); $text =~ s/(.)/_\b$1/g; - $self->SUPER::cmd_head3 ($text); + return $self->SUPER::cmd_head3 ($attrs, $text); } # Level four headings look like level three headings. sub cmd_head4 { - my ($self, $text, $line) = @_; + my ($self, $attrs, $text) = @_; $text =~ s/\s+$//; - $text = $self->strip_format ($self->interpolate ($text, $line)); + $text = $self->strip_format ($text); $text =~ s/(.)/_\b$1/g; - $self->SUPER::cmd_head4 ($text); + return $self->SUPER::cmd_head4 ($attrs, $text); } # The common code for handling all headers. We have to override to avoid # interpolating twice and because we don't want to honor alt. sub heading { - my ($self, $text, $line, $indent, $marker) = @_; + my ($self, $text, $indent, $marker) = @_; $self->item ("\n\n") if defined $$self{ITEM}; - $text .= "\n" if $$self{loose}; - my $margin = ' ' x ($$self{margin} + $indent); + $text .= "\n" if $$self{opt_loose}; + my $margin = ' ' x ($$self{opt_margin} + $indent); $self->output ($margin . $text . "\n"); + return ''; } # Fix the various formatting codes. -sub seq_b { local $_ = strip_format (@_); s/(.)/$1\b$1/g; $_ } -sub seq_f { local $_ = strip_format (@_); s/(.)/_\b$1/g; $_ } -sub seq_i { local $_ = strip_format (@_); s/(.)/_\b$1/g; $_ } +sub cmd_b { local $_ = $_[0]->strip_format ($_[2]); s/(.)/$1\b$1/g; $_ } +sub cmd_f { local $_ = $_[0]->strip_format ($_[2]); s/(.)/_\b$1/g; $_ } +sub cmd_i { local $_ = $_[0]->strip_format ($_[2]); s/(.)/_\b$1/g; $_ } # Output any included code in bold. sub output_code { @@ -108,7 +108,7 @@ sub wrap { local $_ = shift; my $output = ''; my $spaces = ' ' x $$self{MARGIN}; - my $width = $$self{width} - $$self{MARGIN}; + my $width = $$self{opt_width} - $$self{MARGIN}; while (length > $width) { # This regex represents a single character, that's possibly underlined # or in bold (in which case, it's three characters; the character, a @@ -123,7 +123,7 @@ sub wrap { } $output .= $spaces . $_; $output =~ s/\s+$/\n\n/; - $output; + return $output; } ############################################################################## @@ -186,7 +186,7 @@ There may be some better approach possible. =head1 SEE ALSO -L, L +L, L The current version of this module is always available from its web site at L. It is also part of the @@ -200,7 +200,7 @@ Joe Smith , using the framework created by Russ Allbery =head1 COPYRIGHT AND LICENSE Copyright 2000 by Joe Smith . -Copyright 2001 by Russ Allbery . +Copyright 2001, 2004 by Russ Allbery . This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Pod/Text/Termcap.pm b/lib/Pod/Text/Termcap.pm index 02a7fb9..f24e4ee 100644 --- a/lib/Pod/Text/Termcap.pm +++ b/lib/Pod/Text/Termcap.pm @@ -1,7 +1,7 @@ # Pod::Text::Termcap -- Convert POD data to ASCII text with format escapes. -# $Id: Termcap.pm,v 1.11 2003/07/09 21:52:30 eagle Exp $ +# $Id: Termcap.pm,v 2.1 2004/12/31 21:50:00 eagle Exp $ # -# Copyright 1999, 2001, 2002 by Russ Allbery +# Copyright 1999, 2001, 2002, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -30,8 +30,7 @@ use vars qw(@ISA $VERSION); # Don't use the CVS revision as the version, since this module is also in Perl # core and too many things could munge CVS magic revision strings. This # number should ideally be the same as the CVS revision in podlators, however. -$VERSION = 1.11; - +$VERSION = 2.01; ############################################################################## # Overrides @@ -39,9 +38,10 @@ $VERSION = 1.11; # In the initialization method, grab our terminal characteristics as well as # do all the stuff we normally do. -sub initialize { - my $self = shift; +sub new { + my ($self, @args) = @_; my ($ospeed, $term, $termios); + $self = $self->SUPER::new (@args); # $ENV{HOME} is usually not set on Windows. The default Term::Cap path # may not work on Solaris. @@ -66,32 +66,30 @@ sub initialize { $$self{NORM} = $$term{_me} || "\e[m"; unless (defined $$self{width}) { - $$self{width} = $ENV{COLUMNS} || $$term{_co} || 80; - $$self{width} -= 2; + $$self{opt_width} = $ENV{COLUMNS} || $$term{_co} || 80; + $$self{opt_width} -= 2; } - $self->SUPER::initialize; + return $self; } # Make level one headings bold. sub cmd_head1 { - my $self = shift; - local $_ = shift; - s/\s+$//; - $self->SUPER::cmd_head1 ("$$self{BOLD}$_$$self{NORM}"); + my ($self, $attrs, $text) = @_; + $text =~ s/\s+$//; + $self->SUPER::cmd_head1 ($attrs, "$$self{BOLD}$text$$self{NORM}"); } # Make level two headings bold. sub cmd_head2 { - my $self = shift; - local $_ = shift; - s/\s+$//; - $self->SUPER::cmd_head2 ("$$self{BOLD}$_$$self{NORM}"); + my ($self, $attrs, $text) = @_; + $text =~ s/\s+$//; + $self->SUPER::cmd_head2 ($attrs, "$$self{BOLD}$text$$self{NORM}"); } # Fix up B<> and I<>. Note that we intentionally don't do F<>. -sub seq_b { my $self = shift; return "$$self{BOLD}$_[0]$$self{NORM}" } -sub seq_i { my $self = shift; return "$$self{UNDL}$_[0]$$self{NORM}" } +sub cmd_b { my $self = shift; return "$$self{BOLD}$_[1]$$self{NORM}" } +sub cmd_i { my $self = shift; return "$$self{UNDL}$_[1]$$self{NORM}" } # Output any included code in bold. sub output_code { @@ -105,11 +103,14 @@ sub wrap { local $_ = shift; my $output = ''; my $spaces = ' ' x $$self{MARGIN}; - my $width = $$self{width} - $$self{MARGIN}; - my $code = "(?:\Q$$self{BOLD}\E|\Q$$self{UNDL}\E|\Q$$self{NORM}\E)"; + my $width = $$self{opt_width} - $$self{MARGIN}; + + # $codes matches a single special sequence. $char matches any number of + # special sequences preceeding a single character other than a newline. + my $codes = "(?:\Q$$self{BOLD}\E|\Q$$self{UNDL}\E|\Q$$self{NORM}\E)"; + my $char = "(?:$codes*[^\\n])"; while (length > $width) { - if (s/^((?:$code?[^\n]){0,$width})\s+// - || s/^((?:$code?[^\n]){$width})//) { + if (s/^(${char}{0,$width})\s+// || s/^(${char}{$width})//) { $output .= $spaces . $1 . "\n"; } else { last; @@ -117,10 +118,9 @@ sub wrap { } $output .= $spaces . $_; $output =~ s/\s+$/\n\n/; - $output; + return $output; } - ############################################################################## # Module return value and documentation ############################################################################## @@ -160,7 +160,7 @@ termcap information. =head1 SEE ALSO -L, L, L +L, L, L The current version of this module is always available from its web site at L. It is also part of the @@ -172,7 +172,7 @@ Russ Allbery . =head1 COPYRIGHT AND LICENSE -Copyright 1999, 2001, 2002 by Russ Allbery . +Copyright 1999, 2001, 2002, 2004 by Russ Allbery . This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. diff --git a/lib/Pod/t/basic.cap b/lib/Pod/t/basic.cap index d8f1ae2..20fc1e5 100644 --- a/lib/Pod/t/basic.cap +++ b/lib/Pod/t/basic.cap @@ -30,22 +30,10 @@ Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "manpage/section" - Reference the "section" in "manpage" Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - Now try it using the new "|" stuff ... Reference the thistext| @@ -58,14 +46,8 @@ Reference the thistext| - Reference the thistext | - Reference the thistext| - Reference the thistext| - - Reference the thistext | - And then throw in a few new ones of my own. foo @@ -84,16 +66,10 @@ "baz boo" in foo bar - "baz boo" in foo bar - - "boo" in foo bar baz - "boo var baz" "bar baz" - "boo bar baz / baz boo" - "boo", "bar", and "baz" foobar @@ -207,7 +183,7 @@ doing what you might expect since the first > will still terminate the first < seen. - Lets make sure these work for empty ones too, like and ">>" (just to be + Lets make sure these work for empty ones too, like "" and ">>" (just to be obnoxious) The statement: "This is dog kind's finest hour!" is a parody of a diff --git a/lib/Pod/t/basic.clr b/lib/Pod/t/basic.clr index acda09c..f988571 100644 --- a/lib/Pod/t/basic.clr +++ b/lib/Pod/t/basic.clr @@ -30,22 +30,10 @@ Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "manpage/section" - Reference the "section" in "manpage" Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - Now try it using the new "|" stuff ... Reference the thistext| @@ -58,14 +46,8 @@ Reference the thistext| - Reference the thistext | - Reference the thistext| - Reference the thistext| - - Reference the thistext | - And then throw in a few new ones of my own. foo @@ -84,16 +66,10 @@ "baz boo" in foo bar - "baz boo" in foo bar - - "boo" in foo bar baz - "boo var baz" "bar baz" - "boo bar baz / baz boo" - "boo", "bar", and "baz" foobar @@ -208,8 +184,8 @@ up doing what you might expect since the first > will still terminate the first < seen. - Lets make sure these work for empty ones too, like and ">>" (just to be - obnoxious) + Lets make sure these work for empty ones too, like "" and ">>" (just to + be obnoxious) The statement: "This is dog kind's finest hour!" is a parody of a quotation from Winston Churchill. diff --git a/lib/Pod/t/basic.man b/lib/Pod/t/basic.man index c5d8c14..499e06f 100644 --- a/lib/Pod/t/basic.man +++ b/lib/Pod/t/basic.man @@ -41,22 +41,10 @@ Try out \fI\s-1LOTS\s0\fR of different ways of specifying references: .PP Reference the \*(L"section\*(R" in manpage .PP -Reference the \*(L"section\*(R" in manpage -.PP -Reference the \*(L"section\*(R" in manpage -.PP -Reference the \*(L"section\*(R" in manpage -.PP -Reference the \*(L"manpage/section\*(R" -.PP Reference the \*(L"section\*(R" in \*(L"manpage\*(R" .PP Reference the \*(L"section\*(R" in manpage .PP -Reference the \*(L"section\*(R" in manpage -.PP -Reference the \*(L"section\*(R" in manpage -.PP Now try it using the new \*(L"|\*(R" stuff ... .PP Reference the thistext| @@ -69,14 +57,8 @@ Reference the thistext | .PP Reference the thistext| .PP -Reference the thistext | -.PP -Reference the thistext| -.PP Reference the thistext| .PP -Reference the thistext | -.PP And then throw in a few new ones of my own. .PP foo @@ -95,25 +77,19 @@ foo .PP \&\*(L"baz boo\*(R" in foo bar .PP -\&\*(L"baz boo\*(R" in foo bar -.PP -\&\*(L"boo\*(R" in foo bar baz -.PP \&\*(L"boo var baz\*(R" .PP \&\*(L"bar baz\*(R" .PP -\&\*(L"boo bar baz / baz boo\*(R" -.PP \&\*(L"boo\*(R", \*(L"bar\*(R", and \*(L"baz\*(R" .PP -foo\&bar +foobar .PP Testing \fIitalics\fR .PP "\fIItalic\fR text" in foo .PP -"Section \f(CW\*(C`with\*(C'\fR \fI\f(BIother\fI markup\fR" in foo|bar\& +"Section \f(CW\*(C`with\*(C'\fR \fI\f(BIother\fI markup\fR" in foo|bar .PP Nested .SH "OVER AND ITEMS" @@ -127,8 +103,7 @@ There should be whitespace now before this line. .PP Taken from Pod::Parser tests, this is a test to ensure the nested =item paragraphs get indented appropriately. -.IP "1" 2 -.IX Item "1" +.IP "1." 2 First section. .RS 2 .IP "a" 2 @@ -140,8 +115,7 @@ this is item b .RE .RS 2 .RE -.IP "2" 2 -.IX Item "2" +.IP "2." 2 Second section. .RS 2 .IP "a" 2 @@ -253,7 +227,7 @@ So things like \f(CW\*(C`<$self\-\*(C'\fR\fImethod()\fR>> and \f(CW\*(C`<$self\- up doing what you might expect since the first > will still terminate the first < seen. .PP -Lets make sure these work for empty ones too, like and \f(CW\*(C`>>\*(C'\fR +Lets make sure these work for empty ones too, like \f(CW\*(C`\*(C'\fR and \f(CW\*(C`>>\*(C'\fR (just to be obnoxious) .PP The statement: \f(CW\*(C`This is dog kind's \f(CIfinest\f(CW hour!\*(C'\fR is a parody of a @@ -261,7 +235,7 @@ quotation from Winston Churchill. .PP The following tests are added to those: .PP -Make sure that a few oth\&er odd \fI\&things\fR still work. This should be +Make sure that a few other odd \fIthings\fR still work. This should be a vertical bar: |. Here's a test of a few more special escapes that have to be supported: .IP "&" 3 @@ -280,7 +254,7 @@ A forward slash. Try to get this bit of text over towards the edge so |that\ all\ of\ this\ text\ inside\ S<>\ won't| be wrapped. Also test the |same\ thing\ with\ non-breaking\ spaces.| .PP -There is a soft hyphen in hyphen at hy\-phen. +There is a soft hy\%phen in hyphen at hy\-phen. .PP This is a test of an index entry. .IX Xref "index entry" @@ -297,9 +271,7 @@ Throw in a few verbatim paragraphs. \& print colored ("Yellow on magenta.\en", 'yellow on_magenta'); \& print "This text is normal.\en"; \& print colored ['yellow on_magenta'], "Yellow on magenta.\en"; -.Ve -.PP -.Vb 2 +\& \& use Term::ANSIColor qw(uncolor); \& print uncolor '01;31', "\en"; .Ve @@ -310,9 +282,7 @@ paragraph is again: .Vb 2 \& use Term::ANSIColor qw(:constants); \& print BOLD, BLUE, "This text is in bold blue.\en", RESET; -.Ve -.PP -.Vb 1 +\& \& use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; print BOLD BLUE "This text is in bold blue.\en"; print "This text is normal.\en"; .Ve .PP @@ -332,7 +302,7 @@ This isn't. .PP .Vb 2 \& This is. And this: is an internal tab. It should be: -\& |--| <= lined up with that. +\& |\-\-| <= lined up with that. .Ve .PP (Tricky, but tabs should be expanded before the translator starts in on diff --git a/lib/Pod/t/basic.ovr b/lib/Pod/t/basic.ovr index d762930..bb124a0 100644 --- a/lib/Pod/t/basic.ovr +++ b/lib/Pod/t/basic.ovr @@ -30,22 +30,10 @@ LLIINNKKSS Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "manpage/section" - Reference the "section" in "manpage" Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - Now try it using the new "|" stuff ... Reference the thistext| @@ -58,14 +46,8 @@ LLIINNKKSS Reference the thistext| - Reference the thistext | - Reference the thistext| - Reference the thistext| - - Reference the thistext | - And then throw in a few new ones of my own. foo @@ -84,16 +66,10 @@ LLIINNKKSS "baz boo" in foo bar - "baz boo" in foo bar - - "boo" in foo bar baz - "boo var baz" "bar baz" - "boo bar baz / baz boo" - "boo", "bar", and "baz" foobar @@ -208,8 +184,8 @@ FFOORRMMAATTTTIINNGG  CCOODDEESS up doing what you might expect since the first > will still terminate the first < seen. - Lets make sure these work for empty ones too, like and ">>" (just to be - obnoxious) + Lets make sure these work for empty ones too, like "" and ">>" (just to + be obnoxious) The statement: "This is dog kind's _f_i_n_e_s_t hour!" is a parody of a quotation from Winston Churchill. diff --git a/lib/Pod/t/basic.pod b/lib/Pod/t/basic.pod index 03e2a22..949b3a8 100644 --- a/lib/Pod/t/basic.pod +++ b/lib/Pod/t/basic.pod @@ -41,24 +41,10 @@ Try out I of different ways of specifying references: Reference the L -Reference the L - -Reference the L - -Reference the L - -Reference the L<"manpage/section"> - Reference the L<"manpage"/section> Reference the L -Reference the L - -Reference the L - Now try it using the new "|" stuff ... Reference the L| @@ -69,22 +55,12 @@ Reference the L| Reference the L| -Reference the L| - -Reference the L| - Reference the L| Reference the L| -Reference the L| - And then throw in a few new ones of my own. L @@ -103,20 +79,10 @@ L L -L - -L - L<"boo var baz"> L -L<"boo bar baz / baz boo"> - L, L, and L Lbar> diff --git a/lib/Pod/t/basic.t b/lib/Pod/t/basic.t index 984e720..6a70f7c 100644 --- a/lib/Pod/t/basic.t +++ b/lib/Pod/t/basic.t @@ -1,9 +1,9 @@ #!/usr/bin/perl -w -# $Id: basic.t,v 1.4 2002/01/28 02:56:19 eagle Exp $ +# $Id: basic.t,v 1.8 2004/12/31 21:27:58 eagle Exp $ # # basic.t -- Basic tests for podlators. # -# Copyright 2001 by Russ Allbery +# Copyright 2001, 2002, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -16,11 +16,6 @@ BEGIN { unshift (@INC, '../blib/lib'); } unshift (@INC, '../blib/lib'); - require Config; - if (($Config::Config{'extensions'} !~ /\bPOSIX\b/) ){ - print "1..0 # Skip -- Perl configured without POSIX module\n"; - exit 0; - } $| = 1; print "1..11\n"; } @@ -31,7 +26,6 @@ END { use Pod::Man; use Pod::Text; -use Pod::Text::Color; use Pod::Text::Overstrike; use Pod::Text::Termcap; @@ -70,6 +64,17 @@ my %translators = ('Pod::Man' => 'man', my $n = 2; for (sort keys %translators) { + if ($_ eq 'Pod::Text::Color') { + eval { require Term::ANSIColor }; + if ($@) { + print "ok $n # skip\n"; + $n++; + print "ok $n # skip\n"; + $n++; + next; + } + require Pod::Text::Color; + } my $parser = $_->new (%options); print (($parser && ref ($parser) eq $_) ? "ok $n\n" : "not ok $n\n"); $n++; @@ -77,8 +82,9 @@ for (sort keys %translators) { # For Pod::Man, strip out the autogenerated header up to the .TH title # line. That means that we don't check those things; oh well. The header # changes with each version change or touch of the input file. + $parser->parse_from_file (source_path ('basic.pod'), 'out.tmp'); + undef $parser; if ($_ eq 'Pod::Man') { - $parser->parse_from_file (source_path ('basic.pod'), 'out.tmp'); open (TMP, 'out.tmp') or die "Cannot open out.tmp: $!\n"; open (OUTPUT, "> out.$translators{$_}") or die "Cannot create out.$translators{$_}: $!\n"; @@ -89,8 +95,8 @@ for (sort keys %translators) { close TMP; unlink 'out.tmp'; } else { - my $basic = source_path ('basic.pod'); - $parser->parse_from_file ($basic, "out.$translators{$_}"); + rename ('out.tmp', "out.$translators{$_}") + or die "Cannot rename out.tmp: $!\n"; } { local $/; diff --git a/lib/Pod/t/basic.txt b/lib/Pod/t/basic.txt index f2fae9d..986e98a 100644 --- a/lib/Pod/t/basic.txt +++ b/lib/Pod/t/basic.txt @@ -30,22 +30,10 @@ LINKS Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "section" in manpage - - Reference the "manpage/section" - Reference the "section" in "manpage" Reference the "section" in manpage - Reference the "section" in manpage - - Reference the "section" in manpage - Now try it using the new "|" stuff ... Reference the thistext| @@ -58,14 +46,8 @@ LINKS Reference the thistext| - Reference the thistext | - Reference the thistext| - Reference the thistext| - - Reference the thistext | - And then throw in a few new ones of my own. foo @@ -84,16 +66,10 @@ LINKS "baz boo" in foo bar - "baz boo" in foo bar - - "boo" in foo bar baz - "boo var baz" "bar baz" - "boo bar baz / baz boo" - "boo", "bar", and "baz" foobar @@ -208,8 +184,8 @@ FORMATTING CODES up doing what you might expect since the first > will still terminate the first < seen. - Lets make sure these work for empty ones too, like and ">>" (just to be - obnoxious) + Lets make sure these work for empty ones too, like "" and ">>" (just to + be obnoxious) The statement: "This is dog kind's *finest* hour!" is a parody of a quotation from Winston Churchill. diff --git a/lib/Pod/t/color.t b/lib/Pod/t/color.t new file mode 100755 index 0000000..5214647 --- /dev/null +++ b/lib/Pod/t/color.t @@ -0,0 +1,88 @@ +#!/usr/bin/perl -w +# $Id: color.t,v 1.1 2004/12/31 21:50:05 eagle Exp $ +# +# color.t -- Additional specialized tests for Pod::Text::Color. +# +# Copyright 2002, 2004 by Russ Allbery +# +# This program is free software; you may redistribute it and/or modify it +# under the same terms as Perl itself. + +BEGIN { + chdir 't' if -d 't'; + if ($ENV{PERL_CORE}) { + @INC = '../lib'; + } else { + unshift (@INC, '../blib/lib'); + } + unshift (@INC, '../blib/lib'); + $| = 1; + print "1..2\n"; +} + +END { + print "not ok 1\n" unless $loaded; +} + +eval { require Term::ANSIColor }; +if ($@) { + for (1..2) { + print "ok $_ # skip\n"; + } + $loaded = 1; + exit; +} +require Pod::Text::Color; + +$loaded = 1; +print "ok 1\n"; + +my $n = 2; +while () { + next until $_ eq "###\n"; + open (TMP, '> tmp.pod') or die "Cannot create tmp.pod: $!\n"; + while () { + last if $_ eq "###\n"; + print TMP $_; + } + close TMP; + my $parser = Pod::Text::Color->new or die "Cannot create parser\n"; + $parser->parse_from_file ('tmp.pod', 'out.tmp'); + undef $parser; + open (TMP, 'out.tmp') or die "Cannot open out.tmp: $!\n"; + my $output; + { + local $/; + $output = ; + } + close TMP; + unlink ('tmp.pod', 'out.tmp'); + my $expected = ''; + while () { + last if $_ eq "###\n"; + $expected .= $_; + } + if ($output eq $expected) { + print "ok $n\n"; + } else { + print "not ok $n\n"; + print "Expected\n========\n$expected\nOutput\n======\n$output\n"; + } + $n++; +} + +# Below the marker are bits of POD and corresponding expected output. This is +# used to test specific features or problems with Pod::Text::Termcap. The +# input and output are separated by lines containing only ###. + +__DATA__ + +### +=head1 WRAPPING + +B> I> B> B> B>. +### +WRAPPING + Do not include formatting codes when wrapping. + +### diff --git a/lib/Pod/t/man.t b/lib/Pod/t/man.t index f43f32a..a4fc58e 100644 --- a/lib/Pod/t/man.t +++ b/lib/Pod/t/man.t @@ -1,9 +1,9 @@ #!/usr/bin/perl -w -# $Id: man.t,v 1.4 2003/01/05 06:31:52 eagle Exp $ +# $Id: man.t,v 1.5 2004/02/15 06:42:49 eagle Exp $ # # man.t -- Additional specialized tests for Pod::Man. # -# Copyright 2002, 2003 by Russ Allbery +# Copyright 2002, 2003, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -17,7 +17,7 @@ BEGIN { } unshift (@INC, '../blib/lib'); $| = 1; - print "1..5\n"; + print "1..21\n"; } END { @@ -40,14 +40,15 @@ while () { close TMP; my $parser = Pod::Man->new or die "Cannot create parser\n"; $parser->parse_from_file ('tmp.pod', 'out.tmp'); - open (TMP, 'out.tmp') or die "Cannot open out.tmp: $!\n"; - while () { last if /^\.TH/ } + undef $parser; + open (OUT, 'out.tmp') or die "Cannot open out.tmp: $!\n"; + while () { last if /^\.TH/ } my $output; { local $/; - $output = ; + $output = ; } - close TMP; + close OUT; unlink ('tmp.pod', 'out.tmp'); my $expected = ''; while () { @@ -106,7 +107,7 @@ A bullet. Another bullet. -=item * Not a bullet. +=item * Also a bullet. =back ### @@ -114,8 +115,8 @@ Another bullet. A bullet. .IP "\(bu" 4 Another bullet. -.IP "* Not a bullet." 4 -.IX Item "Not a bullet." +.IP "\(bu" 4 +Also a bullet. ### ### @@ -137,3 +138,275 @@ Not a bullet. .IP "*" 4 Also not a bullet. ### + +### +=head1 ACCENTS + +Beyoncé! Beyoncé! Beyoncé!! + + Beyoncé! Beyoncé! + Beyoncé! Beyoncé! + Beyoncé! Beyoncé! + +Older versions didn't convert Beyoncé in verbatim. +### +.SH "ACCENTS" +.IX Header "ACCENTS" +Beyonce\*'! Beyonce\*'! Beyonce\*'!! +.PP +.Vb 3 +\& Beyonce\*'! Beyonce\*'! +\& Beyonce\*'! Beyonce\*'! +\& Beyonce\*'! Beyonce\*'! +.Ve +.PP +Older versions didn't convert Beyonce\*' in verbatim. +### + +### +=over 4 + +=item 1. Not a number + +=item 2. Spaced right + +=back + +=over 2 + +=item 1 Not a number + +=item 2 Spaced right + +=back +### +.IP "1. Not a number" 4 +.IX Item "1. Not a number" +.PD 0 +.IP "2. Spaced right" 4 +.IX Item "2. Spaced right" +.IP "1 Not a number" 2 +.IX Item "1 Not a number" +.IP "2 Spaced right" 2 +.IX Item "2 Spaced right" +### + +### +=over 4 + +=item Z<>* + +Not bullet. + +=back +### +.IP "*" 4 +Not bullet. +### + +### +=head1 SEQS + +"=over ... Z<>=back" + +"SE...E" + +The quotes should be converted in the above to paired quotes. +### +.SH "SEQS" +.IX Header "SEQS" +\&\*(L"=over ... =back\*(R" +.PP +\&\*(L"S<...>\*(R" +.PP +The quotes should be converted in the above to paired quotes. +### + +### +=head1 YEN + +It cost me E<165>12345! That should be an X. +### +.SH "YEN" +.IX Header "YEN" +It cost me X12345! That should be an X. +### + +### +=head1 agrave + +Open E la shell. Previous versions mapped it wrong. +### +.SH "agrave" +.IX Header "agrave" +Open a\*` la shell. Previous versions mapped it wrong. +### + +### +=over + +=item First level + +Blah blah blah.... + +=over + +=item * + +Should be a bullet. + +=back + +=back +### +.IP "First level" 4 +.IX Item "First level" +Blah blah blah.... +.RS 4 +.IP "\(bu" 4 +Should be a bullet. +.RE +.RS 4 +.RE +### + +### +=over 4 + +=item 1. Check fonts in @CARP_NOT test. + +=back +### +.ie n .IP "1. Check fonts in @CARP_NOT test." 4 +.el .IP "1. Check fonts in \f(CW@CARP_NOT\fR test." 4 +.IX Item "1. Check fonts in @CARP_NOT test." +### + +### +=head1 LINK QUOTING + +There should not be double quotes: Lpattern) >>>. +### +.SH "LINK QUOTING" +.IX Header "LINK QUOTING" +There should not be double quotes: \f(CW\*(C`(?>pattern)\*(C'\fR. +### + +### +=head1 SEE MAGIC + +Magic should be applied S to that. +### +.SH "S<> MAGIC" +.IX Header "S<> MAGIC" +Magic should be applied \s-1RISC\s0\ \s-1OS\s0 to that. +### + +### +=head1 MAGIC MONEY + +These should be identical. + +Bippity boppity boo "The +price is $Z<>100." + +Bippity boppity boo "The +price is $100." +### +.SH "MAGIC MONEY" +.IX Header "MAGIC MONEY" +These should be identical. +.PP +Bippity boppity boo \*(L"The +price is \f(CW$100\fR.\*(R" +.PP +Bippity boppity boo \*(L"The +price is \f(CW$100\fR.\*(R" +### + +### +=head1 NAME + +"Stuff" (no guesswork) + +=head2 THINGS + +Oboy, is this C++ "fun" yet! (guesswork) +### +.SH "NAME" +"Stuff" (no guesswork) +.Sh "\s-1THINGS\s0" +.IX Subsection "THINGS" +Oboy, is this \*(C+ \*(L"fun\*(R" yet! (guesswork) +### + +### +=head1 Newline C Quote Weirdness + +Blorp C<' +''>. Yes. +### +.SH "Newline C Quote Weirdness" +.IX Header "Newline C Quote Weirdness" +Blorp \f(CW' +\&''\fR. Yes. +### + +### +=head1 Soft Hypen Testing + +sigEaction +manuEscript +JarkEko HieEtaEnieEmi + +And again: + +sigE<173>action +manuE<173>script +JarkE<173>ko HieE<173>taE<173>nieE<173>mi + +And one more time: + +sigE<0x00AD>action +manuE<0x00AD>script +JarkE<0x00AD>ko HieE<0x00AD>taE<0x00AD>nieE<0x00AD>mi +### +.SH "Soft Hypen Testing" +.IX Header "Soft Hypen Testing" +sig\%action +manu\%script +Jark\%ko Hie\%ta\%nie\%mi +.PP +And again: +.PP +sig\%action +manu\%script +Jark\%ko Hie\%ta\%nie\%mi +.PP +And one more time: +.PP +sig\%action +manu\%script +Jark\%ko Hie\%ta\%nie\%mi +### + +### +=head1 XEE Whitespace + +Blorpy L|blap> X wugga chachacha. +### +.SH "X<> Whitespace" +.IX Header "X<> Whitespace" +Blorpy \fBprok\fR wugga chachacha. +.IX Xref "bivav" +### + +### +=head1 Hyphen in SEE + +Don't S. +### +.SH "Hyphen in S<>" +.IX Header "Hyphen in S<>" +Don't transform\ even-this\ hyphen. +### diff --git a/lib/Pod/t/termcap.t b/lib/Pod/t/termcap.t new file mode 100755 index 0000000..f5e5b39 --- /dev/null +++ b/lib/Pod/t/termcap.t @@ -0,0 +1,85 @@ +#!/usr/bin/perl -w +# $Id: termcap.t,v 1.2 2005/11/28 23:38:02 eagle Exp $ +# +# termcap.t -- Additional specialized tests for Pod::Text::Termcap. +# +# Copyright 2002, 2004 by Russ Allbery +# +# This program is free software; you may redistribute it and/or modify it +# under the same terms as Perl itself. + +BEGIN { + chdir 't' if -d 't'; + if ($ENV{PERL_CORE}) { + @INC = '../lib'; + } else { + unshift (@INC, '../blib/lib'); + } + unshift (@INC, '../blib/lib'); + $| = 1; + print "1..2\n"; +} + +END { + print "not ok 1\n" unless $loaded; +} + +# Hard-code a few values to try to get reproducible results. +$ENV{COLUMNS} = 80; +$ENV{TERM} = 'xterm'; +$ENV{TERMCAP} = 'xterm:co=80:do=^J:md=\E[1m:us=\E[4m:me=\E[m'; + +use Pod::Text::Termcap; + +$loaded = 1; +print "ok 1\n"; + +my $n = 2; +while () { + next until $_ eq "###\n"; + open (TMP, '> tmp.pod') or die "Cannot create tmp.pod: $!\n"; + while () { + last if $_ eq "###\n"; + print TMP $_; + } + close TMP; + my $parser = Pod::Text::Termcap->new or die "Cannot create parser\n"; + $parser->parse_from_file ('tmp.pod', 'out.tmp'); + undef $parser; + open (TMP, 'out.tmp') or die "Cannot open out.tmp: $!\n"; + my $output; + { + local $/; + $output = ; + } + close TMP; + unlink ('tmp.pod', 'out.tmp'); + my $expected = ''; + while () { + last if $_ eq "###\n"; + $expected .= $_; + } + if ($output eq $expected) { + print "ok $n\n"; + } else { + print "not ok $n\n"; + print "Expected\n========\n$expected\nOutput\n======\n$output\n"; + } + $n++; +} + +# Below the marker are bits of POD and corresponding expected output. This is +# used to test specific features or problems with Pod::Text::Termcap. The +# input and output are separated by lines containing only ###. + +__DATA__ + +### +=head1 WRAPPING + +B> I> B> B> B>. +### +WRAPPING + Do not include formatting codes when wrapping. + +### diff --git a/lib/Pod/t/text-errors.t b/lib/Pod/t/text-errors.t deleted file mode 100644 index 48d6c39..0000000 --- a/lib/Pod/t/text-errors.t +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/perl -w -# $Id: text-errors.t,v 1.1 2002/01/01 02:41:53 eagle Exp $ -# -# texterrs.t -- Error tests for Pod::Text. -# -# Copyright 2001 by Russ Allbery -# -# This program is free software; you may redistribute it and/or modify it -# under the same terms as Perl itself. - -BEGIN { - chdir 't' if -d 't'; - if ($ENV{PERL_CORE}) { - @INC = '../lib'; - } else { - unshift (@INC, '../blib/lib'); - } - unshift (@INC, '../blib/lib'); - $| = 1; - print "1..5\n"; -} - -END { - print "not ok 1\n" unless $loaded; -} - -use Pod::Text; - -$loaded = 1; -print "ok 1\n"; - -# Hard-code a few values to try to get reproducible results. -$ENV{COLUMNS} = 80; -$ENV{TERM} = 'xterm'; -$ENV{TERMCAP} = 'xterm:co=80:do=^J:md=\E[1m:us=\E[4m:me=\E[m'; - -# Set default options to match those of pod2man and pod2text. -my %options = (sentence => 0); - -# Capture warnings for inspection. -my $warnings = ''; -$SIG{__WARN__} = sub { $warnings .= $_[0] }; - -# Run a single test, given some POD to parse and the warning messages that are -# expected. Any formatted output is ignored; only warning messages are -# checked. Writes the POD to a temporary file since that's the easiest way to -# interact with Pod::Parser. -sub test_error { - my ($pod, $expected) = @_; - open (TMP, '> tmp.pod') or die "Cannot create tmp.pod: $!\n"; - print TMP $pod; - close TMP; - my $parser = Pod::Text->new (%options); - return unless $parser; - $warnings = ''; - $parser->parse_from_file ('tmp.pod', 'out.tmp'); - unlink ('tmp.pod', 'out.tmp'); - if ($warnings eq $expected) { - return 1; - } else { - print " # '$warnings'\n # '$expected'\n"; - return 0; - } -} - -# The actual tests. -my @tests = ( - [ "=head1 a E<0x2028> b\n" - => "tmp.pod:1: Unknown escape: E<0x2028>\n" ], - [ "=head1 a Y<0x2028> b\n" - => "tmp.pod:1: Unknown formatting code: Y<0x2028>\n" ], - [ "=head1 TEST\n\n=command args\n" - => "tmp.pod:3: Unknown command paragraph: =command args\n" ], - [ "=head1 TEST\n\n Foo bar\n\n=back\n" - => "tmp.pod:5: Unmatched =back\n" ] -); -my $n = 2; -for (@tests) { - print (test_error ($$_[0], $$_[1]) ? "ok $n\n" : "not ok $n\n"); - $n++; -} diff --git a/lib/Pod/t/text-options.t b/lib/Pod/t/text-options.t index b398fcf..6fadd29 100644 --- a/lib/Pod/t/text-options.t +++ b/lib/Pod/t/text-options.t @@ -1,9 +1,9 @@ #!/usr/bin/perl -w -# $Id: text-options.t,v 1.2 2002/08/04 03:38:24 eagle Exp $ +# $Id: text-options.t,v 1.4 2004/12/31 21:29:34 eagle Exp $ # # text-options.t -- Additional tests for Pod::Text options. # -# Copyright 2002 by Russ Allbery +# Copyright 2002, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -17,7 +17,7 @@ BEGIN { } unshift (@INC, '../blib/lib'); $| = 1; - print "1..3\n"; + print "1..5\n"; } END { @@ -46,6 +46,7 @@ while () { close TMP; my $parser = Pod::Text->new (%options) or die "Cannot create parser\n"; $parser->parse_from_file ('tmp.pod', 'out.tmp'); + undef $parser; open (TMP, 'out.tmp') or die "Cannot open out.tmp: $!\n"; my $output; { @@ -142,3 +143,49 @@ This is another indented paragraph. This is another indented paragraph. ### + +### +code 1 +### +This is some random text. +This is more random text. + +This is some random text. +This is more random text. + +=head1 SAMPLE + +This is POD. + +=cut + +This is more random text. +### +This is some random text. +This is more random text. + +This is some random text. +This is more random text. + +SAMPLE + This is POD. + + +This is more random text. +### + +### +sentence 1 +### +=head1 EXAMPLE + +Whitespace around C<< this. >> must be ignored per perlpodspec. >> +needs to eat all of the space in front of it. + +=cut +### +EXAMPLE + Whitespace around "this." must be ignored per perlpodspec. >> needs to + eat all of the space in front of it. + +### diff --git a/lib/Pod/t/text.t b/lib/Pod/t/text.t index dc8579a..ad39b65 100644 --- a/lib/Pod/t/text.t +++ b/lib/Pod/t/text.t @@ -1,9 +1,9 @@ #!/usr/bin/perl -w -# $Id: text.t,v 1.1 2002/06/23 19:16:25 eagle Exp $ +# $Id: text.t,v 1.3 2004/12/31 21:29:48 eagle Exp $ # # text.t -- Additional specialized tests for Pod::Text. # -# Copyright 2002 by Russ Allbery +# Copyright 2002, 2004 by Russ Allbery # # This program is free software; you may redistribute it and/or modify it # under the same terms as Perl itself. @@ -17,7 +17,7 @@ BEGIN { } unshift (@INC, '../blib/lib'); $| = 1; - print "1..2\n"; + print "1..3\n"; } END { @@ -40,6 +40,7 @@ while () { close TMP; my $parser = Pod::Text->new or die "Cannot create parser\n"; $parser->parse_from_file ('tmp.pod', 'out.tmp'); + undef $parser; open (TMP, 'out.tmp') or die "Cannot open out.tmp: $!\n"; my $output; { @@ -77,3 +78,13 @@ PERIODS This "." should be quoted. ### + +### +=head1 CEE WITH SPACES + +What does C<< this. >> end up looking like? +### +C<> WITH SPACES + What does "this." end up looking like? + +### diff --git a/pod/pod2man.PL b/pod/pod2man.PL index b1b1a55..5a78c01 100644 --- a/pod/pod2man.PL +++ b/pod/pod2man.PL @@ -36,7 +36,7 @@ $Config{startperl} print OUT <<'!NO!SUBS!'; # pod2man -- Convert POD data to formatted *roff input. -# $Id: pod2man.PL,v 1.10 2002/07/15 05:45:56 eagle Exp $ +# $Id: pod2man.PL,v 1.14 2004/12/31 20:39:30 eagle Exp $ # # Copyright 1999, 2000, 2001 by Russ Allbery # @@ -55,8 +55,7 @@ use strict; use vars qw($running_under_some_shell); # Insert -- into @ARGV before any single dash argument to hide it from -# Getopt::Long; we want to interpret it as meaning stdin (which Pod::Parser -# does correctly). +# Getopt::Long; we want to interpret it as meaning stdin. my $stdin; @ARGV = map { $_ eq '-' && !$stdin++ ? ('--', $_) : $_ } @ARGV; @@ -85,9 +84,9 @@ delete $options{lax}; # Initialize and run the formatter, pulling a pair of input and output off at # a time. -my $parser = Pod::Man->new (%options); my @files; do { + my $parser = Pod::Man->new (%options); @files = splice (@ARGV, 0, 2); print " $files[1]\n" if $verbose; $parser->parse_from_file (@files); @@ -101,7 +100,7 @@ pod2man - Convert POD data to formatted *roff input =head1 SYNOPSIS -pod2man [B<--section>=I] [B<--release>=I] +pod2man [B<--section>=I] [B<--release>[=I]] [B<--center>=I] [B<--date>=I] [B<--fixed>=I] [B<--fixedbold>=I] [B<--fixeditalic>=I] [B<--fixedbolditalic>=I] [B<--name>=I] [B<--official>] @@ -252,7 +251,7 @@ Print out the name of each output file as it is being generated. =head1 DIAGNOSTICS -If B fails with errors, see L and L for +If B fails with errors, see L and L for information about what those errors might mean. =head1 EXAMPLES @@ -442,20 +441,6 @@ Bugs you don't plan to fix. :-) Miscellaneous commentary. -=item SEE ALSO - -Other man pages to check out, like man(1), man(7), makewhatis(8), or -catman(8). Normally a simple list of man pages separated by commas, or a -paragraph giving the name of a reference work. Man page references, if they -use the standard C form, don't have to be enclosed in -LEE (although it's recommended), but other things in this section -probably should be when appropriate. - -If the package has a mailing list, include a URL or subscription -instructions here. - -If the package has a web site, include a URL here. - =item AUTHOR Who wrote it (use AUTHORS for multiple people). Including your current @@ -464,6 +449,12 @@ so that users have a way of contacting you is a good idea. Remember that program documentation tends to roam the wild for far longer than you expect and pick an e-mail address that's likely to last if possible. +=item HISTORY + +Programs derived from other sources sometimes have this, or you might keep +a modification log here. If the log gets overly long or detailed, +consider maintaining it in a separate file, though. + =item COPYRIGHT AND LICENSE For copyright @@ -481,11 +472,19 @@ This makes it easy for people to use your module with Perl. Note that this licensing is neither an endorsement or a requirement, you are of course free to choose any licensing. -=item HISTORY +=item SEE ALSO -Programs derived from other sources sometimes have this, or you might keep -a modification log here. If the log gets overly long or detailed, -consider maintaining it in a separate file, though. +Other man pages to check out, like man(1), man(7), makewhatis(8), or +catman(8). Normally a simple list of man pages separated by commas, or a +paragraph giving the name of a reference work. Man page references, if they +use the standard C form, don't have to be enclosed in +LEE (although it's recommended), but other things in this section +probably should be when appropriate. + +If the package has a mailing list, include a URL or subscription +instructions here. + +If the package has a web site, include a URL here. =back @@ -511,7 +510,7 @@ function names, man page references, and the like unadorned by markup and the POD translators will figure it out for you. This makes it much easier to later edit the documentation. Note that many existing translators (including this one currently) will do the wrong thing with e-mail addresses -or URLs when wrapped in LEE, so don't do that. +when wrapped in LEE, so don't do that. For additional information that may be more accurate for your specific system, see either L or L depending on your system manual @@ -519,7 +518,7 @@ section numbering conventions. =head1 SEE ALSO -L, L, L, L, L, +L, L, L, L, L, L, L The man page documenting the an macro set may be L instead of diff --git a/pod/pod2text.PL b/pod/pod2text.PL index 0486e2d..785a3f3 100644 --- a/pod/pod2text.PL +++ b/pod/pod2text.PL @@ -67,7 +67,7 @@ for (my $i = 0; $i < @ARGV; $i++) { } # Insert -- into @ARGV before any single dash argument to hide it from -# Getopt::Long; we want to interpret it as meaning stdin (which Pod::Parser +# Getopt::Long; we want to interpret it as meaning stdin (which Pod::Simple # does correctly). my $stdin; @ARGV = map { $_ eq '-' && !$stdin++ ? ('--', $_) : $_ } @ARGV; @@ -99,8 +99,12 @@ if ($options{color}) { delete @options{'color', 'termcap', 'overstrike'}; # Initialize and run the formatter. -my $parser = $formatter->new (%options); -$parser->parse_from_file (@ARGV); +do { + my $parser = $formatter->new (%options); + my ($input, $output) = splice (@ARGV, 0, 2); + $parser->parse_file ($input, $output); + undef $parser; +} while (@ARGV); __END__ @@ -111,7 +115,7 @@ pod2text - Convert POD data to formatted ASCII text =head1 SYNOPSIS pod2text [B<-aclost>] [B<--code>] [B<-i> I] S<[B<-q> I]> -S<[B<-w> I]> [I [I]] +S<[B<-w> I]> [I [I ...]] pod2text B<-h> @@ -124,7 +128,10 @@ either termcap sequences or ANSI color escape sequences to format the text. I is the file to read for POD source (the POD can be embedded in code). If I isn't given, it defaults to STDIN. I, if given, is the file to which to write the formatted output. If I isn't -given, the formatted output is written to STDOUT. +given, the formatted output is written to STDOUT. Several POD files can be +processed in the same B invocation (saving module load and compile +times) by providing multiple pairs of I and I files on the +command line. =head1 OPTIONS @@ -213,7 +220,7 @@ your terminal device. =head1 DIAGNOSTICS -If B fails with errors, see L and L for +If B fails with errors, see L and L for information about what those errors might mean. Internally, it can also produce the following diagnostics: @@ -230,8 +237,8 @@ loaded. =back -In addition, other L error messages may result -from invalid command-line options. +In addition, other L error messages may result from invalid +command-line options. =head1 ENVIRONMENT @@ -254,7 +261,7 @@ current terminal device. =head1 SEE ALSO L, L, L, -L, L +L, L The current version of this script is always available from its web site at L. It is also part of the @@ -266,7 +273,7 @@ Russ Allbery . =head1 COPYRIGHT AND LICENSE -Copyright 1999, 2000, 2001 by Russ Allbery . +Copyright 1999, 2000, 2001, 2004 by Russ Allbery . This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.