1package HTML::Parser;
2
3use strict;
4
5our $VERSION = '3.76';
6
7require HTML::Entities;
8
9require XSLoader;
10XSLoader::load('HTML::Parser', $VERSION);
11
12sub new
13{
14    my $class = shift;
15    my $self = bless {}, $class;
16    return $self->init(@_);
17}
18
19
20sub init
21{
22    my $self = shift;
23    $self->_alloc_pstate;
24
25    my %arg = @_;
26    my $api_version = delete $arg{api_version} || (@_ ? 3 : 2);
27    if ($api_version >= 4) {
28	require Carp;
29	Carp::croak("API version $api_version not supported " .
30		    "by HTML::Parser $VERSION");
31    }
32
33    if ($api_version < 3) {
34	# Set up method callbacks compatible with HTML-Parser-2.xx
35	$self->handler(text    => "text",    "self,text,is_cdata");
36	$self->handler(end     => "end",     "self,tagname,text");
37	$self->handler(process => "process", "self,token0,text");
38	$self->handler(start   => "start",
39		                  "self,tagname,attr,attrseq,text");
40
41	$self->handler(comment =>
42		       sub {
43			   my($self, $tokens) = @_;
44			   for (@$tokens) {
45			       $self->comment($_);
46			   }
47		       }, "self,tokens");
48
49	$self->handler(declaration =>
50		       sub {
51			   my $self = shift;
52			   $self->declaration(substr($_[0], 2, -1));
53		       }, "self,text");
54    }
55
56    if (my $h = delete $arg{handlers}) {
57	$h = {@$h} if ref($h) eq "ARRAY";
58	while (my($event, $cb) = each %$h) {
59	    $self->handler($event => @$cb);
60	}
61    }
62
63    # In the end we try to assume plain attribute or handler
64    while (my($option, $val) = each %arg) {
65	if ($option =~ /^(\w+)_h$/) {
66	    $self->handler($1 => @$val);
67	}
68        elsif ($option =~ /^(text|start|end|process|declaration|comment)$/) {
69	    require Carp;
70	    Carp::croak("Bad constructor option '$option'");
71        }
72	else {
73	    $self->$option($val);
74	}
75    }
76
77    return $self;
78}
79
80
81sub parse_file
82{
83    my($self, $file) = @_;
84    my $opened;
85    if (!ref($file) && ref(\$file) ne "GLOB") {
86        # Assume $file is a filename
87        local(*F);
88        open(F, "<", $file) || return undef;
89        binmode(F);  # should we? good for byte counts
90        $opened++;
91        $file = *F;
92    }
93    my $chunk = '';
94    while (read($file, $chunk, 512)) {
95        $self->parse($chunk) || last;
96    }
97    close($file) if $opened;
98    $self->eof;
99}
100
101
102sub netscape_buggy_comment  # legacy
103{
104    my $self = shift;
105    require Carp;
106    Carp::carp("netscape_buggy_comment() is deprecated.  " .
107        "Please use the strict_comment() method instead");
108    my $old = !$self->strict_comment;
109    $self->strict_comment(!shift) if @_;
110    return $old;
111}
112
113# set up method stubs
114sub text { }
115*start       = \&text;
116*end         = \&text;
117*comment     = \&text;
118*declaration = \&text;
119*process     = \&text;
120
1211;
122
123__END__
124
125
126=head1 NAME
127
128HTML::Parser - HTML parser class
129
130=head1 SYNOPSIS
131
132  use strict;
133  use warnings;
134  use HTML::Parser ();
135
136  # Create parser object
137  my $p = HTML::Parser->new(
138    api_version => 3,
139    start_h => [\&start, "tagname, attr"],
140    end_h   => [\&end,   "tagname"],
141    marked_sections => 1,
142  );
143
144  # Parse document text chunk by chunk
145  $p->parse($chunk1);
146  $p->parse($chunk2);
147  # ...
148  # signal end of document
149  $p->eof;
150
151  # Parse directly from file
152  $p->parse_file("foo.html");
153  # or
154  open(my $fh, "<:utf8", "foo.html") || die;
155  $p->parse_file($fh);
156
157=head1 DESCRIPTION
158
159Objects of the C<HTML::Parser> class will recognize markup and
160separate it from plain text (alias data content) in HTML
161documents.  As different kinds of markup and text are recognized, the
162corresponding event handlers are invoked.
163
164C<HTML::Parser> is not a generic SGML parser.  We have tried to
165make it able to deal with the HTML that is actually "out there", and
166it normally parses as closely as possible to the way the popular web
167browsers do it instead of strictly following one of the many HTML
168specifications from W3C.  Where there is disagreement, there is often
169an option that you can enable to get the official behaviour.
170
171The document to be parsed may be supplied in arbitrary chunks.  This
172makes on-the-fly parsing as documents are received from the network
173possible.
174
175If event driven parsing does not feel right for your application, you
176might want to use C<HTML::PullParser>.  This is an C<HTML::Parser>
177subclass that allows a more conventional program structure.
178
179
180=head1 METHODS
181
182The following method is used to construct a new C<HTML::Parser> object:
183
184=over
185
186=item $p = HTML::Parser->new( %options_and_handlers )
187
188This class method creates a new C<HTML::Parser> object and
189returns it.  Key/value argument pairs may be provided to assign event
190handlers or initialize parser options.  The handlers and parser
191options can also be set or modified later by the method calls described below.
192
193If a top level key is in the form "<event>_h" (e.g., "text_h") then it
194assigns a handler to that event, otherwise it initializes a parser
195option. The event handler specification value must be an array
196reference.  Multiple handlers may also be assigned with the 'handlers
197=> [%handlers]' option.  See examples below.
198
199If new() is called without any arguments, it will create a parser that
200uses callback methods compatible with version 2 of C<HTML::Parser>.
201See the section on "version 2 compatibility" below for details.
202
203The special constructor option 'api_version => 2' can be used to
204initialize version 2 callbacks while still setting other options and
205handlers.  The 'api_version => 3' option can be used if you don't want
206to set any options and don't want to fall back to v2 compatible
207mode.
208
209Examples:
210
211 $p = HTML::Parser->new(
212   api_version => 3,
213   text_h => [ sub {...}, "dtext" ]
214 );
215
216This creates a new parser object with a text event handler subroutine
217that receives the original text with general entities decoded.
218
219 $p = HTML::Parser->new(
220   api_version => 3,
221   start_h => [ 'my_start', "self,tokens" ]
222 );
223
224This creates a new parser object with a start event handler method
225that receives the $p and the tokens array.
226
227 $p = HTML::Parser->new(
228   api_version => 3,
229   handlers => {
230     text => [\@array, "event,text"],
231     comment => [\@array, "event,text"],
232   }
233 );
234
235This creates a new parser object that stores the event type and the
236original text in @array for text and comment events.
237
238=back
239
240The following methods feed the HTML document
241to the C<HTML::Parser> object:
242
243=over
244
245=item $p->parse( $string )
246
247Parse $string as the next chunk of the HTML document.  Handlers invoked should
248not attempt to modify the $string in-place until $p->parse returns.
249
250If an invoked event handler aborts parsing by calling $p->eof, then $p->parse()
251will return a FALSE value.  Otherwise the return value is a reference to the
252parser object ($p).
253
254=item $p->parse( $code_ref )
255
256If a code reference is passed as the argument to be parsed, then the
257chunks to be parsed are obtained by invoking this function repeatedly.
258Parsing continues until the function returns an empty (or undefined)
259result.  When this happens $p->eof is automatically signaled.
260
261Parsing will also abort if one of the event handlers calls $p->eof.
262
263The effect of this is the same as:
264
265  while (1) {
266    my $chunk = &$code_ref();
267    if (!defined($chunk) || !length($chunk)) {
268      $p->eof;
269      return $p;
270    }
271    $p->parse($chunk) || return undef;
272  }
273
274But it is more efficient as this loop runs internally in XS code.
275
276=item $p->parse_file( $file )
277
278Parse text directly from a file.  The $file argument can be a
279filename, an open file handle, or a reference to an open file
280handle.
281
282If $file contains a filename and the file can't be opened, then the
283method returns an undefined value and $! tells why it failed.
284Otherwise the return value is a reference to the parser object.
285
286If a file handle is passed as the $file argument, then the file will
287normally be read until EOF, but not closed.
288
289If an invoked event handler aborts parsing by calling $p->eof,
290then $p->parse_file() may not have read the entire file.
291
292On systems with multi-byte line terminators, the values passed for the
293offset and length argspecs may be too low if parse_file() is called on
294a file handle that is not in binary mode.
295
296If a filename is passed in, then parse_file() will open the file in
297binary mode.
298
299=item $p->eof
300
301Signals the end of the HTML document.  Calling the $p->eof method
302outside a handler callback will flush any remaining buffered text
303(which triggers the C<text> event if there is any remaining text).
304
305Calling $p->eof inside a handler will terminate parsing at that point
306and cause $p->parse to return a FALSE value.  This also terminates
307parsing by $p->parse_file().
308
309After $p->eof has been called, the parse() and parse_file() methods
310can be invoked to feed new documents with the parser object.
311
312The return value from eof() is a reference to the parser object.
313
314=back
315
316
317Most parser options are controlled by boolean attributes.
318Each boolean attribute is enabled by calling the corresponding method
319with a TRUE argument and disabled with a FALSE argument.  The
320attribute value is left unchanged if no argument is given.  The return
321value from each method is the old attribute value.
322
323Methods that can be used to get and/or set parser options are:
324
325=over
326
327=item $p->attr_encoded
328
329=item $p->attr_encoded( $bool )
330
331By default, the C<attr> and C<@attr> argspecs will have general
332entities for attribute values decoded.  Enabling this attribute leaves
333entities alone.
334
335=item $p->backquote
336
337=item $p->backquote( $bool )
338
339By default, only ' and " are recognized as quote characters around
340attribute values.  MSIE also recognizes backquotes for some reason.
341Enabling this attribute provides compatibility with this behaviour.
342
343=item $p->boolean_attribute_value( $val )
344
345This method sets the value reported for boolean attributes inside HTML
346start tags.  By default, the name of the attribute is also used as its
347value.  This affects the values reported for C<tokens> and C<attr>
348argspecs.
349
350=item $p->case_sensitive
351
352=item $p->case_sensitive( $bool )
353
354By default, tag names and attribute names are down-cased.  Enabling this
355attribute leaves them as found in the HTML source document.
356
357=item $p->closing_plaintext
358
359=item $p->closing_plaintext( $bool )
360
361By default, C<plaintext> element can never be closed. Everything up to
362the end of the document is parsed in CDATA mode.  This historical
363behaviour is what at least MSIE does.  Enabling this attribute makes
364closing C< </plaintext> > tag effective and the parsing process will resume
365after seeing this tag.  This emulates early gecko-based browsers.
366
367=item $p->empty_element_tags
368
369=item $p->empty_element_tags( $bool )
370
371By default, empty element tags are not recognized as such and the "/"
372before ">" is just treated like a normal name character (unless
373C<strict_names> is enabled).  Enabling this attribute make
374C<HTML::Parser> recognize these tags.
375
376Empty element tags look like start tags, but end with the character
377sequence "/>" instead of ">".  When recognized by C<HTML::Parser> they
378cause an artificial end event in addition to the start event.  The
379C<text> for the artificial end event will be empty and the C<tokenpos>
380array will be undefined even though the token array will have one
381element containing the tag name.
382
383=item $p->marked_sections
384
385=item $p->marked_sections( $bool )
386
387By default, section markings like <![CDATA[...]]> are treated like
388ordinary text.  When this attribute is enabled section markings are
389honoured.
390
391There are currently no events associated with the marked section
392markup, but the text can be returned as C<skipped_text>.
393
394=item $p->strict_comment
395
396=item $p->strict_comment( $bool )
397
398By default, comments are terminated by the first occurrence of "-->".
399This is the behaviour of most popular browsers (like Mozilla, Opera and
400MSIE), but it is not correct according to the official HTML
401standard.  Officially, you need an even number of "--" tokens before
402the closing ">" is recognized and there may not be anything but
403whitespace between an even and an odd "--".
404
405The official behaviour is enabled by enabling this attribute.
406
407Enabling of 'strict_comment' also disables recognizing these forms as
408comments:
409
410  </ comment>
411  <! comment>
412
413
414=item $p->strict_end
415
416=item $p->strict_end( $bool )
417
418By default, attributes and other junk are allowed to be present on end tags in a
419manner that emulates MSIE's behaviour.
420
421The official behaviour is enabled with this attribute.  If enabled,
422only whitespace is allowed between the tagname and the final ">".
423
424=item $p->strict_names
425
426=item $p->strict_names( $bool )
427
428By default, almost anything is allowed in tag and attribute names.
429This is the behaviour of most popular browsers and allows us to parse
430some broken tags with invalid attribute values like:
431
432   <IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0>
433
434By default, "LIST]" is parsed as a boolean attribute, not as
435part of the ALT value as was clearly intended.  This is also what
436Mozilla sees.
437
438The official behaviour is enabled by enabling this attribute.  If
439enabled, it will cause the tag above to be reported as text
440since "LIST]" is not a legal attribute name.
441
442=item $p->unbroken_text
443
444=item $p->unbroken_text( $bool )
445
446By default, blocks of text are given to the text handler as soon as
447possible (but the parser takes care always to break text at a
448boundary between whitespace and non-whitespace so single words and
449entities can always be decoded safely).  This might create breaks that
450make it hard to do transformations on the text. When this attribute is
451enabled, blocks of text are always reported in one piece.  This will
452delay the text event until the following (non-text) event has been
453recognized by the parser.
454
455Note that the C<offset> argspec will give you the offset of the first
456segment of text and C<length> is the combined length of the segments.
457Since there might be ignored tags in between, these numbers can't be
458used to directly index in the original document file.
459
460=item $p->utf8_mode
461
462=item $p->utf8_mode( $bool )
463
464Enable this option when parsing raw undecoded UTF-8.  This tells the
465parser that the entities expanded for strings reported by C<attr>,
466C<@attr> and C<dtext> should be expanded as decoded UTF-8 so they end
467up compatible with the surrounding text.
468
469If C<utf8_mode> is enabled then it is an error to pass strings
470containing characters with code above 255 to the parse() method, and
471the parse() method will croak if you try.
472
473Example: The Unicode character "\x{2665}" is "\xE2\x99\xA5" when UTF-8
474encoded.  The character can also be represented by the entity
475"&hearts;" or "&#x2665".  If we feed the parser:
476
477  $p->parse("\xE2\x99\xA5&hearts;");
478
479then C<dtext> will be reported as "\xE2\x99\xA5\x{2665}" without
480C<utf8_mode> enabled, but as "\xE2\x99\xA5\xE2\x99\xA5" when enabled.
481The later string is what you want.
482
483This option is only available with perl-5.8 or better.
484
485=item $p->xml_mode
486
487=item $p->xml_mode( $bool )
488
489Enabling this attribute changes the parser to allow some XML
490constructs.  This enables the behaviour controlled by individually by
491the C<case_sensitive>, C<empty_element_tags>, C<strict_names> and
492C<xml_pic> attributes and also suppresses special treatment of
493elements that are parsed as CDATA for HTML.
494
495=item $p->xml_pic
496
497=item $p->xml_pic( $bool )
498
499By default, I<processing instructions> are terminated by ">". When
500this attribute is enabled, processing instructions are terminated by
501"?>" instead.
502
503=back
504
505As markup and text is recognized, handlers are invoked.  The following
506method is used to set up handlers for different events:
507
508=over
509
510=item $p->handler( event => \&subroutine, $argspec )
511
512=item $p->handler( event => $method_name, $argspec )
513
514=item $p->handler( event => \@accum, $argspec )
515
516=item $p->handler( event => "" );
517
518=item $p->handler( event => undef );
519
520=item $p->handler( event );
521
522This method assigns a subroutine, method, or array to handle an event.
523
524Event is one of C<text>, C<start>, C<end>, C<declaration>, C<comment>,
525C<process>, C<start_document>, C<end_document> or C<default>.
526
527The C<\&subroutine> is a reference to a subroutine which is called to handle
528the event.
529
530The C<$method_name> is the name of a method of $p which is called to handle
531the event.
532
533The C<@accum> is an array that will hold the event information as
534sub-arrays.
535
536If the second argument is "", the event is ignored.
537If it is undef, the default handler is invoked for the event.
538
539The C<$argspec> is a string that describes the information to be reported
540for the event.  Any requested information that does not apply to a
541specific event is passed as C<undef>.  If argspec is omitted, then it
542is left unchanged.
543
544The return value from $p->handler is the old callback routine or a
545reference to the accumulator array.
546
547Any return values from handler callback routines/methods are always
548ignored.  A handler callback can request parsing to be aborted by
549invoking the $p->eof method.  A handler callback is not allowed to
550invoke the $p->parse() or $p->parse_file() method.  An exception will
551be raised if it tries.
552
553Examples:
554
555    $p->handler(start =>  "start", 'self, attr, attrseq, text' );
556
557This causes the "start" method of object C<$p> to be called for 'start' events.
558The callback signature is C<< $p->start(\%attr, \@attr_seq, $text) >>.
559
560    $p->handler(start =>  \&start, 'attr, attrseq, text' );
561
562This causes subroutine start() to be called for 'start' events.
563The callback signature is start(\%attr, \@attr_seq, $text).
564
565    $p->handler(start =>  \@accum, '"S", attr, attrseq, text' );
566
567This causes 'start' event information to be saved in @accum.
568The array elements will be ['S', \%attr, \@attr_seq, $text].
569
570   $p->handler(start => "");
571
572This causes 'start' events to be ignored.  It also suppresses
573invocations of any default handler for start events.  It is in most
574cases equivalent to $p->handler(start => sub {}), but is more
575efficient.  It is different from the empty-sub-handler in that
576C<skipped_text> is not reset by it.
577
578   $p->handler(start => undef);
579
580This causes no handler to be associated with start events.
581If there is a default handler it will be invoked.
582
583=back
584
585Filters based on tags can be set up to limit the number of events
586reported.  The main bottleneck during parsing is often the huge number
587of callbacks made from the parser.  Applying filters can improve
588performance significantly.
589
590The following methods control filters:
591
592=over
593
594=item $p->ignore_elements( @tags )
595
596Both the C<start> event and the C<end> event as well as any events that
597would be reported in between are suppressed.  The ignored elements can
598contain nested occurrences of itself.  Example:
599
600   $p->ignore_elements(qw(script style));
601
602The C<script> and C<style> tags will always nest properly since their
603content is parsed in CDATA mode.  For most other tags
604C<ignore_elements> must be used with caution since HTML is often not
605I<well formed>.
606
607=item $p->ignore_tags( @tags )
608
609Any C<start> and C<end> events involving any of the tags given are
610suppressed.  To reset the filter (i.e. don't suppress any C<start> and
611C<end> events), call C<ignore_tags> without an argument.
612
613=item $p->report_tags( @tags )
614
615Any C<start> and C<end> events involving any of the tags I<not> given
616are suppressed.  To reset the filter (i.e. report all C<start> and
617C<end> events), call C<report_tags> without an argument.
618
619=back
620
621Internally, the system has two filter lists, one for C<report_tags>
622and one for C<ignore_tags>, and both filters are applied.  This
623effectively gives C<ignore_tags> precedence over C<report_tags>.
624
625Examples:
626
627   $p->ignore_tags(qw(style));
628   $p->report_tags(qw(script style));
629
630results in only C<script> events being reported.
631
632=head2 Argspec
633
634Argspec is a string containing a comma-separated list that describes
635the information reported by the event.  The following argspec
636identifier names can be used:
637
638=over
639
640=item C<attr>
641
642Attr causes a reference to a hash of attribute name/value pairs to be
643passed.
644
645Boolean attributes' values are either the value set by
646$p->boolean_attribute_value, or the attribute name if no value has been
647set by $p->boolean_attribute_value.
648
649This passes undef except for C<start> events.
650
651Unless C<xml_mode> or C<case_sensitive> is enabled, the attribute
652names are forced to lower case.
653
654General entities are decoded in the attribute values and
655one layer of matching quotes enclosing the attribute values is removed.
656
657The Unicode character set is assumed for entity decoding.
658
659=item C<@attr>
660
661Basically the same as C<attr>, but keys and values are passed as
662individual arguments and the original sequence of the attributes is
663kept.  The parameters passed will be the same as the @attr calculated
664here:
665
666   @attr = map { $_ => $attr->{$_} } @$attrseq;
667
668assuming $attr and $attrseq here are the hash and array passed as the
669result of C<attr> and C<attrseq> argspecs.
670
671This passes no values for events besides C<start>.
672
673=item C<attrseq>
674
675Attrseq causes a reference to an array of attribute names to be
676passed.  This can be useful if you want to walk the C<attr> hash in
677the original sequence.
678
679This passes undef except for C<start> events.
680
681Unless C<xml_mode> or C<case_sensitive> is enabled, the attribute
682names are forced to lower case.
683
684=item C<column>
685
686Column causes the column number of the start of the event to be passed.
687The first column on a line is 0.
688
689=item C<dtext>
690
691Dtext causes the decoded text to be passed.  General entities are
692automatically decoded unless the event was inside a CDATA section or
693was between literal start and end tags (C<script>, C<style>,
694C<xmp>, C<iframe>, C<title>, C<textarea> and C<plaintext>).
695
696The Unicode character set is assumed for entity decoding.  With Perl
697version 5.6 or earlier only the Latin-1 range is supported, and
698entities for characters outside the range 0..255 are left unchanged.
699
700This passes undef except for C<text> events.
701
702=item C<event>
703
704Event causes the event name to be passed.
705
706The event name is one of C<text>, C<start>, C<end>, C<declaration>,
707C<comment>, C<process>, C<start_document> or C<end_document>.
708
709=item C<is_cdata>
710
711Is_cdata causes a TRUE value to be passed if the event is inside a CDATA
712section or between literal start and end tags (C<script>,
713C<style>, C<xmp>, C<iframe>, C<title>, C<textarea> and C<plaintext>).
714
715if the flag is FALSE for a text event, then you should normally
716either use C<dtext> or decode the entities yourself before the text is
717processed further.
718
719=item C<length>
720
721Length causes the number of bytes of the source text of the event to
722be passed.
723
724=item C<line>
725
726Line causes the line number of the start of the event to be passed.
727The first line in the document is 1.  Line counting doesn't start
728until at least one handler requests this value to be reported.
729
730=item C<offset>
731
732Offset causes the byte position in the HTML document of the start of
733the event to be passed.  The first byte in the document has offset 0.
734
735=item C<offset_end>
736
737Offset_end causes the byte position in the HTML document of the end of
738the event to be passed.  This is the same as C<offset> + C<length>.
739
740=item C<self>
741
742Self causes the current object to be passed to the handler.  If the
743handler is a method, this must be the first element in the argspec.
744
745An alternative to passing self as an argspec is to register closures
746that capture $self by themselves as handlers.  Unfortunately this
747creates circular references which prevent the HTML::Parser object
748from being garbage collected.  Using the C<self> argspec avoids this
749problem.
750
751=item C<skipped_text>
752
753Skipped_text returns the concatenated text of all the events that have
754been skipped since the last time an event was reported.  Events might
755be skipped because no handler is registered for them or because some
756filter applies.  Skipped text also includes marked section markup,
757since there are no events that can catch it.
758
759If an C<"">-handler is registered for an event, then the text for this
760event is not included in C<skipped_text>.  Skipped text both before
761and after the C<"">-event is included in the next reported
762C<skipped_text>.
763
764=item C<tag>
765
766Same as C<tagname>, but prefixed with "/" if it belongs to an C<end>
767event and "!" for a declaration.  The C<tag> does not have any prefix
768for C<start> events, and is in this case identical to C<tagname>.
769
770=item C<tagname>
771
772This is the element name (or I<generic identifier> in SGML jargon) for
773start and end tags.  Since HTML is case insensitive, this name is
774forced to lower case to ease string matching.
775
776Since XML is case sensitive, the tagname case is not changed when
777C<xml_mode> is enabled.  The same happens if the C<case_sensitive> attribute
778is set.
779
780The declaration type of declaration elements is also passed as a tagname,
781even if that is a bit strange.
782In fact, in the current implementation tagname is
783identical to C<token0> except that the name may be forced to lower case.
784
785=item C<token0>
786
787Token0 causes the original text of the first token string to be
788passed.  This should always be the same as $tokens->[0].
789
790For C<declaration> events, this is the declaration type.
791
792For C<start> and C<end> events, this is the tag name.
793
794For C<process> and non-strict C<comment> events, this is everything
795inside the tag.
796
797This passes undef if there are no tokens in the event.
798
799=item C<tokenpos>
800
801Tokenpos causes a reference to an array of token positions to be
802passed.  For each string that appears in C<tokens>, this array
803contains two numbers.  The first number is the offset of the start of
804the token in the original C<text> and the second number is the length
805of the token.
806
807Boolean attributes in a C<start> event will have (0,0) for the
808attribute value offset and length.
809
810This passes undef if there are no tokens in the event (e.g., C<text>)
811and for artificial C<end> events triggered by empty element tags.
812
813If you are using these offsets and lengths to modify C<text>, you
814should either work from right to left, or be very careful to calculate
815the changes to the offsets.
816
817=item C<tokens>
818
819Tokens causes a reference to an array of token strings to be passed.
820The strings are exactly as they were found in the original text,
821no decoding or case changes are applied.
822
823For C<declaration> events, the array contains each word, comment, and
824delimited string starting with the declaration type.
825
826For C<comment> events, this contains each sub-comment.  If
827$p->strict_comments is disabled, there will be only one sub-comment.
828
829For C<start> events, this contains the original tag name followed by
830the attribute name/value pairs.  The values of boolean attributes will
831be either the value set by $p->boolean_attribute_value, or the
832attribute name if no value has been set by
833$p->boolean_attribute_value.
834
835For C<end> events, this contains the original tag name (always one token).
836
837For C<process> events, this contains the process instructions (always one
838token).
839
840This passes C<undef> for C<text> events.
841
842=item C<text>
843
844Text causes the source text (including markup element delimiters) to be
845passed.
846
847=item C<undef>
848
849Pass an undefined value.  Useful as padding where the same handler
850routine is registered for multiple events.
851
852=item C<'...'>
853
854A literal string of 0 to 255 characters enclosed
855in single (') or double (") quotes is passed as entered.
856
857=back
858
859The whole argspec string can be wrapped up in C<'@{...}'> to signal
860that the resulting event array should be flattened.  This only makes a
861difference if an array reference is used as the handler target.
862Consider this example:
863
864   $p->handler(text => [], 'text');
865   $p->handler(text => [], '@{text}']);
866
867With two text events; C<"foo">, C<"bar">; then the first example will end
868up with [["foo"], ["bar"]] and the second with ["foo", "bar"] in
869the handler target array.
870
871
872=head2 Events
873
874Handlers for the following events can be registered:
875
876=over
877
878=item C<comment>
879
880This event is triggered when a markup comment is recognized.
881
882Example:
883
884  <!-- This is a comment -- -- So is this -->
885
886=item C<declaration>
887
888This event is triggered when a I<markup declaration> is recognized.
889
890For typical HTML documents, the only declaration you are
891likely to find is <!DOCTYPE ...>.
892
893Example:
894
895  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
896      "http://www.w3.org/TR/html4/strict.dtd">
897
898DTDs inside <!DOCTYPE ...> will confuse HTML::Parser.
899
900=item C<default>
901
902This event is triggered for events that do not have a specific
903handler.  You can set up a handler for this event to catch stuff you
904did not want to catch explicitly.
905
906=item C<end>
907
908This event is triggered when an end tag is recognized.
909
910Example:
911
912  </A>
913
914=item C<end_document>
915
916This event is triggered when $p->eof is called and after any remaining
917text is flushed.  There is no document text associated with this event.
918
919=item C<process>
920
921This event is triggered when a processing instructions markup is
922recognized.
923
924The format and content of processing instructions are system and
925application dependent.
926
927Examples:
928
929  <? HTML processing instructions >
930  <? XML processing instructions ?>
931
932=item C<start>
933
934This event is triggered when a start tag is recognized.
935
936Example:
937
938  <A HREF="http://www.perl.com/">
939
940=item C<start_document>
941
942This event is triggered before any other events for a new document.  A
943handler for it can be used to initialize stuff.  There is no document
944text associated with this event.
945
946=item C<text>
947
948This event is triggered when plain text (characters) is recognized.
949The text may contain multiple lines.  A sequence of text may be broken
950between several text events unless $p->unbroken_text is enabled.
951
952The parser will make sure that it does not break a word or a sequence
953of whitespace between two text events.
954
955=back
956
957=head2 Unicode
958
959C<HTML::Parser> can parse Unicode strings when running under
960perl-5.8 or better.  If Unicode is passed to $p->parse() then chunks
961of Unicode will be reported to the handlers.  The offset and length
962argspecs will also report their position in terms of characters.
963
964It is safe to parse raw undecoded UTF-8 if you either avoid decoding
965entities and make sure to not use I<argspecs> that do, or enable the
966C<utf8_mode> for the parser.  Parsing of undecoded UTF-8 might be
967useful when parsing from a file where you need the reported offsets
968and lengths to match the byte offsets in the file.
969
970If a filename is passed to $p->parse_file() then the file will be read
971in binary mode.  This will be fine if the file contains only ASCII or
972Latin-1 characters.  If the file contains UTF-8 encoded text then care
973must be taken when decoding entities as described in the previous
974paragraph, but better is to open the file with the UTF-8 layer so that
975it is decoded properly:
976
977   open(my $fh, "<:utf8", "index.html") || die "...: $!";
978   $p->parse_file($fh);
979
980If the file contains text encoded in a charset besides ASCII, Latin-1
981or UTF-8 then decoding will always be needed.
982
983=head1 VERSION 2 COMPATIBILITY
984
985When an C<HTML::Parser> object is constructed with no arguments, a set
986of handlers is automatically provided that is compatible with the old
987HTML::Parser version 2 callback methods.
988
989This is equivalent to the following method calls:
990
991  $p->handler(start   => "start",   "self, tagname, attr, attrseq, text");
992  $p->handler(end     => "end",     "self, tagname, text");
993  $p->handler(text    => "text",    "self, text, is_cdata");
994  $p->handler(process => "process", "self, token0, text");
995  $p->handler(
996    comment => sub {
997      my($self, $tokens) = @_;
998      for (@$tokens) {$self->comment($_);}
999    },
1000    "self, tokens"
1001  );
1002  $p->handler(
1003    declaration => sub {
1004      my $self = shift;
1005      $self->declaration(substr($_[0], 2, -1));
1006    },
1007    "self, text"
1008  );
1009
1010Setting up these handlers can also be requested with the "api_version =>
10112" constructor option.
1012
1013=head1 SUBCLASSING
1014
1015The C<HTML::Parser> class is able to be subclassed.  Parser objects are plain
1016hashes and C<HTML::Parser> reserves only hash keys that start with
1017"_hparser".  The parser state can be set up by invoking the init()
1018method, which takes the same arguments as new().
1019
1020=head1 EXAMPLES
1021
1022The first simple example shows how you might strip out comments from
1023an HTML document.  We achieve this by setting up a comment handler that
1024does nothing and a default handler that will print out anything else:
1025
1026  use HTML::Parser;
1027  HTML::Parser->new(
1028    default_h => [sub { print shift }, 'text'],
1029    comment_h => [""],
1030  )->parse_file(shift || die) || die $!;
1031
1032An alternative implementation is:
1033
1034  use HTML::Parser;
1035  HTML::Parser->new(
1036    end_document_h => [sub { print shift }, 'skipped_text'],
1037    comment_h      => [""],
1038  )->parse_file(shift || die) || die $!;
1039
1040This will in most cases be much more efficient since only a single
1041callback will be made.
1042
1043The next example prints out the text that is inside the <title>
1044element of an HTML document.  Here we start by setting up a start
1045handler.  When it sees the title start tag it enables a text handler
1046that prints any text found and an end handler that will terminate
1047parsing as soon as the title end tag is seen:
1048
1049  use HTML::Parser ();
1050
1051  sub start_handler {
1052    return if shift ne "title";
1053    my $self = shift;
1054    $self->handler(text => sub { print shift }, "dtext");
1055    $self->handler(
1056      end  => sub {
1057        shift->eof if shift eq "title";
1058      },
1059      "tagname,self"
1060    );
1061  }
1062
1063  my $p = HTML::Parser->new(api_version => 3);
1064  $p->handler(start => \&start_handler, "tagname,self");
1065  $p->parse_file(shift || die) || die $!;
1066  print "\n";
1067
1068More examples are found in the F<eg/> directory of the C<HTML-Parser>
1069distribution: the program C<hrefsub> shows how you can edit all links
1070found in a document; the program C<htextsub> shows how to edit the text only; the
1071program C<hstrip> shows how you can strip out certain tags/elements
1072and/or attributes; and the program C<htext> show how to obtain the
1073plain text, but not any script/style content.
1074
1075You can browse the F<eg/> directory online from the I<[Browse]> link on
1076the http://search.cpan.org/~gaas/HTML-Parser/ page.
1077
1078=head1 BUGS
1079
1080The <style> and <script> sections do not end with the first "</", but
1081need the complete corresponding end tag.  The standard behaviour is
1082not really practical.
1083
1084When the I<strict_comment> option is enabled, we still recognize
1085comments where there is something other than whitespace between even
1086and odd "--" markers.
1087
1088Once $p->boolean_attribute_value has been set, there is no way to
1089restore the default behaviour.
1090
1091There is currently no way to get both quote characters
1092into the same literal argspec.
1093
1094Empty tags, e.g. "<>" and "</>", are not recognized.  SGML allows them
1095to repeat the previous start tag or close the previous start tag
1096respectively.
1097
1098NET tags, e.g. "code/.../" are not recognized.  This is SGML
1099shorthand for "<code>...</code>".
1100
1101Incomplete start or end tags, e.g. "<tt<b>...</b</tt>" are not
1102recognized.
1103
1104=head1 DIAGNOSTICS
1105
1106The following messages may be produced by HTML::Parser.  The notation
1107in this listing is the same as used in L<perldiag>:
1108
1109=over
1110
1111=item Not a reference to a hash
1112
1113(F) The object blessed into or subclassed from HTML::Parser is not a
1114hash as required by the HTML::Parser methods.
1115
1116=item Bad signature in parser state object at %p
1117
1118(F) The _hparser_xs_state element does not refer to a valid state structure.
1119Something must have changed the internal value
1120stored in this hash element, or the memory has been overwritten.
1121
1122=item _hparser_xs_state element is not a reference
1123
1124(F) The _hparser_xs_state element has been destroyed.
1125
1126=item Can't find '_hparser_xs_state' element in HTML::Parser hash
1127
1128(F) The _hparser_xs_state element is missing from the parser hash.
1129It was either deleted, or not created when the object was created.
1130
1131=item API version %s not supported by HTML::Parser %s
1132
1133(F) The constructor option 'api_version' with an argument greater than
1134or equal to 4 is reserved for future extensions.
1135
1136=item Bad constructor option '%s'
1137
1138(F) An unknown constructor option key was passed to the new() or
1139init() methods.
1140
1141=item Parse loop not allowed
1142
1143(F) A handler invoked the parse() or parse_file() method.
1144This is not permitted.
1145
1146=item marked sections not supported
1147
1148(F) The $p->marked_sections() method was invoked in a HTML::Parser
1149module that was compiled without support for marked sections.
1150
1151=item Unknown boolean attribute (%d)
1152
1153(F) Something is wrong with the internal logic that set up aliases for
1154boolean attributes.
1155
1156=item Only code or array references allowed as handler
1157
1158(F) The second argument for $p->handler must be either a subroutine
1159reference, then name of a subroutine or method, or a reference to an
1160array.
1161
1162=item No handler for %s events
1163
1164(F) The first argument to $p->handler must be a valid event name; i.e. one
1165of "start", "end", "text", "process", "declaration" or "comment".
1166
1167=item Unrecognized identifier %s in argspec
1168
1169(F) The identifier is not a known argspec name.
1170Use one of the names mentioned in the argspec section above.
1171
1172=item Literal string is longer than 255 chars in argspec
1173
1174(F) The current implementation limits the length of literals in
1175an argspec to 255 characters.  Make the literal shorter.
1176
1177=item Backslash reserved for literal string in argspec
1178
1179(F) The backslash character "\" is not allowed in argspec literals.
1180It is reserved to permit quoting inside a literal in a later version.
1181
1182=item Unterminated literal string in argspec
1183
1184(F) The terminating quote character for a literal was not found.
1185
1186=item Bad argspec (%s)
1187
1188(F) Only identifier names, literals, spaces and commas
1189are allowed in argspecs.
1190
1191=item Missing comma separator in argspec
1192
1193(F) Identifiers in an argspec must be separated with ",".
1194
1195=item Parsing of undecoded UTF-8 will give garbage when decoding entities
1196
1197(W) The first chunk parsed appears to contain undecoded UTF-8 and one
1198or more argspecs that decode entities are used for the callback
1199handlers.
1200
1201The result of decoding will be a mix of encoded and decoded characters
1202for any entities that expand to characters with code above 127.  This
1203is not a good thing.
1204
1205The recommended solution is to apply Encode::decode_utf8() on the data before
1206feeding it to the $p->parse().  For $p->parse_file() pass a file that has been
1207opened in ":utf8" mode.
1208
1209The alternative solution is to enable the C<utf8_mode> and not decode before
1210passing strings to $p->parse().  The parser can process raw undecoded UTF-8
1211sanely if the C<utf8_mode> is enabled, or if the C<attr>, C<@attr> or C<dtext>
1212argspecs are avoided.
1213
1214=item Parsing string decoded with wrong endian selection
1215
1216(W) The first character in the document is U+FFFE.  This is not a
1217legal Unicode character but a byte swapped C<BOM>.  The result of parsing
1218will likely be garbage.
1219
1220=item Parsing of undecoded UTF-32
1221
1222(W) The parser found the Unicode UTF-32 C<BOM> signature at the start
1223of the document.  The result of parsing will likely be garbage.
1224
1225=item Parsing of undecoded UTF-16
1226
1227(W) The parser found the Unicode UTF-16 C<BOM> signature at the start of
1228the document.  The result of parsing will likely be garbage.
1229
1230=back
1231
1232=head1 SEE ALSO
1233
1234L<HTML::Entities>, L<HTML::PullParser>, L<HTML::TokeParser>, L<HTML::HeadParser>,
1235L<HTML::LinkExtor>, L<HTML::Form>
1236
1237L<HTML::TreeBuilder> (part of the I<HTML-Tree> distribution)
1238
1239L<http://www.w3.org/TR/html4/>
1240
1241More information about marked sections and processing instructions may
1242be found at L<http://www.is-thought.co.uk/book/sgml-8.htm>.
1243
1244=head1 COPYRIGHT
1245
1246 Copyright 1996-2016 Gisle Aas. All rights reserved.
1247 Copyright 1999-2000 Michael A. Chase.  All rights reserved.
1248
1249This library is free software; you can redistribute it and/or
1250modify it under the same terms as Perl itself.
1251
1252=cut
1253