home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _c08300ff5f5bc079ba39eaa57ea97e36 < prev    next >
Encoding:
Text File  |  2004-06-01  |  70.9 KB  |  1,915 lines

  1.  
  2. require 5;
  3. # Time-stamp: "2003-09-15 00:32:45 ADT"
  4. package HTML::TreeBuilder;
  5.  
  6. use strict;
  7. use integer; # vroom vroom!
  8. use Carp ();
  9. use vars qw(@ISA $VERSION $DEBUG);
  10. $VERSION = '3.13';
  11.  
  12. #---------------------------------------------------------------------------
  13. # Make a 'DEBUG' constant...
  14.  
  15. BEGIN {
  16.   # We used to have things like
  17.   #  print $indent, "lalala" if $Debug;
  18.   # But there were an awful lot of having to evaluate $Debug's value.
  19.   # If we make that depend on a constant, like so:
  20.   #   sub DEBUG () { 1 } # or whatever value.
  21.   #   ...
  22.   #   print $indent, "lalala" if DEBUG;
  23.   # Which at compile-time (thru the miracle of constant folding) turns into:
  24.   #   print $indent, "lalala";
  25.   # or, if DEBUG is a constant with a true value, then that print statement
  26.   # is simply optimized away, and doesn't appear in the target code at all.
  27.   # If you don't believe me, run:
  28.   #    perl -MO=Deparse,-uHTML::TreeBuilder -e 'BEGIN { \
  29.   #      $HTML::TreeBuilder::DEBUG = 4}  use HTML::TreeBuilder'
  30.   # and see for yourself (substituting whatever value you want for $DEBUG
  31.   # there).
  32.  
  33.   if(defined &DEBUG) {
  34.     # Already been defined!  Do nothing.
  35.   } elsif($] < 5.00404) {
  36.     # Grudgingly accomodate ancient (pre-constant) versions.
  37.     eval 'sub DEBUG { $Debug } ';
  38.   } elsif(!$DEBUG) {
  39.     eval 'sub DEBUG () {0}';  # Make it a constant.
  40.   } elsif($DEBUG =~ m<^\d+$>s) {
  41.     eval 'sub DEBUG () { ' . $DEBUG . ' }';  # Make THAT a constant.
  42.   } else { # WTF?
  43.     warn "Non-numeric value \"$DEBUG\" in \$HTML::Element::DEBUG";
  44.     eval 'sub DEBUG () { $DEBUG }'; # I guess.
  45.   }
  46. }
  47.  
  48. #---------------------------------------------------------------------------
  49.  
  50. use HTML::Entities ();
  51. use HTML::Tagset 3.02 ();
  52.  
  53. use HTML::Element ();
  54. use HTML::Parser ();
  55. @ISA = qw(HTML::Element HTML::Parser);
  56.  # This looks schizoid, I know.
  57.  # It's not that we ARE an element AND a parser.
  58.  # We ARE an element, but one that knows how to handle signals
  59.  #  (method calls) from Parser in order to elaborate its subtree.
  60.  
  61. # Legacy aliases:
  62. *HTML::TreeBuilder::isKnown = \%HTML::Tagset::isKnown;
  63. *HTML::TreeBuilder::canTighten = \%HTML::Tagset::canTighten;
  64. *HTML::TreeBuilder::isHeadElement = \%HTML::Tagset::isHeadElement;
  65. *HTML::TreeBuilder::isBodyElement = \%HTML::Tagset::isBodyElement;
  66. *HTML::TreeBuilder::isPhraseMarkup = \%HTML::Tagset::isPhraseMarkup;
  67. *HTML::TreeBuilder::isHeadOrBodyElement = \%HTML::Tagset::isHeadOrBodyElement;
  68. *HTML::TreeBuilder::isList = \%HTML::Tagset::isList;
  69. *HTML::TreeBuilder::isTableElement = \%HTML::Tagset::isTableElement;
  70. *HTML::TreeBuilder::isFormElement = \%HTML::Tagset::isFormElement;
  71. *HTML::TreeBuilder::p_closure_barriers = \@HTML::Tagset::p_closure_barriers;
  72.  
  73. #==========================================================================
  74. # Two little shortcut constructors:
  75.  
  76. sub new_from_file { # or from a FH
  77.   my $class = shift;
  78.   Carp::croak("new_from_file takes only one argument")
  79.    unless @_ == 1;
  80.   Carp::croak("new_from_file is a class method only")
  81.    if ref $class;
  82.   my $new = $class->new();
  83.   $new->parse_file($_[0]);
  84.   return $new;
  85. }
  86.  
  87. sub new_from_content { # from any number of scalars
  88.   my $class = shift;
  89.   Carp::croak("new_from_content is a class method only")
  90.    if ref $class;
  91.   my $new = $class->new();
  92.   foreach my $whunk (@_) {
  93.     if(ref($whunk) eq 'SCALAR') {
  94.       $new->parse($$whunk);
  95.     } else {
  96.       $new->parse($whunk);
  97.     }
  98.     last if $new->{'_stunted'}; # might as well check that.
  99.   }
  100.   $new->eof();
  101.   return $new;
  102. }
  103.  
  104. # TODO: document?
  105. sub parse_content {  # from any number of scalars
  106.   my $tree = shift;
  107.   my $retval;
  108.   foreach my $whunk (@_) {
  109.     if(ref($whunk) eq 'SCALAR') {
  110.       $retval = $tree->parse($$whunk);
  111.     } else {
  112.       $retval = $tree->parse($whunk);
  113.     }
  114.     last if $tree->{'_stunted'}; # might as well check that.
  115.   }
  116.   $tree->eof();
  117.   return $retval;
  118. }
  119.  
  120.  
  121. #---------------------------------------------------------------------------
  122.  
  123. sub new { # constructor!
  124.   my $class = shift;
  125.   $class = ref($class) || $class;
  126.  
  127.   my $self = HTML::Element->new('html');  # Initialize HTML::Element part
  128.   {
  129.     # A hack for certain strange versions of Parser:
  130.     my $other_self = HTML::Parser->new();
  131.     %$self = (%$self, %$other_self);              # copy fields
  132.       # Yes, multiple inheritance is messy.  Kids, don't try this at home.
  133.     bless $other_self, "HTML::TreeBuilder::_hideyhole";
  134.       # whack it out of the HTML::Parser class, to avoid the destructor
  135.   }
  136.  
  137.   # The root of the tree is special, as it has these funny attributes,
  138.   # and gets reblessed into this class.
  139.  
  140.   # Initialize parser settings
  141.   $self->{'_implicit_tags'}  = 1;
  142.   $self->{'_implicit_body_p_tag'} = 0;
  143.     # If true, trying to insert text, or any of %isPhraseMarkup right
  144.     #  under 'body' will implicate a 'p'.  If false, will just go there.
  145.  
  146.   $self->{'_tighten'} = 1;
  147.     # whether ignorable WS in this tree should be deleted
  148.  
  149.   $self->{'_implicit'} = 1;  # to delete, once we find a real open-"html" tag
  150.  
  151.   $self->{'_element_class'}      = 'HTML::Element';
  152.   $self->{'_ignore_unknown'}     = 1;
  153.   $self->{'_ignore_text'}        = 0;
  154.   $self->{'_warn'}               = 0;
  155.   $self->{'_no_space_compacting'}= 0;
  156.   $self->{'_store_comments'}     = 0;
  157.   $self->{'_store_pis'}          = 0;
  158.   $self->{'_store_declarations'} = 0;
  159.   $self->{'_p_strict'} = 0;
  160.   
  161.   # Parse attributes passed in as arguments
  162.   if(@_) {
  163.     my %attr = @_;
  164.     for (keys %attr) {
  165.       $self->{"_$_"} = $attr{$_};
  166.     }
  167.   }
  168.  
  169.   # rebless to our class
  170.   bless $self, $class;
  171.  
  172.   $self->{'_element_count'} = 1;
  173.     # undocumented, informal, and maybe not exactly correct
  174.  
  175.   $self->{'_head'} = $self->insert_element('head',1);
  176.   $self->{'_pos'} = undef; # pull it back up
  177.   $self->{'_body'} = $self->insert_element('body',1);
  178.   $self->{'_pos'} = undef; # pull it back up again
  179.  
  180.   return $self;
  181. }
  182.  
  183. #==========================================================================
  184.  
  185. sub _elem # universal accessor...
  186. {
  187.   my($self, $elem, $val) = @_;
  188.   my $old = $self->{$elem};
  189.   $self->{$elem} = $val if defined $val;
  190.   return $old;
  191. }
  192.  
  193. # accessors....
  194. sub implicit_tags  { shift->_elem('_implicit_tags',  @_); }
  195. sub implicit_body_p_tag  { shift->_elem('_implicit_body_p_tag',  @_); }
  196. sub p_strict       { shift->_elem('_p_strict',  @_); }
  197. sub no_space_compacting { shift->_elem('_no_space_compacting', @_); }
  198. sub ignore_unknown { shift->_elem('_ignore_unknown', @_); }
  199. sub ignore_text    { shift->_elem('_ignore_text',    @_); }
  200. sub ignore_ignorable_whitespace  { shift->_elem('_tighten',    @_); }
  201. sub store_comments { shift->_elem('_store_comments', @_); }
  202. sub store_declarations { shift->_elem('_store_declarations', @_); }
  203. sub store_pis      { shift->_elem('_store_pis', @_); }
  204. sub warn           { shift->_elem('_warn',           @_); }
  205.  
  206.  
  207. #==========================================================================
  208.  
  209. sub warning {
  210.     my $self = shift;
  211.     CORE::warn("HTML::Parse: $_[0]\n") if $self->{'_warn'};
  212.      # should maybe say HTML::TreeBuilder instead
  213. }
  214.  
  215. #==========================================================================
  216.  
  217. {
  218.   # To avoid having to rebuild these lists constantly...
  219.   my $_Closed_by_structurals = [qw(p h1 h2 h3 h4 h5 h6 pre textarea)];
  220.   my $indent;
  221.  
  222.   sub start {
  223.     return if $_[0]{'_stunted'};
  224.     
  225.     # Accept a signal from HTML::Parser for start-tags.
  226.     my($self, $tag, $attr) = @_;
  227.     # Parser passes more, actually:
  228.     #   $self->start($tag, $attr, $attrseq, $origtext)
  229.     # But we can merrily ignore $attrseq and $origtext.
  230.  
  231.     if($tag eq 'x-html') {
  232.       print "Ignoring open-x-html tag.\n" if DEBUG;
  233.       # inserted by some lame code-generators.
  234.       return;    # bypass tweaking.
  235.     }
  236.    
  237.     $tag =~ s{/$}{}s;  # So <b/> turns into <b>.  Silently forgive.
  238.     
  239.     unless($tag =~ m/^[-_a-zA-Z0-9:%]+$/s) {
  240.       DEBUG and print "Start-tag name $tag is no good.  Skipping.\n";
  241.       return;
  242.       # This avoids having Element's new() throw an exception.
  243.     }
  244.  
  245.     my $ptag = (
  246.                 my $pos  = $self->{'_pos'} || $self
  247.                )->{'_tag'};
  248.     my $already_inserted;
  249.     #my($indent);
  250.     if(DEBUG) {
  251.       # optimization -- don't figure out indenting unless we're in debug mode
  252.       my @lineage = $pos->lineage;
  253.       $indent = '  ' x (1 + @lineage);
  254.       print
  255.         $indent, "Proposing a new \U$tag\E under ",
  256.         join('/', map $_->{'_tag'}, reverse($pos, @lineage)) || 'Root',
  257.         ".\n";
  258.     #} else {
  259.     #  $indent = ' ';
  260.     }
  261.     
  262.     #print $indent, "POS: $pos ($ptag)\n" if DEBUG > 2;
  263.     # $attr = {%$attr};
  264.  
  265.     foreach my $k (keys %$attr) {
  266.       # Make sure some stooge doesn't have "<span _content='pie'>".
  267.       # That happens every few million Web pages.
  268.       $attr->{' ' . $k} = delete $attr->{$k}
  269.        if length $k and substr($k,0,1) eq '_';
  270.       # Looks bad, but is fine for round-tripping.
  271.     }
  272.     
  273.     my $e =
  274.      ($self->{'_element_class'} || 'HTML::Element')->new($tag, %$attr);
  275.      # Make a new element object.
  276.      # (Only rarely do we end up just throwing it away later in this call.)
  277.      
  278.     # Some prep -- custom messiness for those damned tables, and strict P's.
  279.     if($self->{'_implicit_tags'}) {  # wallawallawalla!
  280.       
  281.       unless($HTML::TreeBuilder::isTableElement{$tag}) {
  282.         if ($ptag eq 'table') {
  283.           print $indent,
  284.             " * Phrasal \U$tag\E right under TABLE makes implicit TR and TD\n"
  285.            if DEBUG > 1;
  286.           $self->insert_element('tr', 1);
  287.           $pos = $self->insert_element('td', 1); # yes, needs updating
  288.         } elsif ($ptag eq 'tr') {
  289.           print $indent,
  290.             " * Phrasal \U$tag\E right under TR makes an implicit TD\n"
  291.            if DEBUG > 1;
  292.           $pos = $self->insert_element('td', 1); # yes, needs updating
  293.         }
  294.         $ptag = $pos->{'_tag'}; # yes, needs updating
  295.       }
  296.        # end of table-implication block.
  297.       
  298.       
  299.       # Now maybe do a little dance to enforce P-strictness.
  300.       # This seems like it should be integrated with the big
  301.       # "ALL HOPE..." block, further below, but that doesn't
  302.       # seem feasable.
  303.       if(
  304.         $self->{'_p_strict'}
  305.         and $HTML::TreeBuilder::isKnown{$tag}
  306.         and not $HTML::Tagset::is_Possible_Strict_P_Content{$tag}
  307.       ) {
  308.         my $here = $pos;
  309.         my $here_tag = $ptag;
  310.         while(1) {
  311.           if($here_tag eq 'p') {
  312.             print $indent,
  313.               " * Inserting $tag closes strict P.\n" if DEBUG > 1;
  314.             $self->end(\q{p});
  315.              # NB: same as \'q', but less confusing to emacs cperl-mode
  316.             last;
  317.           }
  318.           
  319.           #print("Lasting from $here_tag\n"),
  320.           last if
  321.             $HTML::TreeBuilder::isKnown{$here_tag}
  322.             and not $HTML::Tagset::is_Possible_Strict_P_Content{$here_tag};
  323.            # Don't keep looking up the tree if we see something that can't
  324.            #  be strict-P content.
  325.           
  326.           $here_tag = ($here = $here->{'_parent'} || last)->{'_tag'};
  327.         }# end while
  328.         $ptag = ($pos = $self->{'_pos'} || $self)->{'_tag'}; # better update!
  329.       }
  330.        # end of strict-p block.
  331.     }
  332.     
  333.     # And now, get busy...
  334.     #----------------------------------------------------------------------
  335.     if (!$self->{'_implicit_tags'}) {  # bimskalabim
  336.         # do nothing
  337.         print $indent, " * _implicit_tags is off.  doing nothing\n"
  338.          if DEBUG > 1;
  339.  
  340.     #----------------------------------------------------------------------
  341.     } elsif ($HTML::TreeBuilder::isHeadOrBodyElement{$tag}) {
  342.         if ($pos->is_inside('body')) { # all is well
  343.           print $indent,
  344.             " * ambilocal element \U$tag\E is fine under BODY.\n"
  345.            if DEBUG > 1;
  346.         } elsif ($pos->is_inside('head')) {
  347.           print $indent,
  348.             " * ambilocal element \U$tag\E is fine under HEAD.\n"
  349.            if DEBUG > 1;
  350.         } else {
  351.           # In neither head nor body!  mmmmm... put under head?
  352.           
  353.           if ($ptag eq 'html') { # expected case
  354.             # TODO?? : would there ever be a case where _head would be
  355.             #  absent from a tree that would ever be accessed at this
  356.             #  point?
  357.             die "Where'd my head go?" unless ref $self->{'_head'};
  358.             if ($self->{'_head'}{'_implicit'}) {
  359.               print $indent,
  360.                 " * ambilocal element \U$tag\E makes an implicit HEAD.\n"
  361.                if DEBUG > 1;
  362.               # or rather, points us at it.
  363.               $self->{'_pos'} = $self->{'_head'}; # to insert under...
  364.             } else {
  365.               $self->warning(
  366.                 "Ambilocal element <$tag> not under HEAD or BODY!?");
  367.               # Put it under HEAD by default, I guess
  368.               $self->{'_pos'} = $self->{'_head'}; # to insert under...
  369.             }
  370.             
  371.           } else { 
  372.             # Neither under head nor body, nor right under html... pass thru?
  373.             $self->warning(
  374.              "Ambilocal element <$tag> neither under head nor body, nor right under html!?");
  375.           }
  376.         }
  377.  
  378.     #----------------------------------------------------------------------
  379.     } elsif ($HTML::TreeBuilder::isBodyElement{$tag}) {
  380.         
  381.         # Ensure that we are within <body>
  382.         if($ptag eq 'body') {
  383.             # We're good.
  384.         } elsif($HTML::TreeBuilder::isBodyElement{$ptag}  # glarg
  385.           and not $HTML::TreeBuilder::isHeadOrBodyElement{$ptag}
  386.         ) {
  387.             # Special case: Save ourselves a call to is_inside further down.
  388.             # If our $ptag is an isBodyElement element (but not an
  389.             # isHeadOrBodyElement element), then we must be under body!
  390.             print $indent, " * Inferring that $ptag is under BODY.\n",
  391.              if DEBUG > 3;
  392.             # I think this and the test for 'body' trap everything
  393.             # bodyworthy, except the case where the parent element is
  394.             # under an unknown element that's a descendant of body.
  395.         } elsif ($pos->is_inside('head')) {
  396.             print $indent,
  397.               " * body-element \U$tag\E minimizes HEAD, makes implicit BODY.\n"
  398.              if DEBUG > 1;
  399.             $ptag = (
  400.               $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating
  401.                 || die "Where'd my body go?"
  402.             )->{'_tag'}; # yes, needs updating
  403.         } elsif (! $pos->is_inside('body')) {
  404.             print $indent,
  405.               " * body-element \U$tag\E makes implicit BODY.\n"
  406.              if DEBUG > 1;
  407.             $ptag = (
  408.               $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating
  409.                 || die "Where'd my body go?"
  410.             )->{'_tag'}; # yes, needs updating
  411.         }
  412.          # else we ARE under body, so okay.
  413.         
  414.         
  415.         # Handle implicit endings and insert based on <tag> and position
  416.         # ... ALL HOPE ABANDON ALL YE WHO ENTER HERE ...
  417.         if ($tag eq 'p'  or
  418.             $tag eq 'h1' or $tag eq 'h2' or $tag eq 'h3' or 
  419.             $tag eq 'h4' or $tag eq 'h5' or $tag eq 'h6' or
  420.             $tag eq 'form'
  421.             # Hm, should <form> really be here?!
  422.         ) {
  423.             # Can't have <p>, <h#> or <form> inside these
  424.             $self->end($_Closed_by_structurals,
  425.                        @HTML::TreeBuilder::p_closure_barriers
  426.                         # used to be just li!
  427.                       );
  428.             
  429.         } elsif ($tag eq 'ol' or $tag eq 'ul' or $tag eq 'dl') {
  430.             # Can't have lists inside <h#> -- in the unlikely
  431.             #  event anyone tries to put them there!
  432.             if (
  433.                 $ptag eq 'h1' or $ptag eq 'h2' or $ptag eq 'h3' or 
  434.                 $ptag eq 'h4' or $ptag eq 'h5' or $ptag eq 'h6'
  435.             ) {
  436.                 $self->end(\$ptag);
  437.             }
  438.             # TODO: Maybe keep closing up the tree until
  439.             #  the ptag isn't any of the above?
  440.             # But anyone that says <h1><h2><ul>...
  441.             #  deserves what they get anyway.
  442.             
  443.         } elsif ($tag eq 'li') { # list item
  444.             # Get under a list tag, one way or another
  445.             unless(
  446.               exists $HTML::TreeBuilder::isList{$ptag} or
  447.               $self->end(\q{*}, keys %HTML::TreeBuilder::isList) #'
  448.             ) { 
  449.               print $indent,
  450.                 " * inserting implicit UL for lack of containing ",
  451.                   join('|', keys %HTML::TreeBuilder::isList), ".\n"
  452.                if DEBUG > 1;
  453.               $self->insert_element('ul', 1); 
  454.             }
  455.             
  456.         } elsif ($tag eq 'dt' or $tag eq 'dd') {
  457.             # Get under a DL, one way or another
  458.             unless($ptag eq 'dl' or $self->end(\q{*}, 'dl')) { #'
  459.               print $indent,
  460.                 " * inserting implicit DL for lack of containing DL.\n"
  461.                if DEBUG > 1;
  462.               $self->insert_element('dl', 1);
  463.             }
  464.             
  465.         } elsif ($HTML::TreeBuilder::isFormElement{$tag}) {
  466.             if($self->{'_ignore_formies_outside_form'}  # TODO: document this
  467.                and not $pos->is_inside('form')
  468.             ) {
  469.                 print $indent,
  470.                   " * ignoring \U$tag\E because not in a FORM.\n"
  471.                   if DEBUG > 1;
  472.                 return;    # bypass tweaking.
  473.             }
  474.             if($tag eq 'option') {
  475.                 # return unless $ptag eq 'select';
  476.                 $self->end(\q{option});
  477.                 $ptag = ($self->{'_pos'} || $self)->{'_tag'};
  478.                 unless($ptag eq 'select' or $ptag eq 'optgroup') {
  479.                     print $indent, " * \U$tag\E makes an implicit SELECT.\n"
  480.                        if DEBUG > 1;
  481.                     $pos = $self->insert_element('select', 1);
  482.                     # but not a very useful select -- has no 'name' attribute!
  483.                      # is $pos's value used after this?
  484.                 }
  485.             }
  486.         } elsif ($HTML::TreeBuilder::isTableElement{$tag}) {
  487.             if(!$pos->is_inside('table')) {
  488.                 print $indent, " * \U$tag\E makes an implicit TABLE\n"
  489.                   if DEBUG > 1;
  490.                 $self->insert_element('table', 1);
  491.             }
  492.  
  493.             if($tag eq 'td' or $tag eq 'th') {
  494.                 # Get under a tr one way or another
  495.                 unless(
  496.                   $ptag eq 'tr' # either under a tr
  497.                   or $self->end(\q{*}, 'tr', 'table') #or we can get under one
  498.                 ) {
  499.                     print $indent,
  500.                        " * \U$tag\E under \U$ptag\E makes an implicit TR\n"
  501.                      if DEBUG > 1;
  502.                     $self->insert_element('tr', 1);
  503.                     # presumably pos's value isn't used after this.
  504.                 }
  505.             } else {
  506.                 $self->end(\$tag, 'table'); #'
  507.             }
  508.             # Hmm, I guess this is right.  To work it out:
  509.             #   tr closes any open tr (limited at a table)
  510.             #   thead closes any open thead (limited at a table)
  511.             #   tbody closes any open tbody (limited at a table)
  512.             #   tfoot closes any open tfoot (limited at a table)
  513.             #   colgroup closes any open colgroup (limited at a table)
  514.             #   col can try, but will always fail, at the enclosing table,
  515.             #     as col is empty, and therefore never open!
  516.             # But!
  517.             #   td closes any open td OR th (limited at a table)
  518.             #   th closes any open th OR td (limited at a table)
  519.             #   ...implementable as "close to a tr, or make a tr"
  520.             
  521.         } elsif ($HTML::TreeBuilder::isPhraseMarkup{$tag}) {
  522.             if($ptag eq 'body' and $self->{'_implicit_body_p_tag'}) {
  523.                 print
  524.                   " * Phrasal \U$tag\E right under BODY makes an implicit P\n"
  525.                  if DEBUG > 1;
  526.                 $pos = $self->insert_element('p', 1);
  527.                  # is $pos's value used after this?
  528.             }
  529.         }
  530.         # End of implicit endings logic
  531.         
  532.     # End of "elsif ($HTML::TreeBuilder::isBodyElement{$tag}"
  533.     #----------------------------------------------------------------------
  534.     
  535.     } elsif ($HTML::TreeBuilder::isHeadElement{$tag}) {
  536.         if ($pos->is_inside('body')) {
  537.             print $indent, " * head element \U$tag\E found inside BODY!\n"
  538.              if DEBUG;
  539.             $self->warning("Header element <$tag> in body");  # [sic]
  540.         } elsif (!$pos->is_inside('head')) {
  541.             print $indent, " * head element \U$tag\E makes an implicit HEAD.\n"
  542.              if DEBUG > 1;
  543.         } else {
  544.             print $indent,
  545.               " * head element \U$tag\E goes inside existing HEAD.\n"
  546.              if DEBUG > 1;
  547.         }
  548.         $self->{'_pos'} = $self->{'_head'} || die "Where'd my head go?";
  549.  
  550.     #----------------------------------------------------------------------
  551.     } elsif ($tag eq 'html') {
  552.         if(delete $self->{'_implicit'}) { # first time here
  553.             print $indent, " * good! found the real HTML element!\n"
  554.              if DEBUG > 1;
  555.         } else {
  556.             print $indent, " * Found a second HTML element\n"
  557.              if DEBUG;
  558.             $self->warning("Found a nested <html> element");
  559.         }
  560.  
  561.         # in either case, migrate attributes to the real element
  562.         for (keys %$attr) {
  563.             $self->attr($_, $attr->{$_});
  564.         }
  565.         $self->{'_pos'} = undef;
  566.         return $self;    # bypass tweaking.
  567.  
  568.     #----------------------------------------------------------------------
  569.     } elsif ($tag eq 'head') {
  570.         my $head = $self->{'_head'} || die "Where'd my head go?";
  571.         if(delete $head->{'_implicit'}) { # first time here
  572.             print $indent, " * good! found the real HEAD element!\n"
  573.              if DEBUG > 1;
  574.         } else { # been here before
  575.             print $indent, " * Found a second HEAD element\n"
  576.              if DEBUG;
  577.             $self->warning("Found a second <head> element");
  578.         }
  579.  
  580.         # in either case, migrate attributes to the real element
  581.         for (keys %$attr) {
  582.             $head->attr($_, $attr->{$_});
  583.         }
  584.         return $self->{'_pos'} = $head;    # bypass tweaking.
  585.  
  586.     #----------------------------------------------------------------------
  587.     } elsif ($tag eq 'body') {
  588.         my $body = $self->{'_body'} || die "Where'd my body go?";
  589.         if(delete $body->{'_implicit'}) { # first time here
  590.             print $indent, " * good! found the real BODY element!\n"
  591.              if DEBUG > 1;
  592.         } else { # been here before
  593.             print $indent, " * Found a second BODY element\n"
  594.              if DEBUG;
  595.             $self->warning("Found a second <body> element");
  596.         }
  597.  
  598.         # in either case, migrate attributes to the real element
  599.         for (keys %$attr) {
  600.             $body->attr($_, $attr->{$_});
  601.         }
  602.         return $self->{'_pos'} = $body;    # bypass tweaking.
  603.  
  604.     #----------------------------------------------------------------------
  605.     } elsif ($tag eq 'frameset') {
  606.       if(
  607.         !($self->{'_frameset_seen'}++)   # first frameset seen
  608.         and !$self->{'_noframes_seen'}
  609.           # otherwise it'll be under the noframes already
  610.         and !$self->is_inside('body')
  611.       ) {
  612.     # The following is a bit of a hack.  We don't use the normal
  613.         #  insert_element because 1) we don't want it as _pos, but instead
  614.         #  right under $self, and 2), more importantly, that we don't want
  615.         #  this inserted at the /end/ of $self's content_list, but instead
  616.         #  in the middle of it, specifiaclly right before the body element.
  617.         #
  618.         my $c = $self->{'_content'} || die "Contentless root?";
  619.         my $body = $self->{'_body'} || die "Where'd my BODY go?";
  620.         for(my $i = 0; $i < @$c; ++$i) {
  621.           if($c->[$i] eq $body) {
  622.             splice(@$c, $i, 0, $self->{'_pos'} = $pos = $e);
  623.         $e->{'_parent'} = $self;
  624.             $already_inserted = 1;
  625.             print $indent, " * inserting 'frameset' right before BODY.\n"
  626.              if DEBUG > 1;
  627.             last;
  628.           }
  629.         }
  630.         die "BODY not found in children of root?" unless $already_inserted;
  631.       }
  632.  
  633.     } elsif ($tag eq 'frame') {
  634.         # Okay, fine, pass thru.
  635.         # Should probably enforce that these should be under a frameset.
  636.         # But hey.  Ditto for enforcing that 'noframes' should be under
  637.         # a 'frameset', as the DTDs say.
  638.  
  639.     } elsif ($tag eq 'noframes') {
  640.         # This basically assumes there'll be exactly one 'noframes' element
  641.         #  per document.  At least, only the first one gets to have the
  642.         #  body under it.  And if there are no noframes elements, then
  643.         #  the body pretty much stays where it is.  Is that ever a problem?
  644.         if($self->{'_noframes_seen'}++) {
  645.           print $indent, " * ANOTHER noframes element?\n" if DEBUG;
  646.         } else {
  647.           if($pos->is_inside('body')) {
  648.             print $indent, " * 'noframes' inside 'body'.  Odd!\n" if DEBUG;
  649.             # In that odd case, we /can't/ make body a child of 'noframes',
  650.             # because it's an ancestor of the 'noframes'!
  651.           } else {
  652.             $e->push_content( $self->{'_body'} || die "Where'd my body go?" );
  653.             print $indent, " * Moving body to be under noframes.\n" if DEBUG;
  654.           }
  655.         }
  656.  
  657.     #----------------------------------------------------------------------
  658.     } else {
  659.         # unknown tag
  660.         if ($self->{'_ignore_unknown'}) {
  661.             print $indent, " * Ignoring unknown tag \U$tag\E\n" if DEBUG;
  662.             $self->warning("Skipping unknown tag $tag");
  663.             return;
  664.         } else {
  665.             print $indent, " * Accepting unknown tag \U$tag\E\n"
  666.               if DEBUG;
  667.         }
  668.     }
  669.     #----------------------------------------------------------------------
  670.      # End of mumbo-jumbo
  671.     
  672.     
  673.     print
  674.       $indent, "(Attaching ", $e->{'_tag'}, " under ",
  675.       ($self->{'_pos'} || $self)->{'_tag'}, ")\n"
  676.         # because if _pos isn't defined, it goes under self
  677.      if DEBUG;
  678.     
  679.     
  680.     # The following if-clause is to delete /some/ ignorable whitespace
  681.     #  nodes, as we're making the tree.
  682.     # This'd be a node we'd catch later anyway, but we might as well
  683.     #  nip it in the bud now.
  684.     # This doesn't catch /all/ deletable WS-nodes, so we do have to call
  685.     #  the tightener later to catch the rest.
  686.  
  687.     if($self->{'_tighten'} and !$self->{'_ignore_text'}) {  # if tightenable
  688.       my($sibs, $par);
  689.       if(
  690.          ($sibs = ( $par = $self->{'_pos'} || $self )->{'_content'})
  691.          and @$sibs  # parent already has content
  692.          and !ref($sibs->[-1])  # and the last one there is a text node
  693.          and $sibs->[-1] !~ m<\S>s  # and it's all whitespace
  694.  
  695.          and (  # one of these has to be eligible...
  696.                $HTML::TreeBuilder::canTighten{$tag}
  697.                or
  698.                (
  699.                  (@$sibs == 1)
  700.                    ? # WS is leftmost -- so parent matters
  701.                      $HTML::TreeBuilder::canTighten{$par->{'_tag'}}
  702.                    : # WS is after another node -- it matters
  703.                      (ref $sibs->[-2]
  704.                       and $HTML::TreeBuilder::canTighten{$sibs->[-2]{'_tag'}}
  705.                      )
  706.                )
  707.              )
  708.  
  709.          and !$par->is_inside('pre', 'xmp', 'textarea', 'plaintext')
  710.                 # we're clear
  711.       ) {
  712.         pop @$sibs;
  713.         print $indent, "Popping a preceding all-WS node\n" if DEBUG;
  714.       }
  715.     }
  716.     
  717.     $self->insert_element($e) unless $already_inserted;
  718.  
  719.     if(DEBUG) {
  720.       if($self->{'_pos'}) {
  721.         print
  722.           $indent, "(Current lineage of pos:  \U$tag\E under ",
  723.           join('/',
  724.             reverse(
  725.               # $self->{'_pos'}{'_tag'},  # don't list myself!
  726.               $self->{'_pos'}->lineage_tag_names
  727.             )
  728.           ),
  729.           ".)\n";
  730.       } else {
  731.         print $indent, "(Pos points nowhere!?)\n";
  732.       }
  733.     }
  734.  
  735.     unless(($self->{'_pos'} || '') eq $e) {
  736.       # if it's an empty element -- i.e., if it didn't change the _pos
  737.       &{  $self->{"_tweak_$tag"}
  738.           ||  $self->{'_tweak_*'}
  739.           || return $e
  740.       }(map $_,   $e, $tag, $self); # make a list so the user can't clobber
  741.     }
  742.  
  743.     return $e;
  744.   }
  745. }
  746.  
  747. #==========================================================================
  748.  
  749. {
  750.   my $indent;
  751.  
  752.   sub end {
  753.     return if $_[0]{'_stunted'};
  754.     
  755.     # Either: Acccept an end-tag signal from HTML::Parser
  756.     # Or: Method for closing currently open elements in some fairly complex
  757.     #  way, as used by other methods in this class.
  758.     my($self, $tag, @stop) = @_;
  759.     if($tag eq 'x-html') {
  760.       print "Ignoring close-x-html tag.\n" if DEBUG;
  761.       # inserted by some lame code-generators.
  762.       return;
  763.     }
  764.  
  765.     unless(ref($tag) or $tag =~ m/^[-_a-zA-Z0-9:%]+$/s) {
  766.       DEBUG and print "End-tag name $tag is no good.  Skipping.\n";
  767.       return;
  768.       # This avoids having Element's new() throw an exception.
  769.     }
  770.  
  771.     # This method accepts two calling formats:
  772.     #  1) from Parser:  $self->end('tag_name', 'origtext')
  773.     #        in which case we shouldn't mistake origtext as a blocker tag
  774.     #  2) from myself:  $self->end(\q{tagname1}, 'blk1', ... )
  775.     #     from myself:  $self->end(['tagname1', 'tagname2'], 'blk1',  ... )
  776.     
  777.     # End the specified tag, but don't move above any of the blocker tags.
  778.     # The tag can also be a reference to an array.  Terminate the first
  779.     # tag found.
  780.     
  781.     my $ptag = ( my $p = $self->{'_pos'} || $self )->{'_tag'};
  782.      # $p and $ptag are sort-of stratch
  783.     
  784.     if(ref($tag)) {
  785.       # First param is a ref of one sort or another --
  786.       #  THE CALL IS COMING FROM INSIDE THE HOUSE!
  787.       $tag = $$tag if ref($tag) eq 'SCALAR';
  788.        # otherwise it's an arrayref.
  789.     } else {
  790.       # the call came from Parser -- just ignore origtext
  791.       @stop = ();
  792.     }
  793.     
  794.     #my($indent);
  795.     if(DEBUG) {
  796.       # optimization -- don't figure out depth unless we're in debug mode
  797.       my @lineage_tags = $p->lineage_tag_names;
  798.       $indent = '  ' x (1 + @lineage_tags);
  799.       
  800.       # now announce ourselves
  801.       print $indent, "Ending ",
  802.         ref($tag) ? ('[', join(' ', @$tag ), ']') : "\U$tag\E",
  803.         scalar(@stop) ? (" no higher than [", join(' ', @stop), "]" )
  804.           : (), ".\n"
  805.       ;
  806.       
  807.       print $indent, " (Current lineage: ", join('/', @lineage_tags), ".)\n"
  808.        if DEBUG > 1;
  809.        
  810.       if(DEBUG > 3) {
  811.         #my(
  812.         # $package, $filename, $line, $subroutine,
  813.         # $hasargs, $wantarray, $evaltext, $is_require) = caller;
  814.         print $indent,
  815.           " (Called from ", (caller(1))[3], ' line ', (caller(1))[2],
  816.           ")\n";
  817.       }
  818.       
  819.     #} else {
  820.     #  $indent = ' ';
  821.     }
  822.     # End of if DEBUG
  823.     
  824.     # Now actually do it
  825.     my @to_close;
  826.     if($tag eq '*') {
  827.       # Special -- close everything up to (but not including) the first
  828.       #  limiting tag, or return if none found.  Somewhat of a special case.
  829.      PARENT:
  830.       while (defined $p) {
  831.         $ptag = $p->{'_tag'};
  832.         print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
  833.         for (@stop) {
  834.           if($ptag eq $_) {
  835.             print $indent, " (Hit a $_; closing everything up to here.)\n"
  836.              if DEBUG > 2;
  837.             last PARENT;
  838.           }
  839.         }
  840.         push @to_close, $p;
  841.         $p = $p->{'_parent'}; # no match so far? keep moving up
  842.         print
  843.           $indent, 
  844.           " (Moving on up to ", $p ? $p->{'_tag'} : 'nil', ")\n"
  845.          if DEBUG > 1;
  846.         ;
  847.       }
  848.       unless(defined $p) { # We never found what we were looking for.
  849.         print $indent, " (We never found a limit.)\n" if DEBUG > 1;
  850.         return;
  851.       }
  852.       #print
  853.       #   $indent,
  854.       #   " (To close: ", join('/', map $_->tag, @to_close), ".)\n"
  855.       #  if DEBUG > 4;
  856.       
  857.       # Otherwise update pos and fall thru.
  858.       $self->{'_pos'} = $p;
  859.     } elsif (ref $tag) {
  860.       # Close the first of any of the matching tags, giving up if you hit
  861.       #  any of the stop-tags.
  862.      PARENT:
  863.       while (defined $p) {
  864.         $ptag = $p->{'_tag'};
  865.         print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
  866.         for (@$tag) {
  867.           if($ptag eq $_) {
  868.             print $indent, " (Closing $_.)\n" if DEBUG > 2;
  869.             last PARENT;
  870.           }
  871.         }
  872.         for (@stop) {
  873.           if($ptag eq $_) {
  874.             print $indent, " (Hit a limiting $_ -- bailing out.)\n"
  875.              if DEBUG > 1;
  876.             return; # so it was all for naught
  877.           }
  878.         }
  879.         push @to_close, $p;
  880.         $p = $p->{'_parent'};
  881.       }
  882.       return unless defined $p; # We went off the top of the tree.
  883.       # Otherwise specified element was found; set pos to its parent.
  884.       push @to_close, $p;
  885.       $self->{'_pos'} = $p->{'_parent'};
  886.     } else {
  887.       # Close the first of the specified tag, giving up if you hit
  888.       #  any of the stop-tags.
  889.       while (defined $p) {
  890.         $ptag = $p->{'_tag'};
  891.         print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
  892.         if($ptag eq $tag) {
  893.           print $indent, " (Closing $tag.)\n" if DEBUG > 2;
  894.           last;
  895.         }
  896.         for (@stop) {
  897.           if($ptag eq $_) {
  898.             print $indent, " (Hit a limiting $_ -- bailing out.)\n"
  899.              if DEBUG > 1;
  900.             return; # so it was all for naught
  901.           }
  902.         }
  903.         push @to_close, $p;
  904.         $p = $p->{'_parent'};
  905.       }
  906.       return unless defined $p; # We went off the top of the tree.
  907.       # Otherwise specified element was found; set pos to its parent.
  908.       push @to_close, $p;
  909.       $self->{'_pos'} = $p->{'_parent'};
  910.     }
  911.     
  912.     $self->{'_pos'} = undef if $self eq ($self->{'_pos'} || '');
  913.     print $indent, "(Pos now points to ",
  914.       $self->{'_pos'} ? $self->{'_pos'}{'_tag'} : '???', ".)\n"
  915.      if DEBUG > 1;
  916.     
  917.     ### EXPENSIVE, because has to check that it's not under a pre
  918.     ### or a CDATA-parent.  That's one more method call per end()!
  919.     ### Might as well just do this at the end of the tree-parse, I guess,
  920.     ### at which point we'd be parsing top-down, and just not traversing
  921.     ### under pre's or CDATA-parents.
  922.     ##
  923.     ## Take this opportunity to nix any terminal whitespace nodes.
  924.     ## TODO: consider whether this (plus the logic in start(), above)
  925.     ## would ever leave any WS nodes in the tree.
  926.     ## If not, then there's no reason to have eof() call
  927.     ## delete_ignorable_whitespace on the tree, is there?
  928.     ##
  929.     #if(@to_close and $self->{'_tighten'} and !$self->{'_ignore_text'} and
  930.     #  ! $to_close[-1]->is_inside('pre', keys %HTML::Tagset::isCDATA_Parent)
  931.     #) {  # if tightenable
  932.     #  my($children, $e_tag);
  933.     #  foreach my $e (reverse @to_close) { # going top-down
  934.     #    last if 'pre' eq ($e_tag = $e->{'_tag'}) or
  935.     #     $HTML::Tagset::isCDATA_Parent{$e_tag};
  936.     #    
  937.     #    if(
  938.     #      $children = $e->{'_content'}
  939.     #      and @$children      # has children
  940.     #      and !ref($children->[-1])
  941.     #      and $children->[-1] =~ m<^\s+$>s # last node is all-WS
  942.     #      and
  943.     #        (
  944.     #         # has a tightable parent:
  945.     #         $HTML::TreeBuilder::canTighten{ $e_tag }
  946.     #         or
  947.     #          ( # has a tightenable left sibling:
  948.     #            @$children > 1 and 
  949.     #            ref($children->[-2])
  950.     #            and $HTML::TreeBuilder::canTighten{ $children->[-2]{'_tag'} }
  951.     #          )
  952.     #        )
  953.     #    ) {
  954.     #      pop @$children;
  955.     #      #print $indent, "Popping a terminal WS node from ", $e->{'_tag'},
  956.     #      #  " (", $e->address, ") while exiting.\n" if DEBUG;
  957.     #    }
  958.     #  }
  959.     #}
  960.     
  961.     
  962.     foreach my $e (@to_close) {
  963.       # Call the applicable callback, if any
  964.       $ptag = $e->{'_tag'};
  965.       &{  $self->{"_tweak_$ptag"}
  966.           ||  $self->{'_tweak_*'}
  967.           || next
  968.       }(map $_,   $e, $ptag, $self);
  969.       print $indent, "Back from tweaking.\n" if DEBUG;
  970.       last if $self->{'_stunted'}; # in case one of the handlers called stunt
  971.     }
  972.     return @to_close;
  973.   }
  974. }
  975.  
  976. #==========================================================================
  977. {
  978.   my($indent, $nugget);
  979.  
  980.   sub text {
  981.     return if $_[0]{'_stunted'};
  982.     
  983.   # Accept a "here's a text token" signal from HTML::Parser.
  984.     my($self, $text, $is_cdata) = @_;
  985.       # the >3.0 versions of Parser may pass a cdata node.
  986.       # Thanks to Gisle Aas for pointing this out.
  987.     
  988.     return unless length $text; # I guess that's always right
  989.     
  990.     my $ignore_text = $self->{'_ignore_text'};
  991.     my $no_space_compacting = $self->{'_no_space_compacting'};
  992.     
  993.     my $pos = $self->{'_pos'} || $self;
  994.     
  995.     HTML::Entities::decode($text)
  996.      unless $ignore_text || $is_cdata
  997.       || $HTML::Tagset::isCDATA_Parent{$pos->{'_tag'}};
  998.     
  999.     #my($indent, $nugget);
  1000.     if(DEBUG) {
  1001.       # optimization -- don't figure out depth unless we're in debug mode
  1002.       my @lineage_tags = $pos->lineage_tag_names;
  1003.       $indent = '  ' x (1 + @lineage_tags);
  1004.       
  1005.       $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  1006.       $nugget =~ s<([\x00-\x1F])>
  1007.                  <'\\x'.(unpack("H2",$1))>eg;
  1008.       print
  1009.         $indent, "Proposing a new text node ($nugget) under ",
  1010.         join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  1011.         ".\n";
  1012.       
  1013.     #} else {
  1014.     #  $indent = ' ';
  1015.     }
  1016.     
  1017.     
  1018.     my $ptag;
  1019.     if ($HTML::Tagset::isCDATA_Parent{$ptag = $pos->{'_tag'}}
  1020.         #or $pos->is_inside('pre')
  1021.         or $pos->is_inside('pre', 'textarea')
  1022.     ) {
  1023.         return if $ignore_text;
  1024.         $pos->push_content($text);
  1025.     } else {
  1026.         # return unless $text =~ /\S/;  # This is sometimes wrong
  1027.         
  1028.         if (!$self->{'_implicit_tags'} || $text !~ /\S/) {
  1029.             # don't change anything
  1030.         } elsif ($ptag eq 'head' or $ptag eq 'noframes') {
  1031.             if($self->{'_implicit_body_p_tag'}) {
  1032.               print $indent,
  1033.                 " * Text node under \U$ptag\E closes \U$ptag\E, implicates BODY and P.\n"
  1034.                if DEBUG > 1;
  1035.               $self->end(\$ptag);
  1036.               $pos =
  1037.                 $self->{'_body'}
  1038.                 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  1039.                 : $self->insert_element('body', 1);
  1040.               $pos = $self->insert_element('p', 1);
  1041.             } else {
  1042.               print $indent,
  1043.                 " * Text node under \U$ptag\E closes, implicates BODY.\n"
  1044.                if DEBUG > 1;
  1045.               $self->end(\$ptag);
  1046.               $pos =
  1047.                 $self->{'_body'}
  1048.                 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  1049.                 : $self->insert_element('body', 1);
  1050.             }
  1051.         } elsif ($ptag eq 'html') {
  1052.             if($self->{'_implicit_body_p_tag'}) {
  1053.               print $indent,
  1054.                 " * Text node under HTML implicates BODY and P.\n"
  1055.                if DEBUG > 1;
  1056.               $pos =
  1057.                 $self->{'_body'}
  1058.                 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  1059.                 : $self->insert_element('body', 1);
  1060.               $pos = $self->insert_element('p', 1);
  1061.             } else {
  1062.               print $indent,
  1063.                 " * Text node under HTML implicates BODY.\n"
  1064.                if DEBUG > 1;
  1065.               $pos =
  1066.                 $self->{'_body'}
  1067.                 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
  1068.                 : $self->insert_element('body', 1);
  1069.               #print "POS is $pos, ", $pos->{'_tag'}, "\n";
  1070.             }
  1071.         } elsif ($ptag eq 'body') {
  1072.             if($self->{'_implicit_body_p_tag'}) {
  1073.               print $indent,
  1074.                 " * Text node under BODY implicates P.\n"
  1075.                if DEBUG > 1;
  1076.               $pos = $self->insert_element('p', 1);
  1077.             }
  1078.         } elsif ($ptag eq 'table') {
  1079.             print $indent,
  1080.               " * Text node under TABLE implicates TR and TD.\n"
  1081.              if DEBUG > 1;
  1082.             $self->insert_element('tr', 1);
  1083.             $pos = $self->insert_element('td', 1);
  1084.              # double whammy!
  1085.         } elsif ($ptag eq 'tr') {
  1086.             print $indent,
  1087.               " * Text node under TR implicates TD.\n"
  1088.              if DEBUG > 1;
  1089.             $pos = $self->insert_element('td', 1);
  1090.         }
  1091.         # elsif (
  1092.         #       # $ptag eq 'li'   ||
  1093.         #       # $ptag eq 'dd'   ||
  1094.         #         $ptag eq 'form') {
  1095.         #    $pos = $self->insert_element('p', 1);
  1096.         #}
  1097.         
  1098.         
  1099.         # Whatever we've done above should have had the side
  1100.         # effect of updating $self->{'_pos'}
  1101.         
  1102.                 
  1103.         #print "POS is now $pos, ", $pos->{'_tag'}, "\n";
  1104.         
  1105.         return if $ignore_text;
  1106.         $text =~ s/\s+/ /g unless $no_space_compacting ;  # canonical space
  1107.         
  1108.         print
  1109.           $indent, " (Attaching text node ($nugget) under ",
  1110.           # was: $self->{'_pos'} ? $self->{'_pos'}{'_tag'} : $self->{'_tag'},
  1111.           $pos->{'_tag'},
  1112.           ").\n"
  1113.          if DEBUG > 1;
  1114.         
  1115.         $pos->push_content($text);
  1116.     }
  1117.     
  1118.     &{ $self->{'_tweak_~text'} || return }($text, $pos, $pos->{'_tag'} . '');
  1119.      # Note that this is very exceptional -- it doesn't fall back to
  1120.      #  _tweak_*, and it gives its tweak different arguments.
  1121.     return;
  1122.   }
  1123. }
  1124.  
  1125. #==========================================================================
  1126.  
  1127. # TODO: test whether comment(), declaration(), and process(), do the right
  1128. #  thing as far as tightening and whatnot.
  1129. # Also, currently, doctypes and comments that appear before head or body
  1130. #  show up in the tree in the wrong place.  Something should be done about
  1131. #  this.  Tricky.  Maybe this whole business of pre-making the body and
  1132. #  whatnot is wrong.
  1133.  
  1134. sub comment {
  1135.   return if $_[0]{'_stunted'};
  1136.   # Accept a "here's a comment" signal from HTML::Parser.
  1137.  
  1138.   my($self, $text) = @_;
  1139.   my $pos = $self->{'_pos'} || $self;
  1140.   return unless $self->{'_store_comments'}
  1141.      || $HTML::Tagset::isCDATA_Parent{ $pos->{'_tag'} };
  1142.   
  1143.   if(DEBUG) {
  1144.     my @lineage_tags = $pos->lineage_tag_names;
  1145.     my $indent = '  ' x (1 + @lineage_tags);
  1146.     
  1147.     my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  1148.     $nugget =~ s<([\x00-\x1F])>
  1149.                  <'\\x'.(unpack("H2",$1))>eg;
  1150.     print
  1151.       $indent, "Proposing a Comment ($nugget) under ",
  1152.       join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  1153.       ".\n";
  1154.   }
  1155.  
  1156.   (my $e = (
  1157.     $self->{'_element_class'} || 'HTML::Element'
  1158.    )->new('~comment'))->{'text'} = $text;
  1159.   $pos->push_content($e);
  1160.   ++($self->{'_element_count'});
  1161.  
  1162.   &{  $self->{'_tweak_~comment'}
  1163.       || $self->{'_tweak_*'}
  1164.       || return $e
  1165.    }(map $_,   $e, '~comment', $self);
  1166.   
  1167.   return $e;
  1168. }
  1169.  
  1170. #==========================================================================
  1171. # TODO: currently this puts declarations in just the wrong place.
  1172. #  How to correct? look at pos->_content, and go to insert at end, 
  1173. #  but back up before any head elements?  Do that just if implicit
  1174. #  mode is on?
  1175.  
  1176. sub declaration {
  1177.   return if $_[0]{'_stunted'};
  1178.   # Accept a "here's a markup declaration" signal from HTML::Parser.
  1179.  
  1180.   return unless $_[0]->{'_store_declarations'};
  1181.   my($self, $text) = @_;
  1182.   my $pos = $self->{'_pos'} || $self;
  1183.   
  1184.   if(DEBUG) {
  1185.     my @lineage_tags = $pos->lineage_tag_names;
  1186.     my $indent = '  ' x (1 + @lineage_tags);
  1187.     
  1188.     my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  1189.     $nugget =~ s<([\x00-\x1F])>
  1190.                  <'\\x'.(unpack("H2",$1))>eg;
  1191.     print
  1192.       $indent, "Proposing a Declaration ($nugget) under ",
  1193.       join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  1194.       ".\n";
  1195.   }
  1196.   (my $e = (
  1197.     $self->{'_element_class'} || 'HTML::Element'
  1198.    )->new('~declaration'))->{'text'} = $text;
  1199.   $pos->push_content($e);
  1200.   ++($self->{'_element_count'});
  1201.  
  1202.   &{  $self->{'_tweak_~declaration'}
  1203.       || $self->{'_tweak_*'}
  1204.       || return $e
  1205.    }(map $_, $e,   '~declaration', $self);
  1206.   
  1207.   return $e;
  1208. }
  1209.  
  1210. #==========================================================================
  1211.  
  1212. sub process {
  1213.   return if $_[0]{'_stunted'};
  1214.   # Accept a "here's a PI" signal from HTML::Parser.
  1215.  
  1216.   return unless $_[0]->{'_store_pis'};
  1217.   my($self, $text) = @_;
  1218.   my $pos = $self->{'_pos'} || $self;
  1219.   
  1220.   if(DEBUG) {
  1221.     my @lineage_tags = $pos->lineage_tag_names;
  1222.     my $indent = '  ' x (1 + @lineage_tags);
  1223.     
  1224.     my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
  1225.     $nugget =~ s<([\x00-\x1F])>
  1226.                  <'\\x'.(unpack("H2",$1))>eg;
  1227.     print
  1228.       $indent, "Proposing a PI ($nugget) under ",
  1229.       join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
  1230.       ".\n";
  1231.   }
  1232.   (my $e = (
  1233.     $self->{'_element_class'} || 'HTML::Element'
  1234.    )->new('~pi'))->{'text'} = $text;
  1235.   $pos->push_content($e);
  1236.   ++($self->{'_element_count'});
  1237.  
  1238.   &{  $self->{'_tweak_~pi'}
  1239.       || $self->{'_tweak_*'}
  1240.       || return $e
  1241.    }(map $_,   $e, '~pi', $self);
  1242.   
  1243.   return $e;
  1244. }
  1245.  
  1246.  
  1247. #==========================================================================
  1248.  
  1249. #When you call $tree->parse_file($filename), and the
  1250. #tree's ignore_ignorable_whitespace attribute is on (as it is
  1251. #by default), HTML::TreeBuilder's logic will manage to avoid
  1252. #creating some, but not all, nodes that represent ignorable
  1253. #whitespace.  However, at the end of its parse, it traverses the
  1254. #tree and deletes any that it missed.  (It does this with an
  1255. #around-method around HTML::Parser's eof method.)
  1256. #
  1257. #However, with $tree->parse($content), the cleanup-traversal step
  1258. #doesn't happen automatically -- so when you're done parsing all
  1259. #content for a document (regardless of whether $content is the only
  1260. #bit, or whether it's just another chunk of content you're parsing into
  1261. #the tree), call $tree->eof() to signal that you're at the end of the
  1262. #text you're inputting to the tree.  Besides properly cleaning any bits
  1263. #of ignorable whitespace from the tree, this will also ensure that
  1264. #HTML::Parser's internal buffer is flushed.
  1265.  
  1266. sub eof {
  1267.   # Accept an "end-of-file" signal from HTML::Parser, or thrown by the user.
  1268.   
  1269.   return if $_[0]->{'_done'}; # we've already been here
  1270.   
  1271.   return $_[0]->SUPER::eof() if $_[0]->{'_stunted'};
  1272.   
  1273.   my $x = $_[0];
  1274.   print "EOF received.\n" if DEBUG;
  1275.   my(@rv);
  1276.   if(wantarray) {
  1277.     # I don't think this makes any difference for this particular
  1278.     #  method, but let's be scrupulous, for once.
  1279.     @rv = $x->SUPER::eof();
  1280.   } else {
  1281.     $rv[0] = $x->SUPER::eof();
  1282.   }
  1283.   
  1284.   $x->end('html') unless $x eq ($x->{'_pos'} || $x);
  1285.    # That SHOULD close everything, and will run the appropriate tweaks.
  1286.    # We /could/ be running under some insane mode such that there's more
  1287.    #  than one HTML element, but really, that's just insane to do anyhow.
  1288.  
  1289.   unless($x->{'_implicit_tags'}) {
  1290.     # delete those silly implicit head and body in case we put
  1291.     # them there in implicit tags mode
  1292.     foreach my $node ($x->{'_head'}, $x->{'_body'}) {
  1293.       $node->replace_with_content
  1294.        if defined $node and ref $node
  1295.           and $node->{'_implicit'} and $node->{'_parent'};
  1296.        # I think they should be empty anyhow, since the only
  1297.        # logic that'd insert under them can apply only, I think,
  1298.        # in the case where _implicit_tags is on
  1299.     }
  1300.     # this may still leave an implicit 'html' at the top, but there's
  1301.     # nothing we can do about that, is there?
  1302.   }
  1303.   
  1304.   $x->delete_ignorable_whitespace()
  1305.    # this's why we trap this -- an after-method
  1306.    if $x->{'_tighten'} and ! $x->{'_ignore_text'};
  1307.   $x->{'_done'} = 1;
  1308.   
  1309.   return @rv if wantarray;
  1310.   return $rv[0];
  1311. }
  1312.  
  1313. #==========================================================================
  1314.  
  1315. # TODO: document
  1316.  
  1317. sub stunt {
  1318.   my $self = $_[0];
  1319.   print "Stunting the tree.\n" if DEBUG;
  1320.   $self->{'_done'} = 1;
  1321.   
  1322.   if($HTML::Parser::VERSION < 3) {
  1323.     #This is a MEAN MEAN HACK.  And it works most of the time!
  1324.     $self->{'_buf'} = '';
  1325.     my $fh = *HTML::Parser::F{IO};
  1326.     # the local'd FH used by parse_file loop
  1327.     if(defined $fh) {
  1328.       print "Closing Parser's filehandle $fh\n" if DEBUG;
  1329.       close($fh);
  1330.     }
  1331.     
  1332.     # But if they called $tree->parse_file($filehandle)
  1333.     #  or $tree->parse_file(*IO), then there will be no *HTML::Parser::F{IO}
  1334.     #  to close.  Ahwell.  Not a problem for most users these days.
  1335.     
  1336.   } else {
  1337.     $self->SUPER::eof();
  1338.      # Under 3+ versions, calling eof from inside a parse will abort the
  1339.      #  parse / parse_file
  1340.   }
  1341.   
  1342.   # In the off chance that the above didn't work, we'll throw
  1343.   #  this flag to make any future events be no-ops.
  1344.   $self->stunted(1);
  1345.   return;
  1346. }
  1347.  
  1348. # TODO: document
  1349. sub stunted  { shift->_elem('_stunted',  @_); }
  1350. sub done     { shift->_elem('_done',     @_); }
  1351.  
  1352. #==========================================================================
  1353.  
  1354. sub delete {
  1355.   # Override Element's delete method.
  1356.   # This does most, if not all, of what Element's delete does anyway.
  1357.   # Deletes content, including content in some special attributes.
  1358.   # But doesn't empty out the hash.
  1359.  
  1360.   $_[0]->{'_element_count'} = 1; # never hurts to be scrupulously correct
  1361.  
  1362.   delete @{$_[0]}{'_body', '_head', '_pos'};
  1363.   for (@{ delete($_[0]->{'_content'})
  1364.           || []
  1365.         }, # all/any content
  1366. #       delete @{$_[0]}{'_body', '_head', '_pos'}
  1367.          # ...and these, in case these elements don't appear in the
  1368.          #   content, which is possible.  If they did appear (as they
  1369.          #   usually do), then calling $_->delete on them again is harmless.
  1370. #  I don't think that's such a hot idea now.  Thru creative reattachment,
  1371. #  those could actually now point to elements in OTHER trees (which we do
  1372. #  NOT want to delete!).
  1373. ## Reasoned out:
  1374. #  If these point to elements not in the content list of any element in this
  1375. #   tree, but not in the content list of any element in any OTHER tree, then
  1376. #   just deleting these will make their refcounts hit zero.
  1377. #  If these point to elements in the content lists of elements in THIS tree,
  1378. #   then we'll get to deleting them when we delete from the top.
  1379. #  If these point to elements in the content lists of elements in SOME OTHER
  1380. #   tree, then they're not to be deleted.
  1381.       )
  1382.   {
  1383.     $_->delete
  1384.      if defined $_ and ref $_   #  Make sure it's an object.
  1385.         and $_ ne $_[0];   #  And avoid hitting myself, just in case!
  1386.   }
  1387.  
  1388.   $_[0]->detach if $_[0]->{'_parent'} and $_[0]->{'_parent'}{'_content'};
  1389.    # An 'html' element having a parent is quite unlikely.
  1390.  
  1391.   return undef;
  1392. }
  1393.  
  1394. sub tighten_up { # legacy
  1395.   shift->delete_ignorable_whitespace(@_);
  1396. }
  1397.  
  1398. sub elementify {
  1399.   # Rebless this object down into the normal element class.
  1400.   my $self = $_[0];
  1401.   my $to_class = ($self->{'_element_class'} || 'HTML::Element');
  1402.   delete @{$self}{ grep {;
  1403.     length $_ and substr($_,0,1) eq '_'
  1404.    # The private attributes that we'll retain:
  1405.     and $_ ne '_tag' and $_ ne '_parent' and $_ ne '_content'
  1406.     and $_ ne '_implicit' and $_ ne '_pos'
  1407.     and $_ ne '_element_class'
  1408.   } keys %$self };
  1409.   bless $self, $to_class;   # Returns the same object we were fed
  1410. }
  1411.  
  1412. #--------------------------------------------------------------------------
  1413.  
  1414. sub guts {
  1415.   my @out;
  1416.   my @stack = ($_[0]);
  1417.   my $destructive = $_[1];
  1418.   my $this;
  1419.   while(@stack) {
  1420.     $this = shift @stack;
  1421.     if(!ref $this) {
  1422.       push @out, $this;  # yes, it can include text nodes
  1423.     } elsif(! $this->{'_implicit'}) {
  1424.       push @out, $this;
  1425.       delete $this->{'_parent'} if $destructive;
  1426.     } else {
  1427.       # it's an implicit node.  Delete it and recurse
  1428.       delete $this->{'_parent'} if $destructive;
  1429.       unshift @stack, @{
  1430.         (  $destructive ? 
  1431.            delete($this->{'_content'})
  1432.            :      $this->{'_content'}
  1433.         )
  1434.         || []
  1435.       };
  1436.     }
  1437.   }
  1438.   # Doesn't call a real $root->delete on the (when implicit) root,
  1439.   #  but I don't think it needs to.
  1440.   
  1441.   return @out if wantarray;  # one simple normal case.
  1442.   return undef unless @out;
  1443.   return $out[0] if @out == 1 and ref($out[0]);
  1444.   my $x = HTML::Element->new('div', '_implicit' => 1);
  1445.   $x->push_content(@out);
  1446.   return $x;
  1447. }
  1448.  
  1449. sub disembowel { $_[0]->guts(1) }
  1450.  
  1451. #--------------------------------------------------------------------------
  1452. 1;
  1453.  
  1454. __END__
  1455.  
  1456. =head1 NAME
  1457.  
  1458. HTML::TreeBuilder - Parser that builds a HTML syntax tree
  1459.  
  1460. =head1 SYNOPSIS
  1461.  
  1462.   foreach my $file_name (@ARGV) {
  1463.     my $tree = HTML::TreeBuilder->new; # empty tree
  1464.     $tree->parse_file($file_name);
  1465.     print "Hey, here's a dump of the parse tree of $file_name:\n";
  1466.     $tree->dump; # a method we inherit from HTML::Element
  1467.     print "And here it is, bizarrely rerendered as HTML:\n",
  1468.       $tree->as_HTML, "\n";
  1469.  
  1470.     # Now that we're done with it, we must destroy it.
  1471.     $tree = $tree->delete;
  1472.   }
  1473.  
  1474. =head1 DESCRIPTION
  1475.  
  1476. (This class is part of the L<HTML::Tree|HTML::Tree> dist.)
  1477.  
  1478. This class is for HTML syntax trees that get built out of HTML
  1479. source.  The way to use it is to:
  1480.  
  1481. 1. start a new (empty) HTML::TreeBuilder object,
  1482.  
  1483. 2. then use one of the methods from HTML::Parser (presumably with
  1484. $tree->parse_file($filename) for files, or with
  1485. $tree->parse($document_content) and $tree->eof if you've got
  1486. the content in a string) to parse the HTML
  1487. document into the tree $tree.
  1488.  
  1489. (You can combine steps 1 and 2 with the "new_from_file" or
  1490. "new_from_content" methods.)
  1491.  
  1492. 2b. call $root-E<gt>elementify() if you want.
  1493.  
  1494. 3. do whatever you need to do with the syntax tree, presumably
  1495. involving traversing it looking for some bit of information in it,
  1496.  
  1497. 4. and finally, when you're done with the tree, call $tree->delete() to
  1498. erase the contents of the tree from memory.  This kind of thing
  1499. usually isn't necessary with most Perl objects, but it's necessary for
  1500. TreeBuilder objects.  See L<HTML::Element|HTML::Element> for a more verbose
  1501. explanation of why this is the case.
  1502.  
  1503. =head1 METHODS AND ATTRIBUTES
  1504.  
  1505. Objects of this class inherit the methods of both HTML::Parser and
  1506. HTML::Element.  The methods inherited from HTML::Parser are used for
  1507. building the HTML tree, and the methods inherited from HTML::Element
  1508. are what you use to scrutinize the tree.  Besides this
  1509. (HTML::TreeBuilder) documentation, you must also carefully read the
  1510. HTML::Element documentation, and also skim the HTML::Parser
  1511. documentation -- probably only its parse and parse_file methods are of
  1512. interest.
  1513.  
  1514. Most of the following methods native to HTML::TreeBuilder control how
  1515. parsing takes place; they should be set I<before> you try parsing into
  1516. the given object.  You can set the attributes by passing a TRUE or
  1517. FALSE value as argument.  E.g., $root->implicit_tags returns the current
  1518. setting for the implicit_tags option, $root->implicit_tags(1) turns that
  1519. option on, and $root->implicit_tags(0) turns it off.
  1520.  
  1521. =over 4
  1522.  
  1523. =item $root = HTML::TreeBuilder->new_from_file(...)
  1524.  
  1525. This "shortcut" constructor merely combines constructing a new object
  1526. (with the "new" method, below), and calling $new->parse_file(...) on
  1527. it.  Returns the new object.  Note that this provides no way of
  1528. setting any parse options like store_comments (for that, call new, and
  1529. then set options, before calling parse_file).  See the notes (below)
  1530. on parameters to parse_file.
  1531.  
  1532. =item $root = HTML::TreeBuilder->new_from_content(...)
  1533.  
  1534. This "shortcut" constructor merely combines constructing a new object
  1535. (with the "new" method, below), and calling for(...){$new->parse($_)}
  1536. and $new->eof on it.  Returns the new object.  Note that this provides
  1537. no way of setting any parse options like store_comments (for that,
  1538. call new, and then set options, before calling parse_file).  Example
  1539. usages: HTML::TreeBuilder->new_from_content(@lines), or
  1540. HTML::TreeBuilder->new_from_content($content)
  1541.  
  1542. =item $root = HTML::TreeBuilder->new()
  1543.  
  1544. This creates a new HTML::TreeBuilder object.  This method takes no
  1545. attributes.
  1546.  
  1547. =item $root->parse_file(...)
  1548.  
  1549. [An important method inherited from L<HTML::Parser|HTML::Parser>, which
  1550. see.  Current versions of HTML::Parser can take a filespec, or a
  1551. filehandle object, like *FOO, or some object from class IO::Handle,
  1552. IO::File, IO::Socket) or the like.
  1553. I think you should check that a given file exists I<before> calling
  1554. $root->parse_file($filespec).]
  1555.  
  1556. =item $root->parse(...)
  1557.  
  1558. [A important method inherited from L<HTML::Parser|HTML::Parser>, which
  1559. see.  See the note below for $root->eof().]
  1560.  
  1561. =item $root->eof()
  1562.  
  1563. This signals that you're finished parsing content into this tree; this
  1564. runs various kinds of crucial cleanup on the tree.  This is called
  1565. I<for you> when you call $root->parse_file(...), but not when
  1566. you call $root->parse(...).  So if you call
  1567. $root->parse(...), then you I<must> call $root->eof()
  1568. once you've finished feeding all the chunks to parse(...), and
  1569. before you actually start doing anything else with the tree in C<$root>.
  1570.  
  1571. =item $root->delete()
  1572.  
  1573. [An important method inherited from L<HTML::Element|HTML::Element>, which
  1574. see.]
  1575.  
  1576. =item $root->elementify()
  1577.  
  1578. This changes the class of the object in $root from
  1579. HTML::TreeBuilder to the class used for all the rest of the elements
  1580. in that tree (generally HTML::Element).  Returns $root.
  1581.  
  1582. For most purposes, this is unnecessary, but if you call this after
  1583. (after!!)
  1584. you've finished building a tree, then it keeps you from accidentally
  1585. trying to call anything but HTML::Element methods on it.  (I.e., if
  1586. you accidentally call C<$root-E<gt>parse_file(...)> on the
  1587. already-complete and elementified tree, then instead of charging ahead
  1588. and I<wreaking havoc>, it'll throw a fatal error -- since C<$root> is
  1589. now an object just of class HTML::Element which has no C<parse_file>
  1590. method.
  1591.  
  1592. Note that elementify currently deletes all the private attributes of
  1593. $root except for "_tag", "_parent", "_content", "_pos", and
  1594. "_implicit".  If anyone requests that I change this to leave in yet
  1595. more private attributes, I might do so, in future versions.
  1596.  
  1597. =item @nodes = $root->guts()
  1598.  
  1599. =item $parent_for_nodes = $root->guts()
  1600.  
  1601. In list context (as in the first case), this method returns the topmost
  1602. non-implicit nodes in a tree.  This is useful when you're parsing HTML
  1603. code that you know doesn't expect an HTML document, but instead just
  1604. a fragment of an HTML document.  For example, if you wanted the parse
  1605. tree for a file consisting of just this:
  1606.  
  1607.   <li>I like pie!
  1608.  
  1609. Then you would get that with C<< @nodes = $root->guts(); >>.
  1610. It so happens that in this case, @notes will contain just one
  1611. element object, representing the "li" node (with "I like pie!" being
  1612. its text child node).  However, consider if you were parsing this:
  1613.  
  1614.   <hr>Hooboy!<hr>
  1615.  
  1616. In that case, C<< $root->guts() >> would return three items:
  1617. an element object for the first "hr", a text string "Hooboy!", and
  1618. another "hr" element object.
  1619.  
  1620. For cases where you want definitely one element (so you can treat it as
  1621. a "document fragment", roughly speaking), call C<guts()> in scalar
  1622. context, as in C<< $parent_for_nodes = $root->guts() >>. That works like
  1623. C<guts()> in list context; in fact, C<guts()> in list context would
  1624. have returned exactly one value, and if it would have been an object (as
  1625. opposed to a text string), then that's what C<guts> in scalar context
  1626. will return.  Otherwise, if C<guts()> in list context would have returned
  1627. no values at all, then C<guts()> in scalar context returns undef.  In
  1628. all other cases, C<guts()> in scalar context returns an implicit 'div'
  1629. element node, with children consisting of whatever nodes C<guts()>
  1630. in list context would have returned.  Note that that may detach those
  1631. nodes from C<$root>'s tree.
  1632.  
  1633. =item @nodes = $root->disembowel()
  1634.  
  1635. =item $parent_for_nodes = $root->disembowel()
  1636.  
  1637. The C<disembowel()> method works just like the C<guts()> method, except
  1638. that disembowel definitively destroys the tree above the nodes that
  1639. are returned.  Usually when you want the guts from a tree, you're just
  1640. going to toss out the rest of the tree anyway, so this saves you the
  1641. bother.  (Remember, "disembowel" means "remove the guts from".)
  1642.  
  1643. =item $root->implicit_tags(value)
  1644.  
  1645. Setting this attribute to true will instruct the parser to try to
  1646. deduce implicit elements and implicit end tags.  If it is false you
  1647. get a parse tree that just reflects the text as it stands, which is
  1648. unlikely to be useful for anything but quick and dirty parsing.
  1649. (In fact, I'd be curious to hear from anyone who finds it useful to
  1650. have implicit_tags set to false.)
  1651. Default is true.
  1652.  
  1653. Implicit elements have the implicit() attribute set.
  1654.  
  1655. =item $root->implicit_body_p_tag(value)
  1656.  
  1657. This controls an aspect of implicit element behavior, if implicit_tags
  1658. is on:  If a text element (PCDATA) or a phrasal element (such as
  1659. "E<lt>emE<gt>") is to be inserted under "E<lt>bodyE<gt>", two things
  1660. can happen: if implicit_body_p_tag is true, it's placed under a new,
  1661. implicit "E<lt>pE<gt>" tag.  (Past DTDs suggested this was the only
  1662. correct behavior, and this is how past versions of this module
  1663. behaved.)  But if implicit_body_p_tag is false, nothing is implicated
  1664. -- the PCDATA or phrasal element is simply placed under
  1665. "E<lt>bodyE<gt>".  Default is false.
  1666.  
  1667. =item $root->ignore_unknown(value)
  1668.  
  1669. This attribute controls whether unknown tags should be represented as
  1670. elements in the parse tree, or whether they should be ignored.
  1671. Default is true (to ignore unknown tags.)
  1672.  
  1673. =item $root->ignore_text(value)
  1674.  
  1675. Do not represent the text content of elements.  This saves space if
  1676. all you want is to examine the structure of the document.  Default is
  1677. false.
  1678.  
  1679. =item $root->ignore_ignorable_whitespace(value)
  1680.  
  1681. If set to true, TreeBuilder will try to avoid
  1682. creating ignorable whitespace text nodes in the tree.  Default is
  1683. true.  (In fact, I'd be interested in hearing if there's ever a case
  1684. where you need this off, or where leaving it on leads to incorrect
  1685. behavior.)
  1686.  
  1687. =item $root->no_space_compacting(value)
  1688.  
  1689. This determines whether TreeBuilder compacts all whitespace strings
  1690. in the document (well, outside of PRE or TEXTAREA elements), or
  1691. leaves them alone.  Normally (default, value of 0), each string of
  1692. contiguous whitespace in the document is turned into a single space.
  1693. But that's not done if no_space_compacting is set to 1.
  1694.  
  1695. Setting no_space_compacting to 1 might be useful if you want
  1696. to read in a tree just to make some minor changes to it before
  1697. writing it back out.
  1698.  
  1699. This method is experimental.  If you use it, be sure to report
  1700. any problems you might have with it.
  1701.  
  1702. =item $root->p_strict(value)
  1703.  
  1704. If set to true (and it defaults to false), TreeBuilder will take a
  1705. narrower than normal view of what can be under a "p" element; if it sees
  1706. a non-phrasal element about to be inserted under a "p", it will close that
  1707. "p".  Otherwise it will close p elements only for other "p"'s, headings,
  1708. and "form" (altho the latter may be removed in future versions).
  1709.  
  1710. For example, when going thru this snippet of code,
  1711.  
  1712.   <p>stuff
  1713.   <ul>
  1714.  
  1715. TreeBuilder will normally (with C<p_strict> false) put the "ul" element
  1716. under the "p" element.  However, with C<p_strict> set to true, it will
  1717. close the "p" first.
  1718.  
  1719. In theory, there should be strictness options like this for other/all
  1720. elements besides just "p"; but I treat this as a specal case simply
  1721. because of the fact that "p" occurs so frequently and its end-tag is
  1722. omitted so often; and also because application of strictness rules
  1723. at parse-time across all elements often makes tiny errors in HTML
  1724. coding produce drastically bad parse-trees, in my experience.
  1725.  
  1726. If you find that you wish you had an option like this to enforce
  1727. content-models on all elements, then I suggest that what you want is
  1728. content-model checking as a stage after TreeBuilder has finished
  1729. parsing.
  1730.  
  1731. =item $root->store_comments(value)
  1732.  
  1733. This determines whether TreeBuilder will normally store comments found
  1734. while parsing content into C<$root>.  Currently, this is off by default.
  1735.  
  1736. =item $root->store_declarations(value)
  1737.  
  1738. This determines whether TreeBuilder will normally store markup
  1739. declarations found while parsing content into C<$root>.  Currently,
  1740. this is off by default.
  1741.  
  1742. It is somewhat of a known bug (to be fixed one of these days, if
  1743. anyone needs it?) that declarations in the preamble (before the "html"
  1744. start-tag) end up actually I<under> the "html" element.
  1745.  
  1746. =item $root->store_pis(value)
  1747.  
  1748. This determines whether TreeBuilder will normally store processing
  1749. instructions found while parsing content into C<$root> -- assuming a
  1750. recent version of HTML::Parser (old versions won't parse PIs
  1751. correctly).  Currently, this is off (false) by default.
  1752.  
  1753. It is somewhat of a known bug (to be fixed one of these days, if
  1754. anyone needs it?) that PIs in the preamble (before the "html"
  1755. start-tag) end up actually I<under> the "html" element.
  1756.  
  1757. =item $root->warn(value)
  1758.  
  1759. This determines whether syntax errors during parsing should generate
  1760. warnings, emitted via Perl's C<warn> function.
  1761.  
  1762. This is off (false) by default.
  1763.  
  1764. =back
  1765.  
  1766. =head1 HTML AND ITS DISCONTENTS
  1767.  
  1768. HTML is rather harder to parse than people who write it generally
  1769. suspect.
  1770.  
  1771. Here's the problem: HTML is a kind of SGML that permits "minimization"
  1772. and "implication".  In short, this means that you don't have to close
  1773. every tag you open (because the opening of a subsequent tag may
  1774. implicitly close it), and if you use a tag that can't occur in the
  1775. context you seem to using it in, under certain conditions the parser
  1776. will be able to realize you mean to leave the current context and
  1777. enter the new one, that being the only one that your code could
  1778. correctly be interpreted in.
  1779.  
  1780. Now, this would all work flawlessly and unproblematically if: 1) all
  1781. the rules that both prescribe and describe HTML were (and had been)
  1782. clearly set out, and 2) everyone was aware of these rules and wrote
  1783. their code in compliance to them.
  1784.  
  1785. However, it didn't happen that way, and so most HTML pages are
  1786. difficult if not impossible to correctly parse with nearly any set of
  1787. straightforward SGML rules.  That's why the internals of
  1788. HTML::TreeBuilder consist of lots and lots of special cases -- instead
  1789. of being just a generic SGML parser with HTML DTD rules plugged in.
  1790.  
  1791. =head1 TRANSLATIONS?
  1792.  
  1793. The techniques that HTML::TreeBuilder uses to perform what I consider
  1794. very robust parses on everyday code are not things that can work only
  1795. in Perl.  To date, the algorithms at the center of HTML::TreeBuilder
  1796. have been implemented only in Perl, as far as I know; and I don't
  1797. foresee getting around to implementing them in any other language any
  1798. time soon.
  1799.  
  1800. If, however, anyone is looking for a semester project for an applied
  1801. programming class (or if they merely enjoy I<extra-curricular>
  1802. masochism), they might do well to see about choosing as a topic the
  1803. implementation/adaptation of these routines to any other interesting
  1804. programming language that you feel currently suffers from a lack of
  1805. robust HTML-parsing.  I welcome correspondence on this subject, and
  1806. point out that one can learn a great deal about languages by trying to
  1807. translate between them, and then comparing the result.
  1808.  
  1809. The HTML::TreeBuilder source may seem long and complex, but it is
  1810. rather well commented, and symbol names are generally
  1811. self-explanatory.  (You are encouraged to read the Mozilla HTML parser
  1812. source for comparison.)  Some of the complexity comes from little-used
  1813. features, and some of it comes from having the HTML tokenizer
  1814. (HTML::Parser) being a separate module, requiring somewhat of a
  1815. different interface than you'd find in a combined tokenizer and
  1816. tree-builder.  But most of the length of the source comes from the fact
  1817. that it's essentially a long list of special cases, with lots and lots
  1818. of sanity-checking, and sanity-recovery -- because, as Roseanne
  1819. Rosannadanna once said, "it's always I<something>".
  1820.  
  1821. Users looking to compare several HTML parsers should look at the
  1822. source for Raggett's Tidy
  1823. (C<E<lt>http://www.w3.org/People/Raggett/tidy/E<gt>>),
  1824. Mozilla
  1825. (C<E<lt>http://www.mozilla.org/E<gt>>),
  1826. and possibly root around the browsers section of Yahoo
  1827. to find the various open-source ones
  1828. (C<E<lt>http://dir.yahoo.com/Computers_and_Internet/Software/Internet/World_Wide_Web/Browsers/E<gt>>).
  1829.  
  1830. =head1 BUGS
  1831.  
  1832. * Framesets seem to work correctly now.  Email me if you get a strange
  1833. parse from a document with framesets.
  1834.  
  1835. * Really bad HTML code will, often as not, make for a somewhat
  1836. objectionable parse tree.  Regrettable, but unavoidably true.
  1837.  
  1838. * If you're running with implicit_tags off (God help you!), consider
  1839. that $tree->content_list probably contains the tree or grove from the
  1840. parse, and not $tree itself (which will, oddly enough, be an implicit
  1841. 'html' element).  This seems counter-intuitive and problematic; but
  1842. seeing as how almost no HTML ever parses correctly with implicit_tags
  1843. off, this interface oddity seems the least of your problems.
  1844.  
  1845. =head1 BUG REPORTS
  1846.  
  1847. When a document parses in a way different from how you think it
  1848. should, I ask that you report this to me as a bug.  The first thing
  1849. you should do is copy the document, trim out as much of it as you can
  1850. while still producing the bug in question, and I<then> email me that
  1851. mini-document I<and> the code you're using to parse it, at C<sburke@cpan.org>.
  1852. Include a note as to how it
  1853. parses (presumably including its $tree->dump output), and then a
  1854. I<careful and clear> explanation of where you think the parser is
  1855. going astray, and how you would prefer that it work instead.
  1856.  
  1857. =head1 SEE ALSO
  1858.  
  1859. L<HTML::Tree>; L<HTML::Parser>, L<HTML::Element>, L<HTML::Tagset>
  1860.  
  1861. L<HTML::DOMbo>
  1862.  
  1863. =head1 COPYRIGHT
  1864.  
  1865. Copyright 1995-1998 Gisle Aas; copyright 1999-2002 Sean M. Burke.
  1866. This library is free software; you can redistribute it and/or
  1867. modify it under the same terms as Perl itself.
  1868.  
  1869. This program is distributed in the hope that it will be useful, but
  1870. without any warranty; without even the implied warranty of
  1871. merchantability or fitness for a particular purpose.
  1872.  
  1873. =head1 AUTHOR
  1874.  
  1875. Original author Gisle Aas E<lt>gisle@aas.noE<gt>; current maintainer
  1876. Sean M. Burke, E<lt>sburke@cpan.orgE<gt>
  1877.  
  1878. =cut
  1879.  
  1880.  
  1881. CUCUMBER AND ORANGE SALAD
  1882.  
  1883. Adapted from:
  1884.  
  1885. Holzner, Yupa.  /Great Thai Cooking for My American Friends: Creative
  1886. Thai Dishes Made Easy/.  Royal House 1989.  ISBN:0930440277
  1887.  
  1888. Makes about four servings.
  1889.  
  1890.  1 small greenhouse cucumber, sliced thin.
  1891.  2 navel oranges, peeled, separated into segments (seeded if
  1892.    necessary), and probably chopped into chunks.
  1893.  
  1894. Dressing:
  1895.  3 tablespoons rice vinegar
  1896.  .5 teaspoon salt
  1897.  1 tablespoon sugar
  1898.  1 teaspoon roasted sesame seeds
  1899.  .5 tablespoons mirin
  1900.  
  1901. Mix all ingredients in the dressing.  Pour the dressing over the
  1902. oranges and cucumbers, and toss.  Serve.
  1903.  
  1904.  
  1905. All ingredient quantities are approximate.  Adjust to taste.  Multipy
  1906. quantities for more servings.
  1907.  
  1908. Note: the sesame seeds you get in an American supermarket are almost
  1909. certain to be unroasted, suspiciously waxy-looking, and astronomically
  1910. overpriced.  Good cheap sesame seeds are available at most Asian
  1911. markets -- they usually come roasted; if they're unroasted, roast them
  1912. in a skillet for a few short minutes as needed.
  1913.  
  1914. [End Recipe]
  1915.