lib/LaTeXML/Post/MakeBibliography.pm untested

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