lib/LaTeXML/Post/Scan.pm untested

filter: Statementstmt 0.0% 0 / 309 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 80 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 34 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 543 CC 47 SCAR 28.6
CC
47
Cov
0%
inPageID
56.0
process
42.0
truncateNode
30.0
CRAP 17.4
1 # /=====================================================================\ #
2 # | LaTeXML::Post::Scan | #
3 # | Scan for ID's etc | #
4 # |=====================================================================| #
5 # | Part of LaTeXML: | #
6 # | Public domain software, produced as part of work done by the | #
7 # | United States Government & not subject to copyright in the US. | #
8 # |---------------------------------------------------------------------| #
9 # | Bruce Miller <bruce.miller@nist.gov> #_# | #
10 # | http://dlmf.nist.gov/LaTeXML/ (o o) | #
11 # \=========================================================ooo==U==ooo=/ #
12 package LaTeXML::Post::Scan;
13 use strict;
14 use warnings;
15 use LaTeXML::Util::Pathname;
16 use LaTeXML::Common::XML;
17 use LaTeXML::Post;
18 use base qw(LaTeXML::Post::Processor);
19  
20 # NOTE: This module is one that probably needs a lot of customizability.
21 sub new {
22 my ($class, %options) = @_;
23 my $self = $class->SUPER::new(%options);
24 $$self{db} = $options{db};
25 $$self{handlers} = {};
26 $self->registerHandler('ltx:document' => \&section_handler);
27 $self->registerHandler('ltx:part' => \&section_handler);
28 $self->registerHandler('ltx:chapter' => \&section_handler);
29 $self->registerHandler('ltx:section' => \&section_handler);
30 $self->registerHandler('ltx:appendix' => \&section_handler);
31 $self->registerHandler('ltx:subsection' => \&section_handler);
32 $self->registerHandler('ltx:subsubsection' => \&section_handler);
33 $self->registerHandler('ltx:paragraph' => \&section_handler);
34 $self->registerHandler('ltx:subparagraph' => \&section_handler);
35 $self->registerHandler('ltx:bibliography' => \&section_handler);
36 $self->registerHandler('ltx:index' => \&section_handler);
37 $self->registerHandler('ltx:glossary' => \&section_handler);
38  
39 $self->registerHandler('ltx:table' => \&captioned_handler);
40 $self->registerHandler('ltx:figure' => \&captioned_handler);
41 $self->registerHandler('ltx:float' => \&captioned_handler);
42 $self->registerHandler('ltx:listing' => \&captioned_handler);
43 $self->registerHandler('ltx:theorem' => \&section_handler);
44 $self->registerHandler('ltx:proof' => \&section_handler);
45  
46 $self->registerHandler('ltx:equation' => \&labelled_handler);
47 $self->registerHandler('ltx:equationgroup' => \&labelled_handler);
48 $self->registerHandler('ltx:item' => \&labelled_handler);
49 $self->registerHandler('ltx:anchor' => \&anchor_handler);
50 $self->registerHandler('ltx:note' => \&note_handler);
51  
52 $self->registerHandler('ltx:bibitem' => \&bibitem_handler);
53 $self->registerHandler('ltx:bibentry' => \&bibentry_handler);
54 $self->registerHandler('ltx:indexmark' => \&indexmark_handler);
55 $self->registerHandler('ltx:glossaryentry' => \&glossaryentry_handler);
56 $self->registerHandler('ltx:glossarydefinition' => \&glossaryentry_handler);
57 $self->registerHandler('ltx:ref' => \&ref_handler);
58 $self->registerHandler('ltx:bibref' => \&bibref_handler);
59  
60 $self->registerHandler('ltx:navigation' => \&navigation_handler);
61  
62 $self->registerHandler('ltx:rdf' => \&rdf_handler);
63  
64 $self->registerHandler('ltx:rawhtml' => \&rawhtml_handler);
65  
66 return $self; }
67  
68 sub registerHandler {
69 my ($self, $tag, $handler) = @_;
70 $$self{handlers}{$tag} = $handler;
71 return; }
72  
73 sub process {
74 my ($self, $doc, $root) = @_;
75 # I think we really need an ID here to establish the root node in the DB,
76 # even if the document didn't have one originally.
77 # And for the common case of a single docucment, we'd like to be silent about it,
78 # UNLESS there seem to be multiple documents which would lead to a conflict.
79 my $id = $root->getAttribute('xml:id');
80 if (!defined $id) {
81 $id = "Document";
82 if (my $preventry = $$self{db}->lookup("ID:$id")) {
83 if (my $loc = $doc->siteRelativeDestination) {
84 my $prevloc = $preventry->getValue('location');
85 if ((defined $prevloc) && ($loc ne $prevloc)) {
86 Warn('unexpected', 'location', undef,
87 "Using default ID='$id', "
88 . "but there's an apparent conflict with location '$loc' and previous '$prevloc'"); } } }
89 $root->setAttribute('xml:id' => $id); }
90  
91 $$self{db}->{document_id} = $id unless defined $$self{db}->{document_id};
92 $self->scan($doc, $root, $$doc{parent_id});
93 NoteProgressDetailed(" [DBStatus: " . $$self{db}->status . "]");
94 return $doc; }
95  
96 sub scan {
97 my ($self, $doc, $node, $parent_id) = @_;
98 my $tag = $doc->getQName($node);
99 my $handler = $$self{handlers}{$tag} || \&default_handler;
100 &$handler($self, $doc, $node, $tag, $parent_id);
101 return; }
102  
103 sub scanChildren {
104 my ($self, $doc, $node, $parent_id) = @_;
105 foreach my $child ($node->childNodes) {
106 if ($child->nodeType == XML_ELEMENT_NODE) {
107 $self->scan($doc, $child, $parent_id); } }
108 return; }
109  
110 sub addAsChild {
111 my ($self, $id, $parent_id) = @_;
112 # Find the ancestor that maintains a children list
113 while (my $parent = $parent_id && $$self{db}->lookup("ID:$parent_id")) {
114 if ($parent->hasValue('children')) {
115 $parent->pushNew('children', $id);
116 last; }
117 else {
118 $parent_id = $parent->getValue('parent'); } }
119 return; }
120  
121 sub pageID {
122 my ($self, $doc) = @_;
123 return $doc->getDocumentElement->getAttribute('xml:id'); }
124  
125 # Compute a "Fragment ID", ie. an ID based on the given ID,
126 # but which is potentially shortened so that it need only be
127 # unique within the given page.
128 sub inPageID {
129 my ($self, $doc, $node) = @_;
130 my $id = $node->getAttribute('xml:id');
131 my $baseid = $doc->getDocumentElement->getAttribute('xml:id') || '';
132 # And we're using label-based ids in the target document...
133 if ($$self{labelids}) {
134 if (my $labels = $node->getAttribute('labels')) {
135 my ($l) = split(' ', $labels);
136 $l =~ s/^LABEL://;
137 $id = $l;
138 if (my $baselabels = $doc->getDocumentElement->getAttribute('labels')) {
139 my ($bl) = split(' ', $baselabels);
140 $bl =~ s/^LABEL://;
141 $baseid = $bl; } } }
142 if ($baseid eq $id) {
143 return; }
144 elsif ($baseid && ($id =~ /^\Q$baseid\E\.(.*)$/)) {
145 return $1; }
146 elsif ($$doc{split_from_id} && ($id =~ /^\Q$$doc{split_from_id}\E\.(.*)$/)) {
147 return $1; }
148 else {
149 return $id; } }
150  
151 sub noteLabels {
152 my ($self, $node) = @_;
153 if (my $id = $node->getAttribute('xml:id')) {
154 if (my $labels = $node->getAttribute('labels')) {
155 my @labels = split(' ', $node->getAttribute('labels'));
156 foreach my $label (@labels) {
157 $$self{db}->register($label, id => orNull($id)); }
158 return [@labels]; } }
159 return; }
160  
161 # Clean up a node before insertion into database.
162 sub cleanNode {
163 my ($self, $doc, $node) = @_;
164 return $node unless $node;
165 # Clone the node, and get the ID's unique (at least) within the originating document
166 my $cleaned = $doc->cloneNode($node);
167 # Remove indexmark (anything else ?)
168 map { $_->parentNode->removeChild($_) } $doc->findnodes('.//ltx:indexmark', $cleaned);
169 return $cleaned; }
170  
171 # Assumes $node has been cloned, if needed.
172 # Set to something smallish (eg. 6) to forcibly truncate toctitle/toccaption
173 our $TOCTEXT_MAX_LENGTH = undef;
174  
175 sub truncateNode {
176 my ($self, $doc, $node) = @_;
177 return $node if !$node || !defined $TOCTEXT_MAX_LENGTH;
178 my @children = $node->childNodes;
179 my $n = $TOCTEXT_MAX_LENGTH;
180 my $trunc = 0;
181 while ($n && @children) {
182 my $c = shift(@children);
183 if ($c->nodeType == XML_TEXT_NODE) {
184 my $s = $c->textContent;
185 my @w = split(/\s/, $s);
186 if (scalar(@w) > $n) {
187 $c->setData(join(' ', @w[0 .. $n]));
188 $trunc = 1; $n = 0; }
189 else {
190 $n--; } }
191 else {
192 $n--; } }
193 if ($trunc || (scalar(@children) > 1)) {
194 map { $node->removeChild($_) } @children; # Remove any remaining children.
195 $node->appendText("\x{2026}"); }
196 return $node; }
197  
198 sub addCommon {
199 my ($self, $doc, $node, $tag, $parent_id) = @_;
200 my $id = $node->getAttribute('xml:id');
201 my $inlist;
202 if (my $listnames = $node->getAttribute('inlist')) {
203 $inlist = { map { ($_ => 1) } split(/\s/, $listnames) }; }
204 my %props = (
205 id => orNull($id),
206 type => orNull($tag),
207 parent => orNull($parent_id),
208 labels => orNull($self->noteLabels($node)),
209 location => orNull($doc->siteRelativeDestination),
210 pageid => orNull($self->pageID($doc)),
211 fragid => orNull($self->inPageID($doc, $node)),
212 inlist => $inlist,
213 );
214 # Figure out sane, safe naming?
215 foreach my $tagnode ($doc->findnodes('ltx:tags/ltx:tag', $node)) {
216 my $key;
217 if (my $role = $tagnode->getAttribute('role')) {
218 if ($role =~ /.*refnum$/) {
219 $key = $role; }
220 else {
221 $key = 'tag:' . $role; } }
222 else {
223 $key = 'frefnum'; }
224 ### $key = 'refnum'; } # ???
225 $props{$key} = $self->cleanNode($doc, $tagnode); }
226 return %props; }
227  
228 sub default_handler {
229 my ($self, $doc, $node, $tag, $parent_id) = @_;
230 my $id = $node->getAttribute('xml:id');
231 if ($id) {
232 $$self{db}->register("ID:$id",
233 $self->addCommon($doc, $node, $tag, $parent_id));
234 $self->addAsChild($id, $parent_id); }
235 $self->scanChildren($doc, $node, $id || $parent_id);
236 return; }
237  
238 sub section_handler {
239 my ($self, $doc, $node, $tag, $parent_id) = @_;
240 my $id = $node->getAttribute('xml:id');
241 if ($id) {
242 $$self{db}->register("ID:$id",
243 $self->addCommon($doc, $node, $tag, $parent_id),
244 primary => 1,
245 title => orNull($self->cleanNode($doc, $doc->findnode('ltx:title', $node))),
246 toctitle => orNull($self->cleanNode($doc, $doc->findnode('ltx:toctitle', $node))),
247 children => [],
248 stub => orNull($node->getAttribute('stub')));
249 $self->addAsChild($id, $parent_id); }
250 $self->scanChildren($doc, $node, $id || $parent_id);
251 return; }
252  
253 sub captioned_handler {
254 my ($self, $doc, $node, $tag, $parent_id) = @_;
255 my $id = $node->getAttribute('xml:id');
256 if ($id) {
257 # We're actually trying to find the shallowest caption
258 # Not one nested in another figure/table/float/whoknowswhat !
259 my ($caption) = ($doc->findnode('child::ltx:caption', $node),
260 $doc->findnode('descendant::ltx:caption', $node));
261 my ($toccaption) = ($doc->findnode('child::ltx:toccaption', $node),
262 $doc->findnode('descendant::ltx:toccaption', $node));
263 $$self{db}->register("ID:$id",
264 $self->addCommon($doc, $node, $tag, $parent_id),
265 role => orNull($node->getAttribute('role')),
266 caption => orNull($self->cleanNode($doc, $caption)),
267 ### toccaption => orNull($self->cleanNode($doc,
268 ### $doc->findnode('descendant::ltx:toccaption', $node))));
269 toccaption => orNull($self->truncateNode($doc, $self->cleanNode($doc, $toccaption))));
270 $self->addAsChild($id, $parent_id); }
271 $self->scanChildren($doc, $node, $id || $parent_id);
272 return; }
273  
274 sub labelled_handler {
275 my ($self, $doc, $node, $tag, $parent_id) = @_;
276 my $id = $node->getAttribute('xml:id');
277 if ($id) {
278 $$self{db}->register("ID:$id",
279 $self->addCommon($doc, $node, $tag, $parent_id),
280 role => orNull($node->getAttribute('role')),
281 );
282 $self->addAsChild($id, $parent_id); }
283 $self->scanChildren($doc, $node, $id || $parent_id);
284 return; }
285  
286 # Maybe with some careful redesign of the schema, this would fall under labelled?
287 sub note_handler {
288 my ($self, $doc, $node, $tag, $parent_id) = @_;
289 my $id = $node->getAttribute('xml:id');
290 if ($id) {
291 my $note = $self->cleanNode($doc, $node);
292 map { $note->removeChild($_) } $doc->findnodes('.//ltx:tags', $note);
293 $$self{db}->register("ID:$id",
294 $self->addCommon($doc, $node, $tag, $parent_id),
295 role => orNull($node->getAttribute('role')),
296 note => $note,
297 );
298 $self->addAsChild($id, $parent_id); }
299 $self->scanChildren($doc, $node, $id || $parent_id);
300 return; }
301  
302 sub anchor_handler {
303 my ($self, $doc, $node, $tag, $parent_id) = @_;
304 my $id = $node->getAttribute('xml:id');
305 if ($id) {
306 $$self{db}->register("ID:$id",
307 $self->addCommon($doc, $node, $tag, $parent_id),
308 title => orNull($self->cleanNode($doc, $node)),
309 );
310 $self->addAsChild($id, $parent_id); }
311 $self->scanChildren($doc, $node, $id || $parent_id);
312 return; }
313  
314 sub ref_handler {
315 my ($self, $doc, $node, $tag, $parent_id) = @_;
316 my $id = $node->getAttribute('xml:id');
317 if (my $label = $node->getAttribute('labelref')) { # Only record refs of labels
318 # Don't scan refs from TOC or 'cited' bibblock
319 if (!$doc->findnodes('ancestor::ltx:tocentry'
320 . '| ancestor::ltx:bibblock[contains(@class,"ltx_bib_cited")]',
321 $node)) {
322 my $entry = $$self{db}->register($label);
323 $entry->noteAssociation(referrers => $parent_id); } }
324 # Usually, a ref won't YET have content; but if it does, we should scan it.
325 $self->default_handler($doc, $node, $tag, $parent_id);
326 return; }
327  
328 sub bibref_handler {
329 my ($self, $doc, $node, $tag, $parent_id) = @_;
330 # Don't scan refs from 'cited' bibblock
331 if (!$doc->findnodes('ancestor::ltx:bibblock[contains(@class,"ltx_bib_cited")]', $node)) {
332 ##### if( ($node->getAttribute('class')||'') !~ /\bcitedby\b/){
333 if (my $keys = $node->getAttribute('bibrefs')) {
334 my @lists = split(/\s+/, $node->getAttribute('inlist') || 'bibliography');
335 foreach my $bibkey (split(',', $keys)) {
336 if ($bibkey) {
337 $bibkey = lc($bibkey); # NOW we downcase!
338 my $entry = $$self{db}->register("BIBLABEL:$bibkey");
339 map { $entry->noteAssociation(inlist => $_); } @lists;
340 $entry->noteAssociation(referrers => $parent_id); } } } }
341 # Usually, a bibref will have, at most, some ltx:bibphrase's; should be scanned.
342 $self->default_handler($doc, $node, $tag, $parent_id);
343 return; }
344  
345 # Note that index entries get stored in simple form; just the terms & location.
346 # They will be turned into a tree, sorted, possibly permuted, whatever, by MakeIndex.
347 # [the only content of indexmark should be un-marked up(?) don't recurse]
348 sub indexmark_handler {
349 my ($self, $doc, $node, $tag, $parent_id) = @_;
350 # Get the actual phrases, and any see_also phrases (if any)
351 # Do these need ->cleanNode ???
352 my @phrases = $doc->findnodes('ltx:indexphrase', $node);
353 my @seealso = $doc->findnodes('ltx:indexsee', $node);
354 my $key = join(':', 'INDEX', map { $_->getAttribute('key') } @phrases);
355 my $inlist;
356 if (my $listnames = $node->getAttribute('inlist')) {
357 $inlist = { map { ($_ => 1) } split(/\s/, $listnames) }; }
358 my $entry = $$self{db}->lookup($key)
359 || $$self{db}->register($key, phrases => [@phrases], see_also => [], inlist => $inlist);
360 if (@seealso) {
361 $entry->pushNew('see_also', @seealso); }
362 else {
363 $entry->noteAssociation(referrers => $parent_id => ($node->getAttribute('style') || 'normal')); }
364 return; }
365  
366 # This handles glossaryentry or glossarydefinition
367 sub glossaryentry_handler {
368 my ($self, $doc, $node, $tag, $parent_id) = @_;
369 my $id = $node->getAttribute('xml:id');
370 my $p;
371 my $lists = $node->getAttribute('inlist') ||
372 (($p = $doc->findnode('ancestor::ltx:glossarylist[@lists] | ancestor::ltx:glossary[@lists]', $node))
373 && $p->getAttribute('lists'))
374 || 'glossary';
375 my $key = $node->getAttribute('key');
376 # Get the actual phrases, and any see_also phrases (if any)
377 # Do these need ->cleanNode ???
378 my @phrases = $doc->findnodes('ltx:glossaryphrase', $node);
379 # Create an entry for EACH list (they could be distinct definitions)
380 foreach my $list (split(/\s+/, $lists)) {
381 my $gkey = join(':', 'GLOSSARY', $list, $key);
382 my $entry = $$self{db}->lookup($gkey) || $$self{db}->register($gkey);
383 $entry->setValues(map { ('phrase:' . ($_->getAttribute('role') || 'label') => $_) } @phrases);
384 $entry->noteAssociation(referrers => $parent_id => ($node->getAttribute('style') || 'normal'));
385 $entry->setValues(id => $id) if $id; }
386  
387 if ($id) {
388 $$self{db}->register("ID:$id", id => orNull($id), type => orNull($tag), parent => orNull($parent_id),
389 labels => orNull($self->noteLabels($node)),
390 location => orNull($doc->siteRelativeDestination),
391 pageid => orNull($self->pageID($doc)),
392 fragid => orNull($self->inPageID($doc, $node))); }
393 # Scan content, since could contain other interesting stuff...
394 $self->scanChildren($doc, $node, $id || $parent_id);
395 return; }
396  
397 # Note this bit of perversity:
398 # <ltx:bibentry> is a semantic bibliographic entry,
399 # as generated from a BibTeX file.
400 # <ltx:bibitem> is a formatted bibliographic entry,
401 # as generated from an explicit thebibliography environment,
402 # or as formatted from a <ltx:bibentry> by MakeBibliography.
403 # For a bibitem, we'll store the usual info in the DB.
404 sub bibitem_handler {
405 my ($self, $doc, $node, $tag, $parent_id) = @_;
406 my $id = $node->getAttribute('xml:id');
407 if ($id) {
408 # NOTE: We didn't downcase the key when we created the bib file
409 # BUT, we're going to index it in the ObjectDB by the downcased name!!!
410 my $key = $node->getAttribute('key');
411 $key = lc($key) if $key;
412 $$self{db}->register("BIBLABEL:$key", id => orNull($id)) if $key;
413 # Do these need ->cleanNode ???
414 $$self{db}->register("ID:$id", id => orNull($id), type => orNull($tag), parent => orNull($parent_id), bibkey => orNull($key),
415 location => orNull($doc->siteRelativeDestination),
416 pageid => orNull($self->pageID($doc)),
417 fragid => orNull($self->inPageID($doc, $node)),
418 authors => orNull($doc->findnode('ltx:tags/ltx:tag[@role="authors"]', $node)),
419 fullauthors => orNull($doc->findnode('ltx:tags/ltx:tag[@role="fullauthors"]', $node)),
420 year => orNull($doc->findnode('ltx:tags/ltx:tag[@role="year"]', $node)),
421 number => orNull($doc->findnode('ltx:tags/ltx:tag[@role="number"]', $node)),
422 refnum => orNull($doc->findnode('ltx:tags/ltx:tag[@role="refnum"]', $node)),
423 title => orNull($doc->findnode('ltx:tags/ltx:tag[@role="title"]', $node)),
424 keytag => orNull($doc->findnode('ltx:tags/ltx:tag[@role="key"]', $node)),
425 typetag => orNull($doc->findnode('ltx:tags/ltx:tag[@role="bibtype"]', $node))); }
426 $self->scanChildren($doc, $node, $id || $parent_id);
427 return; }
428  
429 # For a bibentry, we'll only store the citation key, so we know it's there.
430 sub bibentry_handler {
431 my ($self, $doc, $node, $tag, $parent_id) = @_;
432 my $id = $node->getAttribute('xml:id');
433 if ($id) {
434 if (my $key = $node->getAttribute('key')) {
435 $$self{db}->register('BIBLABEL:' . lc($key), id => orNull($id)); } }
436 ## No, let's not scan the content of the bibentry
437 ## until it gets formatted and re-scanned by MakeBibliography.
438 ## $self->scanChildren($doc,$node,$id || $parent_id);
439  
440 ## HOWEVER; this ultimately requires formatting the bibliography twice (for complex sites).
441 ## This needs to be reworked!
442 return; }
443  
444 # I'm thinking we shouldn't acknowledge navigation data at all?
445 sub navigation_handler {
446 my ($self, $doc, $node, $tag, $parent_id) = @_;
447 return; }
448  
449 # RDF should be recorded with its "about" designation, or its immediate parent
450 sub rdf_handler {
451 my ($self, $doc, $node, $tag, $parent_id) = @_;
452 my $id = $node->getAttribute('about');
453 if (!($id && ($id =~ s/^#//))) {
454 $id = $parent_id; }
455 my $property = $node->getAttribute('property');
456 my $value = $node->getAttribute('resource') || $node->getAttribute('content');
457 return unless ($property && $value);
458 $$self{db}->register("ID:$id", $property => orNull($value));
459 return; }
460  
461 # I'm thinking we shouldn't acknowledge rawhtml data at all?
462 sub rawhtml_handler {
463 my ($self, $doc, $node, $tag, $parent_id) = @_;
464 return; }
465  
466 sub orNull {
467 return (grep { defined } @_) ? @_ : undef; }
468  
469 # ================================================================================
470 1;
471