lib/LaTeXML/Post.pm

filter: Statementstmt 40.9% 43 / 105 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 4 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 60.0% 15 / 25 Podpod n/a totaltotal 39.7% 58 / 146 CC 10 SCAR 26.9
CC
10
Cov
36%
ProcessChain_internal
56.0
getsorter
20.0
new
2.0
CRAP 14.8
« lib/LaTeXML/Util/ObjectDB.pm ↑ Summary lib/LaTeXML/Core/Array.pm »
1 # /=====================================================================\ #
2 # | LaTeXML::Post | #
3 # | PostProcessing driver | #
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::Post;
14 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 27 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 27 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 27 ▶use LaTeXML::Util::Radix;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 27 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 27 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 27 ▶use base qw(LaTeXML::Common::Object);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 27 ▶use LaTeXML::Global;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 27 ▶use LaTeXML::Common::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 27 ▶use LaTeXML::Core::State;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 our @EXPORT = (@LaTeXML::Common::Error::EXPORT);
25  
26 sub new {
27 0 ▶ my ($class, %options) = @_;
Subroutine new: not called CC=1 SCAR=6.9
28 0 my $self = bless { status => {}, %options }, $class;
29 # TEMPORARY HACK!!!!
30 # Create a State object, for config & recursive conversions;
31 # Eventually should be managed higher up.
32 0 $$self{state} = LaTeXML::Core::State->new();
33 0 return $self; }
34  
35 #======================================================================
36 sub ProcessChain {
37 0 ▶ my ($self, $doc, @postprocessors) = @_;
Subroutine ProcessChain: not called CC=1 SCAR=6.9
38 return $self->withState(sub {
39 0 ▶ return $self->ProcessChain_internal($doc, @postprocessors); }); }
Subroutine __ANON__: not called CC=1 SCAR=6.9
40  
41 sub ProcessChain_internal {
42 0 ▶ my ($self, $doc, @postprocessors) = @_;
Subroutine ProcessChain_internal: not called CC=7 SCAR=40.3
43 0 local $LaTeXML::POST = $self;
44 0 local $LaTeXML::Post::NOTEINFO = undef;
45 0 local $LaTeXML::Post::DOCUMENT = $doc;
46  
47 0 my @docs = ($doc);
48 0 ProgressSpinup("post-processing");
49  
50 0 foreach my $processor (@postprocessors) {
51 0 local $LaTeXML::Post::PROCESSOR = $processor;
52 0 my @newdocs = ();
53 0 foreach my $doc (@docs) {
54 0 local $LaTeXML::Post::DOCUMENT = $doc;
55 0 ▶ if (my @nodes = grep { $_ } $processor->toProcess($doc)) { # If there are nodes to process
Branch: 1 branch
BranchTrueFalseTotal
if (my(@nodes) = grep({$_;} $processor->toProcess($doc))) { } 0 0 0
56 0 my $n = scalar(@nodes);
57 0 ▶ my $msg = join(' ', $processor->getName || '',
Branch: 1 branch
BranchTrueFalseTotal
$n > 1 ? : 0 0 0
Condition0%0/4
$processor->getName || ''
l!l
00
$doc->siteRelativeDestination || ''
l!l
00
MC/DC0%0/1
$processor->getName || ''
$processor->getName
MC/DC0%0/1
$doc->siteRelativeDestination || ''
$doc->siteRelativeDestination
Truth table0%0/2
A
A= $processor->getName
Aresult
11
00
Truth table0%0/2
A
A= $doc->siteRelativeDestination
Aresult
11
00
58 $doc->siteRelativeDestination || '',
59 ($n > 1 ? "$n to process" : 'processing'));
60 0 ProgressSpinup($msg);
61 0 push(@newdocs, $processor->process($doc, @nodes));
62 0 ProgressSpindown($msg); }
63 else {
64 0 push(@newdocs, $doc); } }
65 0 @docs = @newdocs; }
66 0 ProgressSpindown("post-processing");
67 0 return @docs; }
68  
69 ## HACK!!!
70 ## This is a copy of withState from LaTeXML::Core.pm
71 ## This should eventually be in a higher level, common class
72 ## using a common State or configuration object
73 ## in order to wrap ALL processing.
74 sub withState {
75 0 ▶ my ($self, $closure) = @_;
Subroutine withState: not called CC=1 SCAR=6.9
76 0 local $STATE = $$self{state};
77 # And, set fancy error handler for ANY die!
78 0 local $SIG{__DIE__} = \&LaTeXML::Common::Error::perl_die_handler;
79 0 local $SIG{INT} = \&LaTeXML::Common::Error::perl_interrupt_handler;
80 0 local $SIG{__WARN__} = \&LaTeXML::Common::Error::perl_warn_handler;
81 0 local $SIG{'ALRM'} = \&LaTeXML::Common::Error::perl_timeout_handler;
82 0 local $SIG{'TERM'} = \&LaTeXML::Common::Error::perl_terminate_handler;
83  
84 0 local $LaTeXML::DUAL_BRANCH = '';
85  
86 0 return &$closure($STATE); }
87  
88 sub getStatusCode {
89 0 ▶ my ($self) = @_;
Subroutine getStatusCode: not called CC=1 SCAR=6.9
90 0 return $$self{state}->getStatusCode; }
91  
92 sub getStatusMessage {
93 0 ▶ my ($self) = @_;
Subroutine getStatusMessage: not called CC=1 SCAR=6.9
94 0 return $$self{state}->getStatusMessage; }
95  
96 #======================================================================
97 # "Global" Post processing services
98 #======================================================================
99  
100 # Return a sorter appropriate for lang (if Unicode::Collate::Locale available),
101 # or an undifferentiated Unicode sorter (if only Unicode::Collate is available),
102 # or just a dumb stand-in for perl's sort
103 sub getsorter {
104 0 ▶ my ($self, $lang) = @_;
Subroutine getsorter: not called CC=4 SCAR=30.0
105 0 my $collator;
106 0 ▶ if ($collator = $$self{collatorcache}{$lang}) { }
Branch: 3 branches
BranchTrueFalseTotal
if ($collator = $self->{'collatorcache'}{$lang}) { } 0 0 0
elsif ($collator = eval { do { local $LaTeXML::IGNORE_ERRORS = 1; require 'Unicode/Collate/Locale.pm'; 'Unicode::Collate::Locale'->new('locale', $lang, 'variable', 'non-ignorable', 'upper_before_lower', 1) } }) { } 0 0 0
elsif ($collator = eval { do { local $LaTeXML::IGNORE_ERRORS = 1; require 'Unicode/Collate.pm'; 'Unicode::Collate'->new('variable', 'non-ignorable', 'upper_before_lower', 1) } }) { } 0 0 0
107 elsif ($collator = eval {
108 0 local $LaTeXML::IGNORE_ERRORS = 1;
109 0 require 'Unicode/Collate/Locale.pm';
110 0 Unicode::Collate::Locale->new(
111 locale => $lang,
112 variable => 'non-ignorable', # I think; at least space shouldn't be ignored
113 upper_before_lower => 1); }) { }
114 elsif ($collator = eval {
115 0 local $LaTeXML::IGNORE_ERRORS = 1;
116 0 require 'Unicode/Collate.pm';
117 0 Unicode::Collate->new(
118 variable => 'non-ignorable', # I think; at least space shouldn't be ignored
119 upper_before_lower => 1); }) {
120 0 Info('expected', 'Unicode::Collate::Locale', undef,
121 "No Unicode::Collate::Locale found;",
122 "using Unicode::Collate; ignoring language='$lang'"); }
123 else {
124 # Otherwise, just use primitive codepoint ordering.
125 0 $collator = LaTeXML::Post::DumbCollator->new();
126 0 Info('expected', 'Unicode::Collate::Locale', undef,
127 "No Unicode::Collate::Locale or Unicode::Collate",
128 "using perl's sort; ignoring language='$lang'"); }
129 0 $$self{collatorcache}{$lang} = $collator;
130 0 return $collator; }
131  
132 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
133 package LaTeXML::Post::DumbCollator;
134 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
135  
136 sub new {
137 0 ▶ my ($class) = @_;
Subroutine new: not called CC=1 SCAR=6.9
138 0 return bless {}, $class; }
139  
140 sub sort {
141 0 ▶ my ($self, @things) = @_;
Subroutine sort: not called CC=1 SCAR=6.9
142 0 return (sort @things); }
143  
144 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
145 package LaTeXML::Post::Processor;
146 27 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
147 27 ▶use LaTeXML::Post;
Subroutine BEGIN: called CC=1 SCAR=0.0
148 27 ▶use LaTeXML::Common::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
149 27 ▶use LaTeXML::Common::XML;
Subroutine BEGIN: called CC=1 SCAR=2.6
150 use LaTeXML::Util::Pathname;
151 use base qw(LaTeXML::Common::Object);
152  
153 # An Abstract Post Processor
154 sub new {
155 my ($class, %options) = @_;
156 my $self = bless {%options}, $class;
157 $$self{resource_directory} = $options{resource_directory};
158 $$self{resource_prefix} = $options{resource_prefix};
159 my $name = $class; $name =~ s/^LaTeXML::Post:://;
160 $$self{name} = $name;
161 return $self; }
162  
163 sub getName {
164 my ($self) = @_;
165 return $$self{name}; }
166  
167 # Return the nodes to be processed; by default the document element.
168 # This allows processors to focus on specific kinds of nodes,
169 # or to skip processing if there are none to process.
170 sub toProcess {
171 my ($self, $doc) = @_;
172 return $doc->getDocumentElement; }
173  
174 # This must be defined to do whatever processing is needed to @toprocess nodes.
175 sub process {
176 my ($self, $doc, @toprocess) = @_;
177 Fatal("misdefined", $self, $doc, "This post-processor is abstract; does not implement ->process");
178 return $doc; }
179  
180 #======================================================================
181 # Some postprocessors will want to create a bunch of "resource"s,
182 # such as generated or transformed image files, or other data files.
183 # These should return a pathname, relative to the document's destination,
184 # for storing a resource associated with $node.
185 # Will use the Post option resource_directory
186 sub desiredResourcePathname {
187 my ($self, $doc, $node, $source, $type) = @_;
188 return; }
189  
190 # Ideally this would return a pathname relative to the document
191 # but I think we've accommodated absolute ones.
192 sub generateResourcePathname {
193 my ($self, $doc, $node, $source, $type) = @_;
194 my $subdir = $$self{resource_directory} || '';
195 my $prefix = $$self{resource_prefix} || "x";
196 my $counter = join('_', "_max", $subdir, $prefix, "counter_");
197 my $n = $doc->cacheLookup($counter) || 0;
198 my $name = $prefix . ++$n;
199 $doc->cacheStore($counter, $n);
200 return pathname_make(dir => $subdir, name => $name, type => $type); }
201  
202 # Returns a two-part list of the form:
203 #
204 # [class, classoptions, oldstyle], [package1,package1options], [package2,package2options], ...
205 #
206 # Where there first element is always the *class* (if none, "article" returned as a default)
207 # And all following elements are *packages*
208 #
209 sub find_documentclass_and_packages {
210 my ($self, $doc) = @_;
211 my ($class, $classoptions, $oldstyle, @packages);
212 foreach my $pi ($doc->findnodes(".//processing-instruction('latexml')")) {
213 my $data = $pi->textContent;
214 my $entry = {};
215 while ($data =~ s/\s*([\w\-\_]*)=([\"\'])(.*?)\2//) {
216 $$entry{$1} = $3; }
217 if ($$entry{class}) {
218 $class = $$entry{class};
219 $classoptions = $$entry{options} || 'onecolumn';
220 $oldstyle = $$entry{oldstyle}; }
221 elsif ($$entry{package}) {
222 my @p = grep { $_; } split(/\s*,\s*/, $$entry{package});
223 foreach my $package (@p) {
224 push(@packages, [$package, $$entry{options} || '']); } } }
225 if (!$class) {
226 Warn('expected', 'class', undef, "No document class found; using article");
227 $class = 'article'; }
228 return ([$class, $classoptions, $oldstyle], @packages); }
229  
230 sub find_preambles {
231 my ($self, $doc) = @_;
232 my @preambles = ();
233 foreach my $pi ($doc->findnodes(".//processing-instruction('latexml')")) {
234 my $data = $pi->textContent;
235 while ($data =~ s/\s*([\w\-\_]*)=([\"\'])(.*?)\2//) {
236 if ($1 eq 'preamble') {
237 push(@preambles, $3); } } }
238 return join("\n", @preambles); }
239  
240 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
241 package LaTeXML::Post::MathProcessor;
242 use strict;
243 use LaTeXML::Post;
244 use LaTeXML::Common::Error;
245 use base qw(LaTeXML::Post::Processor);
246 use LaTeXML::Common::XML;
247  
248 # This is an abstract class; A complete MathProcessor will need to define:
249 # $self->convertNode($doc,$xmath)
250 # to generate the converted math node
251 # $self->combineParallel($doc,$math,$primary,@secondaries)
252 # to combine the $primary (the result of $self's conversion of $math)
253 # with the results of other math processors to create the
254 # parallel markup appropriate for this processor's markup.
255 # $self->rawIDSuffix returns a short string to append to id's for nodes
256 # using this markup.
257  
258 # Top level processing finds and converts all top-level math nodes.
259 # Any nested mathnodes would only appear within ltx:XMText;
260 # postprocessors must handle nested math as appropriate (but see convertXMTextContent)
261 # Invokes preprocess on each before doing the conversion in case
262 # analysis is needed.
263 sub toProcess {
264 my ($self, $doc) = @_;
265 return $doc->findnodes('//ltx:Math[not(ancestor::ltx:Math)]'); }
266  
267 sub process {
268 my ($self, $doc, @maths) = @_;
269 local $LaTeXML::Post::MATHPROCESSOR = $self;
270 $doc->markXMNodeVisibility;
271 $self->preprocess($doc, @maths);
272 if ($$self{parallel}) {
273 my @secondaries = @{ $$self{secondary_processors} };
274 # What's the right test for when cross-referencing should be done?
275 # For now: only when the primary and some secondary can cross-ref
276 # (otherwise, end up with peculiar structures?)
277 my ($proc1, @ignore) = grep { $_->can('addCrossref') } @secondaries;
278 if ($self->can('addCrossref') && $proc1) {
279 $$self{crossreferencing} = 1; # We'll need ID's!
280 $$proc1{crossreferencing} = 1; }
281 foreach my $proc (@secondaries) {
282 local $LaTeXML::Post::MATHPROCESSOR = $proc;
283 $proc->preprocess($doc, @maths); } }
284 # Re-Fetch the math nodes, in case preprocessing has messed them up!!!
285 @maths = $self->toProcess($doc);
286  
287 ## Do in reverse, since (in LaTeXML) we allow math nested within text within math.
288 ## So, we want to converted any nested expressions first, so they get carried along
289 ## with the outer ones.
290 my $n = 0;
291 foreach my $math (reverse(@maths)) {
292 # If parent is MathBranch, which branch number is it?
293 # (note: the MathBranch will be in a ltx:MathFork, with a ltx:Math being 1st child)
294 my @preceding = $doc->findnodes("parent::ltx:MathBranch/preceding-sibling::*", $math);
295 local $LaTeXML::Post::MathProcessor::FORK = scalar(@preceding);
296 $self->processNode($doc, $math);
297 $n++; }
298  
299 # Experimentally, cross reference ??? (or clearer name?)
300 if ($$self{parallel}) {
301 # There could be various strategies when there are more than 2 parallel conversions,
302 # eg a cycle or something....
303 # Here, we simply take the first two processors that know how to addCrossref
304 # and connect their nodes to each other.
305 my ($proc1, $proc2, @ignore)
306 = grep { $_->can('addCrossref') } $self, @{ $$self{secondary_processors} };
307 if ($proc1 && $proc2) {
308 # First, prepare a list of all Math id's, in document order, to simplify crossreferencing
309 my $ids = {};
310 my $pos = 0;
311 foreach my $n ($doc->findnodes('descendant-or-self::ltx:Math/descendant::*[@xml:id]')) {
312 $$ids{ $n->getAttribute('xml:id') } = $pos++; }
313 $$proc1{crossreferencing_ids} = $ids;
314 $$proc2{crossreferencing_ids} = $ids;
315 # Now do cross referencing
316 $proc1->addCrossrefs($doc, $proc2);
317 $proc2->addCrossrefs($doc, $proc1); } }
318 NoteLog("converted $n Maths");
319 return $doc; }
320  
321 # Make THIS MathProcessor the primary branch (of whatever parallel markup it supports),
322 # and make all of the @moreprocessors be secondary ones.
323 sub setParallel {
324 my ($self, @moreprocessors) = @_;
325 if (@moreprocessors) {
326 $$self{parallel} = 1;
327 map { $$_{is_secondary} = 1 } @moreprocessors; # Mark the others as secondary
328 $$self{secondary_processors} = [@moreprocessors];
329 $$self{name} .= '[w/' . join('+', map { $_->getName } @moreprocessors) . ']'; }
330 else {
331 $$self{parallel} = 0; }
332 return; }
333  
334 # Optional; if you want to do anything before translation
335 sub preprocess {
336 my ($self, $doc, @nodes) = @_;
337 return; }
338  
339 # $self->processNode($doc,$mathnode) is the top-level conversion
340 # It converts the XMath within $mathnode, and adds it to the $mathnode,
341 # This invokes $self->convertNode($doc,$xmath) to get the conversion.
342 sub processNode {
343 my ($self, $doc, $math) = @_;
344 my $xmath = $doc->findnode('ltx:XMath', $math);
345 return unless $xmath; # Nothing to convert if there's no XMath ... !
346 local $LaTeXML::Post::MATHPROCESSOR = $self;
347 my $conversion;
348 # XMath will be removed (LATER!), but mark its ids as reusable.
349 $doc->preremoveNodes($xmath);
350 if ($$self{parallel}) {
351 my $primary = $self->convertNode($doc, $xmath);
352 my @secondaries = ();
353 foreach my $proc (@{ $$self{secondary_processors} }) {
354 local $LaTeXML::Post::MATHPROCESSOR = $proc;
355 my $secondary = $proc->convertNode($doc, $xmath);
356 # IF it is (first) image, copy image attributes to ltx:Math ???
357 $self->maybeSetMathImage($math, $secondary);
358 push(@secondaries, $secondary); }
359 $conversion = $self->combineParallel($doc, $xmath, $primary, @secondaries); }
360 else {
361 $conversion = $self->convertNode($doc, $xmath);
362 $self->maybeSetMathImage($math, $conversion); }
363 # we now REMOVE the ltx:XMath from the ltx:Math, and whitespace
364 # (if there's an XMath PostProcessing module, it will add it back, with appropriate id's)
365 if (my $xml = $$conversion{xml}) {
366 $$conversion{xml} = $self->outerWrapper($doc, $xmath, $xml); }
367 $doc->removeNodes($xmath);
368 # NOTE: Unless XMath is the primary, (preserving the XMath, w/no IDSuffix)
369 # we've got to remove the id's from the XMath, since the primary will get same id's
370 # and (some versions) of libxml2 complain!
371 if ($$conversion{mimetype} && ($$conversion{mimetype} ne 'application/x-latexml')) {
372 map { $_->removeAttribute('xml:id') }
373 $doc->findnodes('descendant-or-self::*[@xml:id]', $xmath); }
374 $doc->removeBlankNodes($math);
375 if (my $new = $$conversion{xml}) {
376 $doc->addNodes($math, $new); }
377 # else ?
378 return; }
379  
380 sub maybeSetMathImage {
381 my ($self, $math, $conversion) = @_;
382 if ((($$conversion{mimetype} || '') =~ /^image\//) # Got an image?
383 && !$math->getAttribute('imagesrc')) { # and it's the first one
384 if (my $src = $$conversion{src}) {
385 $math->setAttribute(imagesrc => $src);
386 $math->setAttribute(imagewidth => $$conversion{width});
387 $math->setAttribute(imageheight => $$conversion{height});
388 $math->setAttribute(imagedepth => $$conversion{depth}); } }
389 return; }
390  
391 # NOTE: Sort out how parallel & outerWrapper should work.
392 # It probably ought to be that if the conversion is being embedded in
393 # something from another namespace, it needs the wrapper.
394 # ie. when mixing parallel markups, NOT just at the top level, although certainly there too.
395 #
396 # This should wrap the resulting conversion with m:math or om:OMA or whatever appropriate?
397 sub outerWrapper {
398 my ($self, $doc, $xmath, $conversion) = @_;
399 return $conversion; }
400  
401 # This should proably be from the core of the current ->processNode
402 sub convertNode {
403 my ($self, $doc, $node) = @_;
404 Fatal('misdefined', (ref $self), undef,
405 "Abstract package: math conversion has not been defined for this MathProcessor");
406 return; }
407  
408 # This should be implemented by potential Primaries
409 # Maybe the caller of this should check the namespaces, and call wrapper if needed?
410 sub combineParallel {
411 my ($self, $doc, $xmath, $primary, @secondaries) = @_;
412 Error('misdefined', (ref $self), undef,
413 "Abstract package: combining parallel markup has not been defined for this MathProcessor",
414 "dropping the extra markup from: " . join(',', map { $$_{processor} } @secondaries));
415 return $primary; }
416  
417 # A helper for converting XMText
418 # ltx:XMText escapes back to general ltx markup; the only element within XMath that does.
419 # BUT it can contain nested ltx:Math!
420 # When converting to (potentially parallel markup, coarse-grained),
421 # the non-math needs to be duplicated, but with the ID's modified,
422 # AND the nested math needs to be converted to ONLY the current target's markup
423 # NOT parallel within each nested math, although it should still be cross-referencable to others!
424 # moreover, the math will need the outerWrapper.
425 my $NBSP = pack('U', 0xA0); # CONSTANT
426  
427 sub convertXMTextContent {
428 my ($self, $doc, $convertspaces, @nodes) = @_;
429 my @result = ();
430 foreach my $node (@nodes) {
431 if ($node->nodeType == XML_TEXT_NODE) {
432 my $string = $node->textContent;
433 if ($convertspaces) {
434 $string =~ s/^\s+/$NBSP/; $string =~ s/\s+$/$NBSP/; }
435 push(@result, $string); }
436 else {
437 my $tag = $doc->getQName($node);
438 if ($tag eq 'ltx:XMath') {
439 my $conversion = $self->convertNode($doc, $node);
440 my $xml = $$conversion{xml};
441 # And if no xml ????
442 push(@result, $self->outerWrapper($doc, $node, $xml)); }
443 else {
444 my %attr = ();
445 foreach my $attr ($node->attributes) {
446 my $atype = $attr->nodeType;
447 if ($atype == XML_ATTRIBUTE_NODE) {
448 my $key = $attr->nodeName;
449 my $value = $attr->getValue;
450 if ($key =~ /^_/) { } # don't copy internal attributes ???
451 elsif ($key eq 'xml:id') { } # ignore; we'll handle fragid???
452 elsif ($key eq 'fragid') {
453 my $id = $doc->uniquifyID($value, $self->IDSuffix);
454 $attr{'xml:id'} = $id; }
455 else {
456 $attr{$key} = $attr->value; } } }
457 # Probably should invoke associateNode ???
458 push(@result,
459 [$tag, {%attr}, $self->convertXMTextContent($doc, $convertspaces, $node->childNodes)]); } } }
460 return @result; }
461  
462 # When converting an XMath node (with an id) to some other format,
463 # we will generate an id for the new node.
464 # This method returns a suffix to be added to the XMath id.
465 # The primary format gets the id's unchanged, but secondary ones get a suffix (eg. ".pmml")
466 sub IDSuffix {
467 my ($self) = @_;
468 return ($$self{is_secondary} ? $self->rawIDSuffix : ''); }
469  
470 sub rawIDSuffix {
471 return ''; }
472  
473 # In order to do cross-referencing betweeen formats, and to relate semantic/presentation
474 # information to content/presentation nodes (resp), we want to associate each
475 # generated node (MathML, OpenMath,...) with a "source" XMath node "responsible" for it's generation.
476 # This is often the "current" XMath node that was being converted, but sometimes
477 # * the containing XMDual (which makes more sense when we've generated a "container")
478 # * the containing XMDual's semantic operator (makes more sense when we're generating
479 # tokens that are only visible from the presentation branch)
480 sub associateNode {
481 my ($self, $node, $currentnode, $noxref) = @_;
482 my $r = ref $node;
483 return unless $currentnode && $r && ($r eq 'ARRAY' || $r eq 'XML::LibXML::Element');
484 my $document = $LaTeXML::Post::DOCUMENT;
485 # Check if already associated with a source node
486 my $isarray = ref $node eq 'ARRAY';
487 # What kind of branch are we generating?
488 my $ispresentation = $self->rawIDSuffix eq '.pmml'; # TEMPORARY HACK: BAAAAD method!
489 my $iscontainer = 0;
490 my $container;
491 if ($isarray) {
492 return if $$node[1]{'_sourced'};
493 $$node[1]{'_sourced'} = 1;
494 my ($tag, $attr, @children) = @$node;
495 $iscontainer = grep { ref $_ } @children; }
496 else {
497 return if $node->getAttribute('_sourced');
498 $node->setAttribute('_sourced' => 1);
499 $iscontainer = scalar(element_nodes($node)); }
500 my $sourcenode = $currentnode;
501 # If the current node is declared, use it (but meaning is overridden)
502 if ($currentnode->getAttribute('decl_id')) { }
503 # If the generated node is a "container" (non-token!), use the containing XMDual as source
504 elsif ($iscontainer) {
505 my $sid = $sourcenode->getAttribute('xml:id');
506 # But ONLY if that XMDual is the "direct" parent, or is parent of XRef that points to $current
507 if ($container = $document->findnode('parent::ltx:XMDual[1]', $sourcenode)
508 || ($sid &&
509 $document->findnode("ancestor-or-self::ltx:XMDual[ltx:XMRef[\@idref='$sid']][1]",
510 $sourcenode))) {
511 $sourcenode = $container; } }
512 # Parent App w/decl_id or meaning is source, unless current node has decl_id (but ignore meaning)
513 elsif ($container = $document->findnode('ancestor::ltx:XMApp[@decl_id or @meaning][1]', $sourcenode)) {
514 $sourcenode = $container; }
515 # If the current node is appropriately visible, use it.
516 elsif ($currentnode->getAttribute(($ispresentation ? '_cvis' : '_pvis'))) { }
517 # Else (current node isn't visible); try to find content OPERATOR
518 elsif ($container = $document->findnode('ancestor-or-self::ltx:XMDual[1]', $sourcenode)) {
519 my ($op) = element_nodes($container);
520 my $q = $document->getQName($op) || 'unknown';
521 if ($container->hasAttribute('decl_id')) {
522 $op = undef; }
523 elsif ($q eq 'ltx:XMTok') { }
524 elsif ($q eq 'ltx:XMApp') {
525 while (($q eq 'ltx:XMApp') && !$op->hasAttribute('meaning')) {
526 ($op) = element_nodes($op);
527 $q = $document->getQName($op) || 'unknown'; } } # get "real" operator
528 if ($q eq 'ltx:XMRef') {
529 $op = $document->realizeXMNode($op); }
530 # Be a bit fuzzy about whether something is "visible"
531 if ($op && !($op->getAttribute('_pvis')
532 && (($op->getAttribute('thickness') || '<anything>') ne '0pt'))) {
533 $sourcenode = $op; }
534 else {
535 $sourcenode = $container; } }
536 # If we're intending to cross-reference, then source & generated nodes will need ID's
537 if ($$self{crossreferencing}) {
538 if (!$noxref && !$sourcenode->getAttribute('fragid')) { # If no ID, but need one
539 $document->generateNodeID($sourcenode, '', 1); } # but the ID is reusable
540 if (my $sourceid = $sourcenode->getAttribute('fragid')) { # If source has ID
541 my $nodeid = $currentnode->getAttribute('fragid') || $sourceid;
542 my $id = $document->uniquifyID($nodeid, $self->IDSuffix);
543 if ($isarray) {
544 $$node[1]{'xml:id'} = $id; }
545 else {
546 $node->setAttribute('xml:id' => $id); }
547 push(@{ $$self{convertedIDs}{$sourceid} }, $id) unless $noxref; } }
548 $self->associateNodeHook($node, $sourcenode, $noxref);
549 if ($isarray) { # Array represented
550 map { $self->associateNode($_, $currentnode, $noxref) } @$node[2 .. $#$node]; }
551 else { # LibXML node
552 map { $self->associateNode($_, $currentnode, $noxref) } element_nodes($node); }
553 return; }
554  
555 # Customization hook for adding other attributes to the generated math nodes.
556 sub associateNodeHook {
557 my ($self, $node, $sourcenode, $noxref) = @_;
558 return; }
559  
560 sub shownode {
561 my ($node, $level) = @_;
562 $level = 0 unless defined $level;
563 my $ref = ref $node;
564 if ($ref eq 'ARRAY') {
565 my ($tag, $attr, @children) = @$node;
566 return "\n" . (' ' x $level)
567 . '[' . $tag . ',{' . join(',', map { $_ . '=>' . ($$attr{$_} || '') } sort keys %$attr) . '},'
568 . join(',', map { shownode($_, $level + 1) } @children) . ']'; }
569 elsif ($ref =~ /^XML/) {
570 return $node->toString; }
571 else {
572 return "$node"; } }
573  
574 # Add backref linkages (eg. xref) onto the nodes that $self created (converted from XMath)
575 # to reference those that $otherprocessor created.
576 # NOTE: Subclass MUST define addCrossref($node,$xref_id) to add the
577 # id of the "Other Interesting Node" to the (array represented) xml $node
578 # in whatever fashion the markup for that processor uses.
579 #
580 # This may be another useful place to add a hook?
581 # It would provide the list of cross-refenced nodes in document order
582 # This would allow deciding whether or not to copy foreign attributes or other interesting things
583 sub addCrossrefs {
584 my ($self, $doc, $otherprocessor) = @_;
585 my $selfs_map = $$self{convertedIDs};
586 my $others_map = $$otherprocessor{convertedIDs};
587 my $xrefids = $$self{crossreferencing_ids};
588 my $backref = {};
589 foreach my $id (keys %$selfs_map) {
590 foreach my $t (@{ $$selfs_map{$id} }) {
591 $$backref{$t} = $id; } }
592 foreach my $xid (keys %$selfs_map) { # For each XMath id that $self converted
593 my $other_ids = $$others_map{$xid}; # the ids where $xid ended up in $other processor
594 if (!$other_ids) {
595 # But If this node didn't directly end up in $other, try to find alternative
596 # Typically happens when a "visible" node doesn't have visible representation in other format!
597 # So, see if an ancestor got mapped.
598 if (my $mapped = $$selfs_map{$xid}) {
599 foreach my $mid (@$mapped) {
600 if (my $node = $doc->findNodeByID($mid)) {
601 my ($parent, $pid, $xpid) = ($node, undef, undef);
602 while (($parent = $parent->parentNode)
603 && ($parent->nodeType == XML_ELEMENT_NODE) # in case we hit Document
604 && (!($pid = $parent->getAttribute('xml:id'))
605 || !($xpid = $$backref{$pid})
606 || !$$others_map{$xpid})) { }
607 if ($xpid) {
608 $other_ids = $$others_map{$xpid}; } } } } }
609 if ($other_ids) { # Hopefully, we've got the targets, now
610 my $xref_id = $$other_ids[0];
611 if (scalar(@$other_ids) > 1) { # Find 1st in document order! (order is cached)
612 ($xref_id) = sort { $$xrefids{$a} <=> $$xrefids{$b} } @$other_ids; }
613 foreach my $id (@{ $$selfs_map{$xid} }) { # look at each node $self created from $xid
614 if (my $node = $doc->findNodeByID($id)) { # If we find a node,
615 $self->addCrossref($node, $xref_id); } } } # } # add a crossref from it to $others's nod
616 else {
617 } }
618 return; }
619  
620 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
621  
622 package LaTeXML::Post::Document;
623 use strict;
624 use LaTeXML::Common::XML;
625 use LaTeXML::Util::Pathname;
626 use LaTeXML::Util::Radix;
627 use DB_File;
628 use Unicode::Normalize;
629 use LaTeXML::Post; # to import error handling...
630 use LaTeXML::Common::Error;
631 use base qw(LaTeXML::Common::Object);
632 our $NSURI = "http://dlmf.nist.gov/LaTeXML";
633 our $XPATH = LaTeXML::Common::XML::XPath->new(ltx => $NSURI);
634  
635 # Useful options:
636 # destination = the ultimate destination file for this document to be written.
637 # destinationDirectory = the directory it will be stored in (derived from $destination)
638 # siteDirectory = the root directory of where the entire site will be contained
639 # namespaces = a hash of namespace prefix => namespace uri
640 # namespaceURIs = reverse hash of above.
641 # nocache = a boolean, disables storing of permanent LaTeXML.cache
642 # the cache is used to remember things like image conversions from previous runs.
643 # searchpaths = array of paths to search for other resources
644 # Note that these may not be LaTeXML documents (maybe html or ....)
645 sub new {
646 my ($class, $xmldoc, %options) = @_;
647 my $self = $class->new_internal($xmldoc, %options);
648 $self->setDocument_internal($xmldoc);
649 return $self; }
650  
651 sub new_internal {
652 my ($class, $xmldoc, %options) = @_;
653 my %data = ();
654 if (ref $class) { # Cloning!
655 map { $data{$_} = $$class{$_} } keys %$class;
656 $class = ref $class; }
657 map { $data{$_} = $options{$_} } keys %options; # These override.
658 if ((defined $options{destination}) && (!defined $options{destinationDirectory})) {
659 my ($dir, $name, $ext) = pathname_split($data{destination});
660 $data{destinationDirectory} = $dir || '.'; }
661 # Check consistency of siteDirectory (providing there's a destinationDirectory)
662 if ($data{destinationDirectory}) {
663 if ($data{siteDirectory}) {
664 Fatal('unexpected', $data{destinationDirectory}, undef,
665 "The destination directory ($data{destinationDirectory})"
666 . " must be within the siteDirectory ($data{siteDirectory})")
667 unless pathname_is_contained($data{destinationDirectory}, $data{siteDirectory}); }
668 else {
669 $data{siteDirectory} = $data{destinationDirectory}; } }
670 # Start, at least, with our own namespaces.
671 $data{namespaces} = { ltx => $NSURI } unless $data{namespaces};
672 $data{namespaceURIs} = { $NSURI => 'ltx' } unless $data{namespaceURIs};
673 $data{idcache} = {};
674 $data{idcache_reusable} = {};
675 $data{idcache_reserve} = {};
676  
677 my $self = bless {%data}, $class;
678 return $self; }
679  
680 sub newFromFile {
681 my ($class, $source, %options) = @_;
682 my $path = (ref $class
683 ? pathname_find($source, paths => $$class{searchpaths})
684 : $source);
685 if (!$path) {
686 Error('missing_file', $source, $class, "No XML document '$source' found",
687 (ref $class ? "search paths are " . join(', ', @{ $$class{searchpaths} }) : ()));
688 return; }
689 $options{source} = $path;
690 if (!$options{sourceDirectory}) {
691 my ($dir, $name, $ext) = pathname_split($path);
692 $options{sourceDirectory} = $dir || '.'; }
693 my $doc = $class->new(LaTeXML::Common::XML::Parser->new()->parseFile($path), %options);
694 $doc->validate if $$doc{validate};
695 return $doc; }
696  
697 sub newFromString {
698 my ($class, $string, %options) = @_;
699 $options{sourceDirectory} = '.' unless $options{sourceDirectory};
700 my $doc = $class->new(LaTeXML::Common::XML::Parser->new()->parseString($string), %options);
701 $doc->validate if $$doc{validate};
702 return $doc; }
703  
704 sub newFromSTDIN {
705 my ($class, %options) = @_;
706 my $string;
707 { local $/ = undef; $string = <>; }
708 $options{sourceDirectory} = '.' unless $options{sourceDirectory};
709 my $doc = $class->new(LaTeXML::Common::XML::Parser->new()->parseString($string), %options);
710 $doc->validate if $$doc{validate};
711 return $doc; }
712  
713 #======================================================================
714  
715 # This is for creating essentially "sub documents"
716 # that are in some sense children of $self, possibly removed or cloned from it.
717 # And they are presumably LaTeXML documents
718 sub newDocument {
719 my ($self, $root, %options) = @_;
720 my $clone_suffix = $options{clone_suffix};
721 delete $options{clone_suffix};
722 my $doc = $self->new_internal(undef, %options);
723 $doc->setDocument_internal($root, clone_suffix => $clone_suffix);
724  
725 if (my $root_id = $self->getDocumentElement->getAttribute('xml:id')) {
726 $$doc{split_from_id} = $root_id; }
727  
728 # Copy any processing instructions.
729 foreach my $pi ($self->findnodes(".//processing-instruction('latexml')")) {
730 $doc->getDocument->appendChild($pi->cloneNode); }
731  
732 # And any resource elements
733 if (my @resources = $self->findnodes("descendant::ltx:resource")) {
734 $doc->addNodes($doc->getDocumentElement, @resources); } # cloning, as needed...
735  
736 # If new document has no date, try to add one
737 $doc->addDate($self);
738  
739 # And copy class from the top-level document; This is risky...
740 # We want to preserve global document style information
741 # But some may refer specifically to the document, and NOT to the parts?
742 if (my $class = $self->getDocumentElement->getAttribute('class')) {
743 my $root = $doc->getDocumentElement;
744 my $oclass = $root->getAttribute('class');
745 $root->setAttribute(class => ($oclass ? $oclass . ' ' . $class : $class)); }
746  
747 # Finally, return the new document.
748 return $doc; }
749  
750 sub setDocument_internal {
751 my ($self, $root, %options) = @_;
752 # Build the document's XML
753 my $roottype = ref $root;
754 if ($roottype eq 'LaTeXML::Core::Document') {
755 $root = $root->getDocument;
756 $roottype = ref $root; }
757 if (my $clone_suffix = $options{clone_suffix}) {
758 if ($roottype eq 'XML::LibXML::Document') {
759 Fatal('internal', 'unimplemented', undef,
760 "Have not yet implemented cloning for entire documents"); }
761 # Just make a clone, and then insert that.
762 $root = $self->cloneNode($root, $clone_suffix); }
763  
764 if ($roottype eq 'XML::LibXML::Document') {
765 $$self{document} = $root;
766 foreach my $node ($self->findnodes("//*[\@xml:id]")) { # Now record all ID's
767 $$self{idcache}{ $node->getAttribute('xml:id') } = $node; }
768 # Fetch any additional namespaces from the root
769  
770 if (my $docroot = $root->documentElement) {
771 foreach my $ns ($docroot->getNamespaces) {
772 my ($prefix, $uri) = ($ns->getLocalName, $ns->getData);
773 if ($prefix) {
774 $$self{namespaces}{$prefix} = $uri unless $$self{namespaces}{$prefix};
775 $$self{namespaceURIs}{$uri} = $prefix unless $$self{namespaceURIs}{$uri}; } } }
776  
777 # Extract data from latexml's ProcessingInstructions
778 # I'd like to provide structured access to the PI's for those modules that need them,
779 # but it isn't quite clear what that api should be.
780 $$self{processingInstructions} =
781 [map { $_->textContent } $XPATH->findnodes('.//processing-instruction("latexml")', $root)];
782 # Combine specified paths with any from the PI's
783 my @paths = ();
784 @paths = @{ $$self{searchpaths} } if $$self{searchpaths};
785 foreach my $pi (@{ $$self{processingInstructions} }) {
786 if ($pi =~ /^\s*searchpaths\s*=\s*([\"\'])(.*?)\1\s*$/) {
787 push(@paths, split(',', $2)); } }
788 ### No, this ultimately can be the xml source, which may be the destination;
789 ### adding this gets the wrong graphics (already processed!)
790 ### push(@paths, pathname_absolute($$self{sourceDirectory})) if $$self{sourceDirectory};
791 # But do add cwd after the document specified paths.
792 $$self{searchpaths} = [@paths, '.']; }
793 elsif ($roottype eq 'XML::LibXML::Element') {
794 $$self{document} = XML::LibXML::Document->new("1.0", "UTF-8");
795 # Assume we've got any namespaces already ?
796 if (my $parent = $self->findnode('ancestor::*[@id][1]', $root)) {
797 $$self{parent_id} = $parent->getAttribute('xml:id'); }
798 # if no cloning requested, we can just plug the node directly in.
799 # (otherwise, we should use addNodes?)
800 # Seems that only importNode (NOT adopt) works correctly,
801 # PROVIDED we also set the namespace.
802 $$self{document}->setDocumentElement($$self{document}->importNode($root));
803 # $$self{document}->documentElement->setNamespace($root->namespaceURI, $root->prefix, 1);
804 $root->setNamespace($root->namespaceURI, $root->prefix, 1);
805 foreach my $node ($self->findnodes("//*[\@xml:id]")) { # Now record all ID's
806 $$self{idcache}{ $node->getAttribute('xml:id') } = $node; } }
807 elsif ($roottype eq 'ARRAY') {
808 $$self{document} = XML::LibXML::Document->new("1.0", "UTF-8");
809 my ($tag, $attributes, @children) = @$root;
810 my ($prefix, $localname) = $tag =~ /^(.*):(.*)$/;
811 my $nsuri = $$self{namespaces}{$prefix};
812 my $node = $$self{document}->createElementNS($nsuri, $localname);
813 $$self{document}->setDocumentElement($node);
814 map { $$attributes{$_} && $node->setAttribute($_ => $$attributes{$_}) } keys %$attributes
815 if $attributes;
816  
817 if (my $id = $$attributes{'xml:id'}) {
818 $self->recordID($id => $node); }
819 $self->addNodes($node, @children); }
820 else {
821 Fatal('unexpected', $root, undef, "Dont know how to use '$root' as document element"); }
822 return $self; }
823  
824 our @MonthNames = (qw( January February March April May June
825 July August September October November December));
826  
827 sub addDate {
828 my ($self, $fromdoc) = @_;
829 if (!$self->findnodes('ltx:date', $self->getDocumentElement)) {
830 my @dates;
831 # $fromdoc's document has some, so copy them.
832 if ($fromdoc && (@dates = $fromdoc->findnodes('ltx:date', $fromdoc->getDocumentElement))) {
833 $self->addNodes($self->getDocumentElement, @dates); }
834 else {
835 my ($sec, $min, $hour, $mday, $mon, $year) = localtime(time());
836 $self->addNodes($self->getDocumentElement,
837 ['ltx:date', { role => 'creation' },
838 $MonthNames[$mon] . " " . $mday . ", " . (1900 + $year)]); } }
839 return; }
840  
841 #======================================================================
842 # Accessors
843  
844 sub getDocument {
845 my ($self) = @_;
846 return $$self{document}; }
847  
848 sub getDocumentElement {
849 my ($self) = @_;
850 return $$self{document}->documentElement; }
851  
852 sub getSource {
853 my ($self) = @_;
854 return $$self{source}; }
855  
856 sub getSourceDirectory {
857 my ($self) = @_;
858 return $$self{sourceDirectory} || '.'; }
859  
860 sub getSearchPaths {
861 my ($self) = @_;
862 return @{ $$self{searchpaths} }; }
863  
864 sub getDestination {
865 my ($self) = @_;
866 return $$self{destination}; }
867  
868 sub getDestinationDirectory {
869 my ($self) = @_;
870 return $$self{destinationDirectory}; }
871  
872 sub getSiteDirectory {
873 my ($self) = @_;
874 return $$self{siteDirectory}; }
875  
876 # Given an absolute pathname in the document destination directory,
877 # return the corresponding pathname relative to the site directory (they maybe different!).
878 sub siteRelativePathname {
879 my ($self, $pathname) = @_;
880 return (defined $pathname ? pathname_relative($pathname, $$self{siteDirectory}) : undef); }
881  
882 sub siteRelativeDestination {
883 my ($self) = @_;
884 return (defined $$self{destination}
885 ? pathname_relative($$self{destination}, $$self{siteDirectory})
886 : undef); }
887  
888 sub getParentDocument {
889 my ($self) = @_;
890 return $$self{parentDocument}; }
891  
892 sub getAncestorDocument {
893 my ($self) = @_;
894 my ($doc, $d) = $self;
895 while ($d = $$doc{parentDocument}) {
896 $doc = $d; }
897 return $doc; }
898  
899 sub toString {
900 my ($self) = @_;
901 return $$self{document}->toString(1); }
902  
903 sub getDestinationExtension {
904 my ($self) = @_;
905 return ($$self{destination} =~ /\.([^\.\/]*)$/ ? $1 : undef); }
906  
907 sub checkDestination {
908 my ($self, $reldest) = @_;
909 # make absolute (if not already absolute), hopefully in destination directory.
910 my $dest = pathname_absolute($reldest, $self->getDestinationDirectory);
911 if (my $destdir = pathname_directory($dest)) {
912 pathname_mkdir($destdir)
913 or return Fatal("I/O", $destdir, undef,
914 "Could not create directory $destdir for $reldest: $!"); }
915 return $dest; }
916  
917 sub stringify {
918 my ($self) = @_;
919 return 'Post::Document[' . $self->siteRelativeDestination . ']'; }
920  
921 sub getLocator {
922 my ($self) = @_;
923 return $$self{source}; }
924  
925 #======================================================================
926 sub validate {
927 my ($self) = @_;
928 # Check for a RelaxNGSchema PI
929 my $schema;
930 foreach my $pi (@{ $$self{processingInstructions} }) {
931 if ($pi =~ /^\s*RelaxNGSchema\s*=\s*([\"\'])(.*?)\1\s*$/) {
932 $schema = $2; } }
933 if ($schema) { # Validate using rng
934 my $rng = LaTeXML::Common::XML::RelaxNG->new($schema, searchpaths => [$self->getSearchPaths]);
935 Error('I/O', $schema, undef, "Failed to load RelaxNG schema $schema" . "Response was: $@")
936 unless $rng;
937 my $v = eval {
938 local $LaTeXML::IGNORE_ERRORS = 1;
939 $rng->validate($$self{document}); };
940 Error("malformed", 'document', undef,
941 "Document fails RelaxNG validation (" . $schema . ")",
942 "Validation reports: " . $@,
943 "(Jing may provide a more precise report; https://relaxng.org/jclark/jing.html)")
944 if $@ || !defined $v; }
945 elsif (my $decldtd = $$self{document}->internalSubset) { # Else look for DTD Declaration
946 my $dtd = XML::LibXML::Dtd->new($decldtd->publicId, $decldtd->systemId);
947 if (!$dtd) {
948 Error("I/O", $decldtd->publicId, undef,
949 "Failed to load DTD " . $decldtd->publicId . " at " . $decldtd->systemId,
950 "skipping validation"); }
951 else {
952 my $v = eval {
953 local $LaTeXML::IGNORE_ERRORS = 1;
954 $$self{document}->validate($dtd); };
955 Error("malformed", 'document', undef,
956 "Document failed DTD validation (" . $decldtd->systemId . ")",
957 "Validation reports: " . $@) if $@ || !defined $v; } }
958 else { # Nothing found to validate with
959 Warn("expected", 'schema', undef,
960 "No Schema or DTD found for this document"); }
961 return; }
962  
963 sub idcheck {
964 my ($self) = @_;
965 my %idcache = ();
966 my %dups = ();
967 my %missing = ();
968 foreach my $node ($self->findnodes("//*[\@xml:id]")) {
969 my $id = $node->getAttribute('xml:id');
970 $dups{$id} = 1 if $idcache{$id};
971 $idcache{$id} = 1; }
972 foreach my $id (keys %{ $$self{idcache} }) {
973 $missing{$id} = 1 unless $idcache{$id}; }
974 Warn("unexpected", 'ids', undef,
975 "IDs were duplicated in cache for " . $self->siteRelativeDestination,
976 join(',', keys %dups))
977 if keys %dups;
978 Warn("expected", 'ids', undef, "IDs were cached for " . $self->siteRelativeDestination
979 . " but not in document",
980 join(',', keys %missing))
981 if keys %missing;
982 return; }
983  
984 #======================================================================
985 sub findnodes {
986 my ($self, $path, $node) = @_;
987 return $XPATH->findnodes($path, $node || $$self{document}); }
988  
989 # Similar but returns only 1st node
990 sub findnode {
991 my ($self, $path, $node) = @_;
992 my ($first) = $XPATH->findnodes($path, $node || $$self{document});
993 return $first; }
994  
995 sub findvalue {
996 my ($self, $path, $node) = @_;
997 return $XPATH->findvalue($path, $node || $$self{document}); }
998  
999 sub addNamespace {
1000 my ($self, $nsuri, $prefix) = @_;
1001 if (!$$self{namespaces}{$prefix} || ($$self{namespaces}{$prefix} ne $nsuri)
1002 || (($self->getDocumentElement->lookupNamespacePrefix($nsuri) || '') ne $prefix)) {
1003 $$self{namespaces}{$prefix} = $nsuri;
1004 $$self{namespaceURIs}{$nsuri} = $prefix;
1005 $XPATH->registerNS($prefix => $nsuri);
1006 $self->getDocumentElement->setNamespace($nsuri, $prefix, 0); }
1007 return; }
1008  
1009 use Carp;
1010  
1011 sub getQName {
1012 my ($self, $node) = @_;
1013 if (ref $node eq 'ARRAY') {
1014 return $$node[0]; }
1015 elsif (ref $node eq 'XML::LibXML::Element') {
1016 my $nsuri = $node->namespaceURI;
1017 if (!$nsuri) { # No namespace at all???
1018 if ($node->nodeType == XML_ELEMENT_NODE) {
1019 return $node->localname; }
1020 else {
1021 return; } }
1022 elsif (my $prefix = $$self{namespaceURIs}{$nsuri}) {
1023 return $prefix . ":" . $node->localname; }
1024 else {
1025 # Hasn't got one; we'll create a prefix for internal use.
1026 my $prefix = "_ns" . (1 + scalar(grep { /^_ns\d+$/ } keys %{ $$self{namespaces} }));
1027 # Register it, but Don't add it to the document!!! (or xpath, for that matter)
1028 $$self{namespaces}{$prefix} = $nsuri;
1029 $$self{namespaceURIs}{$nsuri} = $prefix;
1030 return $prefix . ":" . $node->localname; } }
1031 else {
1032 # confess "What's this? $node\n";
1033 return; } }
1034  
1035 #======================================================================
1036 # ADD nodes to $node in the document $self.
1037 # This takes a convenient recursive reprsentation for xml:
1038 # data = string | [$tagname, {attr=>value,..}, @children...]
1039 # The $tagname should have a namespace prefix whose URI has been
1040 # registered with addNamespace.
1041  
1042 # Note that we're currently ignoring duplicated ids.
1043 # these should only happen from rearrangement and copying of document fragments
1044 # with embedded bits of math in them, which have those XMTok/XMRef pairs.
1045 # If those are the cases, we should end up finding the original id'd item, anyway, right?
1046 #
1047 # NOTE that only XML::LibXML's addNewChild deals cleanly with namespaces
1048 # and since there is only an "add" (ie. append) version (not prepend, insert after, etc)
1049 # we have to orient everything towards appending.
1050 # In particular, see the perversity in the following few methods.
1051 sub addNodes {
1052 my ($self, $node, @data) = @_;
1053 foreach my $child (@data) {
1054 if (ref $child eq 'ARRAY') {
1055 my ($tag, $attributes, @children) = @$child;
1056 if ($tag eq '_Fragment_') {
1057 my $indent; # Derive indentation from indentation of $node
1058 if (my $pre = $node->previousSibling) {
1059 if (($pre->nodeType == XML_TEXT_NODE) && (($pre = $pre->textContent) =~ /^\s*$/)) {
1060 $indent = $pre . ' '; } }
1061 if ($indent) {
1062 $self->addNodes($node, map { ($indent, $_) } @children); }
1063 else {
1064 $self->addNodes($node, @children); } }
1065 else {
1066 my ($prefix, $localname) = $tag =~ /^(.*):(.*)$/;
1067 my $nsuri = $prefix && $$self{namespaces}{$prefix};
1068 Warn('expected', 'namespace', undef, "No namespace on '$tag'") unless $nsuri;
1069 my $new;
1070 if (ref $node eq 'LibXML::XML::Document') {
1071 $new = $node->createElementNS($nsuri, $localname);
1072 $node->setDocumentElement($new); }
1073 else {
1074 $new = $node->addNewChild($nsuri, $localname); }
1075 if ($attributes) {
1076 foreach my $key (sort keys %$attributes) {
1077 next unless defined $$attributes{$key};
1078 next if $key =~ /^_/; # Ignore internal attributes
1079 my ($attrprefix, $attrname) = $key =~ /^(.*):(.*)$/;
1080 my $value = $$attributes{$key};
1081 if ($key eq 'xml:id') {
1082 if (defined $$self{idcache}{$value}) { # Duplicated ID ?!?!
1083 my $newid = $self->uniquifyID($value);
1084 Info('unexpected', 'duplicate_id', undef,
1085 "Duplicated id=$value using $newid " . ($$self{destination} || ''));
1086 $value = $newid; }
1087 $self->recordID($value => $new);
1088 $new->setAttribute($key, $value); }
1089 elsif ($attrprefix && ($attrprefix ne 'xml')) {
1090 my $attrnsuri = $attrprefix && $$self{namespaces}{$attrprefix};
1091 $new->setAttributeNS($attrnsuri, $key, $$attributes{$key}); }
1092 else {
1093 $new->setAttribute($key, $$attributes{$key}); } } }
1094 $self->addNodes($new, @children); } }
1095 elsif ((ref $child) =~ /^XML::LibXML::/) {
1096 my $type = $child->nodeType;
1097 if ($type == XML_ELEMENT_NODE) {
1098 # Note: this isn't actually much slower than $node->appendChild($child) !
1099 my $nsuri = $child->namespaceURI;
1100 my $localname = $child->localname;
1101 my $new;
1102 if (ref $node eq 'LibXML::XML::Document') {
1103 $new = $node->createElementNS($nsuri, $localname);
1104 $node->setDocumentElement($new); }
1105 else {
1106 $new = $node->addNewChild($nsuri, $localname); }
1107 foreach my $attr ($child->attributes) {
1108 my $atype = $attr->nodeType;
1109 if ($atype == XML_ATTRIBUTE_NODE) {
1110 my $key = $attr->nodeName;
1111 if ($key =~ /^_/) { } # don't copy internal attributes
1112 elsif ($key eq 'xml:id') {
1113 my $value = $attr->getValue;
1114 my $old;
1115 if ((defined($old = $$self{idcache}{$value})) # if xml:id was already used
1116 && !$old->isSameNode($child)) { # and the node was a different one
1117 my $newid = $self->uniquifyID($value);
1118 Info('unexpected', 'duplicate_id', undef,
1119 "Duplicated id=$value using $newid " . ($$self{destination} || ''));
1120 $value = $newid; }
1121 $self->recordID($value => $new);
1122 $new->setAttribute($key, $value); }
1123 elsif (my $ns = $attr->namespaceURI) {
1124 $new->setAttributeNS($ns, $attr->name, $attr->getValue); }
1125 else {
1126 $new->setAttribute($attr->localname, $attr->getValue); } }
1127 }
1128 $self->addNodes($new, $child->childNodes); }
1129 elsif ($type == XML_DOCUMENT_FRAG_NODE) {
1130 $self->addNodes($node, $child->childNodes); }
1131 elsif ($type == XML_TEXT_NODE) {
1132 $node->appendTextNode($child->textContent); }
1133 }
1134 elsif (ref $child) {
1135 Warn('misdefined', $child, undef, "Dont know how to add $child to $node; ignoring"); }
1136 elsif (defined $child) {
1137 $node->appendTextNode($child); } }
1138 return; }
1139  
1140 # Remove @nodes from the document
1141 # Allow the nodes to be array form with possibly nested XML that needs to be removed.
1142 sub removeNodes {
1143 my ($self, @nodes) = @_;
1144 foreach my $node (@nodes) {
1145 my $ref = ref $node;
1146 if (!$ref) { }
1147 elsif ($ref eq 'ARRAY') {
1148 my ($t, $a, @n) = @$node;
1149 if (my $id = $$a{'xml:id'}) {
1150 if ($$self{idcache}{$id}) {
1151 delete $$self{idcache}{$id}; } }
1152 $self->removeNodes(@n); }
1153 elsif ($ref =~ /^XML::LibXML::/) {
1154 if ($node->nodeType == XML_ELEMENT_NODE) {
1155 foreach my $idd ($self->findnodes("descendant-or-self::*[\@xml:id]", $node)) {
1156 my $id = $idd->getAttribute('xml:id');
1157 if ($$self{idcache}{$id}) {
1158 delete $$self{idcache}{$id}; } } }
1159 $node->unlinkNode; } }
1160 return; }
1161  
1162 # These nodes will be removed, but later
1163 # So mark all id's in these trees as reusable
1164 sub preremoveNodes {
1165 my ($self, @nodes) = @_;
1166 foreach my $node (@nodes) {
1167 my $ref = ref $node;
1168 if (!$ref) { }
1169 elsif ($ref eq 'ARRAY') {
1170 my ($t, $a, @n) = @$node;
1171 if (my $id = $$a{'xml:id'}) {
1172 $$self{idcache_reusable}{$id} = 1; }
1173 $self->preremoveNodes(@n); }
1174 elsif ($ref =~ /^XML::LibXML::/) {
1175 if ($node->nodeType == XML_ELEMENT_NODE) {
1176 foreach my $idd ($self->findnodes("descendant-or-self::*[\@xml:id]", $node)) {
1177 my $id = $idd->getAttribute('xml:id');
1178 $$self{idcache_reusable}{$id} = 1; } } } }
1179 return; }
1180  
1181 sub removeBlankNodes {
1182 my ($self, $node) = @_;
1183 my $n = 0;
1184 foreach my $child ($node->childNodes) {
1185 if (($child->nodeType == XML_TEXT_NODE) && ($child->textContent =~ /^\s*$/)) {
1186 $node->removeChild($child); $n++; } }
1187 return $n; }
1188  
1189 # Replace $node by @replacements in the document
1190 sub replaceNode {
1191 my ($self, $node, @replacements) = @_;
1192 my ($parent, $following) = ($node->parentNode, undef);
1193 # Note that since we can only append new stuff, we've got to remove the following first.
1194 my @save = ();
1195 while (($following = $parent->lastChild) && ($$following != $$node)) { # Remove & Save following siblings.
1196 unshift(@save, $parent->removeChild($following)); }
1197 $self->removeNodes($node);
1198 $self->addNodes($parent, @replacements);
1199 map { $parent->appendChild($_) } @save; # Put these back.
1200 return; }
1201  
1202 # Put @nodes at the beginning of $node.
1203 sub prependNodes {
1204 my ($self, $node, @nodes) = @_;
1205 my @save = ();
1206 # Note that since we can only append new stuff, we've got to remove the following first.
1207 while (my $last = $node->lastChild) { # Remove, but save, all children
1208 unshift(@save, $node->removeChild($last)); }
1209 $self->addNodes($node, @nodes); # Now, add the new nodes.
1210 map { $node->appendChild($_) } @save; # Put these back.
1211 return; }
1212  
1213 # Clone a node, but adjusting it so that it has unique id's.
1214 # $document->cloneNode($node) or ->cloneNode($node,$idsuffix)
1215 # This clones the node and adjusts any xml:id's within it to be unique.
1216 # Any idref's to those ids will be changed to the new id values.
1217 # If $idsuffix is supplied, it can be a simple string to append to the ids;
1218 # else can be a function of the id to modify it.
1219 # Then each $id is checked to see whether it is unique; If needed,
1220 # one or more letters are appended, until a new id is found.
1221 sub cloneNode {
1222 my ($self, $node, $idsuffix, %options) = @_;
1223 return $node unless ref $node;
1224 return $node if ref $node eq 'ARRAY'; # Should we deep clone if we get an array? Just return for now
1225 my $copy = $node->cloneNode(1);
1226 my $nocache = $options{nocache};
1227 #### $idsuffix = '' unless defined $idsuffix;
1228 # Find all id's defined in the copy and change the id.
1229 my %idmap = ();
1230 foreach my $n ($self->findnodes('descendant-or-self::*[@xml:id]', $copy)) {
1231 my $id = $n->getAttribute('xml:id');
1232 my $newid = $self->uniquifyID($id, $idsuffix);
1233 $idmap{$id} = $newid;
1234 $self->recordID($newid => $n) unless $nocache;
1235 $n->setAttribute('xml:id' => $newid);
1236 if (my $fragid = $n->getAttribute('fragid')) { # GACK!!
1237 $n->setAttribute(fragid => substr($newid, length($id) - length($fragid))); } }
1238  
1239 # Now, replace all REFERENCES to those modified ids.
1240 foreach my $n ($self->findnodes('descendant-or-self::*[@idref]', $copy)) {
1241 if (my $id = $idmap{ $n->getAttribute('idref') }) {
1242 $n->setAttribute(idref => $id); } } # use id or fragid?
1243 # Finally, we probably shouldn't have any labels attributes in here either
1244 foreach my $n ($self->findnodes('descendant-or-self::*[@labels]', $copy)) {
1245 $n->removeAttribute('labels'); }
1246 # And, if we're relocating the node across documents,
1247 # we may need to patch relative pathnames!
1248 # ????? Something to think about in the future...
1249 # if(my $base = $options{basepathname}){
1250 # foreach my $n ($self->findnodes('descendant::*/@graphic or descendant::*/@href', $copy)) {
1251 # $n->setvalue(relocate($n->value,$base)); }}
1252 return $copy; }
1253  
1254 sub cloneNodes {
1255 my ($self, @nodes) = @_;
1256 return map { $self->cloneNode($_) } @nodes; }
1257  
1258 sub addSSValues {
1259 my ($self, $node, $key, $values) = @_;
1260 $values = $values->toAttribute if ref $values;
1261 if ((defined $values) && ($values ne '')) { # Skip if `empty'; but 0 is OK!
1262 my @values = split(/\s/, $values);
1263 if (my $oldvalues = $node->getAttribute($key)) { # previous values?
1264 my @old = split(/\s/, $oldvalues);
1265 foreach my $new (@values) {
1266 push(@old, $new) unless grep { $_ eq $new } @old; }
1267 $node->setAttribute($key => join(' ', sort @old)); }
1268 else {
1269 $node->setAttribute($key => join(' ', sort @values)); } }
1270 return; }
1271  
1272 sub addClass {
1273 my ($self, $node, $class) = @_;
1274 return $self->addSSValues($node, class => $class); }
1275  
1276 #======================================================================
1277 # DUPLICATED from Core::Document...(see discussion there)
1278 # Decorations on one side of an XMDual should be attributed to the
1279 # parent node on the other side (see ->associateIDs)
1280  
1281 sub markXMNodeVisibility {
1282 my ($self) = @_;
1283 foreach my $math ($self->findnodes('//ltx:XMath/*')) {
1284 $self->markXMNodeVisibility_aux($math, 1, 1); }
1285 return; }
1286  
1287 sub markXMNodeVisibility_aux {
1288 my ($self, $node, $cvis, $pvis) = @_;
1289 return unless $node;
1290 my $qname = $self->getQName($node);
1291 return if (!$cvis || $node->getAttribute('_cvis')) && (!$pvis || $node->getAttribute('_pvis'));
1292 $node->setAttribute('_cvis' => 1) if $cvis;
1293 $node->setAttribute('_pvis' => 1) if $pvis;
1294 if ($qname eq 'ltx:XMDual') {
1295 my ($c, $p) = element_nodes($node);
1296 $self->markXMNodeVisibility_aux($c, 1, 0) if $cvis;
1297 $self->markXMNodeVisibility_aux($p, 0, 1) if $pvis; }
1298 elsif ($qname eq 'ltx:XMRef') {
1299 # $self->markXMNodeVisibility_aux($self->realizeXMNode($node),$cvis,$pvis); }
1300 my $id = $node->getAttribute('idref');
1301 $self->markXMNodeVisibility_aux($self->findNodeByID($id), $cvis, $pvis); }
1302 else {
1303 foreach my $child (element_nodes($node)) {
1304 $self->markXMNodeVisibility_aux($child, $cvis, $pvis); } }
1305 return; }
1306  
1307 #======================================================================
1308 # Given a list of nodes (or node constructors [tag,attr,content...])
1309 # conjoin given a conjunction like ',' or a pair like [',', ' and ']
1310 sub conjoin {
1311 my ($self, $conjunction, @nodes) = @_;
1312 my ($comma, $and) = ($conjunction, $conjunction);
1313 ($comma, $and) = @$conjunction if ref $conjunction;
1314 my $n = scalar(@nodes);
1315 if ($n < 2) {
1316 return @nodes; }
1317 else {
1318 my @foo = ();
1319 push(@foo, shift(@nodes));
1320 while ($nodes[1]) {
1321 push(@foo, $comma, shift(@nodes)); }
1322 push(@foo, $and, shift(@nodes));
1323 return @foo; } }
1324  
1325 # Find the initial letter in a string, or *.
1326 # Uses unicode decomposition to reduce accented characters to A-Z
1327 # If $force is true, skips any non-letter initials
1328 sub initial {
1329 my ($self, $string, $force) = @_;
1330 $string = NFD($string); # Decompose accents, etc.
1331 $string =~ s/^\s+//gs;
1332 $string =~ s/^[^a-zA-Z]*// if $force;
1333 return ($string =~ /^([a-zA-Z])/ ? uc($1) : '*'); }
1334  
1335 # This would typically be called to normalize the leading/trailing whitespace of nodes
1336 # that take mixed markup. WE SHOULDN'T BE DOING THIS. We need to NOT add "ignorable whitespace"
1337 # to nodes that CAN HAVE mixed content. otherwise we don't know if it is ignorable!
1338 sub trimChildNodes {
1339 my ($self, $node) = @_;
1340 if (!$node) {
1341 return (); }
1342 elsif (!ref $node) {
1343 return ($node); }
1344 elsif (my @children = $node->childNodes) {
1345 if ($children[0] && $children[0]->nodeType == XML_TEXT_NODE) {
1346 my $s = $children[0]->data;
1347 $s =~ s/^\s+//;
1348 if ($s) {
1349 $children[0]->setData($s); }
1350 else {
1351 shift(@children); } }
1352 if ($children[-1] && $children[-1]->nodeType == XML_TEXT_NODE) {
1353 my $s = $children[-1]->data;
1354 $s =~ s/\s+$//;
1355 if ($s) {
1356 $children[-1]->setData($s); }
1357 else {
1358 pop(@children); } }
1359 return @children; }
1360 else {
1361 return (); } }
1362  
1363 sub unisort {
1364 my ($self, @keys) = @_;
1365 # Get a (possibly cached) sorter from POST appropriate for this document's language
1366 my $lang = $self->getDocumentElement->getAttribute('xml:lang') || 'en';
1367 return $LaTeXML::POST->getsorter($lang)->sort(@keys); }
1368  
1369 #======================================================================
1370  
1371 sub addNavigation {
1372 my ($self, $relation, $id) = @_;
1373 return if $self->findnode('//ltx:navigation/ltx:ref[@rel="' . $relation . '"][@idref="' . $id . '"]');
1374 my $ref = ['ltx:ref', { idref => $id, rel => $relation, show => 'toctitle' }];
1375 if (my $nav = $self->findnode('//ltx:navigation')) {
1376 $self->addNodes($nav, $ref); }
1377 else {
1378 $self->addNodes($self->getDocumentElement, ['ltx:navigation', {}, $ref]); }
1379 return; }
1380  
1381 #======================================================================
1382 # Support for ID's
1383  
1384 sub recordID {
1385 my ($self, $id, $node) = @_;
1386 # make an issue if already there?
1387 $$self{idcache}{$id} = $node;
1388 delete $$self{idcache_reserve}{$id}; # And no longer reserved
1389 delete $$self{idcache_reusable}{$id}; # or reusable
1390 return; }
1391  
1392 sub findNodeByID {
1393 my ($self, $id) = @_;
1394 my $node = $$self{idcache}{$id};
1395 return $$self{idcache}{$id}; }
1396  
1397 # If $branch given, should be 'content' or 'presentation'
1398 sub realizeXMNode {
1399 my ($self, $node, $branch) = @_;
1400 if ($branch) {
1401 while ($node) {
1402 my $qname = $self->getQName($node);
1403 if ($qname eq 'ltx:XMRef') {
1404 my $id = $node->getAttribute('idref');
1405 if (my $realnode = $self->findNodeByID($id)) {
1406 $node = $realnode; }
1407 else {
1408 Error('expected', 'id', undef, "Cannot find a node with xml:id='$id'");
1409 return; } }
1410 elsif ($qname eq 'ltx:XMDual') {
1411 my ($content, $presentation) = element_nodes($node);
1412 $node = ($branch eq 'content' ? $content : $presentation); }
1413 else {
1414 return $node; } } }
1415 elsif ($self->getQName($node) eq 'ltx:XMRef') {
1416 my $id = $node->getAttribute('idref');
1417 if (my $realnode = $self->findNodeByID($id)) {
1418 return $realnode; }
1419 else {
1420 Error('expected', 'id', undef, "Cannot find a node with xml:id='$id'");
1421 return; } }
1422 return $node; }
1423  
1424 sub uniquifyID {
1425 my ($self, $baseid, $suffix) = @_;
1426 my $id = $baseid;
1427 $id = (ref $suffix eq 'CODE' ? &$suffix($id) : $id . $suffix) if defined $suffix;
1428 my $cachekey = $id;
1429 while (($$self{idcache}{$id} || $$self{idcache_reserve}{$id}) && !$$self{idcache_reusable}{$id}) {
1430 $id = $baseid . radix_alpha(++$$self{idcache_clashes}{$cachekey});
1431 $id = (ref $suffix eq 'CODE' ? &$suffix($id) : $id . $suffix) if defined $suffix; }
1432 delete $$self{idcache_reusable}{$id}; # $id is no longer reusable
1433 $$self{idcache_reserve}{$id} = 1; # and we'll consider it reserved until recorded.
1434 return $id; }
1435  
1436 # Generate, add and register an xml:id for $node.
1437 # Unless it already has an id, the created id will
1438 # be "structured" relative to it's parent using $prefix
1439 sub generateNodeID {
1440 my ($self, $node, $prefix, $reusable) = @_;
1441 my $id = $node->getAttribute('xml:id');
1442 return $id if $id;
1443 # Find the closest parent with an ID
1444 my ($parent, $pid, $n) = ($node->parentNode, undef, undef);
1445 while ($parent && !($pid = $parent->getAttribute('xml:id'))) {
1446 $parent = $parent->parentNode; }
1447 # Now find the next unused id relative to the parent id, as "prefix<number>"
1448 $pid .= '.' if $pid;
1449 for ($n = 1 ; ($id = $pid . $prefix . $n)
1450 && ($$self{idcache}{$id} || $$self{idcache_reserved}{$id}) ; $n++) { }
1451 $node->setAttribute('xml:id' => $id);
1452 $$self{idcache}{$id} = $node;
1453 $$self{idcache_reusable}{$id} = $reusable;
1454 # If we've already been scanned, and have fragid's, create one here, too.
1455 if (my $fragid = $parent && $parent->getAttribute('fragid')) {
1456 $node->setAttribute(fragid => $fragid . '.' . $prefix . $n); }
1457 return $id; }
1458  
1459 #======================================================================
1460 # adjust_latexml_doctype($doc,"Foo","Bar") =>
1461 # <!DOCTYPE document PUBLIC "-//NIST LaTeXML//LaTeXML article + Foo + Bar"
1462 # "http://dlmf.nist.gov/LaTeXML/LaTeXML-Foo-Bar.dtd">
1463 sub adjust_latexml_doctype {
1464 my ($self, @additions) = @_;
1465 my $doc = $$self{document};
1466 if (my $dtd = $doc->internalSubset) {
1467 if ($dtd->toString
1468 =~ /^<!DOCTYPE\s+(\w+)\s+PUBLIC\s+(\"|\')-\/\/NIST LaTeXML\/\/LaTeXML\s+([^\"]*)\2\s+(\"|\')([^\"]*)\4>$/) {
1469 my ($root, $parts, $system) = ($1, $3, $5);
1470 my ($type, @addns) = split(/ \+ /, $parts);
1471 my %addns = ();
1472 map { $addns{$_} = 1 } @addns, @additions;
1473 @addns = sort keys %addns;
1474 my $publicid = join(' + ', "-//NIST LaTeXML//LaTeXML $type", @addns);
1475 my $systemid = join('-', "http://dlmf.nist.gov/LaTeXML/LaTeXML", @addns) . ".dtd";
1476 $doc->removeInternalSubset; # Apparently we've got to remove it first.
1477 $doc->createInternalSubset($root, $publicid, $systemid); } }
1478 return; }
1479  
1480 #======================================================================
1481 # Cache support: storage of data from previous run.
1482 # ?
1483  
1484 # cacheFile as parameter ????
1485  
1486 sub cacheLookup {
1487 my ($self, $key) = @_;
1488 $self->openCache;
1489 $key = Encode::encode_utf8($key) if $key;
1490 return $$self{cache}{$key}; }
1491  
1492 sub cacheStore {
1493 my ($self, $key, $value) = @_;
1494 $self->openCache;
1495 $key = Encode::encode_utf8($key) if $key;
1496 if (defined $value) {
1497 $$self{cache}{$key} = $value; }
1498 else {
1499 delete $$self{cache}{$key}; }
1500 return; }
1501  
1502 sub openCache {
1503 my ($self) = @_;
1504 if (!$$self{cache}) {
1505 $$self{cache} = {};
1506 my $dbfile = $self->checkDestination("LaTeXML.cache");
1507 tie %{ $$self{cache} }, 'DB_File', $dbfile, O_RDWR | O_CREAT
1508 or return Fatal('internal', 'db', undef,
1509 "Couldn't create DB cache for " . $self->getDestination,
1510 "Message was: " . $!,
1511 (-f $dbfile ? "\n(possibly incompatible db format?)" : ''));
1512 }
1513 return; }
1514  
1515 sub closeCache {
1516 my ($self) = @_;
1517 if ($$self{cache}) {
1518 untie %{ $$self{cache} };
1519 $$self{cache} = undef; }
1520 return; }
1521  
1522 1;
1523 #======================================================================
1524  
1525 __END__
« lib/LaTeXML/Util/ObjectDB.pm ↑ Summary lib/LaTeXML/Core/Array.pm »