1 #============================================================= -*-Perl-*-
6 # Parses POD from a file or text string and builds a tree structure,
7 # hereafter known as the POD Object Model (POM).
10 # Andy Wardley <abw@wardley.org>
12 # Andrew Ford <A.Ford@ford-mason.co.uk> (co-maintainer as of 03/2009)
15 # Copyright (C) 2000-2009 Andy Wardley. All Rights Reserved.
16 # Copyright (C) 2009 Andrew Ford. All Rights Reserved.
18 # This module is free software; you can redistribute it and/or
19 # modify it under the same terms as Perl itself.
22 # $Id: POM.pm 88 2010-04-02 13:37:41Z ford $
24 #========================================================================
26 package BASIS::Pod::POM;
31 use BASIS::Pod::POM::Constants qw( :all );
32 use BASIS::Pod::POM::Nodes;
33 use BASIS::Pod::POM::View::Pod;
35 use vars qw( $VERSION $DEBUG $ERROR $ROOT $TEXTSEQ $DEFAULT_VIEW );
36 use base qw( Exporter );
39 $DEBUG = 0 unless defined $DEBUG;
40 $ROOT = 'BASIS::Pod::POM::Node::Pod'; # root node class
41 $TEXTSEQ = 'BASIS::Pod::POM::Node::Sequence'; # text sequence class
42 $DEFAULT_VIEW = 'BASIS::Pod::POM::View::Pod'; # default view class
45 #------------------------------------------------------------------------
46 # allow 'meta' to be specified as a load option to activate =meta tags
47 #------------------------------------------------------------------------
49 use vars qw( @EXPORT_FAIL @EXPORT_OK $ALLOW_META );
50 @EXPORT_OK = qw( meta );
51 @EXPORT_FAIL = qw( meta );
57 return ($meta, @_) unless $meta eq 'meta';
64 #------------------------------------------------------------------------
66 #------------------------------------------------------------------------
70 my $config = ref $_[0] eq 'HASH' ? shift : { @_ };
73 CODE => $config->{ code } || 0,
74 WARN => $config->{ warn } || 0,
75 META => $config->{ meta } || $ALLOW_META,
83 #------------------------------------------------------------------------
84 # parse($text_or_file)
86 # General purpose parse method which attempts to Do The Right Thing in
87 # calling parse_file() or parse_text() according to the argument
88 # passed. A hash reference can be specified that contains a 'text'
89 # or 'file' key and corresponding value. Otherwise, the argument can
90 # be a reference to an input handle which is passed off to parse_file().
91 # If the argument is a text string that contains '=' at the start of
92 # any line then it is treated as Pod text and passed to parse_text(),
93 # otherwise it is assumed to be a filename and passed to parse_file().
94 #------------------------------------------------------------------------
97 my ($self, $input) = @_;
100 if (ref $input eq 'HASH') {
101 if ($input = $input->{ text }) {
102 $result = $self->parse_text($input, $input->{ name });
104 elsif ($input = $input->{ file }) {
105 $result = $self->parse_file($input);
108 $result = $self->error("no 'text' or 'file' specified");
111 elsif (ref $input || $input !~ /^=/m) { # doesn't look like POD text
112 $result = $self->parse_file($input);
114 else { # looks like POD text
115 $result = $self->parse_text($input);
122 #------------------------------------------------------------------------
123 # parse_file($filename_or_handle)
125 # Reads the content of a Pod file specified by name or file handle, and
126 # passes it to parse_text() for parsing.
127 #------------------------------------------------------------------------
130 my ($self, $file) = @_;
133 if (ref $file) { # assume open filehandle
135 $name = '<filehandle>';
138 else { # a file which must be opened
141 $name = ( $file eq '-' ? '<standard input>' : $file );
142 open(FP, $file) || return $self->error("$file: $!");
147 $self->parse_text($text, $name);
151 #------------------------------------------------------------------------
152 # parse_text($text, $name)
154 # Main parser method. Scans the input text for Pod sections and splits
155 # them into paragraphs. Builds a tree of Pod::POM::Node::* objects
156 # to represent the Pod document in object model form.
157 #------------------------------------------------------------------------
160 my ($self, $text, $name) = @_;
161 my ($para, $paralen, $gap, $type, $line, $inpod, $code, $result, $verbatim);
162 my $warn = $self->{ WARNINGS } = [ ];
165 my $item = $ROOT->new($self);
166 return $self->error($ROOT->error())
167 unless defined $item;
170 $name = '<input text>' unless defined $name;
171 $self->{ FILENAME } = $name;
173 $code = $self->{ CODE };
174 $line = \$self->{ LINE };
178 my @encchunks = split /^(=encoding.*)/m, $text;
179 $text = shift @encchunks;
181 my($encline,$chunk) = splice @encchunks, 0, 2;
183 my($encoding) = $encline =~ /^=encoding\s+(\S+)/;
184 Encode::from_to($chunk, $encoding, "utf8");
185 Encode::_utf8_on($chunk);
186 # $text .= "xxx$encline";
191 # while ($text =~ /(?:(.*?)(\n{2,}))|(.+$)/sg) {
192 while ($text =~ /(?:(.*?)((?:\s*\n){2,}))|(.+$)/sg) {
193 ($para, $gap) = defined $1 ? ($1, $2) : ($3, '');
195 if ($para =~ s/^==?(\w+)\s*//) {
197 # switch on for =pod or any other =cmd, switch off for =cut
198 if ($type eq 'pod') { $inpod = 1; next }
199 elsif ($type eq 'cut') { $inpod = 0; next }
202 if ($type eq 'meta') {
204 ? $stack[0]->metadata(split(/\s+/, $para, 2))
205 : $self->warning("metadata not allowed", $name, $$line);
215 elsif ($para =~ /^\s+/) {
222 chomp($para); # catches last line in file
227 $verbatim =~ s/\s+$//s;
228 $result = $stack[-1]->add($self, 'verbatim', $verbatim);
230 if (! defined $result) {
231 $self->warning($stack[-1]->error(), $name, $$line);
235 elsif (ref $result) {
236 push(@stack, $result);
240 elsif ($result == REDUCE) {
245 elsif ($result == REJECT) {
246 $self->warning($stack[-1]->error(), $name, $$line);
249 elsif (@stack == 1) {
250 $self->warning("unexpected $type", $name, $$line);
261 $result = $stack[-1]->add($self, $type, $para);
263 if (! defined $result) {
264 $self->warning($stack[-1]->error(), $name, $$line);
267 elsif (ref $result) {
268 push(@stack, $result);
271 elsif ($result == REDUCE) {
275 elsif ($result == REJECT) {
276 $self->warning($stack[-1]->error(), $name, $$line);
279 elsif (@stack == 1) {
280 $self->warning("unexpected $type", $name, $$line);
289 $$line += ($para =~ tr/\n//);
290 $$line += ($gap =~ tr/\n//);
295 $verbatim =~ s/\s+$//s;
296 $result = $stack[-1]->add($self, 'verbatim', $verbatim);
298 if (! defined $result) {
299 $self->warning($stack[-1]->error(), $name, $$line);
303 elsif (ref $result) {
304 push(@stack, $result);
308 elsif ($result == REDUCE) {
313 elsif ($result == REJECT) {
314 $self->warning($stack[-1]->error(), $name, $$line);
317 elsif (@stack == 1) {
318 $self->warning("unexpected $type", $name, $$line);
332 #------------------------------------------------------------------------
333 # parse_sequence($text)
335 # Parse a text paragraph to identify internal sequences (e.g. B<foo>)
336 # which may be nested within each other. Returns a simple scalar (no
337 # embedded sequences) or a reference to a Pod::POM::Text object.
338 #------------------------------------------------------------------------
341 my ($self, $text) = @_;
342 my ($cmd, $lparen, $rparen, $plain);
343 my ($name, $line, $warn) = @$self{ qw( FILENAME LINE WARNINGS ) };
346 push(@stack, [ '', '', 'EOF', $name, $line, [ ] ] );
349 (?: ([A-Z]) (< (?:<+\s)?) ) # open
350 | ( (?:\s>+)? > ) # or close
351 | (?: (.+?) # or text...
354 | (?: (?: \s>+)? > ) # or close
360 ($cmd, $lparen) = ($1, $2);
362 ($rparen = $lparen) =~ tr/</>/;
363 push(@stack, [ $cmd, $lparen, $rparen, $name, $line, [ ] ]);
368 if ($rparen eq $stack[-1]->[RPAREN]) {
369 $cmd = $TEXTSEQ->new(pop(@stack))
370 || return $self->error($TEXTSEQ->error());
371 push(@{ $stack[-1]->[CONTENT] }, $cmd);
374 $self->warning((scalar @stack > 1
375 ? "expected '$stack[-1]->[RPAREN]' not '$rparen'"
376 : "spurious '$rparen'"), $name, $line);
377 push(@{ $stack[-1]->[CONTENT] }, $rparen);
382 push(@{ $stack[-1]->[CONTENT] }, $plain);
383 $line += ($plain =~ tr/\n//);
386 $self->warning("unexpected end of input", $name, $line);
393 $self->warning("unterminated '$cmd->[CMD]$cmd->[LPAREN]' starting",
394 $name, $cmd->[LINE]);
395 $cmd = $TEXTSEQ->new($cmd)
396 || $self->error($TEXTSEQ->error());
397 push(@{ $stack[-1]->[CONTENT] }, $cmd);
400 return $TEXTSEQ->new(pop(@stack))
401 || $self->error($TEXTSEQ->error());
405 #------------------------------------------------------------------------
406 # default_view($viewer)
408 # Accessor method to return or update the $DEFVIEW package variable,
409 # loading the module for any package name specified.
410 #------------------------------------------------------------------------
413 my ($self, $viewer) = @_;
414 return $DEFAULT_VIEW unless $viewer;
415 unless (ref $viewer) {
419 eval { require $file };
420 return $self->error($@) if $@;
423 return ($DEFAULT_VIEW = $viewer);
427 #------------------------------------------------------------------------
428 # warning($msg, $file, $line)
430 # Appends a string of the form " at $file line $line" to $msg if
431 # $file is specified and then stores $msg in the internals
432 # WARNINGS list. If the WARN option is set then the warning is
433 # raised, either via warn(), or by dispatching to a subroutine
434 # when WARN is defined as such.
435 #------------------------------------------------------------------------
438 my ($self, $msg, $file, $line) = @_;
439 my $warn = $self->{ WARN };
440 $line = 'unknown' unless defined $line && length $line;
441 $msg .= " at $file line $line" if $file;
443 push(@{ $self->{ WARNINGS } }, $msg);
445 if (ref $warn eq 'CODE') {
454 #------------------------------------------------------------------------
457 # Returns a reference to the (possibly empty) list of warnings raised by
458 # the most recent call to any of the parse_XXX() methods
459 #------------------------------------------------------------------------
463 return wantarray ? @{ $self->{ WARNINGS } } : $self->{ WARNINGS };
467 #------------------------------------------------------------------------
470 # Sets the internal ERROR member and returns undef when called with an
471 # argument(s), returns the current value when called without.
472 #------------------------------------------------------------------------
479 no strict qw( refs );
481 $errvar = \$self->{ ERROR };
484 $errvar = \${"$self\::ERROR"};
488 $$errvar = ref($_[0]) ? shift : join('', @_);
499 print STDERR "DEBUG: ", @_ if $DEBUG;
508 Pod::POM - POD Object Model
514 my $parser = Pod::POM->new(\%options);
516 # parse from a text string
517 my $pom = $parser->parse_text($text)
518 || die $parser->error();
520 # parse from a file specified by name or filehandle
521 my $pom = $parser->parse_file($file)
522 || die $parser->error();
524 # parse from text or file
525 my $pom = $parser->parse($text_or_file)
526 || die $parser->error();
528 # examine any warnings raised
529 foreach my $warning ($parser->warnings()) {
533 # print table of contents using each =head1 title
534 foreach my $head1 ($pom->head1()) {
535 print $head1->title(), "\n";
539 foreach my $head1 ($pom->head1()) {
540 print $head1->title(), "\n";
541 print $head1->content();
544 # print the entire document as HTML
545 use Pod::POM::View::HTML;
546 print Pod::POM::View::HTML->print($pom);
550 use base qw( Pod::POM::View::HTML );
553 my ($self, $item) = @_;
555 $item->title->present($self),
557 $item->content->present($self);
561 print My::View->print($pom);
565 This module implements a parser to convert Pod documents into a simple
566 object model form known hereafter as the Pod Object Model. The object
567 model is generated as a hierarchical tree of nodes, each of which
568 represents a different element of the original document. The tree can
569 be walked manually and the nodes examined, printed or otherwise
570 manipulated. In addition, Pod::POM supports and provides view objects
571 which can automatically traverse the tree, or section thereof, and
572 generate an output representation in one form or another.
574 Let's look at a typical Pod document by way of example.
578 My::Module - just another My::Module
582 This is My::Module, a deeply funky piece of Perl code.
586 My::Module implements the following methods
592 This is the constructor method. It accepts the following
593 configuration options:
599 The name of the thingy.
603 The colour of the thingy.
609 This prints the thingy.
615 My::Module was written by me E<lt>me@here.orgE<gt>
617 This document contains 3 main sections, NAME, DESCRIPTION and
618 AUTHOR, each of which is delimited by an opening C<=head1> tag.
619 NAME and AUTHOR each contain only a single line of text, but
620 DESCRIPTION is more interesting. It contains a line of text
621 followed by the C<=head2> subsection, METHODS. This contains
622 a line of text and a list extending from the C<=over 4> to the
623 final C<=back> just before the AUTHOR section starts. The list
624 contains 2 items, C<new(\%config)>, which itself contains some
625 text and a list of 2 items, and C<print()>.
627 Presented as plain text and using indentation to indicate the element
628 nesting, the model then looks something like this :
631 My::Module - just another My::Module
634 This is My::Module, a deeply funky piece of Perl code.
637 My::Module implements the following methods
640 This is the constructor method. It accepts the
641 following configuration options:
644 The name of the thingy.
647 The colour of the thingy.
650 This prints the thingy.
653 My::Myodule was written by me <me@here.org>
655 Those of you familiar with XML may prefer to think of it in the
660 <p>My::Module - just another My::Module</p>
663 <head1 title="DESCRIPTION">
664 <p>This is My::Module, a deeply funky piece of
667 <head2 title="METHODS">
668 <p>My::Module implements the following methods</p>
671 <item title="item new(\%config)">
672 <p>This is the constructor method. It accepts
673 the following configuration options:</p>
677 <p>The name of the thingy.</p>
680 <item title="colour">
681 <p>The colour of the thingy.</p>
686 <item title="print()">
687 <p>This prints the thingy.</p>
693 <head1 title="AUTHOR">
694 <p>My::Myodule was written by me <me@here.org>
698 Notice how we can make certain assumptions about various elements.
699 For example, we can assume that any C<=head1> section we find begins a
700 new section and implicitly ends any previous section. Similarly, we
701 can assume an C<=item> ends when the next one begins, and so on. In
702 terms of the XML example shown above, we are saying that we're smart
703 enough to add a C<E<lt>/head1E<gt>> element to terminate any
704 previously opened C<E<lt>head1E<gt>> when we find a new C<=head1> tag
705 in the input document.
707 However you like to visualise the content, it all comes down to the
708 same underlying model. The job of the Pod::POM module is to read an
709 input Pod document and build an object model to represent it in this
712 Each node in the tree (i.e. element in the document) is represented
713 by a Pod::POM::Node::* object. These encapsulate the attributes for
714 an element (such as the title for a C<=head1> tag) and also act as
715 containers for further Pod::POM::Node::* objects representing the
716 content of the element. Right down at the leaf nodes, we have simple
717 object types to represent formatted and verbatim text paragraphs and
718 other basic elements like these.
722 The Pod::POM module implements the methods parse_file($file),
723 parse_text($text) and parse($file_or_text) to parse Pod files and
724 input text. They return a Pod::POM::Node::Pod object to represent the
725 root of the Pod Object Model, effectively the C<E<lt>podE<gt>> element
726 in the XML tree shown above.
730 my $parser = Pod::POM->new();
731 my $pom = $parser->parse_file($filename)
732 || die $parser->error();
734 The parse(), parse_text() and parse_file() methods return
735 undef on error. The error() method can be called to retrieve the
736 error message generated. Parsing a document may also generate
737 non-fatal warnings. These can be retrieved via the warnings() method
738 which returns a reference to a list when called in scalar context or a
739 list of warnings when called in list context.
741 foreach my $warn ($parser->warnings()) {
745 Alternatively, the 'warn' configuration option can be set to have
746 warnings automatically raised via C<warn()> as they are encountered.
748 my $parser = Pod::POM->new( warn => 1 );
750 =head2 Walking the Object Model
752 Having parsed a document into an object model, we can then select
753 various items from it. Each node implements methods (via AUTOLOAD)
754 which correspond to the attributes and content elements permitted
757 So to fetch the list of '=head1' sections within our parsed document,
758 we would do the following:
760 my $sections = $pom->head1();
762 Methods like this will return a list of further Pod::POM::Node::*
763 objects when called in list context or a reference to a list when
764 called in scalar context. In the latter case, the list is blessed
765 into the Pod::POM::Node::Content class which gives it certain
766 magical properties (more on that later).
768 Given the list of Pod::POM::Node::Head1 objects returned by the above,
769 we can print the title attributes of each like this:
771 foreach my $s (@$sections) {
775 Let's look at the second section, DESCRIPTION.
777 my $desc = $sections->[1];
779 We can print the title of each subsection within it:
781 foreach my $ss ($desc->head2()) {
785 Hopefully you're getting the idea by now, so here's a more studly
786 example to print the title for each item contained in the first list
787 within the METHODS section:
789 foreach my $item ($desc->head2->[0]->over->[0]->item) {
790 print $item->title(), "\n";
793 =head2 Element Content
795 This is all well and good if you know the precise structure of a
796 document in advance. For those more common cases when you don't,
797 each node that can contain other nodes provides a 'content' method
798 to return a complete list of all the other nodes that it contains.
799 The 'type' method can be called on any node to return its element
800 type (e.g. 'head1', 'head2', 'over', item', etc).
802 foreach my $item ($pom->content()) {
803 my $type = $item->type();
804 if ($type eq 'head1') {
807 elsif ($type eq 'head2') {
813 The content for an element is represented by a reference to a list,
814 blessed into the Pod::POM::Node::Content class. This provides some
815 magic in the form of an overloaded stringification operator which
816 will automatically print the contents of the list if you print
817 the object itself. In plain English, or rather, in plain Perl,
818 this means you can do things like the following:
820 foreach my $head1 ($pom->head1()) {
821 print '<h1>', $head1->title(), "</h1>\n\n";
822 print $head1->content();
825 # print all the root content
826 foreach my $item ($pom->content()) {
831 print $pom->content();
833 In fact, all Pod::POM::Node::* objects provide this same magic, and
834 will attempt to Do The Right Thing to present themselves in the
835 appropriate manner when printed. Thus, the following are all valid.
837 print $pom; # entire document
838 print $pom->content; # content of document
839 print $pom->head1->[0]; # just first section
840 print $pom->head1; # print all sections
841 foreach my $h1 ($pom->head1()) {
842 print $h1->head2(); # print all subsections
847 To understand how the different elements go about presenting
848 themselves in "the appropriate manner", we must introduce the concept
849 of a view. A view is quite simply a particular way of looking at the
850 model. In real terms, we can think of a view as being some kind of
851 output type generated by a pod2whatever converter. Notionally we can
852 think in terms of reading in an input document, building a Pod Object
853 Model, and then generating an HTML view of the document, and/or a
854 LaTeX view, a plain text view, and so on.
856 A view is represented in this case by an object class which contains
857 methods for displaying each of the different element types that could
858 be encountered in any Pod document. There's a method for displaying
859 C<=head1> sections (view_head1()), another method for displaying
860 C<=head2> sections (view_head2()), one for C<=over> (view_over()),
861 another for C<=item> (view_item()) and so on.
863 If we happen to have a reference to a $node and we know it's a 'head1'
864 node, then we can directly call the right view method to have it
867 $view = 'Pod::POM::View::HTML';
868 $view->view_head1($node);
870 Thus our earlier example can be modified to be I<slightly> less laborious
871 and I<marginally> more flexible.
873 foreach my $node ($pom->content) {
874 my $type = $node->type();
875 if ($type eq 'head1') {
876 print $view->view_head1($node);
878 elsif ($type eq 'head2') {
879 print $view->view_head2($node);
884 However, this is still far from ideal. To make life easier, each
885 Pod::POM::Node::* class inherits (or possibly redefines) a
886 C<present($view)> method from the Pod::POM::Node base class. This method
887 expects a reference to a view object passed as an argument, and it
888 simply calls the appropriate view_xxx() method on the view object,
889 passing itself back as an argument. In object parlance, this is known
890 as "double dispatch". The beauty of it is that you don't need to know
891 what kind of node you have to be able to print it. You simply pass
892 it a view object and leave it to work out the rest.
894 foreach my $node ($pom->content) {
895 print $node->present($view);
898 If $node is a Pod::POM::Node::Head1 object, then the view_head1($node)
899 method gets called against the $view object. Otherwise, if it's a
900 Pod::POM::Node::Head2 object, then the view_head2($node) method is
901 dispatched. And so on, and so on, with each node knowing what it is
902 and where it's going as if determined by some genetically pre-programmed
903 instinct. Fullfilling their destinies, so to speak.
905 Double dispatch allows us to do away with all the explicit type
906 checking and other nonsense and have the node objects themselves worry
907 about where they should be routed to. At the cost of an extra method
908 call per node, we get programmer convenience, and that's usually
911 Let's have a look at how the view and node classes might be
914 package Pod::POM::View::HTML;
917 my ($self, $node) = @_;
918 return $node->content->present($self);
922 my ($self, $node) = @_;
923 return "<h1>", $node->title->present($self), "</h1>\n\n"
924 . $node->content->present($self);
928 my ($self, $node) = @_;
929 return "<h2>", $node->title->present($self), "</h2>\n\n"
930 . $node->content->present($self);
935 package Pod::POM::Node::Pod;
938 my ($self, $view) = @_;
939 $view->view_pod($self);
942 package Pod::POM::Node::Head1;
945 my ($self, $view) = @_;
946 $view->view_head1($self);
949 package Pod::POM::Node::Head2;
952 my ($self, $view) = @_;
953 $view->view_head2($self);
958 Some of the view_xxx methods make calls back against the node objects
959 to display their attributes and/or content. This is shown in, for
960 example, the view_head1() method above, where the method prints the
961 section title in C<E<lt>h1E<gt>>...C<E<lt>h1E<gt>> tags, followed by
962 the remaining section content.
964 Note that the title() attribute is printed by calling its present()
965 method, passing on the reference to the current view. Similarly,
966 the content present() method is called giving it a chance to Do
967 The Right Thing to present itself correctly via the view object.
969 There's a good chance that the title attribute is going to be regular
970 text, so we might be tempted to simply print the title rather than
971 call its present method.
974 my ($self, $node) = @_;
975 # not recommended, prefer $node->title->present($self)
976 return "<h1>", $node->title(), "</h1>\n\n", ...
979 However, it is entirely valid for titles and other element attributes,
980 as well as regular, formatted text blocks to contain code sequences,
981 such like C<BE<lt>thisE<gt>> and C<IE<lt>thisE<gt>>. These are used
982 to indicate different markup styles, mark external references or index
983 items, and so on. What's more, they can be C<BE<lt>nested
984 IE<lt>indefinatelyE<gt>E<gt>>. Pod::POM takes care of all this by
985 parsing such text, along with any embedded sequences, into Yet Another
986 Tree, the root node of which is a Pod::POM::Node::Text object,
987 possibly containing other Pod::POM::Node::Sequence objects. When the
988 text is presented, the tree is automatically walked and relevant
989 callbacks made against the view for the different sequence types. The
990 methods called against the view are all prefixed 'view_seq_', e.g.
991 'view_seq_bold', 'view_seq_italic'.
993 Now the real magic comes into effect. You can define one view to
994 render bold/italic text in one style:
996 package My::View::Text;
997 use base qw( Pod::POM::View::Text );
1000 my ($self, $text) = @_;
1004 sub view_seq_italic {
1005 my ($self, $text) = @_;
1009 And another view to render it in a different style:
1011 package My::View::HTML;
1012 use base qw( Pod::POM::View::HTML );
1015 my ($self, $text) = @_;
1016 return "<b>$text</b>";
1019 sub view_seq_italic {
1020 my ($self, $text) = @_;
1021 return "<i>$text</i>";
1024 Then, you can easily view a Pod Object Model in either style:
1026 my $text = 'My::View::Text';
1027 my $html = 'My::View::HTML';
1029 print $pom->present($text);
1030 print $pom->present($html);
1032 And you can apply this technique to any node within the object
1035 print $pom->head1->[0]->present($text);
1036 print $pom->head1->[0]->present($html);
1038 In these examples, the view passed to the present() method has
1039 been a class name. Thus, the view_xxx methods get called as
1040 class methods, as if written:
1042 My::View::Text->view_head1(...);
1044 If your view needs to maintain state then you can create a view object
1045 and pass that to the present() method.
1047 my $view = My::View->new();
1048 $node->present($view);
1050 In this case the view_xxx methods get called as object methods.
1053 my ($self, $node) = @_;
1054 my $title = $node->title();
1055 if ($title eq 'NAME' && ref $self) {
1056 $self->{ title } = $title();
1058 $self->SUPER::view_head1($node);
1061 Whenever you print a Pod::POM::Node::* object, or do anything to cause
1062 Perl to stringify it (such as including it another quoted string "like
1063 $this"), then its present() method is automatically called. When
1064 called without a view argument, the present() method uses the default
1065 view specified in $Pod::POM::DEFAULT_VIEW, which is, by default,
1066 'Pod::POM::View::Pod'. This view regenerates the original Pod
1067 document, although it should be noted that the output generated may
1068 not be exactly the same as the input. The parser is smart enough to
1069 detect some common errors (e.g. not terminating an C<=over> with a C<=back>)
1070 and correct them automatically. Thus you might find a C<=back>
1071 correctly placed in the output, even if you forgot to add it to the
1072 input. Such corrections raise non-fatal warnings which can later
1073 be examined via the warnings() method.
1075 You can update the $Pod::POM::DEFAULT_VIEW package variable to set the
1076 default view, or call the default_view() method. The default_view()
1077 method will automatically load any package you specify. If setting
1078 the package variable directly, you should ensure that any packages
1079 required have been pre-loaded.
1082 $Pod::POM::DEFAULT_VIEW = 'My::View::HTML';
1086 Pod::POM->default_view('My::View::HTML');
1088 =head2 Template Toolkit Views
1090 One of the motivations for writing this module was to make it easier
1091 to customise Pod documentation to your own look and feel or local
1092 formatting conventions. By clearly separating the content
1093 (represented by the Pod Object Model) from the presentation style
1094 (represented by one or more views) it becomes much easier to achieve
1097 The latest version of the Template Toolkit (2.06 at the time of
1098 writing) provides a Pod plugin to interface to this module. It also
1099 implements a new (but experimental) VIEW directive which can be used
1100 to build different presentation styles for converting Pod to other
1101 formats. The Template Toolkit is available from CPAN:
1103 http://www.cpan.org/modules/by-module/Template/
1105 Template Toolkit views are similar to the Pod::POM::View objects
1106 described above, except that they allow the presentation style for
1107 each Pod component to be written as a template file or block rather
1108 than an object method. The precise syntax and structure of the VIEW
1109 directive is subject to change (given that it's still experimental),
1110 but at present it can be used to define a view something like this:
1114 [% BLOCK view_head1 %]
1115 <h1>[% item.title.present(view) %]</h1>
1116 [% item.content.present(view) %]
1119 [% BLOCK view_head2 %]
1120 <h2>[% item.title.present(view) %]</h2>
1121 [% item.content.present(view) %]
1128 A plugin is provided to interface to the Pod::POM module:
1131 [% pom = pod.parse('/path/to/podfile') %]
1133 The returned Pod Object Model instance can then be navigated and
1134 presented via the view in almost any way imaginable:
1136 <h1>Table of Contents</h1>
1138 [% FOREACH section = pom.head1 %]
1139 <li>[% section.title.present(view) %]
1145 [% FOREACH section = pom.head1 %]
1146 [% section.present(myview) %]
1149 You can either pass a reference to the VIEW (myview) to the
1150 present() method of a Pod::POM node:
1152 [% pom.present(myview) %] # present entire document
1154 Or alternately call the print() method on the VIEW, passing the
1155 Pod::POM node as an argument:
1157 [% myview.print(pom) %]
1159 Internally, the view calls the present() method on the node,
1160 passing itself as an argument. Thus it is equivalent to the
1163 The Pod::POM node and the view conspire to "Do The Right Thing" to
1164 process the right template block for the node. A reference to the
1165 node is available within the template as the 'item' variable.
1167 [% BLOCK view_head2 %]
1168 <h2>[% item.title.present(view) %]</h2>
1169 [% item.content.present(view) %]
1172 The Template Toolkit documentation contains further information on
1173 defining and using views. However, as noted above, this may be
1174 subject to change or incomplete pending further development of the
1179 =head2 new(\%config)
1181 Constructor method which instantiates and returns a new Pod::POM
1186 my $parser = Pod::POM->new();
1188 A reference to a hash array of configuration options may be passed as
1191 my $parser = Pod::POM->new( { warn => 1 } );
1193 For convenience, configuration options can also be passed as a list of
1194 (key =E<gt> value) pairs.
1196 my $parser = Pod::POM->new( warn => 1 );
1198 The following configuration options are defined:
1204 This option can be set to have all non-Pod parts of the input document
1205 stored within the object model as 'code' elements, represented by
1206 objects of the Pod::POM::Node::Code class. It is disabled by default
1207 and code sections are ignored.
1209 my $parser = Pod::POM->new( code => 1 );
1210 my $podpom = $parser->parse(\*DATA);
1212 foreach my $code ($podpom->code()) {
1213 print "<pre>$code</pre>\n";
1217 This is some program code.
1223 This will generate the output:
1225 <pre>This is some program code.</pre>
1227 Note that code elements are stored within the POM element in which
1228 they are encountered. For example, the code element below embedded
1229 within between Pod sections is stored in the array which can be
1230 retrieved by calling C<$podpom-E<gt>head1-E<gt>[0]-E<gt>code()>.
1238 Some program code embedded in Pod.
1246 Non-fatal warnings encountered while parsing a Pod document are stored
1247 internally and subsequently available via the warnings() method.
1249 my $parser = Pod::POM->new();
1250 my $podpom = $parser->parse_file($filename);
1252 foreach my $warning ($parser->warnings()) {
1253 warn $warning, "\n";
1256 The 'warn' option can be set to have warnings raised automatically
1257 via C<warn()> as and when they are encountered.
1259 my $parser = Pod::POM->new( warn => 1 );
1260 my $podpom = $parser->parse_file($filename);
1262 If the configuration value is specified as a subroutine reference then
1263 the code will be called each time a warning is raised, passing the
1264 warning message as an argument.
1271 my $parser = Pod::POM->new( warn => \&my_warning );
1272 my $podpom = $parser->parse_file($filename);
1276 The 'meta' option can be set to allow C<=meta> tags within the Pod
1279 my $parser = Pod::POM->new( meta => 1 );
1280 my $podpom = $parser->parse_file($filename);
1282 This is an experimental feature which is not part of standard
1285 =meta author Andy Wardley
1287 These are made available as metadata items within the root
1288 node of the parsed POM.
1290 my $author = $podpom->metadata('author');
1292 See the L<METADATA|METADATA> section below for further information.
1296 =head2 parse_file($file)
1298 Parses the file specified by name or reference to a file handle.
1299 Returns a reference to a Pod::POM::Node::Pod object which represents
1300 the root node of the Pod Object Model on success. On error, undef
1301 is returned and the error message generated can be retrieved by calling
1304 my $podpom = $parser->parse_file($filename)
1305 || die $parser->error();
1307 my $podpom = $parser->parse_file(\*STDIN)
1308 || die $parser->error();
1310 Any warnings encountered can be examined by calling the
1313 foreach my $warn ($parser->warnings()) {
1317 =head2 parse_text($text)
1319 Parses the Pod text string passed as an argument into a Pod Object
1320 Model, as per parse_file().
1322 =head2 parse($text_or_$file)
1324 General purpose method which attempts to Do The Right Thing in calling
1325 parse_file() or parse_text() according to the argument passed.
1327 A hash reference can be passed as an argument that contains a 'text'
1328 or 'file' key and corresponding value.
1330 my $podpom = $parser->parse({ file => $filename })
1331 || die $parser->error();
1333 Otherwise, the argument can be a reference to an input handle which is
1334 passed off to parse_file().
1336 my $podpom = $parser->parse(\*DATA)
1337 || die $parser->error();
1339 If the argument is a text string that looks like Pod text (i.e. it
1340 contains '=' at the start of any line) then it is passed to parse_text().
1342 my $podpom = $parser->parse($podtext)
1343 || die $parser->error();
1345 Otherwise it is assumed to be a filename and is passed to parse_file().
1347 my $podpom = $parser->parse($podfile)
1348 || die $parser->error();
1350 =head1 NODE TYPES, ATTRIBUTES AND ELEMENTS
1352 This section lists the different nodes that may be present in a Pod Object
1353 Model. These are implemented as Pod::POM::Node::* object instances
1354 (e.g. head1 =E<gt> Pod::POM::Node::Head1). To present a node, a view should
1355 implement a method which corresponds to the node name prefixed by 'view_'
1356 (e.g. head1 =E<gt> view_head1()).
1362 The C<pod> node is used to represent the root node of the Pod Object Model.
1364 Content elements: head1, head2, head3, head4, over, begin, for,
1365 verbatim, text, code.
1369 A C<head1> node contains the Pod content from a C<=head1> tag up to the
1370 next C<=head1> tag or the end of the file.
1374 Content elements: head2, head3, head4, over, begin, for, verbatim, text, code.
1378 A C<head2> node contains the Pod content from a C<=head2> tag up to the
1379 next C<=head1> or C<=head2> tag or the end of the file.
1383 Content elements: head3, head4, over, begin, for, verbatim, text, code.
1387 A C<head3> node contains the Pod content from a C<=head3> tag up to the
1388 next C<=head1>, C<=head2> or C<=head3> tag or the end of the file.
1392 Content elements: head4, over, begin, for, verbatim, text, code.
1396 A C<head4> node contains the Pod content from a C<=head4> tag up to the
1397 next C<=head1>, C<=head2>, C<=head3> or C<=head4> tag or the end of the file.
1401 Content elements: over, begin, for, verbatim, text, code.
1405 The C<over> node encloses the Pod content in a list starting at an C<=over>
1406 tag and continuing up to the matching C<=back> tag. Lists may be nested
1409 Attributes: indent (default: 4)
1411 Content elements: over, item, begin, for, verbatim, text, code.
1415 The C<item> node encloses the Pod content in a list item starting at an
1416 C<=item> tag and continuing up to the next C<=item> tag or a C<=back> tag
1417 which terminates the list.
1419 Attributes: title (default: *)
1421 Content elements: over, begin, for, verbatim, text, code.
1425 A C<begin> node encloses the Pod content in a conditional block starting
1426 with a C<=begin> tag and continuing up to the next C<=end> tag.
1430 Content elements: verbatim, text, code.
1434 A C<for> node contains a single paragraph containing text relevant to a
1437 Attributes: format, text
1441 A C<verbatim> node contains a verbatim text paragraph which is prefixed by
1442 whitespace in the source Pod document (i.e. indented).
1448 A C<text> node contains a regular text paragraph. This may include
1449 embedded inline sequences.
1455 A C<code> node contains Perl code which is by default, not considered to be
1456 part of a Pod document. The C<code> configuration option must be set for
1457 Pod::POM to generate code blocks, otherwise they are ignored.
1463 =head1 INLINE SEQUENCES
1465 Embedded sequences are permitted within regular text blocks (i.e. not
1466 verbatim) and title attributes. To present these sequences, a view
1467 should implement methods corresponding to the sequence name, prefixed
1468 by 'view_seq_' (e.g. bold =E<gt> view_seq_bold()).
1474 Code extract, e.g. CE<lt>my codeE<gt>
1478 Bold text, e.g. BE<lt>bold textE<gt>
1482 Italic text, e.g. IE<lt>italic textE<gt>
1486 A link (cross reference), e.g. LE<lt>My::ModuleE<gt>
1490 Text contains non-breaking space, e.g.SE<lt>Buffy The Vampire SlayerE<gt>
1494 A filename, e.g. FE<lt>/etc/lilo.confE<gt>
1498 An index entry, e.g. XE<lt>AngelE<gt>
1502 A zero-width character, e.g. ZE<lt>E<gt>
1506 An entity escape, e.g. EE<lt>ltE<gt>
1510 =head1 BUNDLED MODULES AND TOOLS
1512 The Pod::POM module distribution includes a number of sample view
1513 objects for rendering Pod Object Models into particular formats. These
1514 are incomplete and may require some further work, but serve at present to
1515 illustrate the principal and can be used as the basis for your own view
1520 =item Pod::POM::View::Pod
1522 Regenerates the model as Pod.
1524 =item Pod::POM::View::Text
1526 Presents the model as plain text.
1528 =item Pod::POM::View::HTML
1530 Presents the model as HTML.
1534 A script is provided for converting Pod documents to other format by
1535 using the view objects provided. The C<pom2> script should be called
1536 with two arguments, the first specifying the output format, the second
1537 the input filename. e.g.
1539 $ pom2 text My/Module.pm > README
1540 $ pom2 html My/Module.pm > ~/public_html/My/Module.html
1542 You can also create symbolic links to the script if you prefer and
1543 leave it to determine the output format from its own name.
1545 $ ln -s pom2 pom2text
1546 $ ln -s pom2 pom2html
1547 $ pom2text My/Module.pm > README
1548 $ pom2html My/Module.pm > ~/public_html/My/Module.html
1550 The distribution also contains a trivial script, C<podlint>
1551 (previously C<pomcheck>), which checks a Pod document for
1552 well-formedness by simply parsing it into a Pod Object Model with
1553 warnings enabled. Warnings are printed to STDERR.
1555 $ podlint My/Module.pm
1557 The C<-f> option can be set to have the script attempt to fix any problems
1558 it encounters. The regenerated Pod output is printed to STDOUT.
1560 $ podlint -f My/Module.pm > newfile
1564 This module includes support for an experimental new C<=meta> tag. This
1565 is disabled by default but can be enabled by loading Pod::POM with the
1568 use Pod::POM qw( meta );
1570 Alternately, you can specify the C<meta> option to be any true value when
1571 you instantiate a Pod::POM parser:
1573 my $parser = Pod::POM->new( meta => 1 );
1574 my $pom = $parser->parse_file($filename);
1576 Any C<=meta> tags in the document will be stored as metadata items in the
1577 root node of the Pod model created.
1581 =meta module Foo::Bar
1583 =meta author Andy Wardley
1585 You can then access these items via the metadata() method.
1587 print "module: ", $pom->metadata('module'), "\n";
1588 print "author: ", $pom->metadata('author'), "\n";
1592 my $metadata = $pom->metadata();
1593 print "module: $metadata->{ module }\n";
1594 print "author: $metadata->{ author }\n";
1596 Please note that this is an experimental feature which is not supported by
1597 other POD processors and is therefore likely to be most incompatible. Use
1602 Andy Wardley E<lt>abw@kfs.orgE<gt>
1604 Andrew Ford E<lt>A.Ford@ford-mason.co.ukE<gt> (co-maintainer as of 03/2009)
1608 This is version 0.25 of the Pod::POM module.
1612 Copyright (C) 2000-2009 Andy Wardley. All Rights Reserved.
1614 This module is free software; you can redistribute it and/or
1615 modify it under the same terms as Perl itself.
1619 For the definitive reference on Pod, see L<perlpod>.
1621 For an overview of Pod::POM internals and details relating to subclassing
1622 of POM nodes, see L<Pod::POM::Node>.
1624 There are numerous other fine Pod modules available from CPAN which
1625 perform conversion from Pod to other formats. In many cases these are
1626 likely to be faster and quite possibly more reliable and/or complete
1627 than this module. But as far as I know, there aren't any that offer
1628 the same kind of flexibility in being able to customise the generated
1629 output. But don't take my word for it - see your local CPAN site for
1632 http://www.cpan.org/modules/by-module/Pod/