| 1 | # /=====================================================================\ # | ||
| 2 | # | LaTeXML::Core::Document | # | ||
| 3 | # | Constructs the Document from digested material | # | ||
| 4 | # |=====================================================================| # | ||
| 5 | # | Part of LaTeXML: | # | ||
| 6 | # | Public domain software, produced as part of work done by the | # | ||
| 7 | # | United States Government & not subject to copyright in the US. | # | ||
| 8 | # |---------------------------------------------------------------------| # | ||
| 9 | # | Bruce Miller <bruce.miller@nist.gov> #_# | # | ||
| 10 | # | http://dlmf.nist.gov/LaTeXML/ (o o) | # | ||
| 11 | # \=========================================================ooo==U==ooo=/ # | ||
| 12 | |||
| 13 | package LaTeXML::Core::Document; | ||
| 14 | use strict; | ||
| 15 | use warnings; | ||
| 16 | use LaTeXML::Global; | ||
| 17 | use LaTeXML::Common::Object; | ||
| 18 | use LaTeXML::Core::List; | ||
| 19 | use LaTeXML::Common::Error; | ||
| 20 | use LaTeXML::Common::XML; | ||
| 21 | use LaTeXML::Util::Radix; | ||
| 22 | use Unicode::Normalize; | ||
| 23 | use base qw(LaTeXML::Common::Object); | ||
| 24 | |||
| 25 | #********************************************************************** | ||
| 26 | # These two element names are `leaks' of the document structure into | ||
| 27 | # the Core of LaTeXML... In principle, we should be more abstract! | ||
| 28 | |||
| 29 | our $FONT_ELEMENT_NAME = "ltx:text"; | ||
| 30 | our $MATH_TOKEN_NAME = "ltx:XMTok"; | ||
| 31 | #********************************************************************** | ||
| 32 | |||
| 33 | # [could conceivable make more sense to let the Stomach create the Document?] | ||
| 34 | |||
| 35 | # Mystery attributes: | ||
| 36 | # font : | ||
| 37 | # Probably should keep font ONLY in extra properties, | ||
| 38 | # THEN once complete, compute the relative font at each node that accepts | ||
| 39 | # a font attribute, and add the attribute. | ||
| 40 | # locator : a box | ||
| 41 | |||
| 42 | sub new { | ||
| 43 | my ($class, $model) = @_; | ||
| 44 | my $doc = XML::LibXML::Document->new("1.0", "UTF-8"); | ||
| 45 | # We'll set the DocType when the 1st Element gets added. | ||
| 46 | return bless { document => $doc, node => $doc, model => $model, | ||
| 47 | idstore => {}, labelstore => {}, | ||
| 48 | node_fonts => {}, node_boxes => {}, node_properties => {}, | ||
| 49 | pending => [], progress => 0 }, $class; } | ||
| 50 | |||
| 51 | #********************************************************************** | ||
| 52 | # Basic Accessors | ||
| 53 | |||
| 54 | # This will be a node of type XML_DOCUMENT_NODE | ||
| 55 | sub getDocument { my ($self) = @_; return $$self{document}; } | ||
| 56 | sub getModel { my ($self) = @_; return $$self{model}; } | ||
| 57 | sub documentElement { my ($self) = @_; return $$self{document}->documentElement; } | ||
| 58 | |||
| 59 | # Get the node representing the current insertion point. | ||
| 60 | # The node will have nodeType of | ||
| 61 | # XML_DOCUMENT_NODE if the document is empty, so far. | ||
| 62 | # XML_ELEMENT_NODE for normal elements. | ||
| 63 | # XML_TEXT_NODE if the last insertion was text | ||
| 64 | # The other node types will not appear here. | ||
| 65 | sub getNode { my ($self) = @_; return $$self{node}; } | ||
| 66 | |||
| 67 | sub setNode { | ||
| 68 | my ($self, $node) = @_; | ||
| 69 | my $type = $node->nodeType; | ||
| 70 | if ($type == XML_DOCUMENT_FRAG_NODE) { # Whoops | ||
| 71 | my @n = $node->childNodes; | ||
| 72 | if (@n > 1) { | ||
| 73 | Error('unexpected', 'multiple-nodes', $self, | ||
| 74 | "Cannot set insertion point to a DOCUMENT_FRAG_NODE", Stringify($node)); } | ||
| 75 | elsif (@n < 1) { | ||
| 76 | Error('unexpected', 'empty-nodes', $self, | ||
| 77 | "Cannot set insertion point to an empty DOCUMENT_FRAG_NODE"); } | ||
| 78 | $node = $n[0]; } | ||
| 79 | $$self{node} = $node; | ||
| 80 | return; } | ||
| 81 | |||
| 82 | sub getLocator { | ||
| 83 | my ($self) = @_; | ||
| 84 | if (my $box = $self->getNodeBox($$self{node})) { | ||
| 85 | return $box->getLocator; } | ||
| 86 | else { | ||
| 87 | return; } } # well? | ||
| 88 | |||
| 89 | # Get the element at (or containing) the current insertion point. | ||
| 90 | sub getElement { | ||
| 91 | my ($self) = @_; | ||
| 92 | my $node = $$self{node}; | ||
| 93 | $node = $node->parentNode if $node->getType == XML_TEXT_NODE; | ||
| 94 | return ($node->getType == XML_DOCUMENT_NODE ? undef : $node); } | ||
| 95 | |||
| 96 | # Get the child elements of the given $node | ||
| 97 | sub getChildElements { | ||
| 98 | my ($self, $node) = @_; | ||
| 99 | return (!$node ? () : grep { $_->nodeType == XML_ELEMENT_NODE } $node->childNodes); } | ||
| 100 | |||
| 101 | # Get the last element node (if any) in $node | ||
| 102 | sub getLastChildElement { | ||
| 103 | my ($self, $node) = @_; | ||
| 104 | if ($node->hasChildNodes) { | ||
| 105 | my $n = $node->lastChild; | ||
| 106 | while ($n && $n->nodeType != XML_ELEMENT_NODE) { | ||
| 107 | $n = $node->previousSibling; } | ||
| 108 | return $n; } } | ||
| 109 | |||
| 110 | # get the first element node (if any) in $node | ||
| 111 | sub getFirstChildElement { | ||
| 112 | my ($self, $node) = @_; | ||
| 113 | if ($node->hasChildNodes) { | ||
| 114 | my $n = $node->firstChild; | ||
| 115 | while ($n && $n->nodeType != XML_ELEMENT_NODE) { | ||
| 116 | $n = $n->nextSibling; } | ||
| 117 | return $n; } | ||
| 118 | return; } | ||
| 119 | |||
| 120 | # get the second element node (if any) in $node | ||
| 121 | sub getSecondChildElement { | ||
| 122 | my ($self, $node) = @_; | ||
| 123 | my $first_child = $self->getFirstChildElement($node); | ||
| 124 | my $second_child = $first_child && $first_child->nextSibling; | ||
| 125 | while ($second_child && $second_child->nodeType != XML_ELEMENT_NODE) { | ||
| 126 | $second_child = $second_child->nextSibling; } | ||
| 127 | return $second_child; } | ||
| 128 | |||
| 129 | # Find the nodes according to the given $xpath expression, | ||
| 130 | # the xpath is relative to $node (if given), otherwise to the document node. | ||
| 131 | sub findnodes { | ||
| 132 | my ($self, $xpath, $node) = @_; | ||
| 133 | return $$self{model}->getXPath->findnodes($xpath, ($node || $$self{document})); } | ||
| 134 | |||
| 135 | # Like findnodes, but only returns the first matched node | ||
| 136 | sub findnode { | ||
| 137 | my ($self, $xpath, $node) = @_; | ||
| 138 | my @nodes = $$self{model}->getXPath->findnodes($xpath, ($node || $$self{document})); | ||
| 139 | return (@nodes ? $nodes[0] : undef); } | ||
| 140 | |||
| 141 | # Get the node's qualified name in standard form | ||
| 142 | # Ie. using the registered prefix for that namespace. | ||
| 143 | # NOTE: Reconsider how _Capture_ & _WildCard_ should be integrated!?! | ||
| 144 | # NOTE: Should Deprecate! (use model) | ||
| 145 | sub getNodeQName { | ||
| 146 | my ($self, $node) = @_; | ||
| 147 | return $node && $$self{model}->getNodeQName($node); } | ||
| 148 | |||
| 149 | #********************************************************************** | ||
| 150 | # Extensions of Model. | ||
| 151 | |||
| 152 | sub canContain { | ||
| 153 | my ($self, $tag, $child) = @_; | ||
| 154 | my $model = $$self{model}; | ||
| 155 | $tag = $model->getNodeQName($tag) if ref $tag; # In case tag is a node. | ||
| 156 | $child = $model->getNodeQName($child) if ref $child; # In case child is a node. | ||
| 157 | return $model->canContain($tag, $child); } | ||
| 158 | |||
| 159 | # Can an element with (qualified name) $tag contain a $childtag element indirectly? | ||
| 160 | # That is, by openning some number of autoOpen'able tags? | ||
| 161 | # And if so, return the tag to open. | ||
| 162 | sub canContainIndirect { | ||
| 163 | my ($self, $tag, $child) = @_; | ||
| 164 | my $model = $$self{model}; | ||
| 165 | $tag = $model->getNodeQName($tag) if ref $tag; # In case tag is a node. | ||
| 166 | $child = $model->getNodeQName($child) if ref $child; # In case child is a node. | ||
| 167 | # $imodel{$tag}{$child} => $intermediate || $child | ||
| 168 | my $imodel = $STATE->lookupValue('INDIRECT_MODEL'); | ||
| 169 | if (!$imodel) { | ||
| 170 | $imodel = $self->computeIndirectModel(); | ||
| 171 | $STATE->assignValue(INDIRECT_MODEL => $imodel, 'global'); } | ||
| 172 | return $$imodel{$tag}{$child}; } | ||
| 173 | |||
| 174 | # The indirect model includes all elements allowed as direct children, | ||
| 175 | # and all descendents of a node that can be inserted after autoOpen'ing intermediate elements. | ||
| 176 | # This model therefor includes information from the Schema, as well as | ||
| 177 | # autoOpen information that may be introduced in binding files. | ||
| 178 | # [Thus it should NOT be modifying the Model object, which may cover several documents in Daemon] | ||
| 179 | # $imodel{$tag}{$child} => $open means if in $tag, to open $child, we must first open $open | ||
| 180 | sub computeIndirectModel { | ||
| 181 | my ($self) = @_; | ||
| 182 | my $model = $$self{model}; | ||
| 183 | my $imodel = {}; | ||
| 184 | # Determine any indirect paths to each descendent via an `autoOpen-able' tag. | ||
| 185 | local %::OPENABILITY = (); | ||
| 186 | foreach my $tag ($model->getTags) { | ||
| 187 | my $x; | ||
| 188 | if (($x = $STATE->lookupMapping('TAG_PROPERTIES', $tag)) && ($x = $$x{autoOpen})) { | ||
| 189 | $::OPENABILITY{$tag} = ($x =~ /^\d*\.\d*$/ ? $x : 1); } | ||
| 190 | else { | ||
| 191 | $::OPENABILITY{$tag} = 0; } } | ||
| 192 | foreach my $tag ($model->getTags) { | ||
| 193 | local %::DESC = (); | ||
| 194 | computeIndirectModel_aux($model, $tag, '', 1); | ||
| 195 | foreach my $kid (sort keys %::DESC) { | ||
| 196 | my $best = 0; # Find best path to $kid. | ||
| 197 | foreach my $start (sort keys %{ $::DESC{$kid} }) { | ||
| 198 | if (($tag ne $kid) && ($tag ne $start) && ($::DESC{$kid}{$start} > $best)) { | ||
| 199 | $$imodel{$tag}{$kid} = $start; $best = $::DESC{$kid}{$start}; } } } } | ||
| 200 | # PATCHUP | ||
| 201 | if ($$model{permissive}) { # !!! Alarm!!! | ||
| 202 | $$imodel{'#Document'}{'#PCDATA'} = 'ltx:p'; } | ||
| 203 | return $imodel; } | ||
| 204 | |||
| 205 | sub computeIndirectModel_aux { | ||
| 206 | my ($model, $tag, $start, $desirability) = @_; | ||
| 207 | my $x; | ||
| 208 | foreach my $kid ($model->getTagContents($tag)) { | ||
| 209 | next if $::DESC{$kid}{$start}; # Already solved | ||
| 210 | $::DESC{$kid}{$start} = $desirability if $start; | ||
| 211 | if (($kid ne '#PCDATA') && ($x = $::OPENABILITY{$kid})) { | ||
| 212 | computeIndirectModel_aux($model, $kid, $start || $kid, $desirability * $x); } } | ||
| 213 | return; } | ||
| 214 | |||
| 215 | sub canContainSomehow { | ||
| 216 | my ($self, $tag, $child) = @_; | ||
| 217 | my $model = $$self{model}; | ||
| 218 | $tag = $model->getNodeQName($tag) if ref $tag; # In case tag is a node. | ||
| 219 | $child = $model->getNodeQName($child) if ref $child; # In case child is a node. | ||
| 220 | return $model->canContain($tag, $child) || $self->canContainIndirect($tag, $child); } | ||
| 221 | |||
| 222 | sub canHaveAttribute { | ||
| 223 | my ($self, $tag, $attrib) = @_; | ||
| 224 | my $model = $$self{model}; | ||
| 225 | $tag = $model->getNodeQName($tag) if ref $tag; # In case tag is a node. | ||
| 226 | return $model->canHaveAttribute($tag, $attrib); } | ||
| 227 | |||
| 228 | sub canAutoOpen { | ||
| 229 | my ($self, $tag) = @_; | ||
| 230 | if (my $props = $STATE->lookupMapping('TAG_PROPERTIES', $tag)) { | ||
| 231 | return $$props{autoClose}; } } | ||
| 232 | |||
| 233 | # Dirty little secrets: | ||
| 234 | # You can generically allow an element to autoClose using Tag. | ||
| 235 | # OR you can indicate a specific node can autoClose, or forbid it, using | ||
| 236 | # the _autoclose or _noautoclose attributes! | ||
| 237 | sub canAutoClose { | ||
| 238 | my ($self, $node) = @_; | ||
| 239 | my $t = $node->nodeType; | ||
| 240 | my $model = $$self{model}; | ||
| 241 | my $props; | ||
| 242 | return ($t == XML_TEXT_NODE) || ($t == XML_COMMENT_NODE) # text or comments auto close | ||
| 243 | || (($t == XML_ELEMENT_NODE) # otherwise must be element | ||
| 244 | && !$node->getAttribute('_noautoclose') # without _noautoclose | ||
| 245 | && ($node->getAttribute('_autoclose') # and either with _autoclose | ||
| 246 | # OR it has autoClose set on tag properties | ||
| 247 | || (($props = $STATE->lookupMapping('TAG_PROPERTIES', $self->getNodeQName($node))) | ||
| 248 | && $$props{autoClose}))); | ||
| 249 | } | ||
| 250 | |||
| 251 | # get the actions that should be performed on afterOpen or afterClose | ||
| 252 | sub getTagActionList { | ||
| 253 | my ($self, $tag, $when) = @_; | ||
| 254 | $tag = $$self{model}->getNodeQName($tag) if ref $tag; # In case tag is a node. | ||
| 255 | my ($p, $n) = (undef, $tag); | ||
| 256 | if ($tag =~ /^([^:]+):(.+)$/) { | ||
| 257 | ($p, $n) = ($1, $2); } | ||
| 258 | my $when0 = $when . ':early'; | ||
| 259 | my $when1 = $when . ':late'; | ||
| 260 | my $taghash = $STATE->lookupMapping('TAG_PROPERTIES', $tag) || {}; | ||
| 261 | my $nshash = ((defined $p) && $STATE->lookupMapping('TAG_PROPERTIES', $p . ':*')) || {}; | ||
| 262 | my $allhash = $STATE->lookupMapping('TAG_PROPERTIES', '*') || {}; | ||
| 263 | my $v; | ||
| 264 | return ( | ||
| 265 | (($v = $$taghash{$when0}) ? @$v : ()), | ||
| 266 | (($v = $$nshash{$when0}) ? @$v : ()), | ||
| 267 | (($v = $$allhash{$when0}) ? @$v : ()), | ||
| 268 | (($v = $$taghash{$when}) ? @$v : ()), | ||
| 269 | (($v = $$nshash{$when}) ? @$v : ()), | ||
| 270 | (($v = $$allhash{$when}) ? @$v : ()), | ||
| 271 | (($v = $$taghash{$when1}) ? @$v : ()), | ||
| 272 | (($v = $$nshash{$when1}) ? @$v : ()), | ||
| 273 | (($v = $$allhash{$when1}) ? @$v : ()), | ||
| 274 | ); } | ||
| 275 | |||
| 276 | #********************************************************************** | ||
| 277 | # This is a diagnostic tool that MIGHT help locate XML::LibXML bugs; | ||
| 278 | # It simply walks through the document tree. Use it before and after | ||
| 279 | # places where some sort of data corruption might have taken place. | ||
| 280 | sub doctest { | ||
| 281 | my ($self, $when, $severe) = @_; | ||
| 282 | local $LaTeXML::NNODES = 0; | ||
| 283 | print STDERR "\nSTART DOC TEST $when....." . ($severe ? "\n" : ''); | ||
| 284 | if (my $root = $self->getDocument->documentElement) { | ||
| 285 | $self->doctest_rec(undef, $root, $severe); } | ||
| 286 | print STDERR "...(" . $LaTeXML::NNODES . " nodes)....DONE\n"; | ||
| 287 | return; } | ||
| 288 | |||
| 289 | sub doctest_rec { | ||
| 290 | my ($self, $parent, $node, $severe) = @_; | ||
| 291 | # Check consistency of document, parent & type, before proceeding | ||
| 292 | $self->doctest_head($parent, $node, $severe); | ||
| 293 | my $type = $node->nodeType; | ||
| 294 | if ($type == XML_ELEMENT_NODE) { | ||
| 295 | print STDERR "ELEMENT " | ||
| 296 | . join(' ', "<" . $$self{model}->getNodeQName($node), | ||
| 297 | (map { $_->nodeName . '="' . $_->getValue . '"' } $node->attributes)) . ">\n" | ||
| 298 | if $severe; | ||
| 299 | $self->doctest_children($node, $severe); } | ||
| 300 | elsif ($type == XML_ATTRIBUTE_NODE) { | ||
| 301 | print STDERR "ATTRIBUTE " . $node->nodeName . "=>" . $node->getValue . "\n" if $severe; } | ||
| 302 | elsif ($type == XML_TEXT_NODE) { | ||
| 303 | print STDERR "TEXT " . $node->textContent . "\n" if $severe; } | ||
| 304 | elsif ($type == XML_CDATA_SECTION_NODE) { | ||
| 305 | print STDERR "CDATA " . $node->textContent . "\n" if $severe; } | ||
| 306 | # elsif($type == XML_ENTITY_REF_NODE){} | ||
| 307 | # elsif($type == XML_ENTITY_NODE){} | ||
| 308 | elsif ($type == XML_PI_NODE) { | ||
| 309 | print STDERR "PI " . $node->localname . " " . $node->getData . "\n" if $severe; } | ||
| 310 | elsif ($type == XML_COMMENT_NODE) { | ||
| 311 | print STDERR "COMMENT " . $node->textContent . "\n" if $severe; } | ||
| 312 | # elsif($type == XML_DOCUMENT_NODE){} | ||
| 313 | # elsif($type == XML_DOCUMENT_TYPE_NODE){ | ||
| 314 | elsif ($type == XML_DOCUMENT_FRAG_NODE) { | ||
| 315 | print STDERR "DOCUMENT_FRAG \n" if $severe; | ||
| 316 | $self->doctest_children($node, $severe); } | ||
| 317 | # elsif($type == XML_NOTATION_NODE){} | ||
| 318 | # elsif($type == XML_HTML_DOCUMENT_NODE){} | ||
| 319 | # elsif($type == XML_DTD_NODE){} | ||
| 320 | else { | ||
| 321 | print STDERR "OTHER $type\n" if $severe; } | ||
| 322 | return; } | ||
| 323 | |||
| 324 | sub doctest_head { | ||
| 325 | my ($self, $parent, $node, $severe) = @_; | ||
| 326 | # Check consistency of document, parent & type, before proceeding | ||
| 327 | print STDERR " NODE $$node [" if $severe; # BEFORE checking nodeType! | ||
| 328 | print STDERR "d" if $severe; | ||
| 329 | if (!$node->ownerDocument->isSameNode($self->getDocument)) { | ||
| 330 | print STDERR "!" if $severe; } | ||
| 331 | print STDERR "p" if $severe; | ||
| 332 | if ($parent && !$node->parentNode->isSameNode($parent)) { | ||
| 333 | print STDERR "!" if $severe; } | ||
| 334 | print STDERR "t" if $severe; | ||
| 335 | my $type = $node->nodeType; | ||
| 336 | print STDERR "] " if $severe; | ||
| 337 | return; } | ||
| 338 | |||
| 339 | sub doctest_children { | ||
| 340 | my ($self, $node, $severe) = @_; | ||
| 341 | print STDERR "[fc" if $severe; | ||
| 342 | my $c = $node->firstChild; | ||
| 343 | while ($c) { | ||
| 344 | print STDERR "]\n" if $severe; | ||
| 345 | $self->doctest_rec($node, $c, $severe); | ||
| 346 | print STDERR "[nc" if $severe; | ||
| 347 | $c = $c->nextSibling; } | ||
| 348 | print STDERR "]done\n" if $severe; | ||
| 349 | return; } | ||
| 350 | |||
| 351 | #********************************************************************** | ||
| 352 | # This should be called before returning the final XML::LibXML::Document to the | ||
| 353 | # outside world. It resolves the fonts for each node relative to it's ancestors. | ||
| 354 | # It removes the `helper' attributes that store fonts, source box, etc. | ||
| 355 | sub finalize { | ||
| 356 | my ($self) = @_; | ||
| 357 | $self->pruneXMDuals; | ||
| 358 | if (my $root = $self->getDocument->documentElement) { | ||
| 359 | local $LaTeXML::FONT = LaTeXML::Common::Font->textDefault; | ||
| 360 | $self->finalize_rec($root); | ||
| 361 | set_RDFa_prefixes($self->getDocument, $STATE->lookupValue('RDFa_prefixes')); } | ||
| 362 | # return $$self{document}; } | ||
| 363 | return $self; } | ||
| 364 | |||
| 365 | sub finalize_rec { | ||
| 366 | my ($self, $node) = @_; | ||
| 367 | my $model = $$self{model}; | ||
| 368 | my $qname = $model->getNodeQName($node); | ||
| 369 | # _standalone_font is typically for metadata that gets extracted out of context | ||
| 370 | my $declared_font = ($node->getAttribute('_standalone_font') | ||
| 371 | ? LaTeXML::Common::Font->textDefault : $LaTeXML::FONT); | ||
| 372 | my $desired_font = $LaTeXML::FONT; | ||
| 373 | my %pending_declaration = (); | ||
| 374 | if (my $comment = $node->getAttribute('_pre_comment')) { | ||
| 375 | $node->parentNode->insertBefore(XML::LibXML::Comment->new($comment), $node); } | ||
| 376 | if (my $comment = $node->getAttribute('_comment')) { | ||
| 377 | $node->parentNode->insertAfter(XML::LibXML::Comment->new($comment), $node); } | ||
| 378 | |||
| 379 | if (my $font_attr = $node->getAttribute('_font')) { | ||
| 380 | $desired_font = $$self{node_fonts}{$font_attr}; | ||
| 381 | %pending_declaration = $desired_font->relativeTo($declared_font); | ||
| 382 | if (($node->hasChildNodes || $node->getAttribute('_force_font')) | ||
| 383 | && scalar(keys %pending_declaration)) { | ||
| 384 | foreach my $attr (keys %pending_declaration) { | ||
| 385 | # Add (or combine, for @class) the attributes to the current node. | ||
| 386 | if ($model->canHaveAttribute($qname, $attr)) { | ||
| 387 | my $value = $pending_declaration{$attr}{value}; | ||
| 388 | if ($attr eq 'class') { # Generalize? | ||
| 389 | if (my $ovalue = $node->getAttribute('class')) { | ||
| 390 | $value .= ' ' . $ovalue; } } | ||
| 391 | $self->setAttribute($node, $attr => $value); | ||
| 392 | |||
| 393 | # Merge to set the font currently in effect | ||
| 394 | $declared_font = $declared_font->merge(%{ $pending_declaration{$attr}{properties} }); | ||
| 395 | delete $pending_declaration{$attr}; } } | ||
| 396 | } } | ||
| 397 | |||
| 398 | local $LaTeXML::FONT = $declared_font; | ||
| 399 | foreach my $child ($node->childNodes) { | ||
| 400 | my $type = $child->nodeType; | ||
| 401 | if ($type == XML_ELEMENT_NODE) { | ||
| 402 | my $was_forcefont = $child->getAttribute('_force_font'); | ||
| 403 | $self->finalize_rec($child); | ||
| 404 | # Also check if child is $FONT_ELEMENT_NAME AND has no attributes | ||
| 405 | # AND providing $node can contain that child's content, we'll collapse it. | ||
| 406 | if (($model->getNodeQName($child) eq $FONT_ELEMENT_NAME) | ||
| 407 | && !$was_forcefont && !$child->hasAttributes) { | ||
| 408 | my @grandchildren = $child->childNodes; | ||
| 409 | if (!grep { !$self->canContain($qname, $_) } @grandchildren) { | ||
| 410 | $self->replaceNode($child, @grandchildren); } } | ||
| 411 | } | ||
| 412 | # On the other hand, if the font declaration has NOT been effected, | ||
| 413 | # We'll need to put an extra wrapper around the text! | ||
| 414 | # This is usually ltx:text, but Font information can override this (eg. for \emph) | ||
| 415 | elsif ($type == XML_TEXT_NODE) { | ||
| 416 | # Remove any pending declarations that can't be on $FONT_ELEMENT_NAME | ||
| 417 | my $elementname = $pending_declaration{element}{value} || $FONT_ELEMENT_NAME; | ||
| 418 | foreach my $key (keys %pending_declaration) { | ||
| 419 | delete $pending_declaration{$key} unless $self->canHaveAttribute($elementname, $key); } | ||
| 420 | if ($self->canContain($qname, $elementname) | ||
| 421 | && scalar(keys %pending_declaration)) { | ||
| 422 | # Too late to do wrapNodes? | ||
| 423 | my $text = $self->wrapNodes($elementname, $child); | ||
| 424 | # Add (or combine) attributes | ||
| 425 | foreach my $attr (keys %pending_declaration) { | ||
| 426 | my $value = $pending_declaration{$attr}{value}; | ||
| 427 | if ($attr eq 'class') { # Generalize? | ||
| 428 | if (my $ovalue = $text->getAttribute('class')) { | ||
| 429 | $value .= ' ' . $ovalue; } } | ||
| 430 | $self->setAttribute($text, $attr => $value); } | ||
| 431 | $self->finalize_rec($text); # Now have to clean up the new node! | ||
| 432 | } | ||
| 433 | } } | ||
| 434 | |||
| 435 | # Attributes that begin with (the semi-legal) "_" are for Bookkeeping. | ||
| 436 | # Remove them now. | ||
| 437 | foreach my $attr ($node->attributes) { | ||
| 438 | my $n = $attr->nodeName; | ||
| 439 | $node->removeAttribute($n) if $n =~ /^_/; } | ||
| 440 | return; } | ||
| 441 | |||
| 442 | #====================================================================== | ||
| 443 | # Experimental Serializer | ||
| 444 | # inserts formatting whitespace ONLY where allowed by the schema | ||
| 445 | #====================================================================== | ||
| 446 | use Encode; | ||
| 447 | |||
| 448 | sub toString { | ||
| 449 | #sub serialize { | ||
| 450 | my ($self, $format) = @_; | ||
| 451 | # This line is to use libxml2's built-in serializer w/indentation heuristic. | ||
| 452 | # Apparently, libxml2 is giving us "binary" or byte strings which we'd prefer to have as text. | ||
| 453 | # return decode('UTF-8',$self->getDocument->toString($format)); } | ||
| 454 | # This uses our own serializer emulating libxml2's heuristic indentation. | ||
| 455 | # return $self->serialize_aux($self->getDocument, 0, 0, 1); } | ||
| 456 | # This uses our own serializer w/ correct indentation rules. | ||
| 457 | return $self->serialize_aux($self->getDocument, 0, 0, 0); } | ||
| 458 | |||
| 459 | # We ought to try for something close to C14N (http://www.w3.org/TR/xml-c14n), | ||
| 460 | # but keep XML declaration, comments and don't convert empty elements. | ||
| 461 | sub serialize_aux { | ||
| 462 | my ($self, $node, $depth, $noindent, $heuristic) = @_; | ||
| 463 | my $type = $node->nodeType; | ||
| 464 | my $model = $$self{model}; | ||
| 465 | my $indent = (' ' x $depth); | ||
| 466 | if ($type == XML_DOCUMENT_NODE) { | ||
| 467 | my @children = $node->childNodes; | ||
| 468 | return join('', '<?xml version="1.0" encoding="UTF-8"?>', "\n", | ||
| 469 | (map { serialize_aux($self, $_, $depth, $noindent, $heuristic) } @children)); } | ||
| 470 | elsif ($type == XML_ELEMENT_NODE) { | ||
| 471 | my $tag = $model->getNodeDocumentQName($node); | ||
| 472 | my @children = $node->childNodes; | ||
| 473 | # since we're pretty-printing, we _could_ wrap attributes to nominal line length! | ||
| 474 | my @anodes = $node->attributes; | ||
| 475 | my %nsnodes = map { $model->getNodeDocumentQName($_) => serialize_attr($_->nodeValue) } | ||
| 476 | grep { $_->nodeType == XML_NAMESPACE_DECL } @anodes; | ||
| 477 | my %atnodes = map { $model->getNodeDocumentQName($_) => serialize_attr($_->nodeValue) } | ||
| 478 | grep { $_->nodeType == XML_ATTRIBUTE_NODE } @anodes; | ||
| 479 | my $start = join(' ', | ||
| 480 | # start of tag | ||
| 481 | '<' . $tag, | ||
| 482 | # Namespace declarations | ||
| 483 | (map { $_ . '="' . $nsnodes{$_} . '"' } sort keys %nsnodes), | ||
| 484 | # Regular attributes | ||
| 485 | (map { $_ . '="' . $atnodes{$_} . '"' } sort keys %atnodes) | ||
| 486 | ); | ||
| 487 | my $noindent_children = ($heuristic | ||
| 488 | # This emulates libxml2's heuristic | ||
| 489 | # ? $noindent || grep { $_->nodeType != XML_ELEMENT_NODE } @children | ||
| 490 | ? $noindent || grep { $_->nodeType == XML_TEXT_NODE } @children | ||
| 491 | # This is the "Correct" way to determine whether to add indentation | ||
| 492 | : $model->canContain($self->getNodeQName($node), '#PCDATA')); | ||
| 493 | return join('', | ||
| 494 | ($noindent ? '' : $indent), $start, | ||
| 495 | (scalar(@children) # with contents. | ||
| 496 | ? ('>', ($noindent_children ? '' : "\n"), | ||
| 497 | (map { serialize_aux($self, $_, $depth + 1, $noindent_children, $heuristic) } @children), | ||
| 498 | ($noindent_children ? '' : $indent), '</' . $tag . '>', ($noindent ? '' : "\n")) | ||
| 499 | : ('/>' . ($noindent ? '' : "\n")))); } # empty element. | ||
| 500 | elsif ($type == XML_TEXT_NODE) { # NO indentation! | ||
| 501 | return serialize_string($node->textContent); } | ||
| 502 | elsif ($type == XML_PI_NODE) { | ||
| 503 | # should code this by hand, as well... | ||
| 504 | return join('', ($noindent ? '' : $indent), $node->toString, ($noindent ? '' : "\n")); } | ||
| 505 | elsif ($type == XML_COMMENT_NODE) { | ||
| 506 | return join('', '<!-- ', serialize_string($node->textContent), '-->'); } | ||
| 507 | else { | ||
| 508 | return ''; } } | ||
| 509 | |||
| 510 | sub serialize_string { | ||
| 511 | my ($string) = @_; | ||
| 512 | # Basic entities | ||
| 513 | $string =~ s/&/&/g; | ||
| 514 | $string =~ s/>/>/g; | ||
| 515 | $string =~ s/</</g; | ||
| 516 | # Remove dis-allowed code-points. | ||
| 517 | # $string =~ s/(?:\x{00}-\x{08}|\x{0B}|\x{0C}|\x{0D}-\x{19}|\x{D800}-\x{DFFF}|\x{FFFE}-\x{FFFF})//g; | ||
| 518 | # Hmm... the upper ranges gives warning in some Perls... | ||
| 519 | $string =~ s/(?:\x{00}-\x{08}|\x{0B}|\x{0C}|\x{0D}-\x{19})//g; | ||
| 520 | return $string; } | ||
| 521 | |||
| 522 | sub serialize_attr { | ||
| 523 | my ($string) = @_; | ||
| 524 | $string = serialize_string($string); | ||
| 525 | # And escape any remaining special code points | ||
| 526 | $string =~ s/"/"/g; | ||
| 527 | $string =~ s/\n/ /gs; | ||
| 528 | $string =~ s/\t/	/gs; | ||
| 529 | return $string; } | ||
| 530 | |||
| 531 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 532 | # Document construction at the Current Insertion Point. | ||
| 533 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 534 | |||
| 535 | #********************************************************************** | ||
| 536 | # absorb the given $box into the DOM (called from constructors). | ||
| 537 | # This will return a list of whatever nodes were created. | ||
| 538 | # Note that this may include nodes that are children of other nodes in the list | ||
| 539 | # or nodes that are no longer in the document. | ||
| 540 | # Also, note that when a text nodes is appended to, the complete text node is in the list, | ||
| 541 | # not just the portion that was added. | ||
| 542 | # [Note that recording the nodes being constructed isn't all that costly, | ||
| 543 | # but filtering them for parent/child relations IS, particularly since it usually isn't needed] | ||
| 544 | # | ||
| 545 | # A $box that is a Box, or List, or Whatsit, is responsible for carrying out | ||
| 546 | # its own insertion, but it should ultimately call methods of Document | ||
| 547 | # that will record the nodes that were created. | ||
| 548 | # $box can also be a plain string which will be inserted according to whatever | ||
| 549 | # font, mode, etc, are in %props. | ||
| 550 | sub absorb { | ||
| 551 | my ($self, $object, %props) = @_; | ||
| 552 | no warnings 'recursion'; | ||
| 553 | # Nothing? Skip it | ||
| 554 | my @boxes = ($object); | ||
| 555 | my @results = (); | ||
| 556 | while (@boxes) { | ||
| 557 | my $box = shift(@boxes); | ||
| 558 | next unless defined $box; | ||
| 559 | # Simply unwind Lists to avoid unneccessary recursion; This occurs quite frequently! | ||
| 560 | if (((ref $box) || 'nothing') eq 'LaTeXML::Core::List') { | ||
| 561 | unshift(@boxes, $box->unlist); | ||
| 562 | next; } | ||
| 563 | # A Proper Box or Whatsit? It will handle it. | ||
| 564 | if (ref $box) { | ||
| 565 | local $LaTeXML::BOX = $box; | ||
| 566 | # [ATTEMPT to] only record if we're running in NON-VOID context. | ||
| 567 | # [but wantarray seems defined MUCH more than I would have expected!?] | ||
| 568 | if ($LaTeXML::RECORDING_CONSTRUCTION || defined wantarray) { | ||
| 569 | my @n = (); | ||
| 570 | { local $LaTeXML::RECORDING_CONSTRUCTION = 1; | ||
| 571 | local @LaTeXML::CONSTRUCTED_NODES = (); | ||
| 572 | $box->beAbsorbed($self); | ||
| 573 | @n = @LaTeXML::CONSTRUCTED_NODES; } # These were created just now | ||
| 574 | map { $self->recordConstructedNode($_) } @n; # record these for OUTER caller! | ||
| 575 | push(@results, @n); } # but return only the most recent set. | ||
| 576 | else { | ||
| 577 | push(@results, $box->beAbsorbed($self)); } } | ||
| 578 | # Else, plain string in text mode. | ||
| 579 | elsif (!$props{isMath}) { | ||
| 580 | push(@results, $self->openText($box, $props{font} || ($LaTeXML::BOX && $LaTeXML::BOX->getFont))); } | ||
| 581 | # Or plain string in math mode. | ||
| 582 | # Note text nodes can ONLY appear in <XMTok> or <text>!!! | ||
| 583 | # Have we already opened an XMTok? Then insert into it. | ||
| 584 | elsif ($$self{model}->getNodeQName($$self{node}) eq $MATH_TOKEN_NAME) { | ||
| 585 | push(@results, $self->openMathText_internal($box)); } | ||
| 586 | # Else create the XMTok now. | ||
| 587 | else { | ||
| 588 | # Odd case: constructors that work in math & text can insert raw strings in Math mode. | ||
| 589 | push(@results, $self->insertMathToken($box, font => $props{font})); } } | ||
| 590 | return @results; } | ||
| 591 | |||
| 592 | # Note that a box has been absorbed creating $node; | ||
| 593 | # This does book keeping so that we can return the sequence of nodes | ||
| 594 | # that were added by absorbing material. | ||
| 595 | sub recordConstructedNode { | ||
| 596 | my ($self, $node) = @_; | ||
| 597 | if ((defined $LaTeXML::RECORDING_CONSTRUCTION) # If we're recording! | ||
| 598 | && (!@LaTeXML::CONSTRUCTED_NODES # and this node isn't already recorded | ||
| 599 | || !$node->isSameNode($LaTeXML::CONSTRUCTED_NODES[-1]))) { | ||
| 600 | push(@LaTeXML::CONSTRUCTED_NODES, $node); } | ||
| 601 | return; } | ||
| 602 | |||
| 603 | sub filterDeletions { | ||
| 604 | my ($self, @nodes) = @_; | ||
| 605 | my $doc = $$self{document}; | ||
| 606 | # This test seems to successfully determine inclusion, | ||
| 607 | # without requiring the (dangerous? & dubious?) unbindNode to be used. | ||
| 608 | return grep { isDescendantOrSelf($_, $doc) } @nodes; } | ||
| 609 | |||
| 610 | # Given a list of nodes such as from ->absorb, | ||
| 611 | # filter out all the nodes that are children of other nodes in the list. | ||
| 612 | sub filterChildren { | ||
| 613 | my ($self, @node) = @_; | ||
| 614 | # return @node; | ||
| 615 | # return (); | ||
| 616 | return () unless @node; | ||
| 617 | my @n = (shift(@node)); | ||
| 618 | foreach my $n (@node) { | ||
| 619 | push(@n, $n) unless grep { isDescendantOrSelf($n, $_); } @n; } | ||
| 620 | return @n; } | ||
| 621 | |||
| 622 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 623 | |||
| 624 | # Shorthand for open,absorb,close, but returns the new node. | ||
| 625 | sub insertElement { | ||
| 626 | my ($self, $qname, $content, %attrib) = @_; | ||
| 627 | my $node = $self->openElement($qname, %attrib); | ||
| 628 | if (ref $content eq 'ARRAY') { | ||
| 629 | map { $self->absorb($_) } @$content; } | ||
| 630 | elsif (defined $content) { | ||
| 631 | $self->absorb($content); } | ||
| 632 | # In obscure situations, $node may have already gotten closed? | ||
| 633 | # close it if it is still open. | ||
| 634 | my $c = $$self{node}; | ||
| 635 | while ($c && ($c->nodeType != XML_DOCUMENT_NODE) && !$c->isSameNode($node)) { | ||
| 636 | $c = $c->parentNode; } | ||
| 637 | if ($c->isSameNode($node)) { | ||
| 638 | $self->closeElement($qname); } | ||
| 639 | return $node; } | ||
| 640 | |||
| 641 | sub insertMathToken { | ||
| 642 | my ($self, $string, %attributes) = @_; | ||
| 643 | $attributes{role} = 'UNKNOWN' unless $attributes{role}; | ||
| 644 | my $node = $self->openElement($MATH_TOKEN_NAME, %attributes); | ||
| 645 | my $box = $attributes{_box} || $LaTeXML::BOX; | ||
| 646 | my $font = $attributes{font} || $box->getFont; | ||
| 647 | $self->setNodeFont($node, $font); | ||
| 648 | $self->setNodeBox($node, $box); | ||
| 649 | $self->openMathText_internal($string) if defined $string; | ||
| 650 | $self->closeNode_internal($node); # Should be safe. | ||
| 651 | return $node; } | ||
| 652 | |||
| 653 | # Insert a new comment, or append to previous comment. | ||
| 654 | # Does NOT move the current insertion point to the Comment, | ||
| 655 | # but may move up past a text node. | ||
| 656 | sub insertComment { | ||
| 657 | my ($self, $text) = @_; | ||
| 658 | chomp($text); | ||
| 659 | $text =~ s/\-\-+/__/g; | ||
| 660 | $self->closeText_internal; # Close any open text node. | ||
| 661 | my $comment; | ||
| 662 | if ($$self{node}->nodeType == XML_DOCUMENT_NODE) { | ||
| 663 | push(@{ $$self{pending} }, $comment = $$self{document}->createComment(' ' . $text . ' ')); } | ||
| 664 | elsif (($comment = $$self{node}->lastChild) && ($comment->nodeType == XML_COMMENT_NODE)) { | ||
| 665 | $comment->setData($comment->data . "\n " . $text); } | ||
| 666 | else { | ||
| 667 | $comment = $$self{node}->appendChild($$self{document}->createComment(' ' . $text . ' ')); } | ||
| 668 | return $comment; } | ||
| 669 | |||
| 670 | # Insert a ProcessingInstruction of the form <?op attr=value ...?> | ||
| 671 | # Does NOT move the current insertion point to the PI, | ||
| 672 | # but may move up past a text node. | ||
| 673 | sub insertPI { | ||
| 674 | my ($self, $op, %attrib) = @_; | ||
| 675 | # We'll just put these on the document itself. | ||
| 676 | # Put these in an attractive order, main "operator" first | ||
| 677 | my @keys = ((map { ($attrib{$_} ? ($_) : ()) } qw(class package options)), | ||
| 678 | (grep { $_ !~ /^(?:class|package|options)$/ } sort keys %attrib)); | ||
| 679 | my $data = join(' ', map { $_ . "=\"" . ToString($attrib{$_}) . "\"" } @keys); | ||
| 680 | my $pi = $$self{document}->createProcessingInstruction($op, $data); | ||
| 681 | $self->closeText_internal; # Close any open text node | ||
| 682 | if ($$self{node}->nodeType == XML_DOCUMENT_NODE) { | ||
| 683 | push(@{ $$self{pending} }, $pi); } | ||
| 684 | else { | ||
| 685 | $$self{document}->insertBefore($pi, $$self{document}->documentElement); } | ||
| 686 | return $pi; } | ||
| 687 | |||
| 688 | #********************************************************************** | ||
| 689 | # Middle level, mostly public, API. | ||
| 690 | # Handlers for various construction operations. | ||
| 691 | # General naming: 'open' opens a node at current pos and sets it to current, | ||
| 692 | # 'close' closes current node(s), inserts opens & closes, ie. w/o moving current | ||
| 693 | |||
| 694 | # Tricky: Insert some text in a particular font. | ||
| 695 | # We need to find the current effective -- being the closest _declared_ font, | ||
| 696 | # (ie. it will appear in the elements attributes). We may also want | ||
| 697 | # to open/close some elements in such a way as to minimize the font switchiness. | ||
| 698 | # I guess we should only open/close "text" elements, though. | ||
| 699 | # [Actually, we'd like the user to _declare_ what element to use.... | ||
| 700 | # I don't like having "text" built in here! | ||
| 701 | # AND, we've assumed that "font" names the relevant attribute!!!] | ||
| 702 | |||
| 703 | sub openText { | ||
| 704 | my ($self, $text, $font) = @_; | ||
| 705 | my $node = $$self{node}; | ||
| 706 | my $t = $node->nodeType; | ||
| 707 | return if $text =~ /^\s+$/ && | ||
| 708 | (($t == XML_DOCUMENT_NODE) # Ignore initial whitespace | ||
| 709 | || (($t == XML_ELEMENT_NODE) && !$self->canContain($node, '#PCDATA'))); | ||
| 710 | return if $font->getFamily eq 'nullfont'; | ||
| 711 | print STDERR "Insert text \"$text\" /" . Stringify($font) . " at " . Stringify($node) . "\n" | ||
| 712 | if $LaTeXML::Core::Document::DEBUG; | ||
| 713 | |||
| 714 | # Get the desired font attributes, particularly the desired element | ||
| 715 | # (usually ltx:text, but let Font override, eg for \emph) | ||
| 716 | my $declared_font = $self->getNodeFont($node); | ||
| 717 | my %pending_declaration = $font->relativeTo($declared_font); | ||
| 718 | my $elementname = $pending_declaration{element}{value} || $FONT_ELEMENT_NAME; | ||
| 719 | if (($t != XML_DOCUMENT_NODE) # If not at document begin | ||
| 720 | && !(($t == XML_TEXT_NODE) && # And not appending text in same font. | ||
| 721 | ($font->distance($self->getNodeFont($node->parentNode)) == 0))) { | ||
| 722 | # then we'll need to do some open/close to get fonts matched. | ||
| 723 | $node = $self->closeText_internal; # Close text node, if any. | ||
| 724 | my ($bestdiff, $closeto) = (99999, $node); | ||
| 725 | my $n = $node; | ||
| 726 | while ($n->nodeType != XML_DOCUMENT_NODE) { | ||
| 727 | my $d = $font->distance($self->getNodeFont($n)); | ||
| 728 | if ($d < $bestdiff) { | ||
| 729 | $bestdiff = $d; | ||
| 730 | $closeto = $n; | ||
| 731 | last if ($d == 0); } | ||
| 732 | last if ($$self{model}->getNodeQName($n) ne $elementname) || $n->getAttribute('_noautoclose'); | ||
| 733 | $n = $n->parentNode; } | ||
| 734 | $self->closeToNode($closeto) if $closeto ne $node; # Move to best starting point for this text. | ||
| 735 | $self->openElement($elementname, font => $font, _fontswitch => 1) if $bestdiff > 0; # Open if needed. | ||
| 736 | } | ||
| 737 | # Finally, insert the darned text. | ||
| 738 | my $tnode = $self->openText_internal($text); | ||
| 739 | $self->recordConstructedNode($tnode); | ||
| 740 | return $tnode; } | ||
| 741 | |||
| 742 | # Mystery: | ||
| 743 | # How to deal with font declarations? | ||
| 744 | # font vs _font; either must redirect to Font object until they are relativized, at end. | ||
| 745 | # When relativizing, should it depend on font attribute on element and/or DTD allowed attribute? | ||
| 746 | sub openElement { | ||
| 747 | my ($self, $qname, %attributes) = @_; | ||
| 748 | NoteProgress('.') if ($$self{progress}++ % 25) == 0; | ||
| 749 | print STDERR "Open element $qname at " . Stringify($$self{node}) . "\n" if $LaTeXML::Core::Document::DEBUG; | ||
| 750 | my $point = $self->find_insertion_point($qname); | ||
| 751 | $attributes{_box} = $LaTeXML::BOX unless $attributes{_box}; | ||
| 752 | my $newnode = $self->openElementAt($point, $qname, | ||
| 753 | _font => $attributes{font} || $attributes{_box}->getFont, | ||
| 754 | %attributes); | ||
| 755 | $self->setNode($newnode); | ||
| 756 | return $newnode; } | ||
| 757 | |||
| 758 | # Note: This closes the deepest open node of a given type. | ||
| 759 | # This can cause problems with auto-opened nodes, esp. ones for fontswitches! | ||
| 760 | # Since this is an "explicit request", we're currently skipping over those nodes, | ||
| 761 | # ie. we're automatically closing them, even if they're the same type as we're asking to close!!! | ||
| 762 | # This is kinda risky! Maybe we should try to request closing of specific nodes. | ||
| 763 | sub closeElement { | ||
| 764 | my ($self, $qname) = @_; | ||
| 765 | print STDERR "Close element $qname at " . Stringify($$self{node}) . "\n" if $LaTeXML::Core::Document::DEBUG; | ||
| 766 | $self->closeText_internal(); | ||
| 767 | my ($node, @cant_close) = ($$self{node}); | ||
| 768 | while ($node->nodeType != XML_DOCUMENT_NODE) { | ||
| 769 | my $t = $$self{model}->getNodeQName($node); | ||
| 770 | # autoclose until node of same name BUT also close nodes opened' for font switches! | ||
| 771 | last if ($t eq $qname) && !(($t eq $FONT_ELEMENT_NAME) && $node->getAttribute('_fontswitch')); | ||
| 772 | push(@cant_close, $node) unless $self->canAutoClose($node); | ||
| 773 | $node = $node->parentNode; } | ||
| 774 | if ($node->nodeType == XML_DOCUMENT_NODE) { # Didn't find $qname at all!! | ||
| 775 | Error('malformed', $qname, $self, | ||
| 776 | "Attempt to close " . ($qname eq '#PCDATA' ? $qname : '</' . $qname . '>') . ", which isn't open", | ||
| 777 | "Currently in " . $self->getInsertionContext()); | ||
| 778 | return; } | ||
| 779 | else { # Found node. | ||
| 780 | # Intervening non-auto-closeable nodes!! | ||
| 781 | Error('malformed', $qname, $self, | ||
| 782 | "Closing " . ($qname eq '#PCDATA' ? $qname : '</' . $qname . '>') | ||
| 783 | . " whose open descendents do not auto-close", | ||
| 784 | "Descendents are " . join(', ', map { Stringify($_) } @cant_close)) | ||
| 785 | if @cant_close; | ||
| 786 | # So, now close up to the desired node. | ||
| 787 | $self->closeNode_internal($node); | ||
| 788 | return $node; } } | ||
| 789 | |||
| 790 | # Check whether it is possible to open $qname at this point, | ||
| 791 | # possibly by autoOpen'ing & autoClosing other tags. | ||
| 792 | sub isOpenable { | ||
| 793 | my ($self, $qname) = @_; | ||
| 794 | my $node = $$self{node}; | ||
| 795 | while ($node) { | ||
| 796 | return 1 if $self->canContainSomehow($node, $qname); | ||
| 797 | return 0 unless $self->canAutoClose($node); # could close, then check if parent can contain | ||
| 798 | $node = $node->parentNode; } | ||
| 799 | return 0; } | ||
| 800 | |||
| 801 | # Check whether it is possible to close each element in @tags, | ||
| 802 | # any intervening nodes must be autocloseable. | ||
| 803 | # returning the last node that would be closed if it is possible, | ||
| 804 | # otherwise undef. | ||
| 805 | sub isCloseable { | ||
| 806 | my ($self, @tags) = @_; | ||
| 807 | my $node = $$self{node}; | ||
| 808 | $node = $node->parentNode if $node->nodeType == XML_TEXT_NODE; | ||
| 809 | while (my $qname = shift(@tags)) { | ||
| 810 | while (1) { | ||
| 811 | return if $node->nodeType == XML_DOCUMENT_NODE; | ||
| 812 | my $this_qname = $$self{model}->getNodeQName($node); | ||
| 813 | last if $this_qname eq $qname; | ||
| 814 | return unless $self->canAutoClose($node); | ||
| 815 | $node = $node->parentNode; } | ||
| 816 | $node = $node->parentNode if @tags; } | ||
| 817 | return $node; } | ||
| 818 | |||
| 819 | # Close $qname, if it is closeable. | ||
| 820 | sub maybeCloseElement { | ||
| 821 | my ($self, $qname) = @_; | ||
| 822 | if (my $node = $self->isCloseable($qname)) { | ||
| 823 | $self->closeNode_internal($node); | ||
| 824 | return $node; } } | ||
| 825 | |||
| 826 | # This closes all nodes until $node becomes the current point. | ||
| 827 | sub closeToNode { | ||
| 828 | my ($self, $node, $ifopen) = @_; | ||
| 829 | my $model = $$self{model}; | ||
| 830 | my ($t, @cant_close) = (); | ||
| 831 | my $n = $$self{node}; | ||
| 832 | my $lastopen; | ||
| 833 | # go up the tree from current node, till we find $node | ||
| 834 | while ((($t = $n->getType) != XML_DOCUMENT_NODE) && !$n->isSameNode($node)) { | ||
| 835 | push(@cant_close, $n) unless $self->canAutoClose($n); | ||
| 836 | $lastopen = $n; | ||
| 837 | $n = $n->parentNode; } | ||
| 838 | if ($t == XML_DOCUMENT_NODE) { # Didn't find $node at all!! | ||
| 839 | Error('malformed', $model->getNodeQName($node), $self, | ||
| 840 | "Attempt to close " . Stringify($node) . ", which isn't open", | ||
| 841 | "Currently in " . $self->getInsertionContext()) unless $ifopen; | ||
| 842 | return; } | ||
| 843 | else { # Found node. | ||
| 844 | Error('malformed', $model->getNodeQName($node), $self, | ||
| 845 | "Closing " . Stringify($node) . " whose open descendents do not auto-close", | ||
| 846 | "Descendents are " . join(', ', map { Stringify($_) } @cant_close)) | ||
| 847 | if @cant_close; # But found has intervening non-auto-closeable nodes!! | ||
| 848 | $self->closeNode_internal($lastopen) if $lastopen; } | ||
| 849 | return; } | ||
| 850 | |||
| 851 | # This closes all nodes until $node is closed. | ||
| 852 | sub closeNode { | ||
| 853 | my ($self, $node) = @_; | ||
| 854 | my $model = $$self{model}; | ||
| 855 | my ($t, @cant_close) = (); | ||
| 856 | my $n = $$self{node}; | ||
| 857 | while ((($t = $n->getType) != XML_DOCUMENT_NODE) && !$n->isSameNode($node)) { | ||
| 858 | push(@cant_close, $n) unless $self->canAutoClose($n); | ||
| 859 | $n = $n->parentNode; } | ||
| 860 | if ($t == XML_DOCUMENT_NODE) { # Didn't find $qname at all!! | ||
| 861 | Error('malformed', $model->getNodeQName($node), $self, | ||
| 862 | "Attempt to close " . Stringify($node) . ", which isn't open", | ||
| 863 | "Currently in " . $self->getInsertionContext()); } | ||
| 864 | else { # Found node. | ||
| 865 | # Intervening non-auto-closeable nodes!! | ||
| 866 | Error('malformed', $model->getNodeQName($node), $self, | ||
| 867 | "Closing " . Stringify($node) . " whose open descendents do not auto-close", | ||
| 868 | "Descendents are " . join(', ', map { Stringify($_) } @cant_close)) | ||
| 869 | if @cant_close; | ||
| 870 | $self->closeNode_internal($node); } | ||
| 871 | return; } | ||
| 872 | |||
| 873 | # Add the given attribute to the nearest node that is allowed to have it. | ||
| 874 | sub addAttribute { | ||
| 875 | my ($self, $key, $value) = @_; | ||
| 876 | return unless defined $value; | ||
| 877 | my $node = $$self{node}; | ||
| 878 | $node = $node->parentNode if $node->nodeType == XML_TEXT_NODE; | ||
| 879 | while (($node->nodeType != XML_DOCUMENT_NODE) && !$$self{model}->canHaveAttribute($node, $key)) { | ||
| 880 | $node = $node->parentNode; } | ||
| 881 | if ($node->nodeType == XML_DOCUMENT_NODE) { | ||
| 882 | Error('malformed', $key, $self, | ||
| 883 | "Attribute $key not allowed in this node or ancestors"); } | ||
| 884 | else { | ||
| 885 | $self->setAttribute($node, $key, $value); } | ||
| 886 | return; } | ||
| 887 | |||
| 888 | #********************************************************************** | ||
| 889 | # Low level internal interface | ||
| 890 | |||
| 891 | # Return a string indicating the path to the current insertion point in the document. | ||
| 892 | # if $levels is defined, show only that many levels | ||
| 893 | sub getInsertionContext { | ||
| 894 | my ($self, $levels) = @_; | ||
| 895 | if (!defined $levels) { # Default depth is based on verbosity | ||
| 896 | my $verbosity = $STATE && $STATE->lookupValue('VERBOSITY') || 0; | ||
| 897 | $levels = 5 if ($verbosity <= 1); } | ||
| 898 | my $node = $$self{node}; | ||
| 899 | my $type = $node->nodeType; | ||
| 900 | if (($type != XML_TEXT_NODE) && ($type != XML_ELEMENT_NODE) && ($type != XML_DOCUMENT_NODE)) { | ||
| 901 | Error('internal', 'context', $self, | ||
| 902 | "Insertion point is not an element, document or text: ", Stringify($node)); | ||
| 903 | return; } | ||
| 904 | my $path = Stringify($node); | ||
| 905 | while ($node = $node->parentNode) { | ||
| 906 | if ((defined $levels) && (--$levels <= 0)) { $path = '...' . $path; last; } | ||
| 907 | $path = Stringify($node) . $path; } | ||
| 908 | return $path; } | ||
| 909 | |||
| 910 | # Find the node where an element with qualified name $qname can be inserted. | ||
| 911 | # This will move up the tree (closing auto-closable elements), | ||
| 912 | # or down (inserting auto-openable elements), as needed. | ||
| 913 | sub find_insertion_point { | ||
| 914 | my ($self, $qname, $has_opened) = @_; | ||
| 915 | $self->closeText_internal; # Close any current text node. | ||
| 916 | my $cur_qname = $$self{model}->getNodeQName($$self{node}); | ||
| 917 | my $inter; | ||
| 918 | # If $qname is allowed at the current point, we're done. | ||
| 919 | if ($self->canContain($cur_qname, $qname)) { | ||
| 920 | return $$self{node}; } | ||
| 921 | # Else, if we can create an intermediate node that accepts $qname, we'll do that. | ||
| 922 | elsif (($inter = $self->canContainIndirect($cur_qname, $qname)) | ||
| 923 | && ($inter ne $qname) && ($inter ne $cur_qname)) { | ||
| 924 | $self->openElement($inter, font => $self->getNodeFont($$self{node})); | ||
| 925 | return $self->find_insertion_point($qname, $inter); } # And retry insertion (should work now). | ||
| 926 | elsif ($has_opened) { # out of options if already inside an auto-open chain | ||
| 927 | Error('malformed', $qname, $self, | ||
| 928 | ($qname eq '#PCDATA' ? $qname : '<' . $qname . '>') . " failed auto-open through <$has_opened> at inadmissible <$cur_qname>", | ||
| 929 | "Currently in " . $self->getInsertionContext()); | ||
| 930 | return $$self{node}; } # But we'll do it anyway, unless Error => Fatal. | ||
| 931 | else { # Now we're getting more desparate... | ||
| 932 | # Check if we can auto close some nodes, and _then_ insert the $qname. | ||
| 933 | my ($node, $closeto) = ($$self{node}); | ||
| 934 | while (($node->nodeType != XML_DOCUMENT_NODE) && $self->canAutoClose($node)) { | ||
| 935 | my $parent = $node->parentNode; | ||
| 936 | if ($self->canContainSomehow($parent, $qname)) { | ||
| 937 | $closeto = $node; last; } | ||
| 938 | $node = $parent; } | ||
| 939 | if ($closeto) { | ||
| 940 | my $closeto_qname = $$self{model}->getNodeQName($closeto); | ||
| 941 | $self->closeNode_internal($closeto); # Close the auto closeable nodes. | ||
| 942 | return $self->find_insertion_point($qname); } # Then retry, possibly w/auto open's | ||
| 943 | else { # Didn't find a legit place. | ||
| 944 | Error('malformed', $qname, $self, | ||
| 945 | ($qname eq '#PCDATA' ? $qname : '<' . $qname . '>') . " isn't allowed in <$cur_qname>", | ||
| 946 | "Currently in " . $self->getInsertionContext()); | ||
| 947 | return $$self{node}; } } } # But we'll do it anyway, unless Error => Fatal. | ||
| 948 | |||
| 949 | sub getInsertionCandidates { | ||
| 950 | my ($node) = @_; | ||
| 951 | my @nodes = (); | ||
| 952 | # Check the current element FIRST, then build list of candidates. | ||
| 953 | my $first = $node; | ||
| 954 | $first = $first->parentNode if $first && $first->getType == XML_TEXT_NODE; | ||
| 955 | my $isCapture = $first && ($first->localname || '') eq '_Capture_'; | ||
| 956 | push(@nodes, $first) if $first && $first->getType != XML_DOCUMENT_NODE && !$isCapture; | ||
| 957 | # Collect previous siblings, if node is a text node. | ||
| 958 | # OR if it is a effectively a text node (ltx:para/ltx:p/text)!!! | ||
| 959 | my $do_sibs = $node->getType == XML_TEXT_NODE; | ||
| 960 | # Now collect (element) node & ancestors | ||
| 961 | while ($node && ($node->nodeType != XML_DOCUMENT_NODE)) { | ||
| 962 | my $n = $node; | ||
| 963 | if (($node->localname || '') eq '_Capture_') { | ||
| 964 | push(@nodes, element_nodes($node)); } | ||
| 965 | else { | ||
| 966 | push(@nodes, $node); } | ||
| 967 | if ($do_sibs && ($n = $node->previousSibling)) { | ||
| 968 | $node = $n; | ||
| 969 | } | ||
| 970 | else { | ||
| 971 | $node = $node->parentNode; | ||
| 972 | my $t = $node->localname || ''; | ||
| 973 | $do_sibs = 0 unless ($t eq 'p') || ($t eq 'para'); | ||
| 974 | } } | ||
| 975 | push(@nodes, $first) if $isCapture; | ||
| 976 | return @nodes; } | ||
| 977 | |||
| 978 | # The following "floatTo" operations find an appropriate point | ||
| 979 | # within the document tree preceding the current insertion point. | ||
| 980 | # They return undef (& issue a warning) if such a point cannot be found. | ||
| 981 | # Otherwise, they move the current insertion point to the appropriate node, | ||
| 982 | # and return the previous insertion point. | ||
| 983 | # After you make whatever changes (insertions or whatever) to the tree, | ||
| 984 | # you should do | ||
| 985 | # $document->setNode($savenode) | ||
| 986 | # to reset the insertion point to where it had been. | ||
| 987 | |||
| 988 | # Find a node in the document that can contain an element $qname | ||
| 989 | sub floatToElement { | ||
| 990 | my ($self, $qname, $closeifpossible) = @_; | ||
| 991 | my @candidates = getInsertionCandidates($$self{node}); | ||
| 992 | my $closeable = 1; | ||
| 993 | while (@candidates && !$self->canContain($candidates[0], $qname)) { | ||
| 994 | $closeable &&= $self->canAutoClose($candidates[0]); | ||
| 995 | shift(@candidates); } | ||
| 996 | if (my $n = shift(@candidates)) { | ||
| 997 | if ($closeifpossible && $closeable) { | ||
| 998 | $self->closeToNode($n); } | ||
| 999 | else { | ||
| 1000 | my $savenode = $$self{node}; | ||
| 1001 | $self->setNode($n); | ||
| 1002 | print STDERR "Floating from " . Stringify($savenode) . " to " . Stringify($n) . " for $qname\n" | ||
| 1003 | if ($$savenode ne $$n) && $LaTeXML::Core::Document::DEBUG; | ||
| 1004 | return $savenode; } } | ||
| 1005 | else { | ||
| 1006 | Warn('malformed', $qname, $self, "No open node can contain element '$qname'", | ||
| 1007 | $self->getInsertionContext()) | ||
| 1008 | unless $self->canContainSomehow($$self{node}, $qname); } | ||
| 1009 | return; } | ||
| 1010 | |||
| 1011 | # Find a node in the document that can accept the attribute $key | ||
| 1012 | sub floatToAttribute { | ||
| 1013 | my ($self, $key) = @_; | ||
| 1014 | my @candidates = getInsertionCandidates($$self{node}); | ||
| 1015 | while (@candidates && !$self->canHaveAttribute($candidates[0], $key)) { | ||
| 1016 | shift(@candidates); } | ||
| 1017 | if (my $n = shift(@candidates)) { | ||
| 1018 | my $savenode = $$self{node}; | ||
| 1019 | $self->setNode($n); | ||
| 1020 | return $savenode; } | ||
| 1021 | else { | ||
| 1022 | Warn('malformed', $key, $self, "No open node can get attribute '$key'", | ||
| 1023 | $self->getInsertionContext()); | ||
| 1024 | return; } } | ||
| 1025 | |||
| 1026 | # find a node that can accept a label. | ||
| 1027 | # A bit more than just whether the element can have the attribute, but | ||
| 1028 | # whether it has an id (and ideally either a refnum or title) | ||
| 1029 | sub floatToLabel { | ||
| 1030 | my ($self) = @_; | ||
| 1031 | my $key = 'labels'; | ||
| 1032 | my @ancestors = grep { $_->nodeType == XML_ELEMENT_NODE } getInsertionCandidates($$self{node}); | ||
| 1033 | my @candidates = @ancestors; | ||
| 1034 | # Should we only accept a node that already has an id, or should we create an id? | ||
| 1035 | while (@candidates | ||
| 1036 | && !($self->canHaveAttribute($candidates[0], $key) | ||
| 1037 | && $candidates[0]->hasAttribute('xml:id'))) { | ||
| 1038 | shift(@candidates); } | ||
| 1039 | my $node = shift(@candidates); | ||
| 1040 | if (!$node) { # No appropriate ancestor? | ||
| 1041 | my $sib = $ancestors[0] && $ancestors[0]->lastChild; | ||
| 1042 | if ($sib && $self->canHaveAttribute($sib, $key) | ||
| 1043 | && $sib->hasAttribute('xml:id')) { | ||
| 1044 | $node = $sib; } | ||
| 1045 | elsif (@ancestors) { # just take root element? | ||
| 1046 | $node = $ancestors[-1]; } } | ||
| 1047 | if ($node) { | ||
| 1048 | my $savenode = $$self{node}; | ||
| 1049 | $self->setNode($node); | ||
| 1050 | return $savenode; } | ||
| 1051 | else { | ||
| 1052 | Warn('malformed', $key, $self, "No open node with an xml:id can get attribute '$key'", | ||
| 1053 | $self->getInsertionContext()); | ||
| 1054 | return; } } | ||
| 1055 | |||
| 1056 | sub openText_internal { | ||
| 1057 | my ($self, $text) = @_; | ||
| 1058 | my $qname; | ||
| 1059 | if ($$self{node}->nodeType == XML_TEXT_NODE) { # current node already is a text node. | ||
| 1060 | print STDERR "Appending text \"$text\" to " . Stringify($$self{node}) . "\n" if $LaTeXML::Core::Document::DEBUG; | ||
| 1061 | $$self{node}->appendData($text); } | ||
| 1062 | elsif (($text =~ /\S/) # If non space | ||
| 1063 | || $self->canContain($$self{node}, '#PCDATA')) { # or text allowed here | ||
| 1064 | my $point = $self->find_insertion_point('#PCDATA'); | ||
| 1065 | my $node = $$self{document}->createTextNode($text); | ||
| 1066 | print STDERR "Inserting text node for \"$text\" into " . Stringify($point) . "\n" | ||
| 1067 | if $LaTeXML::Core::Document::DEBUG; | ||
| 1068 | $point->appendChild($node); | ||
| 1069 | $self->setNode($node); } | ||
| 1070 | return $$self{node}; } # return the text node (current) | ||
| 1071 | |||
| 1072 | # Question: Why do I have math ligatures handled within openMathText_internal, | ||
| 1073 | # but text ligatures handled within closeText_internal ??? | ||
| 1074 | |||
| 1075 | sub openMathText_internal { | ||
| 1076 | my ($self, $string) = @_; | ||
| 1077 | # And if there's already text??? | ||
| 1078 | my $node = $$self{node}; | ||
| 1079 | my $font = $self->getNodeFont($node); | ||
| 1080 | $node->appendText($string); | ||
| 1081 | ##print STDERR "Trying Math Ligatures at \"$string\"\n"; | ||
| 1082 | if (!$STATE->lookupValue('NOMATHPARSE')) { | ||
| 1083 | $self->applyMathLigatures($node); | ||
| 1084 | } | ||
| 1085 | return $node; } | ||
| 1086 | |||
| 1087 | # New stategy (but inefficient): apply ligatures until one succeeds, | ||
| 1088 | # then remove it, and repeat until ALL (remaining) fail. | ||
| 1089 | sub applyMathLigatures { | ||
| 1090 | my ($self, $node) = @_; | ||
| 1091 | if (my $ligatures = $STATE->lookupValue('MATH_LIGATURES')) { | ||
| 1092 | my @ligatures = @$ligatures; | ||
| 1093 | while (@ligatures) { | ||
| 1094 | my $matched = 0; | ||
| 1095 | foreach my $ligature (@ligatures) { | ||
| 1096 | if ($self->applyMathLigature($node, $ligature)) { | ||
| 1097 | @ligatures = grep { $_ ne $ligature } @ligatures; | ||
| 1098 | $matched = 1; | ||
| 1099 | last; } } | ||
| 1100 | return unless $matched; } } | ||
| 1101 | return; } | ||
| 1102 | |||
| 1103 | # Apply ligature operation to $node, presumed the last insertion into it's parent(?) | ||
| 1104 | sub applyMathLigature { | ||
| 1105 | my ($self, $node, $ligature) = @_; | ||
| 1106 | my ($nmatched, $newstring, %attr); | ||
| 1107 | if ($$ligature{old_style}) { # Obsolete style (expensively) passes in ALL sibling nodes | ||
| 1108 | ($nmatched, $newstring, %attr) = &{ $$ligature{matcher} }($self, $node->parentNode->childNodes); } | ||
| 1109 | else { # New style gets node and should ask for $node->previousSibling | ||
| 1110 | ($nmatched, $newstring, %attr) = &{ $$ligature{matcher} }($self, $node); } | ||
| 1111 | if ($nmatched) { | ||
| 1112 | my @boxes = ($self->getNodeBox($node)); | ||
| 1113 | $node->firstChild->setData($newstring); | ||
| 1114 | for (my $i = 0 ; $i < $nmatched - 1 ; $i++) { | ||
| 1115 | my $remove = $node->previousSibling; | ||
| 1116 | unshift(@boxes, $self->getNodeBox($remove)); | ||
| 1117 | $self->removeNode($remove); } | ||
| 1118 | ## This fragment replaces the node's box by the composite boxes it replaces | ||
| 1119 | ## HOWEVER, this gets things out of sync because parent lists of boxes still | ||
| 1120 | ## have the old ones. Unless we could recursively replace all of them, we'd better skip it(??) | ||
| 1121 | if (scalar(@boxes) > 1) { | ||
| 1122 | $self->setNodeBox($node, List(@boxes, mode => 'math')); } | ||
| 1123 | foreach my $key (sort keys %attr) { | ||
| 1124 | my $value = $attr{$key}; | ||
| 1125 | if (defined $value) { | ||
| 1126 | $node->setAttribute($key => $value); } | ||
| 1127 | else { | ||
| 1128 | $node->removeAttribute($key); } } | ||
| 1129 | return 1; } | ||
| 1130 | else { | ||
| 1131 | return; } } | ||
| 1132 | |||
| 1133 | # Closing a text node is a good time to apply regexps (aka. Ligatures) | ||
| 1134 | sub closeText_internal { | ||
| 1135 | my ($self) = @_; | ||
| 1136 | my $node = $$self{node}; | ||
| 1137 | if ($node->nodeType == XML_TEXT_NODE) { # Current node is text? | ||
| 1138 | my $parent = $node->parentNode; | ||
| 1139 | my $font = $self->getNodeFont($parent); | ||
| 1140 | my $string = $node->data; | ||
| 1141 | my $ostring = $string; | ||
| 1142 | my $fonttest; | ||
| 1143 | if (my $ligatures = $STATE->lookupValue('TEXT_LIGATURES')) { | ||
| 1144 | foreach my $ligature (@$ligatures) { | ||
| 1145 | next if ($fonttest = $$ligature{fontTest}) && !&$fonttest($font); | ||
| 1146 | $string = &{ $$ligature{code} }($string); } } | ||
| 1147 | $node->setData($string) unless $string eq $ostring; | ||
| 1148 | $self->setNode($parent); # Now, effectively Closed | ||
| 1149 | return $parent; } | ||
| 1150 | else { | ||
| 1151 | return $node; } } | ||
| 1152 | |||
| 1153 | # Close $node, and any current nodes below it. | ||
| 1154 | # No checking! Use this when you've already verified that $node can be closed. | ||
| 1155 | # and, of course, $node must be current or some ancestor of it!!! | ||
| 1156 | sub closeNode_internal { | ||
| 1157 | my ($self, $node) = @_; | ||
| 1158 | my $closeto = $node->parentNode; # Grab now in case afterClose screws the structure. | ||
| 1159 | my $n = $self->closeText_internal; # Close any open text node. | ||
| 1160 | while ($n->nodeType == XML_ELEMENT_NODE) { | ||
| 1161 | $self->closeElementAt($n); | ||
| 1162 | $self->autoCollapseChildren($n); | ||
| 1163 | last if $node->isSameNode($n); | ||
| 1164 | $n = $n->parentNode; } | ||
| 1165 | $self->setNode($closeto); | ||
| 1166 | # $self->autoCollapseChildren($node); | ||
| 1167 | return $$self{node}; } | ||
| 1168 | |||
| 1169 | # Avoid redundant nesting of font switching elements: | ||
| 1170 | # If we're closing a node that can take font switches and it contains | ||
| 1171 | # a single FONT_ELEMENT_NAME node; pull it up. | ||
| 1172 | sub autoCollapseChildren { | ||
| 1173 | my ($self, $node) = @_; | ||
| 1174 | my $model = $$self{model}; | ||
| 1175 | my $qname = $model->getNodeQName($node); | ||
| 1176 | my @c; | ||
| 1177 | if (($qname ne 'ltx:_Capture_') | ||
| 1178 | && (scalar(@c = $node->childNodes) == 1) # with single child | ||
| 1179 | && ($model->getNodeQName($c[0]) eq $FONT_ELEMENT_NAME) | ||
| 1180 | # AND, $node can have all the attributes that the child has (but at least 'font') | ||
| 1181 | && !(grep { !$model->canHaveAttribute($qname, $_) } | ||
| 1182 | ('font', grep { /^[^_]/ } map { $_->nodeName } $c[0]->attributes)) | ||
| 1183 | # BUT, it isn't being forced somehow | ||
| 1184 | && !$c[0]->hasAttribute('_force_font')) { | ||
| 1185 | my $c = $c[0]; | ||
| 1186 | $self->setNodeFont($node, $self->getNodeFont($c)); | ||
| 1187 | $self->removeNode($c); | ||
| 1188 | foreach my $gc ($c->childNodes) { | ||
| 1189 | $node->appendChild($gc); | ||
| 1190 | $self->recordNodeIDs($node); } | ||
| 1191 | # Merge the attributes from the child onto $node | ||
| 1192 | foreach my $attr ($c->attributes()) { | ||
| 1193 | if ($attr->nodeType == XML_ATTRIBUTE_NODE) { | ||
| 1194 | my $key = $attr->nodeName; | ||
| 1195 | my $val = $attr->getValue; | ||
| 1196 | # Special case attributes | ||
| 1197 | if ($key eq 'xml:id') { # Use the replacement id | ||
| 1198 | if (!$node->hasAttribute($key)) { | ||
| 1199 | $val = $self->recordID($val, $node); | ||
| 1200 | $node->setAttribute($key, $val); } } | ||
| 1201 | elsif ($key eq 'class') { # combine $class | ||
| 1202 | if (my $class = $node->getAttribute($key)) { | ||
| 1203 | $node->setAttribute($key, $class . ' ' . $val); } | ||
| 1204 | else { | ||
| 1205 | $node->setAttribute($key, $val); } } | ||
| 1206 | # xoffset, yoffset should sum up, if present on both. | ||
| 1207 | elsif ($key =~ /^(xoffset|yoffset)$/) { | ||
| 1208 | if (my $val2 = $node->getAttribute($key)) { | ||
| 1209 | my $v1 = $val =~ /^([\+\-\d\.]*)pt$/ && $1; | ||
| 1210 | my $v2 = $val2 =~ /^([\+\-\d\.]*)pt$/ && $1; | ||
| 1211 | $node->setAttribute($key => ($v1 + $v2) . 'pt'); } | ||
| 1212 | else { | ||
| 1213 | $node->setAttribute($key => $val); } } | ||
| 1214 | # Remaining attributes should prefer the inner (child's) values, if any | ||
| 1215 | # (font, size, color, framed) | ||
| 1216 | # (width,height, depth, align, vattach, float) | ||
| 1217 | elsif (my $ns = $attr->namespaceURI) { | ||
| 1218 | $node->setAttributeNS($ns, $attr->name, $val); } | ||
| 1219 | else { | ||
| 1220 | $node->setAttribute($attr->localname, $val); } } } | ||
| 1221 | } | ||
| 1222 | return; } | ||
| 1223 | |||
| 1224 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 1225 | # Document surgery (?) | ||
| 1226 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 1227 | # The following carry out DOM modification but NOT relative to any current | ||
| 1228 | # insertion point (eg $$self{node}), but rather relative to nodes specified | ||
| 1229 | # in the arguments. | ||
| 1230 | |||
| 1231 | # Set any allowed attribute on a node, decoding the prefix, if any. | ||
| 1232 | # Also records, and checks, any id attributes. | ||
| 1233 | # [xml:id and namespaced attributes are always allowed] | ||
| 1234 | sub setAttribute { | ||
| 1235 | my ($self, $node, $key, $value) = @_; | ||
| 1236 | $value = $value->toAttribute if ref $value; | ||
| 1237 | if ((defined $value) && ($value ne '')) { # Skip if `empty'; but 0 is OK! | ||
| 1238 | if ($key eq 'xml:id') { # If it's an ID attribute | ||
| 1239 | $value = $self->recordID($value, $node); # Do id book keeping | ||
| 1240 | $node->setAttributeNS($LaTeXML::Common::XML::XML_NS, 'id', $value); } # and bypass all ns stuff | ||
| 1241 | elsif ($key !~ /:/) { # No colon; no namespace (the common case!) | ||
| 1242 | # Ignore attributes not allowed by the model, | ||
| 1243 | # but accept "internal" attributes. | ||
| 1244 | my $model = $$self{model}; | ||
| 1245 | my $qname = $model->getNodeQName($node); | ||
| 1246 | if ($model->canHaveAttribute($qname, $key) || $key =~ /^_/) { | ||
| 1247 | $node->setAttribute($key => $value); } } | ||
| 1248 | else { # Accept any namespaced attributes | ||
| 1249 | my ($ns, $name) = $$self{model}->decodeQName($key); | ||
| 1250 | if ($ns) { # If namespaced attribute (must have prefix! | ||
| 1251 | my $prefix = $node->lookupNamespacePrefix($ns); # namespace already declared? | ||
| 1252 | if (!$prefix) { # if namespace not already declared | ||
| 1253 | $prefix = $$self{model}->getDocumentNamespacePrefix($ns, 1); # get the prefix to use | ||
| 1254 | $self->getDocument->documentElement->setNamespace($ns, $prefix, 0); } # and declare it | ||
| 1255 | if ($prefix eq '#default') { # Probably shouldn't happen...? | ||
| 1256 | $node->setAttribute($name => $value); } | ||
| 1257 | else { | ||
| 1258 | $node->setAttributeNS($ns, "$prefix:$name" => $value); } } | ||
| 1259 | else { | ||
| 1260 | $node->setAttribute($name => $value); } } } # redundant case... | ||
| 1261 | return; } | ||
| 1262 | |||
| 1263 | sub addSSValues { | ||
| 1264 | my ($self, $node, $key, $values) = @_; | ||
| 1265 | $values = $values->toAttribute if ref $values; | ||
| 1266 | if ((defined $values) && ($values ne '')) { # Skip if `empty'; but 0 is OK! | ||
| 1267 | my @values = split(/\s/, $values); | ||
| 1268 | if (my $oldvalues = $node->getAttribute($key)) { # previous values? | ||
| 1269 | my @old = split(/\s/, $oldvalues); | ||
| 1270 | foreach my $new (@values) { | ||
| 1271 | push(@old, $new) unless grep { $_ eq $new } @old; } | ||
| 1272 | $self->setAttribute($node, $key => join(' ', sort @old)); } | ||
| 1273 | else { | ||
| 1274 | $self->setAttribute($node, $key => join(' ', sort @values)); } } | ||
| 1275 | return; } | ||
| 1276 | |||
| 1277 | sub addClass { | ||
| 1278 | my ($self, $node, $class) = @_; | ||
| 1279 | return $self->addSSValues($node, class => $class); } | ||
| 1280 | |||
| 1281 | #********************************************************************** | ||
| 1282 | # Association of nodes and ids (xml:id) | ||
| 1283 | |||
| 1284 | sub recordID { | ||
| 1285 | my ($self, $id, $node) = @_; | ||
| 1286 | if (my $prev = $$self{idstore}{$id}) { # Whoops! Already assigned!!! | ||
| 1287 | # Can we recover? | ||
| 1288 | if (!$node->isSameNode($prev)) { | ||
| 1289 | my $badid = $id; | ||
| 1290 | $id = $self->modifyID($id); | ||
| 1291 | Info('malformed', 'id', $node, "Duplicated attribute xml:id", | ||
| 1292 | "Using id='$id' on " . Stringify($node), | ||
| 1293 | "id='$badid' already set on " . Stringify($prev)); } } | ||
| 1294 | $$self{idstore}{$id} = $node; | ||
| 1295 | return $id; } | ||
| 1296 | |||
| 1297 | sub unRecordID { | ||
| 1298 | my ($self, $id) = @_; | ||
| 1299 | delete $$self{idstore}{$id}; | ||
| 1300 | return; } | ||
| 1301 | |||
| 1302 | # These are used to record or unrecord, in bulk, all the ids within a node (tree). | ||
| 1303 | sub recordNodeIDs { | ||
| 1304 | my ($self, $node) = @_; | ||
| 1305 | foreach my $idnode ($self->findnodes('descendant-or-self::*[@xml:id]', $node)) { | ||
| 1306 | if (my $id = $idnode->getAttribute('xml:id')) { | ||
| 1307 | my $newid = $self->recordID($id, $idnode); | ||
| 1308 | $idnode->setAttribute('xml:id' => $newid) if $newid ne $id; } } | ||
| 1309 | return; } | ||
| 1310 | |||
| 1311 | sub unRecordNodeIDs { | ||
| 1312 | my ($self, $node) = @_; | ||
| 1313 | foreach my $idnode ($self->findnodes('descendant-or-self::*[@xml:id]', $node)) { | ||
| 1314 | if (my $id = $idnode->getAttribute('xml:id')) { | ||
| 1315 | $self->unRecordID($id); } } | ||
| 1316 | return; } | ||
| 1317 | |||
| 1318 | # Get a new, related, but unique id | ||
| 1319 | # Sneaky option: try $LaTeXML::Core::Document::ID_SUFFIX as a suffix for id, first. | ||
| 1320 | sub modifyID { | ||
| 1321 | my ($self, $id) = @_; | ||
| 1322 | if (my $prev = $$self{idstore}{$id}) { # Whoops! Already assigned!!! | ||
| 1323 | # Can we recover? | ||
| 1324 | my $badid = $id; | ||
| 1325 | if (!$LaTeXML::Core::Document::ID_SUFFIX | ||
| 1326 | || $$self{idstore}{ $id = $badid . $LaTeXML::Core::Document::ID_SUFFIX }) { | ||
| 1327 | foreach my $s1 (1 .. 26 * 26 * 26) { # Gotta give up, eventually; is 3 letters enough? | ||
| 1328 | return $id unless $$self{idstore}{ $id = $badid . radix_alpha($s1) }; } | ||
| 1329 | Fatal('malformed', 'id', $self, "Automatic incrementing of ID counters failed", | ||
| 1330 | "Last alternative for '$id' is '$badid'"); } } | ||
| 1331 | return $id; } | ||
| 1332 | |||
| 1333 | sub lookupID { | ||
| 1334 | my ($self, $id) = @_; | ||
| 1335 | return $$self{idstore}{$id}; } | ||
| 1336 | |||
| 1337 | #====================================================================== | ||
| 1338 | # Odd bit: | ||
| 1339 | # In an XMDual, in each branch (content, presentation) there will be atoms | ||
| 1340 | # that correspond to the input (one will be real, the other an XMRef to the first). | ||
| 1341 | # But also there will be additional "decoration" (delimiters, punctuation, etc on the presentation | ||
| 1342 | # side; other symbols, bindings, whatever, on the content side). | ||
| 1343 | # These decorations should NOT be subject to rewrite rules, | ||
| 1344 | # and in cross-linked parallel markup, they should be attributed to the | ||
| 1345 | # upper containing object's ID, rather than left dangling. | ||
| 1346 | # | ||
| 1347 | # To determine this, we mark all math nodes as to whether they are "visible" from | ||
| 1348 | # presentation, content or both (the default top-level being both). | ||
| 1349 | # Decorations are the nodes that are visible to only one mode. | ||
| 1350 | # Note that nodes that are not visible at all CAN occur (& do currently when the parser | ||
| 1351 | # creates XMDuals), pruneXMDuals (below) gets rid of them. | ||
| 1352 | |||
| 1353 | # NOTE: This should ultimately be in a base Document class, | ||
| 1354 | # since it is also needed before conversion to parallel markup! | ||
| 1355 | sub markXMNodeVisibility { | ||
| 1356 | my ($self) = @_; | ||
| 1357 | my @xmath = $self->findnodes('//ltx:XMath/*'); | ||
| 1358 | foreach my $math (@xmath) { | ||
| 1359 | foreach my $node ($self->findnodes('descendant-or-self::*[@_pvis or @_cvis]', $math)) { | ||
| 1360 | $node->removeAttribute('_pvis'); | ||
| 1361 | $node->removeAttribute('_cvis'); } } | ||
| 1362 | foreach my $math (@xmath) { | ||
| 1363 | $self->markXMNodeVisibility_aux($math, 1, 1); } | ||
| 1364 | return; } | ||
| 1365 | |||
| 1366 | sub markXMNodeVisibility_aux { | ||
| 1367 | my ($self, $node, $cvis, $pvis) = @_; | ||
| 1368 | my $qname = $self->getNodeQName($node); | ||
| 1369 | return if (!$cvis || $node->getAttribute('_cvis')) && (!$pvis || $node->getAttribute('_pvis')); | ||
| 1370 | # Special case: for XMArg used to wrap "formal" arguments on the content side, | ||
| 1371 | # mark them as visible as presentation as well. | ||
| 1372 | $pvis = 1 if $cvis && ($qname eq 'ltx:XMArg'); | ||
| 1373 | $node->setAttribute('_cvis' => 1) if $cvis; | ||
| 1374 | $node->setAttribute('_pvis' => 1) if $pvis; | ||
| 1375 | if ($qname eq 'ltx:XMDual') { | ||
| 1376 | my ($c, $p) = element_nodes($node); | ||
| 1377 | $self->markXMNodeVisibility_aux($c, 1, 0) if $cvis; | ||
| 1378 | $self->markXMNodeVisibility_aux($p, 0, 1) if $pvis; } | ||
| 1379 | elsif ($qname eq 'ltx:XMRef') { | ||
| 1380 | # $self->markXMNodeVisibility_aux($self->realizeXMNode($node),$cvis,$pvis); } | ||
| 1381 | my $id = $node->getAttribute('idref'); | ||
| 1382 | if (!$id) { | ||
| 1383 | my $key = $node->getAttribute('_xmkey'); | ||
| 1384 | Warn('expected', 'id', $self, "Missing idref on ltx:XMRef", | ||
| 1385 | ($key ? ("_xmkey is $key") : ())); | ||
| 1386 | return; } | ||
| 1387 | my $reffed = $self->lookupID($id); | ||
| 1388 | if (!$reffed) { | ||
| 1389 | Warn('expected', 'node', $self, "No node found with id=$id (referred to from ltx:XMRef)"); | ||
| 1390 | return; } | ||
| 1391 | $self->markXMNodeVisibility_aux($reffed, $cvis, $pvis); } | ||
| 1392 | else { | ||
| 1393 | foreach my $child (element_nodes($node)) { | ||
| 1394 | $self->markXMNodeVisibility_aux($child, $cvis, $pvis); } } | ||
| 1395 | return; } | ||
| 1396 | |||
| 1397 | # Reduce any ltx:XMDual's to just the visible branch, if the other is not visible | ||
| 1398 | # (according to markXMNodeVisibility) | ||
| 1399 | # If we could be 100% sure that the marking had stayed consistent (after various doc surgery) | ||
| 1400 | # we could avoid re-marking, but we'd better be sure before removing nodes! | ||
| 1401 | sub pruneXMDuals { | ||
| 1402 | my ($self) = @_; | ||
| 1403 | # RE-mark visibility! | ||
| 1404 | $self->markXMNodeVisibility; | ||
| 1405 | # will reversing keep from problems removing nodes from trees that already have been removed? | ||
| 1406 | foreach my $dual (reverse $self->findnodes('descendant-or-self::ltx:XMDual')) { | ||
| 1407 | my ($content, $presentation) = element_nodes($dual); | ||
| 1408 | if (!$self->findnode('descendant-or-self::*[@_pvis or @_cvis]', $content)) { # content never seen | ||
| 1409 | $self->collapseXMDual($dual, $presentation); } | ||
| 1410 | elsif (!$self->findnode('descendant-or-self::*[@_pvis or @_cvis]', $presentation)) { # pres. | ||
| 1411 | $self->collapseXMDual($dual, $content); } | ||
| 1412 | } | ||
| 1413 | return; } | ||
| 1414 | |||
| 1415 | # Replace an XMDual with one of its branches | ||
| 1416 | sub collapseXMDual { | ||
| 1417 | my ($self, $dual, $branch) = @_; | ||
| 1418 | # The other branch is not visible, nor referenced, | ||
| 1419 | # but the dual may have an id and be referenced | ||
| 1420 | if (my $dualid = $dual->getAttribute('xml:id')) { | ||
| 1421 | $self->unRecordID($dualid); # We'll move or remove the ID from the dual | ||
| 1422 | if (my $branchid = $branch->getAttribute('xml:id')) { # branch has id too! | ||
| 1423 | foreach my $ref ($self->findnodes("//*[\@idref='$dualid']")) { | ||
| 1424 | $ref->setAttribute(idref => $branchid); } } # Change dualid refs to branchid | ||
| 1425 | else { | ||
| 1426 | $branch->setAttribute('xml:id' => $dualid); # Just use same ID on the branch | ||
| 1427 | $self->recordID($dualid => $branch); } } | ||
| 1428 | $self->replaceTree($branch, $dual); | ||
| 1429 | return; } | ||
| 1430 | |||
| 1431 | #********************************************************************** | ||
| 1432 | # Record the Box that created this node. | ||
| 1433 | sub setNodeBox { | ||
| 1434 | my ($self, $node, $box) = @_; | ||
| 1435 | return unless $box; | ||
| 1436 | my $boxid = "$box"; | ||
| 1437 | $$self{node_boxes}{$boxid} = $box; | ||
| 1438 | return $node->setAttribute(_box => $boxid); } | ||
| 1439 | |||
| 1440 | sub getNodeBox { | ||
| 1441 | my ($self, $node) = @_; | ||
| 1442 | my $t = $node->nodeType; | ||
| 1443 | return if $t != XML_ELEMENT_NODE; | ||
| 1444 | if (my $boxid = $node->getAttribute('_box')) { | ||
| 1445 | return $$self{node_boxes}{$boxid}; } } | ||
| 1446 | |||
| 1447 | sub setNodeFont { | ||
| 1448 | my ($self, $node, $font) = @_; | ||
| 1449 | return unless ref $font; # ? | ||
| 1450 | my $fontid = $font->toString; | ||
| 1451 | $$self{node_fonts}{$fontid} = $font; | ||
| 1452 | if ($node->nodeType == XML_ELEMENT_NODE) { | ||
| 1453 | $node->setAttribute(_font => $fontid); } | ||
| 1454 | # otherwise, probably just ignorable? | ||
| 1455 | return; } | ||
| 1456 | |||
| 1457 | # Possibly a sign of a design flaw; Set the node's font & all children that HAD the same font. | ||
| 1458 | sub mergeNodeFontRec { | ||
| 1459 | my ($self, $node, $font) = @_; | ||
| 1460 | return unless ref $font; # ? | ||
| 1461 | my $oldfont = $self->getNodeFont($node); | ||
| 1462 | my %props = $oldfont->purestyleChanges($font); | ||
| 1463 | my @nodes = ($node); | ||
| 1464 | while (my $n = shift(@nodes)) { | ||
| 1465 | if ($n->nodeType == XML_ELEMENT_NODE) { | ||
| 1466 | $self->setNodeFont($n, $self->getNodeFont($n)->merge(%props)); | ||
| 1467 | push(@nodes, $n->childNodes); } } | ||
| 1468 | return; } | ||
| 1469 | |||
| 1470 | sub getNodeFont { | ||
| 1471 | my ($self, $node) = @_; | ||
| 1472 | my $t; | ||
| 1473 | while ($node && (($t = $node->nodeType) != XML_ELEMENT_NODE)) { | ||
| 1474 | $node = $node->parentNode; } | ||
| 1475 | return ($node && ($t == XML_ELEMENT_NODE) && $$self{node_fonts}{ $node->getAttribute('_font') }) | ||
| 1476 | || LaTeXML::Common::Font->textDefault(); } | ||
| 1477 | |||
| 1478 | sub getNodeLanguage { | ||
| 1479 | my ($self, $node) = @_; | ||
| 1480 | my ($font, $lang); | ||
| 1481 | while ($node && ($node->nodeType == XML_ELEMENT_NODE) | ||
| 1482 | && !(($lang = $node->getAttribute('xml:lang')) | ||
| 1483 | || (($font = $$self{node_fonts}{ $node->getAttribute('_font') }) | ||
| 1484 | && ($lang = $font->getLanguage)))) { | ||
| 1485 | $node = $node->parentNode; } | ||
| 1486 | return $lang || 'en'; } | ||
| 1487 | |||
| 1488 | sub decodeFont { | ||
| 1489 | my ($self, $fontid) = @_; | ||
| 1490 | return $$self{node_fonts}{$fontid} || LaTeXML::Common::Font->textDefault(); } | ||
| 1491 | |||
| 1492 | # Remove a node from the document (from it's parent) | ||
| 1493 | sub removeNode { | ||
| 1494 | my ($self, $node) = @_; | ||
| 1495 | if ($node) { | ||
| 1496 | my $chopped = $$self{node}->isSameNode($node); # Note if we're removing insertion point | ||
| 1497 | if ($node->nodeType == XML_ELEMENT_NODE) { # If an element, do ID bookkeeping. | ||
| 1498 | if (my $id = $node->getAttribute('xml:id')) { | ||
| 1499 | $self->unRecordID($id); } | ||
| 1500 | $chopped ||= grep { $self->removeNode_aux($_) } $node->childNodes; } | ||
| 1501 | my $parent = $node->parentNode; | ||
| 1502 | if ($chopped) { # Don't remove insertion point! | ||
| 1503 | $self->setNode($parent); } | ||
| 1504 | $parent->removeChild($node); | ||
| 1505 | } | ||
| 1506 | return $node; } | ||
| 1507 | |||
| 1508 | sub removeNode_aux { | ||
| 1509 | my ($self, $node) = @_; | ||
| 1510 | my $chopped = $$self{node}->isSameNode($node); | ||
| 1511 | if ($node->nodeType == XML_ELEMENT_NODE) { # If an element, do ID bookkeeping. | ||
| 1512 | if (my $id = $node->getAttribute('xml:id')) { | ||
| 1513 | $self->unRecordID($id); } | ||
| 1514 | $chopped ||= grep { $self->removeNode_aux($_) } $node->childNodes; } | ||
| 1515 | return $chopped; } | ||
| 1516 | |||
| 1517 | #********************************************************************** | ||
| 1518 | # Inserting new nodes at random points into the document, | ||
| 1519 | # typically, later in the process or during some kind of rearrangement. | ||
| 1520 | |||
| 1521 | # This is a somewhat strange situation; There are commands and environments | ||
| 1522 | # that do some interesting thing to their contents. This include things like | ||
| 1523 | # center, flushleft, or rotate, or ... | ||
| 1524 | # Naively one is tempted to create a containing block with appropriate type & attributes. | ||
| 1525 | # However, since these things can be allowed in so many places by LaTeX, that | ||
| 1526 | # one has a difficult time creating a sensible document model. | ||
| 1527 | # The purpose of transformingBlock is to set the contents (possibly creating a | ||
| 1528 | # consistent <p> around them, if called for), and returning the list of newly | ||
| 1529 | # created nodes. These nodes can then have appropriate attributes added as needed | ||
| 1530 | # for each specific case. | ||
| 1531 | |||
| 1532 | # Since this situation can occur in both LaTeX and AmSTeX type documents, | ||
| 1533 | # we'll put it in the TeX pool so it can be reused. | ||
| 1534 | |||
| 1535 | # Tricky bit for creating nodes late in the game, | ||
| 1536 | ###### | ||
| 1537 | ### See createElementAt | ||
| 1538 | # This opens a new element at the _specified_ point, rather than the current insertion point. | ||
| 1539 | # This is useful during document rearrangement or augmentation that may be needed later | ||
| 1540 | # in the process. | ||
| 1541 | sub openElementAt { | ||
| 1542 | my ($self, $point, $qname, %attributes) = @_; | ||
| 1543 | my ($ns, $tag) = $$self{model}->decodeQName($qname); | ||
| 1544 | my $newnode; | ||
| 1545 | my $font = $attributes{_font} || $attributes{font}; | ||
| 1546 | my $box = $attributes{_box}; | ||
| 1547 | $box = $$self{node_boxes}{$box} if $box && !ref $box; # may already be the string key | ||
| 1548 | # If this will be the document root node, things are slightly more involved. | ||
| 1549 | if ($point->nodeType == XML_DOCUMENT_NODE) { # First node! (?) | ||
| 1550 | $$self{model}->addSchemaDeclaration($self, $tag); | ||
| 1551 | map { $$self{document}->appendChild($_) } @{ $$self{pending} }; # Add saved comments, PI's | ||
| 1552 | $newnode = $$self{document}->createElement($tag); | ||
| 1553 | $self->recordConstructedNode($newnode); | ||
| 1554 | $$self{document}->setDocumentElement($newnode); | ||
| 1555 | if ($ns) { | ||
| 1556 | # Here, we're creating the initial, document element, which will hold ALL of the namespace declarations. | ||
| 1557 | # If there is a default namespace (no prefix), that will also be declared, and applied here. | ||
| 1558 | # However, if there is ALSO a prefix associated with that namespace, we have to declare it FIRST | ||
| 1559 | # due to the (apparently) buggy way that XML::LibXML works with namespaces in setAttributeNS. | ||
| 1560 | my $prefix = $$self{model}->getDocumentNamespacePrefix($ns); | ||
| 1561 | my $attprefix = $$self{model}->getDocumentNamespacePrefix($ns, 1, 1); | ||
| 1562 | if (!$prefix && $attprefix) { | ||
| 1563 | $newnode->setNamespace($ns, $attprefix, 0); } | ||
| 1564 | $newnode->setNamespace($ns, $prefix, 1); } } | ||
| 1565 | else { | ||
| 1566 | $font = $self->getNodeFont($point) unless $font; | ||
| 1567 | $box = $self->getNodeBox($point) unless $box; | ||
| 1568 | $newnode = $self->openElement_internal($point, $ns, $tag); } | ||
| 1569 | |||
| 1570 | foreach my $key (sort keys %attributes) { | ||
| 1571 | next if $key eq 'font'; # !!! | ||
| 1572 | next if $key eq 'locator'; # !!! | ||
| 1573 | $self->setAttribute($newnode, $key, $attributes{$key}); } | ||
| 1574 | $self->setNodeFont($newnode, $font) if $font; | ||
| 1575 | $self->setNodeBox($newnode, $box) if $box; | ||
| 1576 | print STDERR "Inserting " . Stringify($newnode) . " into " . Stringify($point) . "\n" if $LaTeXML::Core::Document::DEBUG; | ||
| 1577 | |||
| 1578 | # Run afterOpen operations | ||
| 1579 | $self->afterOpen($newnode); | ||
| 1580 | |||
| 1581 | return $newnode; } | ||
| 1582 | |||
| 1583 | sub openElement_internal { | ||
| 1584 | my ($self, $point, $ns, $tag) = @_; | ||
| 1585 | my $newnode; | ||
| 1586 | if ($ns) { | ||
| 1587 | if (!defined $point->lookupNamespacePrefix($ns)) { # namespace not already declared? | ||
| 1588 | $self->getDocument->documentElement | ||
| 1589 | ->setNamespace($ns, $$self{model}->getDocumentNamespacePrefix($ns), 0); } | ||
| 1590 | $newnode = $point->addNewChild($ns, $tag); } | ||
| 1591 | else { | ||
| 1592 | $newnode = $point->appendChild($$self{document}->createElement($tag)); } | ||
| 1593 | $self->recordConstructedNode($newnode); | ||
| 1594 | return $newnode; } | ||
| 1595 | |||
| 1596 | # Whenever a node has been created using openElementAt, | ||
| 1597 | # closeElementAt ought to be used to close it, when you're finished inserting into $node. | ||
| 1598 | # Basically, this just runs any afterClose operations. | ||
| 1599 | sub closeElementAt { | ||
| 1600 | my ($self, $node) = @_; | ||
| 1601 | return $self->afterClose($node); } | ||
| 1602 | |||
| 1603 | sub afterOpen { | ||
| 1604 | my ($self, $node) = @_; | ||
| 1605 | # Set current point to this node, just in case the afterOpen's use it. | ||
| 1606 | my $savenode = $$self{node}; | ||
| 1607 | $self->setNode($node); | ||
| 1608 | my $box = $self->getNodeBox($node); | ||
| 1609 | map { &$_($self, $node, $box) } $self->getTagActionList($node, 'afterOpen'); | ||
| 1610 | $self->setNode($savenode); | ||
| 1611 | return $node; } | ||
| 1612 | |||
| 1613 | sub afterClose { | ||
| 1614 | my ($self, $node) = @_; | ||
| 1615 | # Should we set point to this node? (or to last child, or something ?? | ||
| 1616 | my $savenode = $$self{node}; | ||
| 1617 | my $box = $self->getNodeBox($node); | ||
| 1618 | map { &$_($self, $node, $box) } $self->getTagActionList($node, 'afterClose'); | ||
| 1619 | $self->setNode($savenode); | ||
| 1620 | return $node; } | ||
| 1621 | |||
| 1622 | #********************************************************************** | ||
| 1623 | # Appending clones of nodes | ||
| 1624 | |||
| 1625 | # Inserting clones of nodes into the document. | ||
| 1626 | # Nodes that exist in some other part of the document (or some other document) | ||
| 1627 | # will need to be cloned so that they can be part of the new document; | ||
| 1628 | # otherwise, they would be removed from thier previous document. | ||
| 1629 | # Also, we want to have a clean namespace node structure | ||
| 1630 | # (otherwise, libxml2 has a tendency to introduce annoying "default" namespace prefix declarations) | ||
| 1631 | # And, finally, we need to modify any id's present in the old nodes, | ||
| 1632 | # since otherwise they may be duplicated. | ||
| 1633 | |||
| 1634 | # Should have variants here for prepend, insert before, insert after.... ??? | ||
| 1635 | sub appendClone { | ||
| 1636 | my ($self, $node, @newchildren) = @_; | ||
| 1637 | # Expand any document fragments | ||
| 1638 | @newchildren = map { ($_->nodeType == XML_DOCUMENT_FRAG_NODE ? $_->childNodes : $_) } @newchildren; | ||
| 1639 | # Now find all xml:id's in the newchildren and record replacement id's for them | ||
| 1640 | local %LaTeXML::Core::Document::IDMAP = (); | ||
| 1641 | # Find all id's defined in the copy and change the id. | ||
| 1642 | foreach my $child (@newchildren) { | ||
| 1643 | foreach my $idnode ($self->findnodes('.//@xml:id', $child)) { | ||
| 1644 | my $id = $idnode->getValue; | ||
| 1645 | $LaTeXML::Core::Document::IDMAP{$id} = $self->modifyID($id); } } | ||
| 1646 | # Now do the cloning (actually copying) and insertion. | ||
| 1647 | $self->appendClone_aux($node, @newchildren); | ||
| 1648 | return $node; } | ||
| 1649 | |||
| 1650 | sub appendClone_aux { | ||
| 1651 | my ($self, $node, @newchildren) = @_; | ||
| 1652 | foreach my $child (@newchildren) { | ||
| 1653 | my $type = $child->nodeType; | ||
| 1654 | if ($type == XML_ELEMENT_NODE) { | ||
| 1655 | my $new = $self->openElement_internal($node, $child->namespaceURI, $child->localname); | ||
| 1656 | foreach my $attr ($child->attributes) { | ||
| 1657 | if ($attr->nodeType == XML_ATTRIBUTE_NODE) { | ||
| 1658 | my $key = $attr->nodeName; | ||
| 1659 | if ($key eq 'xml:id') { # Use the replacement id | ||
| 1660 | my $newid = $LaTeXML::Core::Document::IDMAP{ $attr->getValue }; | ||
| 1661 | $newid = $self->recordID($newid, $new); | ||
| 1662 | $new->setAttribute($key, $newid); } | ||
| 1663 | elsif ($key eq 'idref') { # Refer to the replacement id if it was replaced | ||
| 1664 | my $id = $attr->getValue; | ||
| 1665 | $new->setAttribute($key, $LaTeXML::Core::Document::IDMAP{$id} || $id); } | ||
| 1666 | elsif (my $ns = $attr->namespaceURI) { | ||
| 1667 | $new->setAttributeNS($ns, $attr->name, $attr->getValue); } | ||
| 1668 | else { | ||
| 1669 | $new->setAttribute($attr->localname, $attr->getValue); } } | ||
| 1670 | } | ||
| 1671 | $self->afterOpen($new); | ||
| 1672 | $self->appendClone_aux($new, $child->childNodes); | ||
| 1673 | $self->afterClose($new); } | ||
| 1674 | elsif ($type == XML_TEXT_NODE) { | ||
| 1675 | $node->appendTextNode($child->textContent); } } | ||
| 1676 | return $node; } | ||
| 1677 | |||
| 1678 | #********************************************************************** | ||
| 1679 | # Wrapping & Unwrapping nodes by another element. | ||
| 1680 | |||
| 1681 | # Wrap @nodes with an element named $qname, making the new element replace the first $node, | ||
| 1682 | # and all @nodes becomes the child of the new node. | ||
| 1683 | # [this makes most sense if @nodes are a sequence of siblings] | ||
| 1684 | # Returns undef if $qname isn't allowed in the parent, or if @nodes aren't allowed in $qname, | ||
| 1685 | # otherwise, returns the newly created $qname. | ||
| 1686 | sub wrapNodes { | ||
| 1687 | my ($self, $qname, @nodes) = @_; | ||
| 1688 | return unless @nodes; | ||
| 1689 | my $model = $$self{model}; | ||
| 1690 | my $parent = $nodes[0]->parentNode; | ||
| 1691 | my ($ns, $tag) = $model->decodeQName($qname); | ||
| 1692 | my $new = $self->openElement_internal($parent, $ns, $tag); | ||
| 1693 | $self->afterOpen($new); | ||
| 1694 | $parent->replaceChild($new, $nodes[0]); | ||
| 1695 | |||
| 1696 | if (my $font = $self->getNodeFont($parent)) { | ||
| 1697 | $self->setNodeFont($new, $font); } | ||
| 1698 | if (my $box = $self->getNodeBox($parent)) { | ||
| 1699 | $self->setNodeBox($new, $box); } | ||
| 1700 | foreach my $node (@nodes) { | ||
| 1701 | $new->appendChild($node); } | ||
| 1702 | $self->afterClose($new); | ||
| 1703 | return $new; } | ||
| 1704 | |||
| 1705 | # Unwrap the children of $node, by replacing $node by its children. | ||
| 1706 | sub unwrapNodes { | ||
| 1707 | my ($self, $node) = @_; | ||
| 1708 | return $self->replaceNode($node, $node->childNodes); } | ||
| 1709 | |||
| 1710 | # Replace $node by @nodes (presumably descendants of some kind?) | ||
| 1711 | sub replaceNode { | ||
| 1712 | my ($self, $node, @nodes) = @_; | ||
| 1713 | my $parent = $node->parentNode; | ||
| 1714 | my $c0; | ||
| 1715 | while (my $c1 = shift(@nodes)) { | ||
| 1716 | if ($c0) { $parent->insertAfter($c1, $c0); } | ||
| 1717 | else { $parent->replaceChild($c1, $node); } | ||
| 1718 | $c0 = $c1; } | ||
| 1719 | $self->removeNode($node); | ||
| 1720 | return $node; } | ||
| 1721 | |||
| 1722 | # initially since $node->setNodeName was broken in XML::LibXML 1.58 | ||
| 1723 | # but this can provide for more options & correctness? | ||
| 1724 | sub renameNode { | ||
| 1725 | my ($self, $node, $newname) = @_; | ||
| 1726 | my $model = $$self{model}; | ||
| 1727 | my ($ns, $tag) = $model->decodeQName($newname); | ||
| 1728 | my $parent = $node->parentNode; | ||
| 1729 | my $new = $self->openElement_internal($parent, $ns, $tag); | ||
| 1730 | my $id; | ||
| 1731 | # Move to the position AFTER $node | ||
| 1732 | $parent->insertAfter($new, $node); | ||
| 1733 | # Copy ALL attributes from $node to $newnode | ||
| 1734 | foreach my $attr ($node->attributes) { | ||
| 1735 | my $key = $attr->getName; | ||
| 1736 | my $value = $node->getAttribute($key); | ||
| 1737 | $id = $value if $key eq 'xml:id'; # Save to register after removal of old node. | ||
| 1738 | $new->setAttribute($key, $value); } | ||
| 1739 | # AND move all content from $node to $newnode | ||
| 1740 | foreach my $child ($node->childNodes) { | ||
| 1741 | $new->appendChild($child); } | ||
| 1742 | ## THEN call afterOpen... ? | ||
| 1743 | # It would normally be called before children added, | ||
| 1744 | # but how can we know if we're duplicated auto-added stuff? | ||
| 1745 | $self->afterOpen($new); | ||
| 1746 | $self->afterClose($new); | ||
| 1747 | # Finally, remove the old node | ||
| 1748 | $self->removeNode($node); | ||
| 1749 | # and FINALLY, we can register the new node under the id. | ||
| 1750 | if ($id) { | ||
| 1751 | my $newid = $self->recordID($id, $new); | ||
| 1752 | $new->setAttribute('xml:id' => $newid) if $newid ne $id; } | ||
| 1753 | return $new; } | ||
| 1754 | |||
| 1755 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 1756 | # Finally, another set of surgery methods | ||
| 1757 | # These take an array representation of the XML Tree to append | ||
| 1758 | # [tagname,{attributes..}, children] | ||
| 1759 | # THESE SHOULD BE PART OF A COMMON BASE CLASS; DUPLICATED IN Post::Document | ||
| 1760 | #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% | ||
| 1761 | |||
| 1762 | sub replaceTree { | ||
| 1763 | my ($self, $new, $old) = @_; | ||
| 1764 | my $parent = $old->parentNode; | ||
| 1765 | my @following = (); # Collect the matching and following nodes | ||
| 1766 | while (my $sib = $parent->lastChild) { | ||
| 1767 | last if $sib->isSameNode($old); | ||
| 1768 | $parent->removeChild($sib); # We're putting these back, in a moment! | ||
| 1769 | unshift(@following, $sib); } | ||
| 1770 | $self->removeNode($old); | ||
| 1771 | $self->appendTree($parent, $new); | ||
| 1772 | my $inserted = $parent->lastChild; | ||
| 1773 | map { $parent->appendChild($_) } @following; # No need for clone | ||
| 1774 | return $inserted; } | ||
| 1775 | |||
| 1776 | sub appendTree { | ||
| 1777 | my ($self, $node, @data) = @_; | ||
| 1778 | foreach my $child (@data) { | ||
| 1779 | if (ref $child eq 'ARRAY') { | ||
| 1780 | my ($tag, $attributes, @children) = @$child; | ||
| 1781 | my $new = $self->openElementAt($node, $tag, ($attributes ? %$attributes : ())); | ||
| 1782 | $self->appendTree($new, @children); } | ||
| 1783 | elsif ((ref $child) =~ /^XML::LibXML::/) { | ||
| 1784 | my $type = $child->nodeType; | ||
| 1785 | if ($type == XML_ELEMENT_NODE) { | ||
| 1786 | my $tag = $self->getNodeQName($child); | ||
| 1787 | my %attributes = map { $_->nodeType == XML_ATTRIBUTE_NODE ? ($_->nodeName => $_->getValue) : () } | ||
| 1788 | $child->attributes; | ||
| 1789 | # DANGER: REMOVE the xml:id attribute from $child!!!! | ||
| 1790 | # This protects against some versions of XML::LibXML that warn against duplicate id's | ||
| 1791 | # Hopefully, you shouldn't be using the node any more | ||
| 1792 | if (my $id = $attributes{'xml:id'}) { | ||
| 1793 | $child->removeAttribute('xml:id'); | ||
| 1794 | $self->unRecordID($id); } | ||
| 1795 | my $new = $self->openElementAt($node, $tag, %attributes); | ||
| 1796 | $self->appendTree($new, $child->childNodes); } | ||
| 1797 | elsif ($type == XML_DOCUMENT_FRAG_NODE) { | ||
| 1798 | $self->appendTree($node, $child->childNodes); } | ||
| 1799 | elsif ($type == XML_TEXT_NODE) { | ||
| 1800 | $node->appendTextNode($child->textContent); } | ||
| 1801 | } | ||
| 1802 | elsif ((ref $child) && $child->isaBox) { | ||
| 1803 | my $savenode = $self->getNode; | ||
| 1804 | $self->setNode($node); | ||
| 1805 | $self->absorb($child); | ||
| 1806 | $self->setNode($savenode); } | ||
| 1807 | elsif (ref $child) { | ||
| 1808 | Warn('malformed', $child, $node, "Dont know how to add '$child' to document; ignoring"); } | ||
| 1809 | elsif (defined $child) { | ||
| 1810 | $node->appendTextNode($child); } } | ||
| 1811 | return; } | ||
| 1812 | |||
| 1813 | #********************************************************************** | ||
| 1814 | 1; | ||
| 1815 | |||
| 1816 | __END__ |