Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3821 lines
116 KiB

  1. require 5;
  2. # Time-stamp: "2001-03-10 22:42:16 MST"
  3. package HTML::Element;
  4. # TODO: add pre-content-fixer, like from Pod::HTML2Pod?
  5. # TODO: make extract_links do the right thing with forms with no action param ?
  6. # TODO: add 'are_element_identical' method ?
  7. # TODO: add 'are_content_identical' method ?
  8. # TODO: maybe alias ->destroy to ->delete, because I keep mixing them up ?
  9. # TODO: maybe reorganize the docs some time?
  10. # TODO: $node->rebless( what_class )
  11. # and/or $node->rebless_down( what_class ) # recurses
  12. =head1 NAME
  13. HTML::Element - Class for objects that represent HTML elements
  14. =head1 SYNOPSIS
  15. use HTML::Element;
  16. $a = HTML::Element->new('a', href => 'http://www.perl.com/');
  17. $a->push_content("The Perl Homepage");
  18. $tag = $a->tag;
  19. print "$tag starts out as:", $a->starttag, "\n";
  20. print "$tag ends as:", $a->endtag, "\n";
  21. print "$tag\'s href attribute is: ", $a->attr('href'), "\n";
  22. $links_r = $a->extract_links();
  23. print "Hey, I found ", scalar(@$links_r), " links.\n";
  24. print "And that, as HTML, is: ", $a->as_HTML, "\n";
  25. $a = $a->delete;
  26. =head1 DESCRIPTION
  27. (This class is part of the L<HTML::Tree|HTML::Tree> dist.)
  28. Objects of the HTML::Element class can be used to represent elements
  29. of HTML document trees. These objects have attributes, notably attributes that
  30. designates each element's parent and content. The content is an array
  31. of text segments and other HTML::Element objects. A tree with HTML::Element
  32. objects as nodes can represent the syntax tree for a HTML document.
  33. =head1 HOW WE REPRESENT TREES
  34. It may occur to you to wonder what exactly a "tree" is, and how
  35. it's represented in memory. Consider this HTML document:
  36. <html lang='en-US'>
  37. <head>
  38. <title>Stuff</title>
  39. <meta name='author' content='Jojo'>
  40. </head>
  41. <body>
  42. <h1>I like potatoes!</h1>
  43. </body>
  44. </html>
  45. Building a syntax tree out of it makes a tree-structure in memory
  46. that could be diagrammed as:
  47. html (lang='en-US')
  48. / \
  49. / \
  50. / \
  51. head body
  52. /\ \
  53. / \ \
  54. / \ \
  55. title meta h1
  56. | (name='author', |
  57. "Stuff" content='Jojo') "I like potatoes"
  58. This is the traditional way to diagram a tree, with the "root" at the
  59. top, and it's this kind of diagram that people have in mind when they
  60. say, for example, that "the meta element is under the head element
  61. instead of under the body element". (The same is also said with
  62. "inside" instead of "under" -- the use of "inside" makes more sense
  63. when you're looking at the HTML source.)
  64. Another way to represent the above tree is with indenting:
  65. html (attributes: lang='en-US')
  66. head
  67. title
  68. "Stuff"
  69. meta (attributes: name='author' content='Jojo')
  70. body
  71. h1
  72. "I like potatoes"
  73. Incidentally, diagramming with indenting works much better for very
  74. large trees, and is easier for a program to generate. The $tree->dump
  75. method uses indentation just that way.
  76. However you diagram the tree, it's stored the same in memory -- it's a
  77. network of objects, each of which has attributes like so:
  78. element #1: _tag: 'html'
  79. _parent: none
  80. _content: [element #2, element #5]
  81. lang: 'en-US'
  82. element #2: _tag: 'head'
  83. _parent: element #1
  84. _content: [element #3, element #4]
  85. element #3: _tag: 'title'
  86. _parent: element #2
  87. _content: [text segment "Stuff"]
  88. element #4 _tag: 'meta'
  89. _parent: element #2
  90. _content: none
  91. name: author
  92. content: Jojo
  93. element #5 _tag: 'body'
  94. _parent: element #1
  95. _content: [element #6]
  96. element #6 _tag: 'h1'
  97. _parent: element #5
  98. _content: [text segment "I like potatoes"]
  99. The "treeness" of the tree-structure that these elements comprise is
  100. not an aspect of any particular object, but is emergent from the
  101. relatedness attributes (_parent and _content) of these element-objects
  102. and from how you use them to get from element to element.
  103. While you could access the content of a tree by writing code that says
  104. "access the 'src' attribute of the root's I<first> child's I<seventh>
  105. child's I<third> child", you're more likely to have to scan the contents
  106. of a tree, looking for whatever nodes, or kinds of nodes, you want to
  107. do something with. The most straightforward way to look over a tree
  108. is to "traverse" it; an HTML::Element method ($h->traverse) is
  109. provided for this purpose; and several other HTML::Element methods are
  110. based on it.
  111. (For everything you ever wanted to know about trees, and then some,
  112. see Niklaus Wirth's I<Algorithms + Data Structures = Programs> or
  113. Donald Knuth's I<The Art of Computer Programming, Volume 1>.)
  114. =cut
  115. use strict;
  116. use Carp ();
  117. use HTML::Entities ();
  118. use HTML::Tagset ();
  119. use integer; # vroom vroom!
  120. use vars qw($VERSION $html_uc $Debug $ID_COUNTER %list_type_to_sub);
  121. $VERSION = '3.09';
  122. $Debug = 0 unless defined $Debug;
  123. sub Version { $VERSION; }
  124. my $nillio = [];
  125. *HTML::Element::emptyElement = \%HTML::Tagset::emptyElement; # legacy
  126. *HTML::Element::optionalEndTag = \%HTML::Tagset::optionalEndTag; # legacy
  127. *HTML::Element::linkElements = \%HTML::Tagset::linkElements; # legacy
  128. *HTML::Element::boolean_attr = \%HTML::Tagset::boolean_attr; # legacy
  129. *HTML::Element::canTighten = \%HTML::Tagset::canTighten; # legacy
  130. # Constants for signalling back to the traverser:
  131. my $travsignal_package = __PACKAGE__ . '::_travsignal';
  132. my(
  133. $ABORT, $PRUNE, $PRUNE_SOFTLY, $OK, $PRUNE_UP
  134. ) =
  135. map
  136. {my $x = $_ ; bless \$x, $travsignal_package;}
  137. qw(
  138. ABORT PRUNE PRUNE_SOFTLY OK PRUNE_UP
  139. )
  140. ;
  141. sub ABORT () {$ABORT}
  142. sub PRUNE () {$PRUNE}
  143. sub PRUNE_SOFTLY () {$PRUNE_SOFTLY}
  144. sub OK () {$OK}
  145. sub PRUNE_UP () {$PRUNE_UP}
  146. $html_uc = 0;
  147. # set to 1 if you want tag and attribute names from starttag and endtag
  148. # to be uc'd
  149. # Elements that does not have corresponding end tags (i.e. are empty)
  150. #==========================================================================
  151. =head1 BASIC METHODS
  152. =over 4
  153. =item $h = HTML::Element->new('tag', 'attrname' => 'value', ... )
  154. This constructor method returns a new HTML::Element object. The tag
  155. name is a required argument; it will be forced to lowercase.
  156. Optionally, you can specify other initial attributes at object
  157. creation time.
  158. =cut
  159. #
  160. # An HTML::Element is represented by blessed hash reference, much like
  161. # Tree::DAG_Node objects. Key-names not starting with '_' are reserved
  162. # for the SGML attributes of the element.
  163. # The following special keys are used:
  164. #
  165. # '_tag': The tag name (i.e., the generic identifier)
  166. # '_parent': A reference to the HTML::Element above (when forming a tree)
  167. # '_pos': The current position (a reference to a HTML::Element) is
  168. # where inserts will be placed (look at the insert_element
  169. # method) If not set, the implicit value is the object itself.
  170. # '_content': A ref to an array of nodes under this.
  171. # It might not be set.
  172. #
  173. # Example: <img src="gisle.jpg" alt="Gisle's photo"> is represented like this:
  174. #
  175. # bless {
  176. # _tag => 'img',
  177. # src => 'gisle.jpg',
  178. # alt => "Gisle's photo",
  179. # }, 'HTML::Element';
  180. #
  181. sub new
  182. {
  183. my $class = shift;
  184. $class = ref($class) || $class;
  185. my $tag = shift;
  186. Carp::croak("No tagname") unless defined $tag and length $tag;
  187. my $self = bless { _tag => scalar($class->_fold_case($tag)) }, $class;
  188. my($attr, $val);
  189. while (($attr, $val) = splice(@_, 0, 2)) {
  190. $val = $attr unless defined $val;
  191. $self->{$class->_fold_case($attr)} = $val;
  192. }
  193. if ($tag eq 'html') {
  194. $self->{'_pos'} = undef;
  195. }
  196. $self;
  197. }
  198. =item $h->attr('attr') or $h->attr('attr', 'value')
  199. Returns (optionally sets) the value of the given attribute of $h. The
  200. attribute name (but not the value, if provided) is forced to
  201. lowercase. If trying to read the value of an attribute not present
  202. for this element, the return value is undef.
  203. If setting a new value, the old value of that attribute is
  204. returned.
  205. If methods are provided for accessing an attribute (like $h->tag for
  206. "_tag", $h->content_list, etc. below), use those instead of calling
  207. attr $h->attr, whether for reading or setting.
  208. Note that setting an attribute to undef (as opposed to "", the empty
  209. string) actually deletes the attribute.
  210. =cut
  211. sub attr
  212. {
  213. my $self = shift;
  214. my $attr = scalar($self->_fold_case(shift));
  215. if (@_) { # set
  216. if(defined $_[0]) {
  217. my $old = $self->{$attr};
  218. $self->{$attr} = $_[0];
  219. return $old;
  220. } else { # delete, actually
  221. return delete $self->{$attr};
  222. }
  223. } else { # get
  224. return $self->{$attr};
  225. }
  226. }
  227. =item $h->tag() or $h->tag('tagname')
  228. Returns (optionally sets) the tag name (also known as the generic
  229. identifier) for the element $h. In setting, the tag name is always
  230. converted to lower case.
  231. There are four kinds of "pseudo-elements" that show up as
  232. HTML::Element objects:
  233. =over
  234. =item Comment pseudo-elements
  235. These are element objects with a C<$h-E<gt>tag> value of "~comment",
  236. and the content of the comment is stored in the "text" attribute
  237. (C<$h-E<gt>attr("text")>). For example, parsing this code with
  238. HTML::TreeBuilder...
  239. <!-- I like Pie.
  240. Pie is good
  241. -->
  242. produces an HTML::Element object with these attributes:
  243. "_tag",
  244. "~comment",
  245. "text",
  246. " I like Pie.\n Pie is good\n "
  247. =item Declaration pseudo-elements
  248. Declarations (rarely encountered) are represented as HTML::Element
  249. objects with a tag name of "~declaration", and content in the "text"
  250. attribute. For example, this:
  251. <!DOCTYPE foo>
  252. produces an element whose attributes include:
  253. "_tag", "~declaration", "text", "DOCTYPE foo"
  254. =item Processing instruction pseudo-elements
  255. PIs (rarely encountered) are represented as HTML::Element objects with
  256. a tag name of "~pi", and content in the "text" attribute. For
  257. example, this:
  258. <?stuff foo?>
  259. produces an element whose attributes include:
  260. "_tag", "~pi", "text", "stuff foo?"
  261. (assuming a recent version of HTML::Parser)
  262. =item ~literal pseudo-elements
  263. These objects are not currently produced by HTML::TreeBuilder, but can
  264. be used to represent a "super-literal" -- i.e., a literal you want to
  265. be immune from escaping. (Yes, I just made that term up.)
  266. That is, this is useful if you want to insert code into a tree that
  267. you plan to dump out with C<as_HTML>, where you want, for some reason,
  268. to suppress C<as_HTML>'s normal behavior of amp-quoting text segments.
  269. For expample, this:
  270. my $literal = HTML::Element->new('~literal',
  271. 'text' => 'x < 4 & y > 7'
  272. );
  273. my $span = HTML::Element->new('span');
  274. $span->push_content($literal);
  275. print $span->as_HTML;
  276. prints this:
  277. <span>x < 4 & y > 7</span>
  278. Whereas this:
  279. my $span = HTML::Element->new('span');
  280. $span->push_content('x < 4 & y > 7');
  281. # normal text segment
  282. print $span->as_HTML;
  283. prints this:
  284. <span>x &lt; 4 &amp; y &gt; 7</span>
  285. Unless you're inserting lots of pre-cooked code into existing trees,
  286. and dumping them out again, it's not likely that you'll find
  287. C<~literal> pseudo-elements useful.
  288. =back
  289. =cut
  290. sub tag
  291. {
  292. my $self = shift;
  293. if (@_) { # set
  294. #print "SET\n";
  295. $self->{'_tag'} = $self->_fold_case($_[0]);
  296. } else { # get
  297. #print "GET\n";
  298. $self->{'_tag'};
  299. }
  300. }
  301. =item $h->parent() or $h->parent($new_parent)
  302. Returns (optionally sets) the parent for this element.
  303. The parent should either be undef, or should be another element.
  304. You B<should not> use this to directly set the parent of an element.
  305. Instead use any of the other methods under "Structure-Modifying
  306. Methods", below.
  307. Note that not($h->parent) is a simple test for whether $h is the
  308. root of its subtree.
  309. =cut
  310. sub parent
  311. {
  312. my $self = shift;
  313. if (@_) { # set
  314. Carp::croak "an element can't be made its own parent"
  315. if defined $_[0] and ref $_[0] and $self eq $_[0]; # sanity
  316. $self->{'_parent'} = $_[0];
  317. } else {
  318. $self->{'_parent'}; # get
  319. }
  320. }
  321. =item $h->content_list()
  322. Returns a list representing the content of this element -- i.e., what
  323. nodes (elements or text segments) are inside/under this element. (Note
  324. that this may be an empty list.)
  325. In a scalar context, this returns the count of the items,
  326. as you may expect.
  327. =cut
  328. sub content_list
  329. {
  330. return
  331. wantarray ? @{shift->{'_content'} || return()}
  332. : scalar @{shift->{'_content'} || return 0};
  333. }
  334. =item $h->content()
  335. This somewhat deprecated method returns the content of this element;
  336. but unlike content_list, this returns either undef (which you should
  337. understand to mean no content), or a I<reference to the array> of
  338. content items, each of which is either a text segment (a string, i.e.,
  339. a defined non-reference scalar value), or an HTML::Element object.
  340. Note that even if an arrayref is returned, it may be a reference to an
  341. empty array.
  342. While older code should feel free to continue to use $h->content,
  343. new code should use $h->content_list in almost all conceivable
  344. cases. It is my experience that in most cases this leads to simpler
  345. code anyway, since it means one can say:
  346. @children = $h->content_list;
  347. instead of the inelegant:
  348. @children = @{$h->content || []};
  349. If you do use $h->content (or $h->content_array_ref), you should not
  350. use the reference returned by it (assuming it returned a reference,
  351. and not undef) to directly set or change the content of an element or
  352. text segment! Instead use C<content_refs_list> or any of the other
  353. methods under "Structure-Modifying Methods", below.
  354. =cut
  355. # a read-only method! can't say $h->content( [] )!
  356. sub content
  357. {
  358. shift->{'_content'};
  359. }
  360. =item $h->content_array_ref()
  361. This is like C<content> (with all its caveats and deprecations) except
  362. that it is guaranteed to return an array reference. That is, if the
  363. given node has no C<_content> attribute, the C<content> method would
  364. return that undef, but C<content_array_ref> would set the given node's
  365. C<_content> value to C<[]> (a reference to a new, empty array), and
  366. return that.
  367. =cut
  368. sub content_array_ref {
  369. shift->{'_content'} ||= [];
  370. }
  371. =item $h->content_refs_list
  372. This returns a list of scalar references to each element of $h's
  373. content list. This is useful in case you want to in-place edit any
  374. large text segments without having to get a copy of the current value
  375. of that segment value, modify that copy, then use the
  376. C<splice_content> to replace the old with the new. Instead, here you
  377. can in-place edit:
  378. foreach my $item_r ($h->content_refs_list) {
  379. next if ref $$item_r;
  380. $$item_r =~ s/honour/honor/g;
  381. }
  382. You I<could> currently achieve the same affect with:
  383. foreach my $item (@{ $h->content_array_ref }) {
  384. # deprecated!
  385. next if ref $item;
  386. $item =~ s/honour/honor/g;
  387. }
  388. ...except that using the return value of $h->content or
  389. $h->content_array_ref to do that is deprecated, and just might stop
  390. working in the future.
  391. =cut
  392. sub content_refs_list {
  393. \( @{ shift->{'_content'} || return() } );
  394. }
  395. =item $h->implicit() or $h->implicit($bool)
  396. Returns (optionally sets) the "_implicit" attribute. This attribute is
  397. a flag that's used for indicating that the element was not originally
  398. present in the source, but was added to the parse tree (by
  399. HTML::TreeBuilder, for example) in order to conform to the rules of
  400. HTML structure.
  401. =cut
  402. sub implicit
  403. {
  404. shift->attr('_implicit', @_);
  405. }
  406. =item $h->pos() or $h->pos($element)
  407. Returns (and optionally sets) the "_pos" (for "current I<pos>ition")
  408. pointer of $h.
  409. This attribute is a pointer used during some parsing operations,
  410. whose value is whatever HTML::Element element at or under $h is
  411. currently "open", where $h->insert_element(NEW) will actually insert a
  412. new element.
  413. (This has nothing to do with the Perl function called "pos", for
  414. controlling where regular expression matching starts.)
  415. If you set $h->pos($element), be sure that $element is either $h, or
  416. an element under $h.
  417. If you've been modifying the tree under $h and are
  418. no longer sure $h->pos is valid, you can enforce validity with:
  419. $h->pos(undef) unless $h->pos->is_inside($h);
  420. =cut
  421. sub pos
  422. {
  423. my $self = shift;
  424. my $pos = $self->{'_pos'};
  425. if (@_) { # set
  426. if(defined $_[0] and $_[0] ne $self) {
  427. $self->{'_pos'} = $_[0]; # means that element
  428. } else {
  429. $self->{'_pos'} = undef; # means $self
  430. }
  431. }
  432. return $pos if defined($pos);
  433. $self;
  434. }
  435. =item $h->all_attr()
  436. Returns all this element's attributes and values, as key-value pairs.
  437. This will include any "internal" attributes (i.e., ones not present
  438. in the original element, and which will not be represented if/when you
  439. call $h->as_HTML). Internal attributes are distinguished by the fact
  440. that the first character of their key (not value! key!) is an
  441. underscore ("_").
  442. Example output of C<$h-E<gt>all_attr()> :
  443. C<'_parent', >I<[object_value]>C< , '_tag', 'em', 'lang', 'en-US',
  444. '_content', >I<[array-ref value]>.
  445. =item $h->all_attr_names()
  446. Like all_attr, but only returns the names of the attributes.
  447. Example output of C<$h-E<gt>all_attr()> :
  448. C<'_parent', '_tag', 'lang', '_content', >.
  449. =cut
  450. sub all_attr {
  451. return %{$_[0]};
  452. # Yes, trivial. But no other way for the user to do the same
  453. # without breaking encapsulation.
  454. # And if our object representation changes, this method's behavior
  455. # should stay the same.
  456. }
  457. sub all_attr_names {
  458. return keys %{$_[0]};
  459. }
  460. =item $h->all_external_attr()
  461. Like C<all_attr>, except that internal attributes are not present.
  462. =item $h->all_external_attr_names()
  463. Like C<all_external_attr_names>, except that internal attributes' names
  464. are not present.
  465. =cut
  466. sub all_external_attr {
  467. my $self = $_[0];
  468. return
  469. map(
  470. (length($_) && substr($_,0,1) eq '_') ? () : ($_, $self->{$_}),
  471. keys %$self
  472. );
  473. }
  474. sub all_external_attr_names {
  475. return
  476. grep
  477. !(length($_) && substr($_,0,1) eq '_'),
  478. keys %{$_[0]}
  479. ;
  480. }
  481. =item $h->id() or $h->id($string)
  482. Returns (optionally sets to C<$string>) the "id" attribute.
  483. C<$h-E<gt>id(undef)> deletes the "id" attribute.
  484. =cut
  485. sub id {
  486. if(@_ == 1) {
  487. return $_[0]{'id'};
  488. } elsif(@_ == 2) {
  489. if(defined $_[1]) {
  490. return $_[0]{'id'} = $_[1];
  491. } else {
  492. return delete $_[0]{'id'};
  493. }
  494. } else {
  495. Carp::croak '$node->id can\'t take ' . scalar(@_) . ' parameters!';
  496. }
  497. }
  498. =item $h->idf() or $h->idf($string)
  499. Just like the C<id> method, except that if you call C<$h->idf()> and
  500. no "id" attribute is defined for this element, then it's set to a
  501. likely-to-be-unique value, and returned. (The "f" is for "force".)
  502. =cut
  503. sub _gensym {
  504. unless(defined $ID_COUNTER) {
  505. # start it out...
  506. $ID_COUNTER = sprintf('%04x', rand(0x1000));
  507. $ID_COUNTER =~ tr<0-9a-f><J-NP-Z>; # yes, skip letter "oh"
  508. $ID_COUNTER .= '00000';
  509. }
  510. ++$ID_COUNTER;
  511. }
  512. sub idf {
  513. if(@_ == 1) {
  514. my $x;
  515. if(defined($x = $_[0]{'id'}) and length $x) {
  516. return $x;
  517. } else {
  518. return $_[0]{'id'} = _gensym();
  519. }
  520. } elsif(@_ == 2) {
  521. if(defined $_[1]) {
  522. return $_[0]{'id'} = $_[1];
  523. } else {
  524. return delete $_[0]{'id'};
  525. }
  526. } else {
  527. Carp::croak '$node->idf can\'t take ' . scalar(@_) . ' parameters!';
  528. }
  529. }
  530. #==========================================================================
  531. =back
  532. =head1 STRUCTURE-MODIFYING METHODS
  533. These methods are provided for modifying the content of trees
  534. by adding or changing nodes as parents or children of other nodes.
  535. =over 4
  536. =item $h->push_content($element_or_text, ...)
  537. Adds the specified items to the I<end> of the content list of the
  538. element $h. The items of content to be added should each be either a
  539. text segment (a string), an HTML::Element object, or an arrayref.
  540. Arrayrefs are fed thru C<$h-E<gt>new_from_lol(that_arrayref)> to
  541. convert them into elements, before being added to the content
  542. list of $h. This means you can say things concise things like:
  543. $body->push_content(
  544. ['br'],
  545. ['ul',
  546. map ['li', $_]
  547. qw(Peaches Apples Pears Mangos)
  548. ]
  549. );
  550. See C<new_from_lol> method's documentation, far below, for more
  551. explanation.
  552. The push_content method will try to consolidate adjacent text segments
  553. while adding to the content list. That's to say, if $h's content_list is
  554. ('foo bar ', $some_node, 'baz!')
  555. and you call
  556. $h->push_content('quack?');
  557. then the resulting content list will be this:
  558. ('foo bar ', $some_node, 'baz!quack?')
  559. and not this:
  560. ('foo bar ', $some_node, 'baz!', 'quack?')
  561. If that latter is what you want, you'll have to override the
  562. feature of consolidating text by using splice_content,
  563. as in:
  564. $h->splice_content(scalar($h->content_list),0,'quack?');
  565. Similarly, if you wanted to add 'Skronk' to the beginning of
  566. the content list, calling this:
  567. $h->unshift_content('Skronk');
  568. then the resulting content list will be this:
  569. ('Skronkfoo bar ', $some_node, 'baz!')
  570. and not this:
  571. ('Skronk', 'foo bar ', $some_node, 'baz!')
  572. What you'd to do get the latter is:
  573. $h->splice_content(0,0,'Skronk');
  574. =cut
  575. sub push_content
  576. {
  577. my $self = shift;
  578. return $self unless @_;
  579. my $content = ($self->{'_content'} ||= []);
  580. for (@_) {
  581. if (ref($_) eq 'ARRAY') {
  582. # magically call new_from_lol
  583. push @$content, $self->new_from_lol($_);
  584. $content->[-1]->{'_parent'} = $self;
  585. } elsif(ref($_)) { # insert an element
  586. $_->detach if $_->{'_parent'};
  587. $_->{'_parent'} = $self;
  588. push(@$content, $_);
  589. } else { # insert text segment
  590. if (@$content && !ref $content->[-1]) {
  591. # last content element is also text segment -- append
  592. $content->[-1] .= $_;
  593. } else {
  594. push(@$content, $_);
  595. }
  596. }
  597. }
  598. $self;
  599. }
  600. =item $h->unshift_content($element_or_text, ...)
  601. Just like C<push_content>, but adds to the I<beginning> of the $h
  602. element's content list.
  603. The items of content to be added should each be
  604. either a text segment (a string), an HTML::Element object, or
  605. an arrayref (which is fed thru C<new_from_lol>).
  606. The unshift_content method will try to consolidate adjacent text segments
  607. while adding to the content list. See above for a discussion of this.
  608. =cut
  609. sub unshift_content
  610. {
  611. my $self = shift;
  612. return $self unless @_;
  613. my $content = ($self->{'_content'} ||= []);
  614. for (reverse @_) { # so they get added in the order specified
  615. if (ref($_) eq 'ARRAY') {
  616. # magically call new_from_lol
  617. unshift @$content, $self->new_from_lol($_);
  618. $content->[-1]->{'_parent'} = $self;
  619. } elsif (ref $_) { # insert an element
  620. $_->detach if $_->{'_parent'};
  621. $_->{'_parent'} = $self;
  622. unshift(@$content, $_);
  623. } else { # insert text segment
  624. if (@$content && !ref $content->[0]) {
  625. # last content element is also text segment -- prepend
  626. $content->[0] = $_ . $content->[0];
  627. } else {
  628. unshift(@$content, $_);
  629. }
  630. }
  631. }
  632. $self;
  633. }
  634. # Cf. splice ARRAY,OFFSET,LENGTH,LIST
  635. =item $h->splice_content($offset, $length, $element_or_text, ...)
  636. Detaches the elements from $h's list of content-nodes, starting at
  637. $offset and continuing for $length items, replacing them with the
  638. elements of the following list, if any. Returns the elements (if any)
  639. removed from the content-list. If $offset is negative, then it starts
  640. that far from the end of the array, just like Perl's normal C<splice>
  641. function. If $length and the following list is omitted, removes
  642. everything from $offset onward.
  643. The items of content to be added (if any) should each be either a text
  644. segment (a string), an arrayref (which is fed thru C<new_from_lol>),
  645. or an HTML::Element object that's not already
  646. a child of $h.
  647. =cut
  648. sub splice_content {
  649. my($self, $offset, $length, @to_add) = @_;
  650. Carp::croak
  651. "splice_content requires at least one argument"
  652. if @_ < 2; # at least $h->splice_content($offset);
  653. return $self unless @_;
  654. my $content = ($self->{'_content'} ||= []);
  655. # prep the list
  656. my @out;
  657. if(@_ > 2) { # self, offset, length, ...
  658. foreach my $n (@to_add) {
  659. if(ref($n) eq 'ARRAY') {
  660. $n = $self->new_from_lol($n);
  661. $n->{'_parent'} = $self;
  662. } elsif(ref($n)) {
  663. $n->detach;
  664. $n->{'_parent'} = $self;
  665. }
  666. }
  667. @out = splice @$content, $offset, $length, @to_add;
  668. } else { # self, offset
  669. @out = splice @$content, $offset;
  670. }
  671. foreach my $n (@out) {
  672. $n->{'_parent'} = undef if ref $n;
  673. }
  674. return @out;
  675. }
  676. =item $h->detach()
  677. This unlinks $h from its parent, by setting its 'parent' attribute to
  678. undef, and by removing it from the content list of its parent (if it
  679. had one). The return value is the parent that was detached from (or
  680. undef, if $h had no parent to start with). Note that neither $h nor
  681. its parent are explicitly destroyed.
  682. =cut
  683. sub detach {
  684. my $self = $_[0];
  685. return undef unless(my $parent = $self->{'_parent'});
  686. $self->{'_parent'} = undef;
  687. my $cohort = $parent->{'_content'} || return $parent;
  688. @$cohort = grep { not( ref($_) and $_ eq $self) } @$cohort;
  689. # filter $self out, if parent has any evident content
  690. return $parent;
  691. }
  692. =item $h->detach_content()
  693. This unlinks $h all of $h's children from $h, and returns them.
  694. Note that these are not explicitly destroyed; for that, you
  695. can just use $h->delete_content.
  696. =cut
  697. sub detach_content {
  698. my $c = $_[0]->{'_content'} || return(); # in case of no content
  699. for (@$c) { $_->{'_parent'} = undef if ref $_; }
  700. return splice @$c;
  701. }
  702. =item $h->replace_with( $element_or_text, ... )
  703. This replaces $h in its parent's content list with the nodes specified.
  704. The element $h (which by then may have no parent) is
  705. returned. This causes a fatal error if $h has no parent.
  706. The list of nodes to insert may contain $h, but at most once.
  707. Aside from that possible exception, the nodes to insert should not
  708. already be children of $h's parent.
  709. Also, note that this method does not destroy $h -- use
  710. $h->replace_with(...)->delete if you need that.
  711. =cut
  712. sub replace_with {
  713. my($self, @replacers) = @_;
  714. Carp::croak "the target node has no parent"
  715. unless my($parent) = $self->{'_parent'};
  716. my $parent_content = $parent->{'_content'};
  717. Carp::croak "the target node's parent has no content!?"
  718. unless $parent_content and @$parent_content;
  719. my $replacers_contains_self;
  720. for(@replacers) {
  721. if(!ref $_) {
  722. # noop
  723. } elsif($_ eq $self) {
  724. # noop, but check that it's there just once.
  725. Carp::croak
  726. "Replacement list contains several copies of target!"
  727. if $replacers_contains_self++;
  728. } elsif($_ eq $parent) {
  729. Carp::croak "Can't replace an item with its parent!";
  730. } else {
  731. $_->detach;
  732. $_->{'_parent'} = $parent;
  733. # each of these are necessary
  734. }
  735. }
  736. #my $content_r = $self->{'_content'} || [];
  737. @$parent_content
  738. = map { ( ref($_) and $_ eq $self) ? @replacers : $_ }
  739. @$parent_content
  740. ;
  741. $self->{'_parent'} = undef unless $replacers_contains_self;
  742. # if replacers does contain self, then the parent attribute is fine as-is
  743. return $self;
  744. }
  745. =item $h->preinsert($element_or_text...)
  746. Inserts the given nodes right BEFORE $h in $h's parent's content list.
  747. This causes a fatal error if $h has no parent. None of the
  748. given nodes should be $h or other children of $h. Returns $h.
  749. =cut
  750. sub preinsert {
  751. my $self = shift;
  752. return $self unless @_;
  753. return $self->replace_with(@_, $self);
  754. }
  755. =item $h->postinsert($element_or_text...)
  756. Inserts the given nodes right AFTER $h in $h's parent's content list.
  757. This causes a fatal error if $h has no parent. None of the
  758. given nodes should be $h or other children of $h. Returns $h.
  759. =cut
  760. sub postinsert {
  761. my $self = shift;
  762. return $self unless @_;
  763. return $self->replace_with($self, @_);
  764. }
  765. =item $h->replace_with_content()
  766. This replaces $h in its parent's content list with its own content.
  767. The element $h (which by then has no parent or content of its own) is
  768. returned. This causes a fatal error if $h has no parent. Also, note
  769. that this does not destroy $h -- use $h->replace_with_content->delete
  770. if you need that.
  771. =cut
  772. sub replace_with_content {
  773. my $self = $_[0];
  774. Carp::croak "the target node has no parent"
  775. unless my($parent) = $self->{'_parent'};
  776. my $parent_content = $parent->{'_content'};
  777. Carp::croak "the target node's parent has no content!?"
  778. unless $parent_content and @$parent_content;
  779. my $content_r = $self->{'_content'} || [];
  780. @$parent_content
  781. = map { ( ref($_) and $_ eq $self) ? @$content_r : $_ }
  782. @$parent_content
  783. ;
  784. $self->{'_parent'} = undef; # detach $self from its parent
  785. # Update parentage link, removing from $self's content list
  786. for (splice @$content_r) { $_->{'_parent'} = $parent if ref $_ }
  787. return $self; # note: doesn't destroy it.
  788. }
  789. =item $h->delete_content()
  790. Clears the content of $h, calling $i->delete for each content element.
  791. Compare with $h->detach_content.
  792. Returns $h.
  793. =cut
  794. sub delete_content
  795. {
  796. for (splice @{ delete($_[0]->{'_content'})
  797. # Deleting it here (while holding its value, for the moment)
  798. # will keep calls to detach() from trying to uselessly filter
  799. # the list (as they won't be able to see it once it's been
  800. # deleted)
  801. || return($_[0]) # in case of no content
  802. },
  803. 0
  804. # the splice is so we can null the array too, just in case
  805. # something somewhere holds a ref to it
  806. )
  807. {
  808. $_->delete if ref $_;
  809. }
  810. $_[0];
  811. }
  812. =item $h->delete()
  813. Detaches this element from its parent (if it has one) and explicitly
  814. destroys the element and all its descendants. The return value is
  815. undef.
  816. Perl uses garbage collection based on reference counting; when no
  817. references to a data structure exist, it's implicitly destroyed --
  818. i.e., when no value anywhere points to a given object anymore, Perl
  819. knows it can free up the memory that the now-unused object occupies.
  820. But this fails with HTML::Element trees, because a parent element
  821. always holds references to its children, and its children elements
  822. hold references to the parent, so no element ever looks like it's
  823. I<not> in use. So, to destroy those elements, you need to call
  824. $h->delete on the parent.
  825. =cut
  826. #'
  827. sub delete
  828. {
  829. my $self = $_[0];
  830. $self->delete_content # recurse down
  831. if $self->{'_content'} && @{$self->{'_content'}};
  832. $self->detach if $self->{'_parent'} and $self->{'_parent'}{'_content'};
  833. # not the typical case
  834. %$self = (); # null out the whole object on the way out
  835. return undef;
  836. }
  837. =item $h->clone()
  838. Returns a copy of the element (whose children are clones (recursively)
  839. of the original's children, if any).
  840. The returned element is parentless. Any '_pos' attributes present in the
  841. source element/tree will be absent in the copy. For that and other reasons,
  842. the clone of an HTML::TreeBuilder object that's in mid-parse (i.e, the head
  843. of a tree that HTML::TreeBuilder is elaborating) cannot (currently) be used
  844. to continue the parse.
  845. You are free to clone HTML::TreeBuilder trees, just as long as:
  846. 1) they're done being parsed, or 2) you don't expect to resume parsing
  847. into the clone. (You can continue parsing into the original; it is
  848. never affected.)
  849. =cut
  850. sub clone {
  851. #print "Cloning $_[0]\n";
  852. my $it = shift;
  853. Carp::croak "clone() can be called only as an object method" unless ref $it;
  854. Carp::croak "clone() takes no arguments" if @_;
  855. my $new = bless { %$it }, ref($it); # COPY!!! HOOBOY!
  856. delete @$new{'_content', '_parent', '_pos', '_head', '_body'};
  857. # clone any contents
  858. if($it->{'_content'} and @{$it->{'_content'}}) {
  859. $new->{'_content'} = [ ref($it)->clone_list( @{$it->{'_content'}} ) ];
  860. for(@{$new->{'_content'}}) {
  861. $_->{'_parent'} = $new if ref $_;
  862. }
  863. }
  864. return $new;
  865. }
  866. =item HTML::Element->clone_list(...nodes...)
  867. =item or: ref($h)->clone_list(...nodes...)
  868. Returns a list consisting of a copy of each node given.
  869. Text segments are simply copied; elements are cloned by
  870. calling $it->clone on each of them.
  871. =cut
  872. sub clone_list {
  873. Carp::croak "I can be called only as a class method" if ref shift @_;
  874. # all that does is get me here
  875. return
  876. map
  877. {
  878. ref($_)
  879. ? $_->clone # copy by method
  880. : $_ # copy by evaluation
  881. }
  882. @_
  883. ;
  884. }
  885. =item $h->normalize_content
  886. Normalizes the content of $h -- i.e., concatenates any adjacent text nodes.
  887. (Any undefined text segments are turned into empty-strings.)
  888. Note that this does not recurse into $h's descendants.
  889. =cut
  890. sub normalize_content {
  891. my $start = $_[0];
  892. my $c;
  893. return unless $c = $start->{'_content'} and ref $c and @$c; # nothing to do
  894. # TODO: if we start having text elements, deal with catenating those too?
  895. my @stretches = (undef); # start with a barrier
  896. # I suppose this could be rewritten to treat stretches as it goes, instead
  897. # of at the end. But feh.
  898. # Scan:
  899. for(my $i = 0; $i < @$c; ++$i) {
  900. if(defined $c->[$i] and ref $c->[$i]) { # not a text segment
  901. if($stretches[0]) {
  902. # put in a barrier
  903. if($stretches[0][1] == 1) {
  904. #print "Nixing stretch at ", $i-1, "\n";
  905. undef $stretches[0]; # nix the previous one-node "stretch"
  906. } else {
  907. #print "End of stretch at ", $i-1, "\n";
  908. unshift @stretches, undef
  909. }
  910. }
  911. # else no need for a barrier
  912. } else { # text segment
  913. $c->[$i] = '' unless defined $c->[$i];
  914. if($stretches[0]) {
  915. ++$stretches[0][1]; # increase length
  916. } else {
  917. #print "New stretch at $i\n";
  918. unshift @stretches, [$i,1]; # start and length
  919. }
  920. }
  921. }
  922. # Now combine. Note that @stretches is in reverse order, so the indexes
  923. # still make sense as we work our way thru (i.e., backwards thru $c).
  924. foreach my $s (@stretches) {
  925. if($s and $s->[1] > 1) {
  926. #print "Stretch at ", $s->[0], " for ", $s->[1], "\n";
  927. $c->[$s->[0]] .= join('', splice(@$c, $s->[0] + 1, $s->[1] - 1))
  928. # append the subsequent ones onto the first one.
  929. }
  930. }
  931. return;
  932. }
  933. =item $h->delete_ignorable_whitespace()
  934. This traverses under $h and deletes any text segments that are ignorable
  935. whitespace. You should not use this if $h under a 'pre' element.
  936. =cut
  937. #==========================================================================
  938. sub delete_ignorable_whitespace {
  939. # This doesn't delete all sorts of whitespace that won't actually
  940. # be used in rendering, tho -- that's up to the rendering application.
  941. # For example:
  942. # <input type='text' name='foo'>
  943. # [some whitespace]
  944. # <input type='text' name='bar'>
  945. # The WS between the two elements /will/ get used by the renderer.
  946. # But here:
  947. # <input type='hidden' name='foo' value='1'>
  948. # [some whitespace]
  949. # <input type='text' name='bar' value='2'>
  950. # the WS between them won't be rendered in any way, presumably.
  951. #my $Debug = 4;
  952. die "delete_ignorable_whitespace can be called only as an object method"
  953. unless ref $_[0];
  954. print "About to tighten up...\n" if $Debug > 2;
  955. my(@to_do) = ($_[0]); # Start off.
  956. my($i, $sibs, $ptag, $this); # scratch for the loop...
  957. while(@to_do) {
  958. if(
  959. ( $ptag = ($this = shift @to_do)->{'_tag'} ) eq 'pre'
  960. or $ptag eq 'textarea'
  961. or $HTML::Tagset::isCDATA_Parent{$ptag}
  962. ) {
  963. # block the traversal under those
  964. print "Blocking traversal under $ptag\n" if $Debug;
  965. next;
  966. }
  967. next unless($sibs = $this->{'_content'} and @$sibs);
  968. for($i = $#$sibs; $i >= 0; --$i) { # work backwards thru the list
  969. if(ref $sibs->[$i]) {
  970. unshift @to_do, $sibs->[$i];
  971. # yes, this happens in pre order -- we're going backwards
  972. # thru this sibling list. I doubt it actually matters, tho.
  973. next;
  974. }
  975. next unless $sibs->[$i] =~ m<^\s+$>s; # it's /all/ whitespace
  976. print "Under $ptag whose canTighten ",
  977. "value is ", 0 + $HTML::Element::canTighten{$ptag}, ".\n"
  978. if $Debug > 3;
  979. # It's all whitespace...
  980. if($i == 0) {
  981. if(@$sibs == 1) { # I'm an only child
  982. next unless $HTML::Element::canTighten{$ptag}; # parent
  983. } else { # I'm leftmost of many
  984. # if either my parent or sib are eligible, I'm good.
  985. next unless
  986. $HTML::Element::canTighten{$ptag} # parent
  987. or
  988. (ref $sibs->[1]
  989. and $HTML::Element::canTighten{$sibs->[1]{'_tag'}} # right sib
  990. );
  991. }
  992. } elsif ($i == $#$sibs) { # I'm rightmost of many
  993. # if either my parent or sib are eligible, I'm good.
  994. next unless
  995. $HTML::Element::canTighten{$ptag} # parent
  996. or
  997. (ref $sibs->[$i - 1]
  998. and $HTML::Element::canTighten{$sibs->[$i - 1]{'_tag'}} # left sib
  999. )
  1000. } else { # I'm the piggy in the middle
  1001. # My parent doesn't matter -- it all depends on my sibs
  1002. next
  1003. unless
  1004. ref $sibs->[$i - 1] or ref $sibs->[$i + 1];
  1005. # if NEITHER sib is a node, quit
  1006. next if
  1007. # bailout condition: if BOTH are INeligible nodes
  1008. # (as opposed to being text, or being eligible nodes)
  1009. ref $sibs->[$i - 1]
  1010. and ref $sibs->[$i + 1]
  1011. and !$HTML::Element::canTighten{$sibs->[$i - 1]{'_tag'}} # left sib
  1012. and !$HTML::Element::canTighten{$sibs->[$i + 1]{'_tag'}} # right sib
  1013. ;
  1014. }
  1015. # Unknown tags aren't in canTighten and so AREN'T subject to tightening
  1016. print " delendum: child $i of $ptag\n" if $Debug > 3;
  1017. splice @$sibs, $i, 1;
  1018. }
  1019. # end of the loop-over-children
  1020. }
  1021. # end of the while loop.
  1022. return;
  1023. }
  1024. #--------------------------------------------------------------------------
  1025. =item $h->insert_element($element, $implicit)
  1026. Inserts (via push_content) a new element under the element at
  1027. $h->pos(). Then updates $h->pos() to point to the inserted element,
  1028. unless $element is a prototypically empty element like "br", "hr",
  1029. "img", etc. The new $h->pos() is returned. This method is useful
  1030. only if your particular tree task involves setting $h->pos.
  1031. =cut
  1032. sub insert_element
  1033. {
  1034. my($self, $tag, $implicit) = @_;
  1035. return $self->pos() unless $tag; # noop if nothing to insert
  1036. my $e;
  1037. if (ref $tag) {
  1038. $e = $tag;
  1039. $tag = $e->tag;
  1040. } else { # just a tag name -- so make the element
  1041. $e = ($self->{'_element_class'} || __PACKAGE__)->new($tag);
  1042. ++($self->{'_element_count'}) if exists $self->{'_element_count'};
  1043. # undocumented. see TreeBuilder.
  1044. }
  1045. $e->{'_implicit'} = 1 if $implicit;
  1046. my $pos = $self->{'_pos'};
  1047. $pos = $self unless defined $pos;
  1048. $pos->push_content($e);
  1049. $self->{'_pos'} = $pos = $e
  1050. unless $self->_empty_element_map->{$tag} || $e->{'_empty_element'};
  1051. $pos;
  1052. }
  1053. #==========================================================================
  1054. # Some things to override in XML::Element
  1055. sub _empty_element_map {
  1056. \%HTML::Element::emptyElement;
  1057. }
  1058. sub _fold_case_LC {
  1059. if(wantarray) {
  1060. shift;
  1061. map lc($_), @_;
  1062. } else {
  1063. return lc($_[1]);
  1064. }
  1065. }
  1066. sub _fold_case_NOT {
  1067. if(wantarray) {
  1068. shift;
  1069. @_;
  1070. } else {
  1071. return $_[1];
  1072. }
  1073. }
  1074. *_fold_case = \&_fold_case_LC;
  1075. #==========================================================================
  1076. =back
  1077. =head1 DUMPING METHODS
  1078. =over 4
  1079. =item $h->dump()
  1080. =item $h->dump(*FH) ; # or *FH{IO} or $fh_obj
  1081. Prints the element and all its children to STDOUT (or to a specified
  1082. filehandle), in a format useful
  1083. only for debugging. The structure of the document is shown by
  1084. indentation (no end tags).
  1085. =cut
  1086. sub dump
  1087. {
  1088. my($self, $fh, $depth) = @_;
  1089. $fh = *STDOUT{IO} unless defined $fh;
  1090. $depth = 0 unless defined $depth;
  1091. print $fh
  1092. " " x $depth, $self->starttag, " \@", $self->address,
  1093. $self->{'_implicit'} ? " (IMPLICIT)\n" : "\n";
  1094. for (@{$self->{'_content'}}) {
  1095. if (ref $_) { # element
  1096. $_->dump($fh, $depth+1); # recurse
  1097. } else { # text node
  1098. print $fh " " x ($depth + 1);
  1099. if(length($_) > 65 or m<[\x00-\x1F]>) {
  1100. # it needs prettyin' up somehow or other
  1101. my $x = (length($_) <= 65) ? $_ : (substr($_,0,65) . '...');
  1102. $x =~ s<([\x00-\x1F])>
  1103. <'\\x'.(unpack("H2",$1))>eg;
  1104. print $fh qq{"$x"\n};
  1105. } else {
  1106. print $fh qq{"$_"\n};
  1107. }
  1108. }
  1109. }
  1110. }
  1111. =item $h->as_HTML() or $h->as_HTML($entities)
  1112. =item or $h->as_HTML($entities, $indent_char)
  1113. =item or $h->as_HTML($entities, $indent_char, \%optional_end_tags)
  1114. Returns a string representing in HTML the element and its
  1115. descendants. The optional argument C<$entities> specifies a string of
  1116. the entities to encode. For compatibility with previous versions,
  1117. specify C<'E<lt>E<gt>&'> here. If omitted or undef, I<all> unsafe
  1118. characters are encoded as HTML entities. See L<HTML::Entities> for
  1119. details.
  1120. If $indent_char is specified and defined, the HTML to be output is
  1121. intented, using the string you specify (which you probably should
  1122. set to "\t", or some number of spaces, if you specify it). This
  1123. feature is currently somewhat experimental. But try it, and feel
  1124. free to email me any bug reports. (Note that output, although
  1125. indented, is not wrapped. Patches welcome.)
  1126. If C<\%optional_end_tags> is specified and defined, it should be
  1127. a reference to a hash that holds a true value for every tag name
  1128. whose end tag is optional. Defaults to
  1129. C<\%HTML::Element::optionalEndTag>, which is an alias to
  1130. C<%HTML::Tagset::optionalEndTag>, which, at time of writing, contains
  1131. true values for C<p, li, dt, dd>. A useful value to pass is an empty
  1132. hashref, C<{}>, which means that no end-tags are optional for this dump.
  1133. Otherwise, possibly consider copying C<%HTML::Tagset::optionalEndTag> to a
  1134. hash of your own, adding or deleting values as you like, and passing
  1135. a reference to that hash.
  1136. =cut
  1137. sub as_HTML {
  1138. my($self, $entities, $indent, $omissible_map) = @_;
  1139. #my $indent_on = defined($indent) && length($indent);
  1140. my @html = ();
  1141. $omissible_map ||= \%HTML::Element::optionalEndTag;
  1142. my $empty_element_map = $self->_empty_element_map;
  1143. my $last_tag_tightenable = 0;
  1144. my $this_tag_tightenable = 0;
  1145. my $nonindentable_ancestors = 0; # count of nonindentible tags over us.
  1146. my($tag, $node, $start, $depth); # per-iteration scratch
  1147. if(defined($indent) && length($indent)) {
  1148. $self->traverse(
  1149. sub {
  1150. ($node, $start, $depth) = @_;
  1151. if(ref $node) { # it's an element
  1152. $tag = $node->{'_tag'};
  1153. if($start) { # on the way in
  1154. if(
  1155. ($this_tag_tightenable = $HTML::Element::canTighten{$tag})
  1156. and !$nonindentable_ancestors
  1157. and $last_tag_tightenable
  1158. ) {
  1159. push
  1160. @html,
  1161. "\n",
  1162. $indent x $depth,
  1163. $node->starttag($entities),
  1164. ;
  1165. } else {
  1166. push(@html, $node->starttag($entities));
  1167. }
  1168. $last_tag_tightenable = $this_tag_tightenable;
  1169. ++$nonindentable_ancestors
  1170. if $tag eq 'pre' or $HTML::Tagset::isCDATA_Parent{$tag}; ;
  1171. } elsif (not($empty_element_map->{$tag} or $omissible_map->{$tag})) {
  1172. # on the way out
  1173. if($tag eq 'pre' or $HTML::Tagset::isCDATA_Parent{$tag}) {
  1174. --$nonindentable_ancestors;
  1175. $last_tag_tightenable = $HTML::Element::canTighten{$tag};
  1176. push @html, $node->endtag;
  1177. } else { # general case
  1178. if(
  1179. ($this_tag_tightenable = $HTML::Element::canTighten{$tag})
  1180. and !$nonindentable_ancestors
  1181. and $last_tag_tightenable
  1182. ) {
  1183. push
  1184. @html,
  1185. "\n",
  1186. $indent x $depth,
  1187. $node->endtag,
  1188. ;
  1189. } else {
  1190. push @html, $node->endtag;
  1191. }
  1192. $last_tag_tightenable = $this_tag_tightenable;
  1193. #print "$tag tightenable: $this_tag_tightenable\n";
  1194. }
  1195. }
  1196. } else { # it's a text segment
  1197. $last_tag_tightenable = 0; # I guess this is right
  1198. HTML::Entities::encode_entities($node, $entities)
  1199. # That does magic things if $entities is undef.
  1200. unless $HTML::Tagset::isCDATA_Parent{ $_[3]{'_tag'} };
  1201. # To keep from amp-escaping children of script et al.
  1202. # That doesn't deal with descendants; but then, CDATA
  1203. # parents shouldn't /have/ descendants other than a
  1204. # text children (or comments?)
  1205. if($nonindentable_ancestors) {
  1206. push @html, $node; # say no go
  1207. } else {
  1208. if($last_tag_tightenable) {
  1209. $node =~ s<\s+>< >s;
  1210. #$node =~ s< $><>s;
  1211. $node =~ s<^ ><>s;
  1212. push
  1213. @html,
  1214. "\n",
  1215. $indent x $depth,
  1216. $node,
  1217. #Text::Wrap::wrap($indent x $depth, $indent x $depth, "\n" . $node)
  1218. ;
  1219. } else {
  1220. push
  1221. @html,
  1222. $node,
  1223. #Text::Wrap::wrap('', $indent x $depth, $node)
  1224. ;
  1225. }
  1226. }
  1227. }
  1228. 1; # keep traversing
  1229. }
  1230. );
  1231. } else { # no indenting -- much simpler code
  1232. $self->traverse(
  1233. sub {
  1234. ($node, $start) = @_;
  1235. if(ref $node) {
  1236. $tag = $node->{'_tag'};
  1237. if($start) { # on the way in
  1238. push(@html, $node->starttag($entities));
  1239. } elsif (not($empty_element_map->{$tag} or $omissible_map->{$tag})) {
  1240. # on the way out
  1241. push(@html, $node->endtag);
  1242. }
  1243. } else {
  1244. # simple text content
  1245. HTML::Entities::encode_entities($node, $entities)
  1246. # That does magic things if $entities is undef.
  1247. unless $HTML::Tagset::isCDATA_Parent{ $_[3]{'_tag'} };
  1248. # To keep from amp-escaping children of script et al.
  1249. # That doesn't deal with descendants; but then, CDATA
  1250. # parents shouldn't /have/ descendants other than a
  1251. # text children (or comments?)
  1252. push(@html, $node);
  1253. }
  1254. 1; # keep traversing
  1255. }
  1256. );
  1257. }
  1258. join('', @html, "\n");
  1259. }
  1260. =item $h->as_text()
  1261. =item $h->as_text(skip_dels => 1)
  1262. Returns a string consisting of only the text parts of the element's
  1263. descendants.
  1264. Text under 'script' or 'style' elements is never included in what's
  1265. returned. If C<skip_dels> is true, then text content under "del"
  1266. nodes is not included in what's returned.
  1267. =cut
  1268. sub as_text {
  1269. # Yet another iteratively implemented traverser
  1270. my($this,%options) = @_;
  1271. my $skip_dels = $options{'skip_dels'} || 0;
  1272. #print "Skip dels: $skip_dels\n";
  1273. my(@pile) = ($this);
  1274. my $tag;
  1275. my $text = '';
  1276. while(@pile) {
  1277. if(!defined($pile[0])) { # undef!
  1278. # no-op
  1279. } elsif(!ref($pile[0])) { # text bit! save it!
  1280. $text .= shift @pile;
  1281. } else { # it's a ref -- traverse under it
  1282. unshift @pile, @{$this->{'_content'} || $nillio}
  1283. unless
  1284. ($tag = ($this = shift @pile)->{'_tag'}) eq 'style'
  1285. or $tag eq 'script'
  1286. or ($skip_dels and $tag eq 'del');
  1287. }
  1288. }
  1289. return $text;
  1290. }
  1291. =item $h->as_XML() or $h->as_XML($entities)
  1292. Returns a string representing in XML the element and its descendants.
  1293. The optional argument C<$entities> specifies a string of the entities
  1294. to encode. If omitted or undef, I<all> unsafe characters are encoded
  1295. as HTML (!) entities. See L<HTML::Entities> for details.
  1296. This method is experimental. If you use this method, tell me what you
  1297. use it for, and if you run into any problems.
  1298. The XML is not indented.
  1299. =cut
  1300. # TODO: make it wrap, if not indent?
  1301. sub as_XML {
  1302. # based an as_HTML
  1303. my($self, $entities) = @_;
  1304. #my $indent_on = defined($indent) && length($indent);
  1305. my @xml = ();
  1306. my $empty_element_map = $self->_empty_element_map;
  1307. my($tag, $node, $start); # per-iteration scratch
  1308. $self->traverse(
  1309. sub {
  1310. ($node, $start) = @_;
  1311. if(ref $node) { # it's an element
  1312. $tag = $node->{'_tag'};
  1313. if($start) { # on the way in
  1314. if($empty_element_map->{$tag}
  1315. and !@{$node->{'_content'} || $nillio}
  1316. ) {
  1317. push(@xml, $node->starttag_XML($entities,1));
  1318. } else {
  1319. push(@xml, $node->starttag_XML($entities));
  1320. }
  1321. } else { # on the way out
  1322. unless($empty_element_map->{$tag}
  1323. and !@{$node->{'_content'} || $nillio}
  1324. ) {
  1325. push(@xml, $node->endtag_XML());
  1326. } # otherwise it will have been an <... /> tag.
  1327. }
  1328. } else { # it's just text
  1329. HTML::Entities::encode_entities($node, $entities);
  1330. push(@xml, $node);
  1331. }
  1332. 1; # keep traversing
  1333. }
  1334. );
  1335. join('', @xml, "\n");
  1336. }
  1337. =item $h->as_Lisp_form()
  1338. Returns a string representing the element and its descendants as a
  1339. Lisp form. Unsafe characters are encoded as octal escapes.
  1340. The Lisp form is indented, and contains external ("href", etc.) as
  1341. well as internal attributes ("_tag", "_content", "_implicit", etc.),
  1342. except for "_parent", which is omitted.
  1343. Current example output for a given element:
  1344. ("_tag" "img" "border" "0" "src" "pie.png" "usemap" "#main.map")
  1345. This method is experimental. If you use this method, tell me what you
  1346. use it for, and if you run into any problems.
  1347. =cut
  1348. # NOTES:
  1349. #
  1350. # It's been suggested that attribute names be made :-keywords:
  1351. # (:_tag "img" :border 0 :src "pie.png" :usemap "#main.map")
  1352. # However, it seems that Scheme has no such data type as :-keywords.
  1353. # So, for the moment at least, I tend toward simplicity, uniformity,
  1354. # and universality, where everything a string or a list.
  1355. sub as_Lisp_form {
  1356. my @out;
  1357. my $sub;
  1358. my $depth = 0;
  1359. my(@list, $val);
  1360. $sub = sub { # Recursor
  1361. my $self = $_[0];
  1362. @list = ('_tag', $self->{'_tag'});
  1363. @list = () unless defined $list[-1]; # unlikely
  1364. for (sort keys %$self) { # predictable ordering
  1365. next if $_ eq '_content' or $_ eq '_tag' or $_ eq '_parent' or $_ eq '/';
  1366. # Leave the other private attributes, I guess.
  1367. push @list, $_, $val if defined($val = $self->{$_}); # and !ref $val;
  1368. }
  1369. for (@list) {
  1370. #if(!length $_) {
  1371. # $_ = '""';
  1372. #} elsif(
  1373. # $_ eq '0'
  1374. # or (
  1375. # m/^-?\d+(\.\d+)?$/s
  1376. # and $_ ne '-0' # the strange case that that RE lets thru
  1377. # ) or (
  1378. # m/^-?\.\d+$/s
  1379. # )
  1380. #) {
  1381. # # No-op -- don't bother quoting numbers.
  1382. # # Note: DOES accept strings like "0123" and ".123" as numbers!
  1383. # #
  1384. #} else {
  1385. # octal-escape it
  1386. s<([^\x20\x21\x23\x27-\x5B\x5D-\x7E])>
  1387. <sprintf('\\%03o',ord($1))>eg;
  1388. $_ = qq{"$_"};
  1389. #}
  1390. }
  1391. push @out, (' ' x $depth) . '(' . join ' ', splice @list;
  1392. if(@{$self->{'_content'} || $nillio}) {
  1393. $out[-1] .= " \"_content\" (\n";
  1394. ++$depth;
  1395. foreach my $c (@{$self->{'_content'}}) {
  1396. if(ref($c)) {
  1397. # an element -- recurse
  1398. $sub->($c);
  1399. } else {
  1400. # a text segment -- stick it in and octal-escape it
  1401. push @out, $c;
  1402. $out[-1] =~
  1403. s<([^\x20\x21\x23\x27-\x5B\x5D-\x7E])>
  1404. <sprintf('\\%03o',ord($1))>eg;
  1405. # And quote and indent it.
  1406. $out[-1] .= "\"\n";
  1407. $out[-1] = (' ' x $depth) . '"' . $out[-1];
  1408. }
  1409. }
  1410. --$depth;
  1411. substr($out[-1],-1) = "))\n"; # end of _content and of the element
  1412. } else {
  1413. $out[-1] .= ")\n";
  1414. }
  1415. return;
  1416. };
  1417. $sub->($_[0]);
  1418. undef $sub;
  1419. return join '', @out;
  1420. }
  1421. sub format
  1422. {
  1423. my($self, $formatter) = @_;
  1424. unless (defined $formatter) {
  1425. require HTML::FormatText;
  1426. $formatter = HTML::FormatText->new();
  1427. }
  1428. $formatter->format($self);
  1429. }
  1430. =item $h->starttag() or $h->starttag($entities)
  1431. Returns a string representing the complete start tag for the element.
  1432. I.e., leading "<", tag name, attributes, and trailing ">". Attributes
  1433. values that don't consist entirely of digits are surrounded with
  1434. double-quotes, and appropriate characters are encoded. If C<$entities>
  1435. is omitted or undef, I<all> unsafe characters are encoded as HTML
  1436. entities. See L<HTML::Entities> for details. If you specify some
  1437. value for C<$entities>, remember to include the double-quote character in
  1438. it. (Previous versions of this module would basically behave as if
  1439. C<'&"E<gt>'> were specified for C<$entities>.)
  1440. =cut
  1441. sub starttag
  1442. {
  1443. my($self, $entities) = @_;
  1444. my $name = $self->{'_tag'};
  1445. return $self->{'text'} if $name eq '~literal';
  1446. return "<!" . $self->{'text'} . ">" if $name eq '~declaration';
  1447. return "<?" . $self->{'text'} . ">" if $name eq '~pi';
  1448. if($name eq '~comment') {
  1449. if(ref($self->{'text'} || '') eq 'ARRAY') {
  1450. # Does this ever get used? And is this right?
  1451. return
  1452. "<!" .
  1453. join(' ', map("--$_--", @{$self->{'text'}}))
  1454. . ">"
  1455. ;
  1456. } else {
  1457. return "<!--" . $self->{'text'} . "-->"
  1458. }
  1459. }
  1460. my $tag = $html_uc ? "<\U$name" : "<\L$name";
  1461. my $val;
  1462. for (sort keys %$self) { # predictable ordering
  1463. next if !length $_ or m/^_/s or $_ eq '/';
  1464. $val = $self->{$_};
  1465. next if !defined $val; # or ref $val;
  1466. if ($_ eq $val && # if attribute is boolean, for this element
  1467. exists($HTML::Element::boolean_attr{$name}) &&
  1468. (ref($HTML::Element::boolean_attr{$name})
  1469. ? $HTML::Element::boolean_attr{$name}{$_}
  1470. : $HTML::Element::boolean_attr{$name} eq $_)
  1471. ) {
  1472. $tag .= $html_uc ? " \U$_" : " \L$_";
  1473. } else { # non-boolean attribute
  1474. if ($val !~ m/^[0-9]+$/s) { # quote anything not purely numeric
  1475. # Might as well double-quote everything, for simplicity's sake
  1476. HTML::Entities::encode_entities($val, $entities);
  1477. $val = qq{"$val"};
  1478. }
  1479. $tag .= $html_uc ? qq{ \U$_\E=$val} : qq{ \L$_\E=$val};
  1480. }
  1481. }
  1482. "$tag>";
  1483. }
  1484. # TODO: document?
  1485. sub starttag_XML
  1486. {
  1487. my($self, $entities) = @_;
  1488. # and a third parameter to signal emptiness
  1489. my $name = $self->{'_tag'};
  1490. return $self->{'text'} if $name eq '~literal';
  1491. return '<!' . $self->{'text'}. '>' if $name eq '~declaration';
  1492. return "<?" . $self->{'text'} . "?>" if $name eq '~pi';
  1493. if($name eq '~comment') {
  1494. if(ref($self->{'text'} || '') eq 'ARRAY') {
  1495. # Does this ever get used? And is this right?
  1496. $name = join(' ', @{$self->{'text'}});
  1497. } else {
  1498. $name = $self->{'text'};
  1499. }
  1500. $name =~ s/--/-&#45;/g; # can't have double --'s in XML comments
  1501. return "<!-- $name -->";
  1502. }
  1503. my $tag = "<$name";
  1504. my $val;
  1505. for (sort keys %$self) { # predictable ordering
  1506. next if !length $_ or m/^_/s or $_ eq '/';
  1507. # Hm -- what to do if val is undef?
  1508. # I suppose that shouldn't ever happen.
  1509. next if !defined($val = $self->{$_}); # or ref $val;
  1510. HTML::Entities::encode_entities($val, $entities);
  1511. $tag .= qq{ $_="$val"};
  1512. }
  1513. @_ == 3 ? "$tag />" : "$tag>";
  1514. }
  1515. =item $h->endtag()
  1516. Returns a string representing the complete end tag for this element.
  1517. I.e., "</", tag name, and ">".
  1518. =cut
  1519. sub endtag
  1520. {
  1521. $html_uc ? "</\U$_[0]->{'_tag'}>" : "</\L$_[0]->{'_tag'}>";
  1522. }
  1523. # TODO: document?
  1524. sub endtag_XML
  1525. {
  1526. "</$_[0]->{'_tag'}>";
  1527. }
  1528. #==========================================================================
  1529. # This, ladies and germs, is an iterative implementation of a
  1530. # recursive algorithm. DON'T TRY THIS AT HOME.
  1531. # Basically, the algorithm says:
  1532. #
  1533. # To traverse:
  1534. # 1: pre-order visit this node
  1535. # 2: traverse any children of this node
  1536. # 3: post-order visit this node, unless it's a text segment,
  1537. # or a prototypically empty node (like "br", etc.)
  1538. # Add to that the consideration of the callbacks' return values,
  1539. # so you can block visitation of the children, or siblings, or
  1540. # abort the whole excursion, etc.
  1541. #
  1542. # So, why all this hassle with making the code iterative?
  1543. # It makes for real speed, because it eliminates the whole
  1544. # hassle of Perl having to allocate scratch space for each
  1545. # instance of the recursive sub. Since the algorithm
  1546. # is basically simple (and not all recursive ones are!) and
  1547. # has few necessary lexicals (basically just the current node's
  1548. # content list, and the current position in it), it was relatively
  1549. # straightforward to store that information not as the frame
  1550. # of a sub, but as a stack, i.e., a simple Perl array (well, two
  1551. # of them, actually: one for content-listrefs, one for indexes of
  1552. # current position in each of those).
  1553. my $NIL = [];
  1554. sub traverse {
  1555. my($start, $callback, $ignore_text) = @_;
  1556. Carp::croak "traverse can be called only as an object method"
  1557. unless ref $start;
  1558. Carp::croak('must provide a callback for traverse()!')
  1559. unless defined $callback and ref $callback;
  1560. # Elementary type-checking:
  1561. my($c_pre, $c_post);
  1562. if(UNIVERSAL::isa($callback, 'CODE')) {
  1563. $c_pre = $c_post = $callback;
  1564. } elsif(UNIVERSAL::isa($callback,'ARRAY')) {
  1565. ($c_pre, $c_post) = @$callback;
  1566. Carp::croak("pre-order callback \"$c_pre\" is true but not a coderef!")
  1567. if $c_pre and not UNIVERSAL::isa($c_pre, 'CODE');
  1568. Carp::croak("pre-order callback \"$c_post\" is true but not a coderef!")
  1569. if $c_post and not UNIVERSAL::isa($c_post, 'CODE');
  1570. return $start unless $c_pre or $c_post;
  1571. # otherwise there'd be nothing to actually do!
  1572. } else {
  1573. Carp::croak("$callback is not a known kind of reference")
  1574. unless ref($callback);
  1575. }
  1576. my $empty_element_map = $start->_empty_element_map;
  1577. my(@C) = [$start]; # a stack containing lists of children
  1578. my(@I) = (-1); # initial value must be -1 for each list
  1579. # a stack of indexes to current position in corresponding lists in @C
  1580. # In each of these, 0 is the active point
  1581. # scratch:
  1582. my(
  1583. $rv, # return value of callback
  1584. $this, # current node
  1585. $content_r, # child list of $this
  1586. );
  1587. # THE BIG LOOP
  1588. while(@C) {
  1589. # Move to next item in this frame
  1590. #print "Loop: \@C has ", scalar(@C), " frames: @C\n";
  1591. if(!defined($I[0]) or ++$I[0] >= @{$C[0]}) {
  1592. # We either went off the end of this list, or aborted the list
  1593. # So call the post-order callback:
  1594. if($c_post
  1595. and defined $I[0]
  1596. and @C > 1
  1597. # to keep the next line from autovivifying
  1598. and defined($this = $C[1][ $I[1] ]) # sanity, and
  1599. # suppress callbacks on exiting the fictional top frame
  1600. and ref($this) # sanity
  1601. and not(
  1602. $this->{'_empty_element'}
  1603. || $empty_element_map->{$this->{'_tag'} || ''}
  1604. ) # things that don't get post-order callbacks
  1605. ) {
  1606. shift @I;
  1607. shift @C;
  1608. #print "Post! at depth", scalar(@I), "\n";
  1609. $rv = $c_post->(
  1610. #map $_, # copy to avoid any messiness
  1611. $this, # 0: this
  1612. 0, # 1: startflag (0 for post-order call)
  1613. @I - 1, # 2: depth
  1614. );
  1615. if(defined($rv) and ref($rv) eq $travsignal_package) {
  1616. $rv = $$rv; #deref
  1617. if($rv eq 'ABORT') {
  1618. last; # end of this excursion!
  1619. } elsif($rv eq 'PRUNE') {
  1620. # NOOP on post!!
  1621. } elsif($rv eq 'PRUNE_SOFTLY') {
  1622. # NOOP on post!!
  1623. } elsif($rv eq 'OK') {
  1624. # noop
  1625. } elsif($rv eq 'PRUNE_UP') {
  1626. $I[0] = undef;
  1627. } else {
  1628. die "Unknown travsignal $rv\n";
  1629. # should never happen
  1630. }
  1631. }
  1632. } else {
  1633. #print "Oomph. Callback suppressed\n";
  1634. shift @I;
  1635. shift @C;
  1636. }
  1637. next;
  1638. }
  1639. $this = $C[0][ $I[0] ];
  1640. if($c_pre) {
  1641. if(defined $this and ref $this) { # element
  1642. $rv = $c_pre->(
  1643. #map $_, # copy to avoid any messiness
  1644. $this, # 0: this
  1645. 1, # 1: startflag (1 for pre-order call)
  1646. @I - 1, # 2: depth
  1647. );
  1648. } else { # text segment
  1649. next if $ignore_text;
  1650. $rv = $c_pre->(
  1651. #map $_, # copy to avoid any messiness
  1652. $this, # 0: this
  1653. 1, # 1: startflag (1 for pre-order call)
  1654. @I - 1, # 2: depth
  1655. $C[1][ $I[1] ], # 3: parent
  1656. # And there will always be a $C[1], since
  1657. # we can't start traversing at a text node
  1658. $I[0] # 4: index of self in parent's content list
  1659. );
  1660. }
  1661. if(not $rv) { # returned false. Same as PRUNE.
  1662. next; # prune
  1663. } elsif(ref($rv) eq $travsignal_package) {
  1664. $rv = $$rv; # deref
  1665. if($rv eq 'ABORT') {
  1666. last; # end of this excursion!
  1667. } elsif($rv eq 'PRUNE') {
  1668. next;
  1669. } elsif($rv eq 'PRUNE_SOFTLY') {
  1670. if(ref($this)
  1671. and
  1672. not($this->{'_empty_element'}
  1673. || $empty_element_map->{$this->{'_tag'} || ''})
  1674. ) {
  1675. # push a dummy empty content list just to trigger a post callback
  1676. unshift @I, -1;
  1677. unshift @C, $NIL;
  1678. }
  1679. next;
  1680. } elsif($rv eq 'OK') {
  1681. # noop
  1682. } elsif($rv eq 'PRUNE_UP') {
  1683. $I[0] = undef;
  1684. next;
  1685. # equivalent of last'ing out of the current child list.
  1686. # Used to have PRUNE_UP_SOFTLY and ABORT_SOFTLY here, but the code
  1687. # for these was seriously upsetting, served no particularly clear
  1688. # purpose, and could not, I think, be easily implemented with a
  1689. # recursive routine. All bad things!
  1690. } else {
  1691. die "Unknown travsignal $rv\n";
  1692. # should never happen
  1693. }
  1694. }
  1695. # else fall thru to meaning same as \'OK'.
  1696. }
  1697. # end of pre-order calling
  1698. # Now queue up content list for the current element...
  1699. if(ref $this
  1700. and
  1701. not( # ...except for those which...
  1702. not($content_r = $this->{'_content'} and @$content_r)
  1703. # ...have empty content lists...
  1704. and $this->{'_empty_element'} || $empty_element_map->{$this->{'_tag'} || ''}
  1705. # ...and that don't get post-order callbacks
  1706. )
  1707. ) {
  1708. unshift @I, -1;
  1709. unshift @C, $content_r || $NIL;
  1710. #print $this->{'_tag'}, " ($this) adds content_r ", $C[0], "\n";
  1711. }
  1712. }
  1713. return $start;
  1714. }
  1715. =back
  1716. =head1 SECONDARY STRUCTURAL METHODS
  1717. These methods all involve some structural aspect of the tree;
  1718. either they report some aspect of the tree's structure, or they involve
  1719. traversal down the tree, or walking up the tree.
  1720. =over 4
  1721. =item $h->is_inside('tag', ...) or $h->is_inside($element, ...)
  1722. Returns true if the $h element is, or is contained anywhere inside an
  1723. element that is any of the ones listed, or whose tag name is any of
  1724. the tag names listed.
  1725. =cut
  1726. sub is_inside {
  1727. my $self = shift;
  1728. return undef unless @_; # if no items specified, I guess this is right.
  1729. my $current = $self;
  1730. # the loop starts by looking at the given element
  1731. while (defined $current and ref $current) {
  1732. for (@_) {
  1733. if(ref) { # element
  1734. return 1 if $_ eq $current;
  1735. } else { # tag name
  1736. return 1 if $_ eq $current->{'_tag'};
  1737. }
  1738. }
  1739. $current = $current->{'_parent'};
  1740. }
  1741. 0;
  1742. }
  1743. =item $h->is_empty()
  1744. Returns true if $h has no content, i.e., has no elements or text
  1745. segments under it. In other words, this returns true if $h is a leaf
  1746. node, AKA a terminal node. Do not confuse this sense of "empty" with
  1747. another sense that it can have in SGML/HTML/XML terminology, which
  1748. means that the element in question is of the type (like HTML's "hr",
  1749. "br", "img", etc.) that I<can't> have any content.
  1750. That is, a particular "p" element may happen to have no content, so
  1751. $that_p_element->is_empty will be true -- even though the prototypical
  1752. "p" element isn't "empty" (not in the way that the prototypical "hr"
  1753. element is).
  1754. If you think this might make for potentially confusing code, consider
  1755. simply using the clearer exact equivalent: not($h->content_list)
  1756. =cut
  1757. sub is_empty
  1758. {
  1759. my $self = shift;
  1760. !$self->{'_content'} || !@{$self->{'_content'}};
  1761. }
  1762. =item $h->pindex()
  1763. Return the index of the element in its parent's contents array, such
  1764. that $h would equal
  1765. $h->parent->content->[$h->pindex]
  1766. or
  1767. ($h->parent->content_list)[$h->pindex]
  1768. assuming $h isn't root. If the element $h is root, then
  1769. $h->pindex returns undef.
  1770. =cut
  1771. #'
  1772. sub pindex {
  1773. my $self = shift;
  1774. my $parent = $self->{'_parent'} || return undef;
  1775. my $pc = $parent->{'_content'} || return undef;
  1776. for(my $i = 0; $i < @$pc; ++$i) {
  1777. return $i if ref $pc->[$i] and $pc->[$i] eq $self;
  1778. }
  1779. return undef; # we shouldn't ever get here
  1780. }
  1781. #--------------------------------------------------------------------------
  1782. =item $h->left()
  1783. In scalar context: returns the node that's the immediate left sibling
  1784. of $h. If $h is the leftmost (or only) child of its parent (or has no
  1785. parent), then this returns undef.
  1786. In list context: returns all the nodes that're the left siblings of $h
  1787. (starting with the leftmost). If $h is the leftmost (or only) child
  1788. of its parent (or has no parent), then this returns empty-list.
  1789. (See also $h->preinsert(LIST).)
  1790. =cut
  1791. sub left {
  1792. Carp::croak "left() is supposed to be an object method"
  1793. unless ref $_[0];
  1794. my $pc =
  1795. (
  1796. $_[0]->{'_parent'} || return
  1797. )->{'_content'} || die "parent is childless?";
  1798. die "parent is childless" unless @$pc;
  1799. return if @$pc == 1; # I'm an only child
  1800. if(wantarray) {
  1801. my @out;
  1802. foreach my $j (@$pc) {
  1803. return @out if ref $j and $j eq $_[0];
  1804. push @out, $j;
  1805. }
  1806. } else {
  1807. for(my $i = 0; $i < @$pc; ++$i) {
  1808. return $i ? $pc->[$i - 1] : undef
  1809. if ref $pc->[$i] and $pc->[$i] eq $_[0];
  1810. }
  1811. }
  1812. die "I'm not in my parent's content list?";
  1813. return;
  1814. }
  1815. =item $h->right()
  1816. In scalar context: returns the node that's the immediate right sibling
  1817. of $h. If $h is the rightmost (or only) child of its parent (or has
  1818. no parent), then this returns undef.
  1819. In list context: returns all the nodes that're the right siblings of
  1820. $h, strting with the leftmost. If $h is the rightmost (or only) child
  1821. of its parent (or has no parent), then this returns empty-list.
  1822. (See also $h->postinsert(LIST).)
  1823. =cut
  1824. sub right {
  1825. Carp::croak "right() is supposed to be an object method"
  1826. unless ref $_[0];
  1827. my $pc =
  1828. (
  1829. $_[0]->{'_parent'} || return
  1830. )->{'_content'} || die "parent is childless?";
  1831. die "parent is childless" unless @$pc;
  1832. return if @$pc == 1; # I'm an only child
  1833. if(wantarray) {
  1834. my(@out, $seen);
  1835. foreach my $j (@$pc) {
  1836. if($seen) {
  1837. push @out, $j;
  1838. } else {
  1839. $seen = 1 if ref $j and $j eq $_[0];
  1840. }
  1841. }
  1842. die "I'm not in my parent's content list?" unless $seen;
  1843. return @out;
  1844. } else {
  1845. for(my $i = 0; $i < @$pc; ++$i) {
  1846. return +($i == $#$pc) ? undef : $pc->[$i+1]
  1847. if ref $pc->[$i] and $pc->[$i] eq $_[0];
  1848. }
  1849. die "I'm not in my parent's content list?";
  1850. return;
  1851. }
  1852. }
  1853. #--------------------------------------------------------------------------
  1854. =item $h->address()
  1855. Returns a string representing the location of this node in the tree.
  1856. The address consists of numbers joined by a '.', starting with '0',
  1857. and followed by the pindexes of the nodes in the tree that are
  1858. ancestors of $h, starting from the top.
  1859. So if the way to get to a node starting at the root is to go to child
  1860. 2 of the root, then child 10 of that, and then child 0 of that, and
  1861. then you're there -- then that node's address is "0.2.10.0".
  1862. As a bit of a special case, the address of the root is simply "0".
  1863. I forsee this being used mainly for debugging, but you may
  1864. find your own uses for it.
  1865. =item $h->address($address)
  1866. This returns the node (whether element or text-segment) at
  1867. the given address in the tree that $h is a part of. (That is,
  1868. the address is resolved starting from $h->root.)
  1869. If there is no node at the given address, this returns undef.
  1870. You can specify "relative addressing" (i.e., that indexing is supposed
  1871. to start from $h and not from $h->root) by having the address start
  1872. with a period -- e.g., $h->address(".3.2") will look at child 3 of $h,
  1873. and child 2 of that.
  1874. =cut
  1875. sub address {
  1876. if(@_ == 1) { # report-address form
  1877. return
  1878. join('.',
  1879. reverse( # so it starts at the top
  1880. map($_->pindex() || '0', # so that root's undef -> '0'
  1881. $_[0], # self and...
  1882. $_[0]->lineage
  1883. )
  1884. )
  1885. )
  1886. ;
  1887. } else { # get-node-at-address
  1888. my @stack = split(/\./, $_[1]);
  1889. my $here;
  1890. if(@stack and !length $stack[0]) { # relative addressing
  1891. $here = $_[0];
  1892. shift @stack;
  1893. } else { # absolute addressing
  1894. return undef unless 0 == shift @stack; # to pop the initial 0-for-root
  1895. $here = $_[0]->root;
  1896. }
  1897. while(@stack) {
  1898. return undef
  1899. unless
  1900. $here->{'_content'}
  1901. and @{$here->{'_content'}} > $stack[0];
  1902. # make sure the index isn't too high
  1903. $here = $here->{'_content'}[ shift @stack ];
  1904. return undef if @stack and not ref $here;
  1905. # we hit a text node when we expected a non-terminal element node
  1906. }
  1907. return $here;
  1908. }
  1909. }
  1910. =item $h->depth()
  1911. Returns a number expressing $h's depth within its tree, i.e., how many
  1912. steps away it is from the root. If $h has no parent (i.e., is root),
  1913. its depth is 0.
  1914. =cut
  1915. #'
  1916. sub depth {
  1917. my $here = $_[0];
  1918. my $depth = 0;
  1919. while(defined($here = $here->{'_parent'}) and ref($here)) {
  1920. ++$depth;
  1921. }
  1922. return $depth;
  1923. }
  1924. =item $h->root()
  1925. Returns the element that's the top of $h's tree. If $h is root, this
  1926. just returns $h. (If you want to test whether $h I<is> the root,
  1927. instead of asking what its root is, just test not($h->parent).)
  1928. =cut
  1929. #'
  1930. sub root {
  1931. my $here = my $root = shift;
  1932. while(defined($here = $here->{'_parent'}) and ref($here)) {
  1933. $root = $here;
  1934. }
  1935. return $root;
  1936. }
  1937. =item $h->lineage()
  1938. Returns the list of $h's ancestors, starting with its parent, and then
  1939. that parent's parent, and so on, up to the root. If $h is root, this
  1940. returns an empty list.
  1941. If you simply want a count of the number of elements in $h's lineage,
  1942. use $h->depth.
  1943. =cut
  1944. #'
  1945. sub lineage {
  1946. my $here = shift;
  1947. my @lineage;
  1948. while(defined($here = $here->{'_parent'}) and ref($here)) {
  1949. push @lineage, $here;
  1950. }
  1951. return @lineage;
  1952. }
  1953. =item $h->lineage_tag_names()
  1954. Returns the list of the tag names of $h's ancestors, starting
  1955. with its parent, and that parent's parent, and so on, up to the
  1956. root. If $h is root, this returns an empty list.
  1957. Example output: C<('em', 'td', 'tr', 'table', 'body', 'html')>
  1958. =cut
  1959. #'
  1960. sub lineage_tag_names {
  1961. my $here = my $start = shift;
  1962. my @lineage_names;
  1963. while(defined($here = $here->{'_parent'}) and ref($here)) {
  1964. push @lineage_names, $here->{'_tag'};
  1965. }
  1966. return @lineage_names;
  1967. }
  1968. =item $h->descendants()
  1969. In list context, returns the list of all $h's descendant elements,
  1970. listed in pre-order (i.e., an element appears before its
  1971. content-elements). Text segments DO NOT appear in the list.
  1972. In scalar context, returns a count of all such elements.
  1973. =cut
  1974. #'
  1975. sub descendants {
  1976. my $start = shift;
  1977. if(wantarray) {
  1978. my @descendants;
  1979. $start->traverse(
  1980. [ # pre-order sub only
  1981. sub {
  1982. push(@descendants, $_[0]);
  1983. return 1;
  1984. },
  1985. undef # no post
  1986. ],
  1987. 1, # ignore text
  1988. );
  1989. shift @descendants; # so $self doesn't appear in the list
  1990. return @descendants;
  1991. } else { # just returns a scalar
  1992. my $descendants = -1; # to offset $self being counted
  1993. $start->traverse(
  1994. [ # pre-order sub only
  1995. sub {
  1996. ++$descendants;
  1997. return 1;
  1998. },
  1999. undef # no post
  2000. ],
  2001. 1, # ignore text
  2002. );
  2003. return $descendants;
  2004. }
  2005. }
  2006. =item $h->find_by_tag_name('tag', ...)
  2007. In list context, returns a list of elements at or under $h that have
  2008. any of the specified tag names. In scalar context, returns the first
  2009. (in pre-order traversal of the tree) such element found, or undef if
  2010. none.
  2011. =cut
  2012. sub find_by_tag_name {
  2013. my(@pile) = shift(@_); # start out the to-do stack for the traverser
  2014. Carp::croak "find_by_tag_name can be called only as an object method"
  2015. unless ref $pile[0];
  2016. return() unless @_;
  2017. my(@tags) = $pile[0]->_fold_case(@_);
  2018. my(@matching, $this, $this_tag);
  2019. while(@pile) {
  2020. $this_tag = ($this = shift @pile)->{'_tag'};
  2021. foreach my $t (@tags) {
  2022. if($t eq $this_tag) {
  2023. if(wantarray) {
  2024. push @matching, $this;
  2025. last;
  2026. } else {
  2027. return $this;
  2028. }
  2029. }
  2030. }
  2031. unshift @pile, grep ref($_), @{$this->{'_content'} || next};
  2032. }
  2033. return @matching if wantarray;
  2034. return;
  2035. }
  2036. =item $h->find_by_attribute('attribute', 'value')
  2037. In a list context, returns a list of elements at or under $h that have
  2038. the specified attribute, and have the given value for that attribute.
  2039. In a scalar context, returns the first (in pre-order traversal of the
  2040. tree) such element found, or undef if none.
  2041. This method is B<deprecated> in favor of the more expressive
  2042. C<look_down> method, which new code should use instead.
  2043. =cut
  2044. sub find_by_attribute {
  2045. # We could limit this to non-internal attributes, but hey.
  2046. my($self, $attribute, $value) = @_;
  2047. Carp::croak "Attribute must be a defined value!" unless defined $attribute;
  2048. $attribute = $self->_fold_case($attribute);
  2049. my @matching;
  2050. my $wantarray = wantarray;
  2051. my $quit;
  2052. $self->traverse(
  2053. [ # pre-order only
  2054. sub {
  2055. if( exists $_[0]{$attribute}
  2056. and $_[0]{$attribute} eq $value
  2057. ) {
  2058. push @matching, $_[0];
  2059. return HTML::Element::ABORT unless $wantarray; # only take the first
  2060. }
  2061. 1; # keep traversing
  2062. },
  2063. undef # no post
  2064. ],
  2065. 1, # yes, ignore text nodes.
  2066. );
  2067. if($wantarray) {
  2068. return @matching;
  2069. } else {
  2070. return undef unless @matching;
  2071. return $matching[0];
  2072. }
  2073. }
  2074. #--------------------------------------------------------------------------
  2075. =item $h->look_down( ...criteria... )
  2076. This starts at $h and looks thru its element descendants (in
  2077. pre-order), looking for elements matching the criteria you specify.
  2078. In list context, returns all elements that match all the given
  2079. criteria; in scalar context, returns the first such element (or undef,
  2080. if nothing matched).
  2081. There are two kinds of criteria you can specify:
  2082. =over
  2083. =item (attr_name, attr_value)
  2084. This means you're looking for an element with that value for that
  2085. attribute. Example: C<"alt", "pix!">. Consider that you can search
  2086. on internal attribute values too: C<"_tag", "p">.
  2087. =item a coderef
  2088. This means you're looking for elements where coderef->(each_element)
  2089. returns true. Example:
  2090. my @wide_pix_images
  2091. = $h->look_down(
  2092. "_tag", "img",
  2093. "alt", "pix!",
  2094. sub { $_[0]->attr('width') > 350 }
  2095. );
  2096. =back
  2097. Note that C<(attr_name, attr_value)> criteria are faster than coderef
  2098. criteria, so should presumably be put before them in your list of
  2099. criteria. That is, in the example above, the sub ref is called only
  2100. for elements that have already passed the criteria of having a "_tag"
  2101. attribute with value "img", and an "alt" attribute with value "pix!".
  2102. If the coderef were first, it would be called on every element, and
  2103. I<then> what elements pass that criterion (i.e., elements for which
  2104. the coderef returned true) would be checked for their "_tag" and "alt"
  2105. attributes.
  2106. Note that comparison of string attribute-values against the string
  2107. value in C<(attr_name, attr_value)> is case-INsensitive! A criterion
  2108. of C<('align', 'right')> I<will> match an element whose "align" value
  2109. is "RIGHT", or "right" or "rIGhT", etc.
  2110. Note also that C<look_down> considers "" (empty-string) and undef to
  2111. be different things, in attribute values. So this:
  2112. $h->look_down("alt", "")
  2113. will find elements I<with> an "alt" attribute, but where the value for
  2114. the "alt" attribute is "". But this:
  2115. $h->look_down("alt", undef)
  2116. is the same as:
  2117. $h->look_down(sub { !defined($_[0]->attr('alt')) } )
  2118. That is, it finds elements that do not have an "alt" attribute at all
  2119. (or that do have an "alt" attribute, but with a value of undef --
  2120. which is not normally possible).
  2121. Note that when you give several criteria, this is taken to mean you're
  2122. looking for elements that match I<all> your criterion, not just I<any>
  2123. of them. In other words, there is an implicit "and", not an "or". So
  2124. if you wanted to express that you wanted to find elements with a
  2125. "name" attribute with the value "foo" I<or> with an "id" attribute
  2126. with the value "baz", you'd have to do it like:
  2127. @them = $h->look_down(
  2128. sub {
  2129. # the lcs are to fold case
  2130. lc($_[0]->attr('name')) eq 'foo'
  2131. or lc($_[0]->attr('id')) eq 'baz'
  2132. }
  2133. );
  2134. Coderef criteria are more expressive than C<(attr_name, attr_value)>
  2135. criteria, and all C<(attr_name, attr_value)> criteria could be
  2136. expressed in terms of coderefs. However, C<(attr_name, attr_value)>
  2137. criteria are a convenient shorthand. (In fact, C<look_down> itself is
  2138. basically "shorthand" too, since anything you can do with C<look_down>
  2139. you could do by traversing the tree, either with the C<traverse>
  2140. method or with a routine of your own. However, C<look_down> often
  2141. makes for very concise and clear code.)
  2142. =cut
  2143. sub look_down {
  2144. ref($_[0]) or Carp::croak "look_down works only as an object method";
  2145. my @criteria;
  2146. for(my $i = 1; $i < @_;) {
  2147. Carp::croak "Can't use undef as an attribute name" unless defined $_[$i];
  2148. if(ref $_[$i]) {
  2149. Carp::croak "A " . ref($_[$i]) . " value is not a criterion"
  2150. unless ref $_[$i] eq 'CODE';
  2151. push @criteria, $_[ $i++ ];
  2152. } else {
  2153. Carp::croak "param list to look_down ends in a key!" if $i == $#_;
  2154. push @criteria, [ scalar($_[0]->_fold_case($_[$i])),
  2155. defined($_[$i+1])
  2156. ? ( lc( $_[$i+1] ), ref( $_[$i+1] ) )
  2157. # yes, leave that LC!
  2158. : undef
  2159. ];
  2160. $i += 2;
  2161. }
  2162. }
  2163. Carp::croak "No criteria?" unless @criteria;
  2164. my(@pile) = ($_[0]);
  2165. my(@matching, $val, $this);
  2166. Node:
  2167. while(defined($this = shift @pile)) {
  2168. # Yet another traverser implemented with merely iterative code.
  2169. foreach my $c (@criteria) {
  2170. if(ref($c) eq 'CODE') {
  2171. next Node unless $c->($this); # jump to the continue block
  2172. } else { # it's an attr-value pair
  2173. next Node # jump to the continue block
  2174. if # two values are unequal if:
  2175. (defined($val = $this->{ $c->[0] }))
  2176. ? (
  2177. !defined $c->[1] # actual is def, critval is undef => fail
  2178. or ref $val ne $c->[2]
  2179. # have unequal ref values => fail
  2180. or lc($val) ne $c->[1]
  2181. # have unequal lc string values => fail
  2182. )
  2183. : (defined $c->[1]) # actual is undef, critval is def => fail
  2184. }
  2185. }
  2186. # We make it this far only if all the criteria passed.
  2187. return $this unless wantarray;
  2188. push @matching, $this;
  2189. } continue {
  2190. unshift @pile, grep ref($_), @{$this->{'_content'} || $nillio};
  2191. }
  2192. return @matching if wantarray;
  2193. return;
  2194. }
  2195. =item $h->look_up( ...criteria... )
  2196. This is identical to $h->look_down, except that whereas $h->look_down
  2197. basically scans over the list:
  2198. ($h, $h->descendants)
  2199. $h->look_up instead scans over the list
  2200. ($h, $h->lineage)
  2201. So, for example, this returns all ancestors of $h (possibly including
  2202. $h itself) that are "td" elements with an "align" attribute with a
  2203. value of "right" (or "RIGHT", etc.):
  2204. $h->look_up("_tag", "td", "align", "right");
  2205. =cut
  2206. sub look_up {
  2207. ref($_[0]) or Carp::croak "look_up works only as an object method";
  2208. my @criteria;
  2209. for(my $i = 1; $i < @_;) {
  2210. Carp::croak "Can't use undef as an attribute name" unless defined $_[$i];
  2211. if(ref $_[$i]) {
  2212. Carp::croak "A " . ref($_[$i]) . " value is not a criterion"
  2213. unless ref $_[$i] eq 'CODE';
  2214. push @criteria, $_[ $i++ ];
  2215. } else {
  2216. Carp::croak "param list to look_up ends in a key!" if $i == $#_;
  2217. push @criteria, [ scalar($_[0]->_fold_case($_[$i])),
  2218. defined($_[$i+1])
  2219. ? ( lc( $_[$i+1] ), ref( $_[$i+1] ) )
  2220. : undef # Yes, leave that LC!
  2221. ];
  2222. $i += 2;
  2223. }
  2224. }
  2225. Carp::croak "No criteria?" unless @criteria;
  2226. my(@matching, $val);
  2227. my $this = $_[0];
  2228. Node:
  2229. while(1) {
  2230. # You'll notice that the code here is almost the same as for look_down.
  2231. foreach my $c (@criteria) {
  2232. if(ref($c) eq 'CODE') {
  2233. next Node unless $c->($this); # jump to the continue block
  2234. } else { # it's an attr-value pair
  2235. next Node # jump to the continue block
  2236. if # two values are unequal if:
  2237. (defined($val = $this->{ $c->[0] }))
  2238. ? (
  2239. !defined $c->[1] # actual is def, critval is undef => fail
  2240. or ref $val ne $c->[2]
  2241. # have unequal ref values => fail
  2242. or lc($val) ne $c->[1]
  2243. # have unequal lc string values => fail
  2244. )
  2245. : (defined $c->[1]) # actual is undef, critval is def => fail
  2246. }
  2247. }
  2248. # We make it this far only if all the criteria passed.
  2249. return $this unless wantarray;
  2250. push @matching, $this;
  2251. } continue {
  2252. last unless defined($this = $this->{'_parent'}) and ref $this;
  2253. }
  2254. return @matching if wantarray;
  2255. return;
  2256. }
  2257. #--------------------------------------------------------------------------
  2258. =item $h->traverse(...options...)
  2259. Lengthy discussion of HTML::Element's unnecessary and confusing
  2260. C<traverse> method has been moved to a separate file:
  2261. L<HTML::Element::traverse>
  2262. =item $h->attr_get_i('attribute')
  2263. In list context, returns a list consisting of the values of the given
  2264. attribute for $self and for all its ancestors starting from $self and
  2265. working its way up. Nodes with no such attribute are skipped.
  2266. ("attr_get_i" stands for "attribute get, with inheritance".)
  2267. In scalar context, returns the first such value, or undef if none.
  2268. Consider a document consisting of:
  2269. <html lang='i-klingon'>
  2270. <head><title>Pati Pata</title></head>
  2271. <body>
  2272. <h1 lang='la'>Stuff</h1>
  2273. <p lang='es-MX' align='center'>
  2274. Foo bar baz <cite>Quux</cite>.
  2275. </p>
  2276. <p>Hooboy.</p>
  2277. </body>
  2278. </html>
  2279. If $h is the "cite" element, $h->attr_get_i("lang") in list context
  2280. will return the list ('es-MX', 'i-klingon'). In scalar context, it
  2281. will return the value 'es-MX'.
  2282. If you call with multiple attribute names...
  2283. =item $h->attr_get_i('a1', 'a2', 'a3')
  2284. ...in list context, this will return a list consisting of
  2285. the values of these attributes which exist in $self and its ancestors.
  2286. In scalar context, this returns the first value (i.e., the value of
  2287. the first existing attribute from the first element that has
  2288. any of the attributes listed). So, in the above example,
  2289. $h->attr_get_i('lang', 'align');
  2290. will return:
  2291. ('es-MX', 'center', 'i-klingon') # in list context
  2292. or
  2293. 'es-MX' # in scalar context.
  2294. But note that this:
  2295. $h->attr_get_i('align', 'lang');
  2296. will return:
  2297. ('center', 'es-MX', 'i-klingon') # in list context
  2298. or
  2299. 'center' # in scalar context.
  2300. =cut
  2301. sub attr_get_i {
  2302. if(@_ > 2) {
  2303. my $self = shift;
  2304. Carp::croak "No attribute names can be undef!"
  2305. if grep !defined($_), @_;
  2306. my @attributes = $self->_fold_case(@_);
  2307. if(wantarray) {
  2308. my @out;
  2309. foreach my $x ($self, $self->lineage) {
  2310. push @out, map { exists($x->{$_}) ? $x->{$_} : () } @attributes;
  2311. }
  2312. return @out;
  2313. } else {
  2314. foreach my $x ($self, $self->lineage) {
  2315. foreach my $attribute (@attributes) {
  2316. return $x->{$attribute} if exists $x->{$attribute}; # found
  2317. }
  2318. }
  2319. return undef; # never found
  2320. }
  2321. } else {
  2322. # Single-attribute search. Simpler, most common, so optimize
  2323. # for the most common case
  2324. Carp::croak "Attribute name must be a defined value!" unless defined $_[1];
  2325. my $self = $_[0];
  2326. my $attribute = $self->_fold_case($_[1]);
  2327. if(wantarray) { # list context
  2328. return
  2329. map {
  2330. exists($_->{$attribute}) ? $_->{$attribute} : ()
  2331. } $self, $self->lineage;
  2332. ;
  2333. } else { # scalar context
  2334. foreach my $x ($self, $self->lineage) {
  2335. return $x->{$attribute} if exists $x->{$attribute}; # found
  2336. }
  2337. return undef; # never found
  2338. }
  2339. }
  2340. }
  2341. #--------------------------------------------------------------------------
  2342. =item $h->tagname_map()
  2343. Scans across C<$h> and all its descendants, and makes a hash (a
  2344. reference to which is returned) where each entry consists of a key
  2345. that's a tag name, and a value that's a reference to a list to all
  2346. elements that have that tag name. I.e., this method returns:
  2347. {
  2348. # Across $h and all descendants...
  2349. 'a' => [ ...list of all 'a' elements... ],
  2350. 'em' => [ ...list of all 'em' elements... ],
  2351. 'img' => [ ...list of all 'img' elements... ],
  2352. }
  2353. (There are entries in the hash for only those tagnames that occur
  2354. at/under C<$h> -- so if there's no "img" elements, there'll be no
  2355. "img" entry in the hashr(ref) returned.)
  2356. Example usage:
  2357. my $map_r = $h->tagname_map();
  2358. my @heading_tags = sort grep m/^h\d$/s, keys %$map_r;
  2359. if(@heading_tags) {
  2360. print "Heading levels used: @heading_tags\n";
  2361. } else {
  2362. print "No headings.\n"
  2363. }
  2364. =cut
  2365. sub tagname_map {
  2366. my(@pile) = $_[0]; # start out the to-do stack for the traverser
  2367. Carp::croak "find_by_tag_name can be called only as an object method"
  2368. unless ref $pile[0];
  2369. my(%map, $this_tag, $this);
  2370. while(@pile) {
  2371. $this_tag = ''
  2372. unless defined(
  2373. $this_tag = (
  2374. $this = shift @pile
  2375. )->{'_tag'}
  2376. )
  2377. ; # dance around the strange case of having an undef tagname.
  2378. push @{ $map{$this_tag} ||= [] }, $this; # add to map
  2379. unshift @pile, grep ref($_), @{$this->{'_content'} || next}; # traverse
  2380. }
  2381. return \%map;
  2382. }
  2383. #--------------------------------------------------------------------------
  2384. =item $h->extract_links() or $h->extract_links(@wantedTypes)
  2385. Returns links found by traversing the element and all of its children
  2386. and looking for attributes (like "href" in an "a" element, or "src" in
  2387. an "img" element) whose values represent links. The return value is a
  2388. I<reference> to an array. Each element of the array is reference to
  2389. an array with I<four> items: the link-value, the element that has the
  2390. attribute with that link-value, and the name of that attribute, and
  2391. the tagname of that element.
  2392. (Example: C<['http://www.suck.com/',> I<$elem_obj> C<, 'href', 'a']>.)
  2393. You may or may not end up using the
  2394. element itself -- for some purposes, you may use only the link value.
  2395. You might specify that you want to extract links from just some kinds
  2396. of elements (instead of the default, which is to extract links from
  2397. I<all> the kinds of elements known to have attributes whose values
  2398. represent links). For instance, if you want to extract links from
  2399. only "a" and "img" elements, you could code it like this:
  2400. for (@{ $e->extract_links('a', 'img') }) {
  2401. my($link, $element, $attr, $tag) = @$_;
  2402. print
  2403. "Hey, there's a $tag that links to "
  2404. $link, ", in its $attr attribute, at ",
  2405. $element->address(), ".\n";
  2406. }
  2407. =cut
  2408. sub extract_links
  2409. {
  2410. my $start = shift;
  2411. my %wantType;
  2412. @wantType{$start->_fold_case(@_)} = (1) x @_; # if there were any
  2413. my $wantType = scalar(@_);
  2414. my @links;
  2415. # TODO: add xml:link?
  2416. my($link_attrs, $tag, $self, $val); # scratch for each iteration
  2417. $start->traverse(
  2418. [
  2419. sub { # pre-order call only
  2420. $self = $_[0];
  2421. $tag = $self->{'_tag'};
  2422. return 1 if $wantType && !$wantType{$tag}; # if we're selective
  2423. if(defined( $link_attrs = $HTML::Element::linkElements{$tag} )) {
  2424. # If this is a tag that has any link attributes,
  2425. # look over possibly present link attributes,
  2426. # saving the value, if found.
  2427. for (ref($link_attrs) ? @$link_attrs : $link_attrs) {
  2428. if(defined( $val = $self->attr($_) )) {
  2429. push(@links, [$val, $self, $_, $tag])
  2430. }
  2431. }
  2432. }
  2433. 1; # return true, so we keep recursing
  2434. },
  2435. undef
  2436. ],
  2437. 1, # ignore text nodes
  2438. );
  2439. \@links;
  2440. }
  2441. #--------------------------------------------------------------------------
  2442. =item $h->same_as($i)
  2443. Returns true if $h and $i are both elements representing the same tree
  2444. of elements, each with the same tag name, with the same explicit
  2445. attributes (i.e., not counting attributes whose names start with "_"),
  2446. and with the same content (textual, comments, etc.).
  2447. Sameness of descendant elements is tested, recursively, with
  2448. C<$child1-E<gt>same_as($child_2)>, and sameness of text segments is tested
  2449. with C<$segment1 eq $segment2>.
  2450. =cut
  2451. sub same_as {
  2452. die "same_as() takes only one argument: \$h->same_as(\$i)" unless @_ == 2;
  2453. my($h,$i) = @_[0,1];
  2454. die "same_as() can be called only as an object method" unless ref $h;
  2455. return 0 unless defined $i and ref $i;
  2456. # An element can't be same_as anything but another element!
  2457. # They needn't be of the same class, tho.
  2458. return 1 if $h eq $i;
  2459. # special (if rare) case: anything is the same as... itself!
  2460. # assumes that no content lists in/under $h or $i contain subsequent
  2461. # text segments, like: ['foo', ' bar']
  2462. # compare attributes now.
  2463. #print "Comparing tags of $h and $i...\n";
  2464. return 0 unless $h->{'_tag'} eq $i->{'_tag'};
  2465. # only significant attribute whose name starts with "_"
  2466. #print "Comparing attributes of $h and $i...\n";
  2467. # Compare attributes, but only the real ones.
  2468. {
  2469. # Bear in mind that the average element has very few attributes,
  2470. # and that element names are rather short.
  2471. # (Values are a different story.)
  2472. my @keys_h = sort grep {length $_ and substr($_,0,1) ne '_'} keys %$h;
  2473. my @keys_i = sort grep {length $_ and substr($_,0,1) ne '_'} keys %$i;
  2474. #print '<', join(',', @keys_h), '> =?= <', join(',', @keys_i), ">\n";
  2475. return 0 unless @keys_h == @keys_i;
  2476. # different number of real attributes? they're different.
  2477. for(my $x = 0; $x < @keys_h; ++$x) {
  2478. return 0 unless
  2479. $keys_h[$x] eq $keys_i[$x] and # same key name
  2480. $h->{$keys_h[$x]} eq $i->{$keys_h[$x]}; # same value
  2481. # Should this test for definedness on values?
  2482. # People shouldn't be putting undef in attribute values, I think.
  2483. }
  2484. }
  2485. #print "Comparing children of $h and $i...\n";
  2486. my $hcl = $h->{'_content'} || [];
  2487. my $icl = $i->{'_content'} || [];
  2488. return 0 unless @$hcl == @$icl;
  2489. # different numbers of children? they're different.
  2490. if(@$hcl) {
  2491. # compare each of the children:
  2492. for(my $x = 0; $x < @$hcl; ++$x) {
  2493. if(ref $hcl->[$x]) {
  2494. return 0 unless ref($icl->[$x]);
  2495. # an element can't be the same as a text segment
  2496. # Both elements:
  2497. return 0 unless $hcl->[$x]->same_as($icl->[$x]); # RECURSE!
  2498. } else {
  2499. return 0 if ref($icl->[$x]);
  2500. # a text segment can't be the same as an element
  2501. # Both text segments:
  2502. return 0 unless $hcl->[$x] eq $icl->[$x];
  2503. }
  2504. }
  2505. }
  2506. return 1; # passed all the tests!
  2507. }
  2508. #--------------------------------------------------------------------------
  2509. =item $h = HTML::Element->new_from_lol(ARRAYREF)
  2510. Resursively constructs a tree of nodes, based on the (non-cyclic)
  2511. data structure represented by ARRAYREF, where that is a reference
  2512. to an array of arrays (of arrays (of arrays (etc.))).
  2513. In each arrayref in that structure, different kinds of values are
  2514. treated as follows:
  2515. =over
  2516. =item * Arrayrefs
  2517. Arrayrefs are considered to
  2518. designate a sub-tree representing children for the node constructed
  2519. from the current arrayref.
  2520. =item * Hashrefs
  2521. Hashrefs are considered to contain
  2522. attribute-value pairs to add to the element to be constructed from
  2523. the current arrayref
  2524. =item * Text segments
  2525. Text segments at the start of any arrayref
  2526. will be considered to specify the name of the element to be
  2527. constructed from the current araryref; all other text segments will
  2528. be considered to specify text segments as children for the current
  2529. arrayref.
  2530. =item * Elements
  2531. Existing element objects are either inserted into the treelet
  2532. constructed, or clones of them are. That is, when the lol-tree is
  2533. being traversed and elements constructed based what's in it, if
  2534. an existing element object is found, if it has no parent, then it is
  2535. added directly to the treelet constructed; but if it has a parent,
  2536. then C<$that_node-E<gt>clone> is added to the treelet at the
  2537. appropriate place.
  2538. =back
  2539. An example will hopefully make this more obvious:
  2540. my $h = HTML::Element->new_from_lol(
  2541. ['html',
  2542. ['head',
  2543. [ 'title', 'I like stuff!' ],
  2544. ],
  2545. ['body',
  2546. {'lang', 'en-JP', _implicit => 1},
  2547. 'stuff',
  2548. ['p', 'um, p < 4!', {'class' => 'par123'}],
  2549. ['div', {foo => 'bar'}, '123'],
  2550. ]
  2551. ]
  2552. );
  2553. $h->dump;
  2554. Will print this:
  2555. <html> @0
  2556. <head> @0.0
  2557. <title> @0.0.0
  2558. "I like stuff!"
  2559. <body lang="en-JP"> @0.1 (IMPLICIT)
  2560. "stuff"
  2561. <p class="par123"> @0.1.1
  2562. "um, p < 4!"
  2563. <div foo="bar"> @0.1.2
  2564. "123"
  2565. And printing $h->as_HTML will give something like:
  2566. <html><head><title>I like stuff!</title></head>
  2567. <body lang="en-JP">stuff<p class="par123">um, p &lt; 4!
  2568. <div foo="bar">123</div></body></html>
  2569. You can even do fancy things with C<map>:
  2570. $body->push_content(
  2571. # push_content implicitly calls new_from_lol on arrayrefs...
  2572. ['br'],
  2573. ['blockquote',
  2574. ['h2', 'Pictures!'],
  2575. map ['p', $_],
  2576. $body2->look_down("_tag", "img"),
  2577. # images, to be copied from that other tree.
  2578. ],
  2579. # and more stuff:
  2580. ['ul',
  2581. map ['li', ['a', {'href'=>"$_.png"}, $_ ] ],
  2582. qw(Peaches Apples Pears Mangos)
  2583. ],
  2584. );
  2585. =cut
  2586. sub new_from_lol {
  2587. my $class = ref($_[0]) || $_[0];
  2588. # calling as an object method is just the same as ref($h)->new_from_lol(...)
  2589. my $lol = $_[1];
  2590. Carp::croak "first argument to new_from_lol mustn't be undef!"
  2591. unless defined $lol;
  2592. Carp::croak
  2593. "first argument to new_from_lol must be an arrayref, not \"$lol\"!"
  2594. unless ref($lol) eq 'ARRAY';
  2595. my @ancestor_lols;
  2596. # So we can make sure there's no cyclicities in this lol.
  2597. # That would be perverse, but one never knows.
  2598. my($sub, $k, $v, $node); # last three are scratch values
  2599. $sub = sub {
  2600. #print "Building for $_[0]\n";
  2601. my $lol = $_[0];
  2602. return unless @$lol;
  2603. my(@attributes, @children);
  2604. Carp::croak "Cyclicity detected in source LOL tree, around $lol?!?"
  2605. if grep($_ eq $lol, @ancestor_lols);
  2606. push @ancestor_lols, $lol;
  2607. my $tag_name = 'null';
  2608. # Recursion in in here:
  2609. for(my $i = 0; $i < @$lol; ++$i) { # Iterate over children
  2610. if(ref($lol->[$i]) eq 'ARRAY') { # subtree: most common thing in loltree
  2611. push @children, $sub->($lol->[$i]);
  2612. } elsif(! ref($lol->[$i])) {
  2613. if($i == 0) { # name
  2614. $tag_name = $lol->[$i];
  2615. } else { # text segment child
  2616. push @children, $lol->[$i];
  2617. }
  2618. } elsif(ref($lol->[$i]) eq 'HASH') { # attribute hashref
  2619. keys %{$lol->[$i]}; # reset the each-counter, just in case
  2620. while(($k,$v) = each %{$lol->[$i]}) {
  2621. push @attributes, $class->_fold_case($k), $v
  2622. unless $k eq '_name' or $k eq '_content' or $k eq '_parent';
  2623. # enforce /some/ sanity!
  2624. }
  2625. } elsif(UNIVERSAL::isa($lol->[$i], __PACKAGE__)) {
  2626. if($lol->[$i]->{'_parent'}) { # if claimed
  2627. #print "About to clone ", $lol->[$i], "\n";
  2628. push @children, $lol->[$i]->clone();
  2629. } else {
  2630. push @children, $lol->[$i]; # if unclaimed...
  2631. #print "Claiming ", $lol->[$i], "\n";
  2632. $lol->[$i]->{'_parent'} = 1; # claim it NOW
  2633. # This WILL be replaced by the correct value once we actually
  2634. # construct the parent, just after the end of this loop...
  2635. }
  2636. } else {
  2637. Carp::croak "new_from_lol doesn't handle references of type "
  2638. . ref($lol->[$i]);
  2639. }
  2640. }
  2641. pop @ancestor_lols;
  2642. $node = $class->new($tag_name);
  2643. #print "Children: @children\n";
  2644. if($class eq __PACKAGE__) { # Special-case it, for speed:
  2645. #print "Special cased / [@attributes]\n";
  2646. %$node = (%$node, @attributes) if @attributes;
  2647. #print join(' ', $node, ' ' , map("<$_>", %$node), "\n");
  2648. if(@children) {
  2649. $node->{'_content'} = \@children;
  2650. foreach my $c (@children) { $c->{'_parent'} = $node if ref $c }
  2651. }
  2652. } else { # Do it the clean way...
  2653. #print "Done neatly\n";
  2654. while(@attributes) { $node->attr(splice @attributes,0,2) }
  2655. $node->push_content(@children) if @children;
  2656. }
  2657. return $node;
  2658. };
  2659. $node = $sub->($lol);
  2660. undef $sub; # so it won't be in its own frame, so its refcount can hit 0
  2661. return $node;
  2662. }
  2663. #--------------------------------------------------------------------------
  2664. =item $h->objectify_text()
  2665. This turns any text nodes under $h from mere text segments (strings)
  2666. into real objects, pseudo-elements with a tag-name of "~text", and the
  2667. actual text content in an attribute called "text". (For a discussion
  2668. of pseudo-elements, see the "tag" method, far above.) This method is
  2669. provided because, for some purposes, it is convenient or necessary to
  2670. be able, for a given text node, to ask what element is its parent; and
  2671. clearly this is not possible if a node is just a text string.
  2672. Note that these "~text" objects are not recognized as text nodes by
  2673. methods like as_text. Presumably you will want to call
  2674. $h->objectify_text, perform whatever task that you needed that for,
  2675. and then call $h->deobjectify_text before calling anything like
  2676. $h->as_text.
  2677. This method is experimental, and you are encouraged to report any
  2678. problems you encounter with it.
  2679. =item $h->deobjectify_text()
  2680. This undoes the effect of $h->objectify_text. That is, it takes any
  2681. "~text" pseudo-elements in the tree at/under $h, and deletes each one,
  2682. replacing each with the content of its "text" attribute.
  2683. Note that if $h itself is a "~text" pseudo-element, it will be
  2684. destroyed -- a condition you may need to treat specially in your
  2685. calling code (since it means you can't very well do anything with $h
  2686. after that). So that you can detect that condition, if $h is itself a
  2687. "~text" pseudo-element, then this method returns the value of the
  2688. "text" attribute, which should be a defined value; in all other cases,
  2689. it returns undef.
  2690. This method is experimental, and you are encouraged to report any
  2691. problems you encounter with it.
  2692. (This method assumes that no "~text" pseudo-element has any children.)
  2693. =cut
  2694. sub objectify_text {
  2695. my(@stack) = ($_[0]);
  2696. my($this);
  2697. while(@stack) {
  2698. foreach my $c (@{( $this = shift @stack )->{'_content'}}) {
  2699. if(ref($c)) {
  2700. unshift @stack, $c; # visit it later.
  2701. } else {
  2702. $c = ( $this->{'_element_class'} || __PACKAGE__
  2703. )->new('~text', 'text' => $c, '_parent' => $this);
  2704. }
  2705. }
  2706. }
  2707. return;
  2708. }
  2709. sub deobjectify_text {
  2710. my(@stack) = ($_[0]);
  2711. my($old_node);
  2712. if( $_[0]{'_tag'} eq '~text') { # special case
  2713. # Puts the $old_node variable to a different purpose
  2714. if($_[0]{'_parent'}) {
  2715. $_[0]->replace_with( $old_node = delete $_[0]{'text'} )->delete;
  2716. } else { # well, that's that, then!
  2717. $old_node = delete $_[0]{'text'};
  2718. }
  2719. if(ref($_[0]) eq __PACKAGE__) { # common case
  2720. %{$_[0]} = (); # poof!
  2721. } else {
  2722. # play nice:
  2723. delete $_[0]{'_parent'};
  2724. $_[0]->delete;
  2725. }
  2726. return '' unless defined $old_node; # sanity!
  2727. return $old_node;
  2728. }
  2729. while(@stack) {
  2730. foreach my $c (@{(shift @stack)->{'_content'}}) {
  2731. if(ref($c)) {
  2732. if($c->{'_tag'} eq '~text') {
  2733. $c = ($old_node = $c)->{'text'};
  2734. if(ref($old_node) eq __PACKAGE__) { # common case
  2735. %$old_node = (); # poof!
  2736. } else {
  2737. # play nice:
  2738. delete $old_node->{'_parent'};
  2739. $old_node->delete;
  2740. }
  2741. } else {
  2742. unshift @stack, $c; # visit it later.
  2743. }
  2744. }
  2745. }
  2746. }
  2747. return undef;
  2748. }
  2749. #--------------------------------------------------------------------------
  2750. =item $h->number_lists()
  2751. For every UL, OL, DIR, and MENU element at/under $h, this sets a
  2752. "_bullet" attribute for every child LI element. For LI children of an
  2753. OL, the "_bullet" attribute's value will be something like "4.", "d.",
  2754. "D.", "IV.", or "iv.", depending on the OL element's "type" attribute.
  2755. LI children of a UL, DIR, or MENU get their "_bullet" attribute set
  2756. to "*".
  2757. There should be no other LIs (i.e., except as children of OL, UL, DIR,
  2758. or MENU elements), and if there are, they are unaffected.
  2759. =cut
  2760. {
  2761. # The next three subs are basically copied from my module Number::Latin,
  2762. # based on a one-liner by Abigail. Yes, I could simply require that
  2763. # module, and a roman numeral module too, but really, HTML-Tree already
  2764. # has enough dependecies as it is; and anyhow, I don't need the functions
  2765. # that do latin2int or roman2int.
  2766. sub _int2latin {
  2767. return undef unless defined $_[0];
  2768. return '0' if $_[0] < 1 and $_[0] > -1;
  2769. return '-' . _i2l( abs int $_[0] ) if $_[0] <= -1; # tolerate negatives
  2770. return _i2l( int $_[0] );
  2771. }
  2772. sub _int2LATIN {
  2773. # just the above plus uc
  2774. return undef unless defined $_[0];
  2775. return '0' if $_[0] < 1 and $_[0] > -1;
  2776. return '-' . uc(_i2l( abs int $_[0] )) if $_[0] <= -1; # tolerate negs
  2777. return uc(_i2l( int $_[0] ));
  2778. }
  2779. my @alpha = ('', 'a' .. 'z');
  2780. sub _i2l { # the real work
  2781. my $int = $_[0] || return "";
  2782. _i2l(int (($int - 1) / 26)) . $alpha[$int % 26]; # yes, recursive
  2783. }
  2784. }
  2785. {
  2786. # And now, some much less impressive Roman numerals code:
  2787. my(@i) = ('', qw(I II III IV V VI VII VIII IX));
  2788. my(@x) = ('', qw(X XX XXX XL L LX LXX LXXX XC));
  2789. my(@c) = ('', qw(C CC CCC CD D DC DCC DCCC CM));
  2790. my(@m) = ('', qw(M MM MMM));
  2791. sub _int2ROMAN {
  2792. my($i, $pref);
  2793. return '0' if 0 == ($i = int($_[0] || 0)); # zero is a special case
  2794. return $i + 0 if $i <= -4000 or $i >= 4000;
  2795. # Because over 3999 would require non-ASCII chars, like D-with-)-inside
  2796. if($i < 0) { # grumble grumble tolerate negatives grumble
  2797. $pref = '-'; $i = abs($i);
  2798. } else {
  2799. $pref = ''; # normal case
  2800. }
  2801. my($x,$c,$m) = (0,0,0);
  2802. if( $i >= 10) { $x = $i / 10; $i %= 10;
  2803. if( $x >= 10) { $c = $x / 10; $x %= 10;
  2804. if( $c >= 10) { $m = $c / 10; $c %= 10; } } }
  2805. #print "m$m c$c x$x i$i\n";
  2806. return join('', $pref, $m[$m], $c[$c], $x[$x], $i[$i] );
  2807. }
  2808. sub _int2roman { lc(_int2ROMAN($_[0])) }
  2809. }
  2810. sub _int2int { $_[0] } # dummy
  2811. %list_type_to_sub = (
  2812. 'I' => \&_int2ROMAN, 'i' => \&_int2roman,
  2813. 'A' => \&_int2LATIN, 'a' => \&_int2latin,
  2814. '1' => \&_int2int,
  2815. );
  2816. sub number_lists {
  2817. my(@stack) = ($_[0]);
  2818. my($this, $tag, $counter, $numberer); # scratch
  2819. while(@stack) { # yup, pre-order-traverser idiom
  2820. if(($tag = ($this = shift @stack)->{'_tag'}) eq 'ol') {
  2821. # Prep some things:
  2822. $counter = (($this->{'start'} || '') =~ m<^\s*(\d{1,7})\s*$>s) ? $1 : 1;
  2823. $numberer = $list_type_to_sub{ $this->{'type'} }
  2824. || $list_type_to_sub{'1'};
  2825. # Immeditately iterate over all children
  2826. foreach my $c (@{ $this->{'_content'} || next}) {
  2827. next unless ref $c;
  2828. unshift @stack, $c;
  2829. if($c->{'_tag'} eq 'li') {
  2830. $counter = $1 if(($c->{'value'} || '') =~ m<^\s*(\d{1,7})\s*$>s);
  2831. $c->{'_bullet'} = $numberer->($counter) . '.';
  2832. ++$counter;
  2833. }
  2834. }
  2835. } elsif($tag eq 'ul' or $tag eq 'dir' or $tag eq 'menu') {
  2836. # Immeditately iterate over all children
  2837. foreach my $c (@{ $this->{'_content'} || next}) {
  2838. next unless ref $c;
  2839. unshift @stack, $c;
  2840. $c->{'_bullet'} = '*' if $c->{'_tag'} eq 'li';
  2841. }
  2842. } else {
  2843. foreach my $c (@{ $this->{'_content'} || next}) {
  2844. unshift @stack, $c if ref $c;
  2845. }
  2846. }
  2847. }
  2848. return;
  2849. }
  2850. #--------------------------------------------------------------------------
  2851. =item $h->has_insane_linkage
  2852. This method is for testing whether this element or the elements
  2853. under it have linkage attributes (_parent and _content) whose values
  2854. are deeply aberrant: if there are undefs in a content list; if an
  2855. element appears in the content lists of more than one element;
  2856. if the _parent attribute of an element doesn't match its actual
  2857. parent; or if an element appears as its own descendant (i.e.,
  2858. if there is a cyclicity in the tree).
  2859. This returns empty list (or false, in scalar context) if the subtree's
  2860. linkage methods are sane; otherwise it returns two items (or true, in
  2861. scalar context): the element where the error occurred, and a string
  2862. describing the error.
  2863. This method is provided is mainly for debugging and troubleshooting --
  2864. it should be I<quite impossible> for any document constructed via
  2865. HTML::TreeBuilder to parse into a non-sane tree (since it's not
  2866. the content of the tree per se that's in question, but whether
  2867. the tree in memory was properly constructed); and it I<should> be
  2868. impossible for you to produce an insane tree just thru reasonable
  2869. use of normal documented structure-modifying methods. But if you're
  2870. constructing your own trees, and your program is going into infinite
  2871. loops as during calls to traverse() or any of the secondary
  2872. structural methods, as part of debugging, consider calling is_insane
  2873. on the tree.
  2874. =cut
  2875. sub has_insane_linkage {
  2876. my @pile = ($_[0]);
  2877. my($c, $i, $p, $this); # scratch
  2878. # Another iterative traverser; this time much simpler because
  2879. # only in pre-order:
  2880. my %parent_of = ($_[0], 'TOP-OF-SCAN');
  2881. while(@pile) {
  2882. $this = shift @pile;
  2883. $c = $this->{'_content'} || next;
  2884. return($this, "_content attribute is true but nonref.")
  2885. unless ref($c) eq 'ARRAY';
  2886. next unless @$c;
  2887. for($i = 0; $i < @$c; ++$i) {
  2888. return($this, "Child $i is undef")
  2889. unless defined $c->[$i];
  2890. if(ref($c->[$i])) {
  2891. return($c->[$i], "appears in its own content list")
  2892. if $c->[$i] eq $this;
  2893. return($c->[$i],
  2894. "appears twice in the tree: once under $this, once under $parent_of{$c->[$i]}"
  2895. )
  2896. if exists $parent_of{$c->[$i]};
  2897. $parent_of{$c->[$i]} = ''.$this;
  2898. # might as well just use the stringification of it.
  2899. return($c->[$i], "_parent attribute is wrong (not defined)")
  2900. unless defined($p = $c->[$i]{'_parent'});
  2901. return($c->[$i], "_parent attribute is wrong (nonref)")
  2902. unless ref($p);
  2903. return($c->[$i],
  2904. "_parent attribute is wrong (is $p; should be $this)"
  2905. )
  2906. unless $p eq $this;
  2907. }
  2908. }
  2909. unshift @pile, grep ref($_), @$c;
  2910. # queue up more things on the pile stack
  2911. }
  2912. return; #okay
  2913. }
  2914. #==========================================================================
  2915. sub _asserts_fail { # to be run on trusted documents only
  2916. my(@pile) = ($_[0]);
  2917. my(@errors, $this, $id, $assert, $parent, $rv);
  2918. while(@pile) {
  2919. $this = shift @pile;
  2920. if(defined($assert = $this->{'assert'})) {
  2921. $id = ($this->{'id'} ||= $this->address); # don't use '0' as an ID, okay?
  2922. unless(ref($assert)) {
  2923. package main;
  2924. $assert = $this->{'assert'} = (
  2925. $assert =~ m/\bsub\b/ ? eval($assert) : eval("sub { $assert\n}")
  2926. );
  2927. if($@) {
  2928. push @errors, [$this, "assertion at $id broke in eval: $@"];
  2929. $assert = $this->{'assert'} = sub {};
  2930. }
  2931. }
  2932. $parent = $this->{'_parent'};
  2933. $rv = undef;
  2934. eval {
  2935. $rv =
  2936. $assert->(
  2937. $this, $this->{'_tag'}, $this->{'_id'}, # 0,1,2
  2938. $parent ? ($parent, $parent->{'_tag'}, $parent->{'id'}) : () # 3,4,5
  2939. )
  2940. };
  2941. if($@) {
  2942. push @errors, [$this, "assertion at $id died: $@"];
  2943. } elsif(!$rv) {
  2944. push @errors, [$this, "assertion at $id failed"]
  2945. }
  2946. # else OK
  2947. }
  2948. push @pile, grep ref($_), @{$this->{'_content'} || next};
  2949. }
  2950. return @errors;
  2951. }
  2952. #==========================================================================
  2953. 1;
  2954. __END__
  2955. =back
  2956. =head1 BUGS
  2957. * If you want to free the memory associated with a tree built of
  2958. HTML::Element nodes, then you will have to delete it explicitly.
  2959. See the $h->delete method, above.
  2960. * There's almost nothing to stop you from making a "tree" with
  2961. cyclicities (loops) in it, which could, for example, make the
  2962. traverse method go into an infinite loop. So don't make
  2963. cyclicities! (If all you're doing is parsing HTML files,
  2964. and looking at the resulting trees, this will never be a problem
  2965. for you.)
  2966. * There's no way to represent comments or processing directives
  2967. in a tree with HTML::Elements. Not yet, at least.
  2968. * There's (currently) nothing to stop you from using an undefined
  2969. value as a text segment. If you're running under C<perl -w>, however,
  2970. this may make HTML::Element's code produce a slew of warnings.
  2971. =head1 NOTES ON SUBCLASSING
  2972. You are welcome to derive subclasses from HTML::Element, but you
  2973. should be aware that the code in HTML::Element makes certain
  2974. assumptions about elements (and I'm using "element" to mean ONLY an
  2975. object of class HTML::Element, or of a subclass of HTML::Element):
  2976. * The value of an element's _parent attribute must either be undef or
  2977. otherwise false, or must be an element.
  2978. * The value of an element's _content attribute must either be undef or
  2979. otherwise false, or a reference to an (unblessed) array. The array
  2980. may be empty; but if it has items, they must ALL be either mere
  2981. strings (text segments), or elements.
  2982. * The value of an element's _tag attribute should, at least, be a
  2983. string of printable characters.
  2984. Moreover, bear these rules in mind:
  2985. * Do not break encapsulation on objects. That is, access their
  2986. contents only thru $obj->attr or more specific methods.
  2987. * You should think twice before completely overriding any of the
  2988. methods that HTML::Element provides. (Overriding with a method that
  2989. calls the superclass method is not so bad, tho.)
  2990. =head1 SEE ALSO
  2991. L<HTML::Tree>; L<HTML::TreeBuilder>; L<HTML::AsSubs>; L<HTML::Tagset>;
  2992. and, for the morbidly curious, L<HTML::Element::traverse>.
  2993. =head1 COPYRIGHT
  2994. Copyright 1995-1998 Gisle Aas, 1999-2001 Sean M. Burke.
  2995. This library is free software; you can redistribute it and/or
  2996. modify it under the same terms as Perl itself.
  2997. This program is distributed in the hope that it will be useful, but
  2998. without any warranty; without even the implied warranty of
  2999. merchantability or fitness for a particular purpose.
  3000. =head1 AUTHOR
  3001. Original author Gisle Aas E<lt>gisle@aas.noE<gt>; current maintainer
  3002. Sean M. Burke, E<lt>sburke@cpan.orgE<gt>
  3003. =cut
  3004. If you've read the code this far, you need some hummus:
  3005. EASY HUMMUS
  3006. (Adapted from a recipe by Ralph Baccash (1937-2000))
  3007. INGREDIENTS:
  3008. - The juice of two smallish lemons
  3009. (adjust to taste, and depending on how juicy the lemons are)
  3010. - 6 tablespoons of tahini
  3011. - 4 tablespoons of olive oil
  3012. - 5 big cloves of garlic, chopped fine
  3013. - salt to taste
  3014. - pepper to taste
  3015. - onion powder to taste
  3016. - pinch of coriander powder (optional)
  3017. - big pinch of cumin
  3018. Then:
  3019. - 2 16oz cans of garbanzo beans
  3020. - parsley, or Italian parsley
  3021. - a bit more olive oil
  3022. PREPARATION:
  3023. Drain one of the cans of garbanzos, discarding the juice. Drain the
  3024. other, reserving the juice.
  3025. Peel the garbanzos (just pressing on each a bit until the skin slides
  3026. off). It will take time to peel all the garbanzos. It's optional, but
  3027. it makes for a smoother hummus. Incidentally, peeling seems much
  3028. faster and easier if done underwater -- i.e., if the beans are in a
  3029. bowl under an inch or so of water.
  3030. Now, in a blender, combine everything in the above list, starting at the
  3031. top, stopping at (but including) the cumin. Add one-third of the can's
  3032. worth of the juice that you reserved. Blend very well. (For lack of a
  3033. blender, I've done okay using a Braun hand-mixer.)
  3034. Start adding the beans little by little, and keep blending, and
  3035. increasing speeds until very smooth. If you want to make the mix less
  3036. viscous, add more of the reserved juice. Adjust the seasoning as
  3037. needed.
  3038. Cover with chopped parsley, and a thin layer of olive oil. The parsley
  3039. is more or less optional, but the olive oil is necessary, to keep the
  3040. hummus from discoloring. Possibly sprinkle with paprika or red chile
  3041. flakes.
  3042. Serve at about room temperature, with warm pitas. Possible garnishes
  3043. include olives, peperoncini, tomato wedges.
  3044. Variations on this recipe consist of adding or substituting other
  3045. spices. The garbanzos, tahini, lemon juice, and oil are the only really
  3046. core ingredients, and note that their quantities are approximate.
  3047. For more good recipes along these lines, see:
  3048. Karaoglan, Aida. 1992. /Food for the Vegetarian/. Interlink Books,
  3049. New York. ISBN 1-56656-105-1.
  3050. http://www.amazon.com/exec/obidos/ASIN/1566561051/
  3051. # End