home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2006 December / PCpro_2006_12.ISO / ossdvd / server / Perl2 / site / lib / html / TreeBuilder.pm < prev   
Encoding:
Text File  |  2001-03-20  |  66.7 KB  |  1,784 lines

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