Pod::Man should strip leading lib/ for module manpages (from
[p5sagit/p5-mst-13.2.git] / lib / Pod / Parser.pm
CommitLineData
360aca43 1#############################################################################
2# Pod/Parser.pm -- package which defines a base class for parsing POD docs.
3#
66aff6dd 4# Copyright (C) 1996-2000 by Bradford Appleton. All rights reserved.
360aca43 5# This file is part of "PodParser". PodParser is free software;
6# you can redistribute it and/or modify it under the same terms
7# as Perl itself.
8#############################################################################
9
10package Pod::Parser;
11
12use vars qw($VERSION);
828c4421 13$VERSION = 1.12; ## Current version of this package
14require 5.005; ## requires this Perl version or later
360aca43 15
16#############################################################################
17
18=head1 NAME
19
20Pod::Parser - base class for creating POD filters and translators
21
22=head1 SYNOPSIS
23
24 use Pod::Parser;
25
26 package MyParser;
27 @ISA = qw(Pod::Parser);
28
29 sub command {
30 my ($parser, $command, $paragraph, $line_num) = @_;
31 ## Interpret the command and its text; sample actions might be:
32 if ($command eq 'head1') { ... }
33 elsif ($command eq 'head2') { ... }
34 ## ... other commands and their actions
35 my $out_fh = $parser->output_handle();
36 my $expansion = $parser->interpolate($paragraph, $line_num);
37 print $out_fh $expansion;
38 }
39
40 sub verbatim {
41 my ($parser, $paragraph, $line_num) = @_;
42 ## Format verbatim paragraph; sample actions might be:
43 my $out_fh = $parser->output_handle();
44 print $out_fh $paragraph;
45 }
46
47 sub textblock {
48 my ($parser, $paragraph, $line_num) = @_;
49 ## Translate/Format this block of text; sample actions might be:
50 my $out_fh = $parser->output_handle();
51 my $expansion = $parser->interpolate($paragraph, $line_num);
52 print $out_fh $expansion;
53 }
54
55 sub interior_sequence {
56 my ($parser, $seq_command, $seq_argument) = @_;
57 ## Expand an interior sequence; sample actions might be:
66aff6dd 58 return "*$seq_argument*" if ($seq_command eq 'B');
59 return "`$seq_argument'" if ($seq_command eq 'C');
60 return "_${seq_argument}_'" if ($seq_command eq 'I');
360aca43 61 ## ... other sequence commands and their resulting text
62 }
63
64 package main;
65
66 ## Create a parser object and have it parse file whose name was
67 ## given on the command-line (use STDIN if no files were given).
68 $parser = new MyParser();
69 $parser->parse_from_filehandle(\*STDIN) if (@ARGV == 0);
70 for (@ARGV) { $parser->parse_from_file($_); }
71
72=head1 REQUIRES
73
828c4421 74perl5.005, Pod::InputObjects, Exporter, Symbol, Carp
360aca43 75
76=head1 EXPORTS
77
78Nothing.
79
80=head1 DESCRIPTION
81
82B<Pod::Parser> is a base class for creating POD filters and translators.
83It handles most of the effort involved with parsing the POD sections
84from an input stream, leaving subclasses free to be concerned only with
85performing the actual translation of text.
86
87B<Pod::Parser> parses PODs, and makes method calls to handle the various
88components of the POD. Subclasses of B<Pod::Parser> override these methods
89to translate the POD into whatever output format they desire.
90
91=head1 QUICK OVERVIEW
92
93To create a POD filter for translating POD documentation into some other
94format, you create a subclass of B<Pod::Parser> which typically overrides
95just the base class implementation for the following methods:
96
97=over 2
98
99=item *
100
101B<command()>
102
103=item *
104
105B<verbatim()>
106
107=item *
108
109B<textblock()>
110
111=item *
112
113B<interior_sequence()>
114
115=back
116
117You may also want to override the B<begin_input()> and B<end_input()>
118methods for your subclass (to perform any needed per-file and/or
119per-document initialization or cleanup).
120
121If you need to perform any preprocesssing of input before it is parsed
122you may want to override one or more of B<preprocess_line()> and/or
123B<preprocess_paragraph()>.
124
125Sometimes it may be necessary to make more than one pass over the input
126files. If this is the case you have several options. You can make the
127first pass using B<Pod::Parser> and override your methods to store the
128intermediate results in memory somewhere for the B<end_pod()> method to
129process. You could use B<Pod::Parser> for several passes with an
130appropriate state variable to control the operation for each pass. If
131your input source can't be reset to start at the beginning, you can
132store it in some other structure as a string or an array and have that
133structure implement a B<getline()> method (which is all that
134B<parse_from_filehandle()> uses to read input).
135
136Feel free to add any member data fields you need to keep track of things
137like current font, indentation, horizontal or vertical position, or
138whatever else you like. Be sure to read L<"PRIVATE METHODS AND DATA">
139to avoid name collisions.
140
141For the most part, the B<Pod::Parser> base class should be able to
142do most of the input parsing for you and leave you free to worry about
143how to intepret the commands and translate the result.
144
66aff6dd 145Note that all we have described here in this quick overview is the
146simplest most straightforward use of B<Pod::Parser> to do stream-based
664bb207 147parsing. It is also possible to use the B<Pod::Parser::parse_text> function
148to do more sophisticated tree-based parsing. See L<"TREE-BASED PARSING">.
149
150=head1 PARSING OPTIONS
151
152A I<parse-option> is simply a named option of B<Pod::Parser> with a
153value that corresponds to a certain specified behavior. These various
154behaviors of B<Pod::Parser> may be enabled/disabled by setting or
155or unsetting one or more I<parse-options> using the B<parseopts()> method.
156The set of currently accepted parse-options is as follows:
157
158=over 3
159
160=item B<-want_nonPODs> (default: unset)
161
162Normally (by default) B<Pod::Parser> will only provide access to
163the POD sections of the input. Input paragraphs that are not part
164of the POD-format documentation are not made available to the caller
165(not even using B<preprocess_paragraph()>). Setting this option to a
166non-empty, non-zero value will allow B<preprocess_paragraph()> to see
e3237417 167non-POD sections of the input as well as POD sections. The B<cutting()>
664bb207 168method can be used to determine if the corresponding paragraph is a POD
169paragraph, or some other input paragraph.
170
171=item B<-process_cut_cmd> (default: unset)
172
173Normally (by default) B<Pod::Parser> handles the C<=cut> POD directive
174by itself and does not pass it on to the caller for processing. Setting
a5317591 175this option to a non-empty, non-zero value will cause B<Pod::Parser> to
664bb207 176pass the C<=cut> directive to the caller just like any other POD command
177(and hence it may be processed by the B<command()> method).
178
179B<Pod::Parser> will still interpret the C<=cut> directive to mean that
180"cutting mode" has been (re)entered, but the caller will get a chance
181to capture the actual C<=cut> paragraph itself for whatever purpose
182it desires.
183
a5317591 184=item B<-warnings> (default: unset)
185
186Normally (by default) B<Pod::Parser> recognizes a bare minimum of
187pod syntax errors and warnings and issues diagnostic messages
188for errors, but not for warnings. (Use B<Pod::Checker> to do more
189thorough checking of POD syntax.) Setting this option to a non-empty,
190non-zero value will cause B<Pod::Parser> to issue diagnostics for
191the few warnings it recognizes as well as the errors.
192
664bb207 193=back
194
195Please see L<"parseopts()"> for a complete description of the interface
196for the setting and unsetting of parse-options.
197
360aca43 198=cut
199
200#############################################################################
201
202use vars qw(@ISA);
203use strict;
204#use diagnostics;
205use Pod::InputObjects;
206use Carp;
360aca43 207use Exporter;
f0963acb 208require VMS::Filespec if $^O eq 'VMS';
828c4421 209BEGIN {
210 if ($] < 5.6) {
211 require Symbol;
212 import Symbol;
213 }
214}
360aca43 215@ISA = qw(Exporter);
216
217## These "variables" are used as local "glob aliases" for performance
664bb207 218use vars qw(%myData %myOpts @input_stack);
360aca43 219
220#############################################################################
221
222=head1 RECOMMENDED SUBROUTINE/METHOD OVERRIDES
223
224B<Pod::Parser> provides several methods which most subclasses will probably
225want to override. These methods are as follows:
226
227=cut
228
229##---------------------------------------------------------------------------
230
231=head1 B<command()>
232
233 $parser->command($cmd,$text,$line_num,$pod_para);
234
235This method should be overridden by subclasses to take the appropriate
236action when a POD command paragraph (denoted by a line beginning with
237"=") is encountered. When such a POD directive is seen in the input,
238this method is called and is passed:
239
240=over 3
241
242=item C<$cmd>
243
244the name of the command for this POD paragraph
245
246=item C<$text>
247
248the paragraph text for the given POD paragraph command.
249
250=item C<$line_num>
251
252the line-number of the beginning of the paragraph
253
254=item C<$pod_para>
255
256a reference to a C<Pod::Paragraph> object which contains further
257information about the paragraph command (see L<Pod::InputObjects>
258for details).
259
260=back
261
262B<Note> that this method I<is> called for C<=pod> paragraphs.
263
264The base class implementation of this method simply treats the raw POD
265command as normal block of paragraph text (invoking the B<textblock()>
266method with the command paragraph).
267
268=cut
269
270sub command {
271 my ($self, $cmd, $text, $line_num, $pod_para) = @_;
272 ## Just treat this like a textblock
273 $self->textblock($pod_para->raw_text(), $line_num, $pod_para);
274}
275
276##---------------------------------------------------------------------------
277
278=head1 B<verbatim()>
279
280 $parser->verbatim($text,$line_num,$pod_para);
281
282This method may be overridden by subclasses to take the appropriate
283action when a block of verbatim text is encountered. It is passed the
284following parameters:
285
286=over 3
287
288=item C<$text>
289
290the block of text for the verbatim paragraph
291
292=item C<$line_num>
293
294the line-number of the beginning of the paragraph
295
296=item C<$pod_para>
297
298a reference to a C<Pod::Paragraph> object which contains further
299information about the paragraph (see L<Pod::InputObjects>
300for details).
301
302=back
303
304The base class implementation of this method simply prints the textblock
305(unmodified) to the output filehandle.
306
307=cut
308
309sub verbatim {
310 my ($self, $text, $line_num, $pod_para) = @_;
311 my $out_fh = $self->{_OUTPUT};
312 print $out_fh $text;
313}
314
315##---------------------------------------------------------------------------
316
317=head1 B<textblock()>
318
319 $parser->textblock($text,$line_num,$pod_para);
320
321This method may be overridden by subclasses to take the appropriate
322action when a normal block of POD text is encountered (although the base
323class method will usually do what you want). It is passed the following
324parameters:
325
326=over 3
327
328=item C<$text>
329
330the block of text for the a POD paragraph
331
332=item C<$line_num>
333
334the line-number of the beginning of the paragraph
335
336=item C<$pod_para>
337
338a reference to a C<Pod::Paragraph> object which contains further
339information about the paragraph (see L<Pod::InputObjects>
340for details).
341
342=back
343
344In order to process interior sequences, subclasses implementations of
345this method will probably want to invoke either B<interpolate()> or
346B<parse_text()>, passing it the text block C<$text>, and the corresponding
347line number in C<$line_num>, and then perform any desired processing upon
348the returned result.
349
350The base class implementation of this method simply prints the text block
351as it occurred in the input stream).
352
353=cut
354
355sub textblock {
356 my ($self, $text, $line_num, $pod_para) = @_;
357 my $out_fh = $self->{_OUTPUT};
358 print $out_fh $self->interpolate($text, $line_num);
359}
360
361##---------------------------------------------------------------------------
362
363=head1 B<interior_sequence()>
364
365 $parser->interior_sequence($seq_cmd,$seq_arg,$pod_seq);
366
367This method should be overridden by subclasses to take the appropriate
368action when an interior sequence is encountered. An interior sequence is
369an embedded command within a block of text which appears as a command
370name (usually a single uppercase character) followed immediately by a
371string of text which is enclosed in angle brackets. This method is
372passed the sequence command C<$seq_cmd> and the corresponding text
373C<$seq_arg>. It is invoked by the B<interpolate()> method for each interior
374sequence that occurs in the string that it is passed. It should return
375the desired text string to be used in place of the interior sequence.
376The C<$pod_seq> argument is a reference to a C<Pod::InteriorSequence>
377object which contains further information about the interior sequence.
378Please see L<Pod::InputObjects> for details if you need to access this
379additional information.
380
381Subclass implementations of this method may wish to invoke the
382B<nested()> method of C<$pod_seq> to see if it is nested inside
383some other interior-sequence (and if so, which kind).
384
385The base class implementation of the B<interior_sequence()> method
386simply returns the raw text of the interior sequence (as it occurred
387in the input) to the caller.
388
389=cut
390
391sub interior_sequence {
392 my ($self, $seq_cmd, $seq_arg, $pod_seq) = @_;
393 ## Just return the raw text of the interior sequence
394 return $pod_seq->raw_text();
395}
396
397#############################################################################
398
399=head1 OPTIONAL SUBROUTINE/METHOD OVERRIDES
400
401B<Pod::Parser> provides several methods which subclasses may want to override
402to perform any special pre/post-processing. These methods do I<not> have to
403be overridden, but it may be useful for subclasses to take advantage of them.
404
405=cut
406
407##---------------------------------------------------------------------------
408
409=head1 B<new()>
410
411 my $parser = Pod::Parser->new();
412
413This is the constructor for B<Pod::Parser> and its subclasses. You
414I<do not> need to override this method! It is capable of constructing
415subclass objects as well as base class objects, provided you use
416any of the following constructor invocation styles:
417
418 my $parser1 = MyParser->new();
419 my $parser2 = new MyParser();
420 my $parser3 = $parser2->new();
421
422where C<MyParser> is some subclass of B<Pod::Parser>.
423
424Using the syntax C<MyParser::new()> to invoke the constructor is I<not>
425recommended, but if you insist on being able to do this, then the
426subclass I<will> need to override the B<new()> constructor method. If
427you do override the constructor, you I<must> be sure to invoke the
428B<initialize()> method of the newly blessed object.
429
430Using any of the above invocations, the first argument to the
431constructor is always the corresponding package name (or object
432reference). No other arguments are required, but if desired, an
433associative array (or hash-table) my be passed to the B<new()>
434constructor, as in:
435
436 my $parser1 = MyParser->new( MYDATA => $value1, MOREDATA => $value2 );
437 my $parser2 = new MyParser( -myflag => 1 );
438
439All arguments passed to the B<new()> constructor will be treated as
440key/value pairs in a hash-table. The newly constructed object will be
441initialized by copying the contents of the given hash-table (which may
442have been empty). The B<new()> constructor for this class and all of its
443subclasses returns a blessed reference to the initialized object (hash-table).
444
445=cut
446
447sub new {
448 ## Determine if we were called via an object-ref or a classname
449 my $this = shift;
450 my $class = ref($this) || $this;
451 ## Any remaining arguments are treated as initial values for the
452 ## hash that is used to represent this object.
453 my %params = @_;
454 my $self = { %params };
455 ## Bless ourselves into the desired class and perform any initialization
456 bless $self, $class;
457 $self->initialize();
458 return $self;
459}
460
461##---------------------------------------------------------------------------
462
463=head1 B<initialize()>
464
465 $parser->initialize();
466
467This method performs any necessary object initialization. It takes no
468arguments (other than the object instance of course, which is typically
469copied to a local variable named C<$self>). If subclasses override this
470method then they I<must> be sure to invoke C<$self-E<gt>SUPER::initialize()>.
471
472=cut
473
474sub initialize {
475 #my $self = shift;
476 #return;
477}
478
479##---------------------------------------------------------------------------
480
481=head1 B<begin_pod()>
482
483 $parser->begin_pod();
484
485This method is invoked at the beginning of processing for each POD
486document that is encountered in the input. Subclasses should override
487this method to perform any per-document initialization.
488
489=cut
490
491sub begin_pod {
492 #my $self = shift;
493 #return;
494}
495
496##---------------------------------------------------------------------------
497
498=head1 B<begin_input()>
499
500 $parser->begin_input();
501
502This method is invoked by B<parse_from_filehandle()> immediately I<before>
503processing input from a filehandle. The base class implementation does
504nothing, however, subclasses may override it to perform any per-file
505initializations.
506
507Note that if multiple files are parsed for a single POD document
508(perhaps the result of some future C<=include> directive) this method
509is invoked for every file that is parsed. If you wish to perform certain
510initializations once per document, then you should use B<begin_pod()>.
511
512=cut
513
514sub begin_input {
515 #my $self = shift;
516 #return;
517}
518
519##---------------------------------------------------------------------------
520
521=head1 B<end_input()>
522
523 $parser->end_input();
524
525This method is invoked by B<parse_from_filehandle()> immediately I<after>
526processing input from a filehandle. The base class implementation does
527nothing, however, subclasses may override it to perform any per-file
528cleanup actions.
529
530Please note that if multiple files are parsed for a single POD document
531(perhaps the result of some kind of C<=include> directive) this method
532is invoked for every file that is parsed. If you wish to perform certain
533cleanup actions once per document, then you should use B<end_pod()>.
534
535=cut
536
537sub end_input {
538 #my $self = shift;
539 #return;
540}
541
542##---------------------------------------------------------------------------
543
544=head1 B<end_pod()>
545
546 $parser->end_pod();
547
548This method is invoked at the end of processing for each POD document
549that is encountered in the input. Subclasses should override this method
550to perform any per-document finalization.
551
552=cut
553
554sub end_pod {
555 #my $self = shift;
556 #return;
557}
558
559##---------------------------------------------------------------------------
560
561=head1 B<preprocess_line()>
562
563 $textline = $parser->preprocess_line($text, $line_num);
564
565This method should be overridden by subclasses that wish to perform
566any kind of preprocessing for each I<line> of input (I<before> it has
567been determined whether or not it is part of a POD paragraph). The
568parameter C<$text> is the input line; and the parameter C<$line_num> is
569the line number of the corresponding text line.
570
571The value returned should correspond to the new text to use in its
572place. If the empty string or an undefined value is returned then no
573further processing will be performed for this line.
574
575Please note that the B<preprocess_line()> method is invoked I<before>
576the B<preprocess_paragraph()> method. After all (possibly preprocessed)
577lines in a paragraph have been assembled together and it has been
578determined that the paragraph is part of the POD documentation from one
579of the selected sections, then B<preprocess_paragraph()> is invoked.
580
581The base class implementation of this method returns the given text.
582
583=cut
584
585sub preprocess_line {
586 my ($self, $text, $line_num) = @_;
587 return $text;
588}
589
590##---------------------------------------------------------------------------
591
592=head1 B<preprocess_paragraph()>
593
594 $textblock = $parser->preprocess_paragraph($text, $line_num);
595
596This method should be overridden by subclasses that wish to perform any
597kind of preprocessing for each block (paragraph) of POD documentation
598that appears in the input stream. The parameter C<$text> is the POD
599paragraph from the input file; and the parameter C<$line_num> is the
600line number for the beginning of the corresponding paragraph.
601
602The value returned should correspond to the new text to use in its
603place If the empty string is returned or an undefined value is
604returned, then the given C<$text> is ignored (not processed).
605
e3237417 606This method is invoked after gathering up all the lines in a paragraph
607and after determining the cutting state of the paragraph,
360aca43 608but before trying to further parse or interpret them. After
609B<preprocess_paragraph()> returns, the current cutting state (which
610is returned by C<$self-E<gt>cutting()>) is examined. If it evaluates
e3237417 611to true then input text (including the given C<$text>) is cut (not
360aca43 612processed) until the next POD directive is encountered.
613
614Please note that the B<preprocess_line()> method is invoked I<before>
615the B<preprocess_paragraph()> method. After all (possibly preprocessed)
e3237417 616lines in a paragraph have been assembled together and either it has been
360aca43 617determined that the paragraph is part of the POD documentation from one
66aff6dd 618of the selected sections or the C<-want_nonPODs> option is true,
e3237417 619then B<preprocess_paragraph()> is invoked.
360aca43 620
621The base class implementation of this method returns the given text.
622
623=cut
624
625sub preprocess_paragraph {
626 my ($self, $text, $line_num) = @_;
627 return $text;
628}
629
630#############################################################################
631
632=head1 METHODS FOR PARSING AND PROCESSING
633
634B<Pod::Parser> provides several methods to process input text. These
664bb207 635methods typically won't need to be overridden (and in some cases they
636can't be overridden), but subclasses may want to invoke them to exploit
637their functionality.
360aca43 638
639=cut
640
641##---------------------------------------------------------------------------
642
643=head1 B<parse_text()>
644
645 $ptree1 = $parser->parse_text($text, $line_num);
646 $ptree2 = $parser->parse_text({%opts}, $text, $line_num);
647 $ptree3 = $parser->parse_text(\%opts, $text, $line_num);
648
649This method is useful if you need to perform your own interpolation
650of interior sequences and can't rely upon B<interpolate> to expand
651them in simple bottom-up order order.
652
653The parameter C<$text> is a string or block of text to be parsed
654for interior sequences; and the parameter C<$line_num> is the
655line number curresponding to the beginning of C<$text>.
656
657B<parse_text()> will parse the given text into a parse-tree of "nodes."
658and interior-sequences. Each "node" in the parse tree is either a
659text-string, or a B<Pod::InteriorSequence>. The result returned is a
660parse-tree of type B<Pod::ParseTree>. Please see L<Pod::InputObjects>
661for more information about B<Pod::InteriorSequence> and B<Pod::ParseTree>.
662
663If desired, an optional hash-ref may be specified as the first argument
664to customize certain aspects of the parse-tree that is created and
665returned. The set of recognized option keywords are:
666
667=over 3
668
669=item B<-expand_seq> =E<gt> I<code-ref>|I<method-name>
670
671Normally, the parse-tree returned by B<parse_text()> will contain an
672unexpanded C<Pod::InteriorSequence> object for each interior-sequence
673encountered. Specifying B<-expand_seq> tells B<parse_text()> to "expand"
674every interior-sequence it sees by invoking the referenced function
675(or named method of the parser object) and using the return value as the
676expanded result.
677
678If a subroutine reference was given, it is invoked as:
679
680 &$code_ref( $parser, $sequence )
681
682and if a method-name was given, it is invoked as:
683
684 $parser->method_name( $sequence )
685
686where C<$parser> is a reference to the parser object, and C<$sequence>
687is a reference to the interior-sequence object.
688[I<NOTE>: If the B<interior_sequence()> method is specified, then it is
689invoked according to the interface specified in L<"interior_sequence()">].
690
664bb207 691=item B<-expand_text> =E<gt> I<code-ref>|I<method-name>
692
693Normally, the parse-tree returned by B<parse_text()> will contain a
694text-string for each contiguous sequence of characters outside of an
695interior-sequence. Specifying B<-expand_text> tells B<parse_text()> to
696"preprocess" every such text-string it sees by invoking the referenced
697function (or named method of the parser object) and using the return value
698as the preprocessed (or "expanded") result. [Note that if the result is
699an interior-sequence, then it will I<not> be expanded as specified by the
700B<-expand_seq> option; Any such recursive expansion needs to be handled by
701the specified callback routine.]
702
703If a subroutine reference was given, it is invoked as:
704
705 &$code_ref( $parser, $text, $ptree_node )
706
707and if a method-name was given, it is invoked as:
708
709 $parser->method_name( $text, $ptree_node )
710
711where C<$parser> is a reference to the parser object, C<$text> is the
712text-string encountered, and C<$ptree_node> is a reference to the current
713node in the parse-tree (usually an interior-sequence object or else the
714top-level node of the parse-tree).
715
360aca43 716=item B<-expand_ptree> =E<gt> I<code-ref>|I<method-name>
717
718Rather than returning a C<Pod::ParseTree>, pass the parse-tree as an
719argument to the referenced subroutine (or named method of the parser
720object) and return the result instead of the parse-tree object.
721
722If a subroutine reference was given, it is invoked as:
723
724 &$code_ref( $parser, $ptree )
725
726and if a method-name was given, it is invoked as:
727
728 $parser->method_name( $ptree )
729
730where C<$parser> is a reference to the parser object, and C<$ptree>
731is a reference to the parse-tree object.
732
733=back
734
735=cut
736
360aca43 737sub parse_text {
738 my $self = shift;
739 local $_ = '';
740
741 ## Get options and set any defaults
742 my %opts = (ref $_[0]) ? %{ shift() } : ();
743 my $expand_seq = $opts{'-expand_seq'} || undef;
664bb207 744 my $expand_text = $opts{'-expand_text'} || undef;
360aca43 745 my $expand_ptree = $opts{'-expand_ptree'} || undef;
746
747 my $text = shift;
748 my $line = shift;
749 my $file = $self->input_file();
66aff6dd 750 my $cmd = "";
360aca43 751
752 ## Convert method calls into closures, for our convenience
753 my $xseq_sub = $expand_seq;
664bb207 754 my $xtext_sub = $expand_text;
360aca43 755 my $xptree_sub = $expand_ptree;
e9fdc7d2 756 if (defined $expand_seq and $expand_seq eq 'interior_sequence') {
360aca43 757 ## If 'interior_sequence' is the method to use, we have to pass
758 ## more than just the sequence object, we also need to pass the
759 ## sequence name and text.
760 $xseq_sub = sub {
761 my ($self, $iseq) = @_;
762 my $args = join("", $iseq->parse_tree->children);
763 return $self->interior_sequence($iseq->name, $args, $iseq);
764 };
765 }
766 ref $xseq_sub or $xseq_sub = sub { shift()->$expand_seq(@_) };
664bb207 767 ref $xtext_sub or $xtext_sub = sub { shift()->$expand_text(@_) };
360aca43 768 ref $xptree_sub or $xptree_sub = sub { shift()->$expand_ptree(@_) };
66aff6dd 769
360aca43 770 ## Keep track of the "current" interior sequence, and maintain a stack
771 ## of "in progress" sequences.
772 ##
773 ## NOTE that we push our own "accumulator" at the very beginning of the
774 ## stack. It's really a parse-tree, not a sequence; but it implements
775 ## the methods we need so we can use it to gather-up all the sequences
776 ## and strings we parse. Thus, by the end of our parsing, it should be
777 ## the only thing left on our stack and all we have to do is return it!
778 ##
779 my $seq = Pod::ParseTree->new();
780 my @seq_stack = ($seq);
66aff6dd 781 my ($ldelim, $rdelim) = ('', '');
360aca43 782
faee740f 783 ## Iterate over all sequence starts text (NOTE: split with
784 ## capturing parens keeps the delimiters)
360aca43 785 $_ = $text;
66aff6dd 786 my @tokens = split /([A-Z]<(?:<+\s+)?)/;
787 while ( @tokens ) {
788 $_ = shift @tokens;
faee740f 789 ## Look for the beginning of a sequence
66aff6dd 790 if ( /^([A-Z])(<(?:<+\s+)?)$/ ) {
e9fdc7d2 791 ## Push a new sequence onto the stack of those "in-progress"
66aff6dd 792 ($cmd, $ldelim) = ($1, $2);
360aca43 793 $seq = Pod::InteriorSequence->new(
66aff6dd 794 -name => $cmd,
795 -ldelim => $ldelim, -rdelim => '',
796 -file => $file, -line => $line
360aca43 797 );
66aff6dd 798 $ldelim =~ s/\s+$//, ($rdelim = $ldelim) =~ tr/</>/;
360aca43 799 (@seq_stack > 1) and $seq->nested($seq_stack[-1]);
800 push @seq_stack, $seq;
801 }
66aff6dd 802 ## Look for sequence ending
803 elsif ( @seq_stack > 1 ) {
804 ## Make sure we match the right kind of closing delimiter
805 my ($seq_end, $post_seq) = ("", "");
806 if ( ($ldelim eq '<' and /\A(.*?)(>)/s)
807 or /\A(.*?)(\s+$rdelim)/s )
808 {
809 ## Found end-of-sequence, capture the interior and the
810 ## closing the delimiter, and put the rest back on the
811 ## token-list
812 $post_seq = substr($_, length($1) + length($2));
813 ($_, $seq_end) = ($1, $2);
814 (length $post_seq) and unshift @tokens, $post_seq;
815 }
816 if (length) {
817 ## In the middle of a sequence, append this text to it, and
818 ## dont forget to "expand" it if that's what the caller wanted
819 $seq->append($expand_text ? &$xtext_sub($self,$_,$seq) : $_);
820 $_ .= $seq_end;
821 }
822 if (length $seq_end) {
823 ## End of current sequence, record terminating delimiter
824 $seq->rdelim($seq_end);
825 ## Pop it off the stack of "in progress" sequences
826 pop @seq_stack;
827 ## Append result to its parent in current parse tree
828 $seq_stack[-1]->append($expand_seq ? &$xseq_sub($self,$seq)
829 : $seq);
830 ## Remember the current cmd-name and left-delimiter
831 $cmd = (@seq_stack > 1) ? $seq_stack[-1]->name : '';
832 $ldelim = (@seq_stack > 1) ? $seq_stack[-1]->ldelim : '';
833 $ldelim =~ s/\s+$//, ($rdelim = $ldelim) =~ tr/</>/;
834 }
360aca43 835 }
664bb207 836 elsif (length) {
837 ## In the middle of a sequence, append this text to it, and
838 ## dont forget to "expand" it if that's what the caller wanted
839 $seq->append($expand_text ? &$xtext_sub($self,$_,$seq) : $_);
360aca43 840 }
66aff6dd 841 ## Keep track of line count
842 $line += tr/\n//;
843 ## Remember the "current" sequence
844 $seq = $seq_stack[-1];
360aca43 845 }
846
847 ## Handle unterminated sequences
664bb207 848 my $errorsub = (@seq_stack > 1) ? $self->errorsub() : undef;
360aca43 849 while (@seq_stack > 1) {
850 ($cmd, $file, $line) = ($seq->name, $seq->file_line);
f0963acb 851 $file = VMS::Filespec::unixify($file) if $^O eq 'VMS';
66aff6dd 852 $ldelim = $seq->ldelim;
853 ($rdelim = $ldelim) =~ tr/</>/;
854 $rdelim =~ s/^(\S+)(\s*)$/$2$1/;
360aca43 855 pop @seq_stack;
a5317591 856 my $errmsg = "*** ERROR: unterminated ${cmd}${ldelim}...${rdelim}".
66aff6dd 857 " at line $line in file $file\n";
664bb207 858 (ref $errorsub) and &{$errorsub}($errmsg)
f5daac4a 859 or (defined $errorsub) and $self->$errorsub($errmsg)
664bb207 860 or warn($errmsg);
360aca43 861 $seq_stack[-1]->append($expand_seq ? &$xseq_sub($self,$seq) : $seq);
862 $seq = $seq_stack[-1];
863 }
864
865 ## Return the resulting parse-tree
866 my $ptree = (pop @seq_stack)->parse_tree;
867 return $expand_ptree ? &$xptree_sub($self, $ptree) : $ptree;
868}
869
870##---------------------------------------------------------------------------
871
872=head1 B<interpolate()>
873
874 $textblock = $parser->interpolate($text, $line_num);
875
876This method translates all text (including any embedded interior sequences)
877in the given text string C<$text> and returns the interpolated result. The
878parameter C<$line_num> is the line number corresponding to the beginning
879of C<$text>.
880
881B<interpolate()> merely invokes a private method to recursively expand
882nested interior sequences in bottom-up order (innermost sequences are
883expanded first). If there is a need to expand nested sequences in
884some alternate order, use B<parse_text> instead.
885
886=cut
887
888sub interpolate {
889 my($self, $text, $line_num) = @_;
890 my %parse_opts = ( -expand_seq => 'interior_sequence' );
891 my $ptree = $self->parse_text( \%parse_opts, $text, $line_num );
892 return join "", $ptree->children();
893}
894
895##---------------------------------------------------------------------------
896
897=begin __PRIVATE__
898
899=head1 B<parse_paragraph()>
900
901 $parser->parse_paragraph($text, $line_num);
902
903This method takes the text of a POD paragraph to be processed, along
904with its corresponding line number, and invokes the appropriate method
905(one of B<command()>, B<verbatim()>, or B<textblock()>).
906
664bb207 907For performance reasons, this method is invoked directly without any
908dynamic lookup; Hence subclasses may I<not> override it!
360aca43 909
910=end __PRIVATE__
911
912=cut
913
914sub parse_paragraph {
915 my ($self, $text, $line_num) = @_;
664bb207 916 local *myData = $self; ## alias to avoid deref-ing overhead
917 local *myOpts = ($myData{_PARSEOPTS} ||= {}); ## get parse-options
360aca43 918 local $_;
919
664bb207 920 ## See if we want to preprocess nonPOD paragraphs as well as POD ones.
e3237417 921 my $wantNonPods = $myOpts{'-want_nonPODs'};
922
923 ## Update cutting status
924 $myData{_CUTTING} = 0 if $text =~ /^={1,2}\S/;
664bb207 925
926 ## Perform any desired preprocessing if we wanted it this early
927 $wantNonPods and $text = $self->preprocess_paragraph($text, $line_num);
928
360aca43 929 ## Ignore up until next POD directive if we are cutting
e3237417 930 return if $myData{_CUTTING};
360aca43 931
932 ## Now we know this is block of text in a POD section!
933
934 ##-----------------------------------------------------------------
935 ## This is a hook (hack ;-) for Pod::Select to do its thing without
936 ## having to override methods, but also without Pod::Parser assuming
937 ## $self is an instance of Pod::Select (if the _SELECTED_SECTIONS
938 ## field exists then we assume there is an is_selected() method for
939 ## us to invoke (calling $self->can('is_selected') could verify this
940 ## but that is more overhead than I want to incur)
941 ##-----------------------------------------------------------------
942
943 ## Ignore this block if it isnt in one of the selected sections
944 if (exists $myData{_SELECTED_SECTIONS}) {
945 $self->is_selected($text) or return ($myData{_CUTTING} = 1);
946 }
947
664bb207 948 ## If we havent already, perform any desired preprocessing and
949 ## then re-check the "cutting" state
950 unless ($wantNonPods) {
951 $text = $self->preprocess_paragraph($text, $line_num);
952 return 1 unless ((defined $text) and (length $text));
953 return 1 if ($myData{_CUTTING});
954 }
360aca43 955
956 ## Look for one of the three types of paragraphs
957 my ($pfx, $cmd, $arg, $sep) = ('', '', '', '');
958 my $pod_para = undef;
959 if ($text =~ /^(={1,2})(?=\S)/) {
960 ## Looks like a command paragraph. Capture the command prefix used
961 ## ("=" or "=="), as well as the command-name, its paragraph text,
962 ## and whatever sequence of characters was used to separate them
963 $pfx = $1;
964 $_ = substr($text, length $pfx);
d23ed1f2 965 ($cmd, $sep, $text) = split /(\s+)/, $_, 2;
360aca43 966 ## If this is a "cut" directive then we dont need to do anything
967 ## except return to "cutting" mode.
968 if ($cmd eq 'cut') {
969 $myData{_CUTTING} = 1;
664bb207 970 return unless $myOpts{'-process_cut_cmd'};
360aca43 971 }
972 }
973 ## Save the attributes indicating how the command was specified.
974 $pod_para = new Pod::Paragraph(
975 -name => $cmd,
976 -text => $text,
977 -prefix => $pfx,
978 -separator => $sep,
979 -file => $myData{_INFILE},
980 -line => $line_num
981 );
982 # ## Invoke appropriate callbacks
983 # if (exists $myData{_CALLBACKS}) {
984 # ## Look through the callback list, invoke callbacks,
985 # ## then see if we need to do the default actions
986 # ## (invoke_callbacks will return true if we do).
987 # return 1 unless $self->invoke_callbacks($cmd, $text, $line_num, $pod_para);
988 # }
989 if (length $cmd) {
990 ## A command paragraph
991 $self->command($cmd, $text, $line_num, $pod_para);
992 }
993 elsif ($text =~ /^\s+/) {
994 ## Indented text - must be a verbatim paragraph
995 $self->verbatim($text, $line_num, $pod_para);
996 }
997 else {
998 ## Looks like an ordinary block of text
999 $self->textblock($text, $line_num, $pod_para);
1000 }
1001 return 1;
1002}
1003
1004##---------------------------------------------------------------------------
1005
1006=head1 B<parse_from_filehandle()>
1007
1008 $parser->parse_from_filehandle($in_fh,$out_fh);
1009
1010This method takes an input filehandle (which is assumed to already be
1011opened for reading) and reads the entire input stream looking for blocks
1012(paragraphs) of POD documentation to be processed. If no first argument
1013is given the default input filehandle C<STDIN> is used.
1014
1015The C<$in_fh> parameter may be any object that provides a B<getline()>
1016method to retrieve a single line of input text (hence, an appropriate
1017wrapper object could be used to parse PODs from a single string or an
1018array of strings).
1019
1020Using C<$in_fh-E<gt>getline()>, input is read line-by-line and assembled
1021into paragraphs or "blocks" (which are separated by lines containing
1022nothing but whitespace). For each block of POD documentation
1023encountered it will invoke a method to parse the given paragraph.
1024
1025If a second argument is given then it should correspond to a filehandle where
1026output should be sent (otherwise the default output filehandle is
1027C<STDOUT> if no output filehandle is currently in use).
1028
1029B<NOTE:> For performance reasons, this method caches the input stream at
1030the top of the stack in a local variable. Any attempts by clients to
1031change the stack contents during processing when in the midst executing
1032of this method I<will not affect> the input stream used by the current
1033invocation of this method.
1034
1035This method does I<not> usually need to be overridden by subclasses.
1036
1037=cut
1038
1039sub parse_from_filehandle {
1040 my $self = shift;
1041 my %opts = (ref $_[0] eq 'HASH') ? %{ shift() } : ();
1042 my ($in_fh, $out_fh) = @_;
22641bdf 1043 $in_fh = \*STDIN unless ($in_fh);
a5317591 1044 local *myData = $self; ## alias to avoid deref-ing overhead
1045 local *myOpts = ($myData{_PARSEOPTS} ||= {}); ## get parse-options
360aca43 1046 local $_;
1047
1048 ## Put this stream at the top of the stack and do beginning-of-input
1049 ## processing. NOTE that $in_fh might be reset during this process.
1050 my $topstream = $self->_push_input_stream($in_fh, $out_fh);
1051 (exists $opts{-cutting}) and $self->cutting( $opts{-cutting} );
1052
1053 ## Initialize line/paragraph
1054 my ($textline, $paragraph) = ('', '');
1055 my ($nlines, $plines) = (0, 0);
1056
1057 ## Use <$fh> instead of $fh->getline where possible (for speed)
1058 $_ = ref $in_fh;
1059 my $tied_fh = (/^(?:GLOB|FileHandle|IO::\w+)$/ or tied $in_fh);
1060
1061 ## Read paragraphs line-by-line
1062 while (defined ($textline = $tied_fh ? <$in_fh> : $in_fh->getline)) {
1063 $textline = $self->preprocess_line($textline, ++$nlines);
1064 next unless ((defined $textline) && (length $textline));
1065 $_ = $paragraph; ## save previous contents
1066
1067 if ((! length $paragraph) && ($textline =~ /^==/)) {
1068 ## '==' denotes a one-line command paragraph
1069 $paragraph = $textline;
1070 $plines = 1;
1071 $textline = '';
1072 } else {
1073 ## Append this line to the current paragraph
1074 $paragraph .= $textline;
1075 ++$plines;
1076 }
1077
66aff6dd 1078 ## See if this line is blank and ends the current paragraph.
360aca43 1079 ## If it isnt, then keep iterating until it is.
a5317591 1080 next unless (($textline =~ /^([^\S\r\n]*)[\r\n]*$/)
1081 && (length $paragraph));
66aff6dd 1082
1083 ## Issue a warning about any non-empty blank lines
a5317591 1084 if (length($1) > 1 and $myOpts{'-warnings'} and ! $myData{_CUTTING}) {
1085 my $errorsub = $self->errorsub();
1086 my $file = $self->input_file();
1087 $file = VMS::Filespec::unixify($file) if $^O eq 'VMS';
1088 my $errmsg = "*** WARNING: line containing nothing but whitespace".
1089 " in paragraph at line $nlines in file $file\n";
1090 (ref $errorsub) and &{$errorsub}($errmsg)
1091 or (defined $errorsub) and $self->$errorsub($errmsg)
1092 or warn($errmsg);
1093 }
360aca43 1094
1095 ## Now process the paragraph
1096 parse_paragraph($self, $paragraph, ($nlines - $plines) + 1);
1097 $paragraph = '';
1098 $plines = 0;
1099 }
1100 ## Dont forget about the last paragraph in the file
1101 if (length $paragraph) {
1102 parse_paragraph($self, $paragraph, ($nlines - $plines) + 1)
1103 }
1104
1105 ## Now pop the input stream off the top of the input stack.
1106 $self->_pop_input_stream();
1107}
1108
1109##---------------------------------------------------------------------------
1110
1111=head1 B<parse_from_file()>
1112
1113 $parser->parse_from_file($filename,$outfile);
1114
1115This method takes a filename and does the following:
1116
1117=over 2
1118
1119=item *
1120
1121opens the input and output files for reading
1122(creating the appropriate filehandles)
1123
1124=item *
1125
1126invokes the B<parse_from_filehandle()> method passing it the
1127corresponding input and output filehandles.
1128
1129=item *
1130
1131closes the input and output files.
1132
1133=back
1134
1135If the special input filename "-" or "<&STDIN" is given then the STDIN
1136filehandle is used for input (and no open or close is performed). If no
1137input filename is specified then "-" is implied.
1138
1139If a second argument is given then it should be the name of the desired
1140output file. If the special output filename "-" or ">&STDOUT" is given
1141then the STDOUT filehandle is used for output (and no open or close is
1142performed). If the special output filename ">&STDERR" is given then the
1143STDERR filehandle is used for output (and no open or close is
1144performed). If no output filehandle is currently in use and no output
1145filename is specified, then "-" is implied.
1146
1147This method does I<not> usually need to be overridden by subclasses.
1148
1149=cut
1150
1151sub parse_from_file {
1152 my $self = shift;
1153 my %opts = (ref $_[0] eq 'HASH') ? %{ shift() } : ();
1154 my ($infile, $outfile) = @_;
828c4421 1155 my ($in_fh, $out_fh) = (gensym, gensym) if ($] < 5.6);
360aca43 1156 my ($close_input, $close_output) = (0, 0);
1157 local *myData = $self;
1158 local $_;
1159
1160 ## Is $infile a filename or a (possibly implied) filehandle
1161 $infile = '-' unless ((defined $infile) && (length $infile));
1162 if (($infile eq '-') || ($infile =~ /^<&(STDIN|0)$/i)) {
1163 ## Not a filename, just a string implying STDIN
1164 $myData{_INFILE} = "<standard input>";
1165 $in_fh = \*STDIN;
1166 }
1167 elsif (ref $infile) {
1168 ## Must be a filehandle-ref (or else assume its a ref to an object
1169 ## that supports the common IO read operations).
1170 $myData{_INFILE} = ${$infile};
1171 $in_fh = $infile;
1172 }
1173 else {
1174 ## We have a filename, open it for reading
1175 $myData{_INFILE} = $infile;
475d79b5 1176 open($in_fh, "< $infile") or
360aca43 1177 croak "Can't open $infile for reading: $!\n";
1178 $close_input = 1;
1179 }
1180
1181 ## NOTE: we need to be *very* careful when "defaulting" the output
1182 ## file. We only want to use a default if this is the beginning of
1183 ## the entire document (but *not* if this is an included file). We
1184 ## determine this by seeing if the input stream stack has been set-up
1185 ## already
1186 ##
1187 unless ((defined $outfile) && (length $outfile)) {
1188 (defined $myData{_TOP_STREAM}) && ($out_fh = $myData{_OUTPUT})
1189 || ($outfile = '-');
1190 }
1191 ## Is $outfile a filename or a (possibly implied) filehandle
1192 if ((defined $outfile) && (length $outfile)) {
1193 if (($outfile eq '-') || ($outfile =~ /^>&?(?:STDOUT|1)$/i)) {
1194 ## Not a filename, just a string implying STDOUT
1195 $myData{_OUTFILE} = "<standard output>";
1196 $out_fh = \*STDOUT;
1197 }
1198 elsif ($outfile =~ /^>&(STDERR|2)$/i) {
1199 ## Not a filename, just a string implying STDERR
1200 $myData{_OUTFILE} = "<standard error>";
1201 $out_fh = \*STDERR;
1202 }
1203 elsif (ref $outfile) {
1204 ## Must be a filehandle-ref (or else assume its a ref to an
1205 ## object that supports the common IO write operations).
828c4421 1206 $myData{_OUTFILE} = ${$outfile};
360aca43 1207 $out_fh = $outfile;
1208 }
1209 else {
1210 ## We have a filename, open it for writing
1211 $myData{_OUTFILE} = $outfile;
828c4421 1212 (-d $outfile) and croak "$outfile is a directory, not POD input!\n";
475d79b5 1213 open($out_fh, "> $outfile") or
360aca43 1214 croak "Can't open $outfile for writing: $!\n";
1215 $close_output = 1;
1216 }
1217 }
1218
1219 ## Whew! That was a lot of work to set up reasonably/robust behavior
1220 ## in the case of a non-filename for reading and writing. Now we just
1221 ## have to parse the input and close the handles when we're finished.
1222 $self->parse_from_filehandle(\%opts, $in_fh, $out_fh);
1223
1224 $close_input and
1225 close($in_fh) || croak "Can't close $infile after reading: $!\n";
1226 $close_output and
1227 close($out_fh) || croak "Can't close $outfile after writing: $!\n";
1228}
1229
1230#############################################################################
1231
1232=head1 ACCESSOR METHODS
1233
1234Clients of B<Pod::Parser> should use the following methods to access
1235instance data fields:
1236
1237=cut
1238
1239##---------------------------------------------------------------------------
1240
664bb207 1241=head1 B<errorsub()>
1242
1243 $parser->errorsub("method_name");
1244 $parser->errorsub(\&warn_user);
1245 $parser->errorsub(sub { print STDERR, @_ });
1246
1247Specifies the method or subroutine to use when printing error messages
1248about POD syntax. The supplied method/subroutine I<must> return TRUE upon
1249successful printing of the message. If C<undef> is given, then the B<warn>
1250builtin is used to issue error messages (this is the default behavior).
1251
1252 my $errorsub = $parser->errorsub()
1253 my $errmsg = "This is an error message!\n"
1254 (ref $errorsub) and &{$errorsub}($errmsg)
e3237417 1255 or (defined $errorsub) and $parser->$errorsub($errmsg)
664bb207 1256 or warn($errmsg);
1257
1258Returns a method name, or else a reference to the user-supplied subroutine
1259used to print error messages. Returns C<undef> if the B<warn> builtin
1260is used to issue error messages (this is the default behavior).
1261
1262=cut
1263
1264sub errorsub {
1265 return (@_ > 1) ? ($_[0]->{_ERRORSUB} = $_[1]) : $_[0]->{_ERRORSUB};
1266}
1267
1268##---------------------------------------------------------------------------
1269
360aca43 1270=head1 B<cutting()>
1271
1272 $boolean = $parser->cutting();
1273
1274Returns the current C<cutting> state: a boolean-valued scalar which
1275evaluates to true if text from the input file is currently being "cut"
1276(meaning it is I<not> considered part of the POD document).
1277
1278 $parser->cutting($boolean);
1279
1280Sets the current C<cutting> state to the given value and returns the
1281result.
1282
1283=cut
1284
1285sub cutting {
1286 return (@_ > 1) ? ($_[0]->{_CUTTING} = $_[1]) : $_[0]->{_CUTTING};
1287}
1288
1289##---------------------------------------------------------------------------
1290
664bb207 1291##---------------------------------------------------------------------------
1292
1293=head1 B<parseopts()>
1294
1295When invoked with no additional arguments, B<parseopts> returns a hashtable
1296of all the current parsing options.
1297
1298 ## See if we are parsing non-POD sections as well as POD ones
1299 my %opts = $parser->parseopts();
1300 $opts{'-want_nonPODs}' and print "-want_nonPODs\n";
1301
1302When invoked using a single string, B<parseopts> treats the string as the
1303name of a parse-option and returns its corresponding value if it exists
1304(returns C<undef> if it doesn't).
1305
1306 ## Did we ask to see '=cut' paragraphs?
1307 my $want_cut = $parser->parseopts('-process_cut_cmd');
1308 $want_cut and print "-process_cut_cmd\n";
1309
1310When invoked with multiple arguments, B<parseopts> treats them as
1311key/value pairs and the specified parse-option names are set to the
1312given values. Any unspecified parse-options are unaffected.
1313
1314 ## Set them back to the default
a5317591 1315 $parser->parseopts(-warnings => 0);
664bb207 1316
1317When passed a single hash-ref, B<parseopts> uses that hash to completely
1318reset the existing parse-options, all previous parse-option values
1319are lost.
1320
1321 ## Reset all options to default
1322 $parser->parseopts( { } );
1323
a5317591 1324See L<"PARSING OPTIONS"> for more information on the name and meaning of each
664bb207 1325parse-option currently recognized.
1326
1327=cut
1328
1329sub parseopts {
1330 local *myData = shift;
1331 local *myOpts = ($myData{_PARSEOPTS} ||= {});
1332 return %myOpts if (@_ == 0);
1333 if (@_ == 1) {
1334 local $_ = shift;
1335 return ref($_) ? $myData{_PARSEOPTS} = $_ : $myOpts{$_};
1336 }
1337 my @newOpts = (%myOpts, @_);
1338 $myData{_PARSEOPTS} = { @newOpts };
1339}
1340
1341##---------------------------------------------------------------------------
1342
360aca43 1343=head1 B<output_file()>
1344
1345 $fname = $parser->output_file();
1346
1347Returns the name of the output file being written.
1348
1349=cut
1350
1351sub output_file {
1352 return $_[0]->{_OUTFILE};
1353}
1354
1355##---------------------------------------------------------------------------
1356
1357=head1 B<output_handle()>
1358
1359 $fhandle = $parser->output_handle();
1360
1361Returns the output filehandle object.
1362
1363=cut
1364
1365sub output_handle {
1366 return $_[0]->{_OUTPUT};
1367}
1368
1369##---------------------------------------------------------------------------
1370
1371=head1 B<input_file()>
1372
1373 $fname = $parser->input_file();
1374
1375Returns the name of the input file being read.
1376
1377=cut
1378
1379sub input_file {
1380 return $_[0]->{_INFILE};
1381}
1382
1383##---------------------------------------------------------------------------
1384
1385=head1 B<input_handle()>
1386
1387 $fhandle = $parser->input_handle();
1388
1389Returns the current input filehandle object.
1390
1391=cut
1392
1393sub input_handle {
1394 return $_[0]->{_INPUT};
1395}
1396
1397##---------------------------------------------------------------------------
1398
1399=begin __PRIVATE__
1400
1401=head1 B<input_streams()>
1402
1403 $listref = $parser->input_streams();
1404
1405Returns a reference to an array which corresponds to the stack of all
1406the input streams that are currently in the middle of being parsed.
1407
1408While parsing an input stream, it is possible to invoke
1409B<parse_from_file()> or B<parse_from_filehandle()> to parse a new input
1410stream and then return to parsing the previous input stream. Each input
1411stream to be parsed is pushed onto the end of this input stack
1412before any of its input is read. The input stream that is currently
1413being parsed is always at the end (or top) of the input stack. When an
1414input stream has been exhausted, it is popped off the end of the
1415input stack.
1416
1417Each element on this input stack is a reference to C<Pod::InputSource>
1418object. Please see L<Pod::InputObjects> for more details.
1419
1420This method might be invoked when printing diagnostic messages, for example,
1421to obtain the name and line number of the all input files that are currently
1422being processed.
1423
1424=end __PRIVATE__
1425
1426=cut
1427
1428sub input_streams {
1429 return $_[0]->{_INPUT_STREAMS};
1430}
1431
1432##---------------------------------------------------------------------------
1433
1434=begin __PRIVATE__
1435
1436=head1 B<top_stream()>
1437
1438 $hashref = $parser->top_stream();
1439
1440Returns a reference to the hash-table that represents the element
1441that is currently at the top (end) of the input stream stack
1442(see L<"input_streams()">). The return value will be the C<undef>
1443if the input stack is empty.
1444
1445This method might be used when printing diagnostic messages, for example,
1446to obtain the name and line number of the current input file.
1447
1448=end __PRIVATE__
1449
1450=cut
1451
1452sub top_stream {
1453 return $_[0]->{_TOP_STREAM} || undef;
1454}
1455
1456#############################################################################
1457
1458=head1 PRIVATE METHODS AND DATA
1459
1460B<Pod::Parser> makes use of several internal methods and data fields
1461which clients should not need to see or use. For the sake of avoiding
1462name collisions for client data and methods, these methods and fields
1463are briefly discussed here. Determined hackers may obtain further
1464information about them by reading the B<Pod::Parser> source code.
1465
1466Private data fields are stored in the hash-object whose reference is
1467returned by the B<new()> constructor for this class. The names of all
1468private methods and data-fields used by B<Pod::Parser> begin with a
1469prefix of "_" and match the regular expression C</^_\w+$/>.
1470
1471=cut
1472
1473##---------------------------------------------------------------------------
1474
1475=begin _PRIVATE_
1476
1477=head1 B<_push_input_stream()>
1478
1479 $hashref = $parser->_push_input_stream($in_fh,$out_fh);
1480
1481This method will push the given input stream on the input stack and
1482perform any necessary beginning-of-document or beginning-of-file
1483processing. The argument C<$in_fh> is the input stream filehandle to
1484push, and C<$out_fh> is the corresponding output filehandle to use (if
1485it is not given or is undefined, then the current output stream is used,
1486which defaults to standard output if it doesnt exist yet).
1487
1488The value returned will be reference to the hash-table that represents
1489the new top of the input stream stack. I<Please Note> that it is
1490possible for this method to use default values for the input and output
1491file handles. If this happens, you will need to look at the C<INPUT>
1492and C<OUTPUT> instance data members to determine their new values.
1493
1494=end _PRIVATE_
1495
1496=cut
1497
1498sub _push_input_stream {
1499 my ($self, $in_fh, $out_fh) = @_;
1500 local *myData = $self;
1501
1502 ## Initialize stuff for the entire document if this is *not*
1503 ## an included file.
1504 ##
1505 ## NOTE: we need to be *very* careful when "defaulting" the output
1506 ## filehandle. We only want to use a default value if this is the
1507 ## beginning of the entire document (but *not* if this is an included
1508 ## file).
1509 unless (defined $myData{_TOP_STREAM}) {
1510 $out_fh = \*STDOUT unless (defined $out_fh);
1511 $myData{_CUTTING} = 1; ## current "cutting" state
1512 $myData{_INPUT_STREAMS} = []; ## stack of all input streams
1513 }
1514
1515 ## Initialize input indicators
1516 $myData{_OUTFILE} = '(unknown)' unless (defined $myData{_OUTFILE});
1517 $myData{_OUTPUT} = $out_fh if (defined $out_fh);
1518 $in_fh = \*STDIN unless (defined $in_fh);
1519 $myData{_INFILE} = '(unknown)' unless (defined $myData{_INFILE});
1520 $myData{_INPUT} = $in_fh;
1521 my $input_top = $myData{_TOP_STREAM}
1522 = new Pod::InputSource(
1523 -name => $myData{_INFILE},
1524 -handle => $in_fh,
1525 -was_cutting => $myData{_CUTTING}
1526 );
1527 local *input_stack = $myData{_INPUT_STREAMS};
1528 push(@input_stack, $input_top);
1529
1530 ## Perform beginning-of-document and/or beginning-of-input processing
1531 $self->begin_pod() if (@input_stack == 1);
1532 $self->begin_input();
1533
1534 return $input_top;
1535}
1536
1537##---------------------------------------------------------------------------
1538
1539=begin _PRIVATE_
1540
1541=head1 B<_pop_input_stream()>
1542
1543 $hashref = $parser->_pop_input_stream();
1544
1545This takes no arguments. It will perform any necessary end-of-file or
1546end-of-document processing and then pop the current input stream from
1547the top of the input stack.
1548
1549The value returned will be reference to the hash-table that represents
1550the new top of the input stream stack.
1551
1552=end _PRIVATE_
1553
1554=cut
1555
1556sub _pop_input_stream {
1557 my ($self) = @_;
1558 local *myData = $self;
1559 local *input_stack = $myData{_INPUT_STREAMS};
1560
1561 ## Perform end-of-input and/or end-of-document processing
1562 $self->end_input() if (@input_stack > 0);
1563 $self->end_pod() if (@input_stack == 1);
1564
1565 ## Restore cutting state to whatever it was before we started
1566 ## parsing this file.
1567 my $old_top = pop(@input_stack);
1568 $myData{_CUTTING} = $old_top->was_cutting();
1569
1570 ## Dont forget to reset the input indicators
1571 my $input_top = undef;
1572 if (@input_stack > 0) {
1573 $input_top = $myData{_TOP_STREAM} = $input_stack[-1];
1574 $myData{_INFILE} = $input_top->name();
1575 $myData{_INPUT} = $input_top->handle();
1576 } else {
1577 delete $myData{_TOP_STREAM};
1578 delete $myData{_INPUT_STREAMS};
1579 }
1580
1581 return $input_top;
1582}
1583
1584#############################################################################
1585
664bb207 1586=head1 TREE-BASED PARSING
1587
1588If straightforward stream-based parsing wont meet your needs (as is
1589likely the case for tasks such as translating PODs into structured
1590markup languages like HTML and XML) then you may need to take the
1591tree-based approach. Rather than doing everything in one pass and
1592calling the B<interpolate()> method to expand sequences into text, it
1593may be desirable to instead create a parse-tree using the B<parse_text()>
1594method to return a tree-like structure which may contain an ordered list
1595list of children (each of which may be a text-string, or a similar
1596tree-like structure).
1597
1598Pay special attention to L<"METHODS FOR PARSING AND PROCESSING"> and
1599to the objects described in L<Pod::InputObjects>. The former describes
1600the gory details and parameters for how to customize and extend the
1601parsing behavior of B<Pod::Parser>. B<Pod::InputObjects> provides
1602several objects that may all be used interchangeably as parse-trees. The
1603most obvious one is the B<Pod::ParseTree> object. It defines the basic
1604interface and functionality that all things trying to be a POD parse-tree
1605should do. A B<Pod::ParseTree> is defined such that each "node" may be a
1606text-string, or a reference to another parse-tree. Each B<Pod::Paragraph>
1607object and each B<Pod::InteriorSequence> object also supports the basic
1608parse-tree interface.
1609
1610The B<parse_text()> method takes a given paragraph of text, and
1611returns a parse-tree that contains one or more children, each of which
1612may be a text-string, or an InteriorSequence object. There are also
1613callback-options that may be passed to B<parse_text()> to customize
1614the way it expands or transforms interior-sequences, as well as the
1615returned result. These callbacks can be used to create a parse-tree
1616with custom-made objects (which may or may not support the parse-tree
1617interface, depending on how you choose to do it).
1618
1619If you wish to turn an entire POD document into a parse-tree, that process
1620is fairly straightforward. The B<parse_text()> method is the key to doing
1621this successfully. Every paragraph-callback (i.e. the polymorphic methods
1622for B<command()>, B<verbatim()>, and B<textblock()> paragraphs) takes
1623a B<Pod::Paragraph> object as an argument. Each paragraph object has a
1624B<parse_tree()> method that can be used to get or set a corresponding
1625parse-tree. So for each of those paragraph-callback methods, simply call
1626B<parse_text()> with the options you desire, and then use the returned
1627parse-tree to assign to the given paragraph object.
1628
1629That gives you a parse-tree for each paragraph - so now all you need is
1630an ordered list of paragraphs. You can maintain that yourself as a data
1631element in the object/hash. The most straightforward way would be simply
1632to use an array-ref, with the desired set of custom "options" for each
1633invocation of B<parse_text>. Let's assume the desired option-set is
1634given by the hash C<%options>. Then we might do something like the
1635following:
1636
1637 package MyPodParserTree;
1638
1639 @ISA = qw( Pod::Parser );
1640
1641 ...
1642
1643 sub begin_pod {
1644 my $self = shift;
1645 $self->{'-paragraphs'} = []; ## initialize paragraph list
1646 }
1647
1648 sub command {
1649 my ($parser, $command, $paragraph, $line_num, $pod_para) = @_;
1650 my $ptree = $parser->parse_text({%options}, $paragraph, ...);
1651 $pod_para->parse_tree( $ptree );
1652 push @{ $self->{'-paragraphs'} }, $pod_para;
1653 }
1654
1655 sub verbatim {
1656 my ($parser, $paragraph, $line_num, $pod_para) = @_;
1657 push @{ $self->{'-paragraphs'} }, $pod_para;
1658 }
1659
1660 sub textblock {
1661 my ($parser, $paragraph, $line_num, $pod_para) = @_;
1662 my $ptree = $parser->parse_text({%options}, $paragraph, ...);
1663 $pod_para->parse_tree( $ptree );
1664 push @{ $self->{'-paragraphs'} }, $pod_para;
1665 }
1666
1667 ...
1668
1669 package main;
1670 ...
1671 my $parser = new MyPodParserTree(...);
1672 $parser->parse_from_file(...);
1673 my $paragraphs_ref = $parser->{'-paragraphs'};
1674
1675Of course, in this module-author's humble opinion, I'd be more inclined to
1676use the existing B<Pod::ParseTree> object than a simple array. That way
1677everything in it, paragraphs and sequences, all respond to the same core
1678interface for all parse-tree nodes. The result would look something like:
1679
1680 package MyPodParserTree2;
1681
1682 ...
1683
1684 sub begin_pod {
1685 my $self = shift;
1686 $self->{'-ptree'} = new Pod::ParseTree; ## initialize parse-tree
1687 }
1688
1689 sub parse_tree {
1690 ## convenience method to get/set the parse-tree for the entire POD
1691 (@_ > 1) and $_[0]->{'-ptree'} = $_[1];
1692 return $_[0]->{'-ptree'};
1693 }
1694
1695 sub command {
1696 my ($parser, $command, $paragraph, $line_num, $pod_para) = @_;
1697 my $ptree = $parser->parse_text({<<options>>}, $paragraph, ...);
1698 $pod_para->parse_tree( $ptree );
1699 $parser->parse_tree()->append( $pod_para );
1700 }
1701
1702 sub verbatim {
1703 my ($parser, $paragraph, $line_num, $pod_para) = @_;
1704 $parser->parse_tree()->append( $pod_para );
1705 }
1706
1707 sub textblock {
1708 my ($parser, $paragraph, $line_num, $pod_para) = @_;
1709 my $ptree = $parser->parse_text({<<options>>}, $paragraph, ...);
1710 $pod_para->parse_tree( $ptree );
1711 $parser->parse_tree()->append( $pod_para );
1712 }
1713
1714 ...
1715
1716 package main;
1717 ...
1718 my $parser = new MyPodParserTree2(...);
1719 $parser->parse_from_file(...);
1720 my $ptree = $parser->parse_tree;
1721 ...
1722
1723Now you have the entire POD document as one great big parse-tree. You
1724can even use the B<-expand_seq> option to B<parse_text> to insert
1725whole different kinds of objects. Just don't expect B<Pod::Parser>
1726to know what to do with them after that. That will need to be in your
1727code. Or, alternatively, you can insert any object you like so long as
1728it conforms to the B<Pod::ParseTree> interface.
1729
1730One could use this to create subclasses of B<Pod::Paragraphs> and
1731B<Pod::InteriorSequences> for specific commands (or to create your own
1732custom node-types in the parse-tree) and add some kind of B<emit()>
1733method to each custom node/subclass object in the tree. Then all you'd
1734need to do is recursively walk the tree in the desired order, processing
1735the children (most likely from left to right) by formatting them if
1736they are text-strings, or by calling their B<emit()> method if they
1737are objects/references.
1738
360aca43 1739=head1 SEE ALSO
1740
1741L<Pod::InputObjects>, L<Pod::Select>
1742
1743B<Pod::InputObjects> defines POD input objects corresponding to
1744command paragraphs, parse-trees, and interior-sequences.
1745
1746B<Pod::Select> is a subclass of B<Pod::Parser> which provides the ability
1747to selectively include and/or exclude sections of a POD document from being
1748translated based upon the current heading, subheading, subsubheading, etc.
1749
1750=for __PRIVATE__
1751B<Pod::Callbacks> is a subclass of B<Pod::Parser> which gives its users
1752the ability the employ I<callback functions> instead of, or in addition
1753to, overriding methods of the base class.
1754
1755=for __PRIVATE__
1756B<Pod::Select> and B<Pod::Callbacks> do not override any
1757methods nor do they define any new methods with the same name. Because
1758of this, they may I<both> be used (in combination) as a base class of
1759the same subclass in order to combine their functionality without
1760causing any namespace clashes due to multiple inheritance.
1761
1762=head1 AUTHOR
1763
1764Brad Appleton E<lt>bradapp@enteract.comE<gt>
1765
1766Based on code for B<Pod::Text> written by
1767Tom Christiansen E<lt>tchrist@mox.perl.comE<gt>
1768
1769=cut
1770
17711;