Subversion Repositories DevTools

Rev

Details | Last modification | View Log | RSS feed

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