xref: /openbsd-src/gnu/usr.bin/perl/cpan/podlators/lib/Pod/Text.pm (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1# Pod::Text -- Convert POD data to formatted ASCII text.
2#
3# This module converts POD to formatted text.  It replaces the old Pod::Text
4# module that came with versions of Perl prior to 5.6.0 and attempts to match
5# its output except for some specific circumstances where other decisions
6# seemed to produce better output.  It uses Pod::Parser and is designed to be
7# very easy to subclass.
8#
9# Perl core hackers, please note that this module is also separately
10# maintained outside of the Perl core as part of the podlators.  Please send
11# me any patches at the address above in addition to sending them to the
12# standard Perl mailing lists.
13#
14# Copyright 1999, 2000, 2001, 2002, 2004, 2006, 2008, 2009, 2012, 2013
15#     Russ Allbery <rra@stanford.edu>
16#
17# This program is free software; you may redistribute it and/or modify it
18# under the same terms as Perl itself.
19
20##############################################################################
21# Modules and declarations
22##############################################################################
23
24package Pod::Text;
25
26require 5.004;
27
28use strict;
29use vars qw(@ISA @EXPORT %ESCAPES $VERSION);
30
31use Carp qw(carp croak);
32use Encode qw(encode);
33use Exporter ();
34use Pod::Simple ();
35
36@ISA = qw(Pod::Simple Exporter);
37
38# We have to export pod2text for backward compatibility.
39@EXPORT = qw(pod2text);
40
41$VERSION = '3.17';
42
43##############################################################################
44# Initialization
45##############################################################################
46
47# This function handles code blocks.  It's registered as a callback to
48# Pod::Simple and therefore doesn't work as a regular method call, but all it
49# does is call output_code with the line.
50sub handle_code {
51    my ($line, $number, $parser) = @_;
52    $parser->output_code ($line . "\n");
53}
54
55# Initialize the object and set various Pod::Simple options that we need.
56# Here, we also process any additional options passed to the constructor or
57# set up defaults if none were given.  Note that all internal object keys are
58# in all-caps, reserving all lower-case object keys for Pod::Simple and user
59# arguments.
60sub new {
61    my $class = shift;
62    my $self = $class->SUPER::new;
63
64    # Tell Pod::Simple to handle S<> by automatically inserting &nbsp;.
65    $self->nbsp_for_S (1);
66
67    # Tell Pod::Simple to keep whitespace whenever possible.
68    if ($self->can ('preserve_whitespace')) {
69        $self->preserve_whitespace (1);
70    } else {
71        $self->fullstop_space_harden (1);
72    }
73
74    # The =for and =begin targets that we accept.
75    $self->accept_targets (qw/text TEXT/);
76
77    # Ensure that contiguous blocks of code are merged together.  Otherwise,
78    # some of the guesswork heuristics don't work right.
79    $self->merge_text (1);
80
81    # Pod::Simple doesn't do anything useful with our arguments, but we want
82    # to put them in our object as hash keys and values.  This could cause
83    # problems if we ever clash with Pod::Simple's own internal class
84    # variables.
85    my %opts = @_;
86    my @opts = map { ("opt_$_", $opts{$_}) } keys %opts;
87    %$self = (%$self, @opts);
88
89    # Send errors to stderr if requested.
90    if ($$self{opt_stderr} and not $$self{opt_errors}) {
91        $$self{opt_errors} = 'stderr';
92    }
93    delete $$self{opt_stderr};
94
95    # Validate the errors parameter and act on it.
96    if (not defined $$self{opt_errors}) {
97        $$self{opt_errors} = 'pod';
98    }
99    if ($$self{opt_errors} eq 'stderr' || $$self{opt_errors} eq 'die') {
100        $self->no_errata_section (1);
101        $self->complain_stderr (1);
102        if ($$self{opt_errors} eq 'die') {
103            $$self{complain_die} = 1;
104        }
105    } elsif ($$self{opt_errors} eq 'pod') {
106        $self->no_errata_section (0);
107        $self->complain_stderr (0);
108    } elsif ($$self{opt_errors} eq 'none') {
109        $self->no_whining (1);
110    } else {
111        croak (qq(Invalid errors setting: "$$self{errors}"));
112    }
113    delete $$self{errors};
114
115    # Initialize various things from our parameters.
116    $$self{opt_alt}      = 0  unless defined $$self{opt_alt};
117    $$self{opt_indent}   = 4  unless defined $$self{opt_indent};
118    $$self{opt_margin}   = 0  unless defined $$self{opt_margin};
119    $$self{opt_loose}    = 0  unless defined $$self{opt_loose};
120    $$self{opt_sentence} = 0  unless defined $$self{opt_sentence};
121    $$self{opt_width}    = 76 unless defined $$self{opt_width};
122
123    # Figure out what quotes we'll be using for C<> text.
124    $$self{opt_quotes} ||= '"';
125    if ($$self{opt_quotes} eq 'none') {
126        $$self{LQUOTE} = $$self{RQUOTE} = '';
127    } elsif (length ($$self{opt_quotes}) == 1) {
128        $$self{LQUOTE} = $$self{RQUOTE} = $$self{opt_quotes};
129    } elsif ($$self{opt_quotes} =~ /^(.)(.)$/
130             || $$self{opt_quotes} =~ /^(..)(..)$/) {
131        $$self{LQUOTE} = $1;
132        $$self{RQUOTE} = $2;
133    } else {
134        croak qq(Invalid quote specification "$$self{opt_quotes}");
135    }
136
137    # If requested, do something with the non-POD text.
138    $self->code_handler (\&handle_code) if $$self{opt_code};
139
140    # Return the created object.
141    return $self;
142}
143
144##############################################################################
145# Core parsing
146##############################################################################
147
148# This is the glue that connects the code below with Pod::Simple itself.  The
149# goal is to convert the event stream coming from the POD parser into method
150# calls to handlers once the complete content of a tag has been seen.  Each
151# paragraph or POD command will have textual content associated with it, and
152# as soon as all of a paragraph or POD command has been seen, that content
153# will be passed in to the corresponding method for handling that type of
154# object.  The exceptions are handlers for lists, which have opening tag
155# handlers and closing tag handlers that will be called right away.
156#
157# The internal hash key PENDING is used to store the contents of a tag until
158# all of it has been seen.  It holds a stack of open tags, each one
159# represented by a tuple of the attributes hash for the tag and the contents
160# of the tag.
161
162# Add a block of text to the contents of the current node, formatting it
163# according to the current formatting instructions as we do.
164sub _handle_text {
165    my ($self, $text) = @_;
166    my $tag = $$self{PENDING}[-1];
167    $$tag[1] .= $text;
168}
169
170# Given an element name, get the corresponding method name.
171sub method_for_element {
172    my ($self, $element) = @_;
173    $element =~ tr/-/_/;
174    $element =~ tr/A-Z/a-z/;
175    $element =~ tr/_a-z0-9//cd;
176    return $element;
177}
178
179# Handle the start of a new element.  If cmd_element is defined, assume that
180# we need to collect the entire tree for this element before passing it to the
181# element method, and create a new tree into which we'll collect blocks of
182# text and nested elements.  Otherwise, if start_element is defined, call it.
183sub _handle_element_start {
184    my ($self, $element, $attrs) = @_;
185    my $method = $self->method_for_element ($element);
186
187    # If we have a command handler, we need to accumulate the contents of the
188    # tag before calling it.
189    if ($self->can ("cmd_$method")) {
190        push (@{ $$self{PENDING} }, [ $attrs, '' ]);
191    } elsif ($self->can ("start_$method")) {
192        my $method = 'start_' . $method;
193        $self->$method ($attrs, '');
194    }
195}
196
197# Handle the end of an element.  If we had a cmd_ method for this element,
198# this is where we pass along the text that we've accumulated.  Otherwise, if
199# we have an end_ method for the element, call that.
200sub _handle_element_end {
201    my ($self, $element) = @_;
202    my $method = $self->method_for_element ($element);
203
204    # If we have a command handler, pull off the pending text and pass it to
205    # the handler along with the saved attribute hash.
206    if ($self->can ("cmd_$method")) {
207        my $tag = pop @{ $$self{PENDING} };
208        my $method = 'cmd_' . $method;
209        my $text = $self->$method (@$tag);
210        if (defined $text) {
211            if (@{ $$self{PENDING} } > 1) {
212                $$self{PENDING}[-1][1] .= $text;
213            } else {
214                $self->output ($text);
215            }
216        }
217    } elsif ($self->can ("end_$method")) {
218        my $method = 'end_' . $method;
219        $self->$method ();
220    }
221}
222
223##############################################################################
224# Output formatting
225##############################################################################
226
227# Wrap a line, indenting by the current left margin.  We can't use Text::Wrap
228# because it plays games with tabs.  We can't use formline, even though we'd
229# really like to, because it screws up non-printing characters.  So we have to
230# do the wrapping ourselves.
231sub wrap {
232    my $self = shift;
233    local $_ = shift;
234    my $output = '';
235    my $spaces = ' ' x $$self{MARGIN};
236    my $width = $$self{opt_width} - $$self{MARGIN};
237    while (length > $width) {
238        if (s/^([^\n]{0,$width})\s+// || s/^([^\n]{$width})//) {
239            $output .= $spaces . $1 . "\n";
240        } else {
241            last;
242        }
243    }
244    $output .= $spaces . $_;
245    $output =~ s/\s+$/\n\n/;
246    return $output;
247}
248
249# Reformat a paragraph of text for the current margin.  Takes the text to
250# reformat and returns the formatted text.
251sub reformat {
252    my $self = shift;
253    local $_ = shift;
254
255    # If we're trying to preserve two spaces after sentences, do some munging
256    # to support that.  Otherwise, smash all repeated whitespace.
257    if ($$self{opt_sentence}) {
258        s/ +$//mg;
259        s/\.\n/. \n/g;
260        s/\n/ /g;
261        s/   +/  /g;
262    } else {
263        s/\s+/ /g;
264    }
265    return $self->wrap ($_);
266}
267
268# Output text to the output device.  Replace non-breaking spaces with spaces
269# and soft hyphens with nothing, and then try to fix the output encoding if
270# necessary to match the input encoding unless UTF-8 output is forced.  This
271# preserves the traditional pass-through behavior of Pod::Text.
272sub output {
273    my ($self, @text) = @_;
274    my $text = join ('', @text);
275    $text =~ tr/\240\255/ /d;
276    unless ($$self{opt_utf8} || $$self{CHECKED_ENCODING}) {
277        my $encoding = $$self{encoding} || '';
278        if ($encoding) {
279            eval { binmode ($$self{output_fh}, ":encoding($encoding)") };
280        }
281        $$self{CHECKED_ENCODING} = 1;
282    }
283    if ($$self{ENCODE}) {
284        print { $$self{output_fh} } encode ('UTF-8', $text);
285    } else {
286        print { $$self{output_fh} } $text;
287    }
288}
289
290# Output a block of code (something that isn't part of the POD text).  Called
291# by preprocess_paragraph only if we were given the code option.  Exists here
292# only so that it can be overridden by subclasses.
293sub output_code { $_[0]->output ($_[1]) }
294
295##############################################################################
296# Document initialization
297##############################################################################
298
299# Set up various things that have to be initialized on a per-document basis.
300sub start_document {
301    my ($self, $attrs) = @_;
302    if ($$attrs{contentless} && !$$self{ALWAYS_EMIT_SOMETHING}) {
303        $$self{CONTENTLESS} = 1;
304        return;
305    } else {
306        delete $$self{CONTENTLESS};
307    }
308    my $margin = $$self{opt_indent} + $$self{opt_margin};
309
310    # Initialize a few per-document variables.
311    $$self{INDENTS} = [];       # Stack of indentations.
312    $$self{MARGIN}  = $margin;  # Default left margin.
313    $$self{PENDING} = [[]];     # Pending output.
314
315    # We have to redo encoding handling for each document.
316    delete $$self{CHECKED_ENCODING};
317
318    # When UTF-8 output is set, check whether our output file handle already
319    # has a PerlIO encoding layer set.  If it does not, we'll need to encode
320    # our output before printing it (handled in the output() sub).  Wrap the
321    # check in an eval to handle versions of Perl without PerlIO.
322    $$self{ENCODE} = 0;
323    if ($$self{opt_utf8}) {
324        $$self{ENCODE} = 1;
325        eval {
326            my @options = (output => 1, details => 1);
327            my $flag = (PerlIO::get_layers ($$self{output_fh}, @options))[-1];
328            if ($flag & PerlIO::F_UTF8 ()) {
329                $$self{ENCODE} = 0;
330            }
331        };
332    }
333
334    return '';
335}
336
337# Handle the end of the document.  The only thing we do is handle dying on POD
338# errors, since Pod::Parser currently doesn't.
339sub end_document {
340    my ($self) = @_;
341    if ($$self{complain_die} && $self->errors_seen) {
342        croak ("POD document had syntax errors");
343    }
344}
345
346##############################################################################
347# Text blocks
348##############################################################################
349
350# Intended for subclasses to override, this method returns text with any
351# non-printing formatting codes stripped out so that length() correctly
352# returns the length of the text.  For basic Pod::Text, it does nothing.
353sub strip_format {
354    my ($self, $string) = @_;
355    return $string;
356}
357
358# This method is called whenever an =item command is complete (in other words,
359# we've seen its associated paragraph or know for certain that it doesn't have
360# one).  It gets the paragraph associated with the item as an argument.  If
361# that argument is empty, just output the item tag; if it contains a newline,
362# output the item tag followed by the newline.  Otherwise, see if there's
363# enough room for us to output the item tag in the margin of the text or if we
364# have to put it on a separate line.
365sub item {
366    my ($self, $text) = @_;
367    my $tag = $$self{ITEM};
368    unless (defined $tag) {
369        carp "Item called without tag";
370        return;
371    }
372    undef $$self{ITEM};
373
374    # Calculate the indentation and margin.  $fits is set to true if the tag
375    # will fit into the margin of the paragraph given our indentation level.
376    my $indent = $$self{INDENTS}[-1];
377    $indent = $$self{opt_indent} unless defined $indent;
378    my $margin = ' ' x $$self{opt_margin};
379    my $tag_length = length ($self->strip_format ($tag));
380    my $fits = ($$self{MARGIN} - $indent >= $tag_length + 1);
381
382    # If the tag doesn't fit, or if we have no associated text, print out the
383    # tag separately.  Otherwise, put the tag in the margin of the paragraph.
384    if (!$text || $text =~ /^\s+$/ || !$fits) {
385        my $realindent = $$self{MARGIN};
386        $$self{MARGIN} = $indent;
387        my $output = $self->reformat ($tag);
388        $output =~ s/^$margin /$margin:/ if ($$self{opt_alt} && $indent > 0);
389        $output =~ s/\n*$/\n/;
390
391        # If the text is just whitespace, we have an empty item paragraph;
392        # this can result from =over/=item/=back without any intermixed
393        # paragraphs.  Insert some whitespace to keep the =item from merging
394        # into the next paragraph.
395        $output .= "\n" if $text && $text =~ /^\s*$/;
396
397        $self->output ($output);
398        $$self{MARGIN} = $realindent;
399        $self->output ($self->reformat ($text)) if ($text && $text =~ /\S/);
400    } else {
401        my $space = ' ' x $indent;
402        $space =~ s/^$margin /$margin:/ if $$self{opt_alt};
403        $text = $self->reformat ($text);
404        $text =~ s/^$margin /$margin:/ if ($$self{opt_alt} && $indent > 0);
405        my $tagspace = ' ' x $tag_length;
406        $text =~ s/^($space)$tagspace/$1$tag/ or warn "Bizarre space in item";
407        $self->output ($text);
408    }
409}
410
411# Handle a basic block of text.  The only tricky thing here is that if there
412# is a pending item tag, we need to format this as an item paragraph.
413sub cmd_para {
414    my ($self, $attrs, $text) = @_;
415    $text =~ s/\s+$/\n/;
416    if (defined $$self{ITEM}) {
417        $self->item ($text . "\n");
418    } else {
419        $self->output ($self->reformat ($text . "\n"));
420    }
421    return '';
422}
423
424# Handle a verbatim paragraph.  Just print it out, but indent it according to
425# our margin.
426sub cmd_verbatim {
427    my ($self, $attrs, $text) = @_;
428    $self->item if defined $$self{ITEM};
429    return if $text =~ /^\s*$/;
430    $text =~ s/^(\n*)([ \t]*\S+)/$1 . (' ' x $$self{MARGIN}) . $2/gme;
431    $text =~ s/\s*$/\n\n/;
432    $self->output ($text);
433    return '';
434}
435
436# Handle literal text (produced by =for and similar constructs).  Just output
437# it with the minimum of changes.
438sub cmd_data {
439    my ($self, $attrs, $text) = @_;
440    $text =~ s/^\n+//;
441    $text =~ s/\n{0,2}$/\n/;
442    $self->output ($text);
443    return '';
444}
445
446##############################################################################
447# Headings
448##############################################################################
449
450# The common code for handling all headers.  Takes the header text, the
451# indentation, and the surrounding marker for the alt formatting method.
452sub heading {
453    my ($self, $text, $indent, $marker) = @_;
454    $self->item ("\n\n") if defined $$self{ITEM};
455    $text =~ s/\s+$//;
456    if ($$self{opt_alt}) {
457        my $closemark = reverse (split (//, $marker));
458        my $margin = ' ' x $$self{opt_margin};
459        $self->output ("\n" . "$margin$marker $text $closemark" . "\n\n");
460    } else {
461        $text .= "\n" if $$self{opt_loose};
462        my $margin = ' ' x ($$self{opt_margin} + $indent);
463        $self->output ($margin . $text . "\n");
464    }
465    return '';
466}
467
468# First level heading.
469sub cmd_head1 {
470    my ($self, $attrs, $text) = @_;
471    $self->heading ($text, 0, '====');
472}
473
474# Second level heading.
475sub cmd_head2 {
476    my ($self, $attrs, $text) = @_;
477    $self->heading ($text, $$self{opt_indent} / 2, '==  ');
478}
479
480# Third level heading.
481sub cmd_head3 {
482    my ($self, $attrs, $text) = @_;
483    $self->heading ($text, $$self{opt_indent} * 2 / 3 + 0.5, '=   ');
484}
485
486# Fourth level heading.
487sub cmd_head4 {
488    my ($self, $attrs, $text) = @_;
489    $self->heading ($text, $$self{opt_indent} * 3 / 4 + 0.5, '-   ');
490}
491
492##############################################################################
493# List handling
494##############################################################################
495
496# Handle the beginning of an =over block.  Takes the type of the block as the
497# first argument, and then the attr hash.  This is called by the handlers for
498# the four different types of lists (bullet, number, text, and block).
499sub over_common_start {
500    my ($self, $attrs) = @_;
501    $self->item ("\n\n") if defined $$self{ITEM};
502
503    # Find the indentation level.
504    my $indent = $$attrs{indent};
505    unless (defined ($indent) && $indent =~ /^\s*[-+]?\d{1,4}\s*$/) {
506        $indent = $$self{opt_indent};
507    }
508
509    # Add this to our stack of indents and increase our current margin.
510    push (@{ $$self{INDENTS} }, $$self{MARGIN});
511    $$self{MARGIN} += ($indent + 0);
512    return '';
513}
514
515# End an =over block.  Takes no options other than the class pointer.  Output
516# any pending items and then pop one level of indentation.
517sub over_common_end {
518    my ($self) = @_;
519    $self->item ("\n\n") if defined $$self{ITEM};
520    $$self{MARGIN} = pop @{ $$self{INDENTS} };
521    return '';
522}
523
524# Dispatch the start and end calls as appropriate.
525sub start_over_bullet { $_[0]->over_common_start ($_[1]) }
526sub start_over_number { $_[0]->over_common_start ($_[1]) }
527sub start_over_text   { $_[0]->over_common_start ($_[1]) }
528sub start_over_block  { $_[0]->over_common_start ($_[1]) }
529sub end_over_bullet { $_[0]->over_common_end }
530sub end_over_number { $_[0]->over_common_end }
531sub end_over_text   { $_[0]->over_common_end }
532sub end_over_block  { $_[0]->over_common_end }
533
534# The common handler for all item commands.  Takes the type of the item, the
535# attributes, and then the text of the item.
536sub item_common {
537    my ($self, $type, $attrs, $text) = @_;
538    $self->item if defined $$self{ITEM};
539
540    # Clean up the text.  We want to end up with two variables, one ($text)
541    # which contains any body text after taking out the item portion, and
542    # another ($item) which contains the actual item text.  Note the use of
543    # the internal Pod::Simple attribute here; that's a potential land mine.
544    $text =~ s/\s+$//;
545    my ($item, $index);
546    if ($type eq 'bullet') {
547        $item = '*';
548    } elsif ($type eq 'number') {
549        $item = $$attrs{'~orig_content'};
550    } else {
551        $item = $text;
552        $item =~ s/\s*\n\s*/ /g;
553        $text = '';
554    }
555    $$self{ITEM} = $item;
556
557    # If body text for this item was included, go ahead and output that now.
558    if ($text) {
559        $text =~ s/\s*$/\n/;
560        $self->item ($text);
561    }
562    return '';
563}
564
565# Dispatch the item commands to the appropriate place.
566sub cmd_item_bullet { my $self = shift; $self->item_common ('bullet', @_) }
567sub cmd_item_number { my $self = shift; $self->item_common ('number', @_) }
568sub cmd_item_text   { my $self = shift; $self->item_common ('text',   @_) }
569sub cmd_item_block  { my $self = shift; $self->item_common ('block',  @_) }
570
571##############################################################################
572# Formatting codes
573##############################################################################
574
575# The simple ones.
576sub cmd_b { return $_[0]{alt} ? "``$_[2]''" : $_[2] }
577sub cmd_f { return $_[0]{alt} ? "\"$_[2]\"" : $_[2] }
578sub cmd_i { return '*' . $_[2] . '*' }
579sub cmd_x { return '' }
580
581# Apply a whole bunch of messy heuristics to not quote things that don't
582# benefit from being quoted.  These originally come from Barrie Slaymaker and
583# largely duplicate code in Pod::Man.
584sub cmd_c {
585    my ($self, $attrs, $text) = @_;
586
587    # A regex that matches the portion of a variable reference that's the
588    # array or hash index, separated out just because we want to use it in
589    # several places in the following regex.
590    my $index = '(?: \[.*\] | \{.*\} )?';
591
592    # Check for things that we don't want to quote, and if we find any of
593    # them, return the string with just a font change and no quoting.
594    $text =~ m{
595      ^\s*
596      (?:
597         ( [\'\`\"] ) .* \1                             # already quoted
598       | \` .* \'                                       # `quoted'
599       | \$+ [\#^]? \S $index                           # special ($^Foo, $")
600       | [\$\@%&*]+ \#? [:\'\w]+ $index                 # plain var or func
601       | [\$\@%&*]* [:\'\w]+ (?: -> )? \(\s*[^\s,]\s*\) # 0/1-arg func call
602       | [+-]? ( \d[\d.]* | \.\d+ ) (?: [eE][+-]?\d+ )? # a number
603       | 0x [a-fA-F\d]+                                 # a hex constant
604      )
605      \s*\z
606     }xo && return $text;
607
608    # If we didn't return, go ahead and quote the text.
609    return $$self{opt_alt}
610        ? "``$text''"
611        : "$$self{LQUOTE}$text$$self{RQUOTE}";
612}
613
614# Links reduce to the text that we're given, wrapped in angle brackets if it's
615# a URL.
616sub cmd_l {
617    my ($self, $attrs, $text) = @_;
618    if ($$attrs{type} eq 'url') {
619        if (not defined($$attrs{to}) or $$attrs{to} eq $text) {
620            return "<$text>";
621        } elsif ($$self{opt_nourls}) {
622            return $text;
623        } else {
624            return "$text <$$attrs{to}>";
625        }
626    } else {
627        return $text;
628    }
629}
630
631##############################################################################
632# Backwards compatibility
633##############################################################################
634
635# The old Pod::Text module did everything in a pod2text() function.  This
636# tries to provide the same interface for legacy applications.
637sub pod2text {
638    my @args;
639
640    # This is really ugly; I hate doing option parsing in the middle of a
641    # module.  But the old Pod::Text module supported passing flags to its
642    # entry function, so handle -a and -<number>.
643    while ($_[0] =~ /^-/) {
644        my $flag = shift;
645        if    ($flag eq '-a')       { push (@args, alt => 1)    }
646        elsif ($flag =~ /^-(\d+)$/) { push (@args, width => $1) }
647        else {
648            unshift (@_, $flag);
649            last;
650        }
651    }
652
653    # Now that we know what arguments we're using, create the parser.
654    my $parser = Pod::Text->new (@args);
655
656    # If two arguments were given, the second argument is going to be a file
657    # handle.  That means we want to call parse_from_filehandle(), which means
658    # we need to turn the first argument into a file handle.  Magic open will
659    # handle the <&STDIN case automagically.
660    if (defined $_[1]) {
661        my @fhs = @_;
662        local *IN;
663        unless (open (IN, $fhs[0])) {
664            croak ("Can't open $fhs[0] for reading: $!\n");
665            return;
666        }
667        $fhs[0] = \*IN;
668        $parser->output_fh ($fhs[1]);
669        my $retval = $parser->parse_file ($fhs[0]);
670        my $fh = $parser->output_fh ();
671        close $fh;
672        return $retval;
673    } else {
674        $parser->output_fh (\*STDOUT);
675        return $parser->parse_file (@_);
676    }
677}
678
679# Reset the underlying Pod::Simple object between calls to parse_from_file so
680# that the same object can be reused to convert multiple pages.
681sub parse_from_file {
682    my $self = shift;
683    $self->reinit;
684
685    # Fake the old cutting option to Pod::Parser.  This fiddings with internal
686    # Pod::Simple state and is quite ugly; we need a better approach.
687    if (ref ($_[0]) eq 'HASH') {
688        my $opts = shift @_;
689        if (defined ($$opts{-cutting}) && !$$opts{-cutting}) {
690            $$self{in_pod} = 1;
691            $$self{last_was_blank} = 1;
692        }
693    }
694
695    # Do the work.
696    my $retval = $self->Pod::Simple::parse_from_file (@_);
697
698    # Flush output, since Pod::Simple doesn't do this.  Ideally we should also
699    # close the file descriptor if we had to open one, but we can't easily
700    # figure this out.
701    my $fh = $self->output_fh ();
702    my $oldfh = select $fh;
703    my $oldflush = $|;
704    $| = 1;
705    print $fh '';
706    $| = $oldflush;
707    select $oldfh;
708    return $retval;
709}
710
711# Pod::Simple failed to provide this backward compatibility function, so
712# implement it ourselves.  File handles are one of the inputs that
713# parse_from_file supports.
714sub parse_from_filehandle {
715    my $self = shift;
716    $self->parse_from_file (@_);
717}
718
719# Pod::Simple's parse_file doesn't set output_fh.  Wrap the call and do so
720# ourself unless it was already set by the caller, since our documentation has
721# always said that this should work.
722sub parse_file {
723    my ($self, $in) = @_;
724    unless (defined $$self{output_fh}) {
725        $self->output_fh (\*STDOUT);
726    }
727    return $self->SUPER::parse_file ($in);
728}
729
730##############################################################################
731# Module return value and documentation
732##############################################################################
733
7341;
735__END__
736
737=for stopwords
738alt stderr Allbery Sean Burke's Christiansen UTF-8 pre-Unicode utf8 nourls
739
740=head1 NAME
741
742Pod::Text - Convert POD data to formatted ASCII text
743
744=head1 SYNOPSIS
745
746    use Pod::Text;
747    my $parser = Pod::Text->new (sentence => 0, width => 78);
748
749    # Read POD from STDIN and write to STDOUT.
750    $parser->parse_from_filehandle;
751
752    # Read POD from file.pod and write to file.txt.
753    $parser->parse_from_file ('file.pod', 'file.txt');
754
755=head1 DESCRIPTION
756
757Pod::Text is a module that can convert documentation in the POD format (the
758preferred language for documenting Perl) into formatted ASCII.  It uses no
759special formatting controls or codes whatsoever, and its output is therefore
760suitable for nearly any device.
761
762As a derived class from Pod::Simple, Pod::Text supports the same methods and
763interfaces.  See L<Pod::Simple> for all the details; briefly, one creates a
764new parser with C<< Pod::Text->new() >> and then normally calls parse_file().
765
766new() can take options, in the form of key/value pairs, that control the
767behavior of the parser.  The currently recognized options are:
768
769=over 4
770
771=item alt
772
773If set to a true value, selects an alternate output format that, among other
774things, uses a different heading style and marks C<=item> entries with a
775colon in the left margin.  Defaults to false.
776
777=item code
778
779If set to a true value, the non-POD parts of the input file will be included
780in the output.  Useful for viewing code documented with POD blocks with the
781POD rendered and the code left intact.
782
783=item errors
784
785How to report errors.  C<die> says to throw an exception on any POD
786formatting error.  C<stderr> says to report errors on standard error, but
787not to throw an exception.  C<pod> says to include a POD ERRORS section
788in the resulting documentation summarizing the errors.  C<none> ignores
789POD errors entirely, as much as possible.
790
791The default is C<output>.
792
793=item indent
794
795The number of spaces to indent regular text, and the default indentation for
796C<=over> blocks.  Defaults to 4.
797
798=item loose
799
800If set to a true value, a blank line is printed after a C<=head1> heading.
801If set to false (the default), no blank line is printed after C<=head1>,
802although one is still printed after C<=head2>.  This is the default because
803it's the expected formatting for manual pages; if you're formatting
804arbitrary text documents, setting this to true may result in more pleasing
805output.
806
807=item margin
808
809The width of the left margin in spaces.  Defaults to 0.  This is the margin
810for all text, including headings, not the amount by which regular text is
811indented; for the latter, see the I<indent> option.  To set the right
812margin, see the I<width> option.
813
814=item nourls
815
816Normally, LZ<><> formatting codes with a URL but anchor text are formatted
817to show both the anchor text and the URL.  In other words:
818
819    L<foo|http://example.com/>
820
821is formatted as:
822
823    foo <http://example.com/>
824
825This option, if set to a true value, suppresses the URL when anchor text
826is given, so this example would be formatted as just C<foo>.  This can
827produce less cluttered output in cases where the URLs are not particularly
828important.
829
830=item quotes
831
832Sets the quote marks used to surround CE<lt>> text.  If the value is a
833single character, it is used as both the left and right quote; if it is two
834characters, the first character is used as the left quote and the second as
835the right quoted; and if it is four characters, the first two are used as
836the left quote and the second two as the right quote.
837
838This may also be set to the special value C<none>, in which case no quote
839marks are added around CE<lt>> text.
840
841=item sentence
842
843If set to a true value, Pod::Text will assume that each sentence ends in two
844spaces, and will try to preserve that spacing.  If set to false, all
845consecutive whitespace in non-verbatim paragraphs is compressed into a
846single space.  Defaults to true.
847
848=item stderr
849
850Send error messages about invalid POD to standard error instead of
851appending a POD ERRORS section to the generated output.  This is
852equivalent to setting C<errors> to C<stderr> if C<errors> is not already
853set.  It is supported for backward compatibility.
854
855=item utf8
856
857By default, Pod::Text uses the same output encoding as the input encoding
858of the POD source (provided that Perl was built with PerlIO; otherwise, it
859doesn't encode its output).  If this option is given, the output encoding
860is forced to UTF-8.
861
862Be aware that, when using this option, the input encoding of your POD
863source must be properly declared unless it is US-ASCII or Latin-1.  POD
864input without an C<=encoding> command will be assumed to be in Latin-1,
865and if it's actually in UTF-8, the output will be double-encoded.  See
866L<perlpod(1)> for more information on the C<=encoding> command.
867
868=item width
869
870The column at which to wrap text on the right-hand side.  Defaults to 76.
871
872=back
873
874The standard Pod::Simple method parse_file() takes one argument, the file or
875file handle to read from, and writes output to standard output unless that
876has been changed with the output_fh() method.  See L<Pod::Simple> for the
877specific details and for other alternative interfaces.
878
879=head1 DIAGNOSTICS
880
881=over 4
882
883=item Bizarre space in item
884
885=item Item called without tag
886
887(W) Something has gone wrong in internal C<=item> processing.  These
888messages indicate a bug in Pod::Text; you should never see them.
889
890=item Can't open %s for reading: %s
891
892(F) Pod::Text was invoked via the compatibility mode pod2text() interface
893and the input file it was given could not be opened.
894
895=item Invalid errors setting "%s"
896
897(F) The C<errors> parameter to the constructor was set to an unknown value.
898
899=item Invalid quote specification "%s"
900
901(F) The quote specification given (the C<quotes> option to the
902constructor) was invalid.  A quote specification must be one, two, or four
903characters long.
904
905=item POD document had syntax errors
906
907(F) The POD document being formatted had syntax errors and the C<errors>
908option was set to C<die>.
909
910=back
911
912=head1 BUGS
913
914Encoding handling assumes that PerlIO is available and does not work
915properly if it isn't.  The C<utf8> option is therefore not supported
916unless Perl is built with PerlIO support.
917
918=head1 CAVEATS
919
920If Pod::Text is given the C<utf8> option, the encoding of its output file
921handle will be forced to UTF-8 if possible, overriding any existing
922encoding.  This will be done even if the file handle is not created by
923Pod::Text and was passed in from outside.  This maintains consistency
924regardless of PERL_UNICODE and other settings.
925
926If the C<utf8> option is not given, the encoding of its output file handle
927will be forced to the detected encoding of the input POD, which preserves
928whatever the input text is.  This ensures backward compatibility with
929earlier, pre-Unicode versions of this module, without large numbers of
930Perl warnings.
931
932This is not ideal, but it seems to be the best compromise.  If it doesn't
933work for you, please let me know the details of how it broke.
934
935=head1 NOTES
936
937This is a replacement for an earlier Pod::Text module written by Tom
938Christiansen.  It has a revamped interface, since it now uses Pod::Simple,
939but an interface roughly compatible with the old Pod::Text::pod2text()
940function is still available.  Please change to the new calling convention,
941though.
942
943The original Pod::Text contained code to do formatting via termcap
944sequences, although it wasn't turned on by default and it was problematic to
945get it to work at all.  This rewrite doesn't even try to do that, but a
946subclass of it does.  Look for L<Pod::Text::Termcap>.
947
948=head1 SEE ALSO
949
950L<Pod::Simple>, L<Pod::Text::Termcap>, L<perlpod(1)>, L<pod2text(1)>
951
952The current version of this module is always available from its web site at
953L<http://www.eyrie.org/~eagle/software/podlators/>.  It is also part of the
954Perl core distribution as of 5.6.0.
955
956=head1 AUTHOR
957
958Russ Allbery <rra@stanford.edu>, based I<very> heavily on the original
959Pod::Text by Tom Christiansen <tchrist@mox.perl.com> and its conversion to
960Pod::Parser by Brad Appleton <bradapp@enteract.com>.  Sean Burke's initial
961conversion of Pod::Man to use Pod::Simple provided much-needed guidance on
962how to use Pod::Simple.
963
964=head1 COPYRIGHT AND LICENSE
965
966Copyright 1999, 2000, 2001, 2002, 2004, 2006, 2008, 2009, 2012, 2013 Russ
967Allbery <rra@stanford.edu>.
968
969This program is free software; you may redistribute it and/or modify it
970under the same terms as Perl itself.
971
972=cut
973