lib/LaTeXML/Post/MakeIndex.pm untested

filter: Statementstmt 0.0% 0 / 307 Branchbran 0.0% 0 / 92 Conditioncond 0.0% 0 / 18 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 34 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 476 CC 47 SCAR 32.8
CC
47
Cov
0%
add_rec
56.0
makeIndexEntry
56.0
seealsoSearch_rec
56.0
CRAP 26.5
1 # /=====================================================================\ #
2 # | LaTeXML::Post::MakeIndex | #
3 # | Make an index from scanned indexmark's | #
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::MakeIndex;
13 use strict;
14 use warnings;
15 use LaTeXML::Util::Pathname;
16 use LaTeXML::Common::XML;
17 use charnames qw(:full);
18 use Unicode::Normalize;
19 use LaTeXML::Post;
20 use Text::Unidecode;
21 use base qw(LaTeXML::Post::Collector);
22  
23 # Options:
24 # permuted : Generates a permuted index
25 # The phrases (separated by ! in LaTeX) within each \index entry
26 # are permuted before adding to the index tree.
27 # split : whether the split into separate pages by initial.
28 sub new {
29 my ($class, %options) = @_;
30 my $self = $class->SUPER::new(%options);
31 $$self{permuted} = $options{permuted};
32 $$self{split} = $options{split};
33 return $self; }
34  
35 sub toProcess {
36 my ($self, $doc) = @_;
37 return $doc->findnode('//ltx:index'); }
38  
39 sub process {
40 my ($self, $doc, $index) = @_;
41 my @indices = ($doc);
42 $doc->addDate();
43 my ($tree, $allphrases) = $self->build_tree($doc, $index);
44 if ($tree) {
45 if ($$self{split}) {
46 @indices = map { $self->rescan($_) }
47 $self->makeSubCollectionDocuments($doc, $index,
48 map { ($_ => $self->makeIndexList($doc, $allphrases, $$tree{subtrees}{$_})) }
49 keys %{ $$tree{subtrees} }); }
50 else {
51 $doc->addNodes($index, $self->makeIndexList($doc, $allphrases, $tree));
52 @indices = ($self->rescan($doc)); } }
53 return @indices; }
54  
55 # ================================================================================
56 # Data generated:
57 # $tree : tree representation of the index.
58 # $allphrases : used for inferring the connection from see-also phrases to normal index entries.
59 # ================================================================================
60 # Extracting a tree of index entries from the database
61 sub build_tree {
62 my ($self, $doc, $index) = @_;
63 my $defaultlistname = 'idx';
64 my $listname = 'idx'; # Eventually customizable for different indices?
65 if (my @keys = grep { /^INDEX:/ } $$self{db}->getKeys) {
66 NoteProgress(" [" . scalar(@keys) . " entries]");
67  
68 my $id = $index->getAttribute('xml:id');
69 my $allphrases = {}; # Keep a hash of all phrase textContent=>id encountered (for seealso)
70 my $tree = { subtrees => {}, referrers => {}, id => $id, parent => undef };
71 foreach my $key (@keys) {
72 my $entry = $$self{db}->lookup($key);
73 my $phrases = $entry->getValue('phrases');
74 my @phrases = @$phrases;
75 if (($entry->getValue('inlist') || $defaultlistname) ne $listname) {
76 next; } # Skip any not in this list
77 if (!scalar(@phrases)) {
78 Warn('expected', $key, undef, "Missing phrases in indexmark: '$key'");
79 next; }
80  
81 if ($$self{permuted}) {
82 map { $self->add_entry($doc, $allphrases, $tree, $entry, @{$_}) }
83 cyclic_permute(@phrases); }
84 else {
85 $self->add_entry($doc, $allphrases, $tree, $entry, @phrases); } }
86 return ($tree, $allphrases); }
87 else {
88 return (undef, undef); } }
89  
90 # NOTE: We're building ID's for each entry, of the form idx.key.key...
91 # I'd like to insert the initial in the case of split index: idx.A.key.key...
92 # But this makes it impossible to predict the id of a phrase key, w/o knowing
93 # whether the index has been split!
94 # OTOH, leaving it out risks that a single letter entry, say "A", will have the
95 # same id as the A page! (or maybe not if the key is downcased....)
96 sub add_entry {
97 my ($self, $doc, $allphrases, $tree, $entry, @phrases) = @_;
98 # NOTE: Still need option for splitting!
99 # We'll just prefix a level for the initial...
100 if ($$self{split}) {
101 my $init = $doc->initial($phrases[0]->getAttribute('key'));
102 my $subtree = $$tree{subtrees}{$init};
103 if (!$subtree) {
104 $subtree = $$tree{subtrees}{$init}
105 = { phrase => $init, subtrees => {}, referrers => {}, id => $$tree{id}, parent => $tree }; }
106 add_rec($doc, $allphrases, $subtree, $entry, @phrases); }
107 else {
108 add_rec($doc, $allphrases, $tree, $entry, @phrases); }
109 return; }
110  
111 sub add_rec {
112 my ($doc, $allphrases, $tree, $entry, @phrases) = @_;
113 if (@phrases) {
114 my $phrase = shift(@phrases);
115 my $key = $phrase->getAttribute('key');
116 my $keyid = getIndexKeyID($key);
117 my $subtree = $$tree{subtrees}{$key};
118 if (!$subtree) {
119 my $id = $$tree{id} . '.' . $keyid;
120 my $fullkey = ($$tree{key} ? "$$tree{key}." : '') . $key;
121 # phrasetext is for see & seealso lookup
122 my $phrasetext = getIndexContentKey($phrase);
123 # Store multi-level phrase as well, using space to separate levels
124 my $fullphrasetext = ($$tree{fullphrasetext} ? $$tree{fullphrasetext} . ' ' : '')
125 . $phrasetext;
126 $$allphrases{$fullkey} = $id;
127 $$allphrases{ lc($fullkey) } = $id;
128 $$allphrases{$fullphrasetext} = $id;
129 $$allphrases{ lc($fullphrasetext) } = $id;
130  
131 my $phrasecopy = $doc->cloneNode($phrase);
132 $subtree = $$tree{subtrees}{$key} = { key => $fullkey, id => $id,
133 phrase => $phrasecopy,
134 phrasetext => $phrasetext,
135 fullphrasetext => $fullphrasetext,
136 subtrees => {}, referrers => {}, parent => $tree };
137 }
138 add_rec($doc, $allphrases, $subtree, $entry, @phrases); }
139 else {
140 if (my $seealso = $entry->getValue('see_also')) {
141 $$tree{see_also} = $seealso; }
142 if (my $refs = $entry->getValue('referrers')) {
143 map { $$tree{referrers}{$_} = $$refs{$_} } keys %$refs; } }
144 return; }
145  
146 # Extract the text from the (xml) phrase node, with some normalization.
147 sub getIndexContentKey {
148 my ($node) = @_;
149 my $string = (ref $node ? $node->textContent : $node);
150 $string =~ s/^\s+//s;
151 $string =~ s/\s+$//s;
152 $string =~ s/\s+/ /gs;
153 $string =~ s/\s*[\.\,\;]+$//s; # Remove trailing punctuation
154 return $string; }
155  
156 # This generates the ID from the node
157 # By stripping non-letters, this strips out TOO MUCH; esp. greek etc, in math disappears
158 # Should we keep unicode? (any compatibility issues there?0
159 # Should we just strip to rfc spec?
160 # Should we get the TeX for math?
161 sub getIndexKeyID {
162 my ($key) = @_;
163 $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case
164 # We don't want accented chars (do we?) but we need to decompose the accents!
165 $key = NFD($key);
166 $key = unidecode($key);
167 $key =~ s/[^a-zA-Z0-9]//g;
168 ## Shouldn't be case insensitive?
169 ## $key =~ tr|A-Z|a-z|;
170 return $key; }
171  
172 # ================================================================================
173 # Generate permutations of indexing phrases.
174 sub permute {
175 my (@l) = @_;
176 if (scalar(@l) > 1) {
177 return map { permute_aux($l[$_], @l[0 .. $_ - 1], @l[$_ + 1 .. $#l]) } 0 .. $#l; }
178 else {
179 return [@l]; } }
180  
181 sub permute_aux {
182 my ($first, @rest) = @_;
183 return map { [$first, @$_] } permute(@rest); }
184  
185 # Or would cyclic permutations be more appropriate?
186 # We could get odd orderings, if authors aren't consistent,
187 # but would avoid silly redundancies in small top-level listings.
188 sub cyclic_permute {
189 my (@l) = @_;
190 if (scalar(@l) > 1) {
191 return map { [@l[$_ .. $#l], @l[0 .. $_ - 1]] } 0 .. $#l; }
192 else {
193 return [@l]; } }
194  
195 # ================================================================================
196 # Formatting the resulting index tree.
197  
198 sub makeIndexList {
199 my ($self, $doc, $allphrases, $tree) = @_;
200 my $subtrees = $$tree{subtrees};
201 if (my @keys = $doc->unisort(keys %$subtrees)) {
202 return ['ltx:indexlist', {},
203 map { $self->makeIndexEntry($doc, $allphrases, $$subtrees{$_}) } @keys]; }
204 else {
205 return (); } }
206  
207 sub makeIndexEntry {
208 my ($self, $doc, $allphrases, $tree) = @_;
209 my $refs = $$tree{referrers};
210 my $seealso = $$tree{see_also};
211 my @links = ();
212 if (keys %$refs) {
213 push(@links, ['ltx:text', {}, ' '], $self->combineIndexEntries($doc, $refs)); }
214 if ($seealso) {
215 my %saw = ();
216 foreach my $see (@$seealso) {
217 push(@links, ', '); # if @links;
218 if (my $name = $see->getAttribute('name')) {
219 push(@links, ['ltx:text', { font => 'italic' }, $name, ' ']); }
220 my $phrase = getIndexContentKey($see);
221 if (my @seelinks = $self->seealsoSearch($doc, $allphrases, $tree, $see)) {
222 push(@links, @seelinks); }
223 else {
224 Warn('expected', $phrase, undef,
225 "Missing index see-also term '$phrase'", "(seen under $$tree{key})")
226 unless $doc->findnodes("descendant-or-self::ltx:ref", $see);
227 push(@links, ['ltx:text', {}, $see->childNodes]); } } }
228  
229 return ['ltx:indexentry', { 'xml:id' => $$tree{id} },
230 ['ltx:indexphrase', {}, $doc->trimChildNodes($$tree{phrase})],
231 (@links ? (['ltx:indexrefs', {}, @links]) : ()),
232 $self->makeIndexList($doc, $allphrases, $tree)]; }
233  
234 # Sorting comparison that puts different cases together
235 # Really, it's only used for id's... (would like an id-sort!)
236 sub alphacmp {
237 return (lc($a) cmp lc($b)) || ($a cmp $b); }
238  
239 # combine a set of links into the document; this corresponds to the list of page numbers.
240 # we want them sorted in document order, but also want to combine the end points of ranges.
241 sub combineIndexEntries {
242 my ($self, $doc, $refs) = @_;
243 my @ids = sort alphacmp keys %$refs;
244 # my @ids = $doc->unisort(keys %$refs);
245 my @links = ();
246 while (@ids) {
247 my $id = shift(@ids);
248 my $entry = $$refs{$id};
249 if ($$entry{rangestart}) {
250 my $startid = $id;
251 my $endid = $id;
252 my $lvl = 1;
253 while (@ids) {
254 $endid = shift(@ids);
255 $lvl-- if $$refs{$endid}{rangestart};
256 $lvl-- if $$refs{$endid}{rangeend};
257 last unless $lvl; }
258 push(@links,
259 ['ltx:text', {},
260 $self->makeIndexRefs($doc, $startid,
261 grep { $_ ne 'rangestart' } sort keys %$entry),
262 "\x{2014}",
263 $self->makeIndexRefs($doc, $endid,
264 grep { $_ ne 'rangeend' } sort keys %{ $$refs{$endid} })]); }
265 else {
266 push(@links, $self->makeIndexRefs($doc, $id, sort keys %$entry)); } }
267 return conjoin(@links); }
268  
269 # Make a single ref to a "page", in a particular style.
270 # Given that sorted styles gives bold, italic, normal,
271 # let's just do the first.
272 sub makeIndexRefs {
273 my ($self, $doc, $id, @styles) = @_;
274 return ((($styles[0] || 'normal') ne 'normal')
275 ? ['ltx:text', { font => $styles[0] }, ['ltx:ref', { idref => $id, show => 'typerefnum' }]]
276 : ['ltx:ref', { idref => $id, show => 'typerefnum' }]); }
277  
278 #======================================================================
279 # Dealing with See & Seealso entries.
280 # A LOTTA work, for such a little thing!
281  
282 # Regular index entries, possibly with several levels, are somewhat
283 # structured & formalized: they need to match so that entries can be combined;
284 # they also optionally allow for a sort (& comparison) key.
285 # Seealso entries, are not so structured; there's no provision for a sort key.
286 # They USUALLY will refer to another regular index entry, but aren't required to.
287 # It is nice to LINK such a seealso entry to the corresponding regular entry, if possible!
288  
289 # So, we go on a fishing expedition to find possible phrases.
290 # I find several idioms in use (but perhaps biased by DLMF):
291 # (1) "topic" may refer to top-level "topic", or one within the current subtree
292 # (2) "topic1, topic2 and topic3" may refer to a single entry, or may refer to 3 separate entries.
293 # (3) "topic1 topic2" or "topic1, topic2" may refer to a single entry, or may refer
294 # to a 2 level entry like \index(topic1|topic2)
295 # And finally, case & plural differences may indicate distinct top-level concepts,
296 # or may simply be insignificant variations in phrasing!
297  
298 sub seealsoSearch {
299 my ($self, $doc, $allphrases, $contexttree, $see) = @_;
300 return seealsoSearch_rec($doc, $allphrases, $contexttree, seealsoPartition($doc, $see)); }
301  
302 # @parts are alternating (potential) term, (potential) delimiter, ...
303 sub seealsoSearch_rec {
304 my ($doc, $allphrases, $contexttree, @parts) = @_;
305 my ($link, @links);
306 if (scalar(@parts) < 1) { return (); }
307 elsif (scalar(@parts) < 3) {
308 # Single term? (w/ possible trailing punct) just look it up
309 if ($link = lookupSeealsoPhrase($doc, $allphrases, $contexttree, $parts[0])) {
310 return ($link, ($parts[1] ? cdr($parts[1]) : ())); } }
311 # try first delimiter "literally" (possibly reiterpretedy by lookupSeealsoPhrase)
312 # recurse, so that all alternatives of next delimiter will be considered.
313 elsif (@links = seealsoSearch_rec($doc, $allphrases, $contexttree,
314 seealsoJoin(@parts[0 .. 2]), @parts[3 .. $#parts])) {
315 return @links; }
316 # try any delimiter as possibly a separator between individual entries;
317 # and recurse to handle next delimiter
318 elsif (($link = lookupSeealsoPhrase($doc, $allphrases, $contexttree, $parts[0]))
319 && (@links = seealsoSearch_rec($doc, $allphrases, $contexttree,
320 @parts[2 .. $#parts]))) {
321 return ($link, cdr($parts[1]), @links); }
322 return; }
323  
324 sub car { return $$_[0][0]; }
325  
326 sub cdr {
327 my ($key, @xml) = @{ $_[0] };
328 return @xml; }
329  
330 # Reassemble a partition (list of [key,xml] pairs) into a single such pair.
331 sub seealsoJoin {
332 my (@parts) = @_;
333 return [getIndexContentKey(join('', map { $$_[0] } @parts)), map { cdr($_) } @parts]; }
334  
335 # Look for single phrase either within one of the levels of the current $contexttree,
336 # or at top-level. Try it as-is, or ignoring commas, and/or case-differences.
337 sub lookupSeealsoPhrase {
338 my ($doc, $allphrases, $contexttree, $pair) = @_;
339 my ($phrase, @xml) = @$pair;
340 # concoct various phrases to search for
341 my $pnc = $phrase; $pnc =~ s/,\s*/ /sg; # Ignore punct?
342 my $ps = $phrase; $ps =~ s/(\w+)s\b/$1/sg; # Ignore plurals?
343 my $psnc = $ps; $psnc =~ s/,\s*/ /sg; # Ignore punct AND plurals?
344 my $pnlvl = $phrase; $pnlvl =~ s/,\s*/./sg; # Convert punct to levels?
345 foreach my $trial ($phrase, lc($phrase),
346 $pnc, lc($pnc),
347 $ps, lc($ps),
348 $psnc, lc($psnc),
349 $pnlvl, lc($pnlvl),
350 ) {
351 my $t = $contexttree;
352 while ($t) {
353 if (my $id = $$allphrases{ ($$t{fullphrasetext} ? $$t{fullphrasetext} . " " : '') . $trial }) {
354 return ['ltx:ref', { idref => $id }, @xml]; }
355 $t = $$t{parent}; } }
356 return; }
357  
358 # Partition a seealso (xml) phrase into a sequence of alternating
359 # candidate index phrases (which will be looked up)
360 # candidate delimiters (which potentially split the phrase or not;
361 # see discussion above about delimiters).
362 # This is analogous to a simple split, but that
363 # (a) the argument is XML, with the pieces of delimiter ("," space, "and"...)
364 # potentially distributed amongst distinct xml elements, due to styling.
365 # (b) we want to preserve the XML associated with each phrase & delimiter
366 # in order to fill-in and separate the resulting ltx:ref's
367 # Messy!
368 sub seealsoPartition {
369 my ($doc, $see) = @_;
370 my @parts = seealsoPartition_aux($doc, $see);
371 # Combine adjacent conjunctions & punctuation chunks
372 my @result = (shift(@parts));
373 while (@parts) {
374 my $next = shift(@parts);
375 my $prev_is = ($result[-1][0] =~ /^,?\s*(?:,|\.|\s+|\band\s+also|\band|\bor)\s*$/);
376 my $next_is = ($$next[0] =~ /^(?:,|\.|\s+|and\b|or\b)/);
377 # If either BOTH or NEITHER prev & next are delimiters, combine them.
378 if (!($prev_is xor $next_is)) {
379 my ($k, @x) = @$next;
380 $result[-1][0] .= $k;
381 push(@{ $result[-1] }, @x); }
382 else {
383 push(@result, $next); } }
384 # Now merge any adjacent phrase and/or space chunks into candidate phrase
385 @parts = @result; @result = (shift(@parts));
386 while (@parts) {
387 my $next = shift(@parts);
388 # If next is pure space, combine with prev AND following!
389 if (($$next[0] =~ /^\s+$/s) && scalar(@parts)) {
390 my ($k1, @x1) = @$next;
391 my ($k2, @x2) = @{ shift(@parts) };
392 $result[-1][0] .= $k1 . $k2;
393 push(@{ $result[-1] }, @x1, @x2); }
394 else {
395 push(@result, $next); } }
396 return @result; }
397  
398 # Recursively split the XML $see into pure phrase or delimiter chunks.
399 # we'll still need to combine adjacent chunks appropriately (see above).
400 sub seealsoPartition_aux {
401 my ($doc, $see) = @_;
402 my @result = ();
403 foreach my $ch ($see->childNodes) {
404 my $t = $ch->nodeType;
405 if ($t == XML_TEXT_NODE) {
406 my $string = $ch->textContent;
407 while ($string) {
408 if ($string =~ s/^(,|\.|\s+|and\s+also\b|and\b|or\b)//) {
409 push(@result, [$1, $1]); }
410 elsif ($string =~ s/^([^,\.\s]+)//) {
411 push(@result, [getIndexContentKey($1), $1]); } }
412 push(@result, [getIndexContentKey($string), $string]) if $string; }
413 elsif ($t != XML_ELEMENT_NODE) { }
414 else {
415 my $tag = $doc->getQName($ch);
416 if ($tag =~ /^(ltx:text|ltx:emph)$/) {
417 my $attr = { map { ($_ => $ch->getAttribute($_)) } $ch->attributes };
418 push(@result, map { [$$_[0], [$tag, $attr, cdr($_)]] } seealsoPartition_aux($doc, $ch)); }
419 else {
420 push(@result, [getIndexContentKey($ch), $ch]); }
421 } }
422 return @result; }
423  
424 # ================================================================================
425 sub conjoin {
426 my (@items) = @_;
427 my @result = ();
428 if (@items) {
429 push(@result, shift(@items));
430 while (@items) {
431 push(@result, ", ", shift(@items)); } }
432 return @result; }
433  
434 # ================================================================================
435 1;
436