-
Notifications
You must be signed in to change notification settings - Fork 761
/
BibTeX.js
4236 lines (4043 loc) · 173 KB
/
BibTeX.js
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
{
"translatorID": "9cb70025-a888-4a29-a210-93ec52da40d4",
"label": "BibTeX",
"creator": "Simon Kornblith, Richard Karnesky and Emiliano heyns",
"target": "bib",
"minVersion": "2.1.9",
"maxVersion": "",
"priority": 200,
"configOptions": {
"async": true,
"getCollections": true
},
"displayOptions": {
"exportCharset": "UTF-8",
"exportNotes": true,
"exportFileData": false,
"useJournalAbbreviation": false
},
"inRepository": true,
"translatorType": 3,
"lastUpdated": "2024-03-25 14:51:02"
}
/*
BibTeX Translator
Copyright (C) 2019 CHNM, Simon Kornblith, Richard Karnesky and Emiliano heyns
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function detectImport() {
var maxChars = 1048576; // 1MB
var inComment = false;
var block = "";
var buffer = "";
var chr = "";
var charsRead = 0;
var re = /^\s*@[a-zA-Z]+[\(\{]/;
while ((buffer = Zotero.read(4096)) && charsRead < maxChars) {
Zotero.debug("Scanning " + buffer.length + " characters for BibTeX");
charsRead += buffer.length;
for (var i=0; i<buffer.length; i++) {
chr = buffer[i];
if (inComment && chr != "\r" && chr != "\n") {
continue;
}
inComment = false;
if (chr == "%") {
// read until next newline
block = "";
inComment = true;
} else if ((chr == "\n" || chr == "\r"
// allow one-line entries
|| i == (buffer.length - 1))
&& block) {
// check if this is a BibTeX entry
if (re.test(block)) {
return true;
}
block = "";
} else if (!" \n\r\t".includes(chr)) {
block += chr;
}
}
}
}
//%a = first listed creator surname
//%y = year
//%t = first word of title
var citeKeyFormat = "%a_%t_%y";
var fieldMap = {
address:"place",
chapter:"section",
edition:"edition",
type:"type",
series:"series",
title:"title",
volume:"volume",
copyright:"rights",
isbn:"ISBN",
issn:"ISSN",
shorttitle:"shortTitle",
url:"url",
doi:"DOI",
abstract:"abstractNote",
nationality: "country",
language:"language",
assignee:"assignee"
};
// Fields for which upper case letters will be protected on export
var caseProtectedFields = [
"title",
"type",
"shorttitle",
"booktitle",
"series"
];
// Import/export in BibTeX
var extraIdentifiers = {
lccn: 'LCCN',
mrnumber: 'MR',
zmnumber: 'Zbl',
pmid: 'PMID',
pmcid: 'PMCID'
//Mostly from Wikipedia citation templates
//asin - Amazon ID
//bibcode/refcode - used in astronomy, but haven't seen any Bib(La)TeX examples
//jfm - Jahrbuch ID, but it seems to be part of Zentralblatt MATH, so Zbl
//oclc
//ol - openlibrary.org ID
//osti
//rfc
//ssrn? http://cyber.law.harvard.edu/cybersecurity/Guidelines_for_adding_Bibliography_entries
};
// Make a reverse map for convenience with additional DOI handling
var revExtraIds = {'DOI': 'doi'};
for (var field in extraIdentifiers) {
revExtraIds[extraIdentifiers[field]] = field;
}
// Import only. Exported by BibLaTeX
var eprintIds = {
// eprinttype: Zotero label
// From BibLaTeX manual
'arxiv': 'arXiv', // Sorry, but no support for eprintclass yet
'jstor': 'JSTOR',
'pubmed': 'PMID',
'hdl': 'HDL',
'googlebooks': 'GoogleBooksID'
};
function dateFieldsToDate(year, month, day) {
// per the latest ISO 8601 standard, you can't have a month/day without a
// year (and it would be silly anyway)
if (year) {
let date = year;
if (month) {
if (month.includes(date)) {
date = month;
}
else {
date += `-${month}`;
}
if (day) {
date += `-${day}`;
}
}
return ZU.strToISO(date);
}
return false;
}
function parseExtraFields(extra) {
var lines = extra.split(/[\r\n]+/);
var fields = [];
for (var i=0; i<lines.length; i++) {
var rec = { raw: lines[i] };
var line = lines[i].trim();
var splitAt = line.indexOf(':');
if (splitAt > 1) {
rec.field = line.substr(0,splitAt).trim();
rec.value = line.substr(splitAt + 1).trim();
}
fields.push(rec);
}
return fields;
}
function extraFieldsToString(extra) {
var str = '';
for (var i=0; i<extra.length; i++) {
if (!extra[i].raw) {
str += '\n' + extra[i].field + ': ' + extra[i].value;
} else {
str += '\n' + extra[i].raw;
}
}
return str.substr(1);
}
var inputFieldMap = {
booktitle :"publicationTitle",
school:"publisher",
publisher:"publisher",
issue:"issue",
// import also BibLaTeX fields:
journaltitle:"publicationTitle",
shortjournal:"journalAbbreviation",
eventtitle:"conferenceName",
pagetotal:"numPages",
version:"version"
};
var zotero2bibtexTypeMap = {
"book":"book",
"bookSection":"incollection",
"journalArticle":"article",
"magazineArticle":"article",
"newspaperArticle":"article",
"thesis":"phdthesis",
"letter":"misc",
"manuscript":"unpublished",
"patent" :"patent",
"interview":"misc",
"film":"misc",
"artwork":"misc",
"webpage":"misc",
"conferencePaper":"inproceedings",
"report":"techreport"
};
var bibtex2zoteroTypeMap = {
"book":"book", // or booklet, proceedings
"inbook":"bookSection",
"incollection":"bookSection",
"article":"journalArticle", // or magazineArticle or newspaperArticle
"patent" :"patent",
"phdthesis":"thesis",
"unpublished":"manuscript",
"inproceedings":"conferencePaper", // check for conference also
"conference":"conferencePaper",
"techreport":"report",
"booklet":"book",
"manual":"book",
"mastersthesis":"thesis",
"misc":"document",
"proceedings":"book",
"online":"webpage",
// alias for online from BibLaTeX:
"electronic":"webpage",
// from BibLaTeX translator:
"thesis":"thesis",
"letter":"letter",
"movie":"film",
"artwork":"artwork",
"report":"report",
"legislation":"bill",
"jurisdiction":"case",
"audio":"audioRecording",
"video":"videoRecording",
"software":"computerProgram",
"inreference":"encyclopediaArticle",
"collection":"book",
"mvbook":"book"
};
/*
* three-letter month abbreviations. i assume these are the same ones that the
* docs say are defined in some appendix of the LaTeX book. (i don't have the
* LaTeX book.)
*/
var months = ["jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec"];
var jabref = {
format: null,
root: {}
};
var alwaysMap = {
"|":"{\\textbar}",
"<":"{\\textless}",
">":"{\\textgreater}",
"~":"{\\textasciitilde}",
"^":"{\\textasciicircum}",
"\\":"{\\textbackslash}",
// See http://tex.stackexchange.com/questions/230750/open-brace-in-bibtex-fields/230754
"{" : "\\{\\vphantom{\\}}",
"}" : "\\vphantom{\\{}\\}"
};
var strings = {};
var keyRe = /[a-zA-Z0-9\-]/;
// Split keywords on space by default when called from another translator
// This is purely for historical reasons. Otherwise we risk breaking tag import
// from some websites
var keywordSplitOnSpace = !!Zotero.parentTranslator;
var keywordDelimRe = /\s*[,;]\s*/;
function setKeywordSplitOnSpace( val ) {
keywordSplitOnSpace = val;
}
function setKeywordDelimRe( val, flags ) {
//expect string, but it could be RegExp
if (typeof(val) != 'string') {
val = val.toString();
flags = val.slice(val.lastIndexOf('/')+1);
val = val.slice(1, val.lastIndexOf('/'));
}
keywordDelimRe = new RegExp(val, flags);
}
function processField(item, field, value, rawValue) {
if (Zotero.Utilities.trim(value) == '') return null;
if (fieldMap[field]) {
//map DOIs + Label to Extra for unsupported item types
if (field == "doi" &&!ZU.fieldIsValidForType("DOI", item.itemType) && ZU.cleanDOI(value)) {
item._extraFields.push({field: "DOI", value: ZU.cleanDOI(value)});
}
if (field == "url") { // pass raw values for URL
item.url = rawValue;
}
else {
item[fieldMap[field]] = value;
}
} else if (inputFieldMap[field]) {
item[inputFieldMap[field]] = value;
} else if (field == "subtitle") {
if (!item.title) item.title = '';
item.title = item.title.trim();
value = value.trim();
if (!/[-–—:!?.;]$/.test(item.title)
&& !/^[-–—:.;¡¿]/.test(value)
) {
item.title += ': ';
} else if (item.title.length) {
item.title += ' ';
}
item.title += value;
} else if (field == "journal") {
if (item.publicationTitle) {
item.journalAbbreviation = value;
} else {
item.publicationTitle = value;
}
} else if (field == "fjournal") {
if (item.publicationTitle) {
// move publicationTitle to abbreviation, since it probably came from 'journal'
item.journalAbbreviation = item.publicationTitle;
}
item.publicationTitle = value;
} else if (field == "author" || field == "editor" || field == "translator") {
// parse authors/editors/translators
var names = splitUnprotected(rawValue.trim(), /\s+and\s+/gi);
for (var i in names) {
var name = names[i];
// skip empty names
if (!name) continue;
// Names in BibTeX can have three commas
var pieces = splitUnprotected(name, /\s*,\s*/g);
var creator = {};
if (pieces.length > 1) {
creator.firstName = pieces.pop();
creator.lastName = unescapeBibTeX(pieces.shift());
if (pieces.length) {
// If anything is left, it should only be the 'Jr' part
creator.firstName += ', ' + pieces.join(', ');
}
creator.firstName = unescapeBibTeX(creator.firstName);
creator.creatorType = field;
} else if (splitUnprotected(name, / +/g).length > 1){
creator = Zotero.Utilities.cleanAuthor(unescapeBibTeX(name), field, false);
} else {
creator = {
lastName: unescapeBibTeX(name),
creatorType: field,
fieldMode: 1
};
}
item.creators.push(creator);
}
} else if (field == "institution" || field == "organization") {
item.backupPublisher = value;
} else if (field == "location") {
item.backupLocation = value;
} else if (field == "number") { // fix for techreport
if (item.itemType == "report") {
item.reportNumber = value;
} else if (item.itemType == "book" || item.itemType == "bookSection") {
item.seriesNumber = value;
} else if (item.itemType == "patent"){
item.patentNumber = value;
} else {
item.issue = value;
}
} else if (field == "day") {
// this and the following two blocks assign to temporary fields that
// are cleared before the item is completed. "day" isn't an official
// field, but some sites use it.
item.day = value;
} else if (field == "month") {
var monthIndex = months.indexOf(value.toLowerCase());
if (monthIndex != -1) {
value = Zotero.Utilities.formatDate({month:monthIndex});
}
item.month = value;
} else if (field == "year") {
item.year = value;
} else if (field == "date") {
//We're going to assume that "date" and the date parts don't occur together. If they do, we pick date, which should hold all.
item.date = value;
} else if (field == "pages") {
if (item.itemType == "book" || item.itemType == "thesis" || item.itemType == "manuscript") {
item.numPages = value;
}
else {
item.pages = value.replace(/--/g, "-");
}
} else if (field == "note") {
var isExtraId = false;
for (var element in extraIdentifiers) {
if (value.trim().startsWith(extraIdentifiers[element])) {
isExtraId = true;
}
}
if (isExtraId) {
item._extraFields.push({raw: value.trim()});
} else {
item.notes.push({note:Zotero.Utilities.text2html(value)});
}
} else if (field == "howpublished") {
if (value.length >= 7) {
var str = value.substr(0, 7);
if (str == "http://" || str == "https:/" || str == "mailto:") {
item.url = value;
} else {
item._extraFields.push({field: 'Published', value: value});
}
}
}
//accept lastchecked or urldate for access date. These should never both occur.
//If they do we don't know which is better so we might as well just take the second one
else if (field == "lastchecked"|| field == "urldate"){
item.accessDate = value;
} else if (field == "keywords" || field == "keyword") {
item.tags = value.split(keywordDelimRe);
if (item.tags.length == 1 && keywordSplitOnSpace) {
item.tags = value.split(/\s+/);
}
} else if (field == "comment" || field == "annote" || field == "review" || field == "notes") {
item.notes.push({note:Zotero.Utilities.text2html(value)});
} else if (field == "pdf" || field == "path" /*Papers2 compatibility*/) {
item.attachments.push({path:value, mimeType:"application/pdf"});
} else if (field == "sentelink") { // the reference manager 'Sente' has a unique file scheme in exported BibTeX; it can occur multiple times
item.attachments.push({path:value.split(",")[0], mimeType:"application/pdf"});
} else if (field == "file") {
var start = 0, attachment;
rawValue = rawValue.replace(/\$\\backslash\$/g, '\\') // Mendeley invention?
.replace(/([^\\](?:\\\\)*)\\(.){}/g, '$1$2'); // part of Mendeley's escaping (e.g. \~{} = ~)
for (var i=0; i<rawValue.length; i++) {
if (rawValue[i] == '\\') {
i++; //skip next char
continue;
}
if (rawValue[i] == ';') {
attachment = parseFilePathRecord(rawValue.slice(start, i));
if (attachment) item.attachments.push(attachment);
start = i+1;
}
}
attachment = parseFilePathRecord(rawValue.slice(start));
if (attachment) item.attachments.push(attachment);
} else if (field == "eprint" || field == "eprinttype") {
// Support for IDs exported by BibLaTeX
if (field == 'eprint') item._eprint = value;
else item._eprinttype = value;
var eprint = item._eprint;
var eprinttype = item._eprinttype;
// If we don't have both yet, continue
if (!eprint || !eprinttype) return;
var label = eprintIds[eprinttype.trim().toLowerCase()];
if (!label) return;
item._extraFields.push({field: label, value: eprint.trim()});
delete item._eprinttype;
delete item._eprint;
} else if (extraIdentifiers[field]) {
var label = extraIdentifiers[field];
item._extraFields.push({field: label, value: value.trim()});
}
}
/**
* Split a string on a provided delimiter, but not if delimiter appears inside { }
* @param {String} str String to split
* @param {RegExp} delim RegExp object for the split delimiter. Use g flag to split on each
* @return {String[]} Array of strings without delimiters
*/
function splitUnprotected(str, delim) {
delim.lastIndex = 0; // In case we're reusing a regexp
var nextPossibleSplit = delim.exec(str);
if (!nextPossibleSplit) return [str];
var parts = [], open = 0, nextPartStart = 0;
for (var i=0; i<str.length; i++) {
if (i>nextPossibleSplit.index) {
// Must have been inside braces
nextPossibleSplit = delim.exec(str);
if (!nextPossibleSplit) {
parts.push(str.substr(nextPartStart));
return parts;
}
}
if (str[i] == '\\') {
// Skip next character
i++;
continue;
}
if (str[i] == '{') {
open++;
continue;
}
if (str[i] == '}') {
open--;
if (open < 0) open = 0; // Shouldn't happen, but...
continue;
}
if (open) continue;
if (i == nextPossibleSplit.index) {
parts.push(str.substring(nextPartStart, i));
i += nextPossibleSplit[0].length - 1; // We can jump past the split delim
nextPartStart = i + 1;
nextPossibleSplit = delim.exec(str);
if (!nextPossibleSplit) {
parts.push(str.substr(nextPartStart));
return parts;
}
}
}
// I don't think we should ever get here*, but just to be safe
// *we should always be returning from the for loop
var last = str.substr(nextPartStart).trim();
if (last) parts.push(last);
return parts;
}
function parseFilePathRecord(record) {
var start = 0, fields = [];
for (var i=0; i<record.length; i++) {
if (record[i] == '\\') {
i++;
continue;
}
if (record[i] == ':') {
fields.push(decodeFilePathComponent(record.slice(start, i)));
start = i+1;
}
}
fields.push(decodeFilePathComponent(record.slice(start)));
if (fields.length != 3 && fields.length != 1) {
Zotero.debug("Unknown file path record format: " + record);
return;
}
var attachment = {};
if (fields.length == 3) {
attachment.title = fields[0].trim() || 'Attachment';
attachment.path = fields[1];
attachment.mimeType = fields[2];
if (attachment.mimeType.search(/pdf/i) != -1) {
attachment.mimeType = 'application/pdf';
}
} else {
attachment.title = 'Attachment';
attachment.path = fields[0];
}
attachment.path = attachment.path.trim();
if (!attachment.path) return;
return attachment;
}
function getFieldValue(read) {
var value = "";
// now, we have the first character of the field
if (read == "{") {
// character is a brace
var openBraces = 1, nextAsLiteral = false;
while (read = Zotero.read(1)) {
if (nextAsLiteral) { // Previous character was a backslash
value += read;
nextAsLiteral = false;
continue;
}
if (read == "\\") {
value += read;
nextAsLiteral = true;
continue;
}
if (read == "{") {
openBraces++;
value += "{";
} else if (read == "}") {
openBraces--;
if (openBraces == 0) {
break;
} else {
value += "}";
}
} else {
value += read;
}
}
} else if (read == '"') {
var openBraces = 0;
while (read = Zotero.read(1)) {
if (read == "{" && value[value.length-1] != "\\") {
openBraces++;
value += "{";
} else if (read == "}" && value[value.length-1] != "\\") {
openBraces--;
value += "}";
} else if (read == '"' && openBraces == 0) {
break;
} else {
value += read;
}
}
}
return value;
}
function unescapeBibTeX(value) {
if (value.length < 2) return value;
// replace accented characters (yucky slow)
value = value.replace(/{?(\\[`"'^~=]){?\\?([A-Za-z])}/g, "{$1$2}");
// normalize some special characters, e.g. caron \v{c} -> {\v c}
value = value.replace(/(\\[a-z]){(\\?[A-Za-z])}/g, "{$1 $2}");
//convert tex markup into permitted HTML
value = mapTeXmarkup(value);
for (var mapped in reversemappingTable) { // really really slow!
var unicode = reversemappingTable[mapped];
while (value.includes(mapped)) {
Zotero.debug("Replace " + mapped + " in " + value + " with " + unicode);
value = value.replace(mapped, unicode);
}
mapped = mapped.replace(/[{}]/g, "");
while (value.includes(mapped)) {
//Z.debug(value)
Zotero.debug("Replace(2) " + mapped + " in " + value + " with " + unicode);
value = value.replace(mapped, unicode);
}
}
value = value.replace(/\$([^$]+)\$/g, '$1')
// kill braces
value = value.replace(/([^\\])[{}]+/g, "$1");
if (value[0] == "{") {
value = value.substr(1);
}
// chop off backslashes
value = value.replace(/([^\\])\\([#$%&~_^\\{}])/g, "$1$2");
value = value.replace(/([^\\])\\([#$%&~_^\\{}])/g, "$1$2");
if (value[0] == "\\" && "#$%&~_^\\{}".includes(value[1])) {
value = value.substr(1);
}
if (value[value.length-1] == "\\" && "#$%&~_^\\{}".includes(value[value.length-2])) {
value = value.substr(0, value.length-1);
}
value = value.replace(/\\\\/g, "\\");
value = value.replace(/\s+/g, " ");
// Unescape HTML entities coming from web translators
if (Zotero.parentTranslator && value.includes('&')) {
value = value.replace(/&#?\w+;/g, function(entity) {
var char = ZU.unescapeHTML(entity);
if (char == entity) char = ZU.unescapeHTML(entity.toLowerCase()); // Sometimes case can be incorrect and entities are case-sensitive
return char;
});
}
return value;
}
function jabrefSplit(str, sep) {
var quoted = false;
var result = [];
str = str.split('');
while (str.length > 0) {
if (result.length == 0) { result = ['']; }
if (str[0] == sep) {
str.shift();
result.push('');
} else {
if (str[0] == '\\') { str.shift(); }
result[result.length - 1] += str.shift();
}
}
return result;
}
function jabrefCollect(arr, func) {
if (arr == null) { return []; }
var result = [];
for (var i = 0; i < arr.length; i++) {
if (func(arr[i])) {
result.push(arr[i]);
}
}
return result;
}
function processComment() {
var comment = "";
var read;
var collectionPath = [];
var parentCollection, collection;
while (read = Zotero.read(1)) {
if (read == "}") { break; } // JabRef ought to escape '}' but doesn't; embedded '}' chars will break the import just as it will on JabRef itself
comment += read;
}
if (comment == 'jabref-meta: groupsversion:3;') {
jabref.format = 3;
return;
}
if (comment.startsWith('jabref-meta: groupstree:')) {
if (jabref.format != 3) {
Zotero.debug("jabref: fatal: unsupported group format: " + jabref.format);
return;
}
comment = comment.replace(/^jabref-meta: groupstree:/, '').replace(/[\r\n]/gm, '');
var records = jabrefSplit(comment, ';');
while (records.length > 0) {
var record = records.shift();
var keys = jabrefSplit(record, ';');
if (keys.length < 2) { continue; }
var record = {id: keys.shift()};
record.data = record.id.match(/^([0-9]) ([^:]*):(.*)/);
if (record.data == null) {
Zotero.debug("jabref: fatal: unexpected non-match for group " + record.id);
return;
}
record.level = parseInt(record.data[1]);
record.type = record.data[2];
record.name = record.data[3];
record.intersection = keys.shift(); // 0 = independent, 1 = intersection, 2 = union
if (isNaN(record.level)) {
Zotero.debug("jabref: fatal: unexpected record level in " + record.id);
return;
}
if (record.level == 0) { continue; }
if (record.type != 'ExplicitGroup') {
Zotero.debug("jabref: fatal: group type " + record.type + " is not supported");
return;
}
collectionPath = collectionPath.slice(0, record.level - 1).concat([record.name]);
Zotero.debug("jabref: locating level " + record.level + ": " + collectionPath.join('/'));
if (jabref.root.hasOwnProperty(collectionPath[0])) {
collection = jabref.root[collectionPath[0]];
Zotero.debug("jabref: root " + collection.name + " found");
} else {
collection = new Zotero.Collection();
collection.name = collectionPath[0];
collection.type = 'collection';
collection.children = [];
jabref.root[collectionPath[0]] = collection;
Zotero.debug("jabref: root " + collection.name + " created");
}
parentCollection = null;
for (var i = 1; i < collectionPath.length; i++) {
var path = collectionPath[i];
Zotero.debug("jabref: looking for child " + path + " under " + collection.name);
var child = jabrefCollect(collection.children, function(n) { return (n.name == path); });
if (child.length != 0) {
child = child[0];
Zotero.debug("jabref: child " + child.name + " found under " + collection.name);
} else {
child = new Zotero.Collection();
child.name = path;
child.type = 'collection';
child.children = [];
collection.children.push(child);
Zotero.debug("jabref: child " + child.name + " created under " + collection.name);
}
parentCollection = collection;
collection = child;
}
if (parentCollection) {
parentCollection = jabrefCollect(parentCollection.children, function(n) { return (n.type == 'item'); });
}
if (record.intersection == '2' && parentCollection) { // union with parent
collection.children = parentCollection;
}
while (keys.length > 0) {
var key = keys.shift();
if (key != '') {
Zotero.debug('jabref: adding ' + key + ' to ' + collection.name);
collection.children.push({type: 'item', id: key});
}
}
if (parentCollection && record.intersection == '1') { // intersection with parent
collection.children = jabrefMap(collection.children, function(n) { parentCollection.includes(n); });
}
}
}
}
function beginRecord(type, closeChar) {
type = Zotero.Utilities.trimInternal(type.toLowerCase());
if (type !== "string" && type !== "preamble") {
var zoteroType = bibtex2zoteroTypeMap[type];
if (!zoteroType) {
Zotero.debug("discarded item from BibTeX; type was "+type);
return;
}
var item = new Zotero.Item(zoteroType);
item._extraFields = [];
}
else if (type == "preamble") { // Preamble (keeping separate in case we want to do something with these)
Zotero.debug("discarded preamble from BibTeX");
return;
}
// For theses write the thesisType determined by the BibTeX type.
if (type == "mastersthesis" && item) item.type = "Master's Thesis";
if (type == "phdthesis" && item) item.type = "PhD Thesis";
var field = "";
// by setting dontRead to true, we can skip a read on the next iteration
// of this loop. this is useful after we read past the end of a string.
var dontRead = false;
var value, rawValue;
while (dontRead || (read = Zotero.read(1))) {
dontRead = false;
// the equal sign indicate the start of the value
// which will be handled in the following part
// possible formats are:
// = 42,
// = "42",
// = {42},
// = name, (where this is defined as a string)
if (read == "=") {
var valueArray = [];
var rawValueArray = [];
// concatenation is possible with # and for that we
// do this do-while-loop here, e.g.
// = name # " and " # "Adam Smith",
do {
var read = Zotero.read(1);
// skip whitespaces
while (" \n\r\t".includes(read)) {
read = Zotero.read(1);
}
if (keyRe.test(read)) {
// read numeric data here, since we might get an end bracket
// that we should care about
value = "";
value += read;
// character is a number or part of a string name
while ((read = Zotero.read(1)) && /[a-zA-Z0-9\-:_]/.test(read)) {
value += read;
}
// don't read the next char; instead, process the character
// we already read past the end of the string
dontRead = true;
// see if there's a defined string
if (strings[value.toLowerCase()]) value = strings[value.toLowerCase()];
// rawValue has to be set for some fields to process
// thus, in this case, we set it equal to value
rawValue = value;
} else {
rawValue = getFieldValue(read);
value = unescapeBibTeX(rawValue);
}
valueArray.push(value);
rawValueArray.push(rawValue);
while (" \n\r\t".includes(read)) {
read = Zotero.read(1);
}
} while (read === "#");
value = valueArray.join('');
rawValue = rawValueArray.join('');
if (item) {
processField(item, field.toLowerCase(), value, rawValue);
} else if (type == "string") {
strings[field.toLowerCase()] = value;
}
field = "";
}
// commas reset, i.e. we are not reading a field
// but rather we are reading the bibkey
else if (read == ",") {
if (item.itemID == null) {
item.itemID = field; // itemID = citekey
}
field = "";
}
// closing character
else if (read == closeChar) {
if (item) {
if (item.backupLocation) {
if (item.itemType=="conferencePaper") {
item._extraFields.push({field: "event-place", value: item.backupLocation});
} else if (!item.place) {
item.place = item.backupLocation;
}
delete item.backupLocation;
}
if (!item.date) {
item.date = dateFieldsToDate(item.year, item.month, item.day);
}
delete item.year;
delete item.month;
delete item.day;
item.extra = extraFieldsToString(item._extraFields);
delete item._extraFields;
if (!item.publisher && item.backupPublisher){
item.publisher=item.backupPublisher;
delete item.backupPublisher;
}
return item.complete();
}
return;
}
// skip whitespaces; the rest will become
// the field name (or bibkey)
else if (!" \n\r\t".includes(read)) {