lib/LaTeXML/Post/MakeBibliography.pm untested

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