lib/LaTeXML/Post.pm

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