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