-
Notifications
You must be signed in to change notification settings - Fork 38
/
Biber.pm
5076 lines (4203 loc) · 181 KB
/
Biber.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Biber;
use v5.24;
use strict;
use warnings;
use parent qw(Class::Accessor Biber::Internals);
use constant {
EXIT_OK => 0,
EXIT_ERROR => 2
};
use Biber::Config;
use Biber::DataLists;
use Biber::DataList;
use Biber::DataModel;
use Biber::Constants;
use Biber::Internals;
use Biber::Entries;
use Biber::Entry;
use Biber::Entry::Names;
use Biber::Entry::Name;
use Biber::LangTags;
use Biber::Sections;
use Biber::Section;
use Biber::LaTeX::Recode;
use Biber::UCollate;
use Biber::Utils;
use Carp;
use Data::Dump;
use Digest::MD5 qw( md5_hex );
use Data::Compare;
use Encode;
use File::Copy;
use File::Slurper;
use File::Spec;
use File::Temp;
use IO::File;
use List::AllUtils qw( first uniq max first_index );
use Log::Log4perl qw( :no_extra_logdie_message );
use POSIX qw( locale_h ); # for lc()
use Scalar::Util qw(looks_like_number);
use Sort::Key qw ( multikeysorter );
use Text::BibTeX qw(:macrosubs);
use Unicode::Normalize;
=encoding utf-8
=head1 NAME
Biber - main module for biber, a bibtex replacement for users of biblatex
=cut
my $logger = Log::Log4perl::get_logger('main');
=head1 SYNOPSIS
use Biber;
my $biber = Biber->new();
$biber->parse_ctrlfile("example.bcf");
$biber->prepare;
=cut
our $MASTER; # reference to biber object. Needed all over the place
=head1 METHODS
=head2 new
Initialize the Biber object, optionally passing named options as arguments.
=cut
sub new {
my ($class, %opts) = @_;
my $self = bless {}, $class;
Biber::Config->_initopts(\%opts);
# Add a reference to a global temp dir used for various things
$self->{TEMPDIR} = File::Temp->newdir("biber_tmp_XXXX",
TMPDIR => 1,
CLEANUP => (Biber::Config->getoption('noremove_tmp_dir') ? 0 : 1));
$self->{TEMPDIRNAME} = $self->{TEMPDIR}->dirname;
# Initialise recoding schemes
Biber::LaTeX::Recode->init_sets(Biber::Config->getoption('decodecharsset'),
Biber::Config->getoption('output_safecharsset'));
$MASTER = $self;
# Validate if asked to.
# This has to be here, after config file is read and options
# are parsed. It seems strange to validate the config file after it's been
# read but there is no choice and it's useful anyway as this will catch some semantic
# errors. Uses biber_error() and so $MASTER has to be defined before we call this
if (Biber::Config->getoption('validate_config') and $opts{configfile}) {
validate_biber_xml($opts{configfile}, 'config', '');
}
# Set up LangTag parser
$self->{langtags} = Biber::LangTags->new();
return $self;
}
=head2 display_end
Output summary of warnings/errors/misc before exit
=cut
sub display_end {
my $self = shift;
# Show location of temporary directory
if (Biber::Config->getoption('show_tmp_dir')) {
if (Biber::Config->getoption('noremove_tmp_dir')) {
$logger->info("TEMP DIR: " . $self->biber_tempdir_name);
}
else {
biber_warn("--noremove-tmp-dir was not set, no temporary directory to show");
}
}
if ($self->{warnings}) {
foreach my $w ($self->{warnings}->@*) {
$logger->warn(NFC($w)); # NFC boundary
}
$logger->info('WARNINGS: ' . scalar($self->{warnings}->@*));
}
if ($self->{errors}) {
$logger->info('ERRORS: ' . $self->{errors});
exit EXIT_ERROR;
}
}
=head2 biber_tempdir
Returns a File::Temp directory object for use in various things
=cut
sub biber_tempdir {
my $self = shift;
return $self->{TEMPDIR};
}
=head2 biber_tempdir_name
Returns the directory name of the File::Temp directory object
=cut
sub biber_tempdir_name {
my $self = shift;
return $self->{TEMPDIRNAME};
}
=head2 sections
my $sections= $biber->sections
Returns a Biber::Sections object describing the bibliography sections
=cut
sub sections {
my $self = shift;
return $self->{sections};
}
=head2 add_sections
Adds a Biber::Sections object. Used externally from, e.g. biber
=cut
sub add_sections {
my ($self, $sections) = @_;
$self->{sections} = $sections;
return;
}
=head2 datalists
my $datalists = $biber->datalists
Returns a Biber::DataLists object describing the bibliography sorting lists
=cut
sub datalists {
my $self = shift;
return $self->{datalists};
}
=head2 langtags
Returns a Biber::LangTags object containing a parser for BCP47 tags
=cut
sub langtags {
my $self = shift;
return $self->{langtags};
}
=head2 set_output_obj
Sets the object used to output final results
Must be a subclass of Biber::Output::base
=cut
sub set_output_obj {
my $self = shift;
my $obj = shift;
croak('Output object must be subclass of Biber::Output::base!') unless $obj->isa('Biber::Output::base');
$self->{output_obj} = $obj;
return;
}
=head2 get_preamble
Returns the current preamble as an array ref
=cut
sub get_preamble {
my $self = shift;
return $self->{preamble};
}
=head2 get_output_obj
Returns the object used to output final results
=cut
sub get_output_obj {
my $self = shift;
return $self->{output_obj};
}
=head2 set_current_section
Sets the current section number that we are working on to a section number
=cut
sub set_current_section {
my $self = shift;
my $secnum = shift;
$self->{current_section} = $secnum;
return;
}
=head2 get_current_section
Gets the current section number that we are working on
=cut
sub get_current_section {
my $self = shift;
return $self->{current_section};
}
=head2 tool_mode_setup
Fakes parts of the control file for tool mode
=cut
sub tool_mode_setup {
my $self = shift;
my $bib_sections = new Biber::Sections;
# There are no sections in tool mode so create a pseudo-section
my $bib_section = new Biber::Section('number' => 99999);
my $ifs = [];
foreach my $if (@ARGV) {
push $ifs->@*, {type => 'file',
name => $if,
datatype => Biber::Config->getoption('input_format'),
encoding => Biber::Config->getoption('input_encoding')};
}
$bib_section->set_datasources($ifs);
$bib_section->set_allkeys(1);
$bib_sections->add_section($bib_section);
# Always resolve date meta-information in tool mode
Biber::Config->setblxoption(undef, 'dateapproximate', 1);
Biber::Config->setblxoption(undef, 'dateera', 1);
Biber::Config->setblxoption(undef, 'dateuncertain', 1);
# No need to worry about this in tool mode but it needs to be set
Biber::Config->setblxoption(undef, 'namestrunchandling', 0);
# Add the Biber::Sections object to the Biber object
$self->add_sections($bib_sections);
my $datalists = new Biber::DataLists;
my $seclist = Biber::DataList->new(section => 99999,
sortingtemplatename => 'tool',
sortingnamekeytemplatename => 'global',
uniquenametemplatename => 'global',
labelalphanametemplatename => 'global',
namehashtemplatename => 'global',
labelprefix => '',
name => 'tool/global//global/global/global');
$seclist->set_type('entry');
# Locale just needs a default here - there is no biblatex option to take it from
Biber::Config->setblxoption(undef, 'sortlocale', 'en_US');
if ($logger->is_debug()) {# performance tune
$logger->debug("Adding 'entry' list 'tool' for pseudo-section 99999");
}
$datalists->add_list($seclist);
$self->{datalists} = $datalists;
# User maps are set in config file and need some massaging which normally
# happens in parse_ctrlfile
if (my $usms = Biber::Config->getoption('sourcemap')) {
# Force "user" level for the maps
$usms->@* = map {$_->{level} = 'user';$_} $usms->@*;
}
return;
}
=head2 parse_ctrlfile
This method reads the control file
generated by biblatex to work out the various biblatex options.
See Constants.pm for defaults and example of the data structure being built here.
=cut
sub parse_ctrlfile {
my ($self, $ctrl_file) = @_;
my $ctrl_file_path = locate_data_file($ctrl_file);
Biber::Config->set_ctrlfile_path($ctrl_file_path);
biber_error("Cannot find control file '$ctrl_file'! - Did latex run successfully on your .tex file before you ran biber?") unless ($ctrl_file_path and check_exists($ctrl_file_path));
# Early check to make sure .bcf is well-formed. If not, this means that the last biblatex run
# exited prematurely while writing the .bcf. This results is problems for latexmk. So, if the
# .bcf is broken, just stop here, remove the .bcf and exit with error so that we don't write
# a bad .bbl
my $checkbuf;
unless ($checkbuf = eval {slurp_switchr($ctrl_file_path)->$*}) {
# Reading ctrl-file as UTF-8 failed. Probably it was written by fontenc as latin1
# with some latin1 char in it (probably a sourcemap), so try that as a last resort
unless (eval {$checkbuf = slurp_switchr($ctrl_file_path, 'latin1')->$*}) {
biber_error("$ctrl_file_path is not UTF-8 or even latin1, please delete it and run latex again or check that biblatex is writing a valid .bcf file.");
}
# Write ctrl file as UTF-8
slurp_switchw($ctrl_file_path, $checkbuf);# Unicode NFC boundary
}
$checkbuf = NFD($checkbuf);# Unicode NFD boundary
unless (eval "XML::LibXML->load_xml(string => \$checkbuf)") {
my $output = $self->get_output_obj->get_output_target_file;
unlink($output) unless $output eq '-';# ignore deletion of STDOUT marker
biber_error("$ctrl_file_path is malformed, last biblatex run probably failed. Deleted $output");
}
# Validate if asked to
if (Biber::Config->getoption('validate_control')) {
validate_biber_xml($ctrl_file_path, 'bcf', 'https://sourceforge.net/projects/biblatex');
}
# Convert .bcf to .html using XSLT transform if asked to
if (Biber::Config->getoption('convert_control')) {
require XML::LibXSLT;
require XML::LibXML;
my $xslt = XML::LibXSLT->new();
my $CFstyle;
# we assume that the schema files are in the same dir as Biber.pm:
(my $vol, my $biber_path, undef) = File::Spec->splitpath( $INC{"Biber.pm"} );
# Deal with the strange world of PAR::Packer paths
# We might be running inside a PAR executable and @INC is a bit odd in this case
# Specifically, "Biber.pm" in @INC might resolve to an internal jumbled name
# nowhere near to these files. You know what I mean if you've dealt with pp
my $bcf_xsl;
if ($biber_path =~ m|/par\-| and $biber_path !~ m|/inc|) { # a mangled PAR @INC path
$bcf_xsl = File::Spec->catpath($vol, "$biber_path/inc/lib/Biber", 'bcf.xsl');
}
else {
$bcf_xsl = File::Spec->catpath($vol, "$biber_path/Biber", 'bcf.xsl');
}
if (check_exists($bcf_xsl)) {
$CFstyle = XML::LibXML->load_xml( location => $bcf_xsl, no_cdata=>1 )
}
else {
biber_warn("Cannot find XML::LibXSLT stylesheet. Skipping conversion : $!");
goto LOADCF;
}
my $CF = XML::LibXML->load_xml(location => $ctrl_file_path);
my $stylesheet = $xslt->parse_stylesheet($CFstyle);
my $CFhtml = $stylesheet->transform($CF);
$stylesheet->output_file($CFhtml, $ctrl_file_path . '.html');
$logger->info("Converted BibLaTeX control file '$ctrl_file_path' to '$ctrl_file_path.html'");
}
# Open control file
LOADCF:
$logger->info("Reading '$ctrl_file_path'");
my $buf = slurp_switchr($ctrl_file_path)->$*;
# Unicode NFD boundary, but not for filenames - leave these in OS form
$buf = join("\n", map {m/<bcf:datasource.+>([^<]+)/ ? $_ : NFD($_)} split(/\R\z/, $buf));
# Read control file
require XML::LibXML::Simple;
my $bcfxml = XML::LibXML::Simple::XMLin($buf,
'ForceContent' => 1,
'ForceArray' => [
qr/\A(?:no)*citekey(?:count)?\z/,
qr/\Aoption\z/,
qr/\Aoptions\z/,
qr/\Avalue\z/,
qr/\Asortitem\z/,
qr/\Abibdata\z/,
qr/\Adatasource\z/,
qr/\Aconstant\z/,
qr/\Asection\z/,
qr/\Asort(?:ex|in)clusion\z/,
qr/\A(?:ex|in)clusion\z/,
qr/\Asort\z/,
qr/\Amode\z/,
qr/\Amaps\z/,
qr/\Amap\z/,
qr/\Amap_step\z/,
qr/\Aper_type\z/,
qr/\Aper_nottype\z/,
qr/\Akeypart\z/,
qr/\Apart\z/,
qr/\Asortingnamekeytemplate\z/,
qr/\Asortingtemplate\z/,
qr/\Aper_datasource\z/,
qr/\Anosort\z/,
qr/\Anonamestring\z/,
qr/\Amember\z/,
qr/\Anoinit\z/,
qr/\Anolabel\z/,
qr/\Anolabelwidthcount\z/,
qr/\Apresort\z/,
qr/\Atype_pair\z/,
qr/\Ainherit\z/,
qr/\Anamepart\z/,
qr/\Afieldor\z/,
qr/\Afieldxor\z/,
qr/\Afield\z/,
qr/\Ascope\z/,
qr/\Atransliteration\z/,
qr/\Atranslit\z/,
qr/\Aalias\z/,
qr/\Aalsoset\z/,
qr/\Aconstraints\z/,
qr/\Aconstraint\z/,
qr/\Aentryfields\z/,
qr/\Aentrytype\z/,
qr/\Adatetype\z/,
qr/\Adatalist\z/,
qr/\Alabel(?:part|element|alpha(?:name)?template)\z/,
qr/\Auniquenametemplate\z/,
qr/\Anamehashtemplate\z/,
qr/\Acondition\z/,
qr/\Afilter(?:or)?\z/,
qr/\Aoptionscope\z/,
qr/\Aextradatespec\z/
],
'NsStrip' => 1,
'KeyAttr' => []);
# use Data::Dump;dd($bcfxml);exit 0;
my $controlversion = $bcfxml->{version};
my $bltxversion = $bcfxml->{bltxversion};
Biber::Config->setblxoption(undef, 'controlversion', $controlversion);
unless ($controlversion eq $BCF_VERSION) {
biber_error("Error: Found biblatex control file version $controlversion, expected version $BCF_VERSION.\nThis means that your biber ($Biber::Config::VERSION) and biblatex ($bltxversion) versions are incompatible.\nSee compat matrix in biblatex or biber PDF documentation.");
}
# Option scope
foreach my $bcfscopeopts ($bcfxml->{optionscope}->@*) {
my $scope = $bcfscopeopts->{type};
foreach my $bcfscopeopt ($bcfscopeopts->{option}->@*) {
my $opt = $bcfscopeopt->{content};
$CONFIG_BIBLATEX_OPTIONS{$scope}{$opt}{OUTPUT} = $bcfscopeopt->{backendout} || 0;
if (my $bin = process_backendin($bcfscopeopt->{backendin})) {
$CONFIG_BIBLATEX_OPTIONS{$scope}{$opt}{INPUT} = $bin;
}
$CONFIG_OPTSCOPE_BIBLATEX{$opt}{$scope} = 1;
$CONFIG_SCOPEOPT_BIBLATEX{$scope}{$opt} = 1;
if (defined($CONFIG_OPTTYPE_BIBLATEX{$opt}) and
lc($CONFIG_OPTTYPE_BIBLATEX{$opt}) ne lc($bcfscopeopt->{datatype})) {
biber_warn("Warning: Datatype for biblatex option '$opt' has conflicting values, probably at different scopes. This is not supported.");
}
else {
$CONFIG_OPTTYPE_BIBLATEX{$opt} = lc($bcfscopeopt->{datatype});
}
}
}
# Now we have the per-namelist options, make the accessors for them in the Names package
foreach my $nso (keys $CONFIG_SCOPEOPT_BIBLATEX{NAMELIST}->%*) {
Biber::Entry::Names->follow_best_practice;
Biber::Entry::Names->mk_accessors($nso);
}
# Now we have the per-name options, make the accessors for them in the Name package
foreach my $no (keys $CONFIG_SCOPEOPT_BIBLATEX{NAME}->%*) {
Biber::Entry::Name->follow_best_practice;
Biber::Entry::Name->mk_accessors($no);
}
# OPTIONS
foreach my $bcfopts ($bcfxml->{options}->@*) {
# Biber options
if ($bcfopts->{component} eq 'biber') {
# Global options
if ($bcfopts->{type} eq 'global') {
foreach my $bcfopt ($bcfopts->{option}->@*) {
# unless already explicitly set from cmdline/config file
unless (Biber::Config->isexplicitoption($bcfopt->{key}{content})) {
if ($bcfopt->{type} eq 'singlevalued') {
Biber::Config->setoption($bcfopt->{key}{content}, $bcfopt->{value}[0]{content});
}
elsif ($bcfopt->{type} eq 'multivalued') {
Biber::Config->setoption($bcfopt->{key}{content},
[ map {$_->{content}} sort {$a->{order} <=> $b->{order}} $bcfopt->{value}->@* ]);
}
}
}
}
}
# BibLaTeX options
if ($bcfopts->{component} eq 'biblatex') {
# Global options
if ($bcfopts->{type} eq 'global') {
foreach my $bcfopt ($bcfopts->{option}->@*) {
if ($bcfopt->{type} eq 'singlevalued') {
Biber::Config->setblxoption(undef, $bcfopt->{key}{content}, $bcfopt->{value}[0]{content});
}
elsif ($bcfopt->{type} eq 'multivalued') {
# sort on order attribute and then remove it
Biber::Config->setblxoption(undef, $bcfopt->{key}{content},
[ map {delete($_->{order}); $_} sort {$a->{order} <=> $b->{order}} $bcfopt->{value}->@* ]);
}
}
}
# Entrytype options
else {
my $entrytype = $bcfopts->{type};
foreach my $bcfopt ($bcfopts->{option}->@*) {
if ($bcfopt->{type} eq 'singlevalued') {
Biber::Config->setblxoption(undef, $bcfopt->{key}{content}, $bcfopt->{value}[0]{content}, 'ENTRYTYPE', $entrytype);
}
elsif ($bcfopt->{type} eq 'multivalued') {
# sort on order attribute and then remove it
Biber::Config->setblxoption(undef, $bcfopt->{key}{content},
[ map {delete($_->{order}); $_} sort {$a->{order} <=> $b->{order}} $bcfopt->{value}->@* ],
'ENTRYTYPE',
$entrytype);
}
}
}
}
}
# DATAFIELD SETS
# Since we have to use the datamodel to resolve some members, just record the settings
# here for processing after the datamodel is parsed
foreach my $s ($bcfxml->{datafieldset}->@*) {
my $name = lc($s->{name});
foreach my $m ($s->{member}->@*) {
if (my $field = $m->{field}[0]) {# 'field' has forcearray for other things
push $DATAFIELD_SETS{$name}->@*, $field;
}
else {
push $DATAFIELD_SETS{$name}->@*, {fieldtype => $m->{fieldtype},
datatype => $m->{datatype}};
}
}
}
# DATASOURCE MAPPING
# This is special as it's both a biblatex option and a biber option
# We merge into the biber option
# In biblatex you can set driver mappings but not in biber
# Order of application of maps is decided by the level and within 'user' level,
# which can come from two places (biber.conf and \DeclareSourcemap), order is
# \DeclareSourcemap, then biber.conf
if (exists($bcfxml->{sourcemap})) {
# User maps are set in config file
if (my $usms = Biber::Config->getoption('sourcemap')) {
# Force "user" level for the maps
$usms->@* = map {$_->{level} = 'user';$_} $usms->@*;
# Merge any user maps from the document set by \DeclareSourcemap into user
# maps set in the biber config file. These document user maps take precedence so go
# at the front of any other user maps
# Are there any doc maps to merge?
if (my @docmaps = grep {$_->{level} eq 'user'} $bcfxml->{sourcemap}{maps}->@*) {
# If so, get a reference to the maps in the config map and prepend all
# of the doc maps to it. Must also deref the doc maps map element to make
# sure that they collapse nicely
my $configmaps = first {$_->{level} eq 'user'} $usms->@*;
unshift($configmaps->{map}->@*, map {$_->{map}->@*} @docmaps);
}
# Merge the driver/style maps with the user maps from the config file
if (my @m = grep {$_->{level} eq 'driver' or
$_->{level} eq 'style'} $bcfxml->{sourcemap}{maps}->@* ) {
Biber::Config->setoption('sourcemap', [$usms->@*, @m]);
}
else { # no driver defaults, just override the config file user map settings
Biber::Config->setoption('sourcemap', $bcfxml->{sourcemap}{maps});
}
}
else { # just write the option as there are no config file settings at all
Biber::Config->setoption('sourcemap', $bcfxml->{sourcemap}{maps});
}
}
# LABELALPHA NAME TEMPLATE
my $lants;
foreach my $t ($bcfxml->{labelalphanametemplate}->@*) {
my $lant;
foreach my $np (sort {$a->{order} <=> $b->{order}} $t->{namepart}->@*) {
push $lant->@*, {namepart => $np->{content},
use => $np->{use},
pre => $np->{pre},
substring_compound => $np->{substring_compound},
substring_side => $np->{substring_side},
substring_width => $np->{substring_width}};
}
$lants->{$t->{name}} = $lant;
}
Biber::Config->setblxoption(undef, 'labelalphanametemplate', $lants);
# LABELALPHA TEMPLATE
foreach my $t ($bcfxml->{labelalphatemplate}->@*) {
my $latype = $t->{type};
if ($latype eq 'global') {
Biber::Config->setblxoption(undef, 'labelalphatemplate', $t);
}
else {
Biber::Config->setblxoption(undef, 'labelalphatemplate',
$t,
'ENTRYTYPE',
$latype);
}
}
# EXTRADATE specification
foreach my $eds ($bcfxml->{extradatespec}->@*) {
my $edtype = $eds->{type};
my $ed;
foreach my $scope ($eds->{scope}->@*) {
my $fields;
foreach my $field (sort {$a->{order} <=> $b->{order}} $scope->{field}->@*) {
push $fields->@*, $field->{content};
}
push $ed->@*, $fields;
}
if ($edtype eq 'global') {
Biber::Config->setblxoption(undef, 'extradatespec', $ed);
}
else {
Biber::Config->setblxoption(undef, 'extradatespec',
$ed,
'ENTRYTYPE',
$edtype);
}
}
# INHERITANCE schemes for crossreferences (always global)
Biber::Config->setblxoption(undef, 'inheritance', $bcfxml->{inheritance});
# NOINIT
# Make the data structure look like the biber config file structure
# "value" is forced to arrays for other elements so we extract
# the first element here as they will always be only length=1
my $noinit;
foreach my $ni ($bcfxml->{noinits}{noinit}->@*) {
push $noinit->@*, { value => $ni->{value}[0]};
}
# There is a default so don't set this option if nothing is in the .bcf
Biber::Config->setoption('noinit', $noinit) if $noinit;
# NOLABEL
# Make the data structure look like the biber config file structure
# "value" is forced to arrays for other elements so we extract
# the first element here as they will always be only length=1
my $nolabel;
foreach my $nl ($bcfxml->{nolabels}{nolabel}->@*) {
push $nolabel->@*, { value => $nl->{value}[0]};
}
# There is a default so don't set this option if nothing is in the .bcf
Biber::Config->setoption('nolabel', $nolabel) if $nolabel;
# NOLABELWIDTHCOUNT
# Make the data structure look like the biber config file structure
# "value" is forced to arrays for other elements so we extract
# the first element here as they will always be only length=1
my $nolabelwidthcount;
foreach my $nlwc ($bcfxml->{nolabelwidthcounts}{nolabelwidthcount}->@*) {
push $nolabelwidthcount->@*, { value => $nlwc->{value}[0]};
}
# There is a default so don't set this option if nothing is in the .bcf
Biber::Config->setoption('nolabelwidthcount', $nolabelwidthcount) if $nolabelwidthcount;
# NOSORT
# Make the data structure look like the biber config file structure
# "field" and "value" are forced to arrays for other elements so we extract
# the first element here as they will always be only length=1
my $nosort;
foreach my $ns ($bcfxml->{nosorts}{nosort}->@*) {
push $nosort->@*, {name => $ns->{field}[0], value => $ns->{value}[0]};
}
# There is a default so don't set this option if nothing is in the .bcf
Biber::Config->setoption('nosort', $nosort) if $nosort;
# NONAMESTRING
# Make the data structure look like the biber config file structure
# "field" and "value" are forced to arrays for other elements so we extract
# the first element here as they will always be only length=1
my $nonamestring;
foreach my $ns ($bcfxml->{nonamestrings}{nonamestring}->@*) {
push $nonamestring->@*, {name => $ns->{field}[0], value => $ns->{value}[0]};
}
Biber::Config->setoption('nonamestring', $nonamestring) if $nonamestring;
# UNIQUENAME TEMPLATE
my $unts;
my $checkbase = 0;
foreach my $unt ($bcfxml->{uniquenametemplate}->@*) {
my $untval = [];
foreach my $np (sort {$a->{order} <=> $b->{order}} $unt->{namepart}->@*) {
$checkbase = 1 if $np->{base};
push $untval->@*, {namepart => $np->{content},
use => $np->{use},
disambiguation => $np->{disambiguation},
base => $np->{base}};
}
$unts->{$unt->{name}} = $untval;
}
# Check to make sure we have a base to disambiguate from. If not, we can get infinite loops
# in the disambiguation code
biber_error("The uniquenametemplate must contain at least one 'base' part otherwise name disambiguation is impossible") unless $checkbase;
Biber::Config->setblxoption(undef, 'uniquenametemplate', $unts);
# NAME HASH TEMPLATE
my $nhts;
foreach my $nht ($bcfxml->{namehashtemplate}->@*) {
my $nhtval = [];
foreach my $np (sort {$a->{order} <=> $b->{order}} $nht->{namepart}->@*) {
push $nhtval->@*, {namepart => $np->{content},
hashscope => $np->{hashscope}};
}
$nhts->{$nht->{name}} = $nhtval;
}
Biber::Config->setblxoption(undef, 'namehashtemplate', $nhts);
# SORTING NAME KEY
# Use the order attributes to make sure things are in right order and create a data structure
# we can use later
my $snss;
foreach my $sns ($bcfxml->{sortingnamekeytemplate}->@*) {
my $snkps;
foreach my $snkp (sort {$a->{order} <=> $b->{order}} $sns->{keypart}->@*) {
my $snps;
foreach my $snp (sort {$a->{order} <=> $b->{order}} $snkp->{part}->@*) {
my $np;
if ($snp->{type} eq 'namepart') {
$np = { type => 'namepart', value => $snp->{content} };
if (exists($snp->{use})) {
$np->{use} = $snp->{use};
}
if (exists($snp->{inits})) {
$np->{inits} = $snp->{inits};
}
}
elsif ($snp->{type} eq 'literal') {
$np = { type => 'literal', value => $snp->{content} };
}
push $snps->@*, $np;
}
push $snkps->@*, $snps;
}
$snss->{$sns->{name}}{visibility} = $sns->{visibility};
$snss->{$sns->{name}}{template} = $snkps;
}
Biber::Config->setblxoption(undef, 'sortingnamekeytemplate', $snss);
# SORTING
# transliterations
foreach my $tr ($bcfxml->{transliteration}->@*) {
if ($tr->{entrytype}[0] eq '*') { # already array forced for another option
Biber::Config->setblxoption(undef, 'translit', $tr->{translit});
}
else { # per_entrytype
Biber::Config->setblxoption(undef, 'translit',
$tr->{translit},
'ENTRYTYPE',
$tr->{entrytype}[0]);
}
}
# sorting excludes
foreach my $sex ($bcfxml->{sortexclusion}->@*) {
my $excludes;
foreach my $ex ($sex->{exclusion}->@*) {
$excludes->{$ex->{content}} = 1;
}
Biber::Config->setblxoption(undef, 'sortexclusion',
$excludes,
'ENTRYTYPE',
$sex->{type});
}
# sorting includes
foreach my $sin ($bcfxml->{sortinclusion}->@*) {
my $includes;
foreach my $in ($sin->{inclusion}->@*) {
$includes->{$in->{content}} = 1;
}
Biber::Config->setblxoption(undef, 'sortinclusion',
$includes,
'ENTRYTYPE',
$sin->{type});
}
# presort defaults
foreach my $presort ($bcfxml->{presort}->@*) {
# Global presort default
unless (exists($presort->{type})) {
Biber::Config->setblxoption(undef, 'presort', $presort->{content});
}
# Per-type default
else {
Biber::Config->setblxoption(undef, 'presort',
$presort->{content},
'ENTRYTYPE',
$presort->{type});
}
}
my $sortingtemplates;
foreach my $ss ($bcfxml->{sortingtemplate}->@*) {
$sortingtemplates->{$ss->{name}} = _parse_sort($ss);
}
Biber::Config->setblxoption(undef, 'sortingtemplate', $sortingtemplates);
# DATAMODEL schema (always global and is an array to accommodate multiple
# datamodels in tool mode)
# Because in tests, parse_ctrlfile() is called several times so we need to sanitise this here
Biber::Config->setblxoption(undef, 'datamodel', []);
Biber::Config->addtoblxoption(undef, 'datamodel', $bcfxml->{datamodel});
# SECTIONS
# This is also where we set data files as these are associated with a bib section
# Data sources
my %bibdatasources = ();
foreach my $data ($bcfxml->{bibdata}->@*) {
foreach my $datasource ($data->{datasource}->@*) {
unless (first {$_->{type} eq $datasource->{type} and
$_->{datatype} eq $datasource->{datatype} and
$_->{name} eq $datasource->{content}} $bibdatasources{$data->{section}[0]}->@*) {
push $bibdatasources{$data->{section}[0]}->@*, { type => $datasource->{type},
name => $datasource->{content},
datatype => $datasource->{datatype},
encoding => $datasource->{encoding} // Biber::Config->getoption('input_encoding'),
glob => $datasource->{glob} // Biber::Config->getoption('glob_datasources')};
}
}
}
# Be friendly to latexmk etc.
unless (%bibdatasources) {
biber_warn("No data sources defined!");
exit EXIT_OK;
}
my $key_flag = 0;
my $bib_sections = new Biber::Sections;
SECTION: foreach my $section ($bcfxml->{section}->@*) {
my $bib_section;
my $secnum = $section->{number};
# Can be multiple section 0 entries and so re-use that section object if it exists
if (my $existing_section = $bib_sections->get_section($secnum)) {
$bib_section = $existing_section;
}
else {
$bib_section = new Biber::Section('number' => $secnum);
}
# Set the data files for the section unless we've already done so
# (for example, for multiple section 0 entries)
$bib_section->set_datasources($bibdatasources{$secnum}) unless
$bib_section->get_datasources;
my @prekeys = ();
my @keys = ();
# Pre-process to deal with situation where key is both \nocite'd and \cited
# \cite'd takes priority
foreach my $keyc ($section->{citekey}->@*) {
my $key = NFD($keyc->{content}); # Key is already UTF-8 - it comes from UTF-8 XML
if ($keyc->{nocite}) {# \nocite'd
# Don't add if there is an identical key without nocite since \cite takes precedence
unless (first {$key eq NFD($_->{content})} @prekeys) {
push @prekeys, $keyc;
}
}
else {# \cite'd
# If there is already a nocite of this key, remove the nocite attribute and don't add
if (first {($key eq NFD($_->{content})) and $_->{nocite}} @prekeys) {
@prekeys = map {delete($_->{nocite}) if $key eq NFD($_->{content});$_} @prekeys;
}
else {
push @prekeys, $keyc;
}
}
}
# Loop over all section keys
foreach my $keyc (@prekeys) {
my $key = NFD($keyc->{content}); # Key is already UTF-8 - it comes from UTF-8 XML
# Stop reading citekeys if we encounter "*" as a citation as this means
# "all keys"
if ($key eq '*') {
$bib_section->set_allkeys(1);
Biber::Config->set_keyorder($secnum, $key, $keyc->{order});
if ($keyc->{nocite}) {
$bib_section->set_allkeys_nocite(1);
}
$key_flag = 1; # There is at least one key, used for error reporting below
}
elsif (not $bib_section->get_seenkey($key)) {
# Dynamic set definition
# Save dynamic key -> member keys mapping for set entry auto creation later
# We still need to find these even if allkeys is set
if (exists($keyc->{type}) and $keyc->{type} eq 'set') {
$bib_section->set_dynamic_set($key, split /\s*,\s*/, $keyc->{members});
push @keys, $key;
$key_flag = 1; # There is at least one key, used for error reporting below
}
else {
# Track cite/nocite - needed for sourcemapping logic
if ($keyc->{nocite}) {
$bib_section->add_nocite($key);
}
else {
$bib_section->add_cite($key);
}
# Set order information - there is no order on dynamic key defs above
# as they are a definition, not a cite
Biber::Config->set_keyorder($secnum, $key, $keyc->{order});
# order of keys which have the same order so we can track order in \cite{a,b,c}
if ($keyc->{intorder}) {
Biber::Config->set_internal_keyorder($secnum, $key, $keyc->{intorder});
}
push @keys, $key;
$key_flag = 1; # There is at least one key, used for error reporting below
}
}
$bib_section->incr_seenkey($key); # always increment
}
# Get citecounts if present
foreach my $keycount ($section->{citekeycount}->@*) {
my $key = NFD($keycount->{content}); # Key is already UTF-8 - it comes from UTF-8 XML
$bib_section->set_citecount($key, $keycount->{count});
}