| 1 | # /=====================================================================\ # | ||
| 2 | # | LaTeXML::Core::Rewrite | # | ||
| 3 | # | Rewrite Rules that modify the Constructed Document | # | ||
| 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 | package LaTeXML::Core::Rewrite; | ||
| 13 | use strict; | ||
| 14 | use warnings; | ||
| 15 | use LaTeXML::Global; | ||
| 16 | use LaTeXML::Common::Object; | ||
| 17 | use LaTeXML::Common::Error; | ||
| 18 | use LaTeXML::Common::XML; | ||
| 19 | |||
| 20 | sub new { | ||
| 21 | my ($class, $mode, @specs) = @_; | ||
| 22 | my @clauses = (); | ||
| 23 | while (@specs) { | ||
| 24 | my ($op, $pattern) = (shift(@specs), shift(@specs)); | ||
| 25 | push(@clauses, ['uncompiled', $op, $pattern]); } | ||
| 26 | return bless { | ||
| 27 | mode => $mode, math => ($mode eq 'math'), clauses => [@clauses], labels => {} | ||
| 28 | }, $class; } | ||
| 29 | |||
| 30 | sub clauses { | ||
| 31 | my ($self) = @_; | ||
| 32 | return @{ $$self{clauses} }; } | ||
| 33 | |||
| 34 | sub rewrite { | ||
| 35 | my ($self, $document, $node) = @_; | ||
| 36 | foreach my $node ($document->findnodes('//*[@labels]')) { | ||
| 37 | my $labels = $node->getAttribute('labels'); | ||
| 38 | if (my $id = $node->getAttribute('xml:id')) { | ||
| 39 | foreach my $label (split(/ /, $labels)) { | ||
| 40 | $$self{labels}{$label} = $id; } } | ||
| 41 | else { | ||
| 42 | Error('malformed', 'label', $node, "Node has labels but no xml:id"); } } | ||
| 43 | $self->applyClause($document, $node, 0, $self->clauses); | ||
| 44 | return; } | ||
| 45 | |||
| 46 | sub getLabelID { | ||
| 47 | my ($self, $label) = @_; | ||
| 48 | if (my $id = $$self{labels}{ LaTeXML::Package::CleanLabel($label) }) { | ||
| 49 | return $id; } | ||
| 50 | else { | ||
| 51 | Error('misdefined', '<rewrite>', undef, "No id for label $label in Rewrite"); | ||
| 52 | return; } } | ||
| 53 | |||
| 54 | # Rewrite spec as input | ||
| 55 | # scope => $scope : a scope like "section:1.2.3" or "label:eq.one"; translated to xpath | ||
| 56 | # select => $xpath : selects subtrees based on xpath expression. | ||
| 57 | # match => $code : called on $document and current $node: tests current node, returns $nnodes, if match | ||
| 58 | # match => $string : Treats as TeX, converts Box, then DOM tree, to xpath | ||
| 59 | # (The matching top-level nodes will be replaced, if replace is the next op.) | ||
| 60 | # replace=> $code : removes the current $nnodes, calls $code with $document and removed nodes | ||
| 61 | # replace=> $string : removes $nnodes | ||
| 62 | # Treats $string as TeX, converts to Box and inserts to replace | ||
| 63 | # the removed nodes. | ||
| 64 | # attributes=>$hash : adds data from hash as attributes to the current node. | ||
| 65 | # regexp => $string: apply regexp (subst) to all text nodes in/under the current node. | ||
| 66 | |||
| 67 | # Compiled rewrite spec: | ||
| 68 | # select => $xpath : operate on nodes selected by $xpath. | ||
| 69 | # test => $code : Calls $code on $document and current $node. | ||
| 70 | # Returns number of nodes matched. | ||
| 71 | # replace=> $code : removes the current $nnodes, calls $code on them. | ||
| 72 | # action => $code : invoke $code on current $node, without removing them. | ||
| 73 | # regexp => $string: apply regexp (subst) to all text nodes in/under the current node. | ||
| 74 | |||
| 75 | sub applyClause { | ||
| 76 | my ($self, $document, $tree, $n_to_replace, $clause, @more_clauses) = @_; | ||
| 77 | if ($$clause[0] eq 'uncompiled') { | ||
| 78 | $self->compileClause($document, $clause); } | ||
| 79 | my ($ignore, $op, $pattern) = @$clause; | ||
| 80 | if ($op eq 'trace') { | ||
| 81 | local $LaTeXML::Core::Rewrite::DEBUG = 1; | ||
| 82 | $self->applyClause($document, $tree, $n_to_replace, @more_clauses); } | ||
| 83 | elsif ($op eq 'ignore') { | ||
| 84 | $self->applyClause($document, $tree, $n_to_replace, @more_clauses); } | ||
| 85 | elsif ($op eq 'select') { | ||
| 86 | my ($xpath, $nnodes) = @$pattern; | ||
| 87 | my @matches = $document->findnodes($xpath, $tree); | ||
| 88 | print STDERR "Rewrite selecting \"$xpath\" => " . scalar(@matches) . " matches\n" | ||
| 89 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 90 | foreach my $node (@matches) { | ||
| 91 | next unless $node->ownerDocument->isSameNode($tree->ownerDocument); # If still attached to original document! | ||
| 92 | $self->applyClause($document, $node, $nnodes, @more_clauses); } } | ||
| 93 | elsif ($op eq 'multi_select') { | ||
| 94 | foreach my $subpattern (@$pattern) { | ||
| 95 | my ($xpath, $nnodes) = @$subpattern; | ||
| 96 | my @matches = $document->findnodes($xpath, $tree); | ||
| 97 | print STDERR "Rewrite selecting \"$xpath\" => " . scalar(@matches) . " matches\n" | ||
| 98 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 99 | foreach my $node (@matches) { | ||
| 100 | next unless $node->ownerDocument->isSameNode($tree->ownerDocument); # If still attached to original document! | ||
| 101 | $self->applyClause($document, $node, $nnodes, @more_clauses); } } } | ||
| 102 | elsif ($op eq 'test') { | ||
| 103 | my $nnodes = &$pattern($document, $tree); | ||
| 104 | print STDERR "Rewrite test at " . $tree->toString . ": " . ($nnodes ? $nnodes . " to replace" : "failed") . "\n" | ||
| 105 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 106 | $self->applyClause($document, $tree, $nnodes, @more_clauses) if $nnodes; } | ||
| 107 | elsif ($op eq 'wrap') { | ||
| 108 | if ($n_to_replace > 1) { | ||
| 109 | my $parent = $tree->parentNode; | ||
| 110 | # Remove & separate nodes to be replaced, and sibling nodes following them. | ||
| 111 | my @following = (); # Collect the matching and following nodes | ||
| 112 | while (my $sib = $parent->lastChild) { | ||
| 113 | $parent->removeChild($sib); | ||
| 114 | unshift(@following, $sib); | ||
| 115 | last if $$sib == $$tree; } | ||
| 116 | my @replaced = map { shift(@following) } 1 .. $n_to_replace; # Remove the nodes to be replaced | ||
| 117 | $document->setNode($parent); | ||
| 118 | $tree = $document->openElement('ltx:XMWrap', font => $document->getNodeFont($parent)); | ||
| 119 | print STDERR "Wrapping " . join(' ', map { Stringify($_) } @replaced) . "\n" | ||
| 120 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 121 | map { $tree->appendChild($_) } @replaced; # Add matched nodes to XMWrap | ||
| 122 | map { $parent->appendChild($_) } @following; # Add back the following nodes. | ||
| 123 | } | ||
| 124 | $self->applyClause($document, $tree, 1, @more_clauses); } | ||
| 125 | elsif ($op eq 'replace') { | ||
| 126 | print STDERR "Rewrite replace at " . $tree->toString . " using $pattern\n" | ||
| 127 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 128 | my $parent = $tree->parentNode; | ||
| 129 | # Remove & separate nodes to be replaced, and sibling nodes following them. | ||
| 130 | my @following = (); # Collect the matching and following nodes | ||
| 131 | while (my $sib = $parent->lastChild) { | ||
| 132 | $parent->removeChild($sib); | ||
| 133 | unshift(@following, $sib); | ||
| 134 | last if $tree->isSameNode($sib); } | ||
| 135 | my @replaced = map { shift(@following) } 1 .. $n_to_replace; # Remove the nodes to be replaced | ||
| 136 | map { $document->unRecordNodeIDs($_) } @replaced; | ||
| 137 | # Carry out the operation, inserting whatever nodes. | ||
| 138 | $document->setNode($parent); | ||
| 139 | my $point = $parent->lastChild; | ||
| 140 | &$pattern($document, @replaced); # Carry out the insertion. | ||
| 141 | |||
| 142 | # Now collect the newly inserted nodes for any needed patching | ||
| 143 | my @inserted = (); # Collect the newly added nodes. | ||
| 144 | if ($point) { | ||
| 145 | my @sibs = $parent->childNodes; | ||
| 146 | while (my $sib = pop(@sibs)) { | ||
| 147 | last if $$sib == $$point; | ||
| 148 | unshift(@inserted, $sib); } } | ||
| 149 | else { | ||
| 150 | @inserted = $parent->childNodes; } | ||
| 151 | |||
| 152 | # Now make any adjustments to the new nodes | ||
| 153 | map { $document->recordNodeIDs($_) } @inserted; | ||
| 154 | my $font = $document->getNodeFont($tree); # the font of the matched node | ||
| 155 | foreach my $ins (@inserted) { # Copy the non-semantic parts of font to the replacement | ||
| 156 | $document->mergeNodeFontRec($ins => $font); } | ||
| 157 | # Now, replace the following nodes. | ||
| 158 | map { $parent->appendChild($_) } @following; } | ||
| 159 | elsif ($op eq 'action') { | ||
| 160 | print STDERR "Rewrite action at " . $tree->toString . " using $pattern\n" | ||
| 161 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 162 | &$pattern($tree); } | ||
| 163 | elsif ($op eq 'attributes') { | ||
| 164 | map { $tree->setAttribute($_, $$pattern{$_}) } keys %$pattern; | ||
| 165 | print STDERR "Rewrite attributes for " . Stringify($tree) . "\n" | ||
| 166 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 167 | } | ||
| 168 | elsif ($op eq 'regexp') { | ||
| 169 | my @matches = $document->findnodes('descendant-or-self::text()', $tree); | ||
| 170 | print STDERR "Rewrite regexp => " . scalar(@matches) . " matches\n" | ||
| 171 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 172 | foreach my $text (@matches) { | ||
| 173 | my $string = $text->textContent; | ||
| 174 | if (&$pattern($string)) { | ||
| 175 | $text->setData($string); } } } | ||
| 176 | else { | ||
| 177 | Error('misdefined', '<rewrite>', undef, "Unknown directive '$op' in Compiled Rewrite spec"); } | ||
| 178 | return; } | ||
| 179 | |||
| 180 | #********************************************************************** | ||
| 181 | sub compileClause { | ||
| 182 | my ($self, $document, $clause) = @_; | ||
| 183 | my ($ignore, $op, $pattern) = @$clause; | ||
| 184 | my ($oop, $opattern) = ($op, $pattern); | ||
| 185 | if ($op eq 'label') { | ||
| 186 | if (ref $pattern eq 'ARRAY') { | ||
| 187 | # $op='multi_select'; $pattern = [map(["descendant-or-self::*[\@label='$_']",1], @$pattern)]; } | ||
| 188 | |||
| 189 | $op = 'multi_select'; $pattern = [map { ["descendant-or-self::*[\@xml:id='$_']", 1] } | ||
| 190 | map { $self->getLabelID($_) } @$pattern]; } | ||
| 191 | else { | ||
| 192 | # $op='select'; $pattern=["descendant-or-self::*[\@label='$pattern']",1]; }} | ||
| 193 | $op = 'select'; | ||
| 194 | $pattern = ["descendant-or-self::*[\@xml:id='" . $self->getLabelID($pattern) . "']", 1]; } } | ||
| 195 | elsif ($op eq 'scope') { | ||
| 196 | $op = 'select'; | ||
| 197 | if ($pattern =~ /^label:(.*)$/) { | ||
| 198 | # $pattern=["descendant-or-self::*[\@label='$1']",1]; } | ||
| 199 | $pattern = ["descendant-or-self::*[\@xml:id='" . $self->getLabelID($1) . "']", 1]; } | ||
| 200 | elsif ($pattern =~ /^id:(.*)$/) { | ||
| 201 | $pattern = ["descendant-or-self::*[\@xml:id='$1']", 1]; } | ||
| 202 | ### Is this pattern ever used? <elementname>:<refnum> expects attribute!!! | ||
| 203 | ### elsif ($pattern =~ /^(.*):(.*)$/) { | ||
| 204 | ### $pattern = ["descendant-or-self::*[local-name()='$1' and \@refnum='$2']", 1]; } | ||
| 205 | else { | ||
| 206 | Error('misdefined', '<rewrite>', undef, | ||
| 207 | "Unrecognized scope pattern in Rewrite clause: \"$pattern\"; Ignoring it."); | ||
| 208 | $op = 'ignore'; $pattern = []; } } | ||
| 209 | elsif ($op eq 'xpath') { | ||
| 210 | $op = 'select'; $pattern = [$pattern, 1]; } | ||
| 211 | elsif ($op eq 'match') { | ||
| 212 | if (ref $pattern eq 'CODE') { | ||
| 213 | $op = 'test'; } | ||
| 214 | elsif (ref $pattern eq 'ARRAY') { # Multiple patterns! | ||
| 215 | $op = 'multi_select'; | ||
| 216 | $pattern = [map { $self->compile_match($document, $_) } @$pattern]; } | ||
| 217 | else { | ||
| 218 | $op = 'select'; $pattern = $self->compile_match($document, $pattern); } } | ||
| 219 | elsif ($op eq 'replace') { | ||
| 220 | if (ref $pattern eq 'CODE') { } | ||
| 221 | else { | ||
| 222 | $pattern = $self->compile_replacement($document, $pattern); } } | ||
| 223 | elsif ($op eq 'regexp') { | ||
| 224 | $pattern = $self->compile_regexp($pattern); } | ||
| 225 | print STDERR "Compiled clause $oop=>" . ToString($opattern) . " ==> $op=>" . ToString($pattern) . "\n" | ||
| 226 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 227 | $$clause[0] = 'compiled'; $$clause[1] = $op; $$clause[2] = $pattern; | ||
| 228 | return; } | ||
| 229 | |||
| 230 | #********************************************************************** | ||
| 231 | sub compile_match { | ||
| 232 | my ($self, $document, $pattern) = @_; | ||
| 233 | ### if (!ref $pattern) { | ||
| 234 | ### return $self->compile_match1($document, | ||
| 235 | ### digest_rewrite(($$self{math} ? '$' . $pattern . '$' : $pattern))); } | ||
| 236 | ### els | ||
| 237 | if ($pattern->isaBox) { | ||
| 238 | return $self->compile_match1($document, $pattern); } | ||
| 239 | elsif (ref $pattern) { # Is tokens???? | ||
| 240 | return $self->compile_match1($document, digest_rewrite($pattern)); } | ||
| 241 | else { | ||
| 242 | Error('misdefined', '<rewrite>', undef, | ||
| 243 | "Don't know what to do with match=>\"" . Stringify($pattern) . "\""); | ||
| 244 | return; } } | ||
| 245 | |||
| 246 | sub compile_match1 { | ||
| 247 | my ($self, $document, $patternbox) = @_; | ||
| 248 | # Create a temporary document | ||
| 249 | my $capdocument = LaTeXML::Core::Document->new($document->getModel); | ||
| 250 | my $capture = $capdocument->openElement('_Capture_', font => LaTeXML::Common::Font->new()); | ||
| 251 | $capdocument->absorb($patternbox); | ||
| 252 | my @nodes = ($$self{mode} eq 'math' | ||
| 253 | ? $capdocument->findnodes("//ltx:XMath/*", $capture) | ||
| 254 | : $capture->childNodes); | ||
| 255 | my $frag = $capdocument->getDocument->createDocumentFragment; | ||
| 256 | map { $frag->appendChild($_) } @nodes; | ||
| 257 | # Convert the captured nodes to an XPath that would match them. | ||
| 258 | my $xpath = domToXPath($capdocument, $frag); | ||
| 259 | # The branches of an XMDual can contain "decorations", nodes that are ONLY visible | ||
| 260 | # from either presentation or content, but not both. | ||
| 261 | # [See LaTeXML::Core::Document->markXMNodeVisibility] | ||
| 262 | # These decorations should NOT have rewrite rules applied | ||
| 263 | $xpath .= '[@_pvis and @_cvis]' if $$self{math}; | ||
| 264 | |||
| 265 | print STDERR "Converting \"" . ToString($patternbox) . "\"\n => xpath= \"$xpath\"\n" | ||
| 266 | if $LaTeXML::Core::Rewrite::DEBUG; | ||
| 267 | return [$xpath, scalar(@nodes)]; } | ||
| 268 | |||
| 269 | # Reworked to do digestion at replacement time. | ||
| 270 | sub compile_replacement { | ||
| 271 | my ($self, $document, $pattern) = @_; | ||
| 272 | |||
| 273 | if ((ref $pattern) && $pattern->isaBox) { | ||
| 274 | $pattern = $pattern->getBody if $$self{math}; | ||
| 275 | return sub { $_[0]->absorb($pattern); } } | ||
| 276 | else { | ||
| 277 | ##### $pattern = Tokenize($$self{math} ? '$' . $pattern . '$' : $pattern) unless ref $pattern; | ||
| 278 | return sub { | ||
| 279 | my $stomach = $STATE->getStomach; | ||
| 280 | $stomach->bgroup; | ||
| 281 | $STATE->assignValue(font => LaTeXML::Common::Font->new(), 'local'); | ||
| 282 | $STATE->assignValue(mathfont => LaTeXML::Common::Font->new(), 'local'); | ||
| 283 | my $box = $stomach->digest($pattern, 0); | ||
| 284 | $stomach->egroup; | ||
| 285 | $box = $box->getBody if $$self{math}; | ||
| 286 | $_[0]->absorb($box); } | ||
| 287 | } } | ||
| 288 | |||
| 289 | sub compile_regexp { | ||
| 290 | my ($self, $pattern) = @_; | ||
| 291 | my $code = "sub { \$_[0] =~ s${pattern}g; }"; | ||
| 292 | ## no critic | ||
| 293 | my $fcn = eval $code; | ||
| 294 | ## use critic | ||
| 295 | Error('misdefined', '<rewrite>', undef, | ||
| 296 | "Failed to compile regexp pattern \"$pattern\" into \"$code\": $!") if $@; | ||
| 297 | return $fcn; } | ||
| 298 | |||
| 299 | #********************************************************************** | ||
| 300 | |||
| 301 | sub digest_rewrite { | ||
| 302 | my ($string) = @_; | ||
| 303 | my $stomach = $STATE->getStomach; | ||
| 304 | $stomach->bgroup; | ||
| 305 | $STATE->assignValue(font => LaTeXML::Common::Font->new(), 'local'); # Use empty font, so eventual insertion merges. | ||
| 306 | $STATE->assignValue(mathfont => LaTeXML::Common::Font->new(), 'local'); | ||
| 307 | ### my $box = $stomach->digest((ref $string ? $string : Tokenize($string)), 0); | ||
| 308 | my $box = $stomach->digest($string, 0); | ||
| 309 | $stomach->egroup; | ||
| 310 | return $box; } | ||
| 311 | |||
| 312 | #********************************************************************** | ||
| 313 | sub domToXPath { | ||
| 314 | my ($document, $node) = @_; | ||
| 315 | return "descendant-or-self::" . domToXPath_rec($document, $node); } | ||
| 316 | |||
| 317 | # May need some work here; | ||
| 318 | my %EXCLUDED_MATCH_ATTRIBUTES = (scriptpos => 1, 'xml:id' => 1, fontsize => 1); # [CONSTANT] | ||
| 319 | |||
| 320 | sub domToXPath_rec { | ||
| 321 | my ($document, $node, @extra_predicates) = @_; | ||
| 322 | my $type = $node->nodeType; | ||
| 323 | if ($type == XML_DOCUMENT_FRAG_NODE) { | ||
| 324 | my @nodes = $node->childNodes; | ||
| 325 | return domToXPath_rec($document, shift(@nodes), | ||
| 326 | domToXPath_seq($document, 'following-sibling', @nodes), @extra_predicates); } | ||
| 327 | elsif ($type == XML_ELEMENT_NODE) { | ||
| 328 | my $qname = $document->getNodeQName($node); | ||
| 329 | return '*[true()]' if $qname eq '_WildCard_'; | ||
| 330 | my @predicates = (); | ||
| 331 | # Order the predicates so as to put most quickly restrictive first. | ||
| 332 | if ($node->hasAttributes) { | ||
| 333 | foreach my $attribute (grep { $_->nodeType == XML_ATTRIBUTE_NODE } $node->attributes) { | ||
| 334 | my $key = $attribute->nodeName; | ||
| 335 | next if ($key =~ /^_/) || $EXCLUDED_MATCH_ATTRIBUTES{$key}; | ||
| 336 | push(@predicates, "\@" . $key . "='" . $attribute->getValue . "'"); } } | ||
| 337 | if ($node->hasChildNodes) { | ||
| 338 | my @children = $node->childNodes; | ||
| 339 | if (!grep { $_->nodeType != XML_TEXT_NODE } @children) { # All are text nodes: | ||
| 340 | push(@predicates, "text()='" . $node->textContent . "'"); } | ||
| 341 | elsif (!grep { $_->nodeType != XML_ELEMENT_NODE } @children) { | ||
| 342 | push(@predicates, domToXPath_seq($document, 'child', @children)); } | ||
| 343 | else { | ||
| 344 | Fatal('misdefined', '<rewrite>', $node, | ||
| 345 | "Can't generate XPath for mixed content"); } } | ||
| 346 | if ($document->canHaveAttribute($qname, 'font')) { | ||
| 347 | if (my $font = $node->getAttribute('_font')) { | ||
| 348 | my $pred = LaTeXML::Common::Font::font_match_xpaths($font); | ||
| 349 | push(@predicates, $pred); } } | ||
| 350 | |||
| 351 | return $qname . "[" . join(' and ', grep { $_ } @predicates, @extra_predicates) . "]"; } | ||
| 352 | |||
| 353 | elsif ($type == XML_TEXT_NODE) { | ||
| 354 | ### "text()='".$node->textContent."'"; }} | ||
| 355 | return "*[text()='" . $node->textContent . "']"; } } | ||
| 356 | |||
| 357 | # $axis would be child or following-sibling | ||
| 358 | sub domToXPath_seq { | ||
| 359 | my ($document, $axis, @nodes) = @_; | ||
| 360 | if (@nodes) { | ||
| 361 | return $axis . "::*[position()=1 and self::" | ||
| 362 | . domToXPath_rec($document, shift(@nodes), domToXPath_seq($document, 'following-sibling', @nodes)) . ']'; } | ||
| 363 | else { | ||
| 364 | return (); } } | ||
| 365 | |||
| 366 | #********************************************************************** | ||
| 367 | 1; | ||
| 368 | |||
| 369 | __END__ |