lib/LaTeXML/Post/MakeIndex.pm untested

filter: Statementstmt 0.0% 0 / 310 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 / 479 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 NoteLog("MakeIndex: " . 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 my %GREEK_ASCII_MAP = (
162 "\x{03B1}" => 'alpha', "\x{03B2}" => 'beta', "\x{03B3}" => 'gamma', "\x{03B4}" => 'delta',
163 "\x{03F5}" => 'epsilon', "\x{03B5}" => 'varepsilon', "\x{03B6}" => 'zeta', "\x{03B7}" => 'eta',
164 "\x{03B8}" => 'theta', "\x{03D1}" => 'vartheta', "\x{03B9}" => 'iota', "\x{03BA}" => 'kappa',
165 "\x{03BB}" => 'lambda', "\x{03BC}" => 'mu', "\x{03BD}" => 'nu', "\x{03BE}" => 'xi',
166 "\x{03C0}" => 'pi', "\x{03D6}" => 'varpi', "\x{03C1}" => 'rho', "\x{03F1}" => 'varrho',
167 "\x{03C3}" => 'sigma', "\x{03C2}" => 'varsigma', "\x{03C4}" => 'tau', "\x{03C5}" => 'upsilon',
168 "\x{03D5}" => 'phi', "\x{03C6}" => 'varphi', "\x{03C7}" => 'chi', "\x{03C8}" => 'psi',
169 "\x{03C9}" => 'omega', "\x{0393}" => 'Gamma', "\x{0394}" => 'Delta', "\x{0398}" => 'Theta',
170 "\x{039B}" => 'Lambda', "\x{039E}" => 'Xi', "\x{03A0}" => 'Pi', "\x{03A3}" => 'Sigma',
171 "\x{03A5}" => 'Upsilon', "\x{03A6}" => 'Phi', "\x{03A8}" => 'Psi', "\x{03A9}" => 'Omega');
172 my $GREEK_RE = '(' . join('|', sort keys %GREEK_ASCII_MAP) . ')';
173  
174 sub getIndexKeyID {
175 my ($key) = @_;
176 $key =~ s/^\s+//s; $key =~ s/\s+$//s; # Trim leading/trailing, in any case
177 # We don't want accented chars (do we?) but we need to decompose the accents!
178 $key = NFD($key);
179 $key =~ s/$GREEK_RE/$GREEK_ASCII_MAP{$1}/eg;
180 $key = unidecode($key);
181 $key =~ s/[^a-zA-Z0-9]//g;
182 ## Shouldn't be case insensitive?
183 ## $key =~ tr|A-Z|a-z|;
184 return $key; }
185  
186 # ================================================================================
187 # Generate permutations of indexing phrases.
188 sub permute {
189 my (@l) = @_;
190 if (scalar(@l) > 1) {
191 return map { permute_aux($l[$_], @l[0 .. $_ - 1], @l[$_ + 1 .. $#l]) } 0 .. $#l; }
192 else {
193 return [@l]; } }
194  
195 sub permute_aux {
196 my ($first, @rest) = @_;
197 return map { [$first, @$_] } permute(@rest); }
198  
199 # Or would cyclic permutations be more appropriate?
200 # We could get odd orderings, if authors aren't consistent,
201 # but would avoid silly redundancies in small top-level listings.
202 sub cyclic_permute {
203 my (@l) = @_;
204 if (scalar(@l) > 1) {
205 return map { [@l[$_ .. $#l], @l[0 .. $_ - 1]] } 0 .. $#l; }
206 else {
207 return [@l]; } }
208  
209 # ================================================================================
210 # Formatting the resulting index tree.
211  
212 sub makeIndexList {
213 my ($self, $doc, $allphrases, $tree) = @_;
214 my $subtrees = $$tree{subtrees};
215 if (my @keys = $doc->unisort(keys %$subtrees)) {
216 return ['ltx:indexlist', {},
217 map { $self->makeIndexEntry($doc, $allphrases, $$subtrees{$_}) } @keys]; }
218 else {
219 return (); } }
220  
221 sub makeIndexEntry {
222 my ($self, $doc, $allphrases, $tree) = @_;
223 my $refs = $$tree{referrers};
224 my $seealso = $$tree{see_also};
225 my @links = ();
226 if (keys %$refs) {
227 push(@links, ['ltx:text', {}, ' '], $self->combineIndexEntries($doc, $refs)); }
228 if ($seealso) {
229 my %saw = ();
230 foreach my $see (@$seealso) {
231 push(@links, ', '); # if @links;
232 if (my $name = $see->getAttribute('name')) {
233 push(@links, ['ltx:text', { font => 'italic' }, $name, ' ']); }
234 my $phrase = getIndexContentKey($see);
235 if (my @seelinks = $self->seealsoSearch($doc, $allphrases, $tree, $see)) {
236 push(@links, @seelinks); }
237 else {
238 Warn('expected', $phrase, undef,
239 "Missing index see-also term '$phrase'", "(seen under $$tree{key})")
240 unless $doc->findnodes("descendant-or-self::ltx:ref", $see);
241 push(@links, ['ltx:text', {}, $see->childNodes]); } } }
242  
243 return ['ltx:indexentry', { 'xml:id' => $$tree{id} },
244 ['ltx:indexphrase', {}, $doc->trimChildNodes($$tree{phrase})],
245 (@links ? (['ltx:indexrefs', {}, @links]) : ()),
246 $self->makeIndexList($doc, $allphrases, $tree)]; }
247  
248 # Sorting comparison that puts different cases together
249 # Really, it's only used for id's... (would like an id-sort!)
250 sub alphacmp {
251 return (lc($a) cmp lc($b)) || ($a cmp $b); }
252  
253 # combine a set of links into the document; this corresponds to the list of page numbers.
254 # we want them sorted in document order, but also want to combine the end points of ranges.
255 sub combineIndexEntries {
256 my ($self, $doc, $refs) = @_;
257 my @ids = sort alphacmp keys %$refs;
258 # my @ids = $doc->unisort(keys %$refs);
259 my @links = ();
260 while (@ids) {
261 my $id = shift(@ids);
262 my $entry = $$refs{$id};
263 if ($$entry{rangestart}) {
264 my $startid = $id;
265 my $endid = $id;
266 my $lvl = 1;
267 while (@ids) {
268 $endid = shift(@ids);
269 $lvl-- if $$refs{$endid}{rangestart};
270 $lvl-- if $$refs{$endid}{rangeend};
271 last unless $lvl; }
272 push(@links,
273 ['ltx:text', {},
274 $self->makeIndexRefs($doc, $startid,
275 grep { $_ ne 'rangestart' } sort keys %$entry),
276 "\x{2014}",
277 $self->makeIndexRefs($doc, $endid,
278 grep { $_ ne 'rangeend' } sort keys %{ $$refs{$endid} })]); }
279 else {
280 push(@links, $self->makeIndexRefs($doc, $id, sort keys %$entry)); } }
281 return conjoin(@links); }
282  
283 # Make a single ref to a "page", in a particular style.
284 # Given that sorted styles gives bold, italic, normal,
285 # let's just do the first.
286 sub makeIndexRefs {
287 my ($self, $doc, $id, @styles) = @_;
288 return ((($styles[0] || 'normal') ne 'normal')
289 ? ['ltx:text', { font => $styles[0] }, ['ltx:ref', { idref => $id, show => 'typerefnum' }]]
290 : ['ltx:ref', { idref => $id, show => 'typerefnum' }]); }
291  
292 #======================================================================
293 # Dealing with See & Seealso entries.
294 # A LOTTA work, for such a little thing!
295  
296 # Regular index entries, possibly with several levels, are somewhat
297 # structured & formalized: they need to match so that entries can be combined;
298 # they also optionally allow for a sort (& comparison) key.
299 # Seealso entries, are not so structured; there's no provision for a sort key.
300 # They USUALLY will refer to another regular index entry, but aren't required to.
301 # It is nice to LINK such a seealso entry to the corresponding regular entry, if possible!
302  
303 # So, we go on a fishing expedition to find possible phrases.
304 # I find several idioms in use (but perhaps biased by DLMF):
305 # (1) "topic" may refer to top-level "topic", or one within the current subtree
306 # (2) "topic1, topic2 and topic3" may refer to a single entry, or may refer to 3 separate entries.
307 # (3) "topic1 topic2" or "topic1, topic2" may refer to a single entry, or may refer
308 # to a 2 level entry like \index(topic1|topic2)
309 # And finally, case & plural differences may indicate distinct top-level concepts,
310 # or may simply be insignificant variations in phrasing!
311  
312 sub seealsoSearch {
313 my ($self, $doc, $allphrases, $contexttree, $see) = @_;
314 return seealsoSearch_rec($doc, $allphrases, $contexttree, seealsoPartition($doc, $see)); }
315  
316 # @parts are alternating (potential) term, (potential) delimiter, ...
317 sub seealsoSearch_rec {
318 my ($doc, $allphrases, $contexttree, @parts) = @_;
319 my ($link, @links);
320 if (scalar(@parts) < 1) { return (); }
321 elsif (scalar(@parts) < 3) {
322 # Single term? (w/ possible trailing punct) just look it up
323 if ($link = lookupSeealsoPhrase($doc, $allphrases, $contexttree, $parts[0])) {
324 return ($link, ($parts[1] ? cdr($parts[1]) : ())); } }
325 # try first delimiter "literally" (possibly reiterpretedy by lookupSeealsoPhrase)
326 # recurse, so that all alternatives of next delimiter will be considered.
327 elsif (@links = seealsoSearch_rec($doc, $allphrases, $contexttree,
328 seealsoJoin(@parts[0 .. 2]), @parts[3 .. $#parts])) {
329 return @links; }
330 # try any delimiter as possibly a separator between individual entries;
331 # and recurse to handle next delimiter
332 elsif (($link = lookupSeealsoPhrase($doc, $allphrases, $contexttree, $parts[0]))
333 && (@links = seealsoSearch_rec($doc, $allphrases, $contexttree,
334 @parts[2 .. $#parts]))) {
335 return ($link, cdr($parts[1]), @links); }
336 return; }
337  
338 sub car { return $$_[0][0]; }
339  
340 sub cdr {
341 my ($key, @xml) = @{ $_[0] };
342 return @xml; }
343  
344 # Reassemble a partition (list of [key,xml] pairs) into a single such pair.
345 sub seealsoJoin {
346 my (@parts) = @_;
347 return [getIndexContentKey(join('', map { $$_[0] } @parts)), map { cdr($_) } @parts]; }
348  
349 # Look for single phrase either within one of the levels of the current $contexttree,
350 # or at top-level. Try it as-is, or ignoring commas, and/or case-differences.
351 sub lookupSeealsoPhrase {
352 my ($doc, $allphrases, $contexttree, $pair) = @_;
353 my ($phrase, @xml) = @$pair;
354 # concoct various phrases to search for
355 my $pnc = $phrase; $pnc =~ s/,\s*/ /sg; # Ignore punct?
356 my $ps = $phrase; $ps =~ s/(\w+)s\b/$1/sg; # Ignore plurals?
357 my $psnc = $ps; $psnc =~ s/,\s*/ /sg; # Ignore punct AND plurals?
358 my $pnlvl = $phrase; $pnlvl =~ s/,\s*/./sg; # Convert punct to levels?
359 foreach my $trial ($phrase, lc($phrase),
360 $pnc, lc($pnc),
361 $ps, lc($ps),
362 $psnc, lc($psnc),
363 $pnlvl, lc($pnlvl),
364 ) {
365 my $t = $contexttree;
366 while ($t) {
367 if (my $id = $$allphrases{ ($$t{fullphrasetext} ? $$t{fullphrasetext} . " " : '') . $trial }) {
368 return ['ltx:ref', { idref => $id }, @xml]; }
369 $t = $$t{parent}; } }
370 return; }
371  
372 # Partition a seealso (xml) phrase into a sequence of alternating
373 # candidate index phrases (which will be looked up)
374 # candidate delimiters (which potentially split the phrase or not;
375 # see discussion above about delimiters).
376 # This is analogous to a simple split, but that
377 # (a) the argument is XML, with the pieces of delimiter ("," space, "and"...)
378 # potentially distributed amongst distinct xml elements, due to styling.
379 # (b) we want to preserve the XML associated with each phrase & delimiter
380 # in order to fill-in and separate the resulting ltx:ref's
381 # Messy!
382 sub seealsoPartition {
383 my ($doc, $see) = @_;
384 my @parts = seealsoPartition_aux($doc, $see);
385 # Combine adjacent conjunctions & punctuation chunks
386 my @result = (shift(@parts));
387 while (@parts) {
388 my $next = shift(@parts);
389 my $prev_is = ($result[-1][0] =~ /^,?\s*(?:,|\.|\s+|\band\s+also|\band|\bor)\s*$/);
390 my $next_is = ($$next[0] =~ /^(?:,|\.|\s+|and\b|or\b)/);
391 # If either BOTH or NEITHER prev & next are delimiters, combine them.
392 if (!($prev_is xor $next_is)) {
393 my ($k, @x) = @$next;
394 $result[-1][0] .= $k;
395 push(@{ $result[-1] }, @x); }
396 else {
397 push(@result, $next); } }
398 # Now merge any adjacent phrase and/or space chunks into candidate phrase
399 @parts = @result; @result = (shift(@parts));
400 while (@parts) {
401 my $next = shift(@parts);
402 # If next is pure space, combine with prev AND following!
403 if (($$next[0] =~ /^\s+$/s) && scalar(@parts)) {
404 my ($k1, @x1) = @$next;
405 my ($k2, @x2) = @{ shift(@parts) };
406 $result[-1][0] .= $k1 . $k2;
407 push(@{ $result[-1] }, @x1, @x2); }
408 else {
409 push(@result, $next); } }
410 return @result; }
411  
412 # Recursively split the XML $see into pure phrase or delimiter chunks.
413 # we'll still need to combine adjacent chunks appropriately (see above).
414 sub seealsoPartition_aux {
415 my ($doc, $see) = @_;
416 my @result = ();
417 foreach my $ch ($see->childNodes) {
418 my $t = $ch->nodeType;
419 if ($t == XML_TEXT_NODE) {
420 my $string = $ch->textContent;
421 while ($string) {
422 if ($string =~ s/^(,|\.|\s+|and\s+also\b|and\b|or\b)//) {
423 push(@result, [$1, $1]); }
424 elsif ($string =~ s/^([^,\.\s]+)//) {
425 push(@result, [getIndexContentKey($1), $1]); } }
426 push(@result, [getIndexContentKey($string), $string]) if $string; }
427 elsif ($t != XML_ELEMENT_NODE) { }
428 else {
429 my $tag = $doc->getQName($ch);
430 if ($tag =~ /^(ltx:text|ltx:emph)$/) {
431 my $attr = { map { ($_ => $ch->getAttribute($_)) } $ch->attributes };
432 push(@result, map { [$$_[0], [$tag, $attr, cdr($_)]] } seealsoPartition_aux($doc, $ch)); }
433 else {
434 push(@result, [getIndexContentKey($ch), $ch]); }
435 } }
436 return @result; }
437  
438 # ================================================================================
439 sub conjoin {
440 my (@items) = @_;
441 my @result = ();
442 if (@items) {
443 push(@result, shift(@items));
444 while (@items) {
445 push(@result, ", ", shift(@items)); } }
446 return @result; }
447  
448 # ================================================================================
449 1;
450