lib/LaTeXML/Post/MakeBibliography.pm untested

filter: Statementstmt 0.0% 0 / 610 Branchbran 0.0% 0 / 220 Conditioncond 0.0% 0 / 94 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 25 totaltotal 0.0% 0 / 984 CC 111 SCAR 63.6
CC
111
Cov
0%
formatBibEntry
1560.0
getBibEntries
600.0
getBibliographies
380.0
CRAP 577.1
1 # /=====================================================================\ #
2 # | LaTeXML::Post::MakeBibliography | #
3 # | Make an bibliography from cited entries | #
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::MakeBibliography;
13 use strict;
14 use warnings;
15 use LaTeXML::Util::Pathname;
16 use LaTeXML::Common::XML;
17 use LaTeXML::Util::Radix;
18 use charnames qw(:full);
19 use LaTeXML::Post;
20 use base qw(LaTeXML::Post::Collector);
21  
22 # These are really constant, but set at bottom, for readability
23 our %FMT_SPEC; # CONSTANT
24 our @META_BLOCK; # CONSTANT
25  
26 # Options:
27 # bibliographies : list of xml file names containing bibliographies (from bibtex)
28 # split : whether the split into separate pages by initial.
29 # NOTE:
30 # Ultimately needs to respond to the desired bibligraphic style
31 # Currently set up primarily for author-year
32 # What about numerical citations? (how would we split the bib?)
33 # But we should presumably encode a number anyway...
34 sub new {
35 my ($class, %options) = @_;
36 my $self = $class->SUPER::new(%options);
37 $$self{split} = $options{split};
38 $$self{bibliographies} = $options{bibliographies};
39 return $self; }
40  
41 sub toProcess {
42 my ($self, $doc) = @_;
43 return $doc->findnodes('//ltx:bibliography'); }
44  
45 # Whooo, this is turning into a confusing API!
46 # Potentially multiple biblist's in each document
47 # potentially each one split into multiple output documents (need that option!)
48 # Inevitably duplicates?
49 sub process {
50 my ($self, $doc, @bibs) = @_;
51 my @docs = ($doc);
52 foreach my $bib (@bibs) {
53 next if $doc->findnodes('.//ltx:bibitem', $bib); # Already populated?
54  
55 local $LaTeXML::Post::MakeBibliography::NUMBER = 0;
56 local %LaTeXML::Post::MakeBibliography::STYLE =
57 (map { ($_ => $bib->getAttribute($_)) } qw(bibstyle citestyle sort));
58  
59 my $entries = $self->getBibEntries($doc, $bib);
60 # Remove any bibentry's (these should have been converted to bibitems)
61 $doc->removeNodes($doc->findnodes('//ltx:bibentry'));
62 foreach my $biblist ($doc->findnodes('//ltx:biblist')) {
63 $doc->removeNodes($biblist) unless element_nodes($biblist); }
64  
65 if ($$self{split}) {
66 # Separate by initial.
67 my $split = {};
68 foreach my $sortkey (keys %$entries) {
69 my $entry = $$entries{$sortkey};
70 $$split{ $$entry{initial} }{$sortkey} = $entry; }
71 @docs = map { $self->rescan($_) }
72 $self->makeSubCollectionDocuments($doc, $bib,
73 map { ($_ => $self->makeBibliographyList($doc, $bib, $_, $$split{$_})) }
74 sort keys %$split); }
75 else {
76 $doc->addNodes($bib, $self->makeBibliographyList($doc, $bib, undef, $entries));
77 # @docs = ($self->rescan($doc)); }
78 $self->rescan($doc); } }
79 return @docs; }
80  
81 # Try to preserve the original form & case of the provided Bibkeys
82 # HOWEVER, we downcase them before indexing & looking them up!!!!
83 sub normalizeBibKey {
84 my ($key) = @_;
85 return lc($key); }
86  
87 # ================================================================================
88 # Bibliographies can be specified either
89 # within the document (on ltx:bibliography, due to \bibliography{foo}
90 # or from an option to new (typically coming from the command line).
91 # The commandline option OVERRIDES the internal list (to avoid clashes)
92 #
93 # In the fist case, we only get names, (no bib extension, let alone xml)
94 # but we should look for pre-compiled versions of the bib anyway (pref foo.bib.xml)
95 # In the latter case, we may get pathnames OR literals OR even an XML Document object.
96 # literals can be bibtex (but eventually serialized XML should be allowed).
97 # When XML is supplied, it is assumed to contain an ltx:bibliography containing a ltx:biblist.
98 # In principle, we ought to look for named files also in the file cache (eg. from {filecontents})
99 sub getBibliographies {
100 my ($self, $doc) = @_;
101 my @bibnames = ();
102 my $fromBibliography = 0; # coming from an 'ltx:bibliography'
103 # use the commandline bibliographies, if explicitly given.
104 if ($$self{bibliographies} && scalar(@{ $$self{bibliographies} })) {
105 @bibnames = @{ $$self{bibliographies} }; }
106 else {
107 my $bibnode = $doc->findnode('//ltx:bibliography');
108 if (my $files = $bibnode->getAttribute('files')
109 || $bibnode->parentNode->getAttribute('files') # !!!!!
110 ) {
111 $fromBibliography = 1;
112 @bibnames = split(',', $files); } }
113 my @paths = $doc->getSearchPaths;
114 my @bibs = ();
115 my @rawbibs = ();
116 # Collect the "ready" bibliographies, while accumulating all raw sources for a single conversion pass
117 foreach my $bib (@bibnames) {
118 my $ref = ref $bib;
119 my $bibdoc;
120 if ($ref && ($ref eq 'LaTeXML::Post::Document')) { # It's already a Post::Document (somehow).
121 $bibdoc = $bib; }
122 elsif ($ref && ($ref eq 'XML::LibXML::Document')) { # Or it's a raw XML document?
123 $bibdoc = $doc->new($bib, sourceDirectory => '.'); }
124 elsif ($ref) {
125 Error('unexpected', $ref, $self,
126 "Don't know how to convert '$bib' (a '$ref') into a Bibliography document"); }
127 elsif (pathname_is_literaldata($bib)) {
128 push(@rawbibs, $bib);
129 next; }
130 elsif ($bib =~ /\.xml$/) {
131 $bibdoc = $doc->newFromFile($bib); } # doc will do the searching...
132 elsif ($bib =~ /\.bib(?:\.xml)?$/ || $fromBibliography) {
133 # NOTE: We should also use kpsewhich to get the effects of $BIBINPUTS?
134 # NOTE: When better integrated with Core, should also check for cached bib documents.
135 my $xmlbib = $bib;
136 $xmlbib .= '.bib' if $fromBibliography && !($xmlbib =~ /\.bib$/);
137 if (my $xmlpath = pathname_find($xmlbib, paths => [@paths], types => ['xml'])) {
138 $bibdoc = $doc->newFromFile($xmlpath); } # doc will do the searching...
139 elsif (my $bibpath = pathname_find($bib, paths => [@paths], types => ['bib'])
140 || pathname_kpsewhich($bib)) {
141 push(@rawbibs, $bibpath);
142 next; }
143 else {
144 Error('missing_file', $bib, $self,
145 "Couldn't find Bibliography '$bib'",
146 "Searchpaths were " . join(',', @paths)); } }
147 if ($bibdoc) {
148 push(@bibs, $bibdoc); }
149 else {
150 Info('expected', $bib, $self,
151 "Couldn't find usable Bibliography for '$bib'"); } }
152 # Lastly, If we found any raw .bib files/literaldata, convert and include them.
153 if (@rawbibs) {
154 my $raw;
155 if (scalar(@rawbibs) == 1) { # Single, just convert as-is
156 $raw = $rawbibs[0]; }
157 else {
158 $raw = 'literal:';
159 for my $rawbib (@rawbibs) { # Multiple, arrange into a single conversion payload
160 if ($rawbib =~ s/literal\://) {
161 $raw .= $rawbib; }
162 else {
163 # TODO: Is this a memory concern for large bib files?
164 if (open(my $bibfh, '<', $rawbib)) {
165 $raw .= join("", <$bibfh>);
166 close $bibfh; }
167 else {
168 Info("open", $rawbib, $self, "Couldn't open file $rawbib"); } }
169 $raw .= "%\n"; } }
170 my $bibdoc = $self->convertBibliography($doc, $raw);
171 push(@bibs, $bibdoc) if $bibdoc; }
172 NoteLog("MakeBibliography: using bibliographies "
173 . join(',', map { (length($_) > 100 ? substr($_, 100) . '...' : $_) } @bibnames)
174 . "]");
175 return @bibs; }
176  
177 # This converts a bib into the corresponding XML
178 # $bib is either a filename or literal
179 # Note that for multiple bibliographies it is inefficient to prepare a session for EACH.
180 # However, we really shouldn't be preparing a new session anyway:
181 # In general, it should use the same STATE information as the main document,
182 # so IF that state is still around, we should use it!
183 # That's for future enhancement!!!
184 # Also, it probably doesn't make sense for the session to capture the log output;
185 # it should just continue dribbling out whereever it usually would go.
186 sub convertBibliography {
187 my ($self, $doc, $bib) = @_;
188 require LaTeXML;
189 require LaTeXML::Common::Config;
190 my @preload = (); # custom macros often used in e.g. howpublished field
191 # need to preload all packages used by the main article
192 my ($classdata, @packages) = $self->find_documentclass_and_packages($doc);
193 my ($class, $classoptions) = @$classdata;
194 if ($class) {
195  
196 if ($classoptions) {
197 push(@preload, "[$classoptions]$class.cls"); }
198 else {
199 push(@preload, "$class.cls"); } }
200 foreach my $po (@packages) {
201 my ($pkg, $options) = @$po;
202 if ($options) {
203 push(@preload, "[$options]$pkg.sty"); }
204 else {
205 push(@preload, "$pkg.sty"); } }
206 my $bibname = pathname_is_literaldata($bib) ? 'Anonymous Bib String' : $bib;
207 my $stage = "Recursive MakeBibliography $bibname";
208 ProgressSpinup($stage);
209 my $bib_config = LaTeXML::Common::Config->new(
210 recursive => 1,
211 cache_key => 'BibTeX',
212 type => "BibTeX",
213 post => 0,
214 format => 'dom',
215 whatsin => 'document',
216 whatsout => 'document',
217 includestyles => 1,
218 bibliographies => [],
219 (@preload ? (preload => [@preload]) : ()));
220 my $bib_converter = LaTeXML->get_converter($bib_config);
221 # Tricky and HACKY, we need to release the log to capture the inner workings separately.
222 # ->bind_log analog:
223 my $biblog = '';
224 ### my $biblog_handle;
225 ### open($biblog_handle, ">>", \$biblog) or Error("Can't redirect STDERR to log for inner bibliography converter!");
226 ### *BIB_STDERR_SAVED = *STDERR;
227 ### *STDERR = *$biblog_handle;
228 # end ->bind_log
229  
230 $bib_converter->prepare_session($bib_config);
231 my $response = $bib_converter->convert($bib);
232  
233 # ->flush_log analog:
234 ### close $biblog_handle;
235 ### *STDERR = *BIB_STDERR_SAVED;
236 # end ->flush_log
237  
238 # Trim log to look internal and report.
239 ### $biblog =~ s/^.+?\(Digesting/\n\(Digesting/s;
240 ### $biblog =~ s/Conversion complete:.+$//s;
241 ### print STDERR $biblog;
242 MergeStatus($$bib_converter{latexml}{state});
243  
244 ProgressSpindown($stage);
245 if (my $bibdoc = $$response{result}) {
246 return $doc->new($bibdoc, sourceDirectory => '.'); }
247 return; }
248  
249 # ================================================================================
250 # Get all cited bibentries from the requested bibliography files.
251 # Sort (cited) bibentries on author+year+title, [NOT on the key, or even proper BibTeX choices!!!]
252 # and then check whether author+year is unique!!!
253 # Returns a list of hashes containing:
254 # bibkey : the bibliographic entry's key
255 # bibentry : the bibentry node
256 # citations : array of bib keys that are cited somewhere within this bibentry
257 # referrers : array of ID's of places that refer to this bibentry
258 # suffix : a,b... if adjacent author/year are identical.
259 # NOTE: biblist's now have @lists to restrict to include ONLY
260 # those bibitems which have been referenced by bibref's for one of those lists!
261 # [If a bibref gives several lists, and entries for those lists end up in several bibliographies,
262 # first 'list' determines where the idref points]
263 sub getBibEntries {
264 my ($self, $doc, $bib) = @_;
265  
266 # First, scan the bib files for all ltx:bibentry's, (hash key is bibkey)
267 # Also, record the citations from each bibentry to others.
268 my %entries = ();
269 foreach my $bibdoc ($self->getBibliographies($doc)) {
270 my @lists = split(/\s+/, $doc->findnode('//ltx:bibliography')->getAttribute('lists') || 'bibliography');
271 foreach my $bibentry ($bibdoc->findnodes('//ltx:bibentry')) {
272 my $bibkey = normalizeBibKey($bibentry->getAttribute('key'));
273 my $bibid = $bibentry->getAttribute('xml:id');
274 $entries{$bibkey}{bibkey} = $bibkey;
275 $entries{$bibkey}{bibentry} = $bibentry;
276 $entries{$bibkey}{citations} = [map { normalizeBibKey($_) } grep { $_ } map { split(',', $_->value) }
277 $bibdoc->findnodes('.//@bibrefs', $bibentry)]; } }
278 # Now, collect all bibkeys that were cited in other documents (NOT the bibliography)
279 # And note any referrers to them (also only those outside the bib)
280 my @lists = split(/\s+/, $bib->getAttribute('lists') || 'bibliography');
281 my $citestar = grep { $$self{db}->lookup("BIBLABEL:$_:*"); } @lists;
282  
283 my @queue = ();
284 foreach my $dbkey ($$self{db}->getKeys) {
285 if ($dbkey =~ /^BIBLABEL:(.*?):(.*)$/) {
286 my ($list, $bibkey) = ($1, $2);
287 next unless grep { $_ eq $list; } @lists;
288 my $bibdbentry = $$self{db}->lookup($dbkey);
289 if (my $referrers = $bibdbentry->getValue('referrers')) {
290 foreach my $refr (keys %$referrers) {
291 my ($rid, $e, $t) = ($refr, undef, undef);
292 while ($rid && ($e = $$self{db}->lookup("ID:$rid")) && (($t = ($e->getValue('type') || '')) ne 'ltx:bibitem')) {
293 $rid = $e->getValue('parent'); }
294 if (!$e) {
295 Warn('expected', 'entry', undef,
296 "Didn't find an entry for reference id=$rid"); }
297 elsif ($t ne 'ltx:bibitem') {
298 $entries{$bibkey}{referrers}{$refr} = 1; } }
299 push(@queue, $bibkey) if keys %{ $entries{$bibkey}{referrers} }; }
300 elsif ($citestar) { # If \cite{*} include all of them.
301 push(@queue, $bibkey); } } }
302  
303 # For each bibkey in the queue, complete and include the entry
304 # And add any keys cited from within each include entry
305 my %seen_keys = ();
306 my %missing_keys = ();
307 my $included = {}; # included entries (hash key is sortkey)
308 while (my $bibkey = shift(@queue)) {
309 next if $seen_keys{$bibkey}; # Done already.
310 $seen_keys{$bibkey} = 1;
311 next if $bibkey eq '*';
312 if (my $bibentry = $entries{$bibkey}{bibentry}) {
313 my $entry = $entries{$bibkey};
314 # Extract names, year and title from bibentry.
315 my $names = '';
316 my $sortnames = '';
317 my @names = $doc->findnodes('ltx:bib-name[@role="author"]', $bibentry);
318 @names = $doc->findnodes('ltx:bib-name[@role="editor"]', $bibentry) unless @names;
319 if (my $n = $doc->findnode('ltx:bib-key', $bibentry)) {
320 $sortnames = $names = $n->textContent; }
321 elsif (scalar(@names)) {
322 $sortnames = join(' ', map { getNameText($doc, $_) } @names);
323 my @ns = map { $_ && $_->textContent } map { $doc->findnodes('ltx:surname', $_) } @names;
324 if (@ns > 2) { $names = $ns[0] . ' et al'; }
325 elsif (@ns > 1) { $names = $ns[0] . ' and ' . $ns[1]; }
326 else { $names = $ns[0]; } }
327 elsif (my $t = $doc->findnode('ltx:bib-title', $bibentry)) {
328 $sortnames = $names = $t->textContent; }
329 my $date = $doc->findnode('ltx:bib-date[@role="publication"] | ltx:bib-type', $bibentry);
330 my $title = $doc->findnode('ltx:bib-title', $bibentry);
331 $date = ($date ? $date->textContent : '');
332 $date = $1 if $date && $date =~ /^(\d\d\d\d)/;
333 $title = ($title ? $title->textContent : '');
334 $$entry{ay} = "$names.$date";
335 $$entry{initial} = $doc->initial($names, 1);
336 # Include this entry keyed using a sortkey.
337 $$included{ lc(join('.', $sortnames, $date, $title, $bibkey)) } = $entry;
338 # And, since we're including this entry, we'll need to include any that it cites!
339 push(@queue, @{ $$entry{citations} }) if $$entry{citations}; }
340 else {
341 $missing_keys{$bibkey} = 1; } }
342 # Now that we know which entries will be included, note their citations as bibreferrers.
343 foreach my $sortkey (keys %$included) {
344 my $entry = $$included{$sortkey};
345 my $bibkey = $$entry{bibkey};
346 map { $entries{ normalizeBibKey($_) }{bibreferrers}{$bibkey} = 1 } @{ $$entry{citations} }; }
347  
348 NoteLog("MakeBibliography: " . (scalar keys %entries) . " bibentries, " . (scalar keys %$included) . " cited");
349 Warn('expected', 'bibkeys', undef,
350 "Missing bibkeys " . join(', ', sort keys %missing_keys)) if keys %missing_keys;
351  
352 # Finally, sort the bibentries according to author+year+title+bibkey
353 # If any neighboring entries have same author+year, set a suffix: a,b,...
354 # Actually, it isn't so much if they are adjacent; if author+year isn't unique, need a suffix
355 my @sortkeys = $doc->unisort(keys %$included);
356 my %suffixes = ();
357 while (my $sortkey = shift(@sortkeys)) {
358 # my $i=0;
359 # while(@sortkeys && ($$included{$sortkey}{ay} eq $$included{$sortkeys[0]}{ay})){
360 # $$included{$sortkey}{suffix}='a';
361 # $$included{$sortkeys[0]}{suffix} = chr(ord('a')+(++$i));
362 # shift(@sortkeys); }
363 my $entry = $$included{$sortkey};
364 my $ay = $$entry{ay};
365 if (defined $suffixes{$ay}) {
366 my $prev = $suffixes{$ay};
367 if (!$$prev{suffix}) {
368 $$prev{suffix_counter} = 1;
369 $$prev{suffix} = radix_alpha($$prev{suffix_counter}); }
370 $$entry{suffix_counter} = $$prev{suffix_counter} + 1;
371 $$entry{suffix} = radix_alpha($$entry{suffix_counter}); }
372 $suffixes{$ay} = $entry;
373 # HACKERY: AFTER all the sorting have been done, remove <ERROR role="sort"> nodes.
374 # These may have been inserted to alter sorting, eg \NOOP{a}...
375 foreach my $sortnode ($doc->findnodes('//ltx:ERROR[@class="sort"]', $$entry{bibentry})) {
376 $sortnode->parentNode->removeChild($sortnode); }
377 }
378 return $included; }
379  
380 sub getNameText {
381 my ($doc, $namenode) = @_;
382 my $surname = $doc->findnodes('ltx:surname', $namenode);
383 my $givenname = $doc->findnodes('ltx:givenname', $namenode);
384 return ($surname && $givenname ? $surname . ' ' . $givenname : $surname || $givenname); }
385  
386 # ================================================================================
387 # Convert hash of bibentry(s) into biblist of bibitem(s)
388  
389 sub makeBibliographyList {
390 my ($self, $doc, $bib, $initial, $entries) = @_;
391 my $id = $bib->getAttribute('xml:id')
392 || $doc->getDocumentElement->getAttribute('xml:id') || 'bib';
393 $id .= ".L1";
394 $id .= ".$initial" if $initial;
395 return ['ltx:biblist', { 'xml:id' => $id },
396 map { $self->formatBibEntry($doc, $bib, $$entries{$_}) } $doc->unisort(keys %$entries)]; }
397  
398 # ================================================================================
399 # NOTE: With multiple bibliographies, the ID of the bibentry isn't necessarily
400 # the ID in the "local" bibliography! (ie. bibentry can be repeated in the document!)
401 sub formatBibEntry {
402 my ($self, $doc, $bib, $entry) = @_;
403 my $bibentry = $$entry{bibentry};
404 my $id = $bibentry->getAttribute('xml:id');
405 my $key = $bibentry->getAttribute('key');
406 my $type = $bibentry->getAttribute('type');
407 my @blockspecs = @{ $FMT_SPEC{$type} || [] };
408  
409 # Patch the entry's id in case there are multiple bibs.
410 if (my $bibid = $bib->getAttribute('xml:id')
411 || $doc->getDocumentElement->getAttribute('xml:id') || 'bib') {
412 $id =~ s/^bib//; $id = $bibid . $id; }
413  
414 local $LaTeXML::Post::MakeBibliography::SUFFIX = $$entry{suffix};
415 my $number = ++$LaTeXML::Post::MakeBibliography::NUMBER;
416  
417 Warn('unexpected', $type, undef,
418 "No formatting specification for bibentry of type '$type'") unless @blockspecs;
419  
420 #------------------------------
421 # Format the bibtag's
422 my @tags = ();
423 push(@tags, ['ltx:tag', { role => 'number', class => 'ltx_bib_number' }, $number]); # number tag
424  
425 # Set up authors and fullauthors tags
426 my @names = $doc->findnodes('ltx:bib-name[@role="author"]/ltx:surname', $bibentry);
427 @names = $doc->findnodes('ltx:bib-name[@role="editor"]/ltx:surname', $bibentry) unless @names;
428 my $etal = 0;
429 if (@names && ($names[-1]->toString eq 'others')) { # Magic!
430 $etal = 1; }
431 if (@names > 2) {
432 push(@tags, ['ltx:tag', { role => 'authors', class => 'ltx_bib_author' },
433 $doc->cloneNodes($names[0]->childNodes),
434 ['ltx:text', { class => 'ltx_bib_etal' }, ' et al.']]);
435 my @fnames = ();
436 foreach my $n (@names[0 .. $#names - 1]) {
437 push(@fnames, $n->childNodes, ', '); }
438 push(@tags, ['ltx:tag', { role => 'fullauthors', class => 'ltx_bib_author' },
439 $doc->cloneNodes(@fnames),
440 ' and ', $doc->cloneNodes($names[-1]->childNodes)]); }
441 elsif (@names > 1) {
442 push(@tags, ['ltx:tag', { role => 'authors', class => 'ltx_bib_author' },
443 $doc->cloneNodes($names[0]->childNodes),
444 ' and ', $doc->cloneNodes($names[1]->childNodes)]); }
445 elsif (@names) {
446 push(@tags, ['ltx:tag', { role => 'authors', class => 'ltx_bib_author' },
447 $doc->cloneNodes($names[0]->childNodes)]); }
448  
449 # Put a key tag, to use in place of authors if needed (esp for software, websites, etc)
450 my $keytag;
451 if ($keytag = $doc->findnode('ltx:bib-key', $bibentry)) {
452 push(@tags, ['ltx:tag', { role => 'key', class => 'ltx_bib_key' },
453 $doc->cloneNodes($keytag->childNodes)]); }
454  
455 my @year = ();
456 if (my $date = $doc->findnode('ltx:bib-date[@role="publication"]', $bibentry)) {
457 @year = $date->childNodes;
458 if (my $datetext = $date->textContent) {
459 if ($datetext =~ /^(\d\d\d\d)/) { # Extract 4 digit year, if any
460 @year = ($1); } }
461 push(@tags, ['ltx:tag', { role => 'year', class => 'ltx_bib_year' },
462 $doc->cloneNodes(@year), ($$entry{suffix} || '')]); }
463  
464 # Store a type tag, to use in place of year, if needed (esp for software, ...)
465 my $typetag;
466 if ($typetag = $doc->findnode('ltx:bib-type', $bibentry)) {
467 push(@tags, ['ltx:tag', { role => 'bibtype', class => 'ltx_bib_type' },
468 $doc->cloneNodes($typetag->childNodes)]); }
469  
470 # put in the title
471 if (my $title = $doc->findnode('ltx:bib-title', $bibentry)) {
472 push(@tags, ['ltx:tag', { role => 'title', class => 'ltx_bib_title' },
473 $doc->cloneNodes($title->childNodes)]); }
474  
475 # And finally, the refnum; we need to know the desired citation style!
476 # This is screwy!!!
477 # AND OF COURSE, we need to know the key before we know the suffix!!!
478 my $style = $LaTeXML::Post::MakeBibliography::STYLE{citestyle} || 'numbers';
479 $style = 'numbers' unless (@names || $keytag) && (@year || $typetag);
480 if ($style eq 'numbers') {
481 push(@tags, ['ltx:tag', { role => 'refnum', class => 'ltx_bib_key', open => '[', close => ']' }, $number]); }
482 elsif ($style eq 'AY') {
483 my @rfnames;
484 if (my @authors = $doc->findnodes('ltx:bib-name[@role="author"]/ltx:surname', $bibentry)) {
485 @rfnames = @authors; }
486 elsif (my @editors = $doc->findnodes('ltx:bib-name[@role="editor"]/ltx:surname', $bibentry)) {
487 @rfnames = @editors; }
488 else {
489 @rfnames = $keytag->childNodes; }
490 my $aa;
491 if (scalar(@rfnames) > 1) {
492 $aa = join('', map { substr($_->textContent, 0, 1); } @rfnames);
493 if (length($aa) > 3) {
494 $aa = substr($aa, 0, 3) . "+"; } }
495 else {
496 $aa = uc(substr($rfnames[0]->textContent, 0, 3)); }
497 my $yrtext = (@year ? join('', map { (ref $_ ? $_->textContent : $_); } @year) : '');
498 my $yy = (length($yrtext) >= 2 ? substr($yrtext, 2, 2) : $yrtext);
499 push(@tags, ['ltx:tag', { role => 'refnum', class => 'ltx_bib_abbrv', open => '[', close => ']' },
500 $aa . $yy . ($$entry{suffix} || '')]); }
501  
502 else {
503 shift(@blockspecs); # Skip redundant 1st block!!
504 my @rfnames;
505 if (my @authors = $doc->findnodes('ltx:bib-name[@role="author"]', $bibentry)) {
506 @rfnames = do_authors(@authors); }
507 elsif (my @editors = $doc->findnodes('ltx:bib-name[@role="editor"]', $bibentry)) {
508 @rfnames = do_editorsA(@editors); }
509 else {
510 @rfnames = $keytag->childNodes; }
511 my @rfyear = (@year ? (@year, ($$entry{suffix} || ''))
512 : ($typetag ? $typetag->childNodes : ()));
513 push(@tags, ['ltx:tag', { role => 'refnum', class => 'ltx_bib_author-year' },
514 $doc->cloneNodes(@rfnames), ' (', $doc->cloneNodes(@rfyear), ')']); }
515  
516 #------------------------------
517 # Format the data in blocks, with the first being bib-label, rest bibblock.
518 my @blocks = ();
519 foreach my $blockspec (@blockspecs) {
520 my @x = ();
521 foreach my $row (@$blockspec) {
522 my ($xpath, $punct, $pre, $class, $op, $post) = @$row;
523 my $negated = $xpath =~ s/^!\s*//;
524 my @nodes = ($xpath eq 'true' ? () : $doc->findnodes($xpath, $bibentry));
525 next if ($xpath ne 'true') && ($negated ? @nodes : !@nodes);
526 push(@x, $punct) if $punct && @x;
527 push(@x, $pre) if $pre;
528 push(@x, ['ltx:text', { class => 'ltx_bib_' . $class }, &$op($doc->cloneNodes(@nodes))]) if $op;
529 push(@x, $post) if $post; }
530 push(@blocks, ['ltx:bibblock', { 'xml:space' => 'preserve' }, @x]) if @x;
531 }
532 # Add a Cited by block.
533  
534 my @citedby = map { ['ltx:ref', { idref => $_, show => 'typerefnum' }] }
535 sort keys %{ $$entry{referrers} };
536 push(@citedby, ['ltx:bibref', { bibrefs => join(',', sort keys %{ $$entry{bibreferrers} }), show => 'refnum' }])
537 if $$entry{bibreferrers};
538 push(@blocks, ['ltx:bibblock', { class => 'ltx_bib_cited' },
539 "Cited by: ", $doc->conjoin(",\n", @citedby), '.']) if @citedby;
540  
541 return ['ltx:bibitem', { 'xml:id' => $id, key => $key, type => $type, class => "ltx_bib_$type" },
542 (@tags ? (['ltx:tags', {}, @tags]) : ()),
543 @blocks]; }
544  
545 # ================================================================================
546 # Formatting aids.
547 sub do_any {
548 my (@stuff) = @_;
549 return @stuff; }
550  
551 # Stuff for Author(s) & Editor(s)
552 sub do_name {
553 my ($node) = @_;
554 # NOTE: This should be a formatting option; use initials or full first names.
555 my $first = $LaTeXML::Post::DOCUMENT->findnode('ltx:givenname', $node);
556 if ($first) { # && use initials
557 $first = join('', map { (/\.$/ ? "$_ " : (/^(.)/ ? "$1. " : '')) }
558 split(/\s/, $first->textContent)); }
559 else {
560 $first = (); }
561 my $sur = $LaTeXML::Post::DOCUMENT->findnode('ltx:surname', $node);
562 # Why, oh Why do we need the _extra_ cloneNode ???
563 return ($first, $sur->cloneNode(1)->childNodes); }
564  
565 sub do_names {
566 my (@names) = @_;
567 my @stuff = ();
568 my $sep = (scalar(@names) > 2 ? ', ' : ' ');
569 my $etal = 0;
570 if (@names && ($names[-1]->textContent eq 'others')) { # Magic!
571 pop(@names);
572 $etal = 1; }
573 my $n = scalar(@names);
574 while (my $name = shift(@names)) {
575 if (@stuff) {
576 push(@stuff, $sep);
577 push(@stuff, 'and ') if !$etal && !@names; }
578 push(@stuff, do_name($name)); }
579 if ($etal) {
580 push(@stuff, $sep, ['ltx:text', { class => 'ltx_bib_etal' }, 'et al.']); }
581 return @stuff; }
582  
583 sub do_names_short {
584 my (@names) = @_;
585 if (@names > 2) {
586 return ($names[0]->childNodes, ' ', ['ltx:text', { class => 'ltx_bib_etal' }, 'et al.']); }
587 elsif (@names > 1) {
588 return ($names[0]->childNodes, ' and ', $names[1]->childNodes); }
589 elsif (@names) {
590 return ($names[0]->childNodes); } }
591  
592 sub do_authors {
593 my (@stuff) = @_;
594 return do_names(@stuff); }
595  
596 sub do_editorsA { # Should be used in citation tags?
597 my (@stuff) = @_;
598 my @n = do_names(@stuff);
599 if (scalar(@stuff) > 1) { push(@n, " (Eds.)"); }
600 elsif (scalar(@stuff)) { push(@n, " (Ed.)"); }
601 return @n; }
602  
603 sub do_editorsB {
604 my (@stuff) = @_;
605 my @x = do_names(@stuff);
606 if (scalar(@stuff) > 1) { push(@x, " Eds."); }
607 elsif (scalar(@stuff)) { push(@x, " Ed."); }
608 return (@x ? ("(", @x, ")") : ()); }
609  
610 sub do_year {
611 my (@stuff) = @_;
612 return (' (', @stuff, @LaTeXML::Post::MakeBibliography::SUFFIX, ')'); }
613  
614 sub do_type {
615 my (@stuff) = @_;
616 return ('(', @stuff, ')'); }
617  
618 # Other fields.
619 #### sub do_title { (['ltx:text',{font=>'italic'},@_]); }
620 sub do_title {
621 my (@stuff) = @_;
622 return (@stuff); }
623 ###sub do_bold { (['ltx:text',{font=>'bold'},@_]); }
624 sub do_edition {
625 my (@stuff) = @_;
626 return (@stuff, " edition"); } # If a number, should convert to cardinal!
627  
628 sub do_thesis_type {
629 my (@stuff) = @_;
630 return @stuff; }
631  
632 sub do_pages {
633 my (@stuff) = @_;
634 return (" pp." . pack('U', 0xA0), @stuff); } # Non breaking space
635  
636 sub do_crossref {
637 my ($node, @stuff) = @_;
638 return (['ltx:cite', {},
639 ['ltx:bibref', { bibrefs => $node->getAttribute('bibrefs'), show => 'title, author' }]]); }
640  
641 my $LINKS = # CONSTANT
642 "ltx:bib-links | ltx:bib-review | ltx:bib-identifier | ltx:bib-url";
643  
644 sub do_links {
645 my (@nodes) = @_;
646 my @links = ();
647 my $doc = $LaTeXML::Post::DOCUMENT;
648 foreach my $node (@nodes) {
649 my $scheme = $node->getAttribute('scheme') || '';
650 my $href = $node->getAttribute('href');
651 my $tag = $doc->getQName($node);
652 if (($tag eq 'ltx:bib-identifier') || ($tag eq 'ltx:bib-review')) {
653 if ($href) {
654 push(@links, ['ltx:ref', { href => $href, class => "$scheme ltx_bib_external" },
655 $doc->cloneNodes($node->childNodes)]); }
656 else {
657 push(@links, ['ltx:text', { class => "$scheme ltx_bib_external" },
658 $doc->cloneNodes($node->childNodes)]); } }
659 elsif ($tag eq 'ltx:bib-links') {
660 push(@links, ['ltx:text', { class => "ltx_bib_external" },
661 $doc->cloneNodes($node->childNodes)]); }
662 elsif ($tag eq 'ltx:bib-url') {
663 push(@links, ['ltx:ref', { href => $href, class => 'ltx_bib_external' },
664 $doc->cloneNodes($node->childNodes)]); } }
665  
666 @links = map { (",\n", $_) } @links; # non-string join()
667 return @links[1 .. $#links]; }
668  
669 # ================================================================================
670 # Formatting specifications.
671 # Adpated from amsrefs.sty
672 #BEGIN{
673  
674 # For each bibliographic type,
675 # the specification is an array representing each bibblock.
676 # Each biblock is an array of field specifications.
677 # Each field specification is:
678 # [xpath, punct, prestring, operatorname, poststring]
679 # NOTE That the first block is only shown for numeric style,
680 # since otherwise athors will already be shown in the bibtag@refnum!!!
681 # Ugh...
682  
683 # [xpath punct pre class formatter post ]
684 @META_BLOCK =
685 ([['ltx:bib-note', '', "Note: ", 'note', \&do_any, '']],
686 [[$LINKS, '', 'External Links: ', 'links', \&do_links, '']]);
687  
688 %FMT_SPEC =
689 # [xpath punct pre class formatter post ]
690 (article =>
691 [[['ltx:bib-name[@role="author"]', '', '', 'author', \&do_authors, ''],
692 ['ltx:bib-date[@role="publication"]', '', '', 'year', \&do_year, '']],
693 [['ltx:bib-title', '', '', 'title', \&do_title, '.']],
694 [['ltx:bib-part[@role="part"]', '', '', 'part', \&do_any, ''],
695 ['ltx:bib-related/ltx:bib-title', ', ', '', 'journal', \&do_any, ''],
696 ['ltx:bib-part[@role="volume"]', ' ', '', 'volume', \&do_any, ''],
697 ['ltx:bib-part[@role="number"]', ' ', '(', 'number', \&do_any, ')'],
698 ['ltx:bib-status', ', ', '(', 'status', \&do_any, ')'],
699 ['ltx:bib-part[@role="pages"]', ', ', '', 'pages', \&do_pages, ''],
700 ['ltx:bib-language', ' ', '(', 'language', \&do_any, ')'],
701 ['true', '.']],
702 @META_BLOCK],
703 book =>
704 [[['ltx:bib-name[@role="author"]', '', '', 'author', \&do_authors, ''],
705 ['ltx:bib-name[@role="editor"]', '', '', 'editor', \&do_editorsA, ''],
706 ['ltx:bib-date[@role="publication"]', '', '', 'year', \&do_year, '']],
707 [['ltx:bib-title', '', '', 'title', \&do_title, '.']],
708 [['ltx:bib-type', '', '', 'type', \&do_any, ''],
709 ['ltx:bib-edition', ', ', '', 'edition', \&do_edition, ''],
710 ['ltx:bib-part[@role="series"]', ', ', '', 'series', \&do_any, ''],
711 ['ltx:bib-part[@role="volume"]', ', ', 'Vol. ', 'volume', \&do_any, ''],
712 ['ltx:bib-part[@role="part"]', ', ', 'Part ', 'part', \&do_any, ''],
713 ['ltx:bib-publisher', ', ', ' ', 'publisher', \&do_any, ''],
714 ['ltx:bib-organization', ', ', ' ', 'publisher', \&do_any, ''],
715 ['ltx:bib-place', ', ', '', 'place', \&do_any, ''],
716 ['ltx:bib-status', ' ', '(', 'status', \&do_any, ')'],
717 ['ltx:bib-language', ' ', '(', 'language', \&do_any, ')'],
718 ['true', '.']],
719 @META_BLOCK],
720 'incollection' =>
721 [[['ltx:bib-name[@role="author"]', '', '', 'author', \&do_authors, ''],
722 ['ltx:bib-date[@role="publication"]', '', '', 'year', \&do_year, '']],
723 [['ltx:bib-title', '', '', 'title', \&do_title, '.']],
724 [['ltx:bib-type', '', '', 'type', \&do_any, ''],
725 # Show crossref if any
726 ['ltx:bib-related[@bibrefs]', ' ', 'See ', 'crossref', \&do_crossref, ','],
727 # if NO crossref, used embedded editors & booktitle.
728 # ['ltx:bib-related[@type="book"]/ltx:bib-title', ' ', 'in ', 'inbook', \&do_title, ',']
729 ['ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-title',
730 ' ', 'In ', 'inbook', \&do_title, ','],
731 ['ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-name[@role="editor"]',
732 ' ', ' ', 'editor', \&do_editorsA, ','],
733 ],
734 [['ltx:bib-edition', '', '', 'edition', \&do_edition, ''],
735 ['ltx:bib-name[@role="editor"]', ', ', '', 'editor', \&do_editorsB, ''],
736 ['ltx:bib-related/ltx:bib-part[@role="series"]', ', ', '', 'series', \&do_any, ''],
737 ['ltx:bib-related/ltx:bib-part[@role="volume"]', ', ', 'Vol. ', 'volume', \&do_any, ''],
738 ['ltx:bib-related/ltx:bib-part[@role="part"]', ', ', 'Part ', 'part', \&do_any, ''],
739 ['ltx:bib-publisher', ', ', ' ', 'publisher', \&do_any, ''],
740 ['ltx:bib-organization', ', ', '', 'publisher', \&do_any, ''],
741 ['ltx:bib-place', ', ', '', 'place', \&do_any, ''],
742 ['ltx:bib-part[@role="pages"]', ', ', '', 'pages', \&do_pages, ''],
743 ['ltx:bib-status', ' ', '(', 'status', \&do_any, ')'],
744 ['ltx:bib-language', ' ', '(', 'language', \&do_any, ')'],
745 ['true', '.']],
746 @META_BLOCK],
747 report =>
748 [[['ltx:bib-name[@role="author"]', '', '', 'author', \&do_authors, ''],
749 ['ltx:bib-name[@role="editor"]', '', '', 'editor', \&do_editorsA, ''],
750 ['ltx:bib-date[@role="publication"]', '', '', 'year', \&do_year, '']],
751 [['ltx:bib-title', '', '', 'title', \&do_title, '.']],
752 [['ltx:bib-type', '', '', 'type', \&do_any, '']],
753 [['ltx:bib-part[@role="number"]', '', 'Technical Report ', 'number', \&do_any, ''],
754 ['ltx:bib-part[@role="series"]', ', ', '', 'series', \&do_any, ''],
755 ['ltx:bib-part[@role="volume"]', ', ', 'Vol. ', 'volume', \&do_any, ''],
756 ['ltx:bib-part[@role="part"]', ', ', 'Part ', 'part', \&do_any, ''],
757 ['ltx:bib-publisher', ', ', ' ', 'publisher', \&do_any, ''],
758 ['ltx:bib-organization', ', ', ' ', 'publisher', \&do_any, ''],
759 ['ltx:bib-place', ', ', ' ', 'place', \&do_any, ''],
760 ['ltx:bib-status', ', ', '(', 'status', \&do_any, ')'],
761 ['ltx:bib-language', ' ', '(', 'language', \&do_any, ')'],
762 ['true', '.']],
763 @META_BLOCK],
764 thesis =>
765 [[['ltx:bib-name[@role="author"]', '', '', 'author', \&do_authors, ''],
766 ['ltx:bib-name[@role="editor"]', '', '', 'editor', \&do_editorsA, ''],
767 ['ltx:bib-date[@role="publication"]', '', '', 'year', \&do_year, '']],
768 [['ltx:bib-title', '', '', 'title', \&do_title, '.']],
769 [['ltx:bib-type', ' ', '', 'type', \&do_thesis_type, ''],
770 ['ltx:bib-part[@role="part"]', ', ', 'Part ', 'part', \&do_any, ''],
771 ['ltx:bib-publisher', ', ', '', 'publisher', \&do_any, ''],
772 ['ltx:bib-organization', ', ', '', 'publisher', \&do_any, ''],
773 ['ltx:bib-place', ', ', '', 'place', \&do_any, ''],
774 ['ltx:bib-status', ', ', '(', 'status', \&do_any, ')'],
775 ['ltx:bib-language', ', ', '(', 'language', \&do_any, ')'],
776 ['true', '.']],
777 @META_BLOCK],
778 website =>
779 [[['ltx:bib-name[@role="author"]', '', '', 'author', \&do_authors, ''],
780 ['ltx:bib-name[@role="editor"]', '', '', 'editor', \&do_editorsA, ''],
781 ['ltx:bib-date[@role="publication"]', '', '', 'year', \&do_year, ''],
782 ['ltx:title', '', '', 'title', \&do_any, ''],
783 ['ltx:bib-type', '', '', 'type', \&do_any, ''],
784 ['! ltx:bib-type', '', '', 'type', sub { ('(Website)'); }, '']],
785 [['ltx:bib-organization', ', ', ' ', 'publisher', \&do_any, ''],
786 ['ltx:bib-place', ', ', '', 'place', \&do_any, ''],
787 ['true', '.']],
788 @META_BLOCK],
789 software =>
790 [[['ltx:bib-key', '', '', 'key', \&do_any, ''],
791 ['ltx:bib-type', '', '', 'type', \&do_type, '']],
792 [['ltx:bib-title', '', '', 'title', \&do_any, '']],
793 [['ltx:bib-organization', ', ', ' ', 'publisher', \&do_any, ''],
794 ['ltx:bib-place', ', ', '', 'place', \&do_any, ''],
795 ['true', '.']],
796 @META_BLOCK],
797 );
798  
799 $FMT_SPEC{periodical} = $FMT_SPEC{book};
800 $FMT_SPEC{collection} = $FMT_SPEC{book};
801 $FMT_SPEC{proceedings} = $FMT_SPEC{book};
802 $FMT_SPEC{manual} = $FMT_SPEC{book};
803 $FMT_SPEC{misc} = $FMT_SPEC{book};
804 $FMT_SPEC{unpublished} = $FMT_SPEC{book};
805 $FMT_SPEC{booklet} = $FMT_SPEC{book};
806 $FMT_SPEC{'collection.article'} = $FMT_SPEC{incollection};
807 $FMT_SPEC{'proceedings.article'} = $FMT_SPEC{incollection};
808 $FMT_SPEC{inproceedings} = $FMT_SPEC{incollection};
809 $FMT_SPEC{inbook} = $FMT_SPEC{incollection};
810 $FMT_SPEC{techreport} = $FMT_SPEC{report};
811  
812 #}
813  
814 # ================================================================================
815 1;