blib/lib/XML/Twig.pm

filter: Statementstmt 88.5% 31 / 35 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 78.5% 11 / 14 Podpod n/a totaltotal 85.7% 42 / 49 CC 1 SCAR 1.5
CC
1
Cov
89%
PCDATA
2.0
CDATA
2.0
BEGIN
1.3
CRAP 1.2
« blib/lib/XML/speedup.pl ↑ Summary blib/lib/XML/Twig/XPath.pm »
1 164 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 164 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: not called CC=1 SCAR=0.0
3  
4 # This is created in the caller's space
5 # I realize (now!) that it's not clean, but it's been there for 10+ years...
6 BEGIN
7 0 ▶{ sub ::PCDATA { '#PCDATA' } ## no critic (Subroutines::ProhibitNestedSubs);
Subroutine PCDATA: not called CC=1 SCAR=6.9
8 0 ▶ sub ::CDATA { '#CDATA' } ## no critic (Subroutines::ProhibitNestedSubs);
Subroutine CDATA: not called CC=1 SCAR=6.9
9 }
10  
11 164 ▶use UNIVERSAL();
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 ## if a sub returns a scalar, it better not bloody disappear in list context
14 ## no critic (Subroutines::ProhibitExplicitReturnUndef);
15  
16 my $perl_version;
17 my $parser_version;
18  
19 ######################################################################
20 package XML::Twig;
21 ######################################################################
22  
23 require 5.010;
24  
25 164 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 164 ▶use vars qw($VERSION @ISA %valid_option);
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 164 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 164 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 164 ▶use File::Basename;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 164 ▶use Config; # to get perl's path name in case we need to know if perlio is available
Subroutine BEGIN: called CC=1 SCAR=0.0
34  
35 *isa= *UNIVERSAL::isa;
36  
37 # flag, set to true if the weaken sub is available
38 164 ▶use vars qw( $weakrefs);
Subroutine BEGIN: called CC=1 SCAR=0.0
39  
40 # flag set to true if the version of expat seems to be 1.95.2, which has annoying bugs
41 # wrt doctype handling. This is global for performance reasons.
42 my $expat_1_95_2=0;
43  
44 # a slight non-xml mod: # is allowed as a first character
45 my $REG_TAG_FIRST_LETTER;
46 $REG_TAG_FIRST_LETTER= q{(?:[[:alpha:]:#_])};
47  
48 my $REG_TAG_LETTER= q{(?:[\w_.-]*)};
49  
50 # a simple name (no colon)
51 my $REG_NAME_TOKEN= qq{(?:$REG_TAG_FIRST_LETTER$REG_TAG_LETTER*)};
52  
53 # a tag name, possibly including namespace
54 my $REG_NAME= qq{(?:(?:$REG_NAME_TOKEN:)?$REG_NAME_TOKEN)};
55  
56 # tag name (leading # allowed)
57 my $REG_TAG_NAME=$REG_NAME;
58  
59 # name or wildcard (* or '') (leading # allowed)
60 my $REG_NAME_W = qq{(?:$REG_NAME|[*])};
61  
62 # class and ids are deliberately permissive
63 my $REG_NTOKEN_FIRST_LETTER;
64 $REG_NTOKEN_FIRST_LETTER= q{(?:[[:alpha:]:_])};
65  
66 my $REG_NTOKEN_LETTER= q{(?:[\w_:.-]*)};
67  
68 my $REG_NTOKEN= qq{(?:$REG_NTOKEN_FIRST_LETTER$REG_NTOKEN_LETTER*)};
69 my $REG_CLASS = $REG_NTOKEN;
70 my $REG_ID = $REG_NTOKEN;
71  
72 # allow <tag> #<tag> (private elt) * <tag>.<class> *.<class> <tag>#<id> *#<id>
73 my $REG_TAG_PART= qq{(?:$REG_NAME_W(?:(?:[.]$REG_CLASS)+|[#]$REG_ID)?|(?:[.]$REG_CLASS)+)};
74  
75 my $REG_REGEXP = q{(?:/(?:[^\\/]|\\.)*/[eimsox]*)}; # regexp
76 my $REG_MATCH = q{[!=]~}; # match (or not)
77 my $REG_STRING = q{(?:"(?:[^\\"]|\\.)*"|'(?:[^\\']|\\.)*')}; # string (simple or double quoted)
78 my $REG_NUMBER = q{(?:\d+(?:\.\d*)?|\.\d+)}; # number
79 my $REG_VALUE = qq{(?:$REG_STRING|$REG_NUMBER)}; # value
80 my $REG_OP = q{==|!=|>|<|>=|<=|eq|ne|lt|gt|le|ge|=}; # op
81 my $REG_FUNCTION = q{(?:string|text)\(\s*\)};
82 my $REG_STRING_ARG = qq{(?:string|text)\\(\\s*$REG_NAME_W\\s*\\)};
83 my $REG_COMP = q{(?:>=|<=|!=|<|>|=)};
84  
85 my $REG_TAG_IN_PREDICATE= $REG_NAME_W . q{(?=\s*(?i:and\b|or\b|\]|$))};
86  
87 # keys in the context stack, chosen not to interfere with att names, even private (#-prefixed) ones
88 my $ST_TAG = '##tag';
89 my $ST_ELT = '##elt';
90 my $ST_NS = '##ns' ;
91  
92 # used in the handler trigger code
93 my $REG_NAKED_PREDICATE= qq{((?:"[^"]*"|'[^']*'|$REG_STRING_ARG|$REG_FUNCTION|\@$REG_NAME_W|$REG_MATCH\\s*$REG_REGEXP|[\\s\\d><=!()+.-]|(?i:and)|(?i:or)|$REG_TAG_IN_PREDICATE)*)};
94 my $REG_PREDICATE= qq{\\[$REG_NAKED_PREDICATE\\]};
95  
96 # not all axis, only supported ones (in get_xpath)
97 my @supported_axis= ( 'ancestor', 'ancestor-or-self', 'child', 'descendant', 'descendant-or-self',
98 'following', 'following-sibling', 'parent', 'preceding', 'preceding-sibling', 'self'
99 );
100 my $REG_AXIS = "(?:" . join( '|', @supported_axis) .")";
101  
102 # only used in the "xpath"engine (for get_xpath/findnodes) for now
103 my $REG_PREDICATE_ALT = qr{\[(?:(?:string\(\s*\)|\@$REG_TAG_NAME)\s*$REG_MATCH\s*$REG_REGEXP\s*|[^\]]*)\]};
104  
105 # used to convert XPath tests on strings to the perl equivalent
106 my %PERL_ALPHA_TEST= ( '=' => ' eq ', '!=' => ' ne ', '>' => ' gt ', '>=' => ' ge ', '<' => ' lt ', '<=' => ' le ');
107  
108 my( $FB_HTMLCREF, $FB_XMLCREF); # Encode flags
109  
110 my $NO_WARNINGS= 'no warnings';
111  
112 # default namespaces, both ways
113 my %DEFAULT_NS= ( xml => "http://www.w3.org/XML/1998/namespace",
114 xmlns => "http://www.w3.org/2000/xmlns/",
115 );
116 my %DEFAULT_URI2NS= map { $DEFAULT_NS{$_} => $_ } keys %DEFAULT_NS;
117  
118 # constants
119 my( $PCDATA, $CDATA, $PI, $COMMENT, $ENT, $ELT, $NOTATION, $TEXT, $ASIS, $EMPTY, $BUFSIZE);
120  
121 # used when an HTML doc only has a PUBLIC declaration, to generate the SYSTEM one
122 # this should really be done by HTML::TreeBuilder, but as of HTML::TreeBuilder 4.2 it isn't
123 # the various declarations are taken from http://en.wikipedia.org/wiki/Document_Type_Declaration
124 my %HTML_DECL= ( "-//W3C//DTD HTML 4.0 Transitional//EN" => "http://www.w3.org/TR/REC-html40/loose.dtd",
125 "-//W3C//DTD HTML 4.01//EN" => "http://www.w3.org/TR/html4/strict.dtd",
126 "-//W3C//DTD HTML 4.01 Transitional//EN" => "http://www.w3.org/TR/html4/loose.dtd",
127 "-//W3C//DTD HTML 4.01 Frameset//EN" => "http://www.w3.org/TR/html4/frameset.dtd",
128 "-//W3C//DTD XHTML 1.0 Strict//EN" => "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
129 "-//W3C//DTD XHTML 1.0 Transitional//EN" => "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd",
130 "-//W3C//DTD XHTML 1.0 Frameset//EN" => "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd",
131 "-//W3C//DTD XHTML 1.1//EN" => "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd",
132 "-//W3C//DTD XHTML Basic 1.0//EN" => "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd",
133 "-//W3C//DTD XHTML Basic 1.1//EN" => "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd",
134 "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" => "http://www.wapforum.org/DTD/xhtml-mobile10.dtd",
135 "-//WAPFORUM//DTD XHTML Mobile 1.1//EN" => "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile11.dtd",
136 "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" => "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd",
137 "-//W3C//DTD XHTML+RDFa 1.0//EN" => "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd",
138 );
139  
140 my $DEFAULT_HTML_TYPE= "-//W3C//DTD HTML 4.0 Transitional//EN";
141  
142 my $SEP= qr/\s*(?:$|\|)/;
143  
144 BEGIN
145 {
146 $VERSION = '3.54';
147  
148 164 ▶use XML::Parser;
Subroutine BEGIN: called CC=1 SCAR=2.6
149 my $needVersion = '2.23';
150 ($parser_version= $XML::Parser::VERSION)=~ s{_\d+}{}; # remove _<n> from version so numeric tests do not warn
151 croak "need at least XML::Parser version $needVersion" unless $parser_version >= $needVersion;
152  
153 ($perl_version= $])=~ s{_\d+}{};
154  
155 eval "use Encode qw( :all)"; ## no critic ProhibitStringyEval
156 $FB_XMLCREF = 0x0400; # Encode::FB_XMLCREF;
157 $FB_HTMLCREF = 0x0200; # Encode::FB_HTMLCREF;
158  
159 # test whether we can use weak references
160 # set local empty signal handler to trap error messages
161 { local $SIG{__DIE__};
162 ## no critic (ProhibitStringyEval)
163 if( eval( 'require Scalar::Util') && defined( \&Scalar::Util::weaken))
164 { import Scalar::Util( 'weaken'); $weakrefs= 1; }
165 elsif( eval( 'require WeakRef'))
166 { import WeakRef; $weakrefs= 1; }
167 else
168 { $weakrefs= 0; }
169 }
170  
171 # used to store the gi's
172 # should be set for each twig really, at least when there are several
173 # the init ensures that special gi's are always the same
174  
175 # constants: element types
176 $PCDATA = '#PCDATA';
177 $CDATA = '#CDATA';
178 $PI = '#PI';
179 $COMMENT = '#COMMENT';
180 $ENT = '#ENT';
181 $NOTATION = '#NOTATION';
182  
183 # element classes
184 $ELT = '#ELT';
185 $TEXT = '#TEXT';
186  
187 # element properties
188 $ASIS = '#ASIS';
189 $EMPTY = '#EMPTY';
190  
191 # used in parseurl to set the buffer size to the same size as in XML::Parser::Expat
192 $BUFSIZE = 32768;
193  
194 # gi => index
195 %XML::Twig::gi2index=( '', 0, $PCDATA => 1, $CDATA => 2, $PI => 3, $COMMENT => 4, $ENT => 5);
196 # list of gi's
197 @XML::Twig::index2gi=( '', $PCDATA, $CDATA, $PI, $COMMENT, $ENT);
198  
199 # gi's under this value are special
200 $XML::Twig::SPECIAL_GI= @XML::Twig::index2gi;
201  
202 %XML::Twig::base_ent= ( '>' => '&gt;', '<' => '&lt;', '&' => '&amp;', "'" => '&apos;', '"' => '&quot;',);
203 foreach my $c ( "\n", "\r", "\t") { $XML::Twig::base_ent{$c}= sprintf( "&#x%02x;", ord( $c)); }
204  
205 # now set some aliases
206 *find_nodes = *get_xpath; # same as XML::XPath
207 *findnodes = *get_xpath; # same as XML::LibXML
208 *getElementsByTagName = *descendants;
209 *descendants_or_self = *descendants; # valid in XML::Twig, not in XML::Twig::Elt
210 *find_by_tag_name = *descendants;
211 *getElementById = *elt_id;
212 *getEltById = *elt_id;
213 *toString = *sprint;
214 *create_accessors = *att_accessors;
215  
216 }
217  
218 @ISA = qw(XML::Parser);
219  
220 # fake gi's used in twig_handlers and start_tag_handlers
221 my $ALL = '_all_'; # the associated function is always called
222 my $DEFAULT= '_default_'; # the function is called if no other handler has been
223  
224 # some defaults
225 my $COMMENTS_DEFAULT= 'keep';
226 my $PI_DEFAULT = 'keep';
227  
228 # handlers used in regular mode
229 my %twig_handlers=( Start => \&_twig_start,
230 End => \&_twig_end,
231 Char => \&_twig_char,
232 Entity => \&_twig_entity,
233 Notation => \&_twig_notation,
234 XMLDecl => \&_twig_xmldecl,
235 Doctype => \&_twig_doctype,
236 Element => \&_twig_element,
237 Attlist => \&_twig_attlist,
238 CdataStart => \&_twig_cdatastart,
239 CdataEnd => \&_twig_cdataend,
240 Proc => \&_twig_pi,
241 Comment => \&_twig_comment,
242 Default => \&_twig_default,
243 ExternEnt => \&_twig_extern_ent,
244 );
245  
246 # handlers used when twig_roots is used and we are outside of the roots
247 my %twig_handlers_roots=
248 ( Start => \&_twig_start_check_roots,
249 End => \&_twig_end_check_roots,
250 Doctype => \&_twig_doctype,
251 Char => undef, Entity => undef, XMLDecl => \&_twig_xmldecl,
252 Element => undef, Attlist => undef, CdataStart => undef,
253 CdataEnd => undef, Proc => undef, Comment => undef,
254 Proc => \&_twig_pi_check_roots,
255 Default => sub {}, # hack needed for XML::Parser 2.27
256 ExternEnt => \&_twig_extern_ent,
257 );
258  
259 # handlers used when twig_roots and print_outside_roots are used and we are
260 # outside of the roots
261 my %twig_handlers_roots_print_2_30=
262 ( Start => \&_twig_start_check_roots,
263 End => \&_twig_end_check_roots,
264 Char => \&_twig_print,
265 Entity => \&_twig_print_entity,
266 ExternEnt => \&_twig_print_entity,
267 DoctypeFin => \&_twig_doctype_fin_print,
268 XMLDecl => sub { _twig_xmldecl( @_); _twig_print( @_); },
269 Doctype => \&_twig_print_doctype, # because recognized_string is broken here
270 # Element => \&_twig_print, Attlist => \&_twig_print,
271 CdataStart => \&_twig_print, CdataEnd => \&_twig_print,
272 Proc => \&_twig_pi_check_roots, Comment => \&_twig_print,
273 Default => \&_twig_print_check_doctype,
274 ExternEnt => \&_twig_extern_ent,
275 );
276  
277 # handlers used when twig_roots, print_outside_roots and keep_encoding are used
278 # and we are outside of the roots
279 my %twig_handlers_roots_print_original_2_30=
280 ( Start => \&_twig_start_check_roots,
281 End => \&_twig_end_check_roots,
282 Char => \&_twig_print_original,
283 # I have no idea why I should not be using this handler!
284 Entity => \&_twig_print_entity,
285 ExternEnt => \&_twig_print_entity,
286 DoctypeFin => \&_twig_doctype_fin_print,
287 XMLDecl => sub { _twig_xmldecl( @_); _twig_print_original( @_) },
288 Doctype => \&_twig_print_original_doctype, # because original_string is broken here
289 Element => \&_twig_print_original, Attlist => \&_twig_print_original,
290 CdataStart => \&_twig_print_original, CdataEnd => \&_twig_print_original,
291 Proc => \&_twig_pi_check_roots, Comment => \&_twig_print_original,
292 Default => \&_twig_print_original_check_doctype,
293 );
294  
295 # handlers used when twig_roots and print_outside_roots are used and we are
296 # outside of the roots
297 my %twig_handlers_roots_print_2_27=
298 ( Start => \&_twig_start_check_roots,
299 End => \&_twig_end_check_roots,
300 Char => \&_twig_print,
301 # if the Entity handler is set then it prints the entity declaration
302 # before the entire internal subset (including the declaration!) is output
303 Entity => sub {},
304 XMLDecl => \&_twig_print, Doctype => \&_twig_print,
305 CdataStart => \&_twig_print, CdataEnd => \&_twig_print,
306 Proc => \&_twig_pi_check_roots, Comment => \&_twig_print,
307 Default => \&_twig_print,
308 ExternEnt => \&_twig_extern_ent,
309 );
310  
311 # handlers used when twig_roots, print_outside_roots and keep_encoding are used
312 # and we are outside of the roots
313 my %twig_handlers_roots_print_original_2_27=
314 ( Start => \&_twig_start_check_roots,
315 End => \&_twig_end_check_roots,
316 Char => \&_twig_print_original,
317 # for some reason original_string is wrong here
318 # this can be a problem if the doctype includes non ascii characters
319 XMLDecl => \&_twig_print, Doctype => \&_twig_print,
320 # if the Entity handler is set then it prints the entity declaration
321 # before the entire internal subset (including the declaration!) is output
322 Entity => sub {},
323 #Element => undef, Attlist => undef,
324 CdataStart => \&_twig_print_original, CdataEnd => \&_twig_print_original,
325 Proc => \&_twig_pi_check_roots, Comment => \&_twig_print_original,
326 Default => \&_twig_print, # _twig_print_original does not work
327 ExternEnt => \&_twig_extern_ent,
328 );
329  
330 my %twig_handlers_roots_print= $parser_version > 2.27
331 ? %twig_handlers_roots_print_2_30
332 : %twig_handlers_roots_print_2_27;
333 my %twig_handlers_roots_print_original= $parser_version > 2.27
334 ? %twig_handlers_roots_print_original_2_30
335 : %twig_handlers_roots_print_original_2_27;
336  
337 # handlers used when the finish_print method has been called
338 my %twig_handlers_finish_print=
339 ( Start => \&_twig_print,
340 End => \&_twig_print, Char => \&_twig_print,
341 Entity => \&_twig_print, XMLDecl => \&_twig_print,
342 Doctype => \&_twig_print, Element => \&_twig_print,
343 Attlist => \&_twig_print, CdataStart => \&_twig_print,
344 CdataEnd => \&_twig_print, Proc => \&_twig_print,
345 Comment => \&_twig_print, Default => \&_twig_print,
346 ExternEnt => \&_twig_extern_ent,
347 );
348  
349 # handlers used when the finish_print method has been called and the keep_encoding
350 # option is used
351 my %twig_handlers_finish_print_original=
352 ( Start => \&_twig_print_original, End => \&_twig_print_end_original,
353 Char => \&_twig_print_original, Entity => \&_twig_print_original,
354 XMLDecl => \&_twig_print_original, Doctype => \&_twig_print_original,
355 Element => \&_twig_print_original, Attlist => \&_twig_print_original,
356 CdataStart => \&_twig_print_original, CdataEnd => \&_twig_print_original,
357 Proc => \&_twig_print_original, Comment => \&_twig_print_original,
358 Default => \&_twig_print_original,
359 );
360  
361 # handlers used within ignored elements
362 my %twig_handlers_ignore=
363 ( Start => \&_twig_ignore_start,
364 End => \&_twig_ignore_end,
365 Char => undef, Entity => undef, XMLDecl => undef,
366 Doctype => undef, Element => undef, Attlist => undef,
367 CdataStart => undef, CdataEnd => undef, Proc => undef,
368 Comment => undef, Default => undef,
369 ExternEnt => undef,
370 );
371  
372 # those handlers are only used if the entities are NOT to be expanded
373 my %twig_noexpand_handlers= ( ExternEnt => undef, Default => \&_twig_default );
374  
375 my @saved_default_handler;
376  
377 my $ID= 'id'; # default value, set by the Id argument
378 my $css_sel; # set through the css_sel option to allow .class selectors in triggers
379  
380 # all allowed options
381 %valid_option=
382 ( # XML::Twig options
383 TwigHandlers => 1, Id => 1,
384 TwigRoots => 1, TwigPrintOutsideRoots => 1,
385 StartTagHandlers => 1, EndTagHandlers => 1,
386 ForceEndTagHandlersUsage => 1,
387 DoNotChainHandlers => 1,
388 IgnoreElts => 1,
389 Index => 1,
390 AttAccessors => 1,
391 EltAccessors => 1,
392 FieldAccessors => 1,
393 CharHandler => 1,
394 TopDownHandlers => 1,
395 KeepEncoding => 1, DoNotEscapeAmpInAtts => 1,
396 ParseStartTag => 1, KeepAttsOrder => 1,
397 LoadDTD => 1, DTDHandler => 1, DTDBase => 1, NoXxe => 1,
398 DoNotOutputDTD => 1, NoProlog => 1,
399 ExpandExternalEnts => 1,
400 DiscardSpaces => 1, KeepSpaces => 1, DiscardAllSpaces => 1,
401 DiscardSpacesIn => 1, KeepSpacesIn => 1,
402 PrettyPrint => 1, EmptyTags => 1,
403 EscapeGt => 1,
404 Quote => 1,
405 Comments => 1, Pi => 1,
406 OutputFilter => 1, InputFilter => 1,
407 OutputTextFilter => 1,
408 OutputEncoding => 1,
409 RemoveCdata => 1,
410 EltClass => 1,
411 MapXmlns => 1, KeepOriginalPrefix => 1,
412 SkipMissingEnts => 1,
413 # XML::Parser options
414 ErrorContext => 1, ProtocolEncoding => 1,
415 Namespaces => 1, NoExpand => 1,
416 Stream_Delimiter => 1, ParseParamEnt => 1,
417 NoLWP => 1, Non_Expat_Options => 1,
418 Xmlns => 1, CssSel => 1,
419 UseTidy => 1, TidyOptions => 1,
420 OutputHtmlDoctype => 1,
421 );
422  
423 my $active_twig; # last active twig,for XML::Twig::s
424  
425 # predefined input and output filters
426 use vars qw( %filter);
427 %filter= ( html => \&html_encode,
428 safe => \&safe_encode,
429 safe_hex => \&safe_encode_hex,
430 );
431  
432 # trigger types (used to sort them)
433 my ($LEVEL_TRIGGER, $REGEXP_TRIGGER, $XPATH_TRIGGER)=(1..3);
434  
435 sub new
436 { my ($class, %args) = @_;
437 my $handlers;
438  
439 # change all nice_perlish_names into nicePerlishNames
440 %args= _normalize_args( %args);
441  
442 # check options
443 unless( $args{MoreOptions})
444 { foreach my $arg (keys %args)
445 { carp "invalid option $arg" unless $valid_option{$arg}; }
446 }
447  
448 # a twig is really an XML::Parser
449 # my $self= XML::Parser->new(%args);
450 my $self;
451 $self= XML::Parser->new(%args);
452  
453 bless $self, $class;
454  
455 $self->{_twig_context_stack}= [];
456  
457 # allow tag.class selectors in handler triggers
458 $css_sel= $args{CssSel};
459  
460 if( exists $args{TwigHandlers})
461 { $handlers= $args{TwigHandlers};
462 $self->setTwigHandlers( $handlers);
463 delete $args{TwigHandlers};
464 }
465  
466 # take care of twig-specific arguments
467 if( exists $args{StartTagHandlers})
468 { $self->setStartTagHandlers( $args{StartTagHandlers});
469 delete $args{StartTagHandlers};
470 }
471  
472 if( exists $args{DoNotChainHandlers})
473 { $self->{twig_do_not_chain_handlers}= $args{DoNotChainHandlers}; }
474  
475 if( exists $args{IgnoreElts})
476 { # change array to hash so you can write ignore_elts => [ qw(foo bar baz)]
477 if( isa( $args{IgnoreElts}, 'ARRAY')) { $args{IgnoreElts}= { map { $_ => 1 } @{$args{IgnoreElts}} }; }
478 $self->setIgnoreEltsHandlers( $args{IgnoreElts});
479 delete $args{IgnoreElts};
480 }
481  
482 if( exists $args{Index})
483 { my $index= $args{Index};
484 # we really want a hash name => path, we turn an array into a hash if necessary
485 if( ref( $index) eq 'ARRAY')
486 { my %index= map { $_ => $_ } @$index;
487 $index= \%index;
488 }
489 while( my( $name, $exp)= each %$index)
490 { $self->setTwigHandler( $exp, sub { push @{$_[0]->{_twig_index}->{$name}}, $_; 1; }); }
491 }
492  
493 $self->{twig_elt_class}= $args{EltClass} || 'XML::Twig::Elt';
494 if( defined( $args{EltClass}) && $args{EltClass} ne 'XML::Twig::Elt') { $self->{twig_alt_elt_class}=1; }
495 if( exists( $args{EltClass})) { delete $args{EltClass}; }
496  
497 if( exists( $args{MapXmlns}))
498 { $self->{twig_map_xmlns}= $args{MapXmlns};
499 $self->{Namespaces}=1;
500 delete $args{MapXmlns};
501 }
502  
503 if( exists( $args{KeepOriginalPrefix}))
504 { $self->{twig_keep_original_prefix}= $args{KeepOriginalPrefix};
505 delete $args{KeepOriginalPrefix};
506 }
507  
508 $self->{twig_dtd_handler}= $args{DTDHandler};
509 delete $args{DTDHandler};
510  
511 if( $args{ExpandExternalEnts})
512 { $self->set_expand_external_entities( 1);
513 $self->{twig_expand_external_ents}= $args{ExpandExternalEnts};
514 $self->{twig_read_external_dtd}= 1; # implied by ExpandExternalEnts
515 if( $args{ExpandExternalEnts} == -1)
516 { $self->{twig_extern_ent_nofail}= 1;
517 $self->setHandlers( ExternEnt => \&_twig_extern_ent_nofail);
518 }
519 delete $args{LoadDTD};
520 delete $args{ExpandExternalEnts};
521 }
522 else
523 { $self->set_expand_external_entities( 0); }
524  
525 if( !$args{NoLWP} && ! _use( 'URI') && ! _use( 'URI::File') && ! _use( 'LWP'))
526 { $self->{twig_ext_ent_handler}= \&XML::Parser::initial_ext_ent_handler }
527 elsif( $args{NoXxe})
528 { $self->{twig_ext_ent_handler}=
529 sub { my($xp, $base, $path) = @_; $xp->{ErrorMessage}.= "cannot use entities in document when the no_xxe option is on"; return undef; };
530 }
531 else
532 { $self->{twig_ext_ent_handler}= \&XML::Parser::file_ext_ent_handler }
533  
534 if( $args{DoNotEscapeAmpInAtts})
535 { $self->set_do_not_escape_amp_in_atts( 1);
536 $self->{twig_do_not_escape_amp_in_atts}=1;
537 }
538 else
539 { $self->set_do_not_escape_amp_in_atts( 0);
540 $self->{twig_do_not_escape_amp_in_atts}=0;
541 }
542  
543 # deal with TwigRoots argument, a hash of elements for which
544 # subtrees will be built (and associated handlers)
545  
546 if( $args{TwigRoots})
547 { $self->setTwigRoots( $args{TwigRoots});
548 delete $args{TwigRoots};
549 }
550  
551 if( $args{EndTagHandlers})
552 { unless ($self->{twig_roots} || $args{ForceEndTagHandlersUsage})
553 { croak "you should not use EndTagHandlers without TwigRoots\n",
554 "if you want to use it anyway, normally because you have ",
555 "a start_tag_handlers that calls 'ignore' and you want to ",
556 "call an ent_tag_handlers at the end of the element, then ",
557 "pass 'force_end_tag_handlers_usage => 1' as an argument ",
558 "to new";
559 }
560  
561 $self->setEndTagHandlers( $args{EndTagHandlers});
562 delete $args{EndTagHandlers};
563 }
564  
565 if( $args{TwigPrintOutsideRoots})
566 { croak "cannot use twig_print_outside_roots without twig_roots"
567 unless( $self->{twig_roots});
568 # if the arg is a filehandle then store it
569 if( _is_fh( $args{TwigPrintOutsideRoots}) )
570 { $self->{twig_output_fh}= $args{TwigPrintOutsideRoots}; }
571 $self->{twig_default_print}= $args{TwigPrintOutsideRoots};
572 }
573  
574 # space policy
575 if( $args{KeepSpaces})
576 { croak "cannot use both keep_spaces and discard_spaces" if( $args{DiscardSpaces});
577 croak "cannot use both keep_spaces and discard_all_spaces" if( $args{DiscardAllSpaces});
578 croak "cannot use both keep_spaces and keep_spaces_in" if( $args{KeepSpacesIn});
579 $self->{twig_keep_spaces}=1;
580 delete $args{KeepSpaces};
581 }
582 if( $args{DiscardSpaces})
583 {
584 croak "cannot use both discard_spaces and keep_spaces_in" if( $args{KeepSpacesIn});
585 croak "cannot use both discard_spaces and discard_all_spaces" if( $args{DiscardAllSpaces});
586 croak "cannot use both discard_spaces and discard_spaces_in" if( $args{DiscardSpacesIn});
587 $self->{twig_discard_spaces}=1;
588 delete $args{DiscardSpaces};
589 }
590 if( $args{KeepSpacesIn})
591 { croak "cannot use both keep_spaces_in and discard_spaces_in" if( $args{DiscardSpacesIn});
592 croak "cannot use both keep_spaces_in and discard_all_spaces" if( $args{DiscardAllSpaces});
593 $self->{twig_discard_spaces}=1;
594 $self->{twig_keep_spaces_in}={};
595 my @tags= @{$args{KeepSpacesIn}};
596 foreach my $tag (@tags) { $self->{twig_keep_spaces_in}->{$tag}=1; }
597 delete $args{KeepSpacesIn};
598 }
599  
600 if( $args{DiscardAllSpaces})
601 {
602 croak "cannot use both discard_all_spaces and discard_spaces_in" if( $args{DiscardSpacesIn});
603 $self->{twig_discard_all_spaces}=1;
604 delete $args{DiscardAllSpaces};
605 }
606  
607 if( $args{DiscardSpacesIn})
608 { $self->{twig_keep_spaces}=1;
609 $self->{twig_discard_spaces_in}={};
610 my @tags= @{$args{DiscardSpacesIn}};
611 foreach my $tag (@tags) { $self->{twig_discard_spaces_in}->{$tag}=1; }
612 delete $args{DiscardSpacesIn};
613 }
614 # discard spaces by default
615 $self->{twig_discard_spaces}= 1 unless( $self->{twig_keep_spaces});
616  
617 $args{Comments}||= $COMMENTS_DEFAULT;
618 if( $args{Comments} eq 'drop') { $self->{twig_keep_comments}= 0; }
619 elsif( $args{Comments} eq 'keep') { $self->{twig_keep_comments}= 1; }
620 elsif( $args{Comments} eq 'process') { $self->{twig_process_comments}= 1; }
621 else { croak "wrong value for comments argument: '$args{Comments}' (should be 'drop', 'keep' or 'process')"; }
622 delete $args{Comments};
623  
624 $args{Pi}||= $PI_DEFAULT;
625 if( $args{Pi} eq 'drop') { $self->{twig_keep_pi}= 0; }
626 elsif( $args{Pi} eq 'keep') { $self->{twig_keep_pi}= 1; }
627 elsif( $args{Pi} eq 'process') { $self->{twig_process_pi}= 1; }
628 else { croak "wrong value for pi argument: '$args{Pi}' (should be 'drop', 'keep' or 'process')"; }
629 delete $args{Pi};
630  
631 if( $args{KeepEncoding})
632 {
633 # set it in XML::Twig::Elt so print functions know what to do
634 $self->set_keep_encoding( 1);
635 $self->{parse_start_tag}= $args{ParseStartTag} || \&_parse_start_tag;
636 delete $args{ParseStartTag} if defined( $args{ParseStartTag}) ;
637 delete $args{KeepEncoding};
638 }
639 else
640 { $self->set_keep_encoding( 0);
641 if( $args{ParseStartTag})
642 { $self->{parse_start_tag}= $args{ParseStartTag}; }
643 else
644 { delete $self->{parse_start_tag}; }
645 delete $args{ParseStartTag};
646 }
647  
648 if( $args{OutputFilter})
649 { $self->set_output_filter( $args{OutputFilter});
650 delete $args{OutputFilter};
651 }
652 else
653 { $self->set_output_filter( 0); }
654  
655 if( $args{RemoveCdata})
656 { $self->set_remove_cdata( $args{RemoveCdata});
657 delete $args{RemoveCdata};
658 }
659 else
660 { $self->set_remove_cdata( 0); }
661  
662 if( $args{OutputTextFilter})
663 { $self->set_output_text_filter( $args{OutputTextFilter});
664 delete $args{OutputTextFilter};
665 }
666 else
667 { $self->set_output_text_filter( 0); }
668  
669 if( $args{KeepAttsOrder})
670 { $self->{keep_atts_order}= $args{KeepAttsOrder};
671 if( _use( 'Tie::IxHash'))
672 { $self->set_keep_atts_order( $self->{keep_atts_order}); }
673 else
674 { croak "Tie::IxHash not available, option keep_atts_order not allowed"; }
675 }
676 else
677 { $self->set_keep_atts_order( 0); }
678  
679 if( $args{PrettyPrint}) { $self->set_pretty_print( $args{PrettyPrint}); }
680 if( $args{EscapeGt}) { $self->escape_gt( $args{EscapeGt}); }
681 if( $args{EmptyTags}) { $self->set_empty_tag_style( $args{EmptyTags}) }
682  
683 if( exists $args{Id}) { $ID= $args{Id}; delete $args{ID}; }
684 if( $args{NoProlog}) { $self->{no_prolog}= 1; delete $args{NoProlog}; }
685 if( $args{DoNotOutputDTD}) { $self->{no_dtd_output}= 1; delete $args{DoNotOutputDTD}; }
686 if( $args{LoadDTD}) { $self->{twig_read_external_dtd}= 1; delete $args{LoadDTD}; }
687 if( $args{CharHandler}) { $self->setCharHandler( $args{CharHandler}); delete $args{CharHandler}; }
688  
689 if( $args{InputFilter}) { $self->set_input_filter( $args{InputFilter}); delete $args{InputFilter}; }
690 if( $args{NoExpand}) { $self->setHandlers( %twig_noexpand_handlers); $self->{twig_no_expand}=1; }
691 if( my $output_encoding= $args{OutputEncoding}) { $self->set_output_encoding( $output_encoding); delete $args{OutputFilter}; }
692  
693 if( my $tdh= $args{TopDownHandlers}) { $self->{twig_tdh}=1; delete $args{TopDownHandlers}; }
694  
695 if( my $acc_a= $args{AttAccessors}) { $self->att_accessors( @$acc_a); }
696 if( my $acc_e= $args{EltAccessors}) { $self->elt_accessors( isa( $acc_e, 'ARRAY') ? @$acc_e : $acc_e); }
697 if( my $acc_f= $args{FieldAccessors}) { $self->field_accessors( isa( $acc_f, 'ARRAY') ? @$acc_f : $acc_f); }
698  
699 if( $args{UseTidy}) { $self->{use_tidy}= 1; }
700 $self->{tidy_options}= $args{TidyOptions} || {};
701  
702 if( $args{OutputHtmlDoctype}) { $self->{html_doctype}= 1; }
703  
704 $self->set_quote( $args{Quote} || 'double');
705  
706 # set handlers
707 if( $self->{twig_roots})
708 { if( $self->{twig_default_print})
709 { if( $self->{twig_keep_encoding})
710 { $self->setHandlers( %twig_handlers_roots_print_original); }
711 else
712 { $self->setHandlers( %twig_handlers_roots_print); }
713 }
714 else
715 { $self->setHandlers( %twig_handlers_roots); }
716 }
717 else
718 { $self->setHandlers( %twig_handlers); }
719  
720 # XML::Parser::Expat does not like these handler to be set. So in order to
721 # use the various sets of handlers on XML::Parser or XML::Parser::Expat
722 # objects when needed, these ones have to be set only once, here, at
723 # XML::Parser level
724 $self->setHandlers( Init => \&_twig_init, Final => \&_twig_final);
725  
726 $self->{twig_entity_list}= XML::Twig::Entity_list->new;
727 $self->{twig_notation_list}= XML::Twig::Notation_list->new;
728  
729 $self->{twig_id}= $ID;
730 $self->{twig_stored_spaces}='';
731  
732 $self->{twig_autoflush}= 1; # auto flush by default
733  
734 $self->{twig}= $self;
735 if( $weakrefs) { weaken( $self->{twig}); }
736  
737 return $self;
738 }
739  
740 sub parse
741 {
742 my $t= shift;
743 # if called as a class method, calls nparse, which creates the twig then parses it
744 if( !ref( $t) || !isa( $t, 'XML::Twig')) { return $t->nparse( @_); }
745  
746 # trap underlying bug in IO::Handle (see RT #17500)
747 # croak if -CD (or PERL_UNICODE set to D) and parsing a pipe
748 if( ${^UNICODE} && (${^UNICODE} & 24) && isa( $_[0], 'GLOB') && -p $_[0] )
749 { croak "cannot parse the output of a pipe when perl is set to use the UTF8 perlIO layer\n"
750 . "set the environment variable PERL_UNICODE or use the -C option (see perldoc perlrun)\n"
751 . "not to include 'D'";
752 }
753 $t= eval { $t->SUPER::parse( @_); };
754  
755 if( !$t
756 && $@=~m{(syntax error at line 1, column 0, byte 0|not well-formed \(invalid token\) at line 1, column 1, byte 1)}
757 && -f $_[0]
758 && ( ! ref( $_[0]) || ref( $_[0])) ne 'GLOB' # -f works on a filehandle, so this make sure $_[0] is a real file
759 )
760 { croak "you seem to have used the parse method on a filename ($_[0]), you probably want parsefile instead"; }
761 return _checked_parse_result( $t, $@);
762 }
763  
764 sub parsefile
765 { my $t= shift;
766 if( -f $_[0] && ! -s $_[0]) { return _checked_parse_result( undef, "empty file '$_[0]'"); }
767 $t= eval { $t->SUPER::parsefile( @_); };
768 return _checked_parse_result( $t, $@);
769 }
770  
771 sub _checked_parse_result
772 { my( $t, $returned)= @_;
773 if( !$t)
774 { if( isa( $returned, 'XML::Twig') && $returned->{twig_finish_now})
775 { $t= $returned;
776 delete $t->{twig_finish_now};
777 return $t->_twig_final;
778 }
779 else
780 { _croak( $returned, 0); }
781 }
782  
783 $active_twig= $t;
784 return $t;
785 }
786  
787 sub active_twig { return $active_twig; }
788  
789 sub finish_now
790 { my $t= shift;
791 $t->{twig_finish_now}=1;
792 # XML::Parser 2.43 changed xpcroak in a way that caused test failures for XML::Twig
793 # the change was reverted in 2.44, but this is here to ensure that tests pass with 2.43
794 if( $XML::Parser::VERSION == 2.43)
795 { no warnings;
796 $t->parser->{twig_error}= $t;
797 *XML::Parser::Expat::xpcroak= sub { die $_[0]->{twig_error}; };
798 die $t;
799 }
800 else
801 { die $t; }
802 }
803  
804 sub parsefile_inplace { shift->_parse_inplace( parsefile => @_); }
805 sub parsefile_html_inplace { shift->_parse_inplace( parsefile_html => @_); }
806  
807 sub _parse_inplace
808 { my( $t, $method, $file, $suffix)= @_;
809 _use( 'File::Temp') || croak "need File::Temp to use inplace methods\n";
810 _use( 'File::Basename');
811  
812 my $tmpdir= dirname( $file);
813 my( $tmpfh, $tmpfile)= File::Temp::tempfile( DIR => $tmpdir);
814 my $original_fh= select $tmpfh;
815  
816 # we can only use binmode :utf8 if perl was compiled with useperlio
817 # might be a problem if keep_encoding used but the file is already in utf8
818 if( !$t->{twig_keep_encoding} && _use_perlio()) { binmode( $tmpfh, ":utf8" ); } ## no critic (RequireEncodingWithUTF8Layer)
819  
820 $t->$method( $file);
821  
822 select $original_fh;
823 close $tmpfh;
824 my $mode= (stat( $file))[2] & oct(7777);
825 chmod $mode, $tmpfile or croak "cannot change temp file mode to $mode: $!";
826  
827 if( $suffix)
828 { my $backup;
829 if( $suffix=~ m{\*}) { ($backup = $suffix) =~ s/\*/$file/g; }
830 else { $backup= $file . $suffix; }
831  
832 rename( $file, $backup) or croak "cannot backup initial file ($file) to $backup: $!";
833 }
834 rename( $tmpfile, $file) or croak "cannot rename temp file ($tmpfile) to initial file ($file): $!";
835  
836 return $t;
837 }
838  
839 sub parseurl
840 { my $t= shift;
841 $t->_parseurl( 0, @_);
842 }
843  
844 sub safe_parseurl
845 { my $t= shift;
846 $t->_parseurl( 1, @_);
847 }
848  
849 sub safe_parsefile_html
850 { my $t= shift;
851 eval { $t->parsefile_html( @_); };
852 return $@ ? $t->_reset_twig_after_error : $t;
853 }
854  
855 sub safe_parseurl_html
856 { my $t= shift;
857 _use( 'LWP::Simple') or croak "missing LWP::Simple";
858 eval { $t->parse_html( LWP::Simple::get( shift()), @_); } ;
859 return $@ ? $t->_reset_twig_after_error : $t;
860 }
861  
862 sub parseurl_html
863 { my $t= shift;
864 _use( 'LWP::Simple') or croak "missing LWP::Simple";
865 $t->parse_html( LWP::Simple::get( shift()), @_);
866 }
867  
868 # uses eval to catch the parser's death
869 sub safe_parse_html
870 { my $t= shift;
871 eval { $t->parse_html( @_); } ;
872 return $@ ? $t->_reset_twig_after_error : $t;
873 }
874  
875 sub parsefile_html
876 { my $t= shift;
877 my $file= shift;
878 my $indent= $t->{ErrorContext} ? 1 : 0;
879 $t->set_empty_tag_style( 'html');
880 my $html2xml= $t->{use_tidy} ? \&_tidy_html : \&_html2xml;
881 my $options= $t->{use_tidy} ? $t->{tidy_options} || {} : { indent => $indent, html_doctype => $t->{html_doctype} };
882 $t->parse( $html2xml->( _slurp( $file), $options), @_);
883 return $t;
884 }
885  
886 sub parse_html
887 { my $t= shift;
888 my $options= ref $_[0] && ref $_[0] eq 'HASH' ? shift() : {};
889 my $use_tidy= exists $options->{use_tidy} ? $options->{use_tidy} : $t->{use_tidy};
890 my $content= shift;
891 my $indent= $t->{ErrorContext} ? 1 : 0;
892 $t->set_empty_tag_style( 'html');
893 my $html2xml= $use_tidy ? \&_tidy_html : \&_html2xml;
894 my $conv_options= $use_tidy ? $t->{tidy_options} || {} : { indent => $indent, html_doctype => $t->{html_doctype} };
895 $t->parse( $html2xml->( isa( $content, 'GLOB') ? _slurp_fh( $content) : $content, $conv_options), @_);
896 return $t;
897 }
898  
899 sub xparse
900 { my $t= shift;
901 my $to_parse= $_[0];
902 if( isa( $to_parse, 'GLOB')) { $t->parse( @_); }
903 elsif( $to_parse=~ m{^\s*<}) { $to_parse=~ m{<html}i ? $t->_parse_as_xml_or_html( @_)
904 : $t->parse( @_);
905 }
906 elsif( $to_parse=~ m{^\w+://.*\.html?$}) { _use( 'LWP::Simple') or croak "missing LWP::Simple";
907 $t->_parse_as_xml_or_html( LWP::Simple::get( shift()), @_);
908 }
909 elsif( $to_parse=~ m{^\w+://}) { _use( 'LWP::Simple') or croak "missing LWP::Simple";
910 my $doc= LWP::Simple::get( shift);
911 if( ! defined $doc) { $doc=''; }
912 my $xml_parse_ok= $t->safe_parse( $doc, @_);
913 if( $xml_parse_ok)
914 { return $xml_parse_ok; }
915 else
916 { my $diag= $@;
917 if( $doc=~ m{<html}i)
918 { $t->parse_html( $doc, @_); }
919 else
920 { croak $diag; }
921 }
922 }
923 elsif( $to_parse=~ m{\.html?$}) { my $content= _slurp( shift);
924 $t->_parse_as_xml_or_html( $content, @_);
925 }
926 else { $t->parsefile( @_); }
927 }
928  
929 sub _parse_as_xml_or_html
930 { my $t= shift;
931 if( _is_well_formed_xml( $_[0]))
932 { $t->parse( @_) }
933 else
934 { my $html2xml= $t->{use_tidy} ? \&_tidy_html : \&_html2xml;
935 my $options= $t->{use_tidy} ? $t->{tidy_options} || {} : { indent => 0, html_doctype => $t->{html_doctype} };
936 my $html= $html2xml->( $_[0], $options, @_);
937 if( _is_well_formed_xml( $html))
938 { $t->parse( $html); }
939 else
940 { croak $@; } # can't really test this because HTML::Parser or HTML::Tidy may change how they deal with bas HTML between versions
941 }
942 }
943  
944 { my $parser;
945 sub _is_well_formed_xml
946 { $parser ||= XML::Parser->new;
947 eval { $parser->parse( $_[0]); };
948 return $@ ? 0 : 1;
949 }
950 }
951  
952 sub nparse
953 { my $class= shift;
954 my $to_parse= pop;
955 $class->new( @_)->xparse( $to_parse);
956 }
957  
958 sub nparse_pp { shift()->nparse( pretty_print => 'indented', @_); }
959 sub nparse_e { shift()->nparse( error_context => 1, @_); }
960 sub nparse_ppe { shift()->nparse( pretty_print => 'indented', error_context => 1, @_); }
961  
962 sub _html2xml
963 { my( $html, $options)= @_;
964 _use( 'HTML::TreeBuilder', '3.13') or croak "cannot parse HTML: missing HTML::TreeBuilder v >= 3.13\n";
965 my $tree= HTML::TreeBuilder->new;
966 $tree->ignore_ignorable_whitespace( 0);
967 $tree->ignore_unknown( 0);
968 $tree->no_space_compacting( 1);
969 $tree->store_comments( 1);
970 $tree->store_pis(1);
971 $tree->parse( $html);
972 $tree->eof;
973  
974 my $xml='';
975 if( $options->{html_doctype} && exists $tree->{_decl} )
976 { my $decl= $tree->{_decl}->as_XML;
977  
978 # first try to fix declarations that are missing the SYSTEM part
979 $decl =~ s{^\s*<!DOCTYPE \s+ ((?i)html) \s+ PUBLIC \s+ "([^"]*)" \s* >}
980 { my $system= $HTML_DECL{$2} || $HTML_DECL{$DEFAULT_HTML_TYPE};
981 qq{<!DOCTYPE $1 PUBLIC "$2" "$system">}
982  
983 }xe;
984  
985 # then check that the declaration looks OK (so it parses), if not remove it,
986 # better to parse without the declaration than to die stupidly
987 if( $decl =~ m{<!DOCTYPE \s+ (?i:HTML) (\s+ PUBLIC \s+ "[^"]*" \s+ (SYSTEM \s+)? "[^"]*")? \s*>}x # PUBLIC then SYSTEM
988 || $decl =~ m{<!DOCTYPE \s+ (?i:HTML) \s+ SYSTEM \s+ "[^"]*" \s*>}x # just SYSTEM
989 )
990 { $xml= $decl; }
991 }
992  
993 $xml.= _as_XML( $tree);
994  
995 _fix_xml( $tree, \$xml);
996  
997 if( $options->{indent}) { _indent_xhtml( \$xml); }
998 $tree->delete;
999 $xml=~ s{\s+$}{}s; # trim end
1000 return $xml;
1001 }
1002  
1003 sub _tidy_html
1004 { my( $html, $options)= @_;
1005 _use( 'HTML::Tidy') or croak "cannot cleanup HTML using HTML::Tidy (required by the use_tidy option): $@\n"; ;
1006 my $TIDY_DEFAULTS= { output_xhtml => 1, # duh!
1007 tidy_mark => 0, # do not add the "generated by tidy" comment
1008 numeric_entities => 1,
1009 char_encoding => 'utf8',
1010 bare => 1,
1011 clean => 1,
1012 doctype => 'transitional',
1013 fix_backslash => 1,
1014 merge_divs => 0,
1015 merge_spans => 0,
1016 sort_attributes => 'alpha',
1017 indent => 0,
1018 wrap => 0,
1019 break_before_br => 0,
1020 };
1021 $options ||= {};
1022 my $tidy_options= { %$TIDY_DEFAULTS, %$options};
1023 my $tidy = HTML::Tidy->new( $tidy_options);
1024 $tidy->ignore( type => 1, type => 2 ); # 1 is TIDY_WARNING, 2 is TIDY_ERROR, not clean
1025 my $xml= $tidy->clean( $html );
1026 return $xml;
1027 }
1028  
1029 { my %xml_parser_encoding;
1030 sub _fix_xml
1031 { my( $tree, $xml)= @_; # $xml is a ref to the xml string
1032  
1033 my $max_tries=5;
1034 my $add_decl;
1035  
1036 while( ! _check_xml( $xml) && $max_tries--)
1037 {
1038 # a couple of fixes for weird HTML::TreeBuilder errors
1039 if( $@=~ m{^\s*xml (or text )?declaration not at start of (external )?entity}i)
1040 { $$xml=~ s{<\?xml.*?\?>}{}g;
1041 #warn " fixed xml declaration in the wrong place\n";
1042 }
1043 elsif( $@=~ m{undefined entity})
1044 { $$xml=~ s{&(amp;)?Amp;}{&amp;}g if $HTML::TreeBuilder::VERSION < 4.00;
1045 if( _use( 'HTML::Entities::Numbered')) { $$xml=name2hex_xml( $$xml); }
1046 $$xml=~ s{&(\w+);}{ my $ent= $1; if( $ent !~ m{^(amp|lt|gt|apos|quote)$}) { "&amp;$ent;" } }eg;
1047 }
1048 elsif( $@=~ m{&Amp; used in html})
1049 # if $Amp; is used instead of &amp; then HTML::TreeBuilder's as_xml is tripped (old version)
1050 { $$xml=~ s{&(amp;)?Amp;}{&amp;}g if $HTML::TreeBuilder::VERSION < 4.00;
1051 }
1052 elsif( $@=~ m{^\s*not well-formed \(invalid token\)})
1053 { if( $HTML::TreeBuilder::VERSION < 4.00)
1054 { $$xml=~ s{&(amp;)?Amp;}{&amp;}g;
1055 $$xml=~ s{(<[^>]* )(\d+=)"}{$1a$2"}g; # <table 1> comes out as <table 1="1">, "fix the attribute
1056 }
1057 my $q= '<img "="&#34;" '; # extracted so vim doesn't get confused
1058 if( _use( 'HTML::Entities::Numbered')) { $$xml=name2hex_xml( $$xml); }
1059 if( $$xml=~ m{$q})
1060 { $$xml=~ s{$q}{<img }g; # happens with <img src="foo.png"" ...
1061 }
1062 else
1063 { my $encoding= _encoding_from_meta( $tree);
1064 unless( keys %xml_parser_encoding) { %xml_parser_encoding= _xml_parser_encodings(); }
1065  
1066 if( ! $add_decl)
1067 { if( $xml_parser_encoding{$encoding})
1068 { $add_decl=1; }
1069 elsif( $encoding eq 'euc-jp' && $xml_parser_encoding{'x-euc-jp-jisx0221'})
1070 { $encoding="x-euc-jp-jisx0221"; $add_decl=1;}
1071 elsif( $encoding eq 'shift-jis' && $xml_parser_encoding{'x-sjis-jisx0221'})
1072 { $encoding="x-sjis-jisx0221"; $add_decl=1;}
1073  
1074 if( $add_decl)
1075 { $$xml=~ s{^(<\?xml.*?\?>)?}{<?xml version="1.0" encoding="$encoding"?>}s;
1076 #warn " added decl (encoding $encoding)\n";
1077 }
1078 else
1079 { $$xml=~ s{^(<\?xml.*?\?>)?}{}s;
1080 #warn " converting to utf8 from $encoding\n";
1081 $$xml= _to_utf8( $encoding, $$xml);
1082 }
1083 }
1084 else
1085 { $$xml=~ s{^(<\?xml.*?\?>)?}{}s;
1086 #warn " converting to utf8 from $encoding\n";
1087 $$xml= _to_utf8( $encoding, $$xml);
1088 }
1089 }
1090 }
1091 }
1092  
1093 # some versions of HTML::TreeBuilder escape CDATA sections
1094 $$xml=~ s{(&lt;!\[CDATA\[.*?\]\]&gt;)}{_unescape_cdata( $1)}eg;
1095 }
1096  
1097 sub _xml_parser_encodings
1098 { my @encodings=( 'iso-8859-1'); # this one is included by default, there is no map for it in @INC
1099 foreach my $inc (@INC)
1100 { push @encodings, map { basename( $_, '.enc') } glob( File::Spec->catdir( $inc => XML => Parser => Encodings => '*.enc')); }
1101 return map { $_ => 1 } @encodings;
1102 }
1103 }
1104  
1105 sub _unescape_cdata
1106 { my( $cdata)= @_;
1107 $cdata=~s{&lt;}{<}g;
1108 $cdata=~s{&gt;}{>}g;
1109 $cdata=~s{&amp;}{&}g;
1110 return $cdata;
1111 }
1112  
1113 sub _as_XML {
1114  
1115 # fork of HTML::Element::as_XML, which is a little too buggy and inconsistent between versions for my liking
1116 my ($elt) = @_;
1117 my $xml= '';
1118 my $empty_element_map = $elt->_empty_element_map;
1119  
1120 my ( $tag, $node, $start ); # per-iteration scratch
1121 $elt->traverse(
1122 sub {
1123 ( $node, $start ) = @_;
1124 if ( ref $node )
1125 { # it's an element
1126 $tag = $node->{'_tag'};
1127 if ($start)
1128 { # on the way in
1129 foreach my $att ( grep { ! m{^(_|/$)} } keys %$node )
1130 { # fix attribute names instead of dying
1131 my $new_att= $att;
1132 if( $att=~ m{^\d}) { $new_att= "a$att"; }
1133 $new_att=~ s{[^\w\d:_-]}{}g;
1134 $new_att ||= 'a';
1135 if( $new_att ne $att) { $node->{$new_att}= delete $node->{$att}; }
1136 }
1137  
1138 if ( $empty_element_map->{$tag} && (!@{ $node->{'_content'} || []}) )
1139 { $xml.= $node->starttag_XML( undef, 1 ); }
1140 else
1141 { $xml.= $node->starttag_XML(undef); }
1142 }
1143 else
1144 { # on the way out
1145 unless ( $empty_element_map->{$tag} and !@{ $node->{'_content'} || [] } )
1146 { $xml.= $node->endtag_XML();
1147 } # otherwise it will have been an <... /> tag.
1148 }
1149 }
1150 elsif( $node=~ /<!\[CDATA\[/) # the content includes CDATA
1151 { foreach my $chunk (split /(<!\[CDATA\[.*?\]\]>)/s, $node) # chunks are CDATA sections or normal text
1152 { $xml.= $chunk =~ m{<!\[CDATA\[} ? $chunk : _xml_escape( $chunk); }
1153 }
1154 else # it's just text
1155 { $xml .= _xml_escape($node); }
1156 1; # keep traversing
1157 }
1158 );
1159 return $xml;
1160 }
1161  
1162 sub _xml_escape
1163 { my( $html)= @_;
1164 $html =~ s{&(?! # An ampersand that isn't followed by...
1165 ( \#[0-9]+; | # A hash mark, digits and semicolon, or
1166 \#x[0-9a-fA-F]+; | # A hash mark, "x", hex digits and semicolon, or
1167 [\w]+; # A valid unicode entity name and semicolon
1168 )
1169 )
1170 }
1171 {&amp;}gx if 0; # Needs to be escaped to amp
1172  
1173 $html=~ s{&}{&amp;}g;
1174  
1175 # in old versions of HTML::TreeBuilder &amp; can come out as &Amp;
1176 if( $HTML::TreeBuilder::VERSION && $HTML::TreeBuilder::VERSION <= 3.23) { $html=~ s{&Amp;}{&amp;}g; }
1177  
1178 # simple character escapes
1179 $html =~ s/</&lt;/g;
1180 $html =~ s/>/&gt;/g;
1181 $html =~ s/"/&quot;/g;
1182 $html =~ s/'/&apos;/g;
1183  
1184 return $html;
1185 }
1186  
1187 sub _check_xml
1188 { my( $xml)= @_; # $xml is a ref to the xml string
1189 my $ok= eval { XML::Parser->new->parse( $$xml); };
1190 return $ok;
1191 }
1192  
1193 sub _encoding_from_meta
1194 { my( $tree)= @_;
1195 my $enc="iso-8859-1";
1196 my @meta= $tree->find( 'meta');
1197 foreach my $meta (@meta)
1198 { if( $meta->{'http-equiv'} && ($meta->{'http-equiv'} =~ m{^\s*content-type\s*}i)
1199 && $meta->{content} && ($meta->{content} =~ m{^\s*text/html\s*;\s*charset\s*=\s*(\S*)\s*}i)
1200 )
1201 { $enc= lc $1;
1202 #warn " encoding from meta tag is '$enc'\n";
1203 last;
1204 }
1205 }
1206 return $enc;
1207 }
1208  
1209 { sub _to_utf8
1210 { my( $encoding, $string)= @_;
1211 local $SIG{__DIE__};
1212 if( _use( 'Encode'))
1213 { Encode::from_to( $string, $encoding => 'utf8', 0x0400); } # 0x0400 is Encode::FB_XMLCREF
1214 elsif( _use( 'Text::Iconv'))
1215 { my $converter = eval { Text::Iconv->new( $encoding => "utf8") };
1216 if( $converter) { $string= $converter->convert( $string); }
1217 }
1218 elsif( _use( 'Unicode::Map8') && _use( 'Unicode::String'))
1219 { my $map= Unicode::Map8->new( $encoding);
1220 $string= $map->tou( $string)->utf8;
1221 }
1222 $string=~ s{[\x00-\x08\x0B\x0C\x0E-\x1F]}{}g; # get rid of control chars
1223 return $string;
1224 }
1225 }
1226  
1227 sub _indent_xhtml
1228 { my( $xhtml)= @_; # $xhtml is a ref
1229 my %block_tag= map { $_ => 1 } qw( html
1230 head
1231 meta title link script base
1232 body
1233 h1 h2 h3 h4 h5 h6
1234 p br address blockquote pre
1235 ol ul li dd dl dt
1236 table tr td th tbody tfoot thead col colgroup caption
1237 div frame frameset hr
1238 );
1239  
1240 my $level=0;
1241 $$xhtml=~ s{( (?:<!(?:--.*?-->|[CDATA[.*?]]>)) # ignore comments and CDATA sections
1242 | <(\w+)((?:\s+\w+\s*=\s*(?:"[^"]*"|'[^']*'))*\s*/>) # empty tag
1243 | <(\w+) # start tag
1244 |</(\w+) # end tag
1245 )
1246 }
1247 { if( $2 && $block_tag{$2}) { my $indent= " " x $level;
1248 "\n$indent<$2$3";
1249 }
1250 elsif( $4 && $block_tag{$4}) { my $indent= " " x $level;
1251 $level++ unless( $4=~ m{/>});
1252 my $nl= $4 eq 'html' ? '' : "\n";
1253 "$nl$indent<$4";
1254 }
1255 elsif( $5 && $block_tag{$5}) { $level--; "</$5"; }
1256 else { $1; }
1257 }xesg;
1258 }
1259  
1260 sub add_stylesheet
1261 { my( $t, $type, $href)= @_;
1262 my %text_type= map { $_ => 1 } qw( xsl css);
1263 my $ss= $t->{twig_elt_class}->new( $PI);
1264 if( $text_type{$type})
1265 { $ss->_set_pi( 'xml-stylesheet', qq{type="text/$type" href="$href"}); }
1266 else
1267 { croak "unsupported style sheet type '$type'"; }
1268  
1269 $t->_add_cpi_outside_of_root( leading_cpi => $ss);
1270 return $t;
1271 }
1272  
1273 { my %used; # module => 1 if require ok, 0 otherwise
1274 my %disallowed; # for testing, refuses to _use modules in this hash
1275  
1276 sub _disallow_use ## no critic (Subroutines::ProhibitNestedSubs);
1277 { my( @modules)= @_;
1278 $disallowed{$_}= 1 foreach (@modules);
1279 }
1280  
1281 sub _allow_use ## no critic (Subroutines::ProhibitNestedSubs);
1282 { my( @modules)= @_;
1283 $disallowed{$_}= 0 foreach (@modules);
1284 }
1285  
1286 sub _use ## no critic (Subroutines::ProhibitNestedSubs);
1287 { my( $module, $version)= @_;
1288 $version ||= 0;
1289 if( $disallowed{$module}) { return 0; }
1290 if( $used{$module}) { return 1; }
1291 if( eval "require $module") { import $module; $used{$module}= 1; ## no critic ProhibitStringyEval
1292 if( $version)
1293 {
1294 ## no critic (TestingAndDebugging::ProhibitNoStrict);
1295 no strict 'refs';
1296 if( ${"${module}::VERSION"} >= $version ) { return 1; }
1297 else { return 0; }
1298 }
1299 else
1300 { return 1; }
1301 }
1302 else { $used{$module}= 0; return 0; }
1303 }
1304 }
1305  
1306 # used to solve the [n] predicates while avoiding getting the entire list
1307 # needs a prototype to accept passing bare blocks
1308 sub _first_n(&$@) ## no critic (Subroutines::ProhibitSubroutinePrototypes);
1309 { my $coderef= shift;
1310 my $n= shift;
1311 my $i=0;
1312 if( $n > 0)
1313 { foreach (@_) { if( &$coderef) { $i++; return $_ if( $i == $n); } } }
1314 elsif( $n < 0)
1315 { foreach (reverse @_) { if( &$coderef) { $i--; return $_ if( $i == $n); } } }
1316 else
1317 { croak "illegal position number 0"; }
1318 return undef;
1319 }
1320  
1321 sub _slurp_uri
1322 { my( $uri, $base)= @_;
1323 if( $uri=~ m{^\w+://}) { _use( 'LWP::Simple'); return LWP::Simple::get( $uri); }
1324 else { return _slurp( _based_filename( $uri, $base)); }
1325 }
1326  
1327 sub _based_filename
1328 { my( $filename, $base)= @_;
1329 # cf. XML/Parser.pm's file_ext_ent_handler
1330 if (defined($base) and not ($filename =~ m{^(?:[\\/]|\w+:)}))
1331 { my $newpath = $base;
1332 $newpath =~ s{[^\\/:]*$}{$filename};
1333 $filename = $newpath;
1334 }
1335 return $filename;
1336 }
1337  
1338 sub _slurp
1339 { my( $filename)= @_;
1340 my $to_slurp;
1341 open( $to_slurp, "<$filename") or croak "cannot open '$filename': $!";
1342 local $/= undef;
1343 my $content= <$to_slurp>;
1344 close $to_slurp;
1345 return $content;
1346 }
1347  
1348 sub _slurp_fh
1349 { my( $fh)= @_;
1350 local $/= undef;
1351 my $content= <$fh>;
1352 return $content;
1353 }
1354  
1355 # I should really add extra options to allow better configuration of the
1356 # LWP::UserAgent object
1357 # this method forks (except on VMS!)
1358 # - the child gets the data and copies it to the pipe,
1359 # - the parent reads the stream and sends it to XML::Parser
1360 # the data is cut it chunks the size of the XML::Parser::Expat buffer
1361 # the method returns the twig and the status
1362 sub _parseurl
1363 { my( $t, $safe, $url, $agent)= @_;
1364 _use( 'LWP') || croak "LWP not available, needed to use parseurl methods";
1365 if( $^O ne 'VMS')
1366 { pipe( README, WRITEME) or croak "cannot create connected pipes: $!";
1367 if( my $pid= fork)
1368 { # parent code: parse the incoming file
1369 close WRITEME; # no need to write
1370 my $result= $safe ? $t->safe_parse( \*README) : $t->parse( \*README);
1371 close README;
1372 return $@ ? 0 : $t;
1373 }
1374 else
1375 { # child
1376 close README; # no need to read
1377 local $|=1;
1378 $agent ||= LWP::UserAgent->new;
1379 my $request = HTTP::Request->new( GET => $url);
1380 # _pass_url_content is called with chunks of data the same size as
1381 # the XML::Parser buffer
1382 my $response = $agent->request( $request,
1383 sub { _pass_url_content( \*WRITEME, @_); }, $BUFSIZE);
1384 $response->is_success or croak "$url ", $response->message;
1385 close WRITEME;
1386 CORE::exit(); # CORE is there for mod_perl (which redefines exit)
1387 }
1388 }
1389 else
1390 { # VMS branch (hard to test!)
1391 local $|=1;
1392 $agent ||= LWP::UserAgent->new;
1393 my $request = HTTP::Request->new( GET => $url);
1394 my $response = $agent->request( $request);
1395 $response->is_success or croak "$url ", $response->message;
1396 my $result= $safe ? $t->safe_parse($response->content) : $t->parse($response->content);
1397 return $@ ? 0 : $t;
1398 }
1399  
1400 }
1401  
1402 # get the (hopefully!) XML data from the URL and
1403 sub _pass_url_content
1404 { my( $fh, $data, $response, $protocol)= @_;
1405 print {$fh} $data;
1406 }
1407  
1408 sub add_options
1409 { my %args= map { $_, 1 } @_;
1410 %args= _normalize_args( %args);
1411 foreach (keys %args) { $valid_option{$_}++; }
1412 }
1413  
1414 sub _pretty_print_styles { return XML::Twig::Elt::_pretty_print_styles(); }
1415  
1416 sub _twig_store_internal_dtd
1417 {
1418 # warn " in _twig_store_internal_dtd...\n"; # DEBUG handler
1419 my( $p, $string)= @_;
1420 my $t= $p->{twig};
1421 if( $t->{twig_keep_encoding}) { $string= $p->original_string(); }
1422 $t->{twig_doctype}->{internal} .= $string;
1423 return;
1424 }
1425  
1426 sub _twig_stop_storing_internal_dtd
1427 { # warn " in _twig_stop_storing_internal_dtd...\n"; # DEBUG handler
1428 my $p= shift;
1429 if( @saved_default_handler && defined $saved_default_handler[1])
1430 { $p->setHandlers( @saved_default_handler); }
1431 else
1432 {
1433 $p->setHandlers( Default => undef);
1434 }
1435 $p->{twig}->{twig_doctype}->{internal}=~ s{^\s*\[}{};
1436 $p->{twig}->{twig_doctype}->{internal}=~ s{\]\s*$}{};
1437 return;
1438 }
1439  
1440 sub _twig_doctype_fin_print
1441 { # warn " in _twig_doctype_fin_print...\n"; # DEBUG handler
1442 my( $p)= shift;
1443 if( $p->{twig}->{twig_doctype}->{has_internal} && !$expat_1_95_2) { print ' ]>'; }
1444 return;
1445 }
1446  
1447 sub _normalize_args
1448 { my %normalized_args;
1449 while( my $key= shift )
1450 { $key= join '', map { ucfirst } split /_/, $key;
1451 #$key= "Twig".$key unless( substr( $key, 0, 4) eq 'Twig');
1452 $normalized_args{$key}= shift ;
1453 }
1454 return %normalized_args;
1455 }
1456  
1457 sub _is_fh { return unless $_[0]; return $_[0] if( isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar')); }
1458  
1459 sub _set_handler
1460 { my( $handlers, $whole_path, $handler)= @_;
1461  
1462 my $H_SPECIAL = qr{($ALL|$DEFAULT|$COMMENT|$TEXT)};
1463 my $H_PI = qr{(\?|$PI)\s*(([^\s]*)\s*)};
1464 my $H_LEVEL = qr{level \s* \( \s* ([0-9]+) \s* \)}x;
1465 my $H_REGEXP = qr{\(\?([\^xism]*)(-[\^xism]*)?:(.*)\)}x;
1466 my $H_XPATH = qr{(/?/?$REG_TAG_PART? \s* ($REG_PREDICATE\s*)?)+}x;
1467  
1468 my $prev_handler;
1469  
1470 my $cpath= $whole_path;
1471 #warn "\$cpath: '$cpath\n";
1472 while( $cpath && $cpath=~ s{^\s*($H_SPECIAL|$H_PI|$H_LEVEL|$H_REGEXP|$H_XPATH)\s*($|\|)}{})
1473 { my $path= $1;
1474 #warn "\$cpath: '$cpath' - $path: '$path'\n";
1475 $prev_handler ||= $handlers->{handlers}->{string}->{$path} || undef; # $prev_handler gets the first found handler
1476  
1477 _set_special_handler ( $handlers, $path, $handler, $prev_handler)
1478 || _set_pi_handler ( $handlers, $path, $handler, $prev_handler)
1479 || _set_level_handler ( $handlers, $path, $handler, $prev_handler)
1480 || _set_regexp_handler ( $handlers, $path, $handler, $prev_handler)
1481 || _set_xpath_handler ( $handlers, $path, $handler, $prev_handler)
1482 || croak "unrecognized expression in handler: '$whole_path'";
1483  
1484 # this both takes care of the simple (gi) handlers and store
1485 # the handler code reference for other handlers
1486 $handlers->{handlers}->{string}->{$path}= $handler;
1487 }
1488  
1489 if( $cpath) { croak "unrecognized expression in handler: '$whole_path'"; }
1490  
1491 return $prev_handler;
1492 }
1493  
1494 sub _set_special_handler
1495 { my( $handlers, $path, $handler, $prev_handler)= @_;
1496 if( $path =~ m{^\s*($ALL|$DEFAULT|$COMMENT|$TEXT)\s*$}io )
1497 { $handlers->{handlers}->{$1}= $handler;
1498 return 1;
1499 }
1500 else
1501 { return 0; }
1502 }
1503  
1504 sub _set_xpath_handler
1505 { my( $handlers, $path, $handler, $prev_handler)= @_;
1506 if( my $handler_data= _parse_xpath_handler( $path, $handler))
1507 { _add_handler( $handlers, $handler_data, $path, $prev_handler);
1508 return 1;
1509 }
1510 else
1511 { return 0; }
1512 }
1513  
1514 sub _add_handler
1515 { my( $handlers, $handler_data, $path, $prev_handler)= @_;
1516  
1517 my $tag= $handler_data->{tag};
1518 my @handlers= $handlers->{xpath_handler}->{$tag} ? @{$handlers->{xpath_handler}->{$tag}} : ();
1519  
1520 if( $prev_handler) { @handlers= grep { $_->{path} ne $path } @handlers; }
1521  
1522 push @handlers, $handler_data if( $handler_data->{handler});
1523  
1524 if( @handlers > 1)
1525 { @handlers= sort { (($b->{score}->{type} || 0) <=> ($a->{score}->{type} || 0))
1526 || (($b->{score}->{anchored} || 0) <=> ($a->{score}->{anchored} || 0))
1527 || (($b->{score}->{steps} || 0) <=> ($a->{score}->{steps} || 0))
1528 || (($b->{score}->{predicates} || 0) <=> ($a->{score}->{predicates} || 0))
1529 || (($b->{score}->{tests} || 0) <=> ($a->{score}->{tests} || 0))
1530 || ($a->{path} cmp $b->{path})
1531 } @handlers;
1532 }
1533  
1534 $handlers->{xpath_handler}->{$tag}= \@handlers;
1535 }
1536  
1537 sub _set_pi_handler
1538 { my( $handlers, $path, $handler, $prev_handler)= @_;
1539 # PI conditions ( '?target' => \&handler or '?' => \&handler
1540 # or '#PItarget' => \&handler or '#PI' => \&handler)
1541 if( $path=~ /^\s*(?:\?|$PI)\s*(?:([^\s]*)\s*)$/)
1542 { my $target= $1 || '';
1543 # update the path_handlers count, knowing that
1544 # either the previous or the new handler can be undef
1545 $handlers->{pi_handlers}->{$1}= $handler;
1546 return 1;
1547 }
1548 else
1549 { return 0;
1550 }
1551 }
1552  
1553 sub _set_level_handler
1554 { my( $handlers, $path, $handler, $prev_handler)= @_;
1555 if( $path =~ m{^ \s* level \s* \( \s* ([0-9]+) \s* \) \s* $}ox )
1556 { my $level= $1;
1557 my $sub= sub { my( $stack)= @_; return( ($stack->[-1]->{$ST_TAG} !~ m{^#}) && (scalar @$stack == $level + 1) ) };
1558 my $handler_data= { tag=> '*', score => { type => $LEVEL_TRIGGER}, trigger => $sub,
1559 path => $path, handler => $handler, test_on_text => 0
1560 };
1561 _add_handler( $handlers, $handler_data, $path, $prev_handler);
1562 return 1;
1563 }
1564 else
1565 { return 0; }
1566 }
1567  
1568 sub _set_regexp_handler
1569 { my( $handlers, $path, $handler, $prev_handler)= @_;
1570 # if the expression was a regexp it is now a string (it was stringified when it became a hash key)
1571 if( $path=~ m{^\(\?([\^xism]*)(?:-[\^xism]*)?:(.*)\)$})
1572 { my $regexp= qr/(?$1:$2)/; # convert it back into a regexp
1573 my $sub= sub { my( $stack)= @_; return( $stack->[-1]->{$ST_TAG} =~ $regexp ) };
1574 my $handler_data= { tag=> '*', score => { type => $REGEXP_TRIGGER} , trigger => $sub,
1575 path => $path, handler => $handler, test_on_text => 0
1576 };
1577 _add_handler( $handlers, $handler_data, $path, $prev_handler);
1578 return 1;
1579 }
1580 else
1581 { return 0; }
1582 }
1583  
1584 my $DEBUG_HANDLER= 0; # 0 or 1 (output the handler checking code) or 2 (super verbose)
1585 my $handler_string; # store the handler itself
1586 sub _set_debug_handler { $DEBUG_HANDLER= shift; }
1587 sub _warn_debug_handler { if( $DEBUG_HANDLER < 3) { warn @_; } else { $handler_string .= join( '', @_); } }
1588 sub _return_debug_handler { my $string= $handler_string; $handler_string=''; return $string; }
1589  
1590 sub _parse_xpath_handler
1591 { my( $xpath, $handler)= @_;
1592 my $xpath_original= $xpath;
1593  
1594 if( $DEBUG_HANDLER >=1) { _warn_debug_handler( "\n\nparsing path '$xpath'\n"); }
1595  
1596 my $path_to_check= $xpath;
1597 $path_to_check=~ s{/?/?$REG_TAG_PART?\s*(?:$REG_PREDICATE\s*)?}{}g;
1598 if( $DEBUG_HANDLER && $path_to_check=~ /\S/) { _warn_debug_handler( "left: $path_to_check\n"); }
1599 return if( $path_to_check=~ /\S/);
1600  
1601 (my $xpath_to_display= $xpath)=~ s{(["{}'\[\]\@\$])}{\\$1}g;
1602  
1603 my @xpath_steps;
1604 my $last_token_is_sep;
1605  
1606 while( $xpath=~ s{^\s*
1607 ( (//?) # separator
1608 | (?:$REG_TAG_PART\s*(?:$REG_PREDICATE\s*)?) # tag name and optional predicate
1609 | (?:$REG_PREDICATE) # just a predicate
1610 )
1611 }
1612 {}x
1613 )
1614 { # check that we have alternating separators and steps
1615 if( $2) # found a separator
1616 { if( $last_token_is_sep) { return 0; } # 2 separators in a row
1617 $last_token_is_sep= 1;
1618 }
1619 else
1620 { if( defined( $last_token_is_sep) && !$last_token_is_sep) { return 0; } # 2 steps in a row
1621 $last_token_is_sep= 0;
1622 }
1623  
1624 push @xpath_steps, $1;
1625 }
1626 if( $last_token_is_sep) { return 0; } # expression cannot end with a separator
1627  
1628 my $i=-1;
1629  
1630 my $perlfunc= _join_n( $NO_WARNINGS . ';',
1631 q|my( $stack)= @_; |,
1632 q|my @current_elts= (scalar @$stack); |,
1633 q|my @new_current_elts; |,
1634 q|my $elt; |,
1635 ($DEBUG_HANDLER >= 1) && (qq#warn q{checking path '$xpath_to_display'\n};#),
1636 );
1637  
1638 my $last_tag='';
1639 my $anchored= $xpath_original=~ m{^\s*/(?!/)} ? 1 : 0;
1640 my $score={ type => $XPATH_TRIGGER, anchored => $anchored };
1641 my $flag= { test_on_text => 0 };
1642 my $sep='/'; # '/' or '//'
1643 while( my $xpath_step= pop @xpath_steps)
1644 { my( $tag, $predicate)= $xpath_step =~ m{^($REG_TAG_PART)?(?:\[(.*)\])?\s*$};
1645 $score->{steps}++;
1646 $tag||='*';
1647  
1648 my $warn_empty_stack= $DEBUG_HANDLER >= 2 ? qq{warn "return with empty stack\\n";} : '';
1649  
1650 if( $predicate)
1651 { if( $DEBUG_HANDLER >= 2) { _warn_debug_handler( "predicate is: '$predicate'\n"); }
1652 # changes $predicate (from an XPath expression to a Perl one)
1653 if( $predicate=~ m{^\s*$REG_NUMBER\s*$}) { croak "position selector [$predicate] not supported on twig_handlers"; }
1654 _parse_predicate_in_handler( $predicate, $flag, $score);
1655 if( $DEBUG_HANDLER >= 2) { _warn_debug_handler( "predicate becomes: '$predicate'\n"); }
1656 }
1657  
1658 my $tag_cond= _tag_cond( $tag);
1659 my $cond= join( " && ", grep { $_ } $tag_cond, $predicate) || 1;
1660  
1661 if( $css_sel && $tag=~ m{\.}) { $tag=~s{\..*$}{}; $tag ||='*'; }
1662 $tag=~ s{(.)#.+$}{$1};
1663  
1664 $last_tag ||= $tag;
1665  
1666 if( $sep eq '/')
1667 {
1668 $perlfunc .= sprintf( _join_n( q#foreach my $current_elt (@current_elts) #,
1669 q# { next if( !$current_elt); #,
1670 q# $current_elt--; #,
1671 q# $elt= $stack->[$current_elt]; #,
1672 q# if( %s) { push @new_current_elts, $current_elt;} #,
1673 q# } #,
1674 ),
1675 $cond
1676 );
1677 }
1678 elsif( $sep eq '//')
1679 {
1680 $perlfunc .= sprintf( _join_n( q#foreach my $current_elt (@current_elts) #,
1681 q# { next if( !$current_elt); #,
1682 q# $current_elt--; #,
1683 q# my $candidate= $current_elt; #,
1684 q# while( $candidate >=0) #,
1685 q# { $elt= $stack->[$candidate]; #,
1686 q# if( %s) { push @new_current_elts, $candidate;} #,
1687 q# $candidate--; #,
1688 q# } #,
1689 q# } #,
1690 ),
1691 $cond
1692 );
1693 }
1694 my $warn= $DEBUG_HANDLER >= 2 ? _join_n( qq#warn qq%fail at cond '$cond'%;#) : '';
1695 $perlfunc .= sprintf( _join_n( q#unless( @new_current_elts) { %s return 0; } #,
1696 q#@current_elts= @new_current_elts; #,
1697 q#@new_current_elts=(); #,
1698 ),
1699 $warn
1700 );
1701  
1702 $sep= pop @xpath_steps;
1703 }
1704  
1705 if( $anchored) # there should be a better way, but this works
1706 {
1707 my $warn= $DEBUG_HANDLER >= 2 ? _join_n( qq#warn qq{fail, stack not empty};#) : '';
1708 $perlfunc .= sprintf( _join_n( q#if( ! grep { $_ == 0 } @current_elts) { %s return 0;}#), $warn);
1709 }
1710  
1711 $perlfunc.= qq{warn "handler for '$xpath_to_display' triggered\\n";\n} if( $DEBUG_HANDLER >=2);
1712 $perlfunc.= qq{return q{$xpath_original};\n};
1713 _warn_debug_handler( "\nperlfunc:\n$perlfunc\n") if( $DEBUG_HANDLER>=1);
1714 my $s= eval "sub { $perlfunc }"; ## no critic (ProhibitStringyEval)
1715 if( $@)
1716 { croak "wrong handler condition '$xpath' ($@);" }
1717  
1718 _warn_debug_handler( "last tag: '$last_tag', test_on_text: '$flag->{test_on_text}'\n") if( $DEBUG_HANDLER >=1);
1719 _warn_debug_handler( "score: ", join( ' ', map { "$_: $score->{$_}" } sort keys %$score), "\n") if( $DEBUG_HANDLER >=1);
1720 return { tag=> $last_tag, score => $score, trigger => $s, path => $xpath_original, handler => $handler, test_on_text => $flag->{test_on_text} };
1721 }
1722  
1723 sub _join_n { return join( "\n", @_, ''); }
1724  
1725 # the "tag" part can be <tag>, <tag>.<class> or <tag>#<id> (where tag can be *, or start with # for hidden tags)
1726 sub _tag_cond
1727 { my( $full_tag)= @_;
1728  
1729 my( $tag, $class, $id);
1730 if( $full_tag=~ m{^(.+)#(.+)$})
1731 { ($tag, $id)= ($1, $2); } # <tag>#<id>
1732 else
1733 { ( $tag, $class)= $css_sel ? $full_tag=~ m{^(.*?)(?:\.(.*))?$} : ($full_tag, undef); }
1734  
1735 my $tag_cond = $tag && $tag ne '*' ? qq#(\$elt->{'$ST_TAG'} eq "$tag")# : '';
1736 my $id_cond = defined $id ? qq#(\$elt->{id} eq "$id")# : '';
1737  
1738 my $class_cond;
1739 if( defined $class ) {
1740 my @classes = split /\./, $class;
1741 $class_cond = '(' . join( ' && ', map { qq#(\$elt->{class}=~ m{(^| )$_( |\$)})# } @classes) . ')';
1742 }
1743  
1744 my $full_cond= join( ' && ', grep { $_ } ( $tag_cond, $class_cond, $id_cond));
1745  
1746 # warn "full_cond: [$full_cond]\n";
1747  
1748 return $full_cond;
1749 }
1750  
1751 # input: the predicate ($_[0]) which will be changed in place
1752 # flags, a hashref with various flags (like test_on_text)
1753 # the score
1754 sub _parse_predicate_in_handler
1755 { my( $flag, $score)= @_[1..2];
1756 $_[0]=~ s{( ($REG_STRING) # quoted string
1757 |($REG_REGEXP) # regexp
1758 |\@($REG_TAG_NAME)(\s* $REG_MATCH \s* $REG_REGEXP) # @att and regexp
1759 |\@($REG_TAG_NAME)(?=\s*(?:[><=!])) # @att followed by a comparison operator
1760 |\@($REG_TAG_NAME) # @att (not followed by a comparison operator)
1761 |=~|!~ # matching operators
1762 |([><]=?|=|!=)(?=\s*[\d+-]) # test before a number
1763 |([><]=?|=|!=) # test, other cases
1764 |($REG_FUNCTION) # no arg functions
1765 # this bit is a mess, but it is the only solution with this half-baked parser
1766 |(string\(\s*$REG_NAME?\s*\)\s*$REG_MATCH\s*$REG_REGEXP) # string( child)=~ /regexp/ or string()=~ /regexp/
1767 |(string\(\s*$REG_NAME\s*\)\s*$REG_COMP\s*$REG_STRING) # string( child) = "value" (or other test)
1768 |(string\(\s*$REG_NAME\s*\)\s*$REG_COMP\s*$REG_NUMBER) # string( child) = nb (or other test)
1769 |(\band\b|\bor\b)
1770 # |($REG_NAME(?=\s*(and|or|$))) # nested tag name (needs to be after all other unquoted strings)
1771 |($REG_TAG_IN_PREDICATE) # nested tag name (needs to be after all other unquoted strings)
1772  
1773 )}
1774 { my( $token, $str, $regexp, $att_re_name, $att_re_regexp, $att, $bare_att, $num_test, $alpha_test, $func, $str_regexp, $str_test_alpha, $str_test_num, $and_or, $tag)
1775 = ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15);
1776  
1777 $score->{predicates}++;
1778  
1779 # store tests on text (they are not always allowed)
1780 if( $func || $str_regexp || $str_test_num || $str_test_alpha ) { $flag->{test_on_text}= 1; }
1781  
1782 if( defined $str) { _safe_string( $token) }
1783 elsif( defined $regexp){ _safe_regexp( $token) }
1784 elsif( $tag) { qq{(\$elt->{'$ST_ELT'} && \$elt->{'$ST_ELT'}->has_child( '$tag'))} }
1785 elsif( $att) { $att=~ m{^#} ? qq{ (\$elt->{'$ST_ELT'} && \$elt->{'$ST_ELT'}->{att}->{'$att'})}
1786 : qq{\$elt->{'$att'}}
1787 }
1788 elsif( $att_re_name) { $att_re_name=~ m{^#} ? qq{ (\$elt->{'$ST_ELT'} && \$elt->{'$ST_ELT'}->{att}->{'$att_re_name'}$att_re_regexp)}
1789 : qq{\$elt->{'$att_re_name'}$att_re_regexp}
1790 }
1791 # for some reason Devel::Cover flags the following lines as not tested. They are though.
1792 elsif( $bare_att) { $bare_att=~ m{^#} ? qq{(\$elt->{'$ST_ELT'} && defined(\$elt->{'$ST_ELT'}->{att}->{'$bare_att'}))}
1793 : qq{defined( \$elt->{'$bare_att'})}
1794 }
1795 elsif( $num_test && ($num_test eq '=') ) { "==" } # others tests are unchanged
1796 elsif( $alpha_test) { $PERL_ALPHA_TEST{$alpha_test} }
1797 elsif( $func && $func=~ m{^string})
1798 { "\$elt->{'$ST_ELT'}->text"; }
1799 elsif( $str_regexp && $str_regexp =~ m{string\(\s*($REG_TAG_NAME)?\s*\)\s*($REG_MATCH)\s*($REG_REGEXP)})
1800 { my( $rtag, $rmatch, $rregexp)= ($1, $2, _safe_regexp( $3));
1801 if( $1) { "defined( _first_n { \$_->text $rmatch $rregexp } 1, \$elt->{'$ST_ELT'}->_children( '$rtag'))" }
1802 else { "\$elt->text $rmatch $rregexp" }
1803 }
1804 elsif( $str_test_alpha && $str_test_alpha =~ m{string\(\s*($REG_TAG_NAME)\s*\)\s*($REG_COMP)\s*($REG_STRING)})
1805 { my( $tag, $op, $str)= ($1, $2, _safe_string($3));
1806 $str=~ s{(?<=.)'(?=.)}{\\'}g; # escape a quote within the string
1807 $str=~ s{^"}{'};
1808 $str=~ s{"$}{'};
1809 "defined( _first_n { \$_->text $PERL_ALPHA_TEST{$op} $str } 1, \$elt->{'$ST_ELT'}->children( '$tag'))"; }
1810 elsif( $str_test_num && $str_test_num =~ m{string\(\s*($REG_TAG_NAME)\s*\)\s*($REG_COMP)\s*($REG_NUMBER)})
1811 { my $test= ($2 eq '=') ? '==' : $2;
1812 "defined( _first_n { \$_->text $test $3 } 1, \$elt->{'$ST_ELT'}->children( '$1'))";
1813 }
1814 elsif( $and_or) { $score->{tests}++; $and_or eq 'and' ? '&&' : '||' ; }
1815 else { $token; }
1816 }gexs;
1817 }
1818  
1819 sub _safe_string
1820 { my( $string)= @_;
1821 $string=~ s{([\@\$]\s*\{\s*\[)}{\\$1}g;
1822 return $string;
1823 }
1824  
1825 sub _safe_regexp
1826 { my( $regexp)= @_;
1827 if( $regexp=~ m{\(\s*\?\s*\{}) { s{(\([()])}{\\$1}g; } # if '(?{' (code in a regexp) then escape all '(' and ')'
1828 return $regexp;
1829 }
1830  
1831 sub setCharHandler
1832 { my( $t, $handler)= @_;
1833 $t->{twig_char_handler}= $handler;
1834 }
1835  
1836 sub _reset_handlers
1837 { my $handlers= shift;
1838 delete $handlers->{handlers};
1839 delete $handlers->{path_handlers};
1840 delete $handlers->{subpath_handlers};
1841 $handlers->{attcond_handlers_exp}=[] if( $handlers->{attcond_handlers});
1842 delete $handlers->{attcond_handlers};
1843 }
1844  
1845 sub _set_handlers
1846 { my $handlers= shift || return;
1847 my $set_handlers= {};
1848 foreach my $path (keys %{$handlers})
1849 { _set_handler( $set_handlers, $path, $handlers->{$path}); }
1850  
1851 return $set_handlers;
1852 }
1853  
1854 sub setTwigHandler
1855 { my( $t, $path, $handler)= @_;
1856 $t->{twig_handlers} ||={};
1857 return _set_handler( $t->{twig_handlers}, $path, $handler);
1858 }
1859  
1860 sub setTwigHandlers
1861 { my( $t, $handlers)= @_;
1862 my $previous_handlers= $t->{twig_handlers} || undef;
1863 _reset_handlers( $t->{twig_handlers});
1864 $t->{twig_handlers}= _set_handlers( $handlers);
1865 return $previous_handlers;
1866 }
1867  
1868 sub setStartTagHandler
1869 { my( $t, $path, $handler)= @_;
1870 $t->{twig_starttag_handlers}||={};
1871 return _set_handler( $t->{twig_starttag_handlers}, $path, $handler);
1872 }
1873  
1874 sub setStartTagHandlers
1875 { my( $t, $handlers)= @_;
1876 my $previous_handlers= $t->{twig_starttag_handlers} || undef;
1877 _reset_handlers( $t->{twig_starttag_handlers});
1878 $t->{twig_starttag_handlers}= _set_handlers( $handlers);
1879 return $previous_handlers;
1880 }
1881  
1882 sub setIgnoreEltsHandler
1883 { my( $t, $path, $action)= @_;
1884 $t->{twig_ignore_elts_handlers}||={};
1885 return _set_handler( $t->{twig_ignore_elts_handlers}, $path, $action );
1886 }
1887  
1888 sub setIgnoreEltsHandlers
1889 { my( $t, $handlers)= @_;
1890 my $previous_handlers= $t->{twig_ignore_elts_handlers};
1891 _reset_handlers( $t->{twig_ignore_elts_handlers});
1892 $t->{twig_ignore_elts_handlers}= _set_handlers( $handlers);
1893 return $previous_handlers;
1894 }
1895  
1896 sub setEndTagHandler
1897 { my( $t, $path, $handler)= @_;
1898 $t->{twig_endtag_handlers}||={};
1899 return _set_handler( $t->{twig_endtag_handlers}, $path,$handler);
1900 }
1901  
1902 sub setEndTagHandlers
1903 { my( $t, $handlers)= @_;
1904 my $previous_handlers= $t->{twig_endtag_handlers};
1905 _reset_handlers( $t->{twig_endtag_handlers});
1906 $t->{twig_endtag_handlers}= _set_handlers( $handlers);
1907 return $previous_handlers;
1908 }
1909  
1910 # a little more complex: set the twig_handlers only if a code ref is given
1911 sub setTwigRoots
1912 { my( $t, $handlers)= @_;
1913 my $previous_roots= $t->{twig_roots};
1914 _reset_handlers($t->{twig_roots});
1915 $t->{twig_roots}= _set_handlers( $handlers);
1916  
1917 _check_illegal_twig_roots_handlers( $t->{twig_roots});
1918  
1919 foreach my $path (keys %{$handlers})
1920 { $t->{twig_handlers}||= {};
1921 _set_handler( $t->{twig_handlers}, $path, $handlers->{$path})
1922 if( ref($handlers->{$path}) && isa( $handlers->{$path}, 'CODE'));
1923 }
1924 return $previous_roots;
1925 }
1926  
1927 sub _check_illegal_twig_roots_handlers
1928 { my( $handlers)= @_;
1929 foreach my $tag_handlers (values %{$handlers->{xpath_handler}})
1930 { foreach my $handler_data (@$tag_handlers)
1931 { if( my $type= $handler_data->{test_on_text})
1932 { croak "string() condition not supported on twig_roots option"; }
1933 }
1934 }
1935 return;
1936 }
1937  
1938 # just store the reference to the expat object in the twig
1939 sub _twig_init
1940 { # warn " in _twig_init...\n"; # DEBUG handler
1941  
1942 my $p= shift;
1943 my $t=$p->{twig};
1944  
1945 if( $t->{twig_parsing} ) { croak "cannot reuse a twig that is already parsing"; }
1946 $t->{twig_parsing}=1;
1947  
1948 $t->{twig_parser}= $p;
1949 if( $weakrefs) { weaken( $t->{twig_parser}); }
1950  
1951 # in case they had been created by a previous parse
1952 delete $t->{twig_dtd};
1953 delete $t->{twig_doctype};
1954 delete $t->{twig_xmldecl};
1955 delete $t->{twig_root};
1956  
1957 # if needed set the output filehandle
1958 $t->_set_fh_to_twig_output_fh();
1959 return;
1960 }
1961  
1962 # uses eval to catch the parser's death
1963 sub safe_parse
1964 { my $t= shift;
1965 eval { $t->parse( @_); } ;
1966 return $@ ? $t->_reset_twig_after_error : $t;
1967 }
1968  
1969 sub safe_parsefile
1970 { my $t= shift;
1971 eval { $t->parsefile( @_); } ;
1972 return $@ ? $t->_reset_twig_after_error : $t;
1973 }
1974  
1975 # restore a twig in a proper state so it can be reused for a new parse
1976 sub _reset_twig
1977 { my $t= shift;
1978 $t->{twig_parsing}= 0;
1979 delete $t->{twig_current};
1980 delete $t->{extra_data};
1981 delete $t->{twig_dtd};
1982 delete $t->{twig_in_pcdata};
1983 delete $t->{twig_in_cdata};
1984 delete $t->{twig_stored_space};
1985 delete $t->{twig_entity_list};
1986 $t->root->delete if( $t->root);
1987 delete $t->{twig_root};
1988 return $t;
1989 }
1990  
1991 sub _reset_twig_after_error
1992 { my $t= shift;
1993 $t->_reset_twig;
1994 return undef;
1995 }
1996  
1997 sub _add_or_discard_stored_spaces
1998 { my $t= shift;
1999 $t->{twig_right_after_root}=0; #XX
2000  
2001 my $current= $t->{twig_current} or return; # ugly hack, with ignore on, twig_current can disappear
2002 return unless length $t->{twig_stored_spaces};
2003 my $current_gi= $XML::Twig::index2gi[$current->{'gi'}];
2004  
2005 if( ! $t->{twig_discard_all_spaces})
2006 { if( ! defined( $t->{twig_space_policy}->{$current_gi}))
2007 { $t->{twig_space_policy}->{$current_gi}= _space_policy( $t, $current_gi); }
2008 if( $t->{twig_space_policy}->{$current_gi} || ($t->{twig_stored_spaces}!~ m{\n}) || $t->{twig_preserve_space})
2009 { _insert_pcdata( $t, $t->{twig_stored_spaces} ); }
2010 }
2011  
2012 $t->{twig_stored_spaces}='';
2013  
2014 return;
2015 }
2016  
2017 # the default twig handlers, which build the tree
2018 sub _twig_start
2019 { # warn " in _twig_start...\n"; # DEBUG handler
2020  
2021 #foreach my $s (@_) { next if ref $s; warn "$s: ", is_utf8( $s) ? "has flag" : "FLAG NOT SET"; } # YYY
2022  
2023 my ($p, $gi, @att)= @_;
2024 my $t=$p->{twig};
2025  
2026 # empty the stored pcdata (space stored in case they are really part of
2027 # a pcdata element) or stored it if the space policy dictates so
2028 # create a pcdata element with the spaces if need be
2029 _add_or_discard_stored_spaces( $t);
2030 my $parent= $t->{twig_current};
2031  
2032 # if we were parsing PCDATA then we exit the pcdata
2033 if( $t->{twig_in_pcdata})
2034 { $t->{twig_in_pcdata}= 0;
2035 $t->_trigger_text_handler();
2036  
2037 delete $parent->{'twig_current'};
2038 $parent= $parent->{parent};
2039 }
2040  
2041 # if we choose to keep the encoding then we need to parse the tag
2042 if( my $func = $t->{parse_start_tag})
2043 { ($gi, @att)= &$func($p->original_string); }
2044 elsif( $t->{twig_entities_in_attribute})
2045 {
2046 ($gi,@att)= _parse_start_tag( $p->recognized_string);
2047 $t->{twig_entities_in_attribute}=0;
2048 }
2049  
2050 # if we are using an external DTD, we need to fill the default attributes
2051 if( $t->{twig_read_external_dtd}) { _fill_default_atts( $t, $gi, \@att); }
2052  
2053 # filter the input data if need be
2054 if( my $filter= $t->{twig_input_filter})
2055 { $gi= $filter->( $gi);
2056 foreach my $att (@att) { $att= $filter->($att); }
2057 }
2058  
2059 my $ns_decl;
2060 if( $t->{twig_map_xmlns})
2061 { $ns_decl= _replace_ns( $t, \$gi, \@att); }
2062  
2063 my $elt= $t->{twig_elt_class}->new( $gi);
2064 $elt->set_atts( @att);
2065  
2066 # now we can store the tag and atts
2067 my $context= { $ST_TAG => $gi, $ST_ELT => $elt, @att};
2068 $context->{$ST_NS}= $ns_decl if $ns_decl;
2069 if( $weakrefs) { weaken( $context->{$ST_ELT}); }
2070 push @{$t->{_twig_context_stack}}, $context;
2071  
2072 delete $parent->{'twig_current'} if( $parent);
2073 $t->{twig_current}= $elt;
2074 $elt->{'twig_current'}=1;
2075  
2076 if( $parent)
2077 { my $prev_sibling= $parent->{last_child};
2078 if( $prev_sibling)
2079 { $prev_sibling->{next_sibling}= $elt;
2080 $elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
2081 }
2082  
2083 $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
2084 unless( $parent->{first_child}) { $parent->{first_child}= $elt; }
2085 delete $parent->{empty}; $parent->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ;
2086 }
2087 else
2088 { # processing root
2089 $t->set_root( $elt);
2090 # call dtd handler if need be
2091 $t->{twig_dtd_handler}->($t, $t->{twig_dtd})
2092 if( defined $t->{twig_dtd_handler});
2093  
2094 # set this so we can catch external entities
2095 # (the handler was modified during DTD processing)
2096 if( $t->{twig_default_print})
2097 { $p->setHandlers( Default => \&_twig_print); }
2098 elsif( $t->{twig_roots})
2099 { $p->setHandlers( Default => sub { return }); }
2100 else
2101 { $p->setHandlers( Default => \&_twig_default); }
2102 }
2103  
2104 $elt->{empty}= $p->recognized_string=~ m{/\s*>$}s ? 1 : 0;
2105  
2106 $elt->{extra_data}= $t->{extra_data} if( $t->{extra_data});
2107 $t->{extra_data}='';
2108  
2109 # if the element is ID-ed then store that info
2110 my $id= $elt->{'att'}->{$ID};
2111 if( defined $id)
2112 { $t->{twig_id_list}->{$id}= $elt;
2113 if( $weakrefs) { weaken( $t->{twig_id_list}->{$id}); }
2114 }
2115  
2116 # call user handler if need be
2117 if( $t->{twig_starttag_handlers})
2118 { # call all appropriate handlers
2119 my @handlers= _handler( $t, $t->{twig_starttag_handlers}, $gi);
2120  
2121 local $_= $elt;
2122  
2123 foreach my $handler ( @handlers)
2124 { $handler->($t, $elt) || last; }
2125 # call _all_ handler if needed
2126 if( my $all= $t->{twig_starttag_handlers}->{handlers}->{$ALL})
2127 { $all->($t, $elt); }
2128 }
2129  
2130 # check if the tag is in the list of tags to be ignored
2131 if( $t->{twig_ignore_elts_handlers})
2132 { my @handlers= _handler( $t, $t->{twig_ignore_elts_handlers}, $gi);
2133 # only the first handler counts, it contains the action (discard/print/string)
2134 if( @handlers) { my $action= shift @handlers; $t->ignore( $elt, $action); }
2135 }
2136  
2137 if( $elt->{'att'}->{'xml:space'} && ( $elt->{'att'}->{'xml:space'} eq 'preserve')) { $t->{twig_preserve_space}++; }
2138  
2139 return;
2140 }
2141  
2142 sub _replace_ns
2143 { my( $t, $gi, $atts)= @_;
2144 my $decls;
2145 foreach my $new_prefix ( $t->parser->new_ns_prefixes)
2146 { my $uri= $t->parser->expand_ns_prefix( $new_prefix);
2147 # replace the prefix if it is mapped
2148 $decls->{$new_prefix}= $uri;
2149 if( !$t->{twig_keep_original_prefix} && (my $mapped_prefix= $t->{twig_map_xmlns}->{$uri}))
2150 { $new_prefix= $mapped_prefix; }
2151 # now put the namespace declaration back in the element
2152 if( $new_prefix eq '#default')
2153 { push @$atts, "xmlns" => $uri; }
2154 else
2155 { push @$atts, "xmlns:$new_prefix" => $uri; }
2156 }
2157  
2158 if( $t->{twig_keep_original_prefix})
2159 { # things become more complex: we need to find the original prefix
2160 # and store both prefixes
2161 my $ns_info= $t->_ns_info( $$gi);
2162 my $map_att;
2163 if( $ns_info->{mapped_prefix})
2164 { $$gi= "$ns_info->{mapped_prefix}:$$gi";
2165 $map_att->{$ns_info->{mapped_prefix}}= $ns_info->{prefix};
2166 }
2167 my $att_name=1;
2168 foreach( @$atts)
2169 { if( $att_name)
2170 {
2171 my $ns_info= $t->_ns_info( $_);
2172 if( $ns_info->{mapped_prefix})
2173 { $_= "$ns_info->{mapped_prefix}:$_";
2174 $map_att->{$ns_info->{mapped_prefix}}= $ns_info->{prefix};
2175 }
2176 $att_name=0;
2177 }
2178 else
2179 { $att_name=1; }
2180 }
2181 push @$atts, '#original_gi', $map_att if( $map_att);
2182 }
2183 else
2184 { $$gi= $t->_replace_prefix( $$gi);
2185 my $att_name=1;
2186 foreach( @$atts)
2187 { if( $att_name) { $_= $t->_replace_prefix( $_); $att_name=0; }
2188 else { $att_name=1; }
2189 }
2190 }
2191 return $decls;
2192 }
2193  
2194 # extract prefix, local_name, uri, mapped_prefix from a name
2195 # will only work if called from a start or end tag handler
2196 sub _ns_info
2197 { my( $t, $name)= @_;
2198 my $ns_info={};
2199 my $p= $t->parser;
2200 $ns_info->{uri}= $p->namespace( $name);
2201 return $ns_info unless( $ns_info->{uri});
2202  
2203 $ns_info->{prefix}= _a_proper_ns_prefix( $p, $ns_info->{uri});
2204 $ns_info->{mapped_prefix}= $t->{twig_map_xmlns}->{$ns_info->{uri}} || $ns_info->{prefix};
2205  
2206 return $ns_info;
2207 }
2208  
2209 sub _a_proper_ns_prefix
2210 { my( $p, $uri)= @_;
2211 foreach my $prefix ($p->current_ns_prefixes)
2212 { if( $p->expand_ns_prefix( $prefix) eq $uri)
2213 { return $prefix; }
2214 }
2215 return;
2216 }
2217  
2218 # returns the uri bound to a prefix in the original document
2219 # only works in a handler
2220 # can be used to deal with xsi:type attributes
2221 sub original_uri
2222 { my( $t, $prefix)= @_;
2223 my $ST_NS = '##ns' ;
2224 foreach my $ns (map { $_->{$ST_NS} if $_->{$ST_NS} } reverse @{$t->{_twig_context_stack}})
2225 { return $ns->{$prefix} || next; }
2226 return;
2227 }
2228  
2229 sub _fill_default_atts
2230 { my( $t, $gi, $atts)= @_;
2231 my $dtd= $t->{twig_dtd};
2232 my $attlist= $dtd->{att}->{$gi};
2233 my %value= @$atts;
2234 foreach my $att (keys %$attlist)
2235 { if( !exists( $value{$att})
2236 && exists( $attlist->{$att}->{default})
2237 && ( $attlist->{$att}->{default} ne '#IMPLIED')
2238 )
2239 { # the quotes are included in the default, so we need to remove them
2240 my $default_value= substr( $attlist->{$att}->{default}, 1, -1);
2241 push @$atts, $att, $default_value;
2242 }
2243 }
2244 return;
2245 }
2246  
2247 # the default function to parse a start tag (in keep_encoding mode)
2248 # can be overridden with the parse_start_tag method
2249 # only works for 1-byte character sets
2250 sub _parse_start_tag
2251 { my $string= shift;
2252 my( $gi, @atts);
2253  
2254 # get the gi (between < and the first space, / or > character)
2255 if( $string=~ s{^<\s*($REG_TAG_NAME)\s*[\s>/]}{}s)
2256 { $gi= $1; }
2257 else
2258 { croak "error parsing tag '$string'"; }
2259 while( $string=~ s{^([^\s=]*)\s*=\s*(["'])(.*?)\2\s*}{}s)
2260 { push @atts, $1, $3; }
2261 return $gi, @atts;
2262 }
2263  
2264 sub set_root
2265 { my( $t, $elt)= @_;
2266 $t->{twig_root}= $elt;
2267 if( $elt)
2268 { $elt->{twig}= $t;
2269 if( $weakrefs) { weaken( $elt->{twig}); }
2270 }
2271 return $t;
2272 }
2273  
2274 sub _twig_end
2275 { # warn " in _twig_end...\n"; # DEBUG handler
2276 my ($p, $gi) = @_;
2277  
2278 my $t=$p->{twig};
2279  
2280 if( $t->{twig_in_pcdata} )
2281 { $t->_trigger_text_handler(); }
2282  
2283 if( $t->{twig_map_xmlns}) { $gi= $t->_replace_prefix( $gi); }
2284  
2285 _add_or_discard_stored_spaces( $t);
2286  
2287 # the new twig_current is the parent
2288 my $elt= $t->{twig_current};
2289 delete $elt->{'twig_current'};
2290  
2291 # if we were parsing PCDATA then we exit the pcdata too
2292 if( $t->{twig_in_pcdata})
2293 {
2294 $t->{twig_in_pcdata}= 0;
2295 $elt= $elt->{parent} if($elt->{parent});
2296 delete $elt->{'twig_current'};
2297 }
2298  
2299 # parent is the new current element
2300 my $parent= $elt->{parent};
2301 $t->{twig_current}= $parent;
2302  
2303 if( $parent)
2304 { $parent->{'twig_current'}=1;
2305 # twig_to_be_normalized
2306 if( $parent->{twig_to_be_normalized}) { $parent->normalize; $parent->{twig_to_be_normalized}=0; }
2307 }
2308  
2309 if( $t->{extra_data})
2310 { $elt->_set_extra_data_before_end_tag( $t->{extra_data});
2311 $t->{extra_data}='';
2312 }
2313  
2314 if( $t->{twig_handlers})
2315 { # look for handlers
2316 my @handlers= _handler( $t, $t->{twig_handlers}, $gi);
2317  
2318 if( $t->{twig_tdh})
2319 { if( @handlers) { push @{$t->{twig_handlers_to_trigger}}, [ $elt, \@handlers ]; }
2320 if( my $all= $t->{twig_handlers}->{handlers}->{$ALL})
2321 { push @{$t->{twig_handlers_to_trigger}}, [ $elt, [$all] ]; }
2322 }
2323 else
2324 {
2325 local $_= $elt; # so we can use $_ in the handlers
2326  
2327 foreach my $handler ( @handlers)
2328 { $handler->($t, $elt) || last; }
2329 # call _all_ handler if needed
2330 my $all= $t->{twig_handlers}->{handlers}->{$ALL};
2331 if( $all)
2332 { $all->($t, $elt); }
2333 if( @handlers || $all) { $t->{twig_right_after_root}=0; }
2334 }
2335 }
2336  
2337 # if twig_roots is set for the element then set appropriate handler
2338 if( $t->{twig_root_depth} and ($p->depth == $t->{twig_root_depth}) )
2339 { if( $t->{twig_default_print})
2340 { # select the proper fh (and store the currently selected one)
2341 $t->_set_fh_to_twig_output_fh();
2342 if( !($p->depth==1)) { $t->{twig_right_after_root}=1; } #XX
2343 if( $t->{twig_keep_encoding})
2344 { $p->setHandlers( %twig_handlers_roots_print_original); }
2345 else
2346 { $p->setHandlers( %twig_handlers_roots_print); }
2347 }
2348 else
2349 { $p->setHandlers( %twig_handlers_roots); }
2350 }
2351  
2352 if( $elt->{'att'}->{'xml:space'} && ( $elt->{'att'}->{'xml:space'} eq 'preserve')) { $t->{twig_preserve_space}--; }
2353  
2354 pop @{$t->{_twig_context_stack}};
2355 return;
2356 }
2357  
2358 sub _trigger_tdh
2359 { my( $t)= @_;
2360  
2361 if( @{$t->{twig_handlers_to_trigger}})
2362 { my @handlers_to_trigger_now= sort { $a->[0]->cmp( $b->[0]) } @{$t->{twig_handlers_to_trigger}};
2363 foreach my $elt_handlers (@handlers_to_trigger_now)
2364 { my( $handled_elt, $handlers_to_trigger)= @$elt_handlers;
2365 foreach my $handler ( @$handlers_to_trigger)
2366 { local $_= $handled_elt; $handler->($t, $handled_elt) || last; }
2367 }
2368 }
2369 return;
2370 }
2371  
2372 # return the list of handler that can be activated for an element
2373 # (either of CODE ref's or 1's for twig_roots)
2374  
2375 sub _handler
2376 { my( $t, $handlers, $gi)= @_;
2377  
2378 my @found_handlers=();
2379 my $found_handler;
2380  
2381 foreach my $handler ( map { @$_ } grep { $_ } $handlers->{xpath_handler}->{$gi}, $handlers->{xpath_handler}->{'*'})
2382 { my $trigger= $handler->{trigger};
2383 if( my $found_path= $trigger->( $t->{_twig_context_stack}))
2384 { my $found_handler= $handler->{handler};
2385 push @found_handlers, $found_handler;
2386 }
2387 }
2388  
2389 # if no handler found call default handler if defined
2390 if( !@found_handlers && defined $handlers->{handlers}->{$DEFAULT})
2391 { push @found_handlers, $handlers->{handlers}->{$DEFAULT}; }
2392  
2393 if( @found_handlers and $t->{twig_do_not_chain_handlers})
2394 { @found_handlers= ($found_handlers[0]); }
2395  
2396 return @found_handlers; # empty if no handler found
2397  
2398 }
2399  
2400 sub _replace_prefix
2401 { my( $t, $name)= @_;
2402 my $p= $t->parser;
2403 my $uri= $p->namespace( $name);
2404 # try to get the namespace from default if none is found (for attributes)
2405 # this should probably be an option
2406 if( !$uri and( $name!~/^xml/)) { $uri= $p->expand_ns_prefix( '#default'); }
2407 if( $uri)
2408 { if (my $mapped_prefix= $t->{twig_map_xmlns}->{$uri} || $DEFAULT_URI2NS{$uri})
2409 { return "$mapped_prefix:$name"; }
2410 else
2411 { my $prefix= _a_proper_ns_prefix( $p, $uri);
2412 if( $prefix eq '#default') { $prefix=''; }
2413 return $prefix ? "$prefix:$name" : $name;
2414 }
2415 }
2416 else
2417 { return $name; }
2418 }
2419  
2420 sub _twig_char
2421 { # warn " in _twig_char...\n"; # DEBUG handler
2422  
2423 my ($p, $string)= @_;
2424 my $t=$p->{twig};
2425  
2426 if( $t->{twig_keep_encoding})
2427 { if( !$t->{twig_in_cdata})
2428 { $string= $p->original_string(); }
2429 else
2430 {
2431 use bytes;
2432 if( length( $string) < 1024)
2433 { $string= $p->original_string(); }
2434 else
2435 { #warn "dodgy case";
2436 # TODO original_string does not hold the entire string, but $string is wrong
2437 # I believe due to a bug in XML::Parser
2438 # for now, we use the original string, even if it means that it's been converted to utf8
2439 }
2440 }
2441 }
2442  
2443 if( $t->{twig_input_filter}) { $string= $t->{twig_input_filter}->( $string); }
2444 if( $t->{twig_char_handler}) { $string= $t->{twig_char_handler}->( $string); }
2445  
2446 my $elt= $t->{twig_current};
2447  
2448 if( $t->{twig_in_cdata})
2449 { # text is the continuation of a previously created cdata
2450 $elt->{cdata}.= $t->{twig_stored_spaces} . $string;
2451 }
2452 elsif( $t->{twig_in_pcdata})
2453 { # text is the continuation of a previously created pcdata
2454 if( $t->{extra_data})
2455 { $elt->_push_extra_data_in_pcdata( $t->{extra_data}, length( $elt->{pcdata}));
2456 $t->{extra_data}='';
2457 }
2458 $elt->{pcdata}.= $string;
2459 }
2460 else
2461 {
2462 # text is just space, which might be discarded later
2463 if( $string=~/\A\s*\Z/s)
2464 {
2465 if( $t->{extra_data})
2466 { # we got extra data (comment, pi), lets add the spaces to it
2467 $t->{extra_data} .= $string;
2468 }
2469 else
2470 { # no extra data, just store the spaces
2471 $t->{twig_stored_spaces}.= $string;
2472 }
2473 }
2474 else
2475 { my $new_elt= _insert_pcdata( $t, $t->{twig_stored_spaces}.$string);
2476 delete $elt->{'twig_current'};
2477 $new_elt->{'twig_current'}=1;
2478 $t->{twig_current}= $new_elt;
2479 $t->{twig_in_pcdata}=1;
2480 if( $t->{extra_data})
2481 { $new_elt->_push_extra_data_in_pcdata( $t->{extra_data}, 0);
2482 $t->{extra_data}='';
2483 }
2484 }
2485 }
2486 return;
2487 }
2488  
2489 sub _twig_cdatastart
2490 { # warn " in _twig_cdatastart...\n"; # DEBUG handler
2491  
2492 my $p= shift;
2493 my $t=$p->{twig};
2494  
2495 $t->{twig_in_cdata}=1;
2496 my $cdata= $t->{twig_elt_class}->new( $CDATA);
2497 my $twig_current= $t->{twig_current};
2498  
2499 if( $t->{twig_in_pcdata})
2500 { # create the node as a sibling of the PCDATA
2501 $cdata->{prev_sibling}=$twig_current; if( $XML::Twig::weakrefs) { weaken( $cdata->{prev_sibling});} ;
2502 $twig_current->{next_sibling}= $cdata;
2503 my $parent= $twig_current->{parent};
2504 $cdata->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $cdata->{parent});} ;
2505 delete $parent->{empty}; $parent->{last_child}=$cdata; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ;
2506 $t->{twig_in_pcdata}=0;
2507 }
2508 else
2509 { # we have to create a PCDATA element if we need to store spaces
2510 if( $t->_space_policy($XML::Twig::index2gi[$twig_current->{'gi'}]) && $t->{twig_stored_spaces})
2511 { _insert_pcdata( $t, $t->{twig_stored_spaces}); }
2512 $t->{twig_stored_spaces}='';
2513  
2514 # create the node as a child of the current element
2515 $cdata->{parent}=$twig_current; if( $XML::Twig::weakrefs) { weaken( $cdata->{parent});} ;
2516 if( my $prev_sibling= $twig_current->{last_child})
2517 { $cdata->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $cdata->{prev_sibling});} ;
2518 $prev_sibling->{next_sibling}= $cdata;
2519 }
2520 else
2521 { $twig_current->{first_child}= $cdata; }
2522 delete $twig_current->{empty}; $twig_current->{last_child}=$cdata; if( $XML::Twig::weakrefs) { weaken( $twig_current->{last_child});} ;
2523 }
2524  
2525 delete $twig_current->{'twig_current'};
2526 $t->{twig_current}= $cdata;
2527 $cdata->{'twig_current'}=1;
2528 if( $t->{extra_data}) { $cdata->set_extra_data( $t->{extra_data}); $t->{extra_data}='' };
2529 return;
2530 }
2531  
2532 sub _twig_cdataend
2533 { # warn " in _twig_cdataend...\n"; # DEBUG handler
2534  
2535 my $p= shift;
2536 my $t=$p->{twig};
2537  
2538 $t->{twig_in_cdata}=0;
2539  
2540 my $elt= $t->{twig_current};
2541 delete $elt->{'twig_current'};
2542 my $cdata= $elt->{cdata};
2543 $elt->{cdata}= $cdata;
2544  
2545 push @{$t->{_twig_context_stack}}, { $ST_TAG => $CDATA };
2546  
2547 if( $t->{twig_handlers})
2548 { # look for handlers
2549 my @handlers= _handler( $t, $t->{twig_handlers}, $CDATA);
2550 local $_= $elt; # so we can use $_ in the handlers
2551 foreach my $handler ( @handlers) { $handler->($t, $elt) || last; }
2552 }
2553  
2554 pop @{$t->{_twig_context_stack}};
2555  
2556 $elt= $elt->{parent};
2557 $t->{twig_current}= $elt;
2558 $elt->{'twig_current'}=1;
2559  
2560 $t->{twig_long_cdata}=0;
2561 return;
2562 }
2563  
2564 sub _pi_elt_handlers
2565 { my( $t, $pi)= @_;
2566 my $pi_handlers= $t->{twig_handlers}->{pi_handlers} || return;
2567 foreach my $handler ( $pi_handlers->{$pi->{target}}, $pi_handlers->{''})
2568 { if( $handler) { local $_= $pi; $handler->( $t, $pi) || last; } }
2569 }
2570  
2571 sub _pi_text_handler
2572 { my( $t, $target, $data)= @_;
2573 if( my $handler= $t->{twig_handlers}->{pi_handlers}->{$target})
2574 { return $handler->( $t, $target, $data); }
2575 if( my $handler= $t->{twig_handlers}->{pi_handlers}->{''})
2576 { return $handler->( $t, $target, $data); }
2577 return defined( $data) && $data ne '' ? "<?$target $data?>" : "<?$target?>" ;
2578 }
2579  
2580 sub _comment_elt_handler
2581 { my( $t, $comment)= @_;
2582 if( my $handler= $t->{twig_handlers}->{handlers}->{$COMMENT})
2583 { local $_= $comment; $handler->($t, $comment); }
2584 }
2585  
2586 sub _comment_text_handler
2587 { my( $t, $comment)= @_;
2588 if( my $handler= $t->{twig_handlers}->{handlers}->{$COMMENT})
2589 { $comment= $handler->($t, $comment);
2590 if( !defined $comment || $comment eq '') { return ''; }
2591 }
2592 return "<!--$comment-->";
2593 }
2594  
2595 sub _twig_comment
2596 { # warn " in _twig_comment...\n"; # DEBUG handler
2597 my( $p, $comment_text)= @_;
2598 my $t=$p->{twig};
2599  
2600 if( $t->{twig_keep_encoding}) { $comment_text= substr( $p->original_string(), 4, -3); }
2601  
2602 $t->_twig_pi_comment( $p, $COMMENT, $t->{twig_keep_comments}, $t->{twig_process_comments},
2603 '_set_comment', '_comment_elt_handler', '_comment_text_handler', $comment_text
2604 );
2605 return;
2606 }
2607  
2608 sub _twig_pi
2609 { # warn " in _twig_pi...\n"; # DEBUG handler
2610  
2611 my( $p, $target, $data)= @_;
2612 my $t=$p->{twig};
2613  
2614 if( $t->{twig_keep_encoding})
2615 { my $pi_text= substr( $p->original_string(), 2, -2);
2616 ($target, $data)= split( /\s+/, $pi_text, 2);
2617 }
2618  
2619 $t->_twig_pi_comment( $p, $PI, $t->{twig_keep_pi}, $t->{twig_process_pi},
2620 '_set_pi', '_pi_elt_handlers', '_pi_text_handler', $target, $data
2621 );
2622 return;
2623 }
2624  
2625 sub _twig_pi_comment
2626 { my( $t, $p, $type, $keep, $process, $set, $elt_handler, $text_handler, @parser_args)= @_;
2627  
2628 if( $t->{twig_input_filter})
2629 { foreach my $arg (@parser_args) { $arg= $t->{twig_input_filter}->( $arg); } }
2630  
2631 # if pi/comments are to be kept then we piggyback them to the current element
2632 if( $keep)
2633 { # first add spaces
2634 if( $t->{twig_stored_spaces})
2635 { $t->{extra_data}.= $t->{twig_stored_spaces};
2636 $t->{twig_stored_spaces}= '';
2637 }
2638  
2639 my $extra_data= $t->$text_handler( @parser_args);
2640 $t->{extra_data}.= $extra_data;
2641  
2642 }
2643 elsif( $process)
2644 {
2645 my $twig_current= $t->{twig_current}; # defined unless we are outside of the root
2646  
2647 my $elt= $t->{twig_elt_class}->new( $type);
2648 $elt->$set( @parser_args);
2649 if( $t->{extra_data})
2650 { $elt->set_extra_data( $t->{extra_data});
2651 $t->{extra_data}='';
2652 }
2653  
2654 if( ! $t->root)
2655 { $t->_add_cpi_outside_of_root( leading_cpi => $elt);
2656 }
2657 elsif( $t->{twig_in_pcdata})
2658 { $t->_trigger_text_handler();
2659 # create the node as a sibling of the PCDATA
2660 $elt->paste_after( $twig_current);
2661 $t->{twig_in_pcdata}=0;
2662 }
2663 elsif( $twig_current)
2664 { # we have to create a PCDATA element if we need to store spaces
2665 if( $t->_space_policy($XML::Twig::index2gi[$twig_current->{'gi'}]) && $t->{twig_stored_spaces})
2666 { _insert_pcdata( $t, $t->{twig_stored_spaces}); }
2667 $t->{twig_stored_spaces}='';
2668 # create the node as a child of the current element
2669 $elt->paste_last_child( $twig_current);
2670 }
2671 else
2672 { $t->_add_cpi_outside_of_root( trailing_cpi => $elt); }
2673  
2674 if( $twig_current)
2675 { delete $twig_current->{'twig_current'};
2676 my $parent= $elt->{parent};
2677 $t->{twig_current}= $parent;
2678 $parent->{'twig_current'}=1;
2679 }
2680  
2681 $t->$elt_handler( $elt);
2682 }
2683  
2684 }
2685  
2686 sub _trigger_text_handler
2687 { my ($t) = @_;
2688 if( my $text_handler= $t->{twig_handlers}->{handlers}->{$TEXT} )
2689 { local $_= $t->{twig_current};
2690 $text_handler->( $t, $_) if $_;
2691 }
2692 }
2693  
2694 # add a comment or pi before the first element
2695 sub _add_cpi_outside_of_root
2696 { my($t, $type, $elt)= @_; # $type is 'leading_cpi' or 'trailing_cpi'
2697 $t->{$type} ||= $t->{twig_elt_class}->new( '#CPI');
2698 # create the node as a child of the current element
2699 $elt->paste_last_child( $t->{$type});
2700 return $t;
2701 }
2702  
2703 sub _twig_final
2704 { # warn " in _twig_final...\n"; # DEBUG handler
2705  
2706 my $p= shift;
2707 my $t= $p->isa( 'XML::Twig') ? $p : $p->{twig};
2708  
2709 # store trailing data
2710 if( $t->{extra_data}) { $t->{trailing_cpi_text} = $t->{extra_data}; $t->{extra_data}=''; }
2711 $t->{trailing_spaces}= $t->{twig_stored_spaces} || '';
2712 my $s= $t->{twig_stored_spaces}; $s=~s{\n}{\\n}g;
2713 if( $t->{twig_stored_spaces}) { my $s= $t->{twig_stored_spaces}; }
2714  
2715 # restore the selected filehandle if needed
2716 $t->_set_fh_to_selected_fh();
2717  
2718 $t->_trigger_tdh if( $t->{twig_tdh});
2719  
2720 select $t->{twig_original_selected_fh} if($t->{twig_original_selected_fh}); # probably dodgy
2721  
2722 if( exists $t->{twig_autoflush_data})
2723 { my @args;
2724 push @args, $t->{twig_autoflush_data}->{fh} if( $t->{twig_autoflush_data}->{fh});
2725 push @args, @{$t->{twig_autoflush_data}->{args}} if( $t->{twig_autoflush_data}->{args});
2726 $t->flush( @args);
2727 delete $t->{twig_autoflush_data};
2728 $t->root->delete if $t->root;
2729 }
2730  
2731 # tries to clean-up (probably not very well at the moment)
2732 #undef $p->{twig};
2733 undef $t->{twig_parser};
2734 delete $t->{twig_parsing};
2735 @{$t}{ qw( twig_parser twig_parsing _twig_context_stack twig_current) }=();
2736  
2737 return $t;
2738 }
2739  
2740 sub _insert_pcdata
2741 { my( $t, $string)= @_;
2742 # create a new PCDATA element
2743 my $parent= $t->{twig_current}; # always defined
2744 my $elt;
2745 if( exists $t->{twig_alt_elt_class})
2746 { $elt= $t->{twig_elt_class}->new( $PCDATA);
2747 $elt->{pcdata}= $string;
2748 }
2749 else
2750 { $elt= bless( { gi => $XML::Twig::gi2index{$PCDATA}, pcdata => $string }, 'XML::Twig::Elt'); }
2751  
2752 my $prev_sibling= $parent->{last_child};
2753 if( $prev_sibling)
2754 { $prev_sibling->{next_sibling}= $elt;
2755 $elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
2756 }
2757 else
2758 { $parent->{first_child}= $elt; }
2759  
2760 $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
2761 delete $parent->{empty}; $parent->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ;
2762 $t->{twig_stored_spaces}='';
2763 return $elt;
2764 }
2765  
2766 sub _space_policy
2767 { my( $t, $gi)= @_;
2768 my $policy;
2769 $policy=0 if( $t->{twig_discard_spaces});
2770 $policy=1 if( $t->{twig_keep_spaces});
2771 $policy=1 if( $t->{twig_keep_spaces_in}
2772 && $t->{twig_keep_spaces_in}->{$gi});
2773 $policy=0 if( $t->{twig_discard_spaces_in}
2774 && $t->{twig_discard_spaces_in}->{$gi});
2775 return $policy;
2776 }
2777  
2778 sub _twig_entity
2779 { # warn " in _twig_entity...\n"; # DEBUG handler
2780 my( $p, $name, $val, $sysid, $pubid, $ndata, $param)= @_;
2781 my $t=$p->{twig};
2782  
2783 #{ no warnings; my $base= $p->base; warn "_twig_entity called: expand: '$t->{twig_expand_external_ents}', base: '$base', name: '$name', val: '$val', sysid: '$sysid', pubid: '$pubid', ndata: '$ndata', param: '$param'\n";}
2784  
2785 my $missing_entity=0;
2786  
2787 if( $sysid)
2788 { if($ndata)
2789 { if( ! -f _based_filename( $sysid, $p->base)) { $missing_entity= 1; }
2790 }
2791 else
2792 { if( $t->{twig_expand_external_ents})
2793 { $val= eval { _slurp_uri( $sysid, $p->base) };
2794 if( ! defined $val)
2795 { if( $t->{twig_extern_ent_nofail})
2796 { $missing_entity= 1; }
2797 else
2798 { _croak( "cannot load SYSTEM entity '$name' from '$sysid': $@", 3); }
2799 }
2800 }
2801 }
2802 }
2803  
2804 my $ent=XML::Twig::Entity->new( $name, $val, $sysid, $pubid, $ndata, $param);
2805 if( $missing_entity) { $t->{twig_missing_system_entities}->{$name}= $ent; }
2806  
2807 my $entity_list= $t->entity_list;
2808 if( $entity_list) { $entity_list->add( $ent); }
2809  
2810 if( $parser_version > 2.27)
2811 { # this is really ugly, but with some versions of XML::Parser the value
2812 # of the entity is not properly returned by the default handler
2813 my $ent_decl= $ent->text;
2814 if( $t->{twig_keep_encoding})
2815 { if( defined $ent->{val} && ($ent_decl !~ /["']/))
2816 { my $val= $ent->{val};
2817 $ent_decl .= $val =~ /"/ ? qq{'$val' } : qq{"$val" };
2818 }
2819 # for my solaris box (perl 5.6.1, XML::Parser 2.31, expat?)
2820 $t->{twig_doctype}->{internal}=~ s{<!ENTITY\s+$name\s+$}{substr( $ent_decl, 0, -1)}e;
2821 }
2822 $t->{twig_doctype}->{internal} .= $ent_decl
2823 unless( $t->{twig_doctype}->{internal}=~ m{<!ENTITY\s+$name\s+});
2824 }
2825  
2826 return;
2827 }
2828  
2829 sub _twig_notation
2830 { my( $p, $name, $base, $sysid, $pubid ) = @_;
2831 my $t = $p->{twig};
2832  
2833 my $notation = XML::Twig::Notation->new( $name, $base, $sysid, $pubid );
2834 my $notation_list = $t->notation_list();
2835 if( $notation_list ) { $notation_list->add( $notation ); }
2836  
2837 # internal should get the recognized_string, but XML::Parser does not provide it
2838 # so we need to re-create it ( $notation->text) and stick it there.
2839 $t->{twig_doctype}->{internal} .= $notation->text;
2840  
2841 return;
2842 }
2843  
2844 sub _twig_extern_ent
2845 { # warn " in _twig_extern_ent...I (", $_[0]->original_string, ")\n"; # DEBUG handler
2846 my( $p, $base, $sysid, $pubid)= @_;
2847 my $t= $p->{twig};
2848 if( $t->{twig_no_expand})
2849 { my $ent_name= $t->{twig_keep_encoding} ? $p->original_string : $p->recognized_string;
2850 _twig_insert_ent( $t, $ent_name);
2851 return '';
2852 }
2853 my $ent_content= eval { $t->{twig_ext_ent_handler}->( $p, $base, $sysid) };
2854 if( ! defined $ent_content)
2855 {
2856 my $ent_name = $p->recognized_string;
2857 my $file = _based_filename( $sysid, $base);
2858 my $error_message= "cannot expand $ent_name - cannot load '$file'";
2859 if( $t->{twig_extern_ent_nofail}) { return "<!-- $error_message -->"; }
2860 else { _croak( $error_message); }
2861 }
2862 return $ent_content;
2863 }
2864  
2865 # I use this so I can change the $Carp::CarpLevel (which determines how many call frames to skip when reporting an error)
2866 sub _croak
2867 { my( $message, $level)= @_;
2868 $Carp::CarpLevel= $level || 0;
2869 croak $message;
2870 }
2871  
2872 sub _twig_xmldecl
2873 { # warn " in _twig_xmldecl...\n"; # DEBUG handler
2874  
2875 my $p= shift;
2876 my $t=$p->{twig};
2877 $t->{twig_xmldecl}||={}; # could have been set by set_output_encoding
2878 $t->{twig_xmldecl}->{version}= shift;
2879 $t->{twig_xmldecl}->{encoding}= shift;
2880 $t->{twig_xmldecl}->{standalone}= shift;
2881 return;
2882 }
2883  
2884 sub _twig_doctype
2885 { # warn " in _twig_doctype...\n"; # DEBUG handler
2886 my( $p, $name, $sysid, $pub, $internal)= @_;
2887 my $t=$p->{twig};
2888 $t->{twig_doctype}||= {}; # create
2889 $t->{twig_doctype}->{name}= $name; # always there
2890 $t->{twig_doctype}->{sysid}= $sysid; #
2891 $t->{twig_doctype}->{pub}= $pub; #
2892  
2893 # now let's try to cope with XML::Parser 2.28 and above
2894 if( $parser_version > 2.27)
2895 { @saved_default_handler= $p->setHandlers( Default => \&_twig_store_internal_dtd,
2896 Entity => \&_twig_entity,
2897 );
2898 $p->setHandlers( DoctypeFin => \&_twig_stop_storing_internal_dtd);
2899 $t->{twig_doctype}->{internal}='';
2900 }
2901 else
2902 # for XML::Parser before 2.28
2903 { $internal||='';
2904 $internal=~ s{^\s*\[}{};
2905 $internal=~ s{]\s*$}{};
2906 $t->{twig_doctype}->{internal}=$internal;
2907 }
2908  
2909 # now check if we want to get the DTD info
2910 if( $t->{twig_read_external_dtd} && $sysid)
2911 { # let's build a fake document with an internal DTD
2912 if( $t->{DTDBase})
2913 { _use( 'File::Spec');
2914 $sysid=File::Spec->catfile($t->{DTDBase}, $sysid);
2915 }
2916 my $dtd= _slurp_uri( $sysid);
2917 # if the DTD includes an XML declaration, it needs to be moved before the DOCTYPE bit
2918 if( $dtd=~ s{^(\s*<\?xml(\s+\w+\s*=\s*("[^"]*"|'[^']*'))*\s*\?>)}{})
2919 { $dtd= "$1<!DOCTYPE $name [$dtd]><$name/>"; }
2920 else
2921 { $dtd= "<!DOCTYPE $name [$dtd]><$name/>"; }
2922  
2923 $t->save_global_state(); # save the globals (they will be reset by the following new)
2924 my $t_dtd= XML::Twig->new( load_DTD => 1, ParseParamEnt => 1, error_context => $t->{ErrorContext} || 0); # create a temp twig
2925 $t_dtd->parse( $dtd); # parse it
2926 $t->{twig_dtd}= $t_dtd->{twig_dtd}; # grab the dtd info
2927 #$t->{twig_dtd_is_external}=1;
2928 $t->entity_list->_add_list( $t_dtd->entity_list) if( $t_dtd->entity_list); # grab the entity info
2929 $t->notation_list->_add_list( $t_dtd->notation_list) if( $t_dtd->notation_list); # grab the notation info
2930 $t->restore_global_state();
2931 }
2932 return;
2933 }
2934  
2935 sub _twig_element
2936 { # warn " in _twig_element...\n"; # DEBUG handler
2937  
2938 my( $p, $name, $model)= @_;
2939 my $t=$p->{twig};
2940 $t->{twig_dtd}||= {}; # may create the dtd
2941 $t->{twig_dtd}->{model}||= {}; # may create the model hash
2942 $t->{twig_dtd}->{elt_list}||= []; # ordered list of elements
2943 push @{$t->{twig_dtd}->{elt_list}}, $name; # store the elt
2944 $t->{twig_dtd}->{model}->{$name}= $model; # store the model
2945 if( ($parser_version > 2.27) && ($t->{twig_doctype}->{internal}=~ m{(^|>)\s*$}) )
2946 { my $text= $XML::Twig::Elt::keep_encoding ? $p->original_string : $p->recognized_string;
2947 unless( $text)
2948 { # this version of XML::Parser does not return the text in the *_string method
2949 # we need to rebuild it
2950 $text= "<!ELEMENT $name $model>";
2951 }
2952 $t->{twig_doctype}->{internal} .= $text;
2953 }
2954 return;
2955 }
2956  
2957 sub _twig_attlist
2958 { # warn " in _twig_attlist...\n"; # DEBUG handler
2959  
2960 my( $p, $gi, $att, $type, $default, $fixed)= @_;
2961 #warn "in attlist: gi: '$gi', att: '$att', type: '$type', default: '$default', fixed: '$fixed'\n";
2962 my $t=$p->{twig};
2963 $t->{twig_dtd}||= {}; # create dtd if need be
2964 $t->{twig_dtd}->{$gi}||= {}; # create elt if need be
2965 #$t->{twig_dtd}->{$gi}->{att}||= {}; # create att if need be
2966 if( ($parser_version > 2.27) && ($t->{twig_doctype}->{internal}=~ m{(^|>)\s*$}) )
2967 { my $text= $XML::Twig::Elt::keep_encoding ? $p->original_string : $p->recognized_string;
2968 unless( $text)
2969 { # this version of XML::Parser does not return the text in the *_string method
2970 # we need to rebuild it
2971 my $att_decl="$att $type";
2972 $att_decl .= " #FIXED" if( $fixed);
2973 $att_decl .= " $default" if( defined $default);
2974 # 2 cases: there is already an attlist on that element or not
2975 if( $t->{twig_dtd}->{att}->{$gi})
2976 { # there is already an attlist, add to it
2977 $t->{twig_doctype}->{internal}=~ s{(<!ATTLIST\s*$gi )(.*?)\n?>}
2978 { "$1$2\n" . ' ' x length( $1) . "$att_decl\n>"}es;
2979 }
2980 else
2981 { # create the attlist
2982 $t->{twig_doctype}->{internal}.= "<!ATTLIST $gi $att_decl>"
2983 }
2984 }
2985 }
2986 $t->{twig_dtd}->{att}->{$gi}->{$att}= {} ;
2987 $t->{twig_dtd}->{att}->{$gi}->{$att}->{type}= $type;
2988 $t->{twig_dtd}->{att}->{$gi}->{$att}->{default}= $default if( defined $default);
2989 $t->{twig_dtd}->{att}->{$gi}->{$att}->{fixed}= $fixed;
2990 return;
2991 }
2992  
2993 sub _twig_default
2994 { # warn " in _twig_default...\n"; # DEBUG handler
2995  
2996 my( $p, $string)= @_;
2997  
2998 my $t= $p->{twig};
2999  
3000 # we need to process the data in 2 cases: entity, or spaces after the closing tag
3001  
3002 # after the closing tag (no twig_current and root has been created)
3003 if( ! $t->{twig_current} && $t->{twig_root} && $string=~ m{^\s+$}m) { $t->{twig_stored_spaces} .= $string; }
3004  
3005 # process only if we have an entity
3006 if( $string=~ m{^&([^;]*);$})
3007 { # the entity has to be pure pcdata, or we have a problem
3008 if( ($p->original_string=~ m{^<}) && ($p->original_string=~ m{>$}) )
3009 { # string is a tag, entity is in an attribute
3010 $t->{twig_entities_in_attribute}=1 if( $t->{twig_do_not_escape_amp_in_atts});
3011 }
3012 else
3013 { my $ent;
3014 if( $t->{twig_keep_encoding})
3015 { _twig_char( $p, $string);
3016 $ent= substr( $string, 1, -1);
3017 }
3018 else
3019 { $ent= _twig_insert_ent( $t, $string);
3020 }
3021  
3022 return $ent;
3023 }
3024 }
3025 }
3026  
3027 sub _twig_insert_ent
3028 {
3029 my( $t, $string)=@_;
3030  
3031 my $twig_current= $t->{twig_current};
3032  
3033 my $ent= $t->{twig_elt_class}->new( $ENT);
3034 $ent->{ent}= $string;
3035  
3036 _add_or_discard_stored_spaces( $t);
3037  
3038 if( $t->{twig_in_pcdata})
3039 { # create the node as a sibling of the #PCDATA
3040  
3041 $ent->{prev_sibling}=$twig_current; if( $XML::Twig::weakrefs) { weaken( $ent->{prev_sibling});} ;
3042 $twig_current->{next_sibling}= $ent;
3043 my $parent= $twig_current->{parent};
3044 $ent->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $ent->{parent});} ;
3045 delete $parent->{empty}; $parent->{last_child}=$ent; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ;
3046 # the twig_current is now the parent
3047 delete $twig_current->{'twig_current'};
3048 $t->{twig_current}= $parent;
3049 # we left pcdata
3050 $t->{twig_in_pcdata}=0;
3051 }
3052 else
3053 { # create the node as a child of the current element
3054 $ent->{parent}=$twig_current; if( $XML::Twig::weakrefs) { weaken( $ent->{parent});} ;
3055 if( my $prev_sibling= $twig_current->{last_child})
3056 { $ent->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $ent->{prev_sibling});} ;
3057 $prev_sibling->{next_sibling}= $ent;
3058 }
3059 else
3060 { if( $twig_current) { $twig_current->{first_child}= $ent; } }
3061 if( $twig_current) { delete $twig_current->{empty}; $twig_current->{last_child}=$ent; if( $XML::Twig::weakrefs) { weaken( $twig_current->{last_child});} ; }
3062 }
3063  
3064 return $ent;
3065 }
3066  
3067 sub parser
3068 { return $_[0]->{twig_parser}; }
3069  
3070 # returns the declaration text (or a default one)
3071 sub xmldecl
3072 { my $t= shift;
3073 return '' unless( $t->{twig_xmldecl} || $t->{output_encoding});
3074 my $decl_string;
3075 my $decl= $t->{twig_xmldecl};
3076 if( $decl)
3077 { my $version= $decl->{version};
3078 $decl_string= q{<?xml};
3079 $decl_string .= qq{ version="$version"};
3080  
3081 # encoding can either have been set (in $decl->{output_encoding})
3082 # or come from the document (in $decl->{encoding})
3083 if( $t->{output_encoding})
3084 { my $encoding= $t->{output_encoding};
3085 $decl_string .= qq{ encoding="$encoding"};
3086 }
3087 elsif( $decl->{encoding})
3088 { my $encoding= $decl->{encoding};
3089 $decl_string .= qq{ encoding="$encoding"};
3090 }
3091  
3092 if( defined( $decl->{standalone}))
3093 { $decl_string .= q{ standalone="};
3094 $decl_string .= $decl->{standalone} ? "yes" : "no";
3095 $decl_string .= q{"};
3096 }
3097  
3098 $decl_string .= "?>\n";
3099 }
3100 else
3101 { my $encoding= $t->{output_encoding};
3102 $decl_string= qq{<?xml version="1.0" encoding="$encoding"?>};
3103 }
3104  
3105 my $output_filter= XML::Twig::Elt::output_filter();
3106 return $output_filter ? $output_filter->( $decl_string) : $decl_string;
3107 }
3108  
3109 sub set_doctype
3110 { my( $t, $name, $system, $public, $internal)= @_;
3111 $t->{twig_doctype}= {} unless defined $t->{twig_doctype};
3112 my $doctype= $t->{twig_doctype};
3113 $doctype->{name} = $name if( defined $name);
3114 $doctype->{sysid} = $system if( defined $system);
3115 $doctype->{pub} = $public if( defined $public);
3116 $doctype->{internal} = $internal if( defined $internal);
3117 }
3118  
3119 sub doctype_name
3120 { my $t= shift;
3121 my $doctype= $t->{twig_doctype} or return '';
3122 return $doctype->{name} || '';
3123 }
3124  
3125 sub system_id
3126 { my $t= shift;
3127 my $doctype= $t->{twig_doctype} or return '';
3128 return $doctype->{sysid} || '';
3129 }
3130  
3131 sub public_id
3132 { my $t= shift;
3133 my $doctype= $t->{twig_doctype} or return '';
3134 return $doctype->{pub} || '';
3135 }
3136  
3137 sub internal_subset
3138 { my $t= shift;
3139 my $doctype= $t->{twig_doctype} or return '';
3140 return $doctype->{internal} || '';
3141 }
3142  
3143 # return the dtd object
3144 sub dtd
3145 { my $t= shift;
3146 return $t->{twig_dtd};
3147 }
3148  
3149 # return an element model, or the list of element models
3150 sub model
3151 { my $t= shift;
3152 my $elt= shift;
3153 return $t->dtd->{model}->{$elt} if( $elt);
3154 return (sort keys %{$t->dtd->{model}});
3155 }
3156  
3157 # return the entity_list object
3158 sub entity_list
3159 { my $t= shift;
3160 return $t->{twig_entity_list};
3161 }
3162  
3163 # return the list of entity names
3164 sub entity_names
3165 { my $t= shift;
3166 return $t->entity_list->entity_names;
3167 }
3168  
3169 # return the entity object
3170 sub entity
3171 { my $t= shift;
3172 my $entity_name= shift;
3173 return $t->entity_list->ent( $entity_name);
3174 }
3175  
3176 # return the notation_list object
3177 sub notation_list
3178 { my $t= shift;
3179 return $t->{twig_notation_list};
3180 }
3181  
3182 # return the list of notation names
3183 sub notation_names
3184 { my $t= shift;
3185 return $t->notation_list->notation_names;
3186 }
3187  
3188 # return the notation object
3189 sub notation
3190 { my $t= shift;
3191 my $notation_name= shift;
3192 return $t->notation_list->notation( $notation_name);
3193 }
3194  
3195 sub print_prolog
3196 { my $t= shift;
3197 my $fh= isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar') ? shift : $t->{twig_output_fh} || select() || \*STDOUT;
3198 ## no critic (TestingAndDebugging::ProhibitNoStrict);
3199 no strict 'refs';
3200 print {$fh} $t->prolog( @_);
3201 }
3202  
3203 sub prolog
3204 { my $t= shift;
3205 if( $t->{no_prolog}){ return ''; }
3206  
3207 return $t->{no_prolog} ? ''
3208 : defined $t->{no_dtd_output} ? $t->xmldecl
3209 : $t->xmldecl . $t->doctype( @_);
3210 }
3211  
3212 sub doctype
3213 { my $t= shift;
3214 my %args= _normalize_args( @_);
3215 my $update_dtd = $args{UpdateDTD} || '';
3216 my $doctype_text='';
3217  
3218 my $doctype= $t->{twig_doctype};
3219  
3220 if( $doctype)
3221 { $doctype_text .= qq{<!DOCTYPE $doctype->{name}} if( $doctype->{name});
3222 $doctype_text .= qq{ PUBLIC "$doctype->{pub}"} if( $doctype->{pub});
3223 $doctype_text .= qq{ SYSTEM} if( $doctype->{sysid} && !$doctype->{pub});
3224 $doctype_text .= qq{ "$doctype->{sysid}"} if( $doctype->{sysid});
3225 }
3226  
3227 if( $update_dtd)
3228 { if( $doctype)
3229 { my $internal=$doctype->{internal};
3230 # awful hack, but at least it works a little better that what was there before
3231 if( $internal)
3232 { # remove entity and notation declarations (they will be re-generated from the updated entity list)
3233 $internal=~ s{<! \s* ENTITY \s+ $REG_TAG_NAME \s+ ( ("[^"]*"|'[^']*') \s* | SYSTEM [^>]*) >\s*}{}xg;
3234 $internal=~ s{<! \s* NOTATION .*? >\s*}{}sxg;
3235 $internal=~ s{^\n}{};
3236 }
3237 $internal .= $t->entity_list->text ||'' if( $t->entity_list);
3238 $internal .= $t->notation_list->text ||'' if( $t->notation_list);
3239 if( $internal) { $doctype_text .= "[\n$internal]>\n"; }
3240 }
3241 elsif( !$t->{'twig_dtd'} && ( keys %{$t->entity_list} || keys %{$t->notation_list} ) )
3242 { $doctype_text .= "<!DOCTYPE " . $t->root->gi . " [\n" . $t->entity_list->text . $t->notation_list->text . "\n]>";}
3243 else
3244 { $doctype_text= $t->{twig_dtd};
3245 $doctype_text .= $t->dtd_text;
3246 }
3247 }
3248 elsif( $doctype)
3249 { if( my $internal= $doctype->{internal})
3250 { # add opening and closing brackets if not already there
3251 # plus some spaces and newlines for a nice formating
3252 # I test it here because I can't remember which version of
3253 # XML::Parser need it or not, nor guess which one will in the
3254 # future, so this about the best I can do
3255 $internal=~ s{^\s*(\[\s*)?}{ [\n};
3256 $internal=~ s{\s*(\]\s*(>\s*)?)?\s*$}{\n]>\n};
3257  
3258 $doctype_text .= $internal;
3259 }
3260 }
3261  
3262 if( $doctype_text)
3263 {
3264 # terrible hack, as I can't figure out in which case the darn prolog
3265 # should get an extra > (depends on XML::Parser and expat versions)
3266 $doctype_text=~ s/(>\s*)*$/>\n/;
3267  
3268 my $output_filter= XML::Twig::Elt::output_filter();
3269 return $output_filter ? $output_filter->( $doctype_text) : $doctype_text;
3270 }
3271 else
3272 { return $doctype_text; }
3273 }
3274  
3275 sub _leading_cpi
3276 { my $t= shift;
3277 my $leading_cpi= $t->{leading_cpi} || return '';
3278 return $leading_cpi->sprint( 1);
3279 }
3280  
3281 sub _trailing_cpi
3282 { my $t= shift;
3283 my $trailing_cpi= $t->{trailing_cpi} || return '';
3284 return $trailing_cpi->sprint( 1);
3285 }
3286  
3287 sub _trailing_cpi_text
3288 { my $t= shift;
3289 return $t->{trailing_cpi_text} || '';
3290 }
3291  
3292 sub print_to_file
3293 { my( $t, $filename)= (shift, shift);
3294 my $out_fh;
3295 my $mode= $t->{twig_keep_encoding} && ! _use_perlio() ? '>' : '>:utf8';
3296 open( $out_fh, $mode, $filename) or _croak( "cannot create file $filename: $!");
3297 $t->print( $out_fh, @_);
3298 close $out_fh;
3299 return $t;
3300 }
3301  
3302 # probably only works on *nix (at least the chmod bit)
3303 # first print to a temporary file, then rename that file to the desired file name, then change permissions
3304 # to the original file permissions (or to the current umask)
3305 sub safe_print_to_file
3306 { my( $t, $filename)= (shift, shift);
3307 my $perm= -f $filename ? (stat $filename)[2] & 07777 : ~umask() ; ## no critic (ProhibitLeadingZeros)
3308 XML::Twig::_use( 'File::Temp') || croak "need File::Temp to use safe_print_to_file\n";
3309 my $tmpdir= dirname( $filename);
3310 my( $fh, $tmpfilename) = File::Temp::tempfile( DIR => $tmpdir);
3311 $t->print_to_file( $tmpfilename, @_);
3312 rename( $tmpfilename, $filename) or unlink $tmpfilename && _croak( "cannot move temporary file to $filename: $!");
3313 chmod $perm, $filename;
3314 return $t;
3315 }
3316  
3317 sub print
3318 { my $t= shift;
3319 my $fh= isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar') ? shift : undef;
3320 my %args= _normalize_args( @_);
3321  
3322 my $old_select = defined $fh ? select $fh : undef;
3323 my $old_pretty = defined ($args{PrettyPrint}) ? $t->set_pretty_print( $args{PrettyPrint}) : undef;
3324 my $old_empty_tag = defined ($args{EmptyTags}) ? $t->set_empty_tag_style( $args{EmptyTags}) : undef;
3325  
3326 ## no critic (RequireEncodingWithUTF8Layer)
3327 if( ! $t->{twig_keep_encoding} && _use_perlio() ) { binmode( $fh || \*STDOUT, ":utf8" ); }
3328  
3329 print $t->prolog( %args) . $t->_leading_cpi( %args);
3330 $t->{twig_root}->print;
3331 print $t->_trailing_cpi # trailing comments and pi's (elements, in 'process' mode)
3332 . $t->_trailing_cpi_text # trailing comments and pi's (in 'keep' mode)
3333 . ( ($t->{twig_keep_spaces}||'') && ($t->{trailing_spaces} || ''))
3334 ;
3335  
3336 $t->set_pretty_print( $old_pretty) if( defined $old_pretty);
3337 $t->set_empty_tag_style( $old_empty_tag) if( defined $old_empty_tag);
3338 if( $fh) { select $old_select; }
3339  
3340 return $t;
3341 }
3342  
3343 sub flush
3344 { my $t= shift;
3345  
3346 $t->_trigger_tdh if $t->{twig_tdh};
3347  
3348 return if( $t->{twig_completely_flushed});
3349  
3350 my $fh= isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar') ? shift : undef;
3351 my $old_select= defined $fh ? select $fh : undef;
3352 my $up_to= ref $_[0] ? shift : undef;
3353 my %args= _normalize_args( @_);
3354  
3355 my $old_pretty;
3356 if( defined $args{PrettyPrint})
3357 { $old_pretty= $t->set_pretty_print( $args{PrettyPrint});
3358 delete $args{PrettyPrint};
3359 }
3360  
3361 my $old_empty_tag_style;
3362 if( $args{EmptyTags})
3363 { $old_empty_tag_style= $t->set_empty_tag_style( $args{EmptyTags});
3364 delete $args{EmptyTags};
3365 }
3366  
3367 # the "real" last element processed, as _twig_end has closed it
3368 my $last_elt;
3369 my $flush_trailing_data=0;
3370 if( $up_to)
3371 { $last_elt= $up_to; }
3372 elsif( $t->{twig_current})
3373 { $last_elt= $t->{twig_current}->{last_child}; }
3374 else
3375 { $last_elt= $t->{twig_root};
3376 $flush_trailing_data=1;
3377 $t->{twig_completely_flushed}=1;
3378 }
3379  
3380 # flush the DTD unless it has ready flushed (ie root has been flushed)
3381 my $elt= $t->{twig_root};
3382 unless( $elt->{'flushed'})
3383 { # store flush info so we can auto-flush later
3384 if( $t->{twig_autoflush})
3385 { $t->{twig_autoflush_data}={};
3386 $t->{twig_autoflush_data}->{fh} = $fh if( $fh);
3387 $t->{twig_autoflush_data}->{args} = \@_ if( @_);
3388 }
3389 $t->print_prolog( %args);
3390 print $t->_leading_cpi;
3391 }
3392  
3393 while( $elt)
3394 { my $next_elt;
3395 if( $last_elt && $last_elt->in( $elt))
3396 {
3397 unless( $elt->{'flushed'})
3398 { # just output the front tag
3399 print $elt->start_tag();
3400 $elt->{'flushed'}=1;
3401 }
3402 $next_elt= $elt->{first_child};
3403 }
3404 else
3405 { # an element before the last one or the last one,
3406 $next_elt= $elt->{next_sibling};
3407 $elt->_flush();
3408 $elt->delete;
3409 last if( $last_elt && ($elt == $last_elt));
3410 }
3411 $elt= $next_elt;
3412 }
3413  
3414 if( $flush_trailing_data)
3415 { print $t->_trailing_cpi # trailing comments and pi's (elements, in 'process' mode)
3416 , $t->_trailing_cpi_text # trailing comments and pi's (in 'keep' mode)
3417 }
3418  
3419 select $old_select if( defined $old_select);
3420 $t->set_pretty_print( $old_pretty) if( defined $old_pretty);
3421 $t->set_empty_tag_style( $old_empty_tag_style) if( defined $old_empty_tag_style);
3422  
3423 if( my $ids= $t->{twig_id_list})
3424 { while( my ($id, $elt)= each %$ids)
3425 { if( ! defined $elt)
3426 { delete $t->{twig_id_list}->{$id} }
3427 }
3428 }
3429  
3430 return $t;
3431 }
3432  
3433 # flushes up to an element
3434 # this method just reorders the arguments and calls flush
3435 sub flush_up_to
3436 { my $t= shift;
3437 my $up_to= shift;
3438 if( isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar'))
3439 { my $fh= shift;
3440 $t->flush( $fh, $up_to, @_);
3441 }
3442 else
3443 { $t->flush( $up_to, @_); }
3444  
3445 return $t;
3446 }
3447  
3448 # same as print except the entire document text is returned as a string
3449 sub sprint
3450 { my $t= shift;
3451 my %args= _normalize_args( @_);
3452  
3453 my $old_pretty;
3454 if( defined $args{PrettyPrint})
3455 { $old_pretty= $t->set_pretty_print( $args{PrettyPrint});
3456 delete $args{PrettyPrint};
3457 }
3458  
3459 my $old_empty_tag_style;
3460 if( defined $args{EmptyTags})
3461 { $old_empty_tag_style= $t->set_empty_tag_style( $args{EmptyTags});
3462 delete $args{EmptyTags};
3463 }
3464  
3465 my $string= $t->prolog( %args) # xml declaration and doctype
3466 . $t->_leading_cpi( %args) # leading comments and pi's in 'process' mode
3467 . ( ($t->{twig_root} && $t->{twig_root}->sprint) || '')
3468 . $t->_trailing_cpi # trailing comments and pi's (elements, in 'process' mode)
3469 . $t->_trailing_cpi_text # trailing comments and pi's (in 'keep' mode)
3470 ;
3471 if( $t->{twig_keep_spaces} && $t->{trailing_spaces}) { $string .= $t->{trailing_spaces}; }
3472  
3473 $t->set_pretty_print( $old_pretty) if( defined $old_pretty);
3474 $t->set_empty_tag_style( $old_empty_tag_style) if( defined $old_empty_tag_style);
3475  
3476 return $string;
3477 }
3478  
3479 # this method discards useless elements in a tree
3480 # it does the same thing as a flush except it does not print it
3481 # the second argument is an element, the last purged element
3482 # (this argument is usually set through the purge_up_to method)
3483 sub purge
3484 { my $t= shift;
3485 my $up_to= shift;
3486  
3487 $t->_trigger_tdh if $t->{twig_tdh};
3488  
3489 # the "real" last element processed, as _twig_end has closed it
3490 my $last_elt;
3491 if( $up_to)
3492 { $last_elt= $up_to; }
3493 elsif( $t->{twig_current})
3494 { $last_elt= $t->{twig_current}->{last_child}; }
3495 else
3496 { $last_elt= $t->{twig_root}; }
3497  
3498 my $elt= $t->{twig_root};
3499  
3500 while( $elt)
3501 { my $next_elt;
3502 if( $last_elt && $last_elt->in( $elt))
3503 { $elt->{'flushed'}=1;
3504 $next_elt= $elt->{first_child};
3505 }
3506 else
3507 { # an element before the last one or the last one,
3508 $next_elt= $elt->{next_sibling};
3509 $elt->delete;
3510 last if( $last_elt && ($elt == $last_elt) );
3511 }
3512 $elt= $next_elt;
3513 }
3514  
3515 if( my $ids= $t->{twig_id_list})
3516 { while( my ($id, $elt)= each %$ids) { if( ! defined $elt) { delete $t->{twig_id_list}->{$id} } } }
3517  
3518 return $t;
3519 }
3520  
3521 # flushes up to an element. This method just calls purge
3522 sub purge_up_to
3523 { my $t= shift;
3524 return $t->purge( @_);
3525 }
3526  
3527 sub root
3528 { return $_[0]->{twig_root}; }
3529  
3530 sub normalize
3531 { return $_[0]->root->normalize; }
3532  
3533 # create accessor methods on attribute names
3534 { my %accessor; # memorize accessor names so re-creating them won't trigger an error
3535 sub att_accessors
3536 {
3537 my $twig_or_class= shift;
3538 my $elt_class= ref $twig_or_class ? $twig_or_class->{twig_elt_class}
3539 : 'XML::Twig::Elt'
3540 ;
3541 ## no critic (TestingAndDebugging::ProhibitNoStrict);
3542 no strict 'refs';
3543 foreach my $att (@_)
3544 { _croak( "attempt to redefine existing method $att using att_accessors")
3545 if( $elt_class->can( $att) && !$accessor{$att});
3546  
3547 if( !$accessor{$att})
3548 { *{"$elt_class\::$att"}=
3549 sub :lvalue
3550 { my $elt= shift;
3551 if( @_) { $elt->{att}->{$att}= $_[0]; }
3552 $elt->{att}->{$att};
3553 };
3554 $accessor{$att}=1;
3555 }
3556 }
3557 return $twig_or_class;
3558 }
3559 }
3560  
3561 { my %accessor; # memorize accessor names so re-creating them won't trigger an error
3562 sub elt_accessors
3563 {
3564 my $twig_or_class= shift;
3565 my $elt_class= ref $twig_or_class ? $twig_or_class->{twig_elt_class}
3566 : 'XML::Twig::Elt'
3567 ;
3568  
3569 # if arg is a hash ref, it's exp => name, otherwise it's a list of tags
3570 my %exp_to_alias= ref( $_[0]) && isa( $_[0], 'HASH') ? %{$_[0]}
3571 : map { $_ => $_ } @_;
3572 ## no critic (TestingAndDebugging::ProhibitNoStrict);
3573 no strict 'refs';
3574 while( my( $alias, $exp)= each %exp_to_alias )
3575 { if( $elt_class->can( $alias) && !$accessor{$alias})
3576 { _croak( "attempt to redefine existing method $alias using elt_accessors"); }
3577  
3578 if( !$accessor{$alias})
3579 { *{"$elt_class\::$alias"}=
3580 sub
3581 { my $elt= shift;
3582 return wantarray ? $elt->children( $exp) : $elt->first_child( $exp);
3583 };
3584 $accessor{$alias}=1;
3585 }
3586 }
3587 return $twig_or_class;
3588 }
3589 }
3590  
3591 { my %accessor; # memorize accessor names so re-creating them won't trigger an error
3592 sub field_accessors
3593 {
3594 my $twig_or_class= shift;
3595 my $elt_class= ref $twig_or_class ? $twig_or_class->{twig_elt_class}
3596 : 'XML::Twig::Elt'
3597 ;
3598 my %exp_to_alias= ref( $_[0]) && isa( $_[0], 'HASH') ? %{$_[0]}
3599 : map { $_ => $_ } @_;
3600  
3601 ## no critic (TestingAndDebugging::ProhibitNoStrict);
3602 no strict 'refs';
3603 while( my( $alias, $exp)= each %exp_to_alias )
3604 { if( $elt_class->can( $alias) && !$accessor{$alias})
3605 { _croak( "attempt to redefine existing method $exp using field_accessors"); }
3606 if( !$accessor{$alias})
3607 { *{"$elt_class\::$alias"}=
3608 sub
3609 { my $elt= shift;
3610 $elt->field( $exp)
3611 };
3612 $accessor{$alias}=1;
3613 }
3614 }
3615 return $twig_or_class;
3616 }
3617 }
3618  
3619 sub first_elt
3620 { my( $t, $cond)= @_;
3621 my $root= $t->root || return undef;
3622 return $root if( $root->passes( $cond));
3623 return $root->next_elt( $cond);
3624 }
3625  
3626 sub last_elt
3627 { my( $t, $cond)= @_;
3628 my $root= $t->root || return undef;
3629 return $root->last_descendant( $cond);
3630 }
3631  
3632 sub next_n_elt
3633 { my( $t, $offset, $cond)= @_;
3634 $offset -- if( $t->root->matches( $cond) );
3635 return $t->root->next_n_elt( $offset, $cond);
3636 }
3637  
3638 sub get_xpath
3639 { my $twig= shift;
3640 if( isa( $_[0], 'ARRAY'))
3641 { my $elt_array= shift;
3642 return _unique_elts( map { $_->get_xpath( @_) } @$elt_array);
3643 }
3644 else
3645 { return $twig->root->get_xpath( @_); }
3646 }
3647  
3648 # get a list of elts and return a sorted list of unique elts
3649 sub _unique_elts
3650 { my @sorted= sort { $a ->cmp( $b) } @_;
3651 my @unique;
3652 while( my $current= shift @sorted)
3653 { push @unique, $current unless( @unique && ($unique[-1] == $current)); }
3654 return @unique;
3655 }
3656  
3657 sub findvalue
3658 { my $twig= shift;
3659 if( isa( $_[0], 'ARRAY'))
3660 { my $elt_array= shift;
3661 return join( '', map { $_->findvalue( @_) } @$elt_array);
3662 }
3663 else
3664 { return $twig->root->findvalue( @_); }
3665 }
3666  
3667 sub findvalues
3668 { my $twig= shift;
3669 if( isa( $_[0], 'ARRAY'))
3670 { my $elt_array= shift;
3671 return map { $_->findvalues( @_) } @$elt_array;
3672 }
3673 else
3674 { return $twig->root->findvalues( @_); }
3675 }
3676  
3677 sub set_id_seed
3678 { my $t= shift;
3679 XML::Twig::Elt->set_id_seed( @_);
3680 return $t;
3681 }
3682  
3683 # return an array ref to an index, or undef
3684 sub index
3685 { my( $twig, $name, $index)= @_;
3686 return defined( $index) ? $twig->{_twig_index}->{$name}->[$index] : $twig->{_twig_index}->{$name};
3687 }
3688  
3689 # return a list with just the root
3690 # if a condition is given then return an empty list unless the root matches
3691 sub children
3692 { my( $t, $cond)= @_;
3693 my $root= $t->root;
3694 unless( $cond && !($root->passes( $cond)) )
3695 { return ($root); }
3696 else
3697 { return (); }
3698 }
3699  
3700 sub _children { return ($_[0]->root); }
3701  
3702 # weird, but here for completude
3703 # used to solve (non-sensical) /doc[1] XPath queries
3704 sub child
3705 { my $t= shift;
3706 my $nb= shift;
3707 return ($t->children( @_))[$nb];
3708 }
3709  
3710 sub descendants
3711 { my( $t, $cond)= @_;
3712 my $root= $t->root;
3713 if( $root->passes( $cond) )
3714 { return ($root, $root->descendants( $cond)); }
3715 else
3716 { return ( $root->descendants( $cond)); }
3717 }
3718  
3719 sub simplify { my $t= shift; $t->root->simplify( @_); }
3720 sub subs_text { my $t= shift; $t->root->subs_text( @_); }
3721 sub trim { my $t= shift; $t->root->trim( @_); $t->root->trim; return $t; }
3722  
3723 sub set_keep_encoding
3724 { my( $t, $keep)= @_;
3725 $t->{twig_keep_encoding}= $keep;
3726 $t->{NoExpand}= $keep;
3727 return XML::Twig::Elt::set_keep_encoding( $keep);
3728 }
3729  
3730 sub set_expand_external_entities
3731 { return XML::Twig::Elt::set_expand_external_entities( @_); }
3732  
3733 sub escape_gt
3734 { my $t= shift; $t->{twig_escape_gt}= 1; return XML::Twig::Elt::escape_gt( @_); }
3735  
3736 sub do_not_escape_gt
3737 { my $t= shift; $t->{twig_escape_gt}= 0; return XML::Twig::Elt::do_not_escape_gt( @_); }
3738  
3739 sub elt_id
3740 { return $_[0]->{twig_id_list}->{$_[1]}; }
3741  
3742 # add a gi to the gi table, returns its index
3743 # if the gi already exists, just return it's index
3744 sub _add_gi
3745 { my( $gi )= @_;
3746 if ( ! exists $XML::Twig::gi2index{$gi} )
3747 { push @XML::Twig::index2gi, $gi;
3748 $XML::Twig::gi2index{$gi}= $#XML::Twig::index2gi;
3749 }
3750 return $XML::Twig::gi2index{$gi};
3751 }
3752  
3753 # change it in ALL twigs at the moment
3754 sub change_gi
3755 { my( $twig, $old_gi, $new_gi)= @_;
3756 my $index;
3757 return unless($index= $XML::Twig::gi2index{$old_gi});
3758 $XML::Twig::index2gi[$index]= $new_gi;
3759 delete $XML::Twig::gi2index{$old_gi};
3760 $XML::Twig::gi2index{$new_gi}= $index;
3761 return $twig;
3762 }
3763  
3764 # builds the DTD from the stored (possibly updated) data
3765 sub dtd_text
3766 { my $t= shift;
3767 my $dtd= $t->{twig_dtd};
3768 my $doctype= $t->{twig_doctype} or return '';
3769 my $string= "<!DOCTYPE ".$doctype->{name};
3770  
3771 $string .= " [\n";
3772  
3773 foreach my $gi (@{$dtd->{elt_list}})
3774 { $string.= "<!ELEMENT $gi ".$dtd->{model}->{$gi}.">\n" ;
3775 if( $dtd->{att}->{$gi})
3776 { my $attlist= $dtd->{att}->{$gi};
3777 $string.= "<!ATTLIST $gi\n";
3778 foreach my $att ( sort keys %{$attlist})
3779 {
3780 if( $attlist->{$att}->{fixed})
3781 { $string.= " $att $attlist->{$att}->{type} #FIXED $attlist->{$att}->{default}"; }
3782 else
3783 { $string.= " $att $attlist->{$att}->{type} $attlist->{$att}->{default}"; }
3784 $string.= "\n";
3785 }
3786 $string.= ">\n";
3787 }
3788 }
3789 $string.= $t->entity_list->text if( $t->entity_list);
3790 $string.= "\n]>\n";
3791 return $string;
3792 }
3793  
3794 # prints the DTD from the stored (possibly updated) data
3795 sub dtd_print
3796 { my $t= shift;
3797 my $fh= isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar') ? shift : undef;
3798 if( $fh) { print $fh $t->dtd_text; }
3799 else { print $t->dtd_text; }
3800 return $t;
3801 }
3802  
3803 # build the subs that call directly expat
3804 BEGIN
3805 { my @expat_methods= qw( depth in_element within_element context
3806 current_line current_column current_byte
3807 recognized_string original_string
3808 xpcroak xpcarp
3809 base current_element element_index
3810 xml_escape
3811 position_in_context);
3812 foreach my $method (@expat_methods)
3813 {
3814 ## no critic (TestingAndDebugging::ProhibitNoStrict);
3815 no strict 'refs';
3816 *{$method}= sub { my $t= shift;
3817 _croak( "calling $method after parsing is finished") unless( $t->{twig_parsing});
3818 return $t->{twig_parser}->$method(@_);
3819 };
3820 }
3821 }
3822  
3823 sub path
3824 { my( $t, $gi)= @_;
3825 if( $t->{twig_map_xmlns})
3826 { return "/" . join( "/", map { $t->_replace_prefix( $_)} ($t->{twig_parser}->context, $gi)); }
3827 else
3828 { return "/" . join( "/", ($t->{twig_parser}->context, $gi)); }
3829 }
3830  
3831 sub finish
3832 { my $t= shift;
3833 return $t->{twig_parser}->finish;
3834 }
3835  
3836 # just finish the parse by printing the rest of the document
3837 sub finish_print
3838 { my( $t, $fh)= @_;
3839 my $old_fh;
3840 unless( defined $fh)
3841 { $t->_set_fh_to_twig_output_fh(); }
3842 elsif( defined $fh)
3843 { $old_fh= select $fh;
3844 $t->{twig_original_selected_fh}= $old_fh if( $old_fh);
3845 }
3846  
3847 my $p=$t->{twig_parser};
3848 if( $t->{twig_keep_encoding})
3849 { $p->setHandlers( %twig_handlers_finish_print); }
3850 else
3851 { $p->setHandlers( %twig_handlers_finish_print_original); }
3852 return $t;
3853 }
3854  
3855 sub set_remove_cdata { return XML::Twig::Elt::set_remove_cdata( @_); }
3856  
3857 sub output_filter { return XML::Twig::Elt::output_filter( @_); }
3858 sub set_output_filter { return XML::Twig::Elt::set_output_filter( @_); }
3859  
3860 sub output_text_filter { return XML::Twig::Elt::output_text_filter( @_); }
3861 sub set_output_text_filter { return XML::Twig::Elt::set_output_text_filter( @_); }
3862  
3863 sub set_input_filter
3864 { my( $t, $input_filter)= @_;
3865 my $old_filter= $t->{twig_input_filter};
3866 if( !$input_filter || isa( $input_filter, 'CODE') )
3867 { $t->{twig_input_filter}= $input_filter; }
3868 elsif( $input_filter eq 'latin1')
3869 { $t->{twig_input_filter}= latin1(); }
3870 elsif( $filter{$input_filter})
3871 { $t->{twig_input_filter}= $filter{$input_filter}; }
3872 else
3873 { _croak( "invalid input filter: $input_filter"); }
3874  
3875 return $old_filter;
3876 }
3877  
3878 sub set_empty_tag_style
3879 { return XML::Twig::Elt::set_empty_tag_style( @_); }
3880  
3881 sub set_pretty_print
3882 { return XML::Twig::Elt::set_pretty_print( @_); }
3883  
3884 sub set_quote
3885 { return XML::Twig::Elt::set_quote( @_); }
3886  
3887 sub set_indent
3888 { return XML::Twig::Elt::set_indent( @_); }
3889  
3890 sub set_keep_atts_order
3891 { shift; return XML::Twig::Elt::set_keep_atts_order( @_); }
3892  
3893 sub keep_atts_order
3894 { return XML::Twig::Elt::keep_atts_order( @_); }
3895  
3896 sub set_do_not_escape_amp_in_atts
3897 { return XML::Twig::Elt::set_do_not_escape_amp_in_atts( @_); }
3898  
3899 # save and restore package globals (the ones in XML::Twig::Elt)
3900 # should probably return the XML::Twig object itself, but instead
3901 # returns the state (as a hashref) for backward compatibility
3902 sub save_global_state
3903 { my $t= shift;
3904 return $t->{twig_saved_state}= XML::Twig::Elt::global_state();
3905 }
3906  
3907 sub restore_global_state
3908 { my $t= shift;
3909 XML::Twig::Elt::set_global_state( $t->{twig_saved_state});
3910 }
3911  
3912 sub global_state
3913 { return XML::Twig::Elt::global_state(); }
3914  
3915 sub set_global_state
3916 { return XML::Twig::Elt::set_global_state( $_[1]); }
3917  
3918 sub dispose
3919 { my $t= shift;
3920 $t->DESTROY;
3921 return;
3922 }
3923  
3924 sub DESTROY
3925 { my $t= shift;
3926 if( $t->{twig_root} && isa( $t->{twig_root}, 'XML::Twig::Elt'))
3927 { $t->{twig_root}->delete }
3928  
3929 # added to break circular references
3930 undef $t->{twig};
3931 undef $t->{twig_root}->{twig} if( $t->{twig_root});
3932 undef $t->{twig_parser};
3933  
3934 undef %$t;# prevents memory leaks (especially when using mod_perl)
3935 undef $t;
3936 }
3937  
3938 # return true if perl was compiled using perlio
3939 # if perl is not available return true, these days perlio should be used
3940 sub _use_perlio
3941 { return $Config{useperlio} eq 'define'; }
3942  
3943  
3944 # returns the parth to the perl executable (if available)
3945 sub _this_perl
3946 { # straight from perlvar
3947 my $secure_perl_path= $Config{perlpath};
3948 if ($^O ne 'VMS')
3949 { $secure_perl_path .= $Config{_exe} unless $secure_perl_path =~ m/$Config{_exe}$/i; }
3950 if( ! -f $secure_perl_path) { $secure_perl_path= ''; } # when perl is not available (PDK)
3951 return $secure_perl_path;
3952 }
3953  
3954 #
3955 # non standard handlers
3956 #
3957  
3958 # kludge: expat 1.95.2 calls both Default AND Doctype handlers
3959 # so if the default handler finds '<!DOCTYPE' then it must
3960 # unset itself (_twig_print_doctype will reset it)
3961 sub _twig_print_check_doctype
3962 { # warn " in _twig_print_check_doctype...\n"; # DEBUG handler
3963  
3964 my $p= shift;
3965 my $string= $p->recognized_string();
3966 if( $string eq '<!DOCTYPE')
3967 {
3968 $p->setHandlers( Default => undef);
3969 $p->setHandlers( Entity => undef);
3970 $expat_1_95_2=1;
3971 }
3972 else
3973 { print $string; }
3974  
3975 return;
3976 }
3977  
3978 sub _twig_print
3979 { # warn " in _twig_print...\n"; # DEBUG handler
3980 my $p= shift;
3981 if( $expat_1_95_2 && ($p->recognized_string eq '[') && !$p->{twig}->{expat_1_95_2_seen_bracket})
3982 { # otherwise the opening square bracket of the doctype gets printed twice
3983 $p->{twig}->{expat_1_95_2_seen_bracket}=1;
3984 }
3985 else
3986 { if( $p->{twig}->{twig_right_after_root})
3987 { my $s= $p->recognized_string(); print $s if $s=~ m{\S}; }
3988 else
3989 { print $p->recognized_string(); }
3990 }
3991 return;
3992 }
3993 # recognized_string does not seem to work for entities, go figure!
3994 # so this handler is used to print them anyway
3995 sub _twig_print_entity
3996 { # warn " in _twig_print_entity...\n"; # DEBUG handler
3997 my $p= shift;
3998 XML::Twig::Entity->new( @_)->print;
3999 }
4000  
4001 # kludge: expat 1.95.2 calls both Default AND Doctype handlers
4002 # so if the default handler finds '<!DOCTYPE' then it must
4003 # unset itself (_twig_print_doctype will reset it)
4004 sub _twig_print_original_check_doctype
4005 { # warn " in _twig_print_original_check_doctype...\n"; # DEBUG handler
4006  
4007 my $p= shift;
4008 my $string= $p->original_string();
4009 if( $string eq '<!DOCTYPE')
4010 { $p->setHandlers( Default => undef);
4011 $p->setHandlers( Entity => undef);
4012 $expat_1_95_2=1;
4013 }
4014 else
4015 { print $string; }
4016  
4017 return;
4018 }
4019  
4020 sub _twig_print_original
4021 { # warn " in _twig_print_original...\n"; # DEBUG handler
4022 my $p= shift;
4023 print $p->original_string();
4024 return;
4025 }
4026  
4027 sub _twig_print_original_doctype
4028 { # warn " in _twig_print_original_doctype...\n"; # DEBUG handler
4029 my( $p, $name, $sysid, $pubid, $internal)= @_;
4030 _print_doctype(@_);
4031 $p->setHandlers( Default => \&_twig_print_original);
4032 return;
4033 }
4034  
4035 sub _twig_print_doctype
4036 { # warn " in _twig_print_doctype...\n"; # DEBUG handler
4037 my( $p, $name, $sysid, $pubid, $internal)= @_;
4038 _print_doctype(@_);
4039 $p->setHandlers( Default => \&_twig_print);
4040 return;
4041 }
4042  
4043 sub _print_doctype
4044 { my( $p, $name, $sysid, $pubid, $internal)= @_;
4045 if( $name)
4046 { # with recent versions of XML::Parser original_string does not work,
4047 # hence we need to rebuild the doctype declaration
4048 my $doctype='';
4049 $doctype .= qq{<!DOCTYPE $name} if( $name);
4050 $doctype .= qq{ PUBLIC "$pubid"} if( $pubid);
4051 $doctype .= qq{ SYSTEM} if( $sysid && !$pubid);
4052 $doctype .= qq{ "$sysid"} if( $sysid);
4053 $doctype .= ' [' if( $internal) ;
4054 $doctype .= qq{>} unless( $internal || $expat_1_95_2);
4055 $p->{twig}->{twig_doctype}->{has_internal}=$internal;
4056 print $doctype;
4057 }
4058 return;
4059 }
4060  
4061 sub _twig_print_original_default
4062 { # warn " in _twig_print_original_default...\n"; # DEBUG handler
4063 my $p= shift;
4064 print $p->original_string();
4065 return;
4066 }
4067  
4068 # account for the case where the element is empty
4069 sub _twig_print_end_original
4070 { # warn " in _twig_print_end_original...\n"; # DEBUG handler
4071 my $p= shift;
4072 print $p->original_string();
4073 return;
4074 }
4075  
4076 sub _twig_start_check_roots
4077 { # warn " in _twig_start_check_roots...\n"; # DEBUG handler
4078 my $p= shift;
4079 my $gi= shift;
4080  
4081 my $t= $p->{twig};
4082  
4083 my $fh= $t->{twig_output_fh} || select() || \*STDOUT;
4084  
4085 my $ns_decl;
4086 unless( $p->depth == 0)
4087 { if( $t->{twig_map_xmlns}) { $ns_decl= _replace_ns( $t, \$gi, \@_); }
4088 }
4089  
4090 my $context= { $ST_TAG => $gi, @_};
4091 $context->{$ST_NS}= $ns_decl if $ns_decl;
4092 push @{$t->{_twig_context_stack}}, $context;
4093 my %att= @_;
4094  
4095 if( _handler( $t, $t->{twig_roots}, $gi))
4096 { $p->setHandlers( %twig_handlers); # restore regular handlers
4097 $t->{twig_root_depth}= $p->depth;
4098 pop @{$t->{_twig_context_stack}}; # will be pushed back in _twig_start
4099 _twig_start( $p, $gi, @_);
4100 return;
4101 }
4102  
4103 # $tag will always be true if it needs to be printed (the tag string is never empty)
4104 my $tag= $t->{twig_default_print} ? $t->{twig_keep_encoding} ? $p->original_string
4105 : $p->recognized_string
4106 : '';
4107  
4108 if( $p->depth == 0)
4109 {
4110 ## no critic (TestingAndDebugging::ProhibitNoStrict);
4111 no strict 'refs';
4112 print {$fh} $tag if( $tag);
4113 pop @{$t->{_twig_context_stack}}; # will be pushed back in _twig_start
4114 _twig_start( $p, $gi, @_);
4115 $t->root->{'flushed'}=1; # or the root start tag gets output the first time we flush
4116 }
4117 elsif( $t->{twig_starttag_handlers})
4118 { # look for start tag handlers
4119  
4120 my @handlers= _handler( $t, $t->{twig_starttag_handlers}, $gi);
4121 my $last_handler_res;
4122 foreach my $handler ( @handlers)
4123 { $last_handler_res= $handler->($t, $gi, %att);
4124 last unless $last_handler_res;
4125 }
4126 ## no critic (TestingAndDebugging::ProhibitNoStrict);
4127 no strict 'refs';
4128 print {$fh} $tag if( $tag && (!@handlers || $last_handler_res));
4129 }
4130 else
4131 {
4132 ## no critic (TestingAndDebugging::ProhibitNoStrict);
4133 no strict 'refs';
4134 print {$fh} $tag if( $tag);
4135 }
4136 return;
4137 }
4138  
4139 sub _twig_end_check_roots
4140 { # warn " in _twig_end_check_roots...\n"; # DEBUG handler
4141  
4142 my( $p, $gi, %att)= @_;
4143 my $t= $p->{twig};
4144 # $tag can be empty (<elt/>), hence the undef and the tests for defined
4145 my $tag= $t->{twig_default_print} ? $t->{twig_keep_encoding} ? $p->original_string
4146 : $p->recognized_string
4147 : undef;
4148 my $fh= $t->{twig_output_fh} || select() || \*STDOUT;
4149  
4150 if( $t->{twig_endtag_handlers})
4151 { # look for end tag handlers
4152 my @handlers= _handler( $t, $t->{twig_endtag_handlers}, $gi);
4153 my $last_handler_res=1;
4154 foreach my $handler ( @handlers)
4155 { $last_handler_res= $handler->($t, $gi) || last; }
4156 }
4157 {
4158 ## no critic (TestingAndDebugging::ProhibitNoStrict);
4159 no strict 'refs';
4160 print {$fh} $tag if( defined $tag);
4161 }
4162 if( $p->depth == 0)
4163 {
4164 _twig_end( $p, $gi);
4165 $t->root->{end_tag_flushed}=1;
4166 }
4167  
4168 pop @{$t->{_twig_context_stack}};
4169 return;
4170 }
4171  
4172 sub _twig_pi_check_roots
4173 { # warn " in _twig_pi_check_roots...\n"; # DEBUG handler
4174 my( $p, $target, $data)= @_;
4175 my $t= $p->{twig};
4176 my $pi= $t->{twig_default_print} ? $t->{twig_keep_encoding} ? $p->original_string
4177 : $p->recognized_string
4178 : undef;
4179 my $fh= $t->{twig_output_fh} || select() || \*STDOUT;
4180  
4181 if( my $handler= $t->{twig_handlers}->{pi_handlers}->{$target}
4182 || $t->{twig_handlers}->{pi_handlers}->{''}
4183 )
4184 { # if handler is called on pi, then it needs to be processed as a regular node
4185 my @flags= qw( twig_process_pi twig_keep_pi);
4186 my @save= @{$t}{@flags}; # save pi related flags
4187 @{$t}{@flags}= (1, 0); # override them, pi needs to be processed
4188 _twig_pi( @_); # call handler on the pi
4189 @{$t}{@flags}= @save;; # restore flag
4190 }
4191 else
4192 {
4193 ## no critic (TestingAndDebugging::ProhibitNoStrict);
4194 no strict 'refs';
4195 print {$fh} $pi if( defined( $pi));
4196 }
4197 return;
4198 }
4199  
4200 sub _output_ignored
4201 { my( $t, $p)= @_;
4202 my $action= $t->{twig_ignore_action};
4203  
4204 my $get_string= $t->{twig_keep_encoding} ? 'original_string' : 'recognized_string';
4205  
4206 if( $action eq 'print' ) { print $p->$get_string; }
4207 else
4208 { my $string_ref;
4209 if( $action eq 'string')
4210 { $string_ref= \$t->{twig_buffered_string}; }
4211 elsif( ref( $action) && ref( $action) eq 'SCALAR')
4212 { $string_ref= $action; }
4213 else
4214 { _croak( "wrong ignore action: $action"); }
4215  
4216 $$string_ref .= $p->$get_string;
4217 }
4218 }
4219  
4220 sub _twig_ignore_start
4221 { # warn " in _twig_ignore_start...\n"; # DEBUG handler
4222  
4223 my( $p, $gi)= @_;
4224 my $t= $p->{twig};
4225 $t->{twig_ignore_level}++;
4226 my $action= $t->{twig_ignore_action};
4227  
4228 $t->_output_ignored( $p) unless $action eq 'discard';
4229 return;
4230 }
4231  
4232 sub _twig_ignore_end
4233 { # warn " in _twig_ignore_end...\n"; # DEBUG handler
4234  
4235 my( $p, $gi)= @_;
4236 my $t= $p->{twig};
4237  
4238 my $action= $t->{twig_ignore_action};
4239 $t->_output_ignored( $p) unless $action eq 'discard';
4240  
4241 $t->{twig_ignore_level}--;
4242  
4243 if( ! $t->{twig_ignore_level})
4244 {
4245 $t->{twig_current} = $t->{twig_ignore_elt};
4246 $t->{twig_current}->{'twig_current'}=1;
4247  
4248 $t->{twig_ignore_elt}->cut; # there could possibly be a memory leak here (delete would avoid it,
4249 # but could also delete elements that should not be deleted)
4250  
4251 # restore the saved stack to the current level
4252 splice( @{$t->{_twig_context_stack}}, $p->depth+ 1 );
4253 #warn "stack: ", _dump_stack( $t->{_twig_context_stack}), "\n";
4254  
4255 $p->setHandlers( @{$t->{twig_saved_handlers}});
4256 # test for handlers
4257 if( $t->{twig_endtag_handlers})
4258 { # look for end tag handlers
4259 my @handlers= _handler( $t, $t->{twig_endtag_handlers}, $gi);
4260 my $last_handler_res=1;
4261 foreach my $handler ( @handlers)
4262 { $last_handler_res= $handler->($t, $gi) || last; }
4263 }
4264 pop @{$t->{_twig_context_stack}};
4265 };
4266 return;
4267 }
4268  
4269 #sub _dump_stack { my( $stack)= @_; return join( ":", map { $_->{$ST_TAG} } @$stack); }
4270  
4271 sub ignore
4272 { my( $t, $elt, $action)= @_;
4273 my $current= $t->{twig_current};
4274  
4275 if( ! ($elt && ref( $elt) && isa( $elt, 'XML::Twig::Elt'))) { $elt= $current; }
4276  
4277 #warn "ignore: current = ", $current->tag, ", elt = ", $elt->tag, ")\n";
4278  
4279 # we need the ($elt == $current->{last_child}) test because the current element is set to the
4280 # parent _before_ handlers are called (and I can't figure out how to fix this)
4281 unless( ($elt == $current) || ($current->{last_child} && ($elt == $current->{last_child})) || $current->in( $elt))
4282 { _croak( "element to be ignored must be ancestor of current element"); }
4283  
4284 $t->{twig_ignore_level}= $current == $elt ? 1 : $t->_level_in_stack( $current) - $t->_level_in_stack($elt) + 1;
4285 #warn "twig_ignore_level: $t->{twig_ignore_level} (current: ", $current->tag, ", elt: ", $elt->tag, ")\n";
4286 $t->{twig_ignore_elt} = $elt; # save it, so we can delete it later
4287  
4288 $action ||= 'discard';
4289 if( !($action eq 'print' || $action eq 'string' || ( ref( $action) && ref( $action) eq 'SCALAR')))
4290 { $action= 'discard'; }
4291  
4292 $t->{twig_ignore_action}= $action;
4293  
4294 my $p= $t->{twig_parser};
4295 my @saved_handlers= $p->setHandlers( %twig_handlers_ignore); # set handlers
4296  
4297 my $get_string= $t->{twig_keep_encoding} ? 'original_string' : 'recognized_string';
4298  
4299 my $default_handler;
4300  
4301 if( $action ne 'discard')
4302 { if( $action eq 'print')
4303 { $p->setHandlers( Default => sub { print $_[0]->$get_string; }); }
4304 else
4305 { my $string_ref;
4306 if( $action eq 'string')
4307 { if( ! exists $t->{twig_buffered_string}) { $t->{twig_buffered_string}=''; }
4308 $string_ref= \$t->{twig_buffered_string};
4309 }
4310 elsif( ref( $action) && ref( $action) eq 'SCALAR')
4311 { $string_ref= $action; }
4312  
4313 $p->setHandlers( Default => sub { $$string_ref .= $_[0]->$get_string; });
4314 }
4315 $t->_output_ignored( $p, $action);
4316 }
4317  
4318 $t->{twig_saved_handlers}= \@saved_handlers; # save current handlers
4319 }
4320  
4321 sub _level_in_stack
4322 { my( $t, $elt)= @_;
4323 my $level=1;
4324 foreach my $elt_in_stack ( @{$t->{_twig_context_stack}} )
4325 { if( $elt_in_stack->{$ST_ELT} && ($elt == $elt_in_stack->{$ST_ELT})) { return $level }
4326 $level++;
4327 }
4328 }
4329  
4330 # select $t->{twig_output_fh} and store the current selected fh
4331 sub _set_fh_to_twig_output_fh
4332 { my $t= shift;
4333 my $output_fh= $t->{twig_output_fh};
4334 if( $output_fh && !$t->{twig_output_fh_selected})
4335 { # there is an output fh
4336 $t->{twig_selected_fh}= select(); # store the currently selected fh
4337 $t->{twig_output_fh_selected}=1;
4338 select $output_fh; # select the output fh for the twig
4339 }
4340 }
4341  
4342 # select the fh that was stored in $t->{twig_selected_fh}
4343 # (before $t->{twig_output_fh} was selected)
4344 sub _set_fh_to_selected_fh
4345 { my $t= shift;
4346 return unless( $t->{twig_output_fh});
4347 my $selected_fh= $t->{twig_selected_fh};
4348 $t->{twig_output_fh_selected}=0;
4349 select $selected_fh;
4350 return;
4351 }
4352  
4353 sub encoding
4354 { return $_[0]->{twig_xmldecl}->{encoding} if( $_[0]->{twig_xmldecl}); }
4355  
4356 sub set_encoding
4357 { my( $t, $encoding)= @_;
4358 $t->{twig_xmldecl} ||={};
4359 $t->set_xml_version( "1.0") unless( $t->xml_version);
4360 $t->{twig_xmldecl}->{encoding}= $encoding;
4361 return $t;
4362 }
4363  
4364 sub output_encoding
4365 { return $_[0]->{output_encoding}; }
4366  
4367 sub set_output_encoding
4368 { my( $t, $encoding)= @_;
4369 my $output_filter= $t->output_filter || '';
4370  
4371 if( ($encoding && $encoding !~ m{^utf-?8$}i) || $t->{twig_keep_encoding} || $output_filter)
4372 { $t->set_output_filter( _encoding_filter( $encoding || '')); }
4373  
4374 $t->{output_encoding}= $encoding;
4375 return $t;
4376 }
4377  
4378 sub xml_version
4379 { return $_[0]->{twig_xmldecl}->{version} if( $_[0]->{twig_xmldecl}); }
4380  
4381 sub set_xml_version
4382 { my( $t, $version)= @_;
4383 $t->{twig_xmldecl} ||={};
4384 $t->{twig_xmldecl}->{version}= $version;
4385 return $t;
4386 }
4387  
4388 sub standalone
4389 { return $_[0]->{twig_xmldecl}->{standalone} if( $_[0]->{twig_xmldecl}); }
4390  
4391 sub set_standalone
4392 { my( $t, $standalone)= @_;
4393 $t->{twig_xmldecl} ||={};
4394 $t->set_xml_version( "1.0") unless( $t->xml_version);
4395 $t->{twig_xmldecl}->{standalone}= $standalone;
4396 return $t;
4397 }
4398  
4399 # SAX methods
4400  
4401 sub toSAX1
4402 { _croak( "cannot use toSAX1 while parsing (use flush_toSAX1)") if (defined $_[0]->{twig_parser});
4403 shift(@_)->_toSAX(@_, \&XML::Twig::Elt::_start_tag_data_SAX1,
4404 \&XML::Twig::Elt::_end_tag_data_SAX1
4405 );
4406 }
4407  
4408 sub toSAX2
4409 { _croak( "cannot use toSAX2 while parsing (use flush_toSAX2)") if (defined $_[0]->{twig_parser});
4410 shift(@_)->_toSAX(@_, \&XML::Twig::Elt::_start_tag_data_SAX2,
4411 \&XML::Twig::Elt::_end_tag_data_SAX2
4412 );
4413 }
4414  
4415 sub _toSAX
4416 { my( $t, $handler, $start_tag_data, $end_tag_data) = @_;
4417  
4418 if( my $start_document = $handler->can( 'start_document'))
4419 { $start_document->( $handler); }
4420  
4421 $t->_prolog_toSAX( $handler);
4422  
4423 if( $t->root) { $t->root->_toSAX( $handler, $start_tag_data, $end_tag_data) ; }
4424 if( my $end_document = $handler->can( 'end_document'))
4425 { $end_document->( $handler); }
4426 }
4427  
4428 sub flush_toSAX1
4429 { shift(@_)->_flush_toSAX(@_, \&XML::Twig::Elt::_start_tag_data_SAX1,
4430 \&XML::Twig::Elt::_end_tag_data_SAX1
4431 );
4432 }
4433  
4434 sub flush_toSAX2
4435 { shift(@_)->_flush_toSAX(@_, \&XML::Twig::Elt::_start_tag_data_SAX2,
4436 \&XML::Twig::Elt::_end_tag_data_SAX2
4437 );
4438 }
4439  
4440 sub _flush_toSAX
4441 { my( $t, $handler, $start_tag_data, $end_tag_data)= @_;
4442  
4443 # the "real" last element processed, as _twig_end has closed it
4444 my $last_elt;
4445 if( $t->{twig_current})
4446 { $last_elt= $t->{twig_current}->{last_child}; }
4447 else
4448 { $last_elt= $t->{twig_root}; }
4449  
4450 my $elt= $t->{twig_root};
4451 unless( $elt->{'flushed'})
4452 { # init unless already done (ie root has been flushed)
4453 if( my $start_document = $handler->can( 'start_document'))
4454 { $start_document->( $handler); }
4455 # flush the DTD
4456 $t->_prolog_toSAX( $handler)
4457 }
4458  
4459 while( $elt)
4460 { my $next_elt;
4461 if( $last_elt && $last_elt->in( $elt))
4462 {
4463 unless( $elt->{'flushed'})
4464 { # just output the front tag
4465 if( my $start_element = $handler->can( 'start_element'))
4466 { if( my $tag_data= $start_tag_data->( $elt))
4467 { $start_element->( $handler, $tag_data); }
4468 }
4469 $elt->{'flushed'}=1;
4470 }
4471 $next_elt= $elt->{first_child};
4472 }
4473 else
4474 { # an element before the last one or the last one,
4475 $next_elt= $elt->{next_sibling};
4476 $elt->_toSAX( $handler, $start_tag_data, $end_tag_data);
4477 $elt->delete;
4478 last if( $last_elt && ($elt == $last_elt));
4479 }
4480 $elt= $next_elt;
4481 }
4482 if( !$t->{twig_parsing})
4483 { if( my $end_document = $handler->can( 'end_document'))
4484 { $end_document->( $handler); }
4485 }
4486 }
4487  
4488 sub _prolog_toSAX
4489 { my( $t, $handler)= @_;
4490 $t->_xmldecl_toSAX( $handler);
4491 $t->_DTD_toSAX( $handler);
4492 }
4493  
4494 sub _xmldecl_toSAX
4495 { my( $t, $handler)= @_;
4496 my $decl= $t->{twig_xmldecl};
4497 my $data= { Version => $decl->{version},
4498 Encoding => $decl->{encoding},
4499 Standalone => $decl->{standalone},
4500 };
4501 if( my $xml_decl= $handler->can( 'xml_decl'))
4502 { $xml_decl->( $handler, $data); }
4503 }
4504  
4505 sub _DTD_toSAX
4506 { my( $t, $handler)= @_;
4507 my $doctype= $t->{twig_doctype};
4508 return unless( $doctype);
4509 my $data= { Name => $doctype->{name},
4510 PublicId => $doctype->{pub},
4511 SystemId => $doctype->{sysid},
4512 };
4513  
4514 if( my $start_dtd= $handler->can( 'start_dtd'))
4515 { $start_dtd->( $handler, $data); }
4516  
4517 # I should call code to export the internal subset here
4518  
4519 if( my $end_dtd= $handler->can( 'end_dtd'))
4520 { $end_dtd->( $handler); }
4521 }
4522  
4523 # input/output filters
4524  
4525 sub latin1
4526 { local $SIG{__DIE__};
4527 if( _use( 'Encode'))
4528 { return encode_convert( 'ISO-8859-15'); }
4529 elsif( _use( 'Text::Iconv'))
4530 { return iconv_convert( 'ISO-8859-15'); }
4531 elsif( _use( 'Unicode::Map8') && _use( 'Unicode::String'))
4532 { return unicode_convert( 'ISO-8859-15'); }
4533 else
4534 { return \&regexp2latin1; }
4535 }
4536  
4537 sub _encoding_filter
4538 {
4539 { local $SIG{__DIE__};
4540 my $encoding= $_[1] || $_[0];
4541 if( _use( 'Encode'))
4542 { my $sub= encode_convert( $encoding);
4543 return $sub;
4544 }
4545 elsif( _use( 'Text::Iconv'))
4546 { return iconv_convert( $encoding); }
4547 elsif( _use( 'Unicode::Map8') && _use( 'Unicode::String'))
4548 { return unicode_convert( $encoding); }
4549 }
4550 _croak( "Encode, Text::Iconv or Unicode::Map8 and Unicode::String need to be installed in order to use encoding options");
4551 }
4552  
4553 # shamelessly lifted from XML::TyePYX (works only with XML::Parse 2.27)
4554 sub regexp2latin1
4555 { my $text=shift;
4556 $text=~s{([\xc0-\xc3])(.)}{ my $hi = ord($1);
4557 my $lo = ord($2);
4558 chr((($hi & 0x03) <<6) | ($lo & 0x3F))
4559 }ge;
4560 return $text;
4561 }
4562  
4563 sub html_encode
4564 { _use( 'HTML::Entities') or croak "cannot use html_encode: missing HTML::Entities";
4565 return HTML::Entities::encode_entities($_[0] );
4566 }
4567  
4568 sub safe_encode
4569 { my $str= shift;
4570 $str= encode( ascii => $str, $FB_HTMLCREF);
4571 return $str;
4572 }
4573  
4574 sub safe_encode_hex
4575 { my $str= shift;
4576 $str= encode( ascii => $str, $FB_XMLCREF);
4577 return $str;
4578 }
4579  
4580 # this one shamelessly lifted from XML::DOM
4581 sub _XmlUtf8Decode
4582 { my ($str, $hex) = @_;
4583 my $len = length ($str);
4584 my $n;
4585  
4586 if ($len == 2)
4587 { my @n = unpack "C2", $str;
4588 $n = (($n[0] & 0x3f) << 6) + ($n[1] & 0x3f);
4589 }
4590 elsif ($len == 3)
4591 { my @n = unpack "C3", $str;
4592 $n = (($n[0] & 0x1f) << 12) + (($n[1] & 0x3f) << 6) + ($n[2] & 0x3f);
4593 }
4594 elsif ($len == 4)
4595 { my @n = unpack "C4", $str;
4596 $n = (($n[0] & 0x0f) << 18) + (($n[1] & 0x3f) << 12)
4597 + (($n[2] & 0x3f) << 6) + ($n[3] & 0x3f);
4598 }
4599 elsif ($len == 1) # just to be complete...
4600 { $n = ord ($str); }
4601 else
4602 { croak "bad value [$str] for _XmlUtf8Decode"; }
4603  
4604 my $char= $hex ? sprintf ("&#x%x;", $n) : "&#$n;";
4605 return $char;
4606 }
4607  
4608 # deprecated, was used for unicode processing pre perl 5.8.0
4609 sub unicode_convert
4610 { my $enc= $_[1] ? $_[1] : $_[0]; # so the method can be called on the twig or directly
4611 _use( 'Unicode::Map8') or croak "Unicode::Map8 not available, needed for encoding filter: $!";
4612 _use( 'Unicode::String') or croak "Unicode::String not available, needed for encoding filter: $!";
4613 import Unicode::String qw(utf8);
4614 ## no critic (ProhibitStringyEval)
4615 my $sub= eval qq{ { $NO_WARNINGS;
4616 my \$cnv;
4617 BEGIN { \$cnv= Unicode::Map8->new(\$enc)
4618 or croak "Can't create converter to \$enc";
4619 }
4620 sub { return \$cnv->to8 (utf8(\$_[0])->ucs2); }
4621 }
4622 };
4623 unless( $sub) { croak $@; }
4624 return $sub;
4625 }
4626  
4627 sub iconv_convert
4628 { my $enc= $_[1] ? $_[1] : $_[0]; # so the method can be called on the twig or directly
4629 _use( 'Text::Iconv') or croak "Text::Iconv not available, needed for encoding filter: $!";
4630 ## no critic (ProhibitStringyEval)
4631 my $sub= eval qq{ { $NO_WARNINGS;
4632 my \$cnv;
4633 BEGIN { \$cnv = Text::Iconv->new( 'utf8', \$enc)
4634 or croak "Can't create iconv converter to \$enc";
4635 }
4636 sub { return \$cnv->convert( \$_[0]); }
4637 }
4638 };
4639 unless( $sub)
4640 { if( $@=~ m{^Unsupported conversion: Invalid argument})
4641 { croak "Unsupported encoding: $enc"; }
4642 else
4643 { croak $@; }
4644 }
4645  
4646 return $sub;
4647 }
4648  
4649 sub encode_convert
4650 { my $enc= $_[1] ? $_[1] : $_[0]; # so the method can be called on the twig or directly
4651 my $sub= eval qq{sub { $NO_WARNINGS; return encode( "$enc", \$_[0]); } }; ## no critic (ProhibitStringyEval)
4652 croak "can't create Encode-based filter: $@" unless( $sub);
4653 return $sub;
4654 }
4655  
4656 # XML::XPath compatibility
4657 sub getRootNode { return $_[0]; }
4658 sub getParentNode { return undef; }
4659 sub getChildNodes { my @children= ($_[0]->root); return wantarray ? @children : \@children; }
4660  
4661 sub _weakrefs { return $weakrefs; }
4662 sub _set_weakrefs { $weakrefs=shift() || 0; XML::Twig::Elt::set_destroy()if ! $weakrefs; } # for testing purposes
4663  
4664 sub _dump
4665 { my $t= shift;
4666 my $dump='';
4667  
4668 $dump="document\n"; # should dump twig level data here
4669 if( $t->root) { $dump .= $t->root->_dump( @_); }
4670  
4671 return $dump;
4672  
4673 }
4674  
4675 1;
4676  
4677 ######################################################################
4678 package XML::Twig::Entity_list;
4679 ######################################################################
4680  
4681 *isa= *UNIVERSAL::isa;
4682  
4683 sub new
4684 { my $class = shift;
4685 my $self={ entities => {}, updated => 0};
4686  
4687 bless $self, $class;
4688 return $self;
4689  
4690 }
4691  
4692 sub add_new_ent
4693 { my $ent_list= shift;
4694 my $ent= XML::Twig::Entity->new( @_);
4695 $ent_list->add( $ent);
4696 return $ent_list;
4697 }
4698  
4699 sub _add_list
4700 { my( $ent_list, $to_add)= @_;
4701 my $ents_to_add= $to_add->{entities};
4702 return $ent_list unless( $ents_to_add && %$ents_to_add);
4703 @{$ent_list->{entities}}{keys %$ents_to_add}= values %$ents_to_add;
4704 $ent_list->{updated}=1;
4705 return $ent_list;
4706 }
4707  
4708 sub add
4709 { my( $ent_list, $ent)= @_;
4710 $ent_list->{entities}->{$ent->{name}}= $ent;
4711 $ent_list->{updated}=1;
4712 return $ent_list;
4713 }
4714  
4715 sub ent
4716 { my( $ent_list, $ent_name)= @_;
4717 return $ent_list->{entities}->{$ent_name};
4718 }
4719  
4720 # can be called with an entity or with an entity name
4721 sub delete
4722 { my $ent_list= shift;
4723 if( isa( ref $_[0], 'XML::Twig::Entity'))
4724 { # the second arg is an entity
4725 my $ent= shift;
4726 delete $ent_list->{entities}->{$ent->{name}};
4727 }
4728 else
4729 { # the second arg was not entity, must be a string then
4730 my $name= shift;
4731 delete $ent_list->{entities}->{$name};
4732 }
4733 $ent_list->{updated}=1;
4734 return $ent_list;
4735 }
4736  
4737 sub print
4738 { my ($ent_list, $fh)= @_;
4739 my $old_select= defined $fh ? select $fh : undef;
4740  
4741 foreach my $ent_name ( sort keys %{$ent_list->{entities}})
4742 { my $ent= $ent_list->{entities}->{$ent_name};
4743 # we have to test what the entity is or un-defined entities can creep in
4744 if( isa( $ent, 'XML::Twig::Entity')) { $ent->print(); }
4745 }
4746 select $old_select if( defined $old_select);
4747 return $ent_list;
4748 }
4749  
4750 sub text
4751 { my ($ent_list)= @_;
4752 return join "\n", map { $ent_list->{entities}->{$_}->text} sort keys %{$ent_list->{entities}};
4753 }
4754  
4755 # return the list of entity names
4756 sub entity_names
4757 { my $ent_list= shift;
4758 return (sort keys %{$ent_list->{entities}}) ;
4759 }
4760  
4761 sub list
4762 { my ($ent_list)= @_;
4763 return map { $ent_list->{entities}->{$_} } sort keys %{$ent_list->{entities}};
4764 }
4765  
4766 1;
4767  
4768 ######################################################################
4769 package XML::Twig::Entity;
4770 ######################################################################
4771  
4772 sub new
4773 { my( $class, $name, $val, $sysid, $pubid, $ndata, $param)= @_;
4774 $class= ref( $class) || $class;
4775  
4776 my $self={};
4777  
4778 $self->{name} = $name;
4779 $self->{val} = $val if( defined $val );
4780 $self->{sysid} = $sysid if( defined $sysid);
4781 $self->{pubid} = $pubid if( defined $pubid);
4782 $self->{ndata} = $ndata if( defined $ndata);
4783 $self->{param} = $param if( defined $param);
4784  
4785 bless $self, $class;
4786 return $self;
4787 }
4788  
4789 sub name { return $_[0]->{name}; }
4790 sub val { return $_[0]->{val}; }
4791 sub sysid { return defined( $_[0]->{sysid}) ? $_[0]->{sysid} : ''; }
4792 sub pubid { return defined( $_[0]->{pubid}) ? $_[0]->{pubid} : ''; }
4793 sub ndata { return defined( $_[0]->{ndata}) ? $_[0]->{ndata} : ''; }
4794 sub param { return defined( $_[0]->{param}) ? $_[0]->{param} : ''; }
4795  
4796 sub print
4797 { my ($ent, $fh)= @_;
4798 my $text= $ent->text;
4799 if( $fh) { print $fh $text . "\n"; }
4800 else { print $text . "\n"; }
4801 }
4802  
4803 sub sprint
4804 { my ($ent)= @_;
4805 return $ent->text;
4806 }
4807  
4808 sub text
4809 { my ($ent)= @_;
4810 #warn "text called: '", $ent->_dump, "'\n";
4811 return '' if( !$ent->{name});
4812 my @tokens;
4813 push @tokens, '<!ENTITY';
4814  
4815 push @tokens, '%' if( $ent->{param});
4816 push @tokens, $ent->{name};
4817  
4818 if( defined $ent->{val} && !defined( $ent->{sysid}) && !defined($ent->{pubid}) )
4819 { push @tokens, _quoted_val( $ent->{val});
4820 }
4821 elsif( defined $ent->{sysid})
4822 { push @tokens, 'PUBLIC', _quoted_val( $ent->{pubid}) if( $ent->{pubid});
4823 push @tokens, 'SYSTEM' unless( $ent->{pubid});
4824 push @tokens, _quoted_val( $ent->{sysid});
4825 push @tokens, 'NDATA', $ent->{ndata} if( $ent->{ndata});
4826 }
4827 return join( ' ', @tokens) . '>';
4828 }
4829  
4830 sub _quoted_val
4831 { my $q= $_[0]=~ m{"} ? q{'} : q{"};
4832 return qq{$q$_[0]$q};
4833 }
4834  
4835 sub _dump
4836 { my( $ent)= @_; return join( " - ", map { "$_ => '$ent->{$_}'" } grep { defined $ent->{$_} } sort keys %$ent); }
4837  
4838 1;
4839  
4840 ######################################################################
4841 package XML::Twig::Notation_list;
4842 ######################################################################
4843  
4844 *isa= *UNIVERSAL::isa;
4845  
4846 sub new
4847 { my $class = shift;
4848 my $self={ notations => {}, updated => 0};
4849  
4850 bless $self, $class;
4851 return $self;
4852  
4853 }
4854  
4855 sub add_new_notation
4856 { my $notation_list= shift;
4857 my $notation= XML::Twig::Notation->new( @_);
4858 $notation_list->add( $notation);
4859 return $notation_list;
4860 }
4861  
4862 sub _add_list
4863 { my( $notation_list, $to_add)= @_;
4864 my $notations_to_add= $to_add->{notations};
4865 return $notation_list unless( $notations_to_add && %$notations_to_add);
4866 @{$notation_list->{notations}}{keys %$notations_to_add}= values %$notations_to_add;
4867 $notation_list->{updated}=1;
4868 return $notation_list;
4869 }
4870  
4871 sub add
4872 { my( $notation_list, $notation)= @_;
4873 $notation_list->{notations}->{$notation->{name}}= $notation;
4874 $notation_list->{updated}=1;
4875 return $notation_list;
4876 }
4877  
4878 sub notation
4879 { my( $notation_list, $notation_name)= @_;
4880 return $notation_list->{notations}->{$notation_name};
4881 }
4882  
4883 # can be called with a notation or with a notation name
4884 sub delete
4885 { my $notation_list= shift;
4886 if( isa( ref $_[0], 'XML::Twig::Notation'))
4887 { # the second arg is a notation
4888 my $notation= shift;
4889 delete $notation_list->{notations}->{$notation->{name}};
4890 }
4891 else
4892 { # the second arg was not a notation, must be a string then
4893 my $name= shift;
4894 delete $notation_list->{notations}->{$name};
4895 }
4896 $notation_list->{updated}=1;
4897 return $notation_list;
4898 }
4899  
4900 sub print
4901 { my ($notation_list, $fh)= @_;
4902 my $old_select= defined $fh ? select $fh : undef;
4903 print {$fh} $notation_list->sprint;
4904 select $old_select if( defined $old_select);
4905 return $notation_list;
4906 }
4907  
4908 sub sprint
4909 { my ($notation_list)= @_;
4910  
4911 my $notations='';
4912 foreach my $notation_name ( sort keys %{$notation_list->{notations}})
4913 { my $notation= $notation_list->{notations}->{$notation_name};
4914 # we have to test what the notation is or un-defined notations can creep in
4915 if( isa( $notation, 'XML::Twig::Notation')) { $notations .= $notation->text() . "\n"; }
4916 }
4917 return $notations;
4918 }
4919  
4920 sub text
4921 { my ($notation_list)= @_;
4922 return join "\n", map { $notation_list->{notations}->{$_}->text} sort keys %{$notation_list->{notations}};
4923 }
4924  
4925 # return the list of notation names
4926 sub notation_names
4927 { my $notation_list= shift;
4928 return (sort keys %{$notation_list->{notations}}) ;
4929 }
4930  
4931 sub list
4932 { my ($notation_list)= @_;
4933 return map { $notation_list->{notations}->{$_} } sort keys %{$notation_list->{notations}};
4934 }
4935  
4936 1;
4937  
4938 ######################################################################
4939 package XML::Twig::Notation;
4940 ######################################################################
4941  
4942 BEGIN
4943 { *sprint= *text;
4944 }
4945  
4946 sub new
4947 { my( $class, $name, $base, $sysid, $pubid)= @_;
4948 $class= ref( $class) || $class;
4949  
4950 my $self={};
4951  
4952 $self->{name} = $name;
4953 $self->{base} = $base if( defined $base );
4954 $self->{sysid} = $sysid if( defined $sysid);
4955 $self->{pubid} = $pubid if( defined $pubid);
4956  
4957 bless $self, $class;
4958 return $self;
4959 }
4960  
4961 sub name { return $_[0]->{name}; }
4962 sub base { return $_[0]->{base}; }
4963 sub sysid { return $_[0]->{sysid}; }
4964 sub pubid { return $_[0]->{pubid}; }
4965  
4966 sub print
4967 { my ($notation, $fh)= @_;
4968 my $text= $notation->text;
4969 if( $fh) { print $fh $text . "\n"; }
4970 else { print $text . "\n"; }
4971 }
4972  
4973 sub text
4974 { my ($notation)= @_;
4975 return '' if( !$notation->{name});
4976 my @tokens;
4977 push @tokens, '<!NOTATION';
4978 push @tokens, $notation->{name};
4979 push @tokens, ( 'PUBLIC', _quoted_val( $notation->{pubid} ) ) if $notation->{pubid};
4980 push @tokens, ( 'SYSTEM') if ! $notation->{pubid} && $notation->{sysid};
4981 push @tokens, (_quoted_val( $notation->{sysid}) ) if $notation->{sysid};
4982  
4983 return join( ' ', @tokens) . '>';
4984 }
4985  
4986 sub _quoted_val
4987 { my $q= $_[0]=~ m{"} ? q{'} : q{"};
4988 return qq{$q$_[0]$q};
4989 }
4990  
4991 sub _dump
4992 { my( $notation)= @_; return join( " - ", map { "$_ => '$notation->{$_}'" } grep { defined $notation->{$_} } sort keys %$notation); }
4993  
4994 1;
4995  
4996 ######################################################################
4997 package XML::Twig::Elt;
4998 ######################################################################
4999  
5000 use Carp;
5001 *isa= *UNIVERSAL::isa;
5002  
5003 my $CDATA_START = "<![CDATA[";
5004 my $CDATA_END = "]]>";
5005 my $PI_START = "<?";
5006 my $PI_END = "?>";
5007 my $COMMENT_START = "<!--";
5008 my $COMMENT_END = "-->";
5009  
5010 my $XMLNS_URI = 'http://www.w3.org/2000/xmlns/';
5011  
5012 my %POSITION_ALIAS = (
5013 beforebegin => 'before',
5014 afterbegin => 'first_child',
5015 beforeend => 'last_child',
5016 afterend => 'after',
5017 );
5018  
5019 my %OP_POSITION = reverse %POSITION_ALIAS;
5020  
5021 BEGIN
5022 { # set some aliases for methods
5023 *tag = *gi;
5024 *name = *gi;
5025 *set_tag = *set_gi;
5026 *set_name = *set_gi;
5027 *find_nodes = *get_xpath; # as in XML::DOM
5028 *findnodes = *get_xpath; # as in XML::LibXML
5029 *field = *first_child_text;
5030 *trimmed_field = *first_child_trimmed_text;
5031 *is_field = *contains_only_text;
5032 *is = *passes;
5033 *matches = *passes;
5034 *has_child = *first_child;
5035 *has_children = *first_child;
5036 *all_children_pass = *all_children_are;
5037 *all_children_match= *all_children_are;
5038 *getElementsByTagName= *descendants;
5039 *find_by_tag_name= *descendants_or_self;
5040 *unwrap = *erase;
5041 *inner_xml = *xml_string;
5042 *outer_xml = *sprint;
5043 *add_class = *add_to_class;
5044  
5045 *first_child_is = *first_child_matches;
5046 *last_child_is = *last_child_matches;
5047 *next_sibling_is = *next_sibling_matches;
5048 *prev_sibling_is = *prev_sibling_matches;
5049 *next_elt_is = *next_elt_matches;
5050 *prev_elt_is = *prev_elt_matches;
5051 *parent_is = *parent_matches;
5052 *child_is = *child_matches;
5053 *inherited_att = *inherit_att;
5054  
5055 *sort_children_by_value= *sort_children_on_value;
5056  
5057 *has_atts= *att_nb;
5058  
5059 # imports from XML::Twig
5060 *_is_fh= *XML::Twig::_is_fh;
5061  
5062 # XML::XPath compatibility
5063 *string_value = *text;
5064 *toString = *sprint;
5065 *getName = *gi;
5066 *getRootNode = *twig;
5067 *getNextSibling = *_next_sibling;
5068 *getPreviousSibling = *_prev_sibling;
5069 *isElementNode = *is_elt;
5070 *isTextNode = *is_text;
5071 *isPI = *is_pi;
5072 *isPINode = *is_pi;
5073 *isProcessingInstructionNode= *is_pi;
5074 *isComment = *is_comment;
5075 *isCommentNode = *is_comment;
5076 *getTarget = *target;
5077 *getFirstChild = *_first_child;
5078 *getLastChild = *_last_child;
5079  
5080 # try using weak references
5081 # test whether we can use weak references
5082 { local $SIG{__DIE__};
5083 ## no critic (ProhibitStringyEval)
5084 if( eval 'require Scalar::Util' && defined( &Scalar::Util::weaken) )
5085 { import Scalar::Util qw(weaken); }
5086 elsif( eval 'require WeakRef')
5087 { import WeakRef; }
5088 }
5089 }
5090  
5091 # can be called as XML::Twig::Elt->new( [[$gi, $atts, [@content]])
5092 # - gi is an optional gi given to the element
5093 # - $atts is a hashref to attributes for the element
5094 # - @content is an optional list of text and elements that will
5095 # be inserted under the element
5096 sub new
5097 { my $class= shift;
5098 $class= ref $class || $class;
5099 my $elt = {};
5100 bless ($elt, $class);
5101  
5102 return $elt unless @_;
5103  
5104 if( @_ == 1 && $_[0]=~ m{^\s*<}) { return $class->parse( @_); }
5105  
5106 # if a gi is passed then use it
5107 my $gi= shift;
5108 $elt->{gi}=$XML::Twig::gi2index{$gi} or $elt->set_gi( $gi);
5109  
5110 my $atts= ref $_[0] eq 'HASH' ? shift : undef;
5111  
5112 if( $atts && defined $atts->{$CDATA})
5113 { delete $atts->{$CDATA};
5114  
5115 my $cdata= $class->new( $CDATA => @_);
5116 return $class->new( $gi, $atts, $cdata);
5117 }
5118  
5119 if( $gi eq $PCDATA)
5120 { if( grep { ref $_ } @_) { croak "element $PCDATA can only be created from text"; }
5121 $elt->{pcdata}= join '', @_;
5122 }
5123 elsif( $gi eq $ENT)
5124 { $elt->{ent}= shift; }
5125 elsif( $gi eq $CDATA)
5126 { if( grep { ref $_ } @_) { croak "element $CDATA can only be created from text"; }
5127 $elt->{cdata}= join '', @_;
5128 }
5129 elsif( $gi eq $COMMENT)
5130 { if( grep { ref $_ } @_) { croak "element $COMMENT can only be created from text"; }
5131 $elt->{comment}= join '', @_;
5132 }
5133 elsif( $gi eq $PI)
5134 { if( grep { ref $_ } @_) { croak "element $PI can only be created from text"; }
5135 $elt->_set_pi( shift, join '', @_);
5136 }
5137 else
5138 { # the rest of the arguments are the content of the element
5139 if( @_)
5140 { $elt->set_content( @_); }
5141 else
5142 { $elt->{empty}= 1; }
5143 }
5144  
5145 if( $atts)
5146 { # the attribute hash can be used to pass the asis status
5147 if( defined $atts->{$ASIS}) { $elt->set_asis( $atts->{$ASIS} ); delete $atts->{$ASIS}; }
5148 if( defined $atts->{$EMPTY}) { $elt->{empty}= $atts->{$EMPTY}; delete $atts->{$EMPTY}; }
5149 if( keys %$atts) { $elt->set_atts( $atts); }
5150 $elt->_set_id( $atts->{$ID}) if( $atts->{$ID});
5151 }
5152  
5153 return $elt;
5154 }
5155  
5156 # optimized version of $elt->new( PCDATA, $text);
5157 sub _new_pcdata
5158 { my $class= $_[0];
5159 $class= ref $class || $class;
5160 my $elt = {};
5161 bless $elt, $class;
5162 $elt->{gi}=$XML::Twig::gi2index{$PCDATA} or $elt->set_gi( $PCDATA);
5163 $elt->{pcdata}= $_[1];
5164 return $elt;
5165 }
5166  
5167 # this function creates an XM:::Twig::Elt from a string
5168 # it is quite clumsy at the moment, as it just creates a
5169 # new twig then returns its root
5170 # there might also be memory leaks there
5171 # additional arguments are passed to new XML::Twig
5172 sub parse
5173 { my $class= shift;
5174 if( ref( $class)) { $class= ref( $class); }
5175 my $string= shift;
5176 my %args= @_;
5177 my $t= XML::Twig->new(%args);
5178 $t->parse( $string);
5179 my $elt= $t->root;
5180 # clean-up the node
5181 delete $elt->{twig}; # get rid of the twig data
5182 delete $elt->{twig_current}; # better get rid of this too
5183 if( $t->{twig_id_list}) { $elt->{twig_id_list}= $t->{twig_id_list}; }
5184 $elt->cut;
5185 undef $t->{twig_root};
5186 return $elt;
5187 }
5188  
5189 sub set_inner_xml
5190 { my( $elt, $xml, @args)= @_;
5191 my $new_elt= $elt->parse( "<dummy>$xml</dummy>", @args);
5192 $elt->cut_children;
5193 $new_elt->paste_first_child( $elt);
5194 $new_elt->erase;
5195 return $elt;
5196 }
5197  
5198 sub set_outer_xml
5199 { my( $elt, $xml, @args)= @_;
5200 my $new_elt= $elt->parse( "<dummy>$xml</dummy>", @args);
5201 $elt->cut_children;
5202 $new_elt->replace( $elt);
5203 $new_elt->erase;
5204 return $new_elt;
5205 }
5206  
5207 sub set_inner_html
5208 { my( $elt, $html)= @_;
5209 my $t= XML::Twig->new->parse_html( "<html>$html</html>");
5210 my $new_elt= $t->root;
5211 if( $elt->tag eq 'head')
5212 { $new_elt->first_child( 'head')->unwrap;
5213 $new_elt->first_child( 'body')->cut;
5214 }
5215 elsif( $elt->tag ne 'html')
5216 { $new_elt->first_child( 'head')->cut;
5217 $new_elt->first_child( 'body')->unwrap;
5218 }
5219 $new_elt->cut;
5220 $elt->cut_children;
5221 $new_elt->paste_first_child( $elt);
5222 $new_elt->erase;
5223 return $elt;
5224 }
5225  
5226 sub set_gi
5227 { my ($elt, $gi)= @_;
5228 $elt->{gi} = $XML::Twig::gi2index{$gi} || XML::Twig::_add_gi($gi);
5229 return $elt;
5230 }
5231  
5232 sub gi { return $XML::Twig::index2gi[$_[0]->{gi}]; }
5233  
5234 sub local_name
5235 { my $elt= shift;
5236 return _local_name( $XML::Twig::index2gi[$elt->{'gi'}]);
5237 }
5238  
5239 sub ns_prefix
5240 { my $elt= shift;
5241 return _ns_prefix( $XML::Twig::index2gi[$elt->{'gi'}]);
5242 }
5243  
5244 # namespace prefix for any qname (can be used for elements or attributes)
5245 sub _ns_prefix
5246 { my $qname= shift;
5247 if( $qname=~ m{^([^:]*):})
5248 { return $1; }
5249 else
5250 { return( ''); } # should it be '' ?
5251 }
5252  
5253 # local name for any qname (can be used for elements or attributes)
5254 sub _local_name
5255 { my $qname= shift;
5256 (my $local= $qname)=~ s{^[^:]*:}{};
5257 return $local;
5258 }
5259  
5260 #sub get_namespace
5261 sub namespace ## no critic (Subroutines::ProhibitNestedSubs);
5262 { my $elt= shift;
5263 my $prefix= defined $_[0] ? shift() : $elt->ns_prefix;
5264 my $ns_att= $prefix ? "xmlns:$prefix" : "xmlns";
5265 my $expanded= $DEFAULT_NS{$prefix} || $elt->_inherit_att_through_cut( $ns_att) || '';
5266 return $expanded;
5267 }
5268  
5269 sub declare_missing_ns ## no critic (Subroutines::ProhibitNestedSubs);
5270 { my $root= shift;
5271 my %missing_prefix;
5272 my $map= $root->_current_ns_prefix_map;
5273  
5274 foreach my $prefix (keys %$map)
5275 { my $prefix_att= $prefix eq '#default' ? 'xmlns' : "xmlns:$prefix";
5276 if( ! $root->{'att'}->{$prefix_att})
5277 { $root->set_att( $prefix_att => $map->{$prefix}); }
5278 }
5279 return $root;
5280 }
5281  
5282 sub _current_ns_prefix_map
5283 { my( $elt)= shift;
5284 my $map;
5285 while( $elt)
5286 { foreach my $att ($elt->att_names)
5287 { my $prefix= $att eq 'xmlns' ? '#default'
5288 : $att=~ m{^xmlns:(.*)$} ? $1
5289 : next
5290 ;
5291 if( ! exists $map->{$prefix}) { $map->{$prefix}= $elt->{'att'}->{$att}; }
5292 }
5293 $elt= $elt->{parent} || ($elt->{former} && $elt->{former}->{parent});
5294 }
5295 return $map;
5296 }
5297  
5298 sub set_ns_decl
5299 { my( $elt, $uri, $prefix)= @_;
5300 my $ns_att= $prefix ? "xmlns:$prefix" : 'xmlns';
5301 $elt->set_att( $ns_att => $uri);
5302 return $elt;
5303 }
5304  
5305 sub set_ns_as_default
5306 { my( $root, $uri)= @_;
5307 my @ns_decl_to_remove;
5308 foreach my $elt ($root->descendants_or_self)
5309 { if( $elt->_ns_prefix && $elt->namespace eq $uri)
5310 { $elt->set_tag( $elt->local_name); }
5311 # store any namespace declaration for that uri
5312 foreach my $ns_decl (grep { $_=~ m{xmlns(:|$)} && $elt->{'att'}->{$_} eq $uri } $elt->att_names)
5313 { push @ns_decl_to_remove, [$elt, $ns_decl]; }
5314 }
5315 $root->set_ns_decl( $uri);
5316 # now remove the ns declarations (if done earlier then descendants of an element with the ns declaration
5317 # are not considered being in the namespace
5318 foreach my $ns_decl_to_remove ( @ns_decl_to_remove)
5319 { my( $elt, $ns_decl)= @$ns_decl_to_remove;
5320 $elt->del_att( $ns_decl);
5321 }
5322  
5323 return $root;
5324 }
5325  
5326 # return #ELT for an element and #PCDATA... for others
5327 sub get_type
5328 { my $gi_nb= $_[0]->{gi}; # the number, not the string
5329 return $ELT if( $gi_nb >= $XML::Twig::SPECIAL_GI);
5330 return $_[0]->gi;
5331 }
5332  
5333 # return the gi if it's a "real" element, 0 otherwise
5334 sub is_elt
5335 { if( $_[0]->{gi} >= $XML::Twig::SPECIAL_GI)
5336 { return $_[0]->gi; }
5337 else
5338 { return 0; }
5339 }
5340  
5341 sub is_pcdata
5342 { my $elt= shift;
5343 return (exists $elt->{'pcdata'});
5344 }
5345  
5346 sub is_cdata
5347 { my $elt= shift;
5348 return (exists $elt->{'cdata'});
5349 }
5350  
5351 sub is_pi
5352 { my $elt= shift;
5353 return (exists $elt->{'target'});
5354 }
5355  
5356 sub is_comment
5357 { my $elt= shift;
5358 return (exists $elt->{'comment'});
5359 }
5360  
5361 sub is_ent
5362 { my $elt= shift;
5363 return (exists $elt->{ent} || $elt->{ent_name});
5364 }
5365  
5366 sub is_text
5367 { my $elt= shift;
5368 return (exists( $elt->{'pcdata'}) || (exists $elt->{'cdata'}));
5369 }
5370  
5371 sub is_empty
5372 { return $_[0]->{empty} || 0; }
5373  
5374 sub set_empty
5375 { $_[0]->{empty}= defined( $_[1]) ? $_[1] : 1; return $_[0]; }
5376  
5377 sub set_not_empty
5378 { delete $_[0]->{empty} if( $_[0]->{'empty'}); return $_[0]; }
5379  
5380 sub set_asis
5381 { my $elt=shift;
5382  
5383 foreach my $descendant ($elt, $elt->_descendants )
5384 { $descendant->{asis}= 1;
5385 if( (exists $descendant->{'cdata'}))
5386 { $descendant->{gi}=$XML::Twig::gi2index{$PCDATA} or $descendant->set_gi( $PCDATA);
5387 $descendant->{pcdata}= $descendant->{cdata};
5388 }
5389  
5390 }
5391 return $elt;
5392 }
5393  
5394 sub set_not_asis
5395 { my $elt=shift;
5396 foreach my $descendant ($elt, $elt->descendants)
5397 { delete $descendant->{asis} if $descendant->{asis};}
5398 return $elt;
5399 }
5400  
5401 sub is_asis
5402 { return $_[0]->{asis}; }
5403  
5404 sub closed
5405 { my $elt= shift;
5406 my $t= $elt->twig || return;
5407 my $curr_elt= $t->{twig_current};
5408 return 1 unless( $curr_elt);
5409 return $curr_elt->in( $elt);
5410 }
5411  
5412 sub set_pcdata
5413 { my( $elt, $pcdata)= @_;
5414  
5415 if( $elt->{extra_data_in_pcdata})
5416 { _try_moving_extra_data( $elt, $pcdata);
5417 }
5418 $elt->{pcdata}= $pcdata;
5419 return $elt;
5420 }
5421  
5422 sub _extra_data_in_pcdata { return $_[0]->{extra_data_in_pcdata}; }
5423 sub _set_extra_data_in_pcdata { $_[0]->{extra_data_in_pcdata}= $_[1]; return $_[0]; }
5424 sub _del_extra_data_in_pcdata { delete $_[0]->{extra_data_in_pcdata}; return $_[0]; }
5425 sub _unshift_extra_data_in_pcdata
5426 { my $e= shift;
5427 $e->{extra_data_in_pcdata}||=[];
5428 unshift @{$e->{extra_data_in_pcdata}}, { text => shift(), offset => shift() };
5429 }
5430 sub _push_extra_data_in_pcdata
5431 { my $e= shift;
5432 $e->{extra_data_in_pcdata}||=[];
5433 push @{$e->{extra_data_in_pcdata}}, { text => shift(), offset => shift() };
5434 }
5435  
5436 sub _extra_data_before_end_tag { return $_[0]->{extra_data_before_end_tag} || ''; }
5437 sub _set_extra_data_before_end_tag { $_[0]->{extra_data_before_end_tag}= $_[1]; return $_[0]}
5438 sub _del_extra_data_before_end_tag { delete $_[0]->{extra_data_before_end_tag}; return $_[0]}
5439 sub _prefix_extra_data_before_end_tag
5440 { my( $elt, $data)= @_;
5441 if($elt->{extra_data_before_end_tag})
5442 { $elt->{extra_data_before_end_tag}= $data . $elt->{extra_data_before_end_tag}; }
5443 else
5444 { $elt->{extra_data_before_end_tag}= $data; }
5445 return $elt;
5446 }
5447  
5448 # internal, in cases where we know there is no extra_data (inlined anyway!)
5449 sub _set_pcdata { $_[0]->{pcdata}= $_[1]; }
5450  
5451 # try to figure out if we can keep the extra_data around
5452 sub _try_moving_extra_data
5453 { my( $elt, $modified)=@_;
5454 my $initial= $elt->{pcdata};
5455 my $cpis= $elt->{extra_data_in_pcdata};
5456  
5457 if( (my $offset= index( $modified, $initial)) != -1)
5458 { # text has been added
5459 foreach (@$cpis) { $_->{offset}+= $offset; }
5460 }
5461 elsif( ($offset= index( $initial, $modified)) != -1)
5462 { # text has been cut
5463 my $len= length( $modified);
5464 foreach my $cpi (@$cpis) { $cpi->{offset} -= $offset; }
5465 $elt->_set_extra_data_in_pcdata( [ grep { $_->{offset} >= 0 && $_->{offset} < $len } @$cpis ]);
5466 }
5467 else
5468 { _match_extra_data_words( $elt, $initial, $modified)
5469 || _match_extra_data_chars( $elt, $initial, $modified)
5470 || $elt->_del_extra_data_in_pcdata;
5471 }
5472 }
5473  
5474 sub _match_extra_data_words
5475 { my( $elt, $initial, $modified)= @_;
5476 my @initial= split /\b/, $initial;
5477 my @modified= split /\b/, $modified;
5478  
5479 return _match_extra_data( $elt, length( $initial), \@initial, \@modified);
5480 }
5481  
5482 sub _match_extra_data_chars
5483 { my( $elt, $initial, $modified)= @_;
5484 my @initial= split //, $initial;
5485 my @modified= split //, $modified;
5486  
5487 return _match_extra_data( $elt, length( $initial), \@initial, \@modified);
5488 }
5489  
5490 sub _match_extra_data
5491 { my( $elt, $length, $initial, $modified)= @_;
5492  
5493 my $cpis= $elt->{extra_data_in_pcdata};
5494  
5495 if( @$initial <= @$modified)
5496 {
5497 my( $ok, $positions, $offsets)= _pos_offset( $initial, $modified);
5498 if( $ok)
5499 { my $offset=0;
5500 my $pos= shift @$positions;
5501 foreach my $cpi (@$cpis)
5502 { while( $cpi->{offset} >= $pos)
5503 { $offset= shift @$offsets;
5504 $pos= shift @$positions || $length +1;
5505 }
5506 $cpi->{offset} += $offset;
5507 }
5508 return 1;
5509 }
5510 }
5511 else
5512 { my( $ok, $positions, $offsets)= _pos_offset( $modified, $initial);
5513 if( $ok)
5514 { #print STDERR "pos: ", join( ':', @$positions), "\n",
5515 # "offset: ", join( ':', @$offsets), "\n";
5516 my $offset=0;
5517 my $pos= shift @$positions;
5518 my $prev_pos= 0;
5519  
5520 foreach my $cpi (@$cpis)
5521 { while( $cpi->{offset} >= $pos)
5522 { $offset= shift @$offsets;
5523 $prev_pos= $pos;
5524 $pos= shift @$positions || $length +1;
5525 }
5526 $cpi->{offset} -= $offset;
5527 if( $cpi->{offset} < $prev_pos) { delete $cpi->{text}; }
5528 }
5529 $elt->_set_extra_data_in_pcdata( [ grep { exists $_->{text} } @$cpis ]);
5530 return 1;
5531 }
5532 }
5533 return 0;
5534 }
5535  
5536 sub _pos_offset
5537 { my( $short, $long)= @_;
5538 my( @pos, @offset);
5539 my( $s_length, $l_length)=(0,0);
5540 while (@$short)
5541 { my $s_word= shift @$short;
5542 my $l_word= shift @$long;
5543 if( $s_word ne $l_word)
5544 { while( @$long && $s_word ne $l_word)
5545 { $l_length += length( $l_word);
5546 $l_word= shift @$long;
5547 }
5548 if( !@$long && $s_word ne $l_word) { return 0; }
5549 push @pos, $s_length;
5550 push @offset, $l_length - $s_length;
5551 }
5552 my $length= length( $s_word);
5553 $s_length += $length;
5554 $l_length += $length;
5555 }
5556 return( 1, \@pos, \@offset);
5557 }
5558  
5559 sub append_pcdata
5560 { $_[0]->{'pcdata'}.= $_[1];
5561 return $_[0];
5562 }
5563  
5564 sub pcdata { return $_[0]->{pcdata}; }
5565  
5566 sub append_extra_data
5567 { $_[0]->{extra_data}.= $_[1];
5568 return $_[0];
5569 }
5570  
5571 sub set_extra_data
5572 { $_[0]->{extra_data}= $_[1];
5573 return $_[0];
5574 }
5575 sub extra_data { return $_[0]->{extra_data} || ''; }
5576  
5577 sub set_target
5578 { my( $elt, $target)= @_;
5579 $elt->{target}= $target;
5580 return $elt;
5581 }
5582 sub target { return $_[0]->{target}; }
5583  
5584 sub set_data
5585 { $_[0]->{'data'}= $_[1];
5586 return $_[0];
5587 }
5588 sub data { return $_[0]->{data}; }
5589  
5590 sub set_pi
5591 { my $elt= shift;
5592 unless( $elt->{gi} == $XML::Twig::gi2index{$PI})
5593 { $elt->cut_children;
5594 $elt->{gi}=$XML::Twig::gi2index{$PI} or $elt->set_gi( $PI);
5595 }
5596 return $elt->_set_pi( @_);
5597 }
5598  
5599 sub _set_pi
5600 { $_[0]->set_target( $_[1]);
5601 $_[0]->{data}= $_[2];
5602 return $_[0];
5603 }
5604  
5605 sub pi_string { my $string= $PI_START . $_[0]->{target};
5606 my $data= $_[0]->{data};
5607 if( defined( $data) && $data ne '') { $string .= " $data"; }
5608 $string .= $PI_END ;
5609 return $string;
5610 }
5611  
5612 sub set_comment
5613 { my $elt= shift;
5614 unless( $elt->{gi} == $XML::Twig::gi2index{$COMMENT})
5615 { $elt->cut_children;
5616 $elt->{gi}=$XML::Twig::gi2index{$COMMENT} or $elt->set_gi( $COMMENT);
5617 }
5618 $elt->{comment}= $_[0];
5619 return $elt;
5620 }
5621  
5622 sub _set_comment { $_[0]->{comment}= $_[1]; return $_[0]; }
5623 sub comment { return $_[0]->{comment}; }
5624 sub comment_string { return $COMMENT_START . _comment_escaped_string( $_[0]->{comment}) . $COMMENT_END; }
5625 # comments cannot start or end with
5626 sub _comment_escaped_string
5627 { my( $c)= @_;
5628 $c=~ s{^-}{ -};
5629 $c=~ s{-$}{- };
5630 $c=~ s{--}{- -}g;
5631 return $c;
5632 }
5633  
5634 sub set_ent { $_[0]->{ent}= $_[1]; return $_[0]; }
5635 sub ent { return $_[0]->{ent}; }
5636 sub ent_name { return substr( $_[0]->{ent}, 1, -1);}
5637  
5638 sub set_cdata
5639 { my $elt= shift;
5640 unless( $elt->{gi} == $XML::Twig::gi2index{$CDATA})
5641 { $elt->cut_children;
5642 $elt->insert_new_elt( first_child => $CDATA, @_);
5643 return $elt;
5644 }
5645 $elt->{cdata}= $_[0];
5646 return $_[0];
5647 }
5648  
5649 sub _set_cdata
5650 { $_[0]->{cdata}= $_[1];
5651 return $_[0];
5652 }
5653  
5654 sub append_cdata
5655 { $_[0]->{cdata}.= $_[1];
5656 return $_[0];
5657 }
5658 sub cdata { return $_[0]->{cdata}; }
5659  
5660 sub contains_only_text
5661 { my $elt= shift;
5662 return 0 unless $elt->is_elt;
5663 foreach my $child ($elt->_children)
5664 { return 0 if $child->is_elt; }
5665 return $elt;
5666 }
5667  
5668 sub contains_only
5669 { my( $elt, $exp)= @_;
5670 my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
5671 foreach my $child (@children)
5672 { return 0 unless $child->is( $exp); }
5673 return @children || 1;
5674 }
5675  
5676 sub contains_a_single
5677 { my( $elt, $exp)= @_;
5678 my $child= $elt->{first_child} or return 0;
5679 return 0 unless $child->passes( $exp);
5680 return 0 if( $child->{next_sibling});
5681 return $child;
5682 }
5683  
5684 sub root
5685 { my $elt= shift;
5686 while( $elt->{parent}) { $elt= $elt->{parent}; }
5687 return $elt;
5688 }
5689  
5690 sub _root_through_cut
5691 { my $elt= shift;
5692 while( $elt->{parent} || ($elt->{former} && $elt->{former}->{parent})) { $elt= $elt->{parent} || ($elt->{former} && $elt->{former}->{parent}); }
5693 return $elt;
5694 }
5695  
5696 sub twig
5697 { my $elt= shift;
5698 my $root= $elt->root;
5699 return $root->{twig};
5700 }
5701  
5702 sub _twig_through_cut
5703 { my $elt= shift;
5704 my $root= $elt->_root_through_cut;
5705 return $root->{twig};
5706 }
5707  
5708 # used for navigation
5709 # returns undef or the element, depending on whether $elt passes $cond
5710 # $cond can be
5711 # - empty: the element passes the condition
5712 # - ELT ('#ELT'): the element passes the condition if it is a "real" element
5713 # - TEXT ('#TEXT'): the element passes if it is a CDATA or PCDATA element
5714 # - a string with an XPath condition (only a subset of XPath is actually
5715 # supported).
5716 # - a regexp: the element passes if its gi matches the regexp
5717 # - a code ref: the element passes if the code, applied on the element,
5718 # returns true
5719  
5720 my %cond_cache; # expression => coderef
5721  
5722 sub reset_cond_cache { %cond_cache=(); }
5723  
5724 {
5725 sub _install_cond
5726 { my $cond= shift;
5727 my $test;
5728 my $init='';
5729  
5730 my $original_cond= $cond;
5731  
5732 my $not= ($cond=~ s{^\s*!}{}) ? '!' : '';
5733  
5734 if( ref $cond eq 'CODE') { return $cond; }
5735  
5736 if( ref $cond eq 'Regexp')
5737 { $test = qq{(\$_[0]->gi=~ /$cond/)}; }
5738 else
5739 { my @tests;
5740 while( $cond)
5741 {
5742 # the condition is a string
5743 if( $cond=~ s{$ELT$SEP}{})
5744 { push @tests, qq{\$_[0]->is_elt}; }
5745 elsif( $cond=~ s{$TEXT$SEP}{})
5746 { push @tests, qq{\$_[0]->is_text}; }
5747 elsif( $cond=~ s{^\s*($REG_TAG_PART)$SEP}{})
5748 { push @tests, _gi_test( $1); }
5749 elsif( $cond=~ s{^\s*($REG_REGEXP)$SEP}{})
5750 { # /regexp/
5751 push @tests, qq{ \$_[0]->gi=~ $1 };
5752 }
5753 elsif( $cond=~ s{^\s*($REG_TAG_PART)?\s* # $1
5754 \[\s*(-?)\s*(\d+)\s*\] # [$2]
5755 $SEP}{}xo
5756 )
5757 { my( $gi, $neg, $index)= ($1, $2, $3);
5758 my $siblings= $neg ? q{$_[0]->_next_siblings} : q{$_[0]->_prev_siblings};
5759 if( $gi && ($gi ne '*'))
5760 #{ $test= qq{((\$_[0]->gi eq "$gi") && (scalar( grep { \$_->gi eq "$gi" } $siblings) + 1 == $index))}; }
5761 { push @tests, _and( _gi_test( $gi), qq{ (scalar( grep { \$_->gi eq "$gi" } $siblings) + 1 == $index)}); }
5762 else
5763 { push @tests, qq{(scalar( $siblings) + 1 == $index)}; }
5764 }
5765 elsif( $cond=~ s{^\s*($REG_TAG_PART?)\s*($REG_PREDICATE)$SEP}{})
5766 { my( $gi, $predicate)= ( $1, $2);
5767 push @tests, _and( _gi_test( $gi), _parse_predicate_in_step( $predicate));
5768 }
5769 elsif( $cond=~ s{^\s*($REG_NAKED_PREDICATE)$SEP}{})
5770 { push @tests, _parse_predicate_in_step( $1); }
5771 else
5772 { croak "wrong navigation condition '$original_cond' ($@)"; }
5773 }
5774 $test= @tests > 1 ? '(' . join( '||', map { "($_)" } @tests) . ')' : $tests[0];
5775 }
5776  
5777 #warn "init: '$init' - test: '$test'\n";
5778  
5779 my $sub= qq{sub { $NO_WARNINGS; $init; return $not($test) ? \$_[0] : undef; } };
5780 my $s= eval $sub; ## no critic (ProhibitStringyEval)
5781 # warn "cond: $cond\n$sub\n";
5782 if( $@)
5783 { croak "wrong navigation condition '$original_cond' ($@);" }
5784 return $s;
5785 }
5786  
5787 sub _gi_test
5788 { my( $full_gi)= @_;
5789  
5790 # optimize if the gi exists, including the case where the gi includes a dot
5791 my $index= $XML::Twig::gi2index{$full_gi};
5792  
5793 if( $index)
5794 { return qq{\$_[0]->{gi} == $index}; }
5795 elsif( defined $css_sel && $css_sel == 0 ) {
5796 # css_sel explicitely set to 0 forces treating names with dots as just plain tag names
5797 my $new_index = XML::Twig::_add_gi( $full_gi );
5798 return qq{(\$_[0]->{gi} == $new_index)};
5799 }
5800 my( $gi, $class, $id)= $full_gi=~ m{^(.*?)(?:[.](.*)|[#](.*))?$};
5801  
5802 my $gi_test='';
5803 if( $gi && $gi ne '*' )
5804 { # 2 options, depending on whether the gi exists in gi2index
5805 # start optimization
5806 my $index= $XML::Twig::gi2index{$gi};
5807 if( $index)
5808 { # the gi exists, use its index as a faster shortcut
5809 $gi_test = qq{\$_[0]->{gi} == $index};
5810 }
5811 else
5812 # end optimization
5813 { # it does not exist (but might be created later), compare the strings
5814 $gi_test = qq{ (\$_[0]->{gi} == (\$XML::Twig::gi2index{'$gi'} || 0))};
5815 }
5816 }
5817 else
5818 { $gi_test= 1; }
5819  
5820 my $class_test='';
5821 if( $class)
5822 { my @classes = grep { $_ } split /\./, $class;
5823 $class_test = join ' && ', qq{(defined( \$_[0]->{att}->{class}))}, map { qq{(\$_[0]->{att}->{class}=~ m{\\b$_\\b})} } @classes;
5824 }
5825  
5826 my $id_test='';
5827 if( $id)
5828 { $id_test = qq{ defined( \$_[0]->{att}->{$ID}) && \$_[0]->{att}->{$ID} eq '$id' }; }
5829  
5830 my $test = _and( $gi_test, $class_test, $id_test);
5831 # account for the (unlikely) case where a tag.class condition is actually a tag.withdot condition
5832 # but no tag.withdot element has yet been seen
5833 if( $gi && $gi ne '*' && $class) { $test = qq{((\$_[0]->{full_gi} == (\$XML::Twig::gi2index{'$gi'} || 0)) || $test)}; }
5834 #warn " full_gi is [$full_gi], test is: [$test]";
5835  
5836 return $test;
5837  
5838 }
5839  
5840 # input: the original predicate
5841 sub _parse_predicate_in_step
5842 { my $cond= shift; my $initial_cond= $cond;
5843 my %PERL_ALPHA_TEST= ( '=' => ' eq ', '!=' => ' ne ', '>' => ' gt ', '>=' => ' ge ', '<' => ' lt ', '<=' => ' le ');
5844  
5845 $cond=~ s{^\s*\[\s*}{};
5846 $cond=~ s{\s*\]\s*$}{};
5847 $cond=~ s{( ($REG_STRING|$REG_REGEXP) # strings or regexps
5848 |\@($REG_TAG_NAME)(?=\s*(?:[><=!]|!~|=~)) # @att (followed by a comparison operator)
5849 |\@($REG_TAG_NAME) # @att (not followed by a comparison operator)
5850 |=~|!~ # matching operators
5851 |([><]=?|=|!=)(?=\s*[\d+-]) # test before a number
5852 |([><]=?|=|!=) # test, other cases
5853 |($REG_FUNCTION) # no arg functions
5854 # this bit is a mess, but it is the only solution with this half-baked parser
5855 |((?:string|text)\(\s*$REG_TAG_NAME\s*\)\s*$REG_MATCH\s*$REG_REGEXP) # string( child) =~ /regexp/
5856 |((?:string|text)\(\s*$REG_TAG_NAME\s*\)\s*!?=\s*$REG_VALUE) # string( child) = "value" (or !=)
5857 |((?:string|text)\(\s*$REG_TAG_NAME\s*\)\s*[<>]=?\s*$REG_VALUE) # string( child) > "value"
5858 |(and|or)
5859 )}
5860 { my( $token, $string, $att, $bare_att, $num_test, $alpha_test, $func, $string_regexp, $string_eq, $string_test, $and_or)
5861 = ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
5862  
5863 if( defined $string) { $token }
5864 elsif( $att) { "( \$_[0]->{att} && exists( \$_[0]->{att}->{'$att'}) && \$_[0]->{att}->{'$att'})"; }
5865 elsif( $bare_att) { "(\$_[0]->{att} && defined( \$_[0]->{att}->{'$bare_att'}))"; }
5866 elsif( $num_test && ($num_test eq '=') ) { "==" } # others tests are unchanged
5867 elsif( $alpha_test) { $PERL_ALPHA_TEST{$alpha_test} }
5868 elsif( $func && $func=~ m{^(?:string|text)})
5869 { "\$_[0]->text"; }
5870 elsif( $string_regexp && $string_regexp =~ m{(?:string|text)\(\s*($REG_TAG_NAME)\s*\)\s*($REG_MATCH)\s*($REG_REGEXP)})
5871 { "(XML::Twig::_first_n { (\$_->gi eq '$1') && (\$_->text $2 $3) } 1, \$_[0]->_children)"; }
5872 elsif( $string_eq && $string_eq =~ m{(?:string|text)\(\s*($REG_TAG_NAME)\s*\)\s*(!?=)\s*($REG_VALUE)})
5873 {"(XML::Twig::_first_n { (\$_->gi eq '$1') && (\$_->text $PERL_ALPHA_TEST{$2} $3) } 1, \$_[0]->_children)"; }
5874 elsif( $string_test && $string_test =~ m{(?:string|text)\(\s*($REG_TAG_NAME)\s*\)\s*([<>]=?)\s*($REG_VALUE)})
5875 { "(XML::Twig::_first_n { (\$_->gi eq '$1') && (\$_->text $2 $3) } 1, \$_[0]->_children)"; }
5876 elsif( $and_or) { $and_or eq 'and' ? '&&' : '||' ; }
5877 else { $token; }
5878 }gexs;
5879 #warn "[$initial_cond] => [$cond]\n";
5880 return "($cond)";
5881 }
5882  
5883 sub _op
5884 { my $op= shift;
5885 if( $op eq '=') { $op= 'eq'; }
5886 elsif( $op eq '!=') { $op= 'ne'; }
5887 return $op;
5888 }
5889  
5890 sub passes
5891 { my( $elt, $cond)= @_;
5892 return $elt unless $cond;
5893 my $sub= ($cond_cache{$cond} ||= _install_cond( $cond));
5894 return $sub->( $elt);
5895 }
5896 }
5897  
5898 sub set_parent
5899 { $_[0]->{parent}= $_[1];
5900 if( $XML::Twig::weakrefs) { weaken( $_[0]->{parent}); }
5901 }
5902  
5903 sub parent
5904 { my $elt= shift;
5905 my $cond= shift || return $elt->{parent};
5906 do { $elt= $elt->{parent} || return; } until ( $elt->passes( $cond));
5907 return $elt;
5908 }
5909  
5910 sub set_first_child
5911 { $_[0]->{'first_child'}= $_[1];
5912 }
5913  
5914 sub first_child
5915 { my $elt= shift;
5916 my $cond= shift || return $elt->{first_child};
5917 my $child= $elt->{first_child};
5918 my $test_cond= ($cond_cache{$cond} ||= _install_cond( $cond));
5919 while( $child && !$test_cond->( $child))
5920 { $child= $child->{next_sibling}; }
5921 return $child;
5922 }
5923  
5924 sub _first_child { return $_[0]->{first_child}; }
5925 sub _last_child { return $_[0]->{last_child}; }
5926 sub _next_sibling { return $_[0]->{next_sibling}; }
5927 sub _prev_sibling { return $_[0]->{prev_sibling}; }
5928 sub _parent { return $_[0]->{parent}; }
5929 sub _next_siblings { my $elt= shift; my @siblings; while( $elt= $elt->{next_sibling}) { push @siblings, $elt; } return @siblings; }
5930 sub _prev_siblings { my $elt= shift; my @siblings; while( $elt= $elt->{prev_sibling}) { push @siblings, $elt; } return @siblings; }
5931  
5932 # converts HTML style positions like 'beforebegin' to twig style positions like 'first_child'
5933 sub _op_position {
5934 my ($position) = @_;
5935 return $POSITION_ALIAS{$position} // $position;
5936 }
5937  
5938 # builds a message with allowed position
5939 sub _allowed_positions {
5940 return join ', ', map { "$_ (or $OP_POSITION{$_})" } sort keys %OP_POSITION;
5941 }
5942  
5943 # sets a field
5944 # arguments $record, $cond, @content
5945 sub set_field
5946 { my $record = shift;
5947 my $cond = shift;
5948 my $child= $record->first_child( $cond);
5949 if( $child)
5950 { $child->set_content( @_); }
5951 else
5952 { if( $cond=~ m{^\s*($REG_TAG_NAME)})
5953 { my $gi= $1;
5954 $child= $record->insert_new_elt( last_child => $gi, @_);
5955 }
5956 else
5957 { croak "can't create a field name from $cond"; }
5958 }
5959 return $child;
5960 }
5961  
5962 sub set_last_child
5963 { $_[0]->{'last_child'}= $_[1];
5964 delete $_[0]->{empty};
5965 if( $XML::Twig::weakrefs) { weaken( $_[0]->{'last_child'}); }
5966 }
5967  
5968 sub last_child
5969 { my $elt= shift;
5970 my $cond= shift || return $elt->{last_child};
5971 my $test_cond= ($cond_cache{$cond} ||= _install_cond( $cond));
5972 my $child= $elt->{last_child};
5973 while( $child && !$test_cond->( $child) )
5974 { $child= $child->{prev_sibling}; }
5975 return $child
5976 }
5977  
5978 sub set_prev_sibling
5979 { $_[0]->{'prev_sibling'}= $_[1];
5980 if( $XML::Twig::weakrefs) { weaken( $_[0]->{'prev_sibling'}); }
5981 }
5982  
5983 sub prev_sibling
5984 { my $elt= shift;
5985 my $cond= shift || return $elt->{prev_sibling};
5986 my $test_cond= ($cond_cache{$cond} ||= _install_cond( $cond));
5987 my $sibling= $elt->{prev_sibling};
5988 while( $sibling && !$test_cond->( $sibling) )
5989 { $sibling= $sibling->{prev_sibling}; }
5990 return $sibling;
5991 }
5992  
5993 sub set_next_sibling { $_[0]->{'next_sibling'}= $_[1]; }
5994  
5995 sub next_sibling
5996 { my $elt= shift;
5997 my $cond= shift || return $elt->{next_sibling};
5998 my $test_cond= ($cond_cache{$cond} ||= _install_cond( $cond));
5999 my $sibling= $elt->{next_sibling};
6000 while( $sibling && !$test_cond->( $sibling) )
6001 { $sibling= $sibling->{next_sibling}; }
6002 return $sibling;
6003 }
6004  
6005 # methods dealing with the class attribute, convenient if you work with xhtml
6006 sub class { $_[0]->{att}->{class}; }
6007 # lvalue version of class. separate from class to avoid problem with scalar/list context
6008 sub lclass :lvalue
6009 { $_[0]->{att}->{class}; }
6010  
6011 sub set_class { my( $elt, $class)= @_; $elt->set_att( class => $class); }
6012  
6013 # adds a class to an element
6014 sub add_to_class
6015 { my( $elt, $new_class)= @_;
6016 return $elt unless $new_class;
6017 my $class= $elt->class;
6018 my %class= $class ? map { $_ => 1 } split /\s+/, $class : ();
6019 $class{$new_class}= 1;
6020 $elt->set_class( join( ' ', sort keys %class));
6021 }
6022  
6023 sub remove_class
6024 { my( $elt, $class_to_remove)= @_;
6025 return $elt unless $class_to_remove;
6026 my $class= $elt->class;
6027 my %class= $class ? map { $_ => 1 } split /\s+/, $class : ();
6028 delete $class{$class_to_remove};
6029 $elt->set_class( join( ' ', sort keys %class));
6030 }
6031  
6032 sub att_to_class { my( $elt, $att)= @_; $elt->set_class( $elt->{'att'}->{$att}); }
6033 sub add_att_to_class { my( $elt, $att)= @_; $elt->add_to_class( $elt->{'att'}->{$att}); }
6034 sub move_att_to_class { my( $elt, $att)= @_; $elt->add_to_class( $elt->{'att'}->{$att});
6035 $elt->del_att( $att);
6036 }
6037 sub tag_to_class { my( $elt)= @_; $elt->set_class( $elt->tag); }
6038 sub add_tag_to_class { my( $elt)= @_; $elt->add_to_class( $elt->tag); }
6039 sub set_tag_class { my( $elt, $new_tag)= @_; $elt->add_tag_to_class; $elt->set_tag( $new_tag); }
6040  
6041 sub tag_to_span
6042 { my( $elt)= @_;
6043 $elt->set_class( $elt->tag) unless( $elt->tag eq 'span' && $elt->class); # set class to span unless it would mean replacing it with span
6044 $elt->set_tag( 'span');
6045 }
6046  
6047 sub tag_to_div
6048 { my( $elt)= @_;
6049 $elt->set_class( $elt->tag) unless( $elt->tag eq 'div' && $elt->class); # set class to div unless it would mean replacing it with div
6050 $elt->set_tag( 'div');
6051 }
6052  
6053 sub in_class
6054 { my( $elt, $class)= @_;
6055 my $elt_class= $elt->class;
6056 return unless( defined $elt_class);
6057 return $elt->class=~ m{(?:^|\s)\Q$class\E(?:\s|$)} ? $elt : 0;
6058 }
6059  
6060 # get or set all attributes
6061 # argument can be a hash or a hashref
6062 sub set_atts
6063 { my $elt= shift;
6064 my %atts;
6065 tie %atts, 'Tie::IxHash' if( keep_atts_order());
6066 %atts= @_ == 1 ? %{$_[0]} : @_;
6067 $elt->{att}= \%atts;
6068 if( exists $atts{$ID}) { $elt->_set_id( $atts{$ID}); }
6069 return $elt;
6070 }
6071  
6072 sub atts { return $_[0]->{att}; }
6073 sub att_names { return (sort keys %{$_[0]->{att}}); }
6074 sub del_atts { delete $_[0]->{att}; return $_[0]; }
6075  
6076 # get or set a single attribute (set works for several atts)
6077 sub set_att
6078 { my $elt= shift;
6079 if( $_[0] && ref( $_[0]) && !$_[1])
6080 { croak "improper call to set_att, usage is \$elt->set_att( att1 => 'val1', att2 => 'val2',...)"; }
6081  
6082 $elt->{att} ||= {};
6083 # need to test on keys because the att hash is created, empty, by some methods,
6084 # like sprint (through autovivification)
6085 tie %{$elt->{att}}, 'Tie::IxHash' if keep_atts_order() && ! keys %{$elt->{att}};
6086  
6087 while(@_)
6088 { my( $att, $val)= (shift, shift);
6089 $elt->{att}->{$att}= $val;
6090 if( $att eq $ID) { $elt->_set_id( $val); }
6091 }
6092 return $elt;
6093 }
6094  
6095 sub att { $_[0]->{att}->{$_[1]}; }
6096 # lvalue version of att. separate from class to avoid problems with scalar/list context
6097 sub latt :lvalue
6098 { $_[0]->{att}->{$_[1]}; }
6099  
6100 sub del_att
6101 { my $elt= shift;
6102 while( @_) { delete $elt->{'att'}->{shift()}; }
6103 return $elt;
6104 }
6105  
6106 sub att_exists { return exists $_[0]->{att}->{$_[1]}; }
6107  
6108 # delete one or more attributes from all descendants of an element
6109 sub strip_att
6110 { my( $elt, @att)= @_;
6111 $_->del_att( @att) foreach ($elt->descendants_or_self);
6112 return $elt;
6113 }
6114  
6115 sub change_att_name
6116 { my( $elt, $old_name, $new_name)= @_;
6117 my $value= $elt->{'att'}->{$old_name};
6118 return $elt unless( defined $value);
6119 $elt->del_att( $old_name)
6120 ->set_att( $new_name => $value);
6121 return $elt;
6122 }
6123  
6124 sub lc_attnames
6125 { my $elt= shift;
6126 foreach my $att ($elt->att_names)
6127 { if( $att ne lc $att) { $elt->change_att_name( $att, lc $att); } }
6128 return $elt;
6129 }
6130  
6131 sub set_twig_current { $_[0]->{twig_current}=1; }
6132 sub del_twig_current { delete $_[0]->{twig_current}; }
6133  
6134 # get or set the id attribute
6135 sub set_id
6136 { my( $elt, $id)= @_;
6137 $elt->del_id() if( exists $elt->{att}->{$ID});
6138 $elt->set_att($ID, $id);
6139 $elt->_set_id( $id);
6140 return $elt;
6141 }
6142  
6143 # only set id, does not update the attribute value
6144 sub _set_id
6145 { my( $elt, $id)= @_;
6146 my $t= $elt->twig || $elt;
6147 $t->{twig_id_list}->{$id}= $elt;
6148 if( $XML::Twig::weakrefs) { weaken( $t->{twig_id_list}->{$id}); }
6149 return $elt;
6150 }
6151  
6152 sub id { return $_[0]->{att}->{$ID}; }
6153  
6154 # methods used to add ids to elements that don't have one
6155 BEGIN
6156 { my $id_nb = "0001";
6157 my $id_seed = "twig_id_";
6158  
6159 sub set_id_seed ## no critic (Subroutines::ProhibitNestedSubs);
6160 { $id_seed= $_[1]; $id_nb=1; }
6161  
6162 sub add_id ## no critic (Subroutines::ProhibitNestedSubs);
6163 { my $elt= shift;
6164 if( defined $elt->{'att'}->{$ID})
6165 { return $elt->{'att'}->{$ID}; }
6166 else
6167 { my $id= $_[0] && ref( $_[0]) && isa( $_[0], 'CODE') ? $_[0]->( $elt) : $id_seed . $id_nb++;
6168 $elt->set_id( $id);
6169 return $id;
6170 }
6171 }
6172 }
6173  
6174 # delete the id attribute and remove the element from the id list
6175 sub del_id
6176 { my $elt= shift;
6177 if( ! exists $elt->{att}->{$ID}) { return $elt };
6178 my $id= $elt->{att}->{$ID};
6179  
6180 delete $elt->{att}->{$ID};
6181  
6182 my $t= shift || $elt->twig;
6183 unless( $t) { return $elt; }
6184 if( exists $t->{twig_id_list}->{$id}) { delete $t->{twig_id_list}->{$id}; }
6185  
6186 return $elt;
6187 }
6188  
6189 # return the list of children
6190 sub children
6191 { my $elt= shift;
6192 my @children;
6193 my $child= $elt->first_child( @_);
6194 while( $child)
6195 { push @children, $child;
6196 $child= $child->next_sibling( @_);
6197 }
6198 return @children;
6199 }
6200  
6201 sub _children
6202 { my $elt= shift;
6203 my @children=();
6204 my $child= $elt->{first_child};
6205 while( $child)
6206 { push @children, $child;
6207 $child= $child->{next_sibling};
6208 }
6209 return @children;
6210 }
6211  
6212 sub children_copy
6213 { my $elt= shift;
6214 my @children;
6215 my $child= $elt->first_child( @_);
6216 while( $child)
6217 { push @children, $child->copy;
6218 $child= $child->next_sibling( @_);
6219 }
6220 return @children;
6221 }
6222  
6223 sub children_count
6224 { my $elt= shift;
6225 my $cond= shift;
6226 my $count=0;
6227 my $child= $elt->{first_child};
6228 while( $child)
6229 { $count++ if( $child->passes( $cond));
6230 $child= $child->{next_sibling};
6231 }
6232 return $count;
6233 }
6234  
6235 sub children_text
6236 { my $elt= shift;
6237 return wantarray() ? map { $_->text} $elt->children( @_)
6238 : join( '', map { $_->text} $elt->children( @_) )
6239 ;
6240 }
6241  
6242 sub children_trimmed_text
6243 { my $elt= shift;
6244 return wantarray() ? map { $_->trimmed_text} $elt->children( @_)
6245 : join( '', map { $_->trimmed_text} $elt->children( @_) )
6246 ;
6247 }
6248  
6249 sub all_children_are
6250 { my( $parent, $cond)= @_;
6251 foreach my $child ($parent->_children)
6252 { return 0 unless( $child->passes( $cond)); }
6253 return $parent;
6254 }
6255  
6256 sub ancestors
6257 { my( $elt, $cond)= @_;
6258 my @ancestors;
6259 while( $elt->{parent})
6260 { $elt= $elt->{parent};
6261 push @ancestors, $elt if( $elt->passes( $cond));
6262 }
6263 return @ancestors;
6264 }
6265  
6266 sub ancestors_or_self
6267 { my( $elt, $cond)= @_;
6268 my @ancestors;
6269 while( $elt)
6270 { push @ancestors, $elt if( $elt->passes( $cond));
6271 $elt= $elt->{parent};
6272 }
6273 return @ancestors;
6274 }
6275  
6276 sub _ancestors
6277 { my( $elt, $include_self)= @_;
6278 my @ancestors= $include_self ? ($elt) : ();
6279 while( $elt= $elt->{parent}) { push @ancestors, $elt; }
6280 return @ancestors;
6281 }
6282  
6283 sub inherit_att
6284 { my $elt= shift;
6285 my $att= shift;
6286 my %tags= map { ($_, 1) } @_;
6287  
6288 do
6289 { if( (defined $elt->{'att'}->{$att})
6290 && ( !%tags || $tags{$XML::Twig::index2gi[$elt->{'gi'}]})
6291 )
6292 { return $elt->{'att'}->{$att}; }
6293 } while( $elt= $elt->{parent});
6294 return undef;
6295 }
6296  
6297 sub _inherit_att_through_cut
6298 { my $elt= shift;
6299 my $att= shift;
6300 my %tags= map { ($_, 1) } @_;
6301  
6302 do
6303 { if( (defined $elt->{'att'}->{$att})
6304 && ( !%tags || $tags{$XML::Twig::index2gi[$elt->{'gi'}]})
6305 )
6306 { return $elt->{'att'}->{$att}; }
6307 } while( $elt= $elt->{parent} || ($elt->{former} && $elt->{former}->{parent}));
6308 return undef;
6309 }
6310  
6311 sub current_ns_prefixes
6312 { my $elt= shift;
6313 my %prefix;
6314 $prefix{''}=1 if( $elt->namespace( ''));
6315 while( $elt)
6316 { my @ns= grep { !m{^xml} } map { m{^([^:]+):} } ($XML::Twig::index2gi[$elt->{'gi'}], $elt->att_names);
6317 $prefix{$_}=1 foreach (@ns);
6318 $elt= $elt->{parent};
6319 }
6320  
6321 return (sort keys %prefix);
6322 }
6323  
6324 # kinda counter-intuitive actually:
6325 # the next element is found by looking for the next open tag after from the
6326 # current one, which is the first child, if it exists, or the next sibling
6327 # or the first next sibling of an ancestor
6328 # optional arguments are:
6329 # - $subtree_root: a reference to an element, when the next element is not
6330 # within $subtree_root anymore then next_elt returns undef
6331 # - $cond: a condition, next_elt returns the next element matching the condition
6332  
6333 sub next_elt
6334 { my $elt= shift;
6335 my $subtree_root= 0;
6336 $subtree_root= shift if( ref( $_[0]) && isa( $_[0], 'XML::Twig::Elt'));
6337 my $cond= shift;
6338 my $next_elt;
6339  
6340 my $ind; # optimization
6341 my $test_cond;
6342 if( $cond) # optimization
6343 { unless( defined( $ind= $XML::Twig::gi2index{$cond}) ) # optimization
6344 { $test_cond= ($cond_cache{$cond} ||= _install_cond( $cond)); } # optimization
6345 } # optimization
6346  
6347 do
6348 { if( $next_elt= $elt->{first_child})
6349 { # simplest case: the elt has a child
6350 }
6351 elsif( $next_elt= $elt->{next_sibling})
6352 { # no child but a next sibling (just check we stay within the subtree)
6353  
6354 # case where elt is subtree_root, is empty and has a sibling
6355 return undef if( $subtree_root && ($elt == $subtree_root));
6356  
6357 }
6358 else
6359 { # case where the element has no child and no next sibling:
6360 # get the first next sibling of an ancestor, checking subtree_root
6361  
6362 # case where elt is subtree_root, is empty and has no sibling
6363 return undef if( $subtree_root && ($elt == $subtree_root));
6364  
6365 $next_elt= $elt->{parent} || return undef;
6366  
6367 until( $next_elt->{next_sibling})
6368 { return undef if( $subtree_root && ($subtree_root == $next_elt));
6369 $next_elt= $next_elt->{parent} || return undef;
6370 }
6371 return undef if( $subtree_root && ($subtree_root == $next_elt));
6372 $next_elt= $next_elt->{next_sibling};
6373 }
6374 $elt= $next_elt; # just in case we need to loop
6375 } until( ! defined $elt
6376 || ! defined $cond
6377 || (defined $ind && ($elt->{gi} eq $ind)) # optimization
6378 || (defined $test_cond && ($test_cond->( $elt)))
6379 );
6380  
6381 return $elt;
6382 }
6383  
6384 # return the next_elt within the element
6385 # just call next_elt with the element as first and second argument
6386 sub first_descendant { return $_[0]->next_elt( @_); }
6387  
6388 # get the last descendant, # then return the element found or call prev_elt with the condition
6389 sub last_descendant
6390 { my( $elt, $cond)= @_;
6391 my $last_descendant= $elt->_last_descendant;
6392 if( !$cond || $last_descendant->matches( $cond))
6393 { return $last_descendant; }
6394 else
6395 { return $last_descendant->prev_elt( $elt, $cond); }
6396 }
6397  
6398 # no argument allowed here, just go down the last_child recursively
6399 sub _last_descendant
6400 { my $elt= shift;
6401 while( my $child= $elt->{last_child}) { $elt= $child; }
6402 return $elt;
6403 }
6404  
6405 # counter-intuitive too:
6406 # the previous element is found by looking
6407 # for the first open tag backwards from the current one
6408 # it's the last descendant of the previous sibling
6409 # if it exists, otherwise it's simply the parent
6410 sub prev_elt
6411 { my $elt= shift;
6412 my $subtree_root= 0;
6413 if( defined $_[0] and (ref( $_[0]) && isa( $_[0], 'XML::Twig::Elt')))
6414 { $subtree_root= shift ;
6415 return undef if( $elt == $subtree_root);
6416 }
6417 my $cond= shift;
6418 # get prev elt
6419 my $prev_elt;
6420 do
6421 { return undef if( $elt == $subtree_root);
6422 if( $prev_elt= $elt->{prev_sibling})
6423 { while( $prev_elt->{last_child})
6424 { $prev_elt= $prev_elt->{last_child}; }
6425 }
6426 else
6427 { $prev_elt= $elt->{parent} || return undef; }
6428 $elt= $prev_elt; # in case we need to loop
6429 } until( $elt->passes( $cond));
6430  
6431 return $elt;
6432 }
6433  
6434 sub _following_elt
6435 { my( $elt)= @_;
6436 while( $elt && !$elt->{next_sibling})
6437 { $elt= $elt->{parent}; }
6438 return $elt ? $elt->{next_sibling} : undef;
6439 }
6440  
6441 sub following_elt
6442 { my( $elt, $cond)= @_;
6443 $elt= $elt->_following_elt || return undef;
6444 return $elt if( !$cond || $elt->matches( $cond));
6445 return $elt->next_elt( $cond);
6446 }
6447  
6448 sub following_elts
6449 { my( $elt, $cond)= @_;
6450 if( !$cond) { undef $cond; }
6451 my $following= $elt->following_elt( $cond);
6452 if( $following)
6453 { my @followings= $following;
6454 while( $following= $following->next_elt( $cond))
6455 { push @followings, $following; }
6456 return( @followings);
6457 }
6458 else
6459 { return (); }
6460 }
6461  
6462 sub _preceding_elt
6463 { my( $elt)= @_;
6464 while( $elt && !$elt->{prev_sibling})
6465 { $elt= $elt->{parent}; }
6466 return $elt ? $elt->{prev_sibling}->_last_descendant : undef;
6467 }
6468  
6469 sub preceding_elt
6470 { my( $elt, $cond)= @_;
6471 $elt= $elt->_preceding_elt || return undef;
6472 return $elt if( !$cond || $elt->matches( $cond));
6473 return $elt->prev_elt( $cond);
6474 }
6475  
6476 sub preceding_elts
6477 { my( $elt, $cond)= @_;
6478 if( !$cond) { undef $cond; }
6479 my $preceding= $elt->preceding_elt( $cond);
6480 if( $preceding)
6481 { my @precedings= $preceding;
6482 while( $preceding= $preceding->prev_elt( $cond))
6483 { push @precedings, $preceding; }
6484 return( @precedings);
6485 }
6486 else
6487 { return (); }
6488 }
6489  
6490 # used in get_xpath
6491 sub _self
6492 { my( $elt, $cond)= @_;
6493 return $cond ? $elt->matches( $cond) : $elt;
6494 }
6495  
6496 sub next_n_elt
6497 { my $elt= shift;
6498 my $offset= shift || return undef;
6499 foreach (1..$offset)
6500 { $elt= $elt->next_elt( @_) || return undef; }
6501 return $elt;
6502 }
6503  
6504 # checks whether $elt is included in $ancestor, returns 1 in that case
6505 sub in
6506 { my ($elt, $ancestor)= @_;
6507 if( ref( $ancestor) && isa( $ancestor, 'XML::Twig::Elt'))
6508 { # element
6509 while( $elt= $elt->{parent}) { return $elt if( $elt == $ancestor); }
6510 }
6511 else
6512 { # condition
6513 while( $elt= $elt->{parent}) { return $elt if( $elt->matches( $ancestor)); }
6514 }
6515 return 0;
6516 }
6517  
6518 sub first_child_text
6519 { my $elt= shift;
6520 my $dest=$elt->first_child(@_) or return '';
6521 return $dest->text;
6522 }
6523  
6524 sub fields
6525 { my $elt= shift;
6526 return map { $elt->field( $_) } @_;
6527 }
6528  
6529 sub first_child_trimmed_text
6530 { my $elt= shift;
6531 my $dest=$elt->first_child(@_) or return '';
6532 return $dest->trimmed_text;
6533 }
6534  
6535 sub first_child_matches
6536 { my $elt= shift;
6537 my $dest= $elt->{first_child} or return undef;
6538 return $dest->passes( @_);
6539 }
6540  
6541 sub last_child_text
6542 { my $elt= shift;
6543 my $dest=$elt->last_child(@_) or return '';
6544 return $dest->text;
6545 }
6546  
6547 sub last_child_trimmed_text
6548 { my $elt= shift;
6549 my $dest=$elt->last_child(@_) or return '';
6550 return $dest->trimmed_text;
6551 }
6552  
6553 sub last_child_matches
6554 { my $elt= shift;
6555 my $dest= $elt->{last_child} or return undef;
6556 return $dest->passes( @_);
6557 }
6558  
6559 sub child_text
6560 { my $elt= shift;
6561 my $dest=$elt->child(@_) or return '';
6562 return $dest->text;
6563 }
6564  
6565 sub child_trimmed_text
6566 { my $elt= shift;
6567 my $dest=$elt->child(@_) or return '';
6568 return $dest->trimmed_text;
6569 }
6570  
6571 sub child_matches
6572 { my $elt= shift;
6573 my $nb= shift;
6574 my $dest= $elt->child( $nb) or return undef;
6575 return $dest->passes( @_);
6576 }
6577  
6578 sub prev_sibling_text
6579 { my $elt= shift;
6580 my $dest= $elt->_prev_sibling(@_) or return '';
6581 return $dest->text;
6582 }
6583  
6584 sub prev_sibling_trimmed_text
6585 { my $elt= shift;
6586 my $dest= $elt->_prev_sibling(@_) or return '';
6587 return $dest->trimmed_text;
6588 }
6589  
6590 sub prev_sibling_matches
6591 { my $elt= shift;
6592 my $dest= $elt->{prev_sibling} or return undef;
6593 return $dest->passes( @_);
6594 }
6595  
6596 sub next_sibling_text
6597 { my $elt= shift;
6598 my $dest= $elt->next_sibling(@_) or return '';
6599 return $dest->text;
6600 }
6601  
6602 sub next_sibling_trimmed_text
6603 { my $elt= shift;
6604 my $dest= $elt->next_sibling(@_) or return '';
6605 return $dest->trimmed_text;
6606 }
6607  
6608 sub next_sibling_matches
6609 { my $elt= shift;
6610 my $dest= $elt->{next_sibling} or return undef;
6611 return $dest->passes( @_);
6612 }
6613  
6614 sub prev_elt_text
6615 { my $elt= shift;
6616 my $dest= $elt->prev_elt(@_) or return '';
6617 return $dest->text;
6618 }
6619  
6620 sub prev_elt_trimmed_text
6621 { my $elt= shift;
6622 my $dest= $elt->prev_elt(@_) or return '';
6623 return $dest->trimmed_text;
6624 }
6625  
6626 sub prev_elt_matches
6627 { my $elt= shift;
6628 my $dest= $elt->prev_elt or return undef;
6629 return $dest->passes( @_);
6630 }
6631  
6632 sub next_elt_text
6633 { my $elt= shift;
6634 my $dest= $elt->next_elt(@_) or return '';
6635 return $dest->text;
6636 }
6637  
6638 sub next_elt_trimmed_text
6639 { my $elt= shift;
6640 my $dest= $elt->next_elt(@_) or return '';
6641 return $dest->trimmed_text;
6642 }
6643  
6644 sub next_elt_matches
6645 { my $elt= shift;
6646 my $dest= $elt->next_elt or return undef;
6647 return $dest->passes( @_);
6648 }
6649  
6650 sub parent_text
6651 { my $elt= shift;
6652 my $dest= $elt->parent(@_) or return '';
6653 return $dest->text;
6654 }
6655  
6656 sub parent_trimmed_text
6657 { my $elt= shift;
6658 my $dest= $elt->parent(@_) or return '';
6659 return $dest->trimmed_text;
6660 }
6661  
6662 sub parent_matches
6663 { my $elt= shift;
6664 my $dest= $elt->{parent} or return undef;
6665 return $dest->passes( @_);
6666 }
6667  
6668 sub is_first_child
6669 { my $elt= shift;
6670 my $parent= $elt->{parent} or return 0;
6671 my $first_child= $parent->first_child( @_) or return 0;
6672 return ($first_child == $elt) ? $elt : 0;
6673 }
6674  
6675 sub is_last_child
6676 { my $elt= shift;
6677 my $parent= $elt->{parent} or return 0;
6678 my $last_child= $parent->last_child( @_) or return 0;
6679 return ($last_child == $elt) ? $elt : 0;
6680 }
6681  
6682 # returns the depth level of the element
6683 # if 2 parameter are used then counts the 2cd element name in the
6684 # ancestors list
6685 sub level
6686 { my( $elt, $cond)= @_;
6687 my $level=0;
6688 my $name=shift || '';
6689 while( $elt= $elt->{parent}) { $level++ if( !$cond || $elt->matches( $cond)); }
6690 return $level;
6691 }
6692  
6693 # checks whether $elt has an ancestor that satisfies $cond, returns the ancestor
6694 sub in_context
6695 { my ($elt, $cond, $level)= @_;
6696 $level= -1 unless( $level) ; # $level-- will never hit 0
6697  
6698 while( $level)
6699 { $elt= $elt->{parent} or return 0;
6700 if( $elt->matches( $cond)) { return $elt; }
6701 $level--;
6702 }
6703 return 0;
6704 }
6705  
6706 sub _descendants
6707 { my( $subtree_root, $include_self)= @_;
6708 my @descendants= $include_self ? ($subtree_root) : ();
6709  
6710 my $elt= $subtree_root;
6711 my $next_elt;
6712  
6713 MAIN: while( 1)
6714 { if( $next_elt= $elt->{first_child})
6715 { # simplest case: the elt has a child
6716 }
6717 elsif( $next_elt= $elt->{next_sibling})
6718 { # no child but a next sibling (just check we stay within the subtree)
6719  
6720 # case where elt is subtree_root, is empty and has a sibling
6721 last MAIN if( $elt == $subtree_root);
6722 }
6723 else
6724 { # case where the element has no child and no next sibling:
6725 # get the first next sibling of an ancestor, checking subtree_root
6726  
6727 # case where elt is subtree_root, is empty and has no sibling
6728 last MAIN if( $elt == $subtree_root);
6729  
6730 # backtrack until we find a parent with a next sibling
6731 $next_elt= $elt->{parent} || last;
6732 until( $next_elt->{next_sibling})
6733 { last MAIN if( $subtree_root == $next_elt);
6734 $next_elt= $next_elt->{parent} || last MAIN;
6735 }
6736 last MAIN if( $subtree_root == $next_elt);
6737 $next_elt= $next_elt->{next_sibling};
6738 }
6739 $elt= $next_elt || last MAIN;
6740 push @descendants, $elt;
6741 }
6742 return @descendants;
6743 }
6744  
6745 sub descendants
6746 { my( $subtree_root, $cond)= @_;
6747 my @descendants=();
6748 my $elt= $subtree_root;
6749  
6750 # this branch is pure optimization for speed: if $cond is a gi replace it
6751 # by the index of the gi and loop here
6752 # start optimization
6753 my $ind;
6754 if( !$cond || ( defined ( $ind= $XML::Twig::gi2index{$cond})) )
6755 {
6756 my $next_elt;
6757  
6758 while( 1)
6759 { if( $next_elt= $elt->{first_child})
6760 { # simplest case: the elt has a child
6761 }
6762 elsif( $next_elt= $elt->{next_sibling})
6763 { # no child but a next sibling (just check we stay within the subtree)
6764  
6765 # case where elt is subtree_root, is empty and has a sibling
6766 last if( $subtree_root && ($elt == $subtree_root));
6767 }
6768 else
6769 { # case where the element has no child and no next sibling:
6770 # get the first next sibling of an ancestor, checking subtree_root
6771  
6772 # case where elt is subtree_root, is empty and has no sibling
6773 last if( $subtree_root && ($elt == $subtree_root));
6774  
6775 # backtrack until we find a parent with a next sibling
6776 $next_elt= $elt->{parent} || last;
6777 until( $next_elt->{next_sibling})
6778 { last if( $subtree_root && ($subtree_root == $next_elt));
6779 $next_elt= $next_elt->{parent} || last;
6780 }
6781 last if( $subtree_root && ($subtree_root == $next_elt));
6782 $next_elt= $next_elt->{next_sibling};
6783 }
6784 $elt= $next_elt || last;
6785 push @descendants, $elt if( !$cond || ($elt->{gi} eq $ind));
6786 }
6787 }
6788 else
6789 # end optimization
6790 { # branch for a complex condition: use the regular (slow but simple) way
6791 while( $elt= $elt->next_elt( $subtree_root, $cond))
6792 { push @descendants, $elt; }
6793 }
6794 return @descendants;
6795 }
6796  
6797 sub descendants_or_self
6798 { my( $elt, $cond)= @_;
6799 my @descendants= $elt->passes( $cond) ? ($elt) : ();
6800 push @descendants, $elt->descendants( $cond);
6801 return @descendants;
6802 }
6803  
6804 sub sibling
6805 { my $elt= shift;
6806 my $nb= shift;
6807 if( $nb > 0)
6808 { foreach( 1..$nb)
6809 { $elt= $elt->next_sibling( @_) or return undef; }
6810 }
6811 elsif( $nb < 0)
6812 { foreach( 1..(-$nb))
6813 { $elt= $elt->prev_sibling( @_) or return undef; }
6814 }
6815 else # $nb == 0
6816 { return $elt->passes( $_[0]); }
6817 return $elt;
6818 }
6819  
6820 sub sibling_text
6821 { my $elt= sibling( @_);
6822 return $elt ? $elt->text : undef;
6823 }
6824  
6825 sub child
6826 { my $elt= shift;
6827 my $nb= shift;
6828 if( $nb >= 0)
6829 { $elt= $elt->first_child( @_) or return undef;
6830 foreach( 1..$nb)
6831 { $elt= $elt->next_sibling( @_) or return undef; }
6832 }
6833 else
6834 { $elt= $elt->last_child( @_) or return undef;
6835 foreach( 2..(-$nb))
6836 { $elt= $elt->prev_sibling( @_) or return undef; }
6837 }
6838 return $elt;
6839 }
6840  
6841 sub prev_siblings
6842 { my $elt= shift;
6843 my @siblings=();
6844 while( $elt= $elt->prev_sibling( @_))
6845 { unshift @siblings, $elt; }
6846 return @siblings;
6847 }
6848  
6849 sub siblings
6850 { my $elt= shift;
6851 return grep { $_ ne $elt } $elt->{parent}->children( @_);
6852 }
6853  
6854 sub pos
6855 { my $elt= shift;
6856 return 0 if ($_[0] && !$elt->matches( @_));
6857 my $pos=1;
6858 $pos++ while( $elt= $elt->prev_sibling( @_));
6859 return $pos;
6860 }
6861  
6862 sub next_siblings
6863 { my $elt= shift;
6864 my @siblings=();
6865 while( $elt= $elt->next_sibling( @_))
6866 { push @siblings, $elt; }
6867 return @siblings;
6868 }
6869  
6870 # used by get_xpath: parses the xpath expression and generates a sub that performs the
6871 # search
6872 { my %axis2method;
6873 BEGIN { %axis2method= ( child => 'children',
6874 descendant => 'descendants',
6875 'descendant-or-self' => 'descendants_or_self',
6876 parent => 'parent_is',
6877 ancestor => 'ancestors',
6878 'ancestor-or-self' => 'ancestors_or_self',
6879 'following-sibling' => 'next_siblings',
6880 'preceding-sibling' => 'prev_siblings',
6881 following => 'following_elts',
6882 preceding => 'preceding_elts',
6883 self => '_self',
6884 );
6885 }
6886  
6887 sub _install_xpath
6888 { my( $xpath_exp, $type)= @_;
6889 my $original_exp= $xpath_exp;
6890 my $sub= 'my $elt= shift; my @results;';
6891  
6892 # grab the root if expression starts with a /
6893 if( $xpath_exp=~ s{^/}{})
6894 { $sub .= '@results= ($elt->twig) || croak "cannot use an XPath query starting with a / on a node not attached to a whole twig";'; }
6895 elsif( $xpath_exp=~ s{^\./}{})
6896 { $sub .= '@results= ($elt);'; }
6897 else
6898 { $sub .= '@results= ($elt);'; }
6899  
6900 #warn "xpath_exp= '$xpath_exp'\n";
6901  
6902 while( $xpath_exp &&
6903 $xpath_exp=~s{^\s*(/?)
6904 # the xxx=~/regexp/ is a pain as it includes /
6905 (\s*(?:(?:($REG_AXIS)::)?(\*|$REG_TAG_PART|\.\.|\.)\s*)?($REG_PREDICATE_ALT*)
6906 )
6907 (/|$)}{}xo)
6908  
6909 { my( $wildcard, $sub_exp, $axis, $gi, $predicates)= ($1, $2, $3, $4, $5);
6910 if( $axis && ! $gi)
6911 { _croak_and_doublecheck_xpath( $original_exp, "error in xpath expression $original_exp"); }
6912  
6913 # grab a parent
6914 if( $sub_exp eq '..')
6915 { _croak_and_doublecheck_xpath( $original_exp, "error in xpath expression $original_exp") if( $wildcard);
6916 $sub .= '@results= map { $_->{parent}} @results;';
6917 }
6918 # test the element itself
6919 elsif( $sub_exp=~ m{^\.(.*)$}s)
6920 { $sub .= "\@results= grep { \$_->matches( q{$1}) } \@results;" }
6921 # grab children
6922 else
6923 {
6924 if( !$axis)
6925 { $axis= $wildcard ? 'descendant' : 'child'; }
6926 if( !$gi or $gi eq '*') { $gi=''; }
6927 my $function;
6928  
6929 # "special" predicates, that return just one element
6930 if( $predicates && ($predicates =~ m{^\s*\[\s*((-\s*)?\d+)\s*\]\s*$}))
6931 { # [<nb>]
6932 my $offset= $1;
6933 $offset-- if( $offset > 0);
6934 $function= $axis eq 'descendant' ? "next_n_elt( $offset, '$gi')"
6935 : $axis eq 'child' ? "child( $offset, '$gi')"
6936 : _croak_and_doublecheck_xpath( $original_exp, "error [$1] not supported along axis '$axis'")
6937 ;
6938 $sub .= "\@results= grep { \$_ } map { \$_->$function } \@results;"
6939 }
6940 elsif( $predicates && ($predicates =~ m{^\s*\[\s*last\s*\(\s*\)\s*\]\s*$}) )
6941 { # last()
6942 _croak_and_doublecheck_xpath( $original_exp, "error in xpath expression $original_exp, usage of // and last() not supported") if( $wildcard);
6943 $sub .= "\@results= map { \$_->last_child( '$gi') } \@results;";
6944 }
6945 else
6946 { # follow the axis
6947 #warn "axis: '$axis' - method: '$axis2method{$axis}' - gi: '$gi'\n";
6948  
6949 my $follow_axis= " \$_->$axis2method{$axis}( '$gi')";
6950 my $step= $follow_axis;
6951  
6952 # now filter using the predicate
6953 while( $predicates=~ s{^\s*($REG_PREDICATE_ALT)\s*}{}o)
6954 { my $pred= $1;
6955 $pred=~ s{^\s*\[\s*}{};
6956 $pred=~ s{\s*\]\s*$}{};
6957 my $test="";
6958 my $pos;
6959 if( $pred=~ m{^(-?\s*\d+)$})
6960 { my $pos= $1;
6961 if( $step=~ m{^\s*grep(.*) (\$_->\w+\(\s*'[^']*'\s*\))})
6962 { $step= "XML::Twig::_first_n $1 $pos, $2"; }
6963 else
6964 { if( $pos > 0) { $pos--; }
6965 $step= "($step)[$pos]";
6966 }
6967 #warn "number predicate '$pos' - generated step '$step'\n";
6968 }
6969 else
6970 { my $syntax_error=0;
6971 do
6972 { if( $pred =~ s{^string\(\s*\)\s*=\s*($REG_STRING)\s*}{}o) # string()="string" pred
6973 { $test .= "\$_->text eq $1"; }
6974 elsif( $pred =~ s{^string\(\s*\)\s*!=\s*($REG_STRING)\s*}{}o) # string()!="string" pred
6975 { $test .= "\$_->text ne $1"; }
6976 if( $pred =~ s{^string\(\s*\)\s*=\s*($REG_NUMBER)\s*}{}o) # string()=<number> pred
6977 { $test .= "\$_->text eq $1"; }
6978 elsif( $pred =~ s{^string\(\s*\)\s*!=\s*($REG_NUMBER)\s*}{}o) # string()!=<number> pred
6979 { $test .= "\$_->text ne $1"; }
6980 elsif( $pred =~ s{^string\(\s*\)\s*(>|<|>=|<=)\s*($REG_NUMBER)\s*}{}o) # string()!=<number> pred
6981 { $test .= "\$_->text $1 $2"; }
6982  
6983 elsif( $pred =~ s{^string\(\s*\)\s*($REG_MATCH)\s*($REG_REGEXP)\s*}{}o) # string()=~/regex/ pred
6984 { my( $match, $regexp)= ($1, $2);
6985 $test .= "\$_->text $match $regexp";
6986 }
6987 elsif( $pred =~ s{^string\(\s*\)\s*}{}o) # string() pred
6988 { $test .= "\$_->text"; }
6989 elsif( $pred=~ s{^@($REG_TAG_NAME)\s*($REG_OP)\s*($REG_STRING|$REG_NUMBER)}{}o) # @att="val" pred
6990 { my( $att, $oper, $val)= ($1, _op( $2), $3);
6991 $test .= qq{((defined \$_->{'att'}->{"$att"}) && (\$_->{'att'}->{"$att"} $oper $val))};
6992 }
6993 elsif( $pred =~ s{^@($REG_TAG_NAME)\s*($REG_MATCH)\s*($REG_REGEXP)\s*}{}o) # @att=~/regex/ pred XXX
6994 { my( $att, $match, $regexp)= ($1, $2, $3);
6995 $test .= qq{((defined \$_->{'att'}->{"$att"}) && (\$_->{'att'}->{"$att"} $match $regexp))};;
6996 }
6997 elsif( $pred=~ s{^@($REG_TAG_NAME)\s*}{}o) # @att pred
6998 { $test .= qq{(defined \$_->{'att'}->{"$1"})}; }
6999 elsif( $pred=~ s{^\s*(?:not|!)\s*@($REG_TAG_NAME)\s*}{}o) # not @att pred
7000 { $test .= qq{((\$_->is_elt) && (not defined \$_->{'att'}->{"$1"}))}; }
7001 elsif( $pred=~ s{^\s*([()])}{}) # ( or ) (just add to the test)
7002 { $test .= qq{$1}; }
7003 elsif( $pred=~ s{^\s*(and|or)\s*}{})
7004 { $test .= lc " $1 "; }
7005 else
7006 { $syntax_error=1; }
7007  
7008 } while( !$syntax_error && $pred);
7009 _croak_and_doublecheck_xpath( $original_exp, "error in xpath expression $original_exp at $pred") if( $pred);
7010 $step= " grep { $test } $step ";
7011 }
7012 }
7013 #warn "step: '$step'";
7014 $sub .= "\@results= grep defined, map { $step } \@results;";
7015 }
7016 }
7017 }
7018  
7019 if( $xpath_exp)
7020 { _croak_and_doublecheck_xpath( $original_exp, "error in xpath expression $original_exp around $xpath_exp"); }
7021  
7022 $sub .= q{return XML::Twig::_unique_elts( @results); };
7023 #warn "generated: '$sub'\n";
7024 my $s= eval "sub { $NO_WARNINGS; $sub }"; ## no critic (ProhibitStringyEval)
7025 if( $@)
7026 { _croak_and_doublecheck_xpath( $original_exp, "error in xpath expression $original_exp ($@);") }
7027 return( $s);
7028 }
7029 }
7030  
7031 sub _croak_and_doublecheck_xpath
7032 { my $xpath_expression= shift;
7033 my $mess= join( "\n", @_);
7034 if( $XML::Twig::XPath::VERSION || 0)
7035 { my $check_twig= XML::Twig::XPath->new;
7036 if( eval { $check_twig->{twig_xp}->_parse( $xpath_expression) })
7037 { $mess .= "\nthe expression is a valid XPath statement, and you are using XML::Twig::XPath, but"
7038 . "\nyou are using either 'find_nodes' or 'get_xpath' where the method you likely wanted"
7039 . "\nto use is 'findnodes', which is the only one that uses the full XPath engine"
7040 . "\nalternatively, check that the main twig is an XML::Twig::XPath object,"
7041 . "\n and not just an XML::Twig object"
7042 . "\n"
7043 ;
7044 }
7045 }
7046 croak $mess;
7047 }
7048  
7049 { # extremely elaborate caching mechanism
7050 my %xpath; # xpath_expression => subroutine_code;
7051 sub get_xpath
7052 { my( $elt, $xpath_exp, $offset)= @_;
7053 my $sub= ($xpath{$xpath_exp} ||= _install_xpath( $xpath_exp));
7054 return $sub->( $elt) unless( defined $offset);
7055 my @res= $sub->( $elt);
7056 return $res[$offset];
7057 }
7058 }
7059  
7060 sub findvalues
7061 { my $elt= shift;
7062 return map { $_->text } $elt->get_xpath( @_);
7063 }
7064  
7065 sub findvalue
7066 { my $elt= shift;
7067 return join '', map { $_->text } $elt->get_xpath( @_);
7068 }
7069  
7070 # XML::XPath compatibility
7071 sub getElementById { return $_[0]->twig->elt_id( $_[1]); }
7072 sub getChildNodes { my @children= do { my $elt= $_[0]; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; }; return wantarray ? @children : \@children; }
7073  
7074 sub _flushed { return $_[0]->{flushed}; }
7075 sub _set_flushed { $_[0]->{flushed}=1; }
7076 sub _del_flushed { delete $_[0]->{flushed}; }
7077  
7078 sub cut
7079 { my $elt= shift;
7080 my( $parent, $prev_sibling, $next_sibling);
7081 $parent= $elt->{parent};
7082 if( ! $parent && $elt->is_elt)
7083 { # are we cutting the root?
7084 my $t= $elt->{twig};
7085 if( $t && ! $t->{twig_parsing})
7086 { delete $t->{twig_root};
7087 delete $elt->{twig};
7088 return $elt;
7089 } # cutt`ing the root
7090 else
7091 { return; } # cutting an orphan, returning $elt would break backward compatibility
7092 }
7093  
7094 # save the old links, that'll make it easier for some loops
7095 foreach my $link ( qw(parent prev_sibling next_sibling) )
7096 { $elt->{former}->{$link}= $elt->{$link};
7097 if( $XML::Twig::weakrefs) { weaken( $elt->{former}->{$link}); }
7098 }
7099  
7100 # if we cut the current element then its parent becomes the current elt
7101 if( $elt->{twig_current})
7102 { my $twig_current= $elt->{parent};
7103 $elt->twig->{twig_current}= $twig_current;
7104 $twig_current->{'twig_current'}=1;
7105 delete $elt->{'twig_current'};
7106 }
7107  
7108 if( $parent->{first_child} && $parent->{first_child} == $elt)
7109 { $parent->{first_child}= $elt->{next_sibling};
7110 # cutting can make the parent empty
7111 if( ! $parent->{first_child}) { $parent->{empty}= 1; }
7112 }
7113  
7114 if( $parent->{last_child} && $parent->{last_child} == $elt)
7115 { delete $parent->{empty}; $parent->{last_child}=$elt->{prev_sibling}; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ;
7116 }
7117  
7118 if( $prev_sibling= $elt->{prev_sibling})
7119 { $prev_sibling->{next_sibling}= $elt->{next_sibling}; }
7120 if( $next_sibling= $elt->{next_sibling})
7121 { $next_sibling->{prev_sibling}=$elt->{prev_sibling}; if( $XML::Twig::weakrefs) { weaken( $next_sibling->{prev_sibling});} ; }
7122  
7123 $elt->{parent}=undef; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
7124 $elt->{prev_sibling}=undef; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
7125 $elt->{next_sibling}= undef;
7126  
7127 # merge 2 (now) consecutive text nodes if they are of the same type
7128 # (type can be PCDATA or CDATA)
7129 if( $prev_sibling && $next_sibling && $prev_sibling->is_text && ( $XML::Twig::index2gi[$prev_sibling->{'gi'}] eq $XML::Twig::index2gi[$next_sibling->{'gi'}]))
7130 { $prev_sibling->merge_text( $next_sibling); }
7131  
7132 return $elt;
7133 }
7134  
7135 sub former_next_sibling { return $_[0]->{former}->{next_sibling}; }
7136 sub former_prev_sibling { return $_[0]->{former}->{prev_sibling}; }
7137 sub former_parent { return $_[0]->{former}->{parent}; }
7138  
7139 sub cut_children
7140 { my( $elt, $exp)= @_;
7141 my @children= $elt->children( $exp);
7142 foreach (@children) { $_->cut; }
7143 if( ! $elt->has_children) { $elt->{empty}= 1; }
7144 return @children;
7145 }
7146  
7147 sub cut_descendants
7148 { my( $elt, $exp)= @_;
7149 my @descendants= $elt->descendants( $exp);
7150 foreach ($elt->descendants( $exp)) { $_->cut; }
7151 if( ! $elt->has_children) { $elt->{empty}= 1; }
7152 return @descendants;
7153 }
7154  
7155 sub erase
7156 { my $elt= shift;
7157 #you cannot erase the current element
7158 if( $elt->{twig_current})
7159 { croak "trying to erase an element before it has been completely parsed"; }
7160 if( my $parent= $elt->{parent})
7161 { # normal case
7162 $elt->_move_extra_data_after_erase;
7163 my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
7164 if( @children)
7165 {
7166 # elt has children, move them up
7167  
7168 # the first child may need to be merged with a previous text
7169 my $first_child= shift @children;
7170 $first_child->move( before => $elt);
7171 my $prev= $first_child->{prev_sibling};
7172 if( $prev && $prev->is_text && ($XML::Twig::index2gi[$first_child->{'gi'}] eq $XML::Twig::index2gi[$prev->{'gi'}]) )
7173 { $prev->merge_text( $first_child); }
7174  
7175 # move the rest of the children
7176 foreach my $child (@children)
7177 { $child->move( before => $elt); }
7178  
7179 # now the elt had no child, delete it
7180 $elt->delete;
7181  
7182 # now see if we need to merge the last child with the next element
7183 my $last_child= $children[-1] || $first_child; # if no last child, then it's also the first child
7184 my $next= $last_child->{next_sibling};
7185 if( $next && $next->is_text && ($XML::Twig::index2gi[$last_child->{'gi'}] eq $XML::Twig::index2gi[$next->{'gi'}]) )
7186 { $last_child->merge_text( $next); }
7187  
7188 # if parsing and have now a PCDATA text, mark so we can normalize later on if need be
7189 if( $parent->{twig_current} && $last_child->is_text) { $parent->{twig_to_be_normalized}=1; }
7190 }
7191 else
7192 { # no children, just cut the elt
7193 $elt->delete;
7194 }
7195 }
7196 else
7197 { # trying to erase the root (of a twig or of a cut/new element)
7198 my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
7199 unless( @children == 1)
7200 { croak "can only erase an element with no parent if it has a single child"; }
7201 $elt->_move_extra_data_after_erase;
7202 my $child= shift @children;
7203 $child->{parent}=undef; if( $XML::Twig::weakrefs) { weaken( $child->{parent});} ;
7204 my $twig= $elt->twig;
7205 $twig->set_root( $child);
7206 }
7207  
7208 return $elt;
7209  
7210 }
7211  
7212 sub _move_extra_data_after_erase
7213 { my( $elt)= @_;
7214 # extra_data
7215 if( my $extra_data= $elt->{extra_data})
7216 { my $target= $elt->{first_child} || $elt->{next_sibling};
7217 if( $target)
7218 {
7219 if( $target->is( $ELT))
7220 { $target->set_extra_data( $extra_data . ($target->extra_data || '')); }
7221 elsif( $target->is( $TEXT))
7222 { $target->_unshift_extra_data_in_pcdata( $extra_data, 0); } # TO CHECK
7223 }
7224 else
7225 { my $parent= $elt->{parent}; # always exists or the erase cannot be performed
7226 $parent->_prefix_extra_data_before_end_tag( $extra_data);
7227 }
7228 }
7229  
7230 # extra_data_before_end_tag
7231 if( my $extra_data= $elt->{extra_data_before_end_tag})
7232 { if( my $target= $elt->{next_sibling})
7233 { if( $target->is( $ELT))
7234 { $target->set_extra_data( $extra_data . ($target->extra_data || '')); }
7235 elsif( $target->is( $TEXT))
7236 {
7237 $target->_unshift_extra_data_in_pcdata( $extra_data, 0);
7238 }
7239 }
7240 elsif( my $parent= $elt->{parent})
7241 { $parent->_prefix_extra_data_before_end_tag( $extra_data); }
7242 }
7243  
7244 return $elt;
7245  
7246 }
7247 BEGIN
7248 { my %method= ( before => \&paste_before,
7249 after => \&paste_after,
7250 first_child => \&paste_first_child,
7251 last_child => \&paste_last_child,
7252 within => \&paste_within,
7253 );
7254  
7255 # paste elt somewhere around ref
7256 # pos can be first_child (default), last_child, before, after or within
7257 sub paste ## no critic (Subroutines::ProhibitNestedSubs);
7258 { my $elt= shift;
7259 if( $elt->{parent})
7260 { croak "cannot paste an element that belongs to a tree"; }
7261 my $pos;
7262 my $ref;
7263 if( ref $_[0])
7264 { $pos= 'first_child';
7265 croak "wrong argument order in paste, should be $_[1] first" if($_[1]);
7266 }
7267 else
7268 { $pos= _op_position(shift); }
7269  
7270 if( my $method= $method{$pos})
7271 {
7272 unless( ref( $_[0]) && isa( $_[0], 'XML::Twig::Elt'))
7273 { if( ! defined( $_[0]))
7274 { croak "missing target in paste"; }
7275 elsif( ! ref( $_[0]))
7276 { croak "wrong target type in paste (not a reference), should be XML::Twig::Elt or a subclass"; }
7277 else
7278 { my $ref= ref $_[0];
7279 croak "wrong target type in paste: '$ref', should be XML::Twig::Elt or a subclass";
7280 }
7281 }
7282 $ref= $_[0];
7283 # check here so error message lists the caller file/line
7284 if( !$ref->{parent} && ($pos=~ m{^(before|after)$}) && !(exists $elt->{'target'}) && !(exists $elt->{'comment'}))
7285 { croak "cannot paste $1 root"; }
7286 $elt->$method( @_);
7287 }
7288 else
7289 { croak "tried to paste in wrong position '$pos', allowed positions are "
7290 . _allowed_positions() . ".\n";
7291 }
7292 if( (my $ids= $elt->{twig_id_list}) && (my $t= $ref->twig) )
7293 { $t->{twig_id_list}||={};
7294 foreach my $id (keys %$ids)
7295 { $t->{twig_id_list}->{$id}= $ids->{$id};
7296 if( $XML::Twig::weakrefs) { weaken( $t->{twig_id_list}->{$id}); }
7297 }
7298 }
7299 return $elt;
7300 }
7301  
7302 sub paste_before
7303 { my( $elt, $ref)= @_;
7304 my( $parent, $prev_sibling, $next_sibling );
7305  
7306 # trying to paste before an orphan (root or detached wlt)
7307 unless( $ref->{parent})
7308 { if( my $t= $ref->twig)
7309 { if( (exists $elt->{'comment'}) || (exists $elt->{'target'})) # we can still do this
7310 { $t->_add_cpi_outside_of_root( leading_cpi => $elt); return; }
7311 else
7312 { croak "cannot paste before root"; }
7313 }
7314 else
7315 { croak "cannot paste before an orphan element"; }
7316 }
7317 $parent= $ref->{parent};
7318 $prev_sibling= $ref->{prev_sibling};
7319 $next_sibling= $ref;
7320  
7321 $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
7322 if( $parent->{first_child} == $ref) { $parent->{first_child}= $elt; }
7323  
7324 if( $prev_sibling) { $prev_sibling->{next_sibling}= $elt; }
7325 $elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
7326  
7327 $next_sibling->{prev_sibling}=$elt; if( $XML::Twig::weakrefs) { weaken( $next_sibling->{prev_sibling});} ;
7328 $elt->{next_sibling}= $ref;
7329 return $elt;
7330 }
7331  
7332 sub paste_after
7333 { my( $elt, $ref)= @_;
7334 my( $parent, $prev_sibling, $next_sibling );
7335  
7336 # trying to paste after an orphan (root or detached wlt)
7337 unless( $ref->{parent})
7338 { if( my $t= $ref->twig)
7339 { if( (exists $elt->{'comment'}) || (exists $elt->{'target'})) # we can still do this
7340 { $t->_add_cpi_outside_of_root( trailing_cpi => $elt); return; }
7341 else
7342 { croak "cannot paste after root"; }
7343 }
7344 else
7345 { croak "cannot paste after an orphan element"; }
7346 }
7347 $parent= $ref->{parent};
7348 $prev_sibling= $ref;
7349 $next_sibling= $ref->{next_sibling};
7350  
7351 $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
7352 if( $parent->{last_child}== $ref) { delete $parent->{empty}; $parent->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ; }
7353  
7354 $prev_sibling->{next_sibling}= $elt;
7355 $elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
7356  
7357 if( $next_sibling) { $next_sibling->{prev_sibling}=$elt; if( $XML::Twig::weakrefs) { weaken( $next_sibling->{prev_sibling});} ; }
7358 $elt->{next_sibling}= $next_sibling;
7359 return $elt;
7360  
7361 }
7362  
7363 sub paste_first_child
7364 { my( $elt, $ref)= @_;
7365 my( $parent, $prev_sibling, $next_sibling );
7366 $parent= $ref;
7367 $next_sibling= $ref->{first_child};
7368  
7369 $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
7370 $parent->{first_child}= $elt;
7371 unless( $parent->{last_child}) { delete $parent->{empty}; $parent->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ; }
7372  
7373 $elt->{prev_sibling}=undef; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
7374  
7375 if( $next_sibling) { $next_sibling->{prev_sibling}=$elt; if( $XML::Twig::weakrefs) { weaken( $next_sibling->{prev_sibling});} ; }
7376 $elt->{next_sibling}= $next_sibling;
7377 return $elt;
7378 }
7379  
7380 sub paste_last_child
7381 { my( $elt, $ref)= @_;
7382 my( $parent, $prev_sibling, $next_sibling );
7383 $parent= $ref;
7384 $prev_sibling= $ref->{last_child};
7385  
7386 $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
7387 delete $parent->{empty}; $parent->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ;
7388 unless( $parent->{first_child}) { $parent->{first_child}= $elt; }
7389  
7390 $elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
7391 if( $prev_sibling) { $prev_sibling->{next_sibling}= $elt; }
7392  
7393 $elt->{next_sibling}= undef;
7394 return $elt;
7395 }
7396  
7397 sub paste_within
7398 { my( $elt, $ref, $offset)= @_;
7399 my $text= $ref->is_text ? $ref : $ref->next_elt( $TEXT, $ref);
7400 my $new= $text->split_at( $offset);
7401 $elt->paste_before( $new);
7402 return $elt;
7403 }
7404 }
7405  
7406 # load an element into a structure similar to XML::Simple's
7407 sub simplify
7408 { my $elt= shift;
7409  
7410 # normalize option names
7411 my %options= @_;
7412 %options= map { my ($key, $val)= ($_, $options{$_});
7413 $key=~ s{(\w)([A-Z])}{$1_\L$2}g;
7414 $key => $val
7415 } keys %options;
7416  
7417 # check options
7418 my @allowed_options= qw( keyattr forcearray noattr content_key
7419 var var_regexp variables var_attr
7420 group_tags forcecontent
7421 normalise_space normalize_space
7422 );
7423 my %allowed_options= map { $_ => 1 } @allowed_options;
7424 foreach my $option (keys %options)
7425 { carp "invalid option $option\n" unless( $allowed_options{$option}); }
7426  
7427 $options{normalise_space} ||= $options{normalize_space} || 0;
7428  
7429 $options{content_key} ||= 'content';
7430 if( $options{content_key}=~ m{^-})
7431 { # need to remove the - and to activate extra folding
7432 $options{content_key}=~ s{^-}{};
7433 $options{extra_folding}= 1;
7434 }
7435 else
7436 { $options{extra_folding}= 0; }
7437  
7438 $options{forcearray} ||=0;
7439 if( isa( $options{forcearray}, 'ARRAY'))
7440 { my %forcearray_tags= map { $_ => 1 } @{$options{forcearray}};
7441 $options{forcearray_tags}= \%forcearray_tags;
7442 $options{forcearray}= 0;
7443 }
7444  
7445 $options{keyattr} ||= ['name', 'key', 'id'];
7446 if( ref $options{keyattr} eq 'ARRAY')
7447 { foreach my $keyattr (@{$options{keyattr}})
7448 { my( $prefix, $att)= ($keyattr=~ m{^([+-])?(.*)});
7449 $prefix ||= '';
7450 $options{key_for_all}->{$att}= 1;
7451 $options{remove_key_for_all}->{$att}=1 unless( $prefix eq '+');
7452 $options{prefix_key_for_all}->{$att}=1 if( $prefix eq '-');
7453 }
7454 }
7455 elsif( ref $options{keyattr} eq 'HASH')
7456 { while( my( $elt, $keyattr)= each %{$options{keyattr}})
7457 { my( $prefix, $att)= ($keyattr=~ m{^([+-])?(.*)});
7458 $prefix ||='';
7459 $options{key_for_elt}->{$elt}= $att;
7460 $options{remove_key_for_elt}->{"$elt#$att"}=1 unless( $prefix);
7461 $options{prefix_key_for_elt}->{"$elt#$att"}=1 if( $prefix eq '-');
7462 }
7463 }
7464  
7465 $options{var}||= $options{var_attr}; # for compat with XML::Simple
7466 if( $options{var}) { $options{var_values}= {}; }
7467 else { $options{var}=''; }
7468  
7469 if( $options{variables})
7470 { $options{var}||= 1;
7471 $options{var_values}= $options{variables};
7472 }
7473  
7474 if( $options{var_regexp} and !$options{var})
7475 { warn "var option not used, var_regexp option ignored\n"; }
7476 $options{var_regexp} ||= '\$\{?(\w+)\}?';
7477  
7478 $elt->_simplify( \%options);
7479  
7480 }
7481  
7482 sub _simplify
7483 { my( $elt, $options)= @_;
7484  
7485 my $data;
7486  
7487 my $gi= $XML::Twig::index2gi[$elt->{'gi'}];
7488 my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
7489 my %atts= $options->{noattr} || !$elt->{att} ? () : %{$elt->{att}};
7490 my $nb_atts= keys %atts;
7491 my $nb_children= $elt->children_count + $nb_atts;
7492  
7493 my %nb_children;
7494 foreach (@children) { $nb_children{$_->tag}++; }
7495 foreach (keys %atts) { $nb_children{$_}++; }
7496  
7497 my $arrays; # tag => array where elements are stored
7498  
7499 # store children
7500 foreach my $child (@children)
7501 { if( $child->is_text)
7502 { # generate with a content key
7503 my $text= $elt->_text_with_vars( $options);
7504 if( $options->{normalise_space} >= 2) { $text= _normalize_space( $text); }
7505 if( $options->{force_content}
7506 || $nb_atts
7507 || (scalar @children > 1)
7508 )
7509 { $data->{$options->{content_key}}= $text; }
7510 else
7511 { $data= $text; }
7512 }
7513 else
7514 { # element with sub-elements
7515 my $child_gi= $XML::Twig::index2gi[$child->{'gi'}];
7516  
7517 my $child_data= $child->_simplify( $options);
7518  
7519 # first see if we need to simplify further the child data
7520 # simplify because of grouped tags
7521 if( my $grouped_tag= $options->{group_tags}->{$child_gi})
7522 { # check that the child data is a hash with a single field
7523 unless( (ref( $child_data) eq 'HASH')
7524 && (keys %$child_data == 1)
7525 && defined ( my $grouped_child_data= $child_data->{$grouped_tag})
7526 )
7527 { croak "error in grouped tag $child_gi"; }
7528 else
7529 { $child_data= $grouped_child_data; }
7530 }
7531 # simplify because of extra folding
7532 if( $options->{extra_folding})
7533 { if( (ref( $child_data) eq 'HASH')
7534 && (keys %$child_data == 1)
7535 && defined( my $content= $child_data->{$options->{content_key}})
7536 )
7537 { $child_data= $content; }
7538 }
7539  
7540 if( my $keyatt= $child->_key_attr( $options))
7541 { # simplify element with key
7542 my $key= $child->{'att'}->{$keyatt};
7543 if( $options->{normalise_space} >= 1) { $key= _normalize_space( $key); }
7544 $data->{$child_gi}->{$key}= $child_data;
7545 }
7546 elsif( $options->{forcearray}
7547 || $options->{forcearray_tags}->{$child_gi}
7548 || ( $nb_children{$child_gi} > 1)
7549 )
7550 { # simplify element to store in an array
7551 if( defined $child_data && $child_data ne "" )
7552 { $data->{$child_gi} ||= [];
7553 push @{$data->{$child_gi}}, $child_data;
7554 }
7555 else
7556 { $data->{$child_gi}= [{}]; }
7557 }
7558 else
7559 { # simplify element to store as a hash field
7560 $data->{$child_gi}=$child_data;
7561 $data->{$child_gi}= defined $child_data && $child_data ne "" ? $child_data : {};
7562 }
7563 }
7564 }
7565  
7566 # store atts
7567 # TODO: deal with att that already have an element by that name
7568 foreach my $att (keys %atts)
7569 { # do not store if the att is a key that needs to be removed
7570 if( $options->{remove_key_for_all}->{$att}
7571 || $options->{remove_key_for_elt}->{"$gi#$att"}
7572 )
7573 { next; }
7574  
7575 my $att_text= $options->{var} ? _replace_vars_in_text( $atts{$att}, $options) : $atts{$att} ;
7576 if( $options->{normalise_space} >= 2) { $att_text= _normalize_space( $att_text); }
7577  
7578 if( $options->{prefix_key_for_all}->{$att}
7579 || $options->{prefix_key_for_elt}->{"$gi#$att"}
7580 )
7581 { # prefix the att
7582 $data->{"-$att"}= $att_text;
7583 }
7584 else
7585 { # normal case
7586 $data->{$att}= $att_text;
7587 }
7588 }
7589  
7590 return $data;
7591 }
7592  
7593 sub _key_attr
7594 { my( $elt, $options)=@_;
7595 return if( $options->{noattr});
7596 if( $options->{key_for_all})
7597 { foreach my $att ($elt->att_names)
7598 { if( $options->{key_for_all}->{$att})
7599 { return $att; }
7600 }
7601 }
7602 elsif( $options->{key_for_elt})
7603 { if( my $key_for_elt= $options->{key_for_elt}->{$XML::Twig::index2gi[$elt->{'gi'}]} )
7604 { return $key_for_elt if( defined( $elt->{'att'}->{$key_for_elt})); }
7605 }
7606 return;
7607 }
7608  
7609 sub _text_with_vars
7610 { my( $elt, $options)= @_;
7611 my $text;
7612 if( $options->{var})
7613 { $text= _replace_vars_in_text( $elt->text, $options);
7614 $elt->_store_var( $options);
7615 }
7616 else
7617 { $text= $elt->text; }
7618 return $text;
7619 }
7620  
7621 sub _normalize_space
7622 { my $text= shift;
7623 $text=~ s{\s+}{ }sg;
7624 $text=~ s{^\s}{};
7625 $text=~ s{\s$}{};
7626 return $text;
7627 }
7628  
7629 sub att_nb
7630 { return 0 unless( my $atts= $_[0]->{att});
7631 return scalar keys %$atts;
7632 }
7633  
7634 sub has_no_atts
7635 { return 1 unless( my $atts= $_[0]->{att});
7636 return scalar keys %$atts ? 0 : 1;
7637 }
7638  
7639 sub _replace_vars_in_text
7640 { my( $text, $options)= @_;
7641  
7642 $text=~ s{($options->{var_regexp})}
7643 { if( defined( my $value= $options->{var_values}->{$2}))
7644 { $value }
7645 else
7646 { warn "unknown variable $2\n";
7647 $1
7648 }
7649 }gex;
7650 return $text;
7651 }
7652  
7653 sub _store_var
7654 { my( $elt, $options)= @_;
7655 if( defined (my $var_name= $elt->{'att'}->{$options->{var}}))
7656 { $options->{var_values}->{$var_name}= $elt->text;
7657 }
7658 }
7659  
7660 # split a text element at a given offset
7661 sub split_at
7662 { my( $elt, $offset)= @_;
7663 my $text_elt= $elt->is_text ? $elt : $elt->first_child( $TEXT) || return '';
7664 my $string= $text_elt->text;
7665 my $left_string= substr( $string, 0, $offset);
7666 my $right_string= substr( $string, $offset);
7667 $text_elt->{pcdata}= (delete $text_elt->{empty} || 1) && $left_string;
7668 my $new_elt= $elt->new( $XML::Twig::index2gi[$elt->{'gi'}], $right_string);
7669 $new_elt->paste( after => $elt);
7670 return $new_elt;
7671 }
7672  
7673 # split an element or its text descendants into several, in place
7674 # all elements (new and untouched) are returned
7675 sub split
7676 { my $elt= shift;
7677 my @text_chunks;
7678 my @result;
7679 if( $elt->is_text) { @text_chunks= ($elt); }
7680 else { @text_chunks= $elt->descendants( $TEXT); }
7681 foreach my $text_chunk (@text_chunks)
7682 { push @result, $text_chunk->_split( 1, @_); }
7683 return @result;
7684 }
7685  
7686 # split an element or its text descendants into several, in place
7687 # created elements (those which match the regexp) are returned
7688 sub mark
7689 { my $elt= shift;
7690 my @text_chunks;
7691 my @result;
7692 if( $elt->is_text) { @text_chunks= ($elt); }
7693 else { @text_chunks= $elt->descendants( $TEXT); }
7694 foreach my $text_chunk (@text_chunks)
7695 { push @result, $text_chunk->_split( 0, @_); }
7696 return @result;
7697 }
7698  
7699 # split a single text element
7700 # return_all defines what is returned: if it is true
7701 # only returns the elements created by matches in the split regexp
7702 # otherwise all elements (new and untouched) are returned
7703 {
7704  
7705 sub _split
7706 { my $elt= shift;
7707 my $return_all= shift;
7708 my $regexp= shift;
7709 my @tags;
7710  
7711 while( @_)
7712 { my $tag= shift();
7713 if( ref $_[0])
7714 { push @tags, { tag => $tag, atts => shift }; }
7715 else
7716 { push @tags, { tag => $tag }; }
7717 }
7718  
7719 unless( @tags) { @tags= { tag => $elt->{parent}->gi }; }
7720  
7721 my @result; # the returned list of elements
7722 my $text= $elt->text;
7723 my $gi= $XML::Twig::index2gi[$elt->{'gi'}];
7724  
7725 # 2 uses: if split matches then the first substring reuses $elt
7726 # once a split has occurred then the last match needs to be put in
7727 # a new element
7728 my $previous_match= 0;
7729  
7730 while( my( $pre_match, @matches)= $text=~ /^(.*?)$regexp(.*)$/gcs)
7731 { $text= pop @matches;
7732 if( $previous_match)
7733 { # match, not the first one, create a new text ($gi) element
7734 $elt= $elt->insert_new_elt( after => $gi, $pre_match);
7735 push @result, $elt if( $return_all);
7736 }
7737 else
7738 { # first match in $elt, re-use $elt for the first sub-string
7739 $elt->set_text( $pre_match);
7740 $previous_match++; # store the fact that there was a match
7741 push @result, $elt if( $return_all);
7742 }
7743  
7744 # now deal with matches captured in the regexp
7745 if( @matches)
7746 { # match, with capture
7747 my $i=0;
7748 foreach my $match (@matches)
7749 { # create new element, text is the match
7750 my $tag = _repl_match( $tags[$i]->{tag}, @matches) || '#PCDATA';
7751 my $atts = \%{$tags[$i]->{atts}} || {};
7752 my %atts= map { _repl_match( $_, @matches) => _repl_match( $atts->{$_}, @matches) } keys %$atts;
7753 $elt= $elt->insert_new_elt( after => $tag, \%atts, $match);
7754 push @result, $elt;
7755 $i= ($i + 1) % @tags;
7756 }
7757 }
7758 else
7759 { # match, no captures
7760 my $tag = $tags[0]->{tag};
7761 my $atts = \%{$tags[0]->{atts}} || {};
7762 $elt= $elt->insert_new_elt( after => $tag, $atts);
7763 push @result, $elt;
7764 }
7765 }
7766 if( $previous_match && $text)
7767 { # there was at least 1 match, and there is text left after the match
7768 $elt= $elt->insert_new_elt( after => $gi, $text);
7769 }
7770  
7771 push @result, $elt if( $return_all);
7772  
7773 return @result; # return all elements
7774 }
7775  
7776 sub _repl_match
7777 { my( $val, @matches)= @_;
7778 $val=~ s{\$(\d+)}{$matches[$1-1]}g;
7779 return $val;
7780 }
7781  
7782 }
7783  
7784 { my %replace_sub; # cache for complex expressions (expression => sub)
7785  
7786 sub subs_text
7787 { my( $elt, $regexp, $replace)= @_;
7788  
7789 my $replacement_string;
7790 my $is_string= _is_string( $replace);
7791  
7792 my @parents;
7793  
7794 foreach my $text_elt ($elt->descendants_or_self( $TEXT))
7795 {
7796 if( $is_string)
7797 { my $text= $text_elt->text;
7798 $text=~ s{$regexp}{ _replace_var( $replace, $1, $2, $3, $4, $5, $6, $7, $8, $9)}egx;
7799 $text_elt->set_text( $text);
7800 }
7801 else
7802 {
7803 my $replace_sub= ( $replace_sub{$replace} ||= _install_replace_sub( $replace));
7804 my $text= $text_elt->text;
7805 my $pos=0; # used to skip text that was previously matched
7806 my $found_hit;
7807 while( my( $pre_match_string, $match_string, @var)= ($text=~ m{(.*?)($regexp)}sg))
7808 { $found_hit=1;
7809 my $match_start = length( $pre_match_string);
7810 my $match = $match_start ? $text_elt->split_at( $match_start + $pos) : $text_elt;
7811 my $match_length = length( $match_string);
7812 my $post_match = $match->split_at( $match_length);
7813 $replace_sub->( $match, @var);
7814  
7815 # go to next
7816 $text_elt= $post_match;
7817 $text= $post_match->text;
7818  
7819 if( $found_hit) { push @parents, $text_elt->{parent} unless $parents[-1] && $parents[-1]== $text_elt->{parent}; }
7820  
7821 }
7822 }
7823 }
7824  
7825 foreach my $parent (@parents) { $parent->normalize; }
7826  
7827 return $elt;
7828 }
7829  
7830 sub _is_string
7831 { return ($_[0]=~ m{&e[ln]t}) ? 0: 1 }
7832  
7833 sub _replace_var
7834 { my( $string, @var)= @_;
7835 unshift @var, undef;
7836 $string=~ s{\$(\d)}{$var[$1]}g;
7837 return $string;
7838 }
7839  
7840 sub _install_replace_sub
7841 { my $replace_exp= shift;
7842 my @item= split m{(&e[ln]t\s*\([^)]*\))}, $replace_exp;
7843 my $sub= q{ my( $match, @var)= @_; my $new; my $last_inserted=$match;};
7844 my( $gi, $exp);
7845 foreach my $item (@item)
7846 { next if ! length $item;
7847 if( $item=~ m{^&elt\s*\(([^)]*)\)})
7848 { $exp= $1; }
7849 elsif( $item=~ m{^&ent\s*\(\s*([^\s)]*)\s*\)})
7850 { $exp= " '#ENT' => $1"; }
7851 else
7852 { $exp= qq{ '#PCDATA' => "$item"}; }
7853 $exp=~ s{\$(\d)}{my $i= $1-1; "\$var[$i]"}eg; # replace references to matches
7854 $sub.= qq{ \$new= \$match->new( $exp); };
7855 $sub .= q{ $new->paste( after => $last_inserted); $last_inserted=$new;};
7856 }
7857 $sub .= q{ $match->delete; };
7858 #$sub=~ s/;/;\n/g; warn "subs: $sub";
7859 my $coderef= eval "sub { $NO_WARNINGS; $sub }"; ## no critic (ProhibitStringyEval)
7860 if( $@) {
7861 my $msg = "invalid replacement expression $replace_exp: " . $@;
7862 if( $@ =~ m{Global symbol .* requires explicit package name} )
7863 { my $suggested = $replace_exp;
7864 $suggested =~ s{\$(\d)}{\\\$$1}g;
7865 $msg = join "\n ",
7866 $msg,
7867 "the problem seems to be that the replacement expression is a single-quoted string".
7868 "that includes variables. Those need to be expanded.",
7869 "ie replace the following:",
7870 " '$replace_exp'",
7871 "with:",
7872 " qq{$suggested}",
7873 ;
7874 }
7875 croak $msg;
7876 }
7877 return $coderef;
7878 }
7879  
7880 }
7881  
7882 sub merge_text
7883 { my( $e1, $e2)= @_;
7884 croak "invalid merge: can only merge 2 elements"
7885 unless( isa( $e2, 'XML::Twig::Elt'));
7886 croak "invalid merge: can only merge 2 text elements"
7887 unless( $e1->is_text && $e2->is_text && ($e1->gi eq $e2->gi));
7888  
7889 my $t1_length= length( $e1->text);
7890  
7891 $e1->set_text( $e1->text . $e2->text);
7892  
7893 if( my $extra_data_in_pcdata= $e2->_extra_data_in_pcdata)
7894 { foreach my $data (@$extra_data_in_pcdata) { $e1->_push_extra_data_in_pcdata( $data->{text}, $data->{offset} + $t1_length); } }
7895  
7896 $e2->delete;
7897  
7898 return $e1;
7899 }
7900  
7901 sub merge
7902 { my( $e1, $e2)= @_;
7903 my @e2_children= $e2->_children;
7904 if( $e1->_last_child && $e1->_last_child->is_pcdata
7905 && @e2_children && $e2_children[0]->is_pcdata
7906 )
7907 { my $t1_length= length( $e1->_last_child->{pcdata});
7908 my $child1= $e1->_last_child;
7909 my $child2= shift @e2_children;
7910 $child1->{pcdata} .= $child2->{pcdata};
7911  
7912 my $extra_data= $e1->_extra_data_before_end_tag . $e2->extra_data;
7913  
7914 if( $extra_data)
7915 { $e1->_del_extra_data_before_end_tag;
7916 $child1->_push_extra_data_in_pcdata( $extra_data, $t1_length);
7917 }
7918  
7919 if( my $extra_data_in_pcdata= $child2->_extra_data_in_pcdata)
7920 { foreach my $data (@$extra_data_in_pcdata) { $child1->_push_extra_data_in_pcdata( $data->{text}, $data->{offset} + $t1_length); } }
7921  
7922 if( my $extra_data_before_end_tag= $e2->_extra_data_before_end_tag)
7923 { $e1->_set_extra_data_before_end_tag( $extra_data_before_end_tag); }
7924 }
7925  
7926 foreach my $e (@e2_children) { $e->move( last_child => $e1); }
7927  
7928 $e2->delete;
7929 return $e1;
7930 }
7931  
7932 # recursively copy an element and returns the copy (can be huge and long)
7933 sub copy
7934 { my $elt= shift;
7935 my $copy= $elt->new( $XML::Twig::index2gi[$elt->{'gi'}]);
7936  
7937 if( $elt->extra_data) { $copy->set_extra_data( $elt->extra_data); }
7938 if( $elt->{extra_data_before_end_tag}) { $copy->_set_extra_data_before_end_tag( $elt->{extra_data_before_end_tag}); }
7939  
7940 if( $elt->is_asis) { $copy->set_asis; }
7941  
7942 if( (exists $elt->{'pcdata'}))
7943 { $copy->{pcdata}= (delete $copy->{empty} || 1) && $elt->{pcdata};
7944 if( $elt->{extra_data_in_pcdata}) { $copy->_set_extra_data_in_pcdata( $elt->{extra_data_in_pcdata}); }
7945 }
7946 elsif( (exists $elt->{'cdata'}))
7947 { $copy->{cdata}= $elt->{cdata};
7948 if( $elt->{extra_data_in_pcdata}) { $copy->_set_extra_data_in_pcdata( $elt->{extra_data_in_pcdata}); }
7949 }
7950 elsif( (exists $elt->{'target'}))
7951 { $copy->_set_pi( $elt->{target}, $elt->{data}); }
7952 elsif( (exists $elt->{'comment'}))
7953 { $copy->{comment}= $elt->{comment}; }
7954 elsif( (exists $elt->{'ent'}))
7955 { $copy->{ent}= $elt->{ent}; }
7956 else
7957 { my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
7958 if( my $atts= $elt->{att})
7959 { my %atts;
7960 tie %atts, 'Tie::IxHash' if (keep_atts_order());
7961 %atts= %{$atts}; # we want to do a real copy of the attributes
7962 $copy->set_atts( \%atts);
7963 }
7964 foreach my $child (@children)
7965 { my $child_copy= $child->copy;
7966 $child_copy->paste( 'last_child', $copy);
7967 }
7968 }
7969 # save links to the original location, which can be convenient and is used for namespace resolution
7970 foreach my $link ( qw(parent prev_sibling next_sibling) )
7971 { $copy->{former}->{$link}= $elt->{$link};
7972 if( $XML::Twig::weakrefs) { weaken( $copy->{former}->{$link}); }
7973 }
7974  
7975 $copy->{empty}= $elt->{'empty'};
7976  
7977 return $copy;
7978 }
7979  
7980 sub delete
7981 { my $elt= shift;
7982 $elt->cut;
7983 $elt->DESTROY unless $XML::Twig::weakrefs;
7984 return undef;
7985 }
7986  
7987 sub __destroy
7988 { my $elt= shift;
7989 return if( $XML::Twig::weakrefs);
7990 my $t= shift || $elt->twig; # optional argument, passed in recursive calls
7991  
7992 foreach( @{[$elt->_children]}) { $_->DESTROY( $t); }
7993  
7994 # the id reference needs to be destroyed
7995 # lots of tests to avoid warnings during the cleanup phase
7996 $elt->del_id( $t) if( $ID && $t && defined( $elt->{att}) && exists( $elt->{att}->{$ID}));
7997 if( $elt->{former}) { foreach (keys %{$elt->{former}}) { delete $elt->{former}->{$_}; } delete $elt->{former}; }
7998 foreach (qw( keys %$elt)) { delete $elt->{$_}; }
7999 undef $elt;
8000 }
8001  
8002 BEGIN
8003 { sub set_destroy { if( $XML::Twig::weakrefs) { undef *DESTROY } else { *DESTROY= *__destroy; } }
8004 set_destroy();
8005 }
8006  
8007 # ignores the element
8008 sub ignore
8009 { my $elt= shift;
8010 my $t= $elt->twig;
8011 $t->ignore( $elt, @_);
8012 }
8013  
8014 BEGIN {
8015 my $pretty = 0;
8016 my $quote = '"';
8017 my $INDENT = ' ';
8018 my $empty_tag_style = 0;
8019 my $remove_cdata = 0;
8020 my $keep_encoding = 0;
8021 my $expand_external_entities = 0;
8022 my $keep_atts_order = 0;
8023 my $do_not_escape_amp_in_atts = 0;
8024 my $WRAP = '80';
8025 my $REPLACED_ENTS = qq{&<};
8026  
8027 my ($NSGMLS, $NICE, $INDENTED, $INDENTEDCT, $INDENTEDC, $WRAPPED, $RECORD1, $RECORD2, $INDENTEDA)= (1..9);
8028 my %KEEP_TEXT_TAG_ON_ONE_LINE= map { $_ => 1 } ( $INDENTED, $INDENTEDCT, $INDENTEDC, $INDENTEDA, $WRAPPED);
8029 my %WRAPPED = map { $_ => 1 } ( $WRAPPED, $INDENTEDA, $INDENTEDC);
8030  
8031 my %pretty_print_style=
8032 ( none => 0, # no added \n
8033 nsgmls => $NSGMLS, # nsgmls-style, \n in tags
8034 # below this line styles are UNSAFE (the generated XML can be well-formed but invalid)
8035 nice => $NICE, # \n after open/close tags except when the
8036 # element starts with text
8037 indented => $INDENTED, # nice plus indented
8038 indented_close_tag => $INDENTEDCT, # nice plus indented
8039 indented_c => $INDENTEDC, # slightly more compact than indented (closing
8040 # tags are on the same line)
8041 wrapped => $WRAPPED, # text is wrapped at column
8042 record_c => $RECORD1, # for record-like data (compact)
8043 record => $RECORD2, # for record-like data (not so compact)
8044 indented_a => $INDENTEDA, # nice, indented, and with attributes on separate
8045 # lines as the nsgmls style, as well as wrapped
8046 # lines - to make the xml friendly to line-oriented tools
8047 cvs => $INDENTEDA, # alias for indented_a
8048 );
8049  
8050 my ($HTML, $EXPAND)= (1..2);
8051 my %empty_tag_style=
8052 ( normal => 0, # <tag/>
8053 html => $HTML, # <tag />
8054 xhtml => $HTML, # <tag />
8055 expand => $EXPAND, # <tag></tag>
8056 );
8057  
8058 my %quote_style=
8059 ( double => '"',
8060 single => "'",
8061 # smart => "smart",
8062 );
8063  
8064 my $xml_space_preserve; # set when an element includes xml:space="preserve"
8065  
8066 my $output_filter; # filters the entire output (including < and >)
8067 my $output_text_filter; # filters only the text part (tag names, attributes, pcdata)
8068  
8069 my $replaced_ents= $REPLACED_ENTS;
8070  
8071 # returns those pesky "global" variables so you can switch between twigs
8072 sub global_state ## no critic (Subroutines::ProhibitNestedSubs);
8073 { return
8074 { pretty => $pretty,
8075 quote => $quote,
8076 indent => $INDENT,
8077 empty_tag_style => $empty_tag_style,
8078 remove_cdata => $remove_cdata,
8079 keep_encoding => $keep_encoding,
8080 expand_external_entities => $expand_external_entities,
8081 output_filter => $output_filter,
8082 output_text_filter => $output_text_filter,
8083 keep_atts_order => $keep_atts_order,
8084 do_not_escape_amp_in_atts => $do_not_escape_amp_in_atts,
8085 wrap => $WRAP,
8086 replaced_ents => $replaced_ents,
8087 };
8088 }
8089  
8090 # restores the global variables
8091 sub set_global_state
8092 { my $state= shift;
8093 $pretty = $state->{pretty};
8094 $quote = $state->{quote};
8095 $INDENT = $state->{indent};
8096 $empty_tag_style = $state->{empty_tag_style};
8097 $remove_cdata = $state->{remove_cdata};
8098 $keep_encoding = $state->{keep_encoding};
8099 $expand_external_entities = $state->{expand_external_entities};
8100 $output_filter = $state->{output_filter};
8101 $output_text_filter = $state->{output_text_filter};
8102 $keep_atts_order = $state->{keep_atts_order};
8103 $do_not_escape_amp_in_atts = $state->{do_not_escape_amp_in_atts};
8104 $WRAP = $state->{wrap};
8105 $replaced_ents = $state->{replaced_ents},
8106 }
8107  
8108 # sets global state to defaults
8109 sub init_global_state
8110 { set_global_state(
8111 { pretty => 0,
8112 quote => '"',
8113 indent => $INDENT,
8114 empty_tag_style => 0,
8115 remove_cdata => 0,
8116 keep_encoding => 0,
8117 expand_external_entities => 0,
8118 output_filter => undef,
8119 output_text_filter => undef,
8120 keep_atts_order => undef,
8121 do_not_escape_amp_in_atts => 0,
8122 wrap => $WRAP,
8123 replaced_ents => $REPLACED_ENTS,
8124 });
8125 }
8126  
8127 # set the pretty_print style (in $pretty) and returns the old one
8128 # can be called from outside the package with 2 arguments (elt, style)
8129 # or from inside with only one argument (style)
8130 # the style can be either a string (one of the keys of %pretty_print_style
8131 # or a number (presumably an old value saved)
8132 sub set_pretty_print
8133 { my $style= lc( defined $_[1] ? $_[1] : $_[0]); # so we cover both cases
8134 my $old_pretty= $pretty;
8135 if( $style=~ /^\d+$/)
8136 { croak "invalid pretty print style $style" unless( $style < keys %pretty_print_style);
8137 $pretty= $style;
8138 }
8139 else
8140 { croak "invalid pretty print style '$style'" unless( exists $pretty_print_style{$style});
8141 $pretty= $pretty_print_style{$style};
8142 }
8143 if( $WRAPPED{$pretty} )
8144 { XML::Twig::_use( 'Text::Wrap') or croak( "Text::Wrap not available, cannot use style $style"); }
8145 return $old_pretty;
8146 }
8147  
8148 sub _pretty_print { return $pretty; }
8149  
8150 # set the empty tag style (in $empty_tag_style) and returns the old one
8151 # can be called from outside the package with 2 arguments (elt, style)
8152 # or from inside with only one argument (style)
8153 # the style can be either a string (one of the keys of %empty_tag_style
8154 # or a number (presumably an old value saved)
8155 sub set_empty_tag_style
8156 { my $style= lc( defined $_[1] ? $_[1] : $_[0]); # so we cover both cases
8157 my $old_style= $empty_tag_style;
8158 if( $style=~ /^\d+$/)
8159 { croak "invalid empty tag style $style"
8160 unless( $style < keys %empty_tag_style);
8161 $empty_tag_style= $style;
8162 }
8163 else
8164 { croak "invalid empty tag style '$style'"
8165 unless( exists $empty_tag_style{$style});
8166 $empty_tag_style= $empty_tag_style{$style};
8167 }
8168 return $old_style;
8169 }
8170  
8171 sub _pretty_print_styles
8172 { return (sort { $pretty_print_style{$a} <=> $pretty_print_style{$b} || $a cmp $b } keys %pretty_print_style); }
8173  
8174 sub set_quote
8175 { my $style= $_[1] || $_[0];
8176 my $old_quote= $quote;
8177 croak "invalid quote '$style'" unless( exists $quote_style{$style});
8178 $quote= $quote_style{$style};
8179 return $old_quote;
8180 }
8181  
8182 sub set_remove_cdata
8183 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8184 my $old_value= $remove_cdata;
8185 $remove_cdata= $new_value;
8186 return $old_value;
8187 }
8188  
8189 sub set_indent
8190 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8191 my $old_value= $INDENT;
8192 $INDENT= $new_value;
8193 return $old_value;
8194 }
8195  
8196 sub set_wrap
8197 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8198 my $old_value= $WRAP;
8199 $WRAP= $new_value;
8200 return $old_value;
8201 }
8202  
8203 sub set_keep_encoding
8204 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8205 my $old_value= $keep_encoding;
8206 $keep_encoding= $new_value;
8207 return $old_value;
8208 }
8209  
8210 sub set_replaced_ents
8211 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8212 my $old_value= $replaced_ents;
8213 $replaced_ents= $new_value;
8214 return $old_value;
8215 }
8216  
8217 sub do_not_escape_gt
8218 { my $old_value= $replaced_ents;
8219 $replaced_ents= q{&<}; # & needs to be first
8220 return $old_value;
8221 }
8222  
8223 sub escape_gt
8224 { my $old_value= $replaced_ents;
8225 $replaced_ents= qq{&<>}; # & needs to be first
8226 return $old_value;
8227 }
8228  
8229 sub _keep_encoding { return $keep_encoding; } # so I can use elsewhere in the module
8230  
8231 sub set_do_not_escape_amp_in_atts
8232 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8233 my $old_value= $do_not_escape_amp_in_atts;
8234 $do_not_escape_amp_in_atts= $new_value;
8235 return $old_value;
8236 }
8237  
8238 sub output_filter { return $output_filter; }
8239 sub output_text_filter { return $output_text_filter; }
8240  
8241 sub set_output_filter
8242 { my $new_value= defined $_[1] ? $_[1] : $_[0]; # can be called in object/non-object mode
8243 # if called in object mode with no argument, the filter is undefined
8244 if( isa( $new_value, 'XML::Twig::Elt') || isa( $new_value, 'XML::Twig')) { undef $new_value; }
8245 my $old_value= $output_filter;
8246 if( !$new_value || isa( $new_value, 'CODE') )
8247 { $output_filter= $new_value; }
8248 elsif( $new_value eq 'latin1')
8249 { $output_filter= XML::Twig::latin1();
8250 }
8251 elsif( $XML::Twig::filter{$new_value})
8252 { $output_filter= $XML::Twig::filter{$new_value}; }
8253 else
8254 { croak "invalid output filter '$new_value'"; }
8255  
8256 return $old_value;
8257 }
8258  
8259 sub set_output_text_filter
8260 { my $new_value= defined $_[1] ? $_[1] : $_[0]; # can be called in object/non-object mode
8261 # if called in object mode with no argument, the filter is undefined
8262 if( isa( $new_value, 'XML::Twig::Elt') || isa( $new_value, 'XML::Twig')) { undef $new_value; }
8263 my $old_value= $output_text_filter;
8264 if( !$new_value || isa( $new_value, 'CODE') )
8265 { $output_text_filter= $new_value; }
8266 elsif( $new_value eq 'latin1')
8267 { $output_text_filter= XML::Twig::latin1();
8268 }
8269 elsif( $XML::Twig::filter{$new_value})
8270 { $output_text_filter= $XML::Twig::filter{$new_value}; }
8271 else
8272 { croak "invalid output text filter '$new_value'"; }
8273  
8274 return $old_value;
8275 }
8276  
8277 sub set_expand_external_entities
8278 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8279 my $old_value= $expand_external_entities;
8280 $expand_external_entities= $new_value;
8281 return $old_value;
8282 }
8283  
8284 sub set_keep_atts_order
8285 { my $new_value= defined $_[1] ? $_[1] : $_[0];
8286 my $old_value= $keep_atts_order;
8287 $keep_atts_order= $new_value;
8288 return $old_value;
8289  
8290 }
8291  
8292 sub keep_atts_order { return $keep_atts_order; } # so I can use elsewhere in the module
8293  
8294 my %html_empty_elt;
8295 BEGIN { %html_empty_elt= map { $_ => 1} qw( base meta link hr br param img area input col); }
8296  
8297 sub start_tag
8298 { my( $elt, $option)= @_;
8299  
8300 return if( $elt->{gi} < $XML::Twig::SPECIAL_GI);
8301  
8302 my $extra_data= $elt->{extra_data} || '';
8303  
8304 my $gi= $XML::Twig::index2gi[$elt->{'gi'}];
8305 my $att= $elt->{att}; # should be $elt->{att}, optimized into a pure hash look-up
8306  
8307 my $ns_map= $att ? $att->{'#original_gi'} : '';
8308 if( $ns_map) { $gi= _restore_original_prefix( $ns_map, $gi); }
8309 $gi=~ s{^#default:}{}; # remove default prefix
8310  
8311 if( $output_text_filter) { $gi= $output_text_filter->( $gi); }
8312  
8313 # get the attribute and their values
8314 my $att_sep = $pretty==$NSGMLS ? "\n"
8315 : $pretty==$INDENTEDA ? "\n" . $INDENT x ($elt->level+1) . ' '
8316 : ' '
8317 ;
8318  
8319 my $replace_in_att_value= $replaced_ents . "$quote\t\r\n";
8320 if( $option->{escape_gt} && $replaced_ents !~ m{>}) { $replace_in_att_value.= '>'; }
8321  
8322 my $tag;
8323 my @att_names= grep { !( $_=~ m{^#(?!default:)} ) } $keep_atts_order ? keys %{$att} : sort keys %{$att};
8324 if( @att_names)
8325 { my $atts= join $att_sep, map { my $output_att_name= $ns_map ? _restore_original_prefix( $ns_map, $_) : $_;
8326 if( $output_text_filter)
8327 { $output_att_name= $output_text_filter->( $output_att_name); }
8328 $output_att_name . '=' . $quote . _att_xml_string( $att->{$_}, $replace_in_att_value) . $quote
8329  
8330 }
8331 @att_names
8332 ;
8333 if( $pretty==$INDENTEDA && @att_names == 1) { $att_sep= ' '; }
8334 $tag= "<$gi$att_sep$atts";
8335 }
8336 else
8337 { $tag= "<$gi"; }
8338  
8339 $tag .= "\n" if($pretty==$NSGMLS);
8340  
8341 # force empty if suitable HTML tag, otherwise use the value from the input tree
8342 if( ($empty_tag_style eq $HTML) && !$elt->{first_child} && !$elt->{extra_data_before_end_tag} && $html_empty_elt{$gi})
8343 { $elt->{empty}= 1; }
8344 my $empty= defined $elt->{empty} ? $elt->{empty}
8345 : $elt->{first_child} ? 0
8346 : 1;
8347  
8348 $tag .= (!$elt->{empty} || $elt->{extra_data_before_end_tag}) ? '>' # element has content
8349 : (($empty_tag_style eq $HTML) && $html_empty_elt{$gi}) ? ' />' # html empty element
8350 # cvs-friendly format
8351 : ( $pretty == $INDENTEDA && @att_names > 1) ? "\n" . $INDENT x $elt->level . "/>"
8352 : ( $pretty == $INDENTEDA && @att_names == 1) ? " />"
8353 : $empty_tag_style ? "></" . $XML::Twig::index2gi[$elt->{'gi'}] . ">" # $empty_tag_style is $HTML or $EXPAND
8354 : '/>'
8355 ;
8356  
8357 if( ( (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 1) eq '#') && (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 9) ne '#default:') )) { $tag= ''; }
8358  
8359 #warn "TRACE: ", $tag,": ", Encode::is_utf8( $tag) ? "has flag" : "FLAG NOT SET";
8360  
8361 unless( $pretty) { return defined( $extra_data) ? $extra_data . $tag : $tag; }
8362  
8363 my $prefix='';
8364 my $return=''; # '' or \n is to be printed before the tag
8365 my $indent=0; # number of indents before the tag
8366  
8367 if( $pretty==$RECORD1)
8368 { my $level= $elt->level;
8369 $return= "\n" if( $level < 2);
8370 $indent= 1 if( $level == 1);
8371 }
8372  
8373 elsif( $pretty==$RECORD2)
8374 { $return= "\n";
8375 $indent= $elt->level;
8376 }
8377  
8378 elsif( $pretty==$NICE)
8379 { my $parent= $elt->{parent};
8380 unless( !$parent || $parent->{contains_text})
8381 { $return= "\n"; }
8382 $elt->{contains_text}= 1 if( ($parent && $parent->{contains_text})
8383 || $elt->contains_text);
8384 }
8385  
8386 elsif( $KEEP_TEXT_TAG_ON_ONE_LINE{$pretty})
8387 { my $parent= $elt->{parent};
8388 unless( !$parent || $parent->{contains_text})
8389 { $return= "\n";
8390 $indent= $elt->level;
8391 }
8392 $elt->{contains_text}= 1 if( ($parent && $parent->{contains_text})
8393 || $elt->contains_text);
8394 }
8395  
8396 if( $return || $indent)
8397 { # check for elements in which spaces should be kept
8398 my $t= $elt->twig;
8399 return $extra_data . $tag if( $xml_space_preserve);
8400 if( $t && $t->{twig_keep_spaces_in})
8401 { foreach my $ancestor ($elt->ancestors)
8402 { return $extra_data . $tag if( $t->{twig_keep_spaces_in}->{$XML::Twig::index2gi[$ancestor->{'gi'}]}) }
8403 }
8404  
8405 $prefix= $INDENT x $indent;
8406 if( $extra_data)
8407 { $extra_data=~ s{\s+$}{};
8408 $extra_data=~ s{^\s+}{};
8409 $extra_data= $prefix . $extra_data . $return;
8410 }
8411 }
8412  
8413 return $return . $extra_data . $prefix . $tag;
8414 }
8415  
8416 sub end_tag
8417 { my $elt= shift;
8418 return '' if( ($elt->{gi}<$XML::Twig::SPECIAL_GI)
8419 || ($elt->{'empty'} && !$elt->{extra_data_before_end_tag})
8420 );
8421 my $tag= "<";
8422 my $gi= $XML::Twig::index2gi[$elt->{'gi'}];
8423  
8424 if( my $map= $elt->{'att'}->{'#original_gi'}) { $gi= _restore_original_prefix( $map, $gi); }
8425 $gi=~ s{^#default:}{}; # remove default prefix
8426  
8427 if( $output_text_filter) { $gi= $output_text_filter->( $XML::Twig::index2gi[$elt->{'gi'}]); }
8428 $tag .= "/$gi>";
8429  
8430 $tag = ($elt->{extra_data_before_end_tag} || '') . $tag;
8431  
8432 if( ( (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 1) eq '#') && (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 9) ne '#default:') )) { $tag= ''; }
8433  
8434 return $tag unless $pretty;
8435  
8436 my $prefix='';
8437 my $return=0; # 1 if a \n is to be printed before the tag
8438 my $indent=0; # number of indents before the tag
8439  
8440 if( $pretty==$RECORD1)
8441 { $return= 1 if( $elt->level == 0);
8442 }
8443  
8444 elsif( $pretty==$RECORD2)
8445 { unless( $elt->contains_text)
8446 { $return= 1 ;
8447 $indent= $elt->level;
8448 }
8449 }
8450  
8451 elsif( $pretty==$NICE)
8452 { my $parent= $elt->{parent};
8453 if( ( ($parent && !$parent->{contains_text}) || !$parent )
8454 && ( !$elt->{contains_text}
8455 && ($elt->{has_flushed_child} || $elt->{first_child})
8456 )
8457 )
8458 { $return= 1; }
8459 }
8460  
8461 elsif( $KEEP_TEXT_TAG_ON_ONE_LINE{$pretty})
8462 { my $parent= $elt->{parent};
8463 if( ( ($parent && !$parent->{contains_text}) || !$parent )
8464 && ( !$elt->{contains_text}
8465 && ($elt->{has_flushed_child} || $elt->{first_child})
8466 )
8467 )
8468 { $return= 1;
8469 $indent= $elt->level;
8470 }
8471 }
8472  
8473 if( $return || $indent)
8474 { # check for elements in which spaces should be kept
8475 my $t= $elt->twig;
8476 return $tag if( $xml_space_preserve);
8477 if( $t && $t->{twig_keep_spaces_in})
8478 { foreach my $ancestor ($elt, $elt->ancestors)
8479 { return $tag if( $t->{twig_keep_spaces_in}->{$XML::Twig::index2gi[$ancestor->{'gi'}]}) }
8480 }
8481  
8482 if( $return) { $prefix= ($pretty== $INDENTEDCT) ? "\n$INDENT" : "\n"; }
8483 $prefix.= $INDENT x $indent;
8484 }
8485  
8486 # add a \n at the end of the document (after the root element)
8487 $tag .= "\n" unless( $elt->{parent});
8488  
8489 return $prefix . $tag;
8490 }
8491  
8492 sub _restore_original_prefix
8493 { my( $map, $name)= @_;
8494 my $prefix= _ns_prefix( $name);
8495 if( my $original_prefix= $map->{$prefix})
8496 { if( $original_prefix eq '#default')
8497 { $name=~ s{^$prefix:}{}; }
8498 else
8499 { $name=~ s{^$prefix(?=:)}{$original_prefix}; }
8500 }
8501 return $name;
8502 }
8503  
8504 # buffer used to hold the text to print/sprint, to avoid passing it back and forth between methods
8505 my @sprint;
8506  
8507 # $elt is an element to print
8508 # $fh is an optional filehandle to print to
8509 # $pretty is an optional value, if true a \n is printed after the < of the
8510 # opening tag
8511 sub print
8512 { my $elt= shift;
8513  
8514 my $fh= isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar') ? shift : undef;
8515 my $old_select= defined $fh ? select $fh : undef;
8516 print $elt->sprint( @_);
8517 select $old_select if( defined $old_select);
8518 }
8519  
8520 # those next 2 methods need to be refactored, they are copies of the same methods in XML::Twig
8521 sub print_to_file
8522 { my( $elt, $filename)= (shift, shift);
8523 my $out_fh;
8524 my $mode= $keep_encoding ? '>' : '>:utf8';
8525 open( $out_fh, $mode, $filename) or _croak( "cannot create file $filename: $!");
8526 $elt->print( $out_fh, @_);
8527 close $out_fh;
8528 return $elt;
8529 }
8530  
8531 # probably only works on *nix (at least the chmod bit)
8532 # first print to a temporary file, then rename that file to the desired file name, then change permissions
8533 # to the original file permissions (or to the current umask)
8534 sub safe_print_to_file
8535 { my( $elt, $filename)= (shift, shift);
8536 my $perm= -f $filename ? (stat $filename)[2] & 07777 : ~umask() ; ## no critic (ProhibitLeadingZeros)
8537 XML::Twig::_use( 'File::Temp') || croak "need File::Temp to use safe_print_to_file\n";
8538 XML::Twig::_use( 'File::Basename') || croak "need File::Basename to use safe_print_to_file\n";
8539 my $tmpdir= File::Basename::dirname( $filename);
8540 my( $fh, $tmpfilename) = File::Temp::tempfile( DIR => $tmpdir);
8541 $elt->print_to_file( $tmpfilename, @_);
8542 rename( $tmpfilename, $filename) or unlink $tmpfilename && _croak( "cannot move temporary file to $filename: $!");
8543 chmod $perm, $filename;
8544 return $elt;
8545 }
8546  
8547 # same as print but does not output the start tag if the element
8548 # is marked as flushed
8549 sub flush
8550 { my $elt= shift;
8551 my $up_to= $_[0] && isa( $_[0], 'XML::Twig::Elt') ? shift : $elt;
8552 $elt->twig->flush_up_to( $up_to, @_);
8553 }
8554 sub purge
8555 { my $elt= shift;
8556 my $up_to= $_[0] && isa( $_[0], 'XML::Twig::Elt') ? shift : $elt;
8557 $elt->twig->purge_up_to( $up_to, @_);
8558 }
8559  
8560 sub _flush
8561 { my $elt= shift;
8562  
8563 my $pretty;
8564 my $fh= isa( $_[0], 'GLOB') || isa( $_[0], 'IO::Scalar') ? shift : undef;
8565 my $old_select= defined $fh ? select $fh : undef;
8566 my $old_pretty= defined ($pretty= shift) ? set_pretty_print( $pretty) : undef;
8567  
8568 $xml_space_preserve= 1 if( ($elt->inherit_att( 'xml:space') || '') eq 'preserve');
8569  
8570 $elt->__flush();
8571  
8572 $xml_space_preserve= 0;
8573  
8574 select $old_select if( defined $old_select);
8575 set_pretty_print( $old_pretty) if( defined $old_pretty);
8576 }
8577  
8578 sub __flush
8579 { my $elt= shift;
8580  
8581 if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
8582 { my $preserve= ($elt->{'att'}->{'xml:space'} || '') eq 'preserve';
8583 $xml_space_preserve++ if $preserve;
8584 unless( $elt->{'flushed'})
8585 { print $elt->start_tag();
8586 }
8587  
8588 # flush the children
8589 my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
8590 foreach my $child (@children)
8591 { $child->_flush( $pretty);
8592 $child->{'flushed'}=1;
8593 }
8594 if( ! $elt->{end_tag_flushed})
8595 { print $elt->end_tag;
8596 $elt->{end_tag_flushed}=1;
8597 $elt->{'flushed'}=1;
8598 }
8599 $xml_space_preserve-- if $preserve;
8600 # used for pretty printing
8601 if( my $parent= $elt->{parent}) { $parent->{has_flushed_child}= 1; }
8602 }
8603 else # text or special element
8604 { my $text;
8605 if( (exists $elt->{'pcdata'})) { $text= $elt->pcdata_xml_string;
8606 if( my $parent= $elt->{parent})
8607 { $parent->{contains_text}= 1; }
8608 }
8609 elsif( (exists $elt->{'cdata'})) { $text= $elt->cdata_string;
8610 if( my $parent= $elt->{parent})
8611 { $parent->{contains_text}= 1; }
8612 }
8613 elsif( (exists $elt->{'target'})) { $text= $elt->pi_string; }
8614 elsif( (exists $elt->{'comment'})) { $text= $elt->comment_string; }
8615 elsif( (exists $elt->{'ent'})) { $text= $elt->ent_string; }
8616  
8617 print $output_filter ? $output_filter->( $text) : $text;
8618 }
8619 }
8620  
8621 sub xml_text
8622 { my( $elt, @options)= @_;
8623  
8624 if( @options && grep { lc( $_) eq 'no_recurse' } @options) { return $elt->xml_text_only; }
8625  
8626 my $string='';
8627  
8628 if( ($elt->{gi} >= $XML::Twig::SPECIAL_GI) )
8629 { # sprint the children
8630 my $child= $elt->{first_child} || '';
8631 while( $child)
8632 { $string.= $child->xml_text;
8633 } continue { $child= $child->{next_sibling}; }
8634 }
8635 elsif( (exists $elt->{'pcdata'})) { $string .= $output_filter ? $output_filter->($elt->pcdata_xml_string)
8636 : $elt->pcdata_xml_string;
8637 }
8638 elsif( (exists $elt->{'cdata'})) { $string .= $output_filter ? $output_filter->($elt->cdata_string)
8639 : $elt->cdata_string;
8640 }
8641 elsif( (exists $elt->{'ent'})) { $string .= $elt->ent_string; }
8642  
8643 return $string;
8644 }
8645  
8646 sub xml_text_only
8647 { return join '', map { $_->xml_text if( $_->is_text || (exists $_->{'ent'})) } $_[0]->_children; }
8648  
8649 # same as print but except... it does not print but rather returns the string
8650 # if the second parameter is set then only the content is returned, not the
8651 # start and end tags of the element (but the tags of the included elements are
8652 # returned)
8653  
8654 sub sprint
8655 { my $elt= shift;
8656 my( $old_pretty, $old_empty_tag_style);
8657  
8658 if( $_[0])
8659 { if( isa( $_[0], 'HASH'))
8660 { # "proper way, using a hashref for options
8661 my %args= XML::Twig::_normalize_args( %{shift()});
8662 if( defined $args{PrettyPrint}) { $old_pretty = set_pretty_print( $args{PrettyPrint}); }
8663 if( defined $args{EmptyTags}) { $old_empty_tag_style = set_empty_tag_style( $args{EmptyTags}); }
8664 }
8665 else
8666 { # "old" way, just using the option name
8667 my @other_opt;
8668 foreach my $opt (@_)
8669 { if( exists $pretty_print_style{$opt}) { $old_pretty = set_pretty_print( $opt); }
8670 elsif( exists $empty_tag_style{$opt}) { $old_empty_tag_style = set_empty_tag_style( $opt); }
8671 else { push @other_opt, $opt; }
8672 }
8673 @_= @other_opt;
8674 }
8675 }
8676  
8677 $xml_space_preserve= 1 if( ($elt->inherit_att( 'xml:space') || '') eq 'preserve');
8678  
8679 @sprint=();
8680 $elt->_sprint( @_);
8681 my $sprint= join( '', @sprint);
8682 if( $output_filter) { $sprint= $output_filter->( $sprint); }
8683  
8684 if( ( ($pretty== $WRAPPED) || ($pretty==$INDENTEDC)) && !$xml_space_preserve)
8685 { $sprint= _wrap_text( $sprint); }
8686 $xml_space_preserve= 0;
8687  
8688 if( defined $old_pretty) { set_pretty_print( $old_pretty); }
8689 if( defined $old_empty_tag_style) { set_empty_tag_style( $old_empty_tag_style); }
8690  
8691 return $sprint;
8692 }
8693  
8694 sub _wrap_text
8695 { my( $string)= @_;
8696 my $wrapped;
8697 foreach my $line (split /\n/, $string)
8698 { my( $initial_indent)= $line=~ m{^(\s*)};
8699 my $wrapped_line= Text::Wrap::wrap( '', $initial_indent . $INDENT, $line) . "\n";
8700  
8701 # fix glitch with Text::wrap when the first line is long and does not include spaces
8702 # the first line ends up being too short by 2 chars, but we'll have to live with it!
8703 $wrapped_line=~ s{^ +\n }{}s; # this prefix needs to be removed
8704  
8705 $wrapped .= $wrapped_line;
8706 }
8707 return $wrapped;
8708 }
8709  
8710 sub _sprint
8711 { my $elt= shift;
8712 my $no_tag= shift || 0;
8713 # in case there's some comments or PI's piggybacking
8714  
8715 if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
8716 {
8717 my $preserve= ($elt->{'att'}->{'xml:space'} || '') eq 'preserve';
8718 $xml_space_preserve++ if $preserve;
8719  
8720 push @sprint, $elt->start_tag unless( $no_tag);
8721  
8722 # sprint the children
8723 my $child= $elt->{first_child};
8724 while( $child)
8725 { $child->_sprint;
8726 $child= $child->{next_sibling};
8727 }
8728 push @sprint, $elt->end_tag unless( $no_tag);
8729 $xml_space_preserve-- if $preserve;
8730 }
8731 else
8732 { push @sprint, $elt->{extra_data} if( $elt->{extra_data}) ;
8733 if( (exists $elt->{'pcdata'})) { push @sprint, $elt->pcdata_xml_string; }
8734 elsif( (exists $elt->{'cdata'})) { push @sprint, $elt->cdata_string; }
8735 elsif( (exists $elt->{'target'})) { if( ($pretty >= $INDENTED) && !$elt->{parent}->{contains_text}) { push @sprint, "\n" . $INDENT x $elt->level; }
8736 push @sprint, $elt->pi_string;
8737 }
8738 elsif( (exists $elt->{'comment'})) { if( ($pretty >= $INDENTED) && !$elt->{parent}->{contains_text}) { push @sprint, "\n" . $INDENT x $elt->level; }
8739 push @sprint, $elt->comment_string;
8740 }
8741 elsif( (exists $elt->{'ent'})) { push @sprint, $elt->ent_string; }
8742 }
8743  
8744 return;
8745 }
8746  
8747 # just a shortcut to $elt->sprint( 1)
8748 sub xml_string
8749 { my $elt= shift;
8750 isa( $_[0], 'HASH') ? $elt->sprint( shift(), 1) : $elt->sprint( 1);
8751 }
8752  
8753 sub pcdata_xml_string
8754 { my $elt= shift;
8755 if( defined( my $string= $elt->{pcdata}) )
8756 {
8757 if( ! $elt->{extra_data_in_pcdata})
8758 {
8759 $string=~ s/([$replaced_ents])/$XML::Twig::base_ent{$1}/g unless( !$replaced_ents || $keep_encoding || $elt->{asis});
8760 $string=~ s{\Q]]>}{]]&gt;}g;
8761 }
8762 else
8763 { _gen_mark( $string); # used by _(un)?protect_extra_data
8764 foreach my $data (reverse @{$elt->{extra_data_in_pcdata}})
8765 { my $substr= substr( $string, $data->{offset});
8766 if( $keep_encoding || $elt->{asis})
8767 { substr( $string, $data->{offset}, 0, $data->{text}); }
8768 else
8769 { substr( $string, $data->{offset}, 0, _protect_extra_data( $data->{text})); }
8770 }
8771 unless( $keep_encoding || $elt->{asis})
8772 {
8773 $string=~ s{([$replaced_ents])}{$XML::Twig::base_ent{$1}}g ;
8774 $string=~ s{\Q]]>}{]]&gt;}g;
8775 _unprotect_extra_data( $string);
8776 }
8777 }
8778 return $output_text_filter ? $output_text_filter->( $string) : $string;
8779 }
8780 else
8781 { return ''; }
8782 }
8783  
8784 { my $mark;
8785 my( %char2ent, %ent2char);
8786 BEGIN
8787 { %char2ent= ( '<' => 'lt', '&' => 'amp', '>' => 'gt');
8788 %ent2char= map { $char2ent{$_} => $_ } keys %char2ent;
8789 }
8790  
8791 # generate a unique mark (a string) not found in the string,
8792 # used to mark < and & in the extra data
8793 sub _gen_mark
8794 { $mark="AAAA";
8795 $mark++ while( index( $_[0], $mark) > -1);
8796 return $mark;
8797 }
8798  
8799 sub _protect_extra_data
8800 { my( $extra_data)= @_;
8801 $extra_data=~ s{([<&>])}{:$mark:$char2ent{$1}:}g;
8802 return $extra_data;
8803 }
8804  
8805 sub _unprotect_extra_data
8806 { $_[0]=~ s{:$mark:(\w+):}{$ent2char{$1}}g; }
8807  
8808 }
8809  
8810 sub cdata_string
8811 { my $cdata= $_[0]->{cdata};
8812 unless( defined $cdata) { return ''; }
8813 if( $remove_cdata)
8814 { $cdata=~ s/([$replaced_ents])/$XML::Twig::base_ent{$1}/g; }
8815 else
8816 { # if the CDATA includes the end of CDATA marker, we need to split it
8817 $cdata=~ s{$CDATA_END}{]]$CDATA_END$CDATA_START>}g;
8818 $cdata= $CDATA_START . $cdata . $CDATA_END;
8819 }
8820 return $cdata;
8821 }
8822  
8823 sub att_xml_string
8824 { my $elt= shift;
8825 my $att= shift;
8826  
8827 my $replace= $replaced_ents . "$quote\n\r\t";
8828 if($_[0] && $_[0]->{escape_gt} && ($replace!~ m{>}) ) { $replace .='>'; }
8829  
8830 if( defined (my $string= $elt->{att}->{$att}))
8831 { return _att_xml_string( $string, $replace); }
8832 else
8833 { return ''; }
8834 }
8835  
8836 # escaped xml string for an attribute value
8837 sub _att_xml_string
8838 { my( $string, $escape)= @_;
8839 if( !defined( $string)) { return ''; }
8840 if( $keep_encoding)
8841 { $string=~ s{$quote}{$XML::Twig::base_ent{$quote}}g;
8842 }
8843 else
8844 {
8845 if( $do_not_escape_amp_in_atts)
8846 { $escape=~ s{^.}{}; # seems like the most backward compatible way to remove & from the list
8847 $string=~ s{([$escape])}{$XML::Twig::base_ent{$1}}g;
8848 $string=~ s{&(?!(\w+|#\d+|[xX][0-9a-fA-F]+);)}{&amp;}g; # dodgy: escape & that do not start an entity
8849 }
8850 else
8851 { $string=~ s{([$escape])}{$XML::Twig::base_ent{$1}}g;
8852 $string=~ s{\Q]]>}{]]&gt;}g;
8853 }
8854 }
8855  
8856 return $output_text_filter ? $output_text_filter->( $string) : $string;
8857 }
8858  
8859 sub ent_string
8860 { my $ent= shift;
8861 my $ent_text= $ent->{ent};
8862 my( $t, $el, $ent_string);
8863 if( $expand_external_entities
8864 && ($t= $ent->twig)
8865 && ($el= $t->entity_list)
8866 && ($ent_string= $el->{entities}->{$ent->ent_name}->{val})
8867 )
8868 { return $ent_string; }
8869 else
8870 { return $ent_text; }
8871 }
8872  
8873 # returns just the text, no tags, for an element
8874 sub text
8875 { my( $elt, @options)= @_;
8876  
8877 if( @options && grep { lc( $_) eq 'no_recurse' } @options) { return $elt->text_only; }
8878 my $sep = (@options && grep { lc( $_) eq 'sep' } @options) ? ' ' : '';
8879  
8880 my $string;
8881  
8882 if( (exists $elt->{'pcdata'})) { return $elt->{pcdata} . $sep; }
8883 elsif( (exists $elt->{'cdata'})) { return $elt->{cdata} . $sep; }
8884 elsif( (exists $elt->{'target'})) { return $elt->pi_string . $sep; }
8885 elsif( (exists $elt->{'comment'})) { return $elt->{comment} . $sep; }
8886 elsif( (exists $elt->{'ent'})) { return $elt->{ent} . $sep ; }
8887  
8888 my $child= $elt->{first_child} ||'';
8889 while( $child)
8890 {
8891 my $child_text= $child->text( @options);
8892 $string.= defined( $child_text) ? $sep . $child_text : '';
8893 } continue { $child= $child->{next_sibling}; }
8894  
8895 unless( defined $string) { $string=''; }
8896  
8897 return $output_text_filter ? $output_text_filter->( $string) : $string;
8898 }
8899  
8900 sub text_only
8901 { return join '', map { $_->text if( $_->is_text || (exists $_->{'ent'})) } $_[0]->_children; }
8902  
8903 sub trimmed_text
8904 { my $elt= shift;
8905 my $text= $elt->text( @_);
8906 $text=~ s{\s+}{ }sg;
8907 $text=~ s{^\s}{};
8908 $text=~ s{\s$}{};
8909 return $text;
8910 }
8911  
8912 sub trim
8913 { my( $elt)= @_;
8914 my $pcdata= $elt->first_descendant( $TEXT);
8915 (my $pcdata_text= $pcdata->text)=~ s{^\s+}{}s;
8916 $pcdata->set_text( $pcdata_text);
8917 $pcdata= $elt->last_descendant( $TEXT);
8918 ($pcdata_text= $pcdata->text)=~ s{\s+$}{};
8919 $pcdata->set_text( $pcdata_text);
8920 foreach my $pcdata ($elt->descendants( $TEXT))
8921 { ($pcdata_text= $pcdata->text)=~ s{\s+}{ }g;
8922 $pcdata->set_text( $pcdata_text);
8923 }
8924 return $elt;
8925 }
8926  
8927 # remove cdata sections (turns them into regular pcdata) in an element
8928 sub remove_cdata
8929 { my $elt= shift;
8930 foreach my $cdata ($elt->descendants_or_self( $CDATA))
8931 { if( $keep_encoding)
8932 { my $data= $cdata->{cdata};
8933 $data=~ s{([&<"'])}{$XML::Twig::base_ent{$1}}g;
8934 $cdata->{pcdata}= (delete $cdata->{empty} || 1) && $data;
8935 }
8936 else
8937 { $cdata->{pcdata}= (delete $cdata->{empty} || 1) && $cdata->{cdata}; }
8938 $cdata->{gi}=$XML::Twig::gi2index{$PCDATA} or $cdata->set_gi( $PCDATA);
8939 undef $cdata->{cdata};
8940 }
8941 }
8942  
8943 sub _is_private { return _is_private_name( $_[0]->gi); }
8944 sub _is_private_name { return $_[0]=~ m{^#(?!default:)}; }
8945  
8946 } # end of block containing package globals ($pretty_print, $quotes, keep_encoding...)
8947  
8948 # merges consecutive #PCDATAs in am element
8949 sub normalize
8950 { my( $elt)= @_;
8951 my @descendants= $elt->descendants( $PCDATA);
8952 while( my $desc= shift @descendants)
8953 { if( ! length $desc->{pcdata}) { $desc->delete; next; }
8954 while( @descendants && $desc->{next_sibling} && $desc->{next_sibling}== $descendants[0])
8955 { my $to_merge= shift @descendants;
8956 $desc->merge_text( $to_merge);
8957 }
8958 }
8959 return $elt;
8960 }
8961  
8962 # SAX export methods
8963 sub toSAX1
8964 { _toSAX(@_, \&_start_tag_data_SAX1, \&_end_tag_data_SAX1); }
8965  
8966 sub toSAX2
8967 { _toSAX(@_, \&_start_tag_data_SAX2, \&_end_tag_data_SAX2); }
8968  
8969 sub _toSAX
8970 { my( $elt, $handler, $start_tag_data, $end_tag_data)= @_;
8971 if( $elt->{gi} >= $XML::Twig::SPECIAL_GI)
8972 { my $data= $start_tag_data->( $elt);
8973 _start_prefix_mapping( $elt, $handler, $data);
8974 if( $data && (my $start_element = $handler->can( 'start_element')))
8975 { unless( $elt->{'flushed'}) { $start_element->( $handler, $data); } }
8976  
8977 foreach my $child ($elt->_children)
8978 { $child->_toSAX( $handler, $start_tag_data, $end_tag_data); }
8979  
8980 if( (my $data= $end_tag_data->( $elt)) && (my $end_element = $handler->can( 'end_element')) )
8981 { $end_element->( $handler, $data); }
8982 _end_prefix_mapping( $elt, $handler);
8983 }
8984 else # text or special element
8985 { if( (exists $elt->{'pcdata'}) && (my $characters= $handler->can( 'characters')))
8986 { $characters->( $handler, { Data => $elt->{pcdata} }); }
8987 elsif( (exists $elt->{'cdata'}))
8988 { if( my $start_cdata= $handler->can( 'start_cdata'))
8989 { $start_cdata->( $handler); }
8990 if( my $characters= $handler->can( 'characters'))
8991 { $characters->( $handler, {Data => $elt->{cdata} }); }
8992 if( my $end_cdata= $handler->can( 'end_cdata'))
8993 { $end_cdata->( $handler); }
8994 }
8995 elsif( ((exists $elt->{'target'})) && (my $pi= $handler->can( 'processing_instruction')))
8996 { $pi->( $handler, { Target =>$elt->{target}, Data => $elt->{data} }); }
8997 elsif( ((exists $elt->{'comment'})) && (my $comment= $handler->can( 'comment')))
8998 { $comment->( $handler, { Data => $elt->{comment} }); }
8999 elsif( ((exists $elt->{'ent'})))
9000 {
9001 if( my $se= $handler->can( 'skipped_entity'))
9002 { $se->( $handler, { Name => $elt->ent_name }); }
9003 elsif( my $characters= $handler->can( 'characters'))
9004 { if( defined $elt->ent_string)
9005 { $characters->( $handler, {Data => $elt->ent_string}); }
9006 else
9007 { $characters->( $handler, {Data => $elt->ent_name}); }
9008 }
9009 }
9010  
9011 }
9012 }
9013  
9014 sub _start_tag_data_SAX1
9015 { my( $elt)= @_;
9016 my $name= $XML::Twig::index2gi[$elt->{'gi'}];
9017 return if( ( (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 1) eq '#') && (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 9) ne '#default:') ));
9018 my $attributes={};
9019 my $atts= $elt->{att};
9020 while( my( $att, $value)= each %$atts)
9021 { $attributes->{$att}= $value unless( ( $att=~ m{^#(?!default:)} )); }
9022 my $data= { Name => $name, Attributes => $attributes};
9023 return $data;
9024 }
9025  
9026 sub _end_tag_data_SAX1
9027 { my( $elt)= @_;
9028 return if( ( (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 1) eq '#') && (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 9) ne '#default:') ));
9029 return { Name => $XML::Twig::index2gi[$elt->{'gi'}] };
9030 }
9031  
9032 sub _start_tag_data_SAX2
9033 { my( $elt)= @_;
9034 my $data={};
9035  
9036 my $name= $XML::Twig::index2gi[$elt->{'gi'}];
9037 return if( ( (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 1) eq '#') && (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 9) ne '#default:') ));
9038 $data->{Name} = $name;
9039 $data->{Prefix} = $elt->ns_prefix;
9040 $data->{LocalName} = $elt->local_name;
9041 $data->{NamespaceURI} = $elt->namespace;
9042  
9043 # save a copy of the data so we can re-use it for the end tag
9044 my %sax2_data= %$data;
9045 $elt->{twig_elt_SAX2_data}= \%sax2_data;
9046  
9047 # add the attributes
9048 $data->{Attributes}= $elt->_atts_to_SAX2;
9049  
9050 return $data;
9051 }
9052  
9053 sub _atts_to_SAX2
9054 { my $elt= shift;
9055 my $SAX2_atts= {};
9056 foreach my $att (keys %{$elt->{att}})
9057 {
9058 next if( ( $att=~ m{^#(?!default:)} ));
9059 my $SAX2_att={};
9060 $SAX2_att->{Name} = $att;
9061 $SAX2_att->{Prefix} = _ns_prefix( $att);
9062 $SAX2_att->{LocalName} = _local_name( $att);
9063 $SAX2_att->{NamespaceURI} = $elt->namespace( $SAX2_att->{Prefix});
9064 $SAX2_att->{Value} = $elt->{'att'}->{$att};
9065 my $SAX2_att_name= "{$SAX2_att->{NamespaceURI}}$SAX2_att->{LocalName}";
9066  
9067 $SAX2_atts->{$SAX2_att_name}= $SAX2_att;
9068 }
9069 return $SAX2_atts;
9070 }
9071  
9072 sub _start_prefix_mapping
9073 { my( $elt, $handler, $data)= @_;
9074 if( my $start_prefix_mapping= $handler->can( 'start_prefix_mapping')
9075 and my @new_prefix_mappings= grep { /^\{[^}]*\}xmlns/ || /^\{$XMLNS_URI\}/ } keys %{$data->{Attributes}}
9076 )
9077 { foreach my $prefix (@new_prefix_mappings)
9078 { my $prefix_string= $data->{Attributes}->{$prefix}->{LocalName};
9079 if( $prefix_string eq 'xmlns') { $prefix_string=''; }
9080 my $prefix_data=
9081 { Prefix => $prefix_string,
9082 NamespaceURI => $data->{Attributes}->{$prefix}->{Value}
9083 };
9084 $start_prefix_mapping->( $handler, $prefix_data);
9085 $elt->{twig_end_prefix_mapping} ||= [];
9086 push @{$elt->{twig_end_prefix_mapping}}, $prefix_string;
9087 }
9088 }
9089 }
9090  
9091 sub _end_prefix_mapping
9092 { my( $elt, $handler)= @_;
9093 if( my $end_prefix_mapping= $handler->can( 'end_prefix_mapping'))
9094 { foreach my $prefix (@{$elt->{twig_end_prefix_mapping}})
9095 { $end_prefix_mapping->( $handler, { Prefix => $prefix} ); }
9096 }
9097 }
9098  
9099 sub _end_tag_data_SAX2
9100 { my( $elt)= @_;
9101 return if( ( (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 1) eq '#') && (substr( $XML::Twig::index2gi[$elt->{'gi'}], 0, 9) ne '#default:') ));
9102 return $elt->{twig_elt_SAX2_data};
9103 }
9104  
9105 sub contains_text
9106 { my $elt= shift;
9107 my $child= $elt->{first_child};
9108 while ($child)
9109 { return 1 if( $child->is_text || (exists $child->{'ent'}));
9110 $child= $child->{next_sibling};
9111 }
9112 return 0;
9113 }
9114  
9115 # creates a single pcdata element containing the text as child of the element
9116 # options:
9117 # - force_pcdata: when set to a true value forces the text to be in a #PCDATA
9118 # even if the original element was a #CDATA
9119 sub set_text
9120 { my( $elt, $string, %option)= @_;
9121  
9122 if( $XML::Twig::index2gi[$elt->{'gi'}] eq $PCDATA)
9123 { return $elt->{pcdata}= (delete $elt->{empty} || 1) && $string; }
9124 elsif( $XML::Twig::index2gi[$elt->{'gi'}] eq $CDATA)
9125 { if( $option{force_pcdata})
9126 { $elt->{gi}=$XML::Twig::gi2index{$PCDATA} or $elt->set_gi( $PCDATA);
9127 $elt->{cdata}= '';
9128 return $elt->{pcdata}= (delete $elt->{empty} || 1) && $string;
9129 }
9130 else
9131 { $elt->{cdata}= $string;
9132 return $string;
9133 }
9134 }
9135 elsif( $elt->contains_a_single( $PCDATA) )
9136 { # optimized so we have a slight chance of not losing embedded comments and pi's
9137 $elt->{first_child}->set_pcdata( $string);
9138 return $elt;
9139 }
9140  
9141 foreach my $child (@{[$elt->_children]})
9142 { $child->delete; }
9143  
9144 my $pcdata= $elt->_new_pcdata( $string);
9145 $pcdata->paste( $elt);
9146  
9147 delete $elt->{empty};
9148  
9149 return $elt;
9150 }
9151  
9152 # set the content of an element from a list of strings and elements
9153 sub set_content
9154 { my $elt= shift;
9155  
9156 return $elt unless defined $_[0];
9157  
9158 # attributes can be given as a hash (passed by ref)
9159 if( ref $_[0] eq 'HASH')
9160 { my $atts= shift;
9161 $elt->del_atts; # usually useless but better safe than sorry
9162 $elt->set_atts( $atts);
9163 return $elt unless defined $_[0];
9164 }
9165  
9166 # check next argument for #EMPTY
9167 if( !(ref $_[0]) && ($_[0] eq $EMPTY) )
9168 { $elt->{empty}= 1; return $elt; }
9169  
9170 # case where we really want to do a set_text, the element is '#PCDATA'
9171 # or contains a single PCDATA and we only want to add text in it
9172 if( ($XML::Twig::index2gi[$elt->{'gi'}] eq $PCDATA || $elt->contains_a_single( $PCDATA))
9173 && (@_ == 1) && !( ref $_[0]))
9174 { $elt->set_text( $_[0]);
9175 return $elt;
9176 }
9177 elsif( ($XML::Twig::index2gi[$elt->{'gi'}] eq $CDATA) && (@_ == 1) && !( ref $_[0]))
9178 { $elt->{cdata}= $_[0];
9179 return $elt;
9180 }
9181  
9182 # delete the children
9183 foreach my $child (@{[$elt->_children]})
9184 { $child->delete; }
9185  
9186 if( @_) { delete $elt->{empty}; }
9187  
9188 foreach my $child (@_)
9189 { if( ref( $child) && isa( $child, 'XML::Twig::Elt'))
9190 { # argument is an element
9191 $child->paste( 'last_child', $elt);
9192 }
9193 else
9194 { # argument is a string
9195 if( (my $pcdata= $elt->{last_child}) && $elt->{last_child}->is_pcdata)
9196 { # previous child is also pcdata: just concatenate
9197 $pcdata->{pcdata}= (delete $pcdata->{empty} || 1) && $pcdata->{pcdata} . $child
9198 }
9199 else
9200 { # previous child is not a string: create a new pcdata element
9201 $pcdata= $elt->_new_pcdata( $child);
9202 $pcdata->paste( 'last_child', $elt);
9203 }
9204 }
9205 }
9206  
9207 return $elt;
9208 }
9209  
9210 # inserts an element (whose gi is given) as child of the element
9211 # all children of the element are now children of the new element
9212 # returns the new element
9213 sub insert
9214 { my ($elt, @args)= @_;
9215 # first cut the children
9216 my @children= do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; };
9217 foreach my $child (@children)
9218 { $child->cut; }
9219 # insert elements
9220 while( my $gi= shift @args)
9221 { my $new_elt= $elt->new( $gi);
9222 # add attributes if needed
9223 if( defined( $args[0]) && ( isa( $args[0], 'HASH')) )
9224 { $new_elt->set_atts( shift @args); }
9225 # paste the element
9226 $new_elt->paste( $elt);
9227 delete $elt->{empty};
9228 $elt= $new_elt;
9229 }
9230 # paste back the children
9231 foreach my $child (@children)
9232 { $child->paste( 'last_child', $elt); }
9233 return $elt;
9234 }
9235  
9236 # insert a new element
9237 # $elt->insert_new_element( $opt_position, $gi, $opt_atts_hash, @opt_content);
9238 # the element is created with the same syntax as new
9239 # position is the same as in paste, first_child by default
9240 sub insert_new_elt {
9241 my $elt= shift;
9242 my $position= _op_position($_[0]);
9243 if( $OP_POSITION{$position} )
9244 { shift; }
9245 else
9246 { $position= 'first_child'; }
9247  
9248 my $new_elt = !ref( $_[0] ) && $_[0] =~ m{^\s*<}
9249 ? $elt->parse( $_[0], elt_class => ref($elt) ) # arg is an xml string
9250 : $elt->new( @_); # args are tag/atts/conten
9251  
9252 $new_elt->paste( $position, $elt);
9253 }
9254  
9255 # wraps an element in elements which gi's are given as arguments
9256 # $elt->wrap_in( 'td', 'tr', 'table') wraps the element as a single
9257 # cell in a table for example
9258 # returns the new element
9259 sub wrap_in
9260 { my $elt= shift;
9261 my $t= $elt->twig;
9262 while( my $gi = shift @_)
9263 { my $new_elt = $elt->new( $gi);
9264 if( $elt->{twig_current})
9265 { $t->{twig_current}= $new_elt;
9266 delete $elt->{'twig_current'};
9267 $new_elt->{'twig_current'}=1;
9268 }
9269  
9270 if( my $parent= $elt->{parent})
9271 { $new_elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $new_elt->{parent});} ;
9272 if( $parent->{first_child} == $elt) { $parent->{first_child}= $new_elt; }
9273 if( $parent->{last_child} == $elt) { delete $parent->{empty}; $parent->{last_child}=$new_elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ; }
9274 }
9275 else
9276 { # wrapping the root
9277 my $twig= $elt->twig;
9278 if( $twig && $twig->root && ($twig->root eq $elt) )
9279 { $twig->set_root( $new_elt);
9280 }
9281 }
9282  
9283 if( my $prev_sibling= $elt->{prev_sibling})
9284 { $new_elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $new_elt->{prev_sibling});} ;
9285 $prev_sibling->{next_sibling}= $new_elt;
9286 }
9287  
9288 if( my $next_sibling= $elt->{next_sibling})
9289 { $new_elt->{next_sibling}= $next_sibling;
9290 $next_sibling->{prev_sibling}=$new_elt; if( $XML::Twig::weakrefs) { weaken( $next_sibling->{prev_sibling});} ;
9291 }
9292 $new_elt->{first_child}= $elt;
9293 delete $new_elt->{empty}; $new_elt->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $new_elt->{last_child});} ;
9294  
9295 $elt->{parent}=$new_elt; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
9296 $elt->{prev_sibling}=undef; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
9297 $elt->{next_sibling}= undef;
9298  
9299 # add the attributes if the next argument is a hash ref
9300 if( defined( $_[0]) && (isa( $_[0], 'HASH')) )
9301 { $new_elt->set_atts( shift @_); }
9302  
9303 $elt= $new_elt;
9304 }
9305  
9306 return $elt;
9307 }
9308  
9309 sub replace
9310 { my( $elt, $ref)= @_;
9311  
9312 if( $elt->{parent}) { $elt->cut; }
9313  
9314 if( my $parent= $ref->{parent})
9315 { $elt->{parent}=$parent; if( $XML::Twig::weakrefs) { weaken( $elt->{parent});} ;
9316 if( $parent->{first_child} == $ref) { $parent->{first_child}= $elt; }
9317 if( $parent->{last_child} == $ref) { delete $parent->{empty}; $parent->{last_child}=$elt; if( $XML::Twig::weakrefs) { weaken( $parent->{last_child});} ; }
9318 }
9319 elsif( $ref->twig && $ref == $ref->twig->root)
9320 { $ref->twig->set_root( $elt); }
9321  
9322 if( my $prev_sibling= $ref->{prev_sibling})
9323 { $elt->{prev_sibling}=$prev_sibling; if( $XML::Twig::weakrefs) { weaken( $elt->{prev_sibling});} ;
9324 $prev_sibling->{next_sibling}= $elt;
9325 }
9326 if( my $next_sibling= $ref->{next_sibling})
9327 { $elt->{next_sibling}= $next_sibling;
9328 $next_sibling->{prev_sibling}=$elt; if( $XML::Twig::weakrefs) { weaken( $next_sibling->{prev_sibling});} ;
9329 }
9330  
9331 $ref->{parent}=undef; if( $XML::Twig::weakrefs) { weaken( $ref->{parent});} ;
9332 $ref->{prev_sibling}=undef; if( $XML::Twig::weakrefs) { weaken( $ref->{prev_sibling});} ;
9333 $ref->{next_sibling}= undef;
9334 return $ref;
9335 }
9336  
9337 sub replace_with
9338 { my $ref= shift;
9339 my $elt= shift;
9340 $elt->replace( $ref);
9341 foreach my $new_elt (reverse @_)
9342 { $new_elt->paste( after => $elt); }
9343 return $elt;
9344 }
9345  
9346 # move an element, same syntax as paste, except the element is first cut
9347 sub move
9348 { my $elt= shift;
9349 $elt->cut;
9350 $elt->paste( @_);
9351 return $elt;
9352 }
9353  
9354 # adds a prefix to an element, creating a pcdata child if needed
9355 sub prefix
9356 { my ($elt, $prefix, $option)= @_;
9357 my $asis= ($option && ($option eq 'asis')) ? 1 : 0;
9358 if( (exists $elt->{'pcdata'})
9359 && (($asis && $elt->{asis}) || (!$asis && ! $elt->{asis}))
9360 )
9361 { $elt->{pcdata}= (delete $elt->{empty} || 1) && $prefix . $elt->{pcdata}; }
9362 elsif( $elt->{first_child} && $elt->{first_child}->is_pcdata
9363 && ( ($asis && $elt->{first_child}->{asis})
9364 || (!$asis && ! $elt->{first_child}->{asis}))
9365 )
9366 {
9367 $elt->{first_child}->set_pcdata( $prefix . $elt->{first_child}->pcdata);
9368 }
9369 else
9370 { my $new_elt= $elt->_new_pcdata( $prefix);
9371 my $pos= (exists $elt->{'pcdata'}) ? 'before' : 'first_child';
9372 $new_elt->paste( $pos => $elt);
9373 if( $asis) { $new_elt->set_asis; }
9374 }
9375 return $elt;
9376 }
9377  
9378 # adds a suffix to an element, creating a pcdata child if needed
9379 sub suffix
9380 { my ($elt, $suffix, $option)= @_;
9381 my $asis= ($option && ($option eq 'asis')) ? 1 : 0;
9382 if( (exists $elt->{'pcdata'})
9383 && (($asis && $elt->{asis}) || (!$asis && ! $elt->{asis}))
9384 )
9385 { $elt->{pcdata}= (delete $elt->{empty} || 1) && $elt->{pcdata} . $suffix; }
9386 elsif( $elt->{last_child} && $elt->{last_child}->is_pcdata
9387 && ( ($asis && $elt->{last_child}->{asis})
9388 || (!$asis && ! $elt->{last_child}->{asis}))
9389 )
9390 { $elt->{last_child}->set_pcdata( $elt->{last_child}->pcdata . $suffix); }
9391 else
9392 { my $new_elt= $elt->_new_pcdata( $suffix);
9393 my $pos= (exists $elt->{'pcdata'}) ? 'after' : 'last_child';
9394 $new_elt->paste( $pos => $elt);
9395 if( $asis) { $new_elt->set_asis; }
9396 }
9397 return $elt;
9398 }
9399  
9400 # create a path to an element ('/root/.../gi)
9401 sub path
9402 { my $elt= shift;
9403 my @context= ( $elt, $elt->ancestors);
9404 return "/" . join( "/", reverse map {$_->gi} @context);
9405 }
9406  
9407 sub xpath
9408 { my $elt= shift;
9409 my $xpath;
9410 foreach my $ancestor (reverse $elt->ancestors_or_self)
9411 { my $gi= $XML::Twig::index2gi[$ancestor->{'gi'}];
9412 $xpath.= "/$gi";
9413 my $index= $ancestor->prev_siblings( $gi) + 1;
9414 unless( ($index == 1) && !$ancestor->next_sibling( $gi))
9415 { $xpath.= "[$index]"; }
9416 }
9417 return $xpath;
9418 }
9419  
9420 # methods used mainly by wrap_children
9421  
9422 # return a string with the
9423 # for an element <foo><elt att="val">...</elt><elt2/><elt>...</elt></foo>
9424 # returns '<elt att="val"><elt2><elt>'
9425 sub _stringify_struct
9426 { my( $elt, %opt)= @_;
9427 my $string='';
9428 my $pretty_print= set_pretty_print( 'none');
9429 foreach my $child ($elt->_children)
9430 { $child->add_id; $string .= $child->start_tag( { escape_gt => 1 }) ||''; }
9431 set_pretty_print( $pretty_print);
9432 return $string;
9433 }
9434  
9435 # wrap a series of elements in a new one
9436 sub _wrap_range
9437 { my $elt= shift;
9438 my $gi= shift;
9439 my $atts= isa( $_[0], 'HASH') ? shift : undef;
9440 my $range= shift; # the string with the tags to wrap
9441  
9442 my $t= $elt->twig;
9443  
9444 # get the tags to wrap
9445 my @to_wrap;
9446 while( $range=~ m{<[\w.*-]+\s+[^>]*id=("[^"]*"|'[^']*')[^>]*>}g)
9447 { push @to_wrap, $t->elt_id( substr( $1, 1, -1)); }
9448  
9449 return '' unless @to_wrap;
9450  
9451 my $to_wrap= shift @to_wrap;
9452 my %atts= %$atts;
9453 my $new_elt= $to_wrap->wrap_in( $gi, \%atts);
9454 $_->move( last_child => $new_elt) foreach (@to_wrap);
9455  
9456 return '';
9457 }
9458  
9459 # wrap children matching a regexp in a new element
9460 sub wrap_children
9461 { my( $elt, $regexp, $gi, $atts)= @_;
9462  
9463 $atts ||={};
9464  
9465 my $elt_as_string= $elt->_stringify_struct; # stringify the elt structure
9466 $regexp=~ s{(<[^>]*>)}{_match_expr( $1)}eg; # in the regexp, replace gi's by the proper regexp
9467 $elt_as_string=~ s{($regexp)}{$elt->_wrap_range( $gi, $atts, $1)}eg; # then do the actual replace
9468  
9469 return $elt;
9470 }
9471  
9472 sub _match_expr
9473 { my $tag= shift;
9474 $tag=~s{<\*}{<#star};
9475 my( $gi, %atts)= XML::Twig::_parse_start_tag( $tag);
9476 if( $gi eq '#star') { $gi= $REG_TAG_NAME; }
9477 return _match_tag( $gi, %atts);
9478 }
9479  
9480 sub _match_tag
9481 { my( $elt, %atts)= @_;
9482 my $string= "<$elt\\b";
9483 foreach my $key (sort keys %atts)
9484 { my $val= qq{\Q$atts{$key}\E};
9485 $string.= qq{[^>]*$key=(?:"$val"|'$val')};
9486 }
9487 $string.= qq{[^>]*>};
9488 return "(?:$string)";
9489 }
9490  
9491 sub field_to_att
9492 { my( $elt, $cond, $att)= @_;
9493 $att ||= $cond;
9494 my $child= $elt->first_child( $cond) or return undef;
9495 $elt->set_att( $att => $child->text);
9496 $child->cut;
9497 return $elt;
9498 }
9499  
9500 sub att_to_field
9501 { my( $elt, $att, $tag)= @_;
9502 $tag ||= $att;
9503 my $child= $elt->insert_new_elt( first_child => $tag, $elt->{'att'}->{$att});
9504 $elt->del_att( $att);
9505 return $elt;
9506 }
9507  
9508 # sort children methods
9509  
9510 sub sort_children_on_field
9511 { my $elt = shift;
9512 my $field = shift;
9513 my $get_key= sub { return $_[0]->field( $field) };
9514 return $elt->sort_children( $get_key, @_);
9515 }
9516  
9517 sub sort_children_on_att
9518 { my $elt = shift;
9519 my $att = shift;
9520 my $get_key= sub { return $_[0]->{'att'}->{$att} };
9521 return $elt->sort_children( $get_key, @_);
9522 }
9523  
9524 sub sort_children_on_value
9525 { my $elt = shift;
9526 #my $get_key= eval qq{ sub { $NO_WARNINGS; return \$_[0]->text } };
9527 my $get_key= \&text;
9528 return $elt->sort_children( $get_key, @_);
9529 }
9530  
9531 sub sort_children
9532 { my( $elt, $get_key, %opt)=@_;
9533 $opt{order} ||= 'normal';
9534 $opt{type} ||= 'alpha';
9535 #my( $par_a, $par_b)= ($opt{order} eq 'reverse') ? qw( b a) : qw ( a b) ;
9536 #my $op= ($opt{type} eq 'numeric') ? '<=>' : 'cmp' ;
9537 my @children= $elt->cut_children;
9538 if( $opt{type} eq 'numeric')
9539 { @children= map { $_->[1] }
9540 sort { $a->[0] <=> $b->[0] }
9541 map { [ $get_key->( $_), $_] } @children;
9542 }
9543 elsif( $opt{type} eq 'alpha')
9544 { @children= map { $_->[1] }
9545 sort { $a->[0] cmp $b->[0] }
9546 map { [ $get_key->( $_), $_] } @children;
9547 }
9548 else
9549 { croak "wrong sort type '$opt{type}', should be either 'alpha' or 'numeric'"; }
9550  
9551 @children= reverse @children if( $opt{order} eq 'reverse');
9552 $elt->set_content( @children);
9553 }
9554  
9555 # comparison methods
9556  
9557 sub before
9558 { my( $a, $b)=@_;
9559 if( $a->cmp( $b) == -1) { return 1; } else { return 0; }
9560 }
9561  
9562 sub after
9563 { my( $a, $b)=@_;
9564 if( $a->cmp( $b) == 1) { return 1; } else { return 0; }
9565 }
9566  
9567 sub lt
9568 { my( $a, $b)=@_;
9569 return 1 if( $a->cmp( $b) == -1);
9570 return 0;
9571 }
9572  
9573 sub le
9574 { my( $a, $b)=@_;
9575 return 1 unless( $a->cmp( $b) == 1);
9576 return 0;
9577 }
9578  
9579 sub gt
9580 { my( $a, $b)=@_;
9581 return 1 if( $a->cmp( $b) == 1);
9582 return 0;
9583 }
9584  
9585 sub ge
9586 { my( $a, $b)=@_;
9587 return 1 unless( $a->cmp( $b) == -1);
9588 return 0;
9589 }
9590  
9591 sub cmp
9592 { my( $a, $b)=@_;
9593  
9594 # easy cases
9595 return 0 if( $a == $b);
9596 return 1 if( $a->in($b)); # a in b => a starts after b
9597 return -1 if( $b->in($a)); # b in a => a starts before b
9598  
9599 # ancestors does not include the element itself
9600 my @a_pile= ($a, $a->ancestors);
9601 my @b_pile= ($b, $b->ancestors);
9602  
9603 # the 2 elements are not in the same twig
9604 return undef unless( $a_pile[-1] == $b_pile[-1]);
9605  
9606 # find the first non common ancestors (they are siblings)
9607 my $a_anc= pop @a_pile;
9608 my $b_anc= pop @b_pile;
9609  
9610 while( $a_anc == $b_anc)
9611 { $a_anc= pop @a_pile;
9612 $b_anc= pop @b_pile;
9613 }
9614  
9615 # from there move left and right and figure out the order
9616 my( $a_prev, $a_next, $b_prev, $b_next)= ($a_anc, $a_anc, $b_anc, $b_anc);
9617 while()
9618 { $a_prev= $a_prev->{prev_sibling} || return( -1);
9619 return 1 if( $a_prev == $b_next);
9620 $a_next= $a_next->{next_sibling} || return( 1);
9621 return -1 if( $a_next == $b_prev);
9622 $b_prev= $b_prev->{prev_sibling} || return( 1);
9623 return -1 if( $b_prev == $a_next);
9624 $b_next= $b_next->{next_sibling} || return( -1);
9625 return 1 if( $b_next == $a_prev);
9626 }
9627 }
9628  
9629 sub _dump
9630 { my( $elt, $option)= @_;
9631  
9632 my $atts = defined $option->{atts} ? $option->{atts} : 1;
9633 my $extra = defined $option->{extra} ? $option->{extra} : 0;
9634 my $short_text = defined $option->{short_text} ? $option->{short_text} : 40;
9635 # $option->{depth} is the number of levels that should be dumped
9636  
9637 my $sp= '| ';
9638 my $indent= $sp x $elt->level;
9639 my $indent_sp= ' ' x $elt->level;
9640  
9641 my $dump='';
9642 if( $elt->is_elt)
9643 {
9644 $dump .= $indent . '|-' . $XML::Twig::index2gi[$elt->{'gi'}];
9645  
9646 if( $atts && (my @atts= $elt->att_names) )
9647 { $dump .= ' ' . join( ' ', map { qq{$_="} . $elt->{'att'}->{$_} . qq{"} } @atts); }
9648  
9649 $dump .= "\n";
9650 if( $extra) { $dump .= $elt->_dump_extra_data( $indent, $indent_sp, $short_text); }
9651  
9652 if( exists $option->{depth}) { $option->{depth}--; }
9653 $dump .= join( "", map { $_->_dump( $option) } do { my $elt= $elt; my @children=(); my $child= $elt->{first_child}; while( $child) { push @children, $child; $child= $child->{next_sibling}; } @children; }) unless exists $option->{depth} && $option->{depth} <= 0;
9654 }
9655 else
9656 {
9657 if( (exists $elt->{'pcdata'}))
9658 { $dump .= "$indent|-PCDATA: '" . _short_text( $elt->{pcdata}, $short_text) . "'\n" }
9659 elsif( (exists $elt->{'ent'}))
9660 { $dump .= "$indent|-ENTITY: '" . _short_text( $elt->{ent}, $short_text) . "'\n" }
9661 elsif( (exists $elt->{'cdata'}))
9662 { $dump .= "$indent|-CDATA: '" . _short_text( $elt->{cdata}, $short_text) . "'\n" }
9663 elsif( (exists $elt->{'comment'}))
9664 { $dump .= "$indent|-COMMENT: '" . _short_text( $elt->comment_string, $short_text) . "'\n" }
9665 elsif( (exists $elt->{'target'}))
9666 { $dump .= "$indent|-PI: '" . $elt->{target} . "' - '" . _short_text( $elt->{data}, $short_text) . "'\n" }
9667 if( $extra) { $dump .= $elt->_dump_extra_data( $indent, $indent_sp, $short_text); }
9668 }
9669 return $dump;
9670 }
9671  
9672 sub _dump_extra_data
9673 { my( $elt, $indent, $indent_sp, $short_text)= @_;
9674 my $dump='';
9675 if( $elt->extra_data)
9676 { my $extra_data = $indent . "|-- (cpi before) '" . _short_text( $elt->extra_data, $short_text) . "'";
9677 $extra_data=~ s{\n}{$indent_sp}g;
9678 $dump .= $extra_data . "\n";
9679 }
9680 if( $elt->{extra_data_in_pcdata})
9681 { foreach my $data ( @{$elt->{extra_data_in_pcdata}})
9682 { my $extra_data = $indent . "|-- (cpi offset $data->{offset}) '" . _short_text( $data->{text}, $short_text) . "'";
9683 $extra_data=~ s{\n}{$indent_sp}g;
9684 $dump .= $extra_data . "\n";
9685 }
9686 }
9687 if( $elt->{extra_data_before_end_tag})
9688 { my $extra_data = $indent . "|-- (cpi end) '" . _short_text( $elt->{extra_data_before_end_tag}, $short_text) . "'";
9689 $extra_data=~ s{\n}{$indent_sp}g;
9690 $dump .= $extra_data . "\n";
9691 }
9692 return $dump;
9693 }
9694  
9695 sub _short_text
9696 { my( $string, $length)= @_;
9697 if( !$length || (length( $string) < $length) ) { return $string; }
9698 my $l1= (length( $string) -5) /2;
9699 my $l2= length( $string) - ($l1 + 5);
9700 return substr( $string, 0, $l1) . ' ... ' . substr( $string, -$l2);
9701 }
9702  
9703 sub _and { return _join_defined( ' && ', map { $_ } @_); }
9704 sub _join_defined { return join( shift(), grep { $_ } @_); }
9705  
9706 1;
9707 __END__
« blib/lib/XML/speedup.pl ↑ Summary blib/lib/XML/Twig/XPath.pm »