PDFLibrarian/BibTeX.pm untested

filter: Statementstmt 0.0% 0 / 582 Branchbran 0.0% 0 / 172 Conditioncond 0.0% 0 / 73 MC/DCmcdc 0.0% 0 / 41 Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 919 CC 87 SCAR 58.6
CC
87
Cov
0%
format_bib
1122.0
edit_bib_in_fh
210.0
read_bib_from_file
182.0
CRAP 352.3
1 # Copyright (C) 2016--2026 Karl Wette
2 #
3 # This file is part of App::PDFLibrarian.
4 #
5 # App::PDFLibrarian is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or (at
8 # your option) any later version.
9 #
10 # App::PDFLibrarian is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with App::PDFLibrarian. If not, see <http://www.gnu.org/licenses/>.
17  
18 use v5.18;
19 use strict;
20 use warnings;
21 use utf8;
22 use open qw(:std :encoding(UTF-8));
23  
24 package App::PDFLibrarian::BibTeX;
25 $App::PDFLibrarian::BibTeX::VERSION = '6.3.4';
26 use parent 'Exporter';
27  
28 use Capture::Tiny;
29 use Carp;
30 use Digest::SHA;
31 use Encode;
32 use File::ShareDir qw(dist_file);
33 use File::Temp;
34 use FindBin qw($Script);
35 use List::Util qw(max);
36 use PDF::API2;
37 use Scalar::Util qw(blessed);
38 use Text::BibTeX qw(:nameparts :joinmethods :macrosubs);
39 use Text::BibTeX::Bib;
40 use Text::BibTeX::NameFormat;
41 use Text::Unidecode;
42 use Text::Wrap;
43 use URI::Encode qw(uri_encode uri_decode);
44 use XML::LibXML;
45 use XML::LibXSLT;
46  
47 require Encode::Detect;
48  
49 use App::PDFLibrarian qw(%bibtex_macros);
50 use App::PDFLibrarian::Util qw(unique_list keyword_display_str parallel_loop remove_tex_markup remove_short_words replace_accents_with_latex);
51  
52 our @EXPORT_OK = qw(bib_checksum read_bib_from_str read_bib_from_file read_bib_from_pdf format_bib write_bib_to_fh write_bib_to_pdf edit_bib_in_fh find_dup_bib_keys format_bib_authors generate_bib_keys);
53  
54 # BibTeX database structure
55 my $structure = new Text::BibTeX::Structure('Bib');
56 foreach my $type ($structure->types()) {
57 $structure->add_fields($type, [qw(keyword title year file)], [qw(collaboration)]);
58 }
59 foreach my $type (qw(booklet manual misc)) {
60 $structure->add_fields($type, [qw(author)]);
61 }
62 $structure->add_fields("mastersthesis", [qw(type)]);
63 $structure->add_fields("misc", [qw(howpublished)]);
64  
65 # BibTeX field order
66 my @fieldorder = qw (
67 keyword
68 title
69 key author collaboration
70 journal school institution type
71 editor booktitle edition series
72 volume number issue chapter pages eid numpages
73 month year
74 publisher organization address isbn issn
75 howpublished
76 doi
77 archiveprefix primaryclass eprint
78 url adsurl
79 note annote comments
80 abstract
81 );
82  
83 1;
84  
85 sub bib_checksum {
86 my ($bibentry, @exclude) = @_;
87  
88 # generate a checksum for a BibTeX entry
89 push @exclude, 'checksum';
90 my $digest = Digest::SHA->new();
91 $digest->add($bibentry->type, $bibentry->key);
92 foreach my $bibfield (sort { $a cmp $b } $bibentry->fieldlist()) {
93 next if grep /^$bibfield$/, @exclude;
94 my $bibfieldvalue = $bibentry->get($bibfield);
95 $digest->add($bibfield, encode('ascii', $bibfieldvalue));
96 }
97  
98 return $digest->hexdigest;
99 }
100  
101 sub read_bib_from_str {
102 my ($bibstr) = @_;
103  
104 # read BibTeX entry from a string
105 my $bibentry = new Text::BibTeX::BibEntry $bibstr;
106 croak "$Script: failed to parse BibTeX entry" unless $bibentry->parse_ok;
107 $bibentry->{structure} = $structure;
108  
109 return $bibentry;
110 }
111  
112 sub read_bib_from_file {
113 my ($errors, $bibentries, $filename) = @_;
114 die unless ref($errors) eq 'ARRAY';
115 die unless ref($bibentries) eq 'ARRAY';
116  
117 # initialise output arrays
118 @$errors = ();
119 @$bibentries = ();
120  
121 # check that the file contains non-comment, non-empty lines
122 {
123 my $nonempty = 1;
124 open(my $fh, "<:raw", $filename) or croak "$Script: could not open file '$filename': $!";
125 while (<$fh>) {
126 next if /^%/;
127 next if /^\s*$/;
128 $nonempty = 0;
129 last;
130 }
131 $fh->close();
132 return if $nonempty;
133 }
134  
135 # define BibTeX macros
136 foreach my $macro (keys %bibtex_macros) {
137 delete_macro($macro);
138 add_macro_text($macro, $bibtex_macros{$macro});
139 }
140  
141 # parse the BibTeX file, capturing any error messages
142 my $errmsgs;
143 {
144 croak "$Script: file '$filename' does not exist" unless -r $filename;
145 my $bib = Text::BibTeX::File->new($filename, "<:raw") or croak "$Script: could not open file '$filename'";
146 $bib->{structure} = $structure;
147 $errmsgs = Capture::Tiny::capture_merged {
148 while (my $bibentry = Text::BibTeX::BibEntry->new($bib)) {
149 next unless $bibentry->parse_ok;
150 next unless $bibentry->check();
151 foreach my $bibfield ($bibentry->fieldlist()) {
152 my $bibfieldvalue = $bibentry->get($bibfield);
153 $bibfieldvalue = decode("Detect", $bibfieldvalue);
154 $bibentry->set($bibfield, $bibfieldvalue);
155 }
156 push @$bibentries, $bibentry;
157 }
158 };
159 $bib->close();
160 }
161  
162 # remove 'file' field from Text::BibTeX::BibEntry, since it
163 # contains a GLOB item that cannot be serialised by Storable
164 foreach my $bibentry (@$bibentries) {
165 delete($bibentry->{file}) if defined($bibentry->{file});
166 }
167  
168 # format error messages, if any
169 if (length($errmsgs) > 0) {
170 foreach my $msg (split(/\n/, $errmsgs)) {
171 $msg =~ s/^$filename,\s*//;
172 if ($msg =~ /^line (\d+)[,:]?\s*(.*)$/) {
173 push @$errors, { from => $1, msg => $2 };
174 } elsif ($msg =~ /^lines (\d+)-(\d+)[,:]?\s*(.*)$/) {
175 push @$errors, { from => $1, to => $2, msg => $3 };
176 } else {
177 push @$errors, { msg => $msg };
178 }
179 }
180 }
181  
182 }
183  
184 sub read_bib_from_pdf {
185 my (@pdffiles) = @_;
186  
187 # get location of BibTeX XSLT style file
188 my $xsltbibtex = dist_file('App-PDFLibrarian', 'bibtex.xsl');
189 croak "$Script: missing XSLT style file '$xsltbibtex'" unless -f $xsltbibtex;
190  
191 # read BibTeX entries from PDF files
192 my $body = sub {
193 my ($pdffile) = @_;
194  
195 # open PDF file and read XMP metadata
196 my $pdf = PDF::API2->open($pdffile);
197 my $xmpbytes = "";
198 eval {
199 $xmpbytes = $pdf->xml_metadata() // "";
200 };
201 my $xmp = decode('utf-8', $xmpbytes);
202 $xmp = "" unless $xmp =~ /<\?xpacket /;
203 $xmp =~ s/\s*<\?xpacket .*\?>\s*//g;
204 $pdf->end();
205  
206 # convert BibTeX XML (if any) to parsed BibTeX entry
207 my $bibstr = '@article{:,}';
208 my $xml = "";
209 if (length($xmp) > 0) {
210 eval {
211 $xml = XML::LibXML->load_xml(string => $xmp);
212 };
213 }
214 if (length($xml) > 0) {
215 my $xslt = XML::LibXSLT->new();
216 my $xsltstylesrc = XML::LibXML->load_xml(location => $xsltbibtex);
217 my $xsltstyle = $xslt->parse_stylesheet($xsltstylesrc);
218 my $bib = $xsltstyle->transform($xml);
219 my $bibtext = $bib->textContent();
220 $bibtext =~ s/^\s+//;
221 $bibtext =~ s/\s+$//;
222 if (length($bibtext) > 0) {
223 $bibstr = $bibtext;
224 }
225 }
226 my $bibentry = read_bib_from_str($bibstr);
227  
228 # save name of PDF file
229 $bibentry->set('file', $pdffile);
230  
231 return $bibentry;
232 };
233 my @bibentries = parallel_loop("reading BibTeX entries from %i/%i PDF files", \@pdffiles, $body);
234  
235 # add checksums to BibTeX entries
236 foreach my $bibentry (@bibentries) {
237 my $checksum = bib_checksum($bibentry);
238 $bibentry->set('checksum', $checksum);
239 }
240  
241 return @bibentries;
242 }
243  
244 sub format_bib {
245 my ($opts, @bibentries) = @_;
246  
247 # check options
248 $opts->{max_authors} = 0 unless defined($opts->{max_authors});
249 $opts->{only_first_author} = 0 unless defined($opts->{only_first_author});
250  
251 # format BibTeX entries
252 my @fmtbibentries;
253 foreach my $bibentry (@bibentries) {
254  
255 # create a copy of BibTeX entry
256 $bibentry = $bibentry->clone();
257  
258 # merge BibTeX field names which differ by 's', e.g. 'keyword' and 'keywords'
259 foreach my $bibfield ($bibentry->fieldlist()) {
260 if ($bibentry->exists($bibfield) && $bibentry->exists($bibfield . "s")) {
261 my $bibfieldvalue = $bibentry->get($bibfield);
262 my $bibfieldsvalue = $bibentry->get($bibfield . "s");
263 if ($bibfieldvalue eq "") {
264 $bibfieldvalue = $bibfieldsvalue;
265 } elsif ($bibfieldsvalue ne "") {
266 $bibfieldvalue .= ", " . $bibfieldsvalue;
267 }
268 $bibentry->set($bibfield, $bibfieldvalue);
269 $bibentry->delete($bibfield . "s");
270 }
271 }
272  
273 # remove wrapping braces from title fields
274 foreach my $bibfield ($bibentry->fieldlist()) {
275 if ($bibfield =~ /title$/) {
276 my $bibfieldvalue = $bibentry->get($bibfield);
277 while ($bibfieldvalue =~ /^(\{(?:[^{}]++|(?1))*\})$/) {
278 $bibfieldvalue = substr($1, 1, -1);
279 };
280 $bibentry->set($bibfield, $bibfieldvalue);
281 }
282 }
283  
284 # replace accented characters with LaTeX accents
285 foreach my $bibfield ($bibentry->fieldlist()) {
286 my $bibfieldvalue = $bibentry->get($bibfield);
287 $bibfieldvalue = replace_accents_with_latex($bibfieldvalue);
288 $bibentry->set($bibfield, $bibfieldvalue);
289 }
290  
291 # uniformly format authors, editors, and collaborations
292 foreach my $bibfield (qw(author editor collaboration)) {
293 if ($bibentry->exists($bibfield)) {
294  
295 # determine author format
296 my $authorformat;
297 if ($bibfield eq "collaboration") {
298 $authorformat = new Text::BibTeX::NameFormat("l");
299 $authorformat->set_text(BTN_LAST, "{", "}", undef, undef);
300 } else {
301 $authorformat = new Text::BibTeX::NameFormat("vljf");
302 $authorformat->set_text(BTN_LAST, "{", "}", undef, undef);
303 $authorformat->set_text(BTN_FIRST, undef, undef, undef, ".");
304 $authorformat->set_options(BTN_FIRST, 1, BTJ_FORCETIE, BTJ_SPACE);
305 }
306  
307 # iterate over authors
308 my @authors = $bibentry->split($bibfield);
309 foreach my $author (@authors) {
310  
311 # sanitise author string
312 $author =~ s/([^\\])~/$1 /g;
313 $author =~ s/\.\s-/.-/g;
314 $author =~ s/\bet\sal\.?/others/;
315  
316 if ($author ne "others") {
317  
318 # format author
319 $author = Text::BibTeX::Name->new($author);
320 $author = $authorformat->apply($author);
321  
322 # use braces around special character commands
323 $author =~ s/\\(\W)(\w)/\{\\$1$2\}/g;
324 $author =~ s/\\(\w+)\s+(\w)/\\$1\{$2\}/g;
325  
326 # remove duplicate braces
327 my @parts = split(",", $author);
328 foreach my $part (@parts) {
329 while ($part =~ s{\{\{(.*?(\{(?:(?>[^{}]+)|(?2))*\}.*?)*)\}\}}{\{$1\}}) {
330 next;
331 }
332 }
333 $author = join(",", @parts);
334  
335 }
336 }
337  
338 # truncate author list
339 if ($opts->{max_authors} > 0 && @authors > $opts->{max_authors}) {
340 if ($opts->{only_first_author}) {
341 @authors = ($authors[0]);
342 } else {
343 @authors = @authors[0 .. ($opts->{max_authors} - 1)];
344 }
345 push @authors, "others";
346 }
347  
348 # set BibTeX field to concatenated authors
349 $bibentry->set($bibfield, join(" and ", @authors));
350  
351 }
352 }
353  
354 # remove trailing periods from title fields
355 foreach my $bibfield ($bibentry->fieldlist()) {
356 if ($bibfield =~ /title$/) {
357 my $bibfieldvalue = $bibentry->get($bibfield);
358 $bibfieldvalue =~ s/\.+$//;
359 $bibentry->set($bibfield, $bibfieldvalue);
360 }
361 }
362  
363 # handle e-print journals
364 if ($bibentry->exists('journal') && $bibentry->exists('archiveprefix') && $bibentry->exists('eprint')) {
365 my $journal = $bibentry->get('journal');
366 my $archiveprefix = $bibentry->get('archiveprefix');
367 my $eprint = $bibentry->get('eprint');
368 if ($journal eq $archiveprefix) {
369 $bibentry->set('pages', $eprint);
370 $bibentry->set('eid', $eprint);
371 }
372 }
373  
374 # regularise BibTeX 'month' field
375 if ($bibentry->exists('month')) {
376 my $month = $bibentry->get('month');
377 $month =~ s/\s//g;
378 $month =~ s/^jan.*$/January/i;
379 $month =~ s/^feb.*$/February/i;
380 $month =~ s/^mar.*$/March/i;
381 $month =~ s/^apr.*$/April/i;
382 $month =~ s/^may.*$/May/i;
383 $month =~ s/^jun.*$/June/i;
384 $month =~ s/^jul.*$/July/i;
385 $month =~ s/^aug.*$/August/i;
386 $month =~ s/^sep.*$/September/i;
387 $month =~ s/^oct.*$/October/i;
388 $month =~ s/^nov.*$/November/i;
389 $month =~ s/^dec.*$/December/i;
390 $bibentry->set('month', $month);
391 }
392  
393 # regularise BibTeX 'volume', 'number', 'issue', 'numpages' fields
394 # - remove redundant prefixes e.g. 'vol.', 'p.'
395 # - use single hyphen for ranges
396 foreach my $bibfield (qw(chapter volume number issue pages numpages)) {
397 if ($bibentry->exists($bibfield)) {
398 my $field = $bibentry->get($bibfield);
399 $field =~ s/^[a-z]+\.//;
400 $field =~ s/--+/-/g;
401 $field =~ s/\s*-\s*/-/g;
402 $bibentry->set($bibfield, $field);
403 }
404 }
405  
406 # regularise BibTeX 'edition' field
407 # - if a number, add appropriate ordinal suffix
408 foreach my $bibfield (qw(edition)) {
409 if ($bibentry->exists($bibfield)) {
410 my $field = $bibentry->get($bibfield);
411 if ($field =~ /^\s*[0-9]/) {
412 $field =~ s/[^0-9]//g;
413 my $last_digit = $field % 10;
414 if ($last_digit == 2 && $field != 12) {
415 $field .= 'nd';
416 } elsif ($last_digit == 3 && $field != 13) {
417 $field .= 'rd';
418 } else {
419 $field .= 'th';
420 }
421 }
422 $bibentry->set('edition', $field);
423 }
424 }
425  
426 # regularise BibTeX 'doi' field
427 if ($bibentry->exists('doi')) {
428 my $doi = $bibentry->get('doi');
429 $doi =~ s|https?[:]//[\w.]*doi\.org/||g;
430 $bibentry->set('doi', $doi);
431 }
432  
433 # set missing BibTeX 'doi' field from arXiv e-print
434 if (!$bibentry->exists('doi') && $bibentry->exists('archiveprefix') && $bibentry->exists('eprint')) {
435 my $archiveprefix = $bibentry->get('archiveprefix');
436 my $eprint = $bibentry->get('eprint');
437 if ($archiveprefix =~ /arxiv/i) {
438 my $doi = "10.48550/arXiv.$eprint";
439 $bibentry->set('doi', $doi);
440 }
441 }
442  
443 # set missing BibTeX 'doi' field from hyphenated ISBN-13
444 if (!$bibentry->exists('doi') && $bibentry->exists('isbn')) {
445 my $isbn = $bibentry->get('isbn');
446 if ($isbn =~ /^(97[89])-(\d+)-(\d+)-(\d+)-(\d+)/) {
447 my $doi = "10.$1.$2$3/$4$5";
448 $bibentry->set('doi', $doi);
449 }
450 }
451  
452 # set BibTeX 'url' field
453 if ($bibentry->exists('doi')) {
454 my $doi = $bibentry->get('doi');
455 my $url = "https://doi.org/$doi";
456 $bibentry->set('url', $url);
457 } else {
458 my @urlbibfields = grep { $_ =~ /.url$/ } $bibentry->fieldlist();
459 if (@urlbibfields == 1) {
460 $bibentry->set('url', $bibentry->get($urlbibfields[0]));
461 }
462 }
463  
464 # set BibTeX 'misc' entry 'howpublished' field
465 if ($bibentry->type eq 'misc') {
466 if ($bibentry->exists('archiveprefix')) {
467 my $archiveprefix = $bibentry->get('archiveprefix');
468 $bibentry->set('howpublished', $archiveprefix);
469 }
470 }
471  
472 # escape special characters
473 foreach my $bibfield ($bibentry->fieldlist()) {
474 my $bibfieldvalue = $bibentry->get($bibfield);
475 if ($bibfield =~ /url$/) {
476  
477 # encode special URL characters
478 $bibfieldvalue = uri_decode($bibfieldvalue);
479 $bibfieldvalue = uri_encode($bibfieldvalue, {encode_reserved => 0, double_encode => 0});
480  
481 } else {
482  
483 # escape special TeX characters
484 $bibfieldvalue =~ s{\\*&}{\\&}g;
485  
486 }
487 $bibentry->set($bibfield, $bibfieldvalue);
488 }
489  
490 # arrange BibTeX fields in the order given by @fieldorder
491 my %order;
492 my $orderidx;
493 foreach my $bibfield (@fieldorder, sort { $a cmp $b } $bibentry->fieldlist()) {
494 $order{$bibfield} = ++$orderidx if $bibentry->exists($bibfield) && !defined($order{$bibfield});
495 }
496 $order{'file'} = ++$orderidx if $bibentry->exists('file');
497 my @fieldlist = sort { $order{$a} <=> $order{$b} } keys(%order);
498 $bibentry->set_fieldlist(\@fieldlist);
499  
500 # output formatted entry
501 push @fmtbibentries, $bibentry;
502  
503 }
504  
505 return @fmtbibentries;
506 }
507  
508 sub write_bib_to_fh {
509 my ($opts, @bibentries) = @_;
510  
511 # check options
512 die unless defined($opts->{fh});
513 my $fh = $opts->{fh};
514  
515 # print BibTeX entries
516 foreach my $bibentry (sort { $a->key cmp $b->key } @bibentries) {
517  
518 # create a copy of BibTeX entry
519 $bibentry = $bibentry->clone();
520  
521 # remove checksum before printing
522 $bibentry->delete('checksum');
523  
524 # decide if/how to output PDF filename
525 my $pdf_file_comment = "";
526 if (defined($opts->{pdf_file})) {
527 if ($opts->{pdf_file} eq "comment") {
528 my $pdf_file = $bibentry->get("file");
529 $pdf_file_comment = "% file: $pdf_file\n";
530 }
531 $bibentry->delete("file");
532 }
533  
534 # print entry
535 my $bibstr = $bibentry->print_s();
536 $bibstr =~ s/^\s+//g;
537 $bibstr =~ s/\s+$//g;
538 eval {
539 no warnings 'utf8';
540 no warnings 'io';
541 print $fh "\n", $pdf_file_comment, $bibstr, "\n";
542 };
543  
544 }
545  
546 }
547  
548 sub write_bib_to_pdf {
549 my (@bibentries) = @_;
550  
551 # get location of DublinCore XSLT style file
552 my $xsltdublincore = dist_file('App-PDFLibrarian', 'dublincore.xsl');
553 croak "$Script: missing XSLT style file '$xsltdublincore'" unless -f $xsltdublincore;
554  
555 # filter out unmodified BibTeX entries
556 my @modbibentries;
557 foreach my $bibentry (@bibentries) {
558 my $checksum = bib_checksum($bibentry);
559 next if ($bibentry->get('checksum') // "") eq $checksum;
560 push @modbibentries, $bibentry;
561 $bibentry->set('checksum', $checksum);
562 }
563 printf STDERR "$Script: not writing %i unmodified BibTeX entries\n", @bibentries - @modbibentries if @modbibentries < @bibentries;
564  
565 # write modified BibTeX entries to PDF files
566 my $body = sub {
567 my ($bibentry) = @_;
568  
569 # get name of PDF file
570 my $pdffile = $bibentry->get('file');
571  
572 # check for existence of PDF file
573 croak "$Script: BibTeX entry '@{[$bibentry->key]}' cannot be written to missing PDF file '$pdffile'" unless -f $pdffile;
574  
575 # create XML document
576 my $xml = XML::LibXML::Document->new('1.0', 'utf-8');
577 my $xmlmeta = $xml->createElementNS("adobe:ns:meta/", "xmpmeta");
578 $xmlmeta->setNamespace("adobe:ns:meta/", "x", 1);
579 $xml->setDocumentElement($xmlmeta);
580  
581 # convert BibTeX into XML
582 my $xmlbibentry = $xml->createElementNS("http://bibtexml.sf.net/", "entry");
583 $xmlbibentry->setNamespace("http://bibtexml.sf.net/", "bibtex", 1);
584 $xmlbibentry->setAttribute("id" => $bibentry->key);
585 $xmlmeta->appendChild($xmlbibentry);
586 my $xmlbibtype = $xml->createElementNS("http://bibtexml.sf.net/", lc($bibentry->type));
587 $xmlbibtype->setNamespace("http://bibtexml.sf.net/", "bibtex", 1);
588 $xmlbibentry->appendChild($xmlbibtype);
589 foreach my $bibfield ($bibentry->fieldlist()) {
590 next if grep { $bibfield eq $_ } qw(checksum file);
591 next unless length($bibentry->get($bibfield)) > 0;
592 my $xmlbibfield = $xml->createElementNS("http://bibtexml.sf.net/", lc($bibfield));
593 $xmlbibfield->setNamespace("http://bibtexml.sf.net/", "bibtex", 1);
594 $xmlbibfield->appendTextNode($bibentry->get($bibfield));
595 $xmlbibtype->appendChild($xmlbibfield);
596 }
597  
598 # convert BibTeX XML to DublinCore XML and append
599 my $xslt = XML::LibXSLT->new();
600 my $xsltstylesrc = XML::LibXML->load_xml(location => $xsltdublincore);
601 my $xsltstyle = $xslt->parse_stylesheet($xsltstylesrc);
602 my $xmldc = $xsltstyle->transform($xml);
603 my $xmldcentry = $xmldc->documentElement()->cloneNode(1);
604 $xml->adoptNode($xmldcentry);
605 $xmlmeta->insertBefore($xmldcentry, $xmlbibentry);
606  
607 # open PDF file
608 my $pdf = PDF::API2->open($pdffile);
609  
610 # write document information to PDF file
611 my %pdfinfo;
612 eval {
613 %pdfinfo = $pdf->info();
614 };
615 $pdfinfo{Author} = remove_tex_markup($bibentry->get("author") // $bibentry->get("editor") . " ed.");
616 $pdfinfo{Title} = remove_tex_markup($bibentry->get("title"));
617 $pdfinfo{Subject} = remove_tex_markup($bibentry->get("abstract"));
618 $pdf->infoMetaAttributes(keys(%pdfinfo));
619 $pdf->info(%pdfinfo);
620 $pdf->preferences(-displaytitle => 1);
621  
622 # write XMP metadata to PDF file
623 my $xmphead = "<?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?>\n";
624 my $xmpdata = $xml->documentElement()->toString(0);
625 my $xmptail = "\n<?xpacket end='w'?>";
626 my $newxmp = $xmphead . $xmpdata . $xmptail;
627 my $newxmpbytes = encode('utf-8', $newxmp);
628 $pdf->xml_metadata($newxmpbytes);
629  
630 # write PDF file
631 eval {
632 $pdf->update();
633 $pdf->end();
634 1;
635 } or do {
636 chomp(my $error = $@);
637 print STDERR "$Script: could not save PDF file '$pdffile': $error\n";
638 $bibentry = undef;
639 };
640  
641 return $bibentry;
642 };
643 @modbibentries = parallel_loop("writing BibTeX entries to %i/%i PDF files", \@modbibentries, $body);
644  
645 return @modbibentries;
646 }
647  
648 sub edit_bib_in_fh {
649 my ($oldfh, @bibentries) = @_;
650 die unless blessed($oldfh) eq 'File::Temp';
651  
652 # save checksums of BibTeX entries
653 my %checksums;
654 foreach my $bibentry (@bibentries) {
655 $checksums{$bibentry->get('file')} = $bibentry->get('checksum');
656 }
657  
658 # edit and re-read BibTeX entries, allowing for errors
659 my @errors;
660 while (1) {
661  
662 while (1) {
663  
664 # open new temporary file for editing BibTeX entries
665 my $fh = File::Temp->new(SUFFIX => '.bib', EXLOCK => 0) or croak "$Script: could not create temporary file";
666  
667 # write header message
668 if (@errors > 0) {
669 print $fh wrap("% ", "% ", <<"EOF");
670 PDFLibrarian has encountered several errors in parsing the following BibTeX records. These errors are indicated with comments next to the line where the errors occurred.
671  
672 All errors MUST be corrected before the BibTeX records can be written back to the PDF file given by the 'file' field in each record.
673  
674 To ABORT ANY CHANGES from being written, simply delete the relevant records, or the entire contents of this file.
675 EOF
676 } else {
677 print $fh wrap("% ", "% ", <<"EOF");
678 PDFLibrarian has extracted the following BibTeX records for editing. Any changes to the records will be written back to the PDF file given by the 'file' field in each record.
679  
680 To ABORT ANY CHANGES from being written, simply delete the relevant records, or the entire contents of this file.
681 EOF
682 }
683 if (%bibtex_macros > 0) {
684 print $fh "%\n% Available BibTeX macros:\n";
685 foreach my $macro (keys %bibtex_macros) {
686 print $fh "% $macro: $bibtex_macros{$macro}\n";
687 }
688 }
689 print $fh "\n";
690  
691 # build hash of errors by line number
692 my %errorsbyline;
693 foreach (@errors) {
694 if (defined($_->{from})) {
695 push @{$errorsbyline{$_->{from}}}, $_->{msg};
696 } else {
697 push @{$errorsbyline{0}}, $_->{msg};
698 }
699 }
700  
701 # write any error messages without line numbers
702 if (defined($errorsbyline{0})) {
703 foreach (@{$errorsbyline{0}}) {
704 print $fh "% ERROR: $_\n";
705 }
706 delete $errorsbyline{0};
707 print $fh "\n";
708 }
709  
710 # write contents of old temporary file, with any error messages inline
711 $oldfh->flush();
712 $oldfh->seek(0, SEEK_SET);
713 while (<$oldfh>) {
714 chomp;
715 my $line = sprintf("%i", $oldfh->input_line_number);
716 foreach (@{$errorsbyline{$line}}) {
717 print $fh "% ERROR: $_\n";
718 }
719 delete $errorsbyline{$line};
720 s/\s+$//;
721 next if /^%/;
722 next if /^$/;
723 print $fh "$_\n";
724 if (/^}$/) {
725 print $fh "\n";
726 }
727 }
728 $fh->flush();
729  
730 # write any remaining error messages
731 foreach (keys %errorsbyline) {
732 foreach (@{$errorsbyline{$_}}) {
733 print $fh "% ERROR: $_\n";
734 }
735 }
736  
737 # print index of all currently-defined keywords
738 print $fh keyword_display_str();
739  
740 # save handle to new temporary file; old temporary file is deleted
741 $oldfh = $fh;
742  
743 # edit BibTeX entries
744 my $editor = $ENV{'VISUAL'} // $ENV{'EDITOR'} // 'editor';
745 printf STDERR "$Script: opening %i BibTeX entries in editing program '$editor' ...\n", scalar(@bibentries);
746 system($editor, $fh->filename) == 0 or croak "$Script: could not edit file '$fh->filename' with editing program '$editor'";
747  
748 # try to re-read BibTeX entries
749 read_bib_from_file(\@errors, \@bibentries, $fh->filename);
750  
751 # error if duplicate BibTeX keys are found
752 foreach my $dupkey (find_dup_bib_keys(@bibentries)) {
753 push @errors, { msg => "duplicated key '$dupkey'" };
754 }
755  
756 foreach my $bibentry (@bibentries) {
757  
758 # error if required fields are empty
759 foreach my $bibfield ($structure->required_fields($bibentry->type)) {
760 my $bibfieldvalue = $bibentry->get($bibfield) // "";
761 $bibfieldvalue =~ s/[{}]//g;
762 if ($bibfieldvalue eq "") {
763 push @errors, { msg => "entry '@{[$bibentry->key]}' is missing required field '${bibfield}'" };
764 }
765 }
766  
767 # error if BibTeX entries contain field names which differ by 's', e.g. 'keyword' and 'keywords'
768 foreach my $bibfield ($bibentry->fieldlist()) {
769 if ($bibentry->exists($bibfield) && $bibentry->exists($bibfield . "s")) {
770 push @errors, { msg => "entry '@{[$bibentry->key]}' contains duplicate fields '${bibfield}' and '${bibfield}s'" };
771 }
772 }
773  
774 # error if BibTeX fields are not UTF-8 strings
775 foreach my $bibfield ($bibentry->fieldlist()) {
776 my $bibfieldvalue = $bibentry->get($bibfield);
777 if ($bibfieldvalue =~ /\x{fffd}/) {
778 push @errors, { msg => "entry '@{[$bibentry->key]}' field '${bibfield}' contains non-Unicode characters" };
779 }
780 }
781  
782 }
783  
784 # BibTeX entries have been successfully read
785 last if @errors == 0;
786  
787 }
788  
789 {
790 # open new temporary file for editing BibTeX entries
791 my $fh = File::Temp->new(SUFFIX => '.bib', EXLOCK => 0) or croak "$Script: could not create temporary file";
792  
793 # format and print BibTeX entries
794 write_bib_to_fh({ fh => $fh }, format_bib({}, @bibentries));
795 $fh->flush();
796  
797 # save handle to new temporary file; old temporary file is deleted
798 $oldfh = $fh;
799  
800 # try to re-read BibTeX entries
801 read_bib_from_file(\@errors, \@bibentries, $fh->filename);
802 }
803  
804 # BibTeX entries have been successfully read
805 last if @errors == 0;
806  
807 }
808  
809 # restore checksums of BibTeX entries
810 foreach my $bibentry (@bibentries) {
811 $bibentry->set('checksum', $checksums{$bibentry->get('file')});
812 }
813  
814 return @bibentries;
815 }
816  
817 sub find_dup_bib_keys {
818 my (@bibentries) = @_;
819  
820 # find duplicate keys in BibTeX entries
821 my %keycount;
822 foreach my $bibentry (@bibentries) {
823 ++$keycount{$bibentry->key};
824 }
825  
826 return grep { $keycount{$_} > 1 } keys(%keycount);
827 }
828  
829 sub format_bib_authors {
830 my ($nameformat, $maxauthors, $etal, @authors) = @_;
831  
832 # format authors
833 my $authorformat = new Text::BibTeX::NameFormat($nameformat);
834 foreach my $author (@authors) {
835 $author = $authorformat->apply($author);
836 $author = remove_tex_markup($author);
837 if ($author =~ /\sCollaboration$/i) {
838 $author =~ s/\s.*$//;
839 }
840 }
841  
842 if (@authors > 0) {
843  
844 # limit number of authors to '$maxathors'
845 if (defined($maxauthors) && $maxauthors > 0 && @authors > $maxauthors) {
846 @authors = ($authors[0], $etal);
847 }
848  
849 # replace 'others' with preferred form of 'et al.'
850 $authors[-1] = $etal if $authors[-1] eq "others";
851  
852 }
853  
854 return @authors;
855 }
856  
857 sub generate_bib_keys {
858 my (@bibentries) = @_;
859  
860 # generate keys for BibTeX entries
861 my $keys = 0;
862 foreach my $bibentry (@bibentries) {
863 my $key = "";
864  
865 # add formatted authors, editors, or collaborations
866 {
867 my @authors = format_bib_authors("l", 2, "EtAl", $bibentry->names("collaboration"));
868 @authors = format_bib_authors("l", 2, "EtAl", $bibentry->names("author")) unless @authors > 0;
869 @authors = format_bib_authors("l", 2, "EtAl", $bibentry->names("editor")) unless @authors > 0;
870 $key .= join('', map { $_ =~ s/\s//g; substr($_, 0, 4) } @authors);
871 }
872  
873 # add year
874 my $year = $bibentry->get("year") // "";
875 $key .= $year;
876  
877 # add abbreviated title
878 {
879 my $suffix = "";
880 my $erratum = "";
881  
882 my $title = $bibentry->get("title");
883 $title = remove_tex_markup($title);
884 if ($title =~ s/^erratum[\p{IsPunct}\s]//i) {
885 $erratum = "-ERRATUM";
886 $title =~ s/\([^()]+\)$//;
887 $title =~ s/\[[^[\]]+\]$//;
888 }
889 $title =~ s/[^\w\d\s]//g;
890  
891 # abbreviate title words
892 my @words = remove_short_words(split(/\s+/, $title));
893 my @wordlens = (3, 3, 2, 2, 2);
894 foreach my $word (sort { length($b) <=> length($a) } @words) {
895  
896 # add any Roman numeral to suffix, and stop processing title
897 if (grep { $word eq $_ } qw(II III IV V VI VII VIII IX)) {
898 $suffix .= "-$word";
899 last;
900 }
901  
902 # always include numbers in full
903 next if $word =~ /^\d+$/;
904  
905 # abbreviate word to the next available length, after removing vowels
906 my $wordlen = shift(@wordlens) // 1;
907 my $shrt = ucfirst($word);
908 $shrt =~ s/[aeiou]//g;
909 $shrt = substr($shrt, 0, $wordlen);
910  
911 map { s/^$word$/$shrt/ } @words;
912 }
913  
914 unless (length($suffix) > 0) {
915  
916 # add volume number (if any) to suffix for books and proceedings
917 $suffix .= '-v' . $bibentry->get("volume") if (grep { $bibentry->type eq $_ } qw(book inbook proceedings)) && $bibentry->exists("volume");
918  
919 }
920  
921 # add abbreviated title and suffix to key
922 $key .= '-' . join('', @words);
923 $key .= $suffix . $erratum;
924  
925 }
926  
927 # sanitise key
928 $key = unidecode($key);
929 $key =~ s/[^\w\d-]//g;
930 $key =~ s/^-//;
931 $key =~ s/^--+/-/g;
932  
933 # set key to generated key, unless start of key matches generated key
934 # - this is so user can further customise key by appending characters
935 unless ($bibentry->key =~ /^$key($|-)/) {
936 $bibentry->set_key($key);
937 ++$keys;
938 }
939  
940 }
941 printf STDERR "$Script: generated keys for %i BibTeX entries\n", $keys if $keys > 0;
942  
943 }