Debian Codegraph @

texmf-dist/scripts/citation-style-language/citeproc-bibtex2csl.lua

raw symbols SCIP
1 --
2 -- Copyright (c) 2021-2026 Zeping Lee
3 -- Released under the MIT license.
4 -- Repository: https://github.com/zepinglee/citeproc-lua
5 --
6
7 local bibtex2csl = {}
8
9 local uni_utf8
10 local bibtex_parser
11 local bibtex_data
12 local journal_data
13 local latex_parser
14 local unicode
15 local util
16 local using_luatex, _ = pcall(require, "kpse")
17 if using_luatex then
18 uni_utf8 = require("unicode").utf8
19 bibtex_parser = require("citeproc-bibtex-parser")
20 bibtex_data = require("citeproc-bibtex-data")
21 unicode = require("citeproc-unicode")
22 util = require("citeproc-util")
23 else
24 uni_utf8 = require("lua-utf8")
25 bibtex_parser = require("citeproc.bibtex-parser")
26 bibtex_data = require("citeproc.bibtex-data")
27 unicode = require("citeproc.unicode")
28 util = require("citeproc.util")
29 end
30
31
32 ---@alias CslItem ItemData
33 ---@alias CslData CslItem[]
34
35
36 ---Parse BibTeX content and convert to CSL-JSON
37 ---@param str string
38 ---@param keep_unknown_commands boolean? Keep unknown latex markups in <code>.
39 ---@param case_protection boolean? Add case-protection to braces as in BibTeX.
40 ---@param sentence_case_title boolean? Convert `title` and `booktitle` to sentence case.
41 ---@param check_sentence_case boolean? Check titles that are already sentence cased and do not conver them.
42 ---@return CslData?, Exception[]
43 function bibtex2csl.parse_bibtex_to_csl(str, keep_unknown_commands, case_protection, sentence_case_title,
44 check_sentence_case)
45 local strings = {}
46 for name, macro in pairs(bibtex_data.macros) do
47 strings[name] = macro.value
48 end
49 local bib_data, exceptions = bibtex_parser.parse(str, strings)
50 local csl_json_items = nil
51 if bib_data then
52 -- TODO: Ideally we should load all .bib files and then resolve crossrefs and related
53 bibtex_parser.resolve_crossrefs(bib_data.entries, bibtex_data.entries_by_id)
54 csl_json_items = bibtex2csl.convert_to_csl_data(bib_data, keep_unknown_commands, case_protection,
55 sentence_case_title, check_sentence_case)
56 end
57 return csl_json_items, exceptions
58 end
59
60
61 ---@param bib BibtexData
62 ---@param keep_unknown_commands boolean?
63 ---@param case_protection boolean?
64 ---@param sentence_case_title boolean?
65 ---@param check_sentence_case boolean?
66 ---@return CslData
67 function bibtex2csl.convert_to_csl_data(bib, keep_unknown_commands, case_protection, sentence_case_title,
68 check_sentence_case)
69 local csl_data = {}
70
71 -- BibTeX looks for crossref in a case-insensitive manner.
72 local bib_entry_dict = {}
73 local csl_item_dict = {}
74
75 for _, entry in ipairs(bib.entries) do
76 bib_entry_dict[unicode.casefold(entry.key)] = entry
77 local item = bibtex2csl.convert_to_csl_item(entry, keep_unknown_commands, case_protection, sentence_case_title,
78 check_sentence_case)
79
80 table.insert(csl_data, item)
81 csl_item_dict[item.id] = item
82 end
83
84 bibtex2csl.resolve_related(csl_item_dict, bib_entry_dict)
85
86 return csl_data
87 end
88
89
90 ---@param entry BibtexEntry
91 ---@param keep_unknown_commands boolean?
92 ---@param case_protection boolean?
93 ---@param sentence_case_title boolean?
94 ---@param check_sentence_case boolean?
95 ---@return CslItem
96 function bibtex2csl.convert_to_csl_item(entry, keep_unknown_commands, case_protection, sentence_case_title,
97 check_sentence_case, disable_journal_abbreviation)
98 ---@type CslItem
99 local item = {
100 id = entry.key,
101 type = "document",
102 }
103
104 bibtex2csl.pre_process_special_fields(item, entry)
105
106 -- First convert primary fields
107 for field, csl_field in pairs(bibtex_data.primary_fields) do
108 local value = entry.fields[field]
109 if value then
110 local _, csl_value = bibtex2csl.convert_field(
111 field, value, keep_unknown_commands, case_protection, sentence_case_title, item.language, check_sentence_case)
112 if csl_field and csl_value and not item[csl_field] then
113 item[csl_field] = csl_value
114 end
115 end
116 end
117
118 -- Convert the fields in a fixed order
119 local field_list = {}
120 for field, _ in pairs(entry.fields) do
121 table.insert(field_list, field)
122 end
123 table.sort(field_list)
124
125 for _, field in ipairs(field_list) do
126 local value = entry.fields[field]
127 local csl_field, csl_value = bibtex2csl.convert_field(
128 field, value, keep_unknown_commands, case_protection, sentence_case_title, item.language, check_sentence_case)
129 if csl_field and csl_value and not item[csl_field] then
130 item[csl_field] = csl_value
131 end
132 end
133
134 bibtex2csl.post_process_special_fields(item, entry, disable_journal_abbreviation)
135 return item
136 end
137
138
139 ---@param item CslItem
140 ---@param entry BibtexEntry
141 function bibtex2csl.pre_process_special_fields(item, entry)
142 -- CSL types
143 local type_data = bibtex_data.types[entry.type]
144 if type_data and type_data.csl then
145 item.type = type_data.csl
146 elseif entry.fields.url then
147 item.type = "webpage"
148 end
149
150 -- BibTeX's `edition` is expected to be an ordinal.
151 if entry.fields.edition then
152 item.edition = util.convert_ordinal_to_arabic(entry.fields.edition)
153 end
154
155 -- language: convert `babel` language to ISO 639-1 language code
156 local lang = entry.fields.langid or entry.fields.language
157 if lang then
158 item.language = bibtex_data.language_code_map[unicode.casefold(lang)]
159 end
160 -- if not item.language then
161 -- if util.has_cjk_char(item.title) then
162 -- item.language = "zh"
163 -- end
164 -- end
165
166 -- Merge title, maintitle, subtitle, titleaddon
167 bibtex2csl.process_titles(entry)
168
169 -- biblatex-apa
170 if entry.fields.howpublished then
171 local howpublished = string.lower(entry.fields.howpublished)
172 if howpublished == "advance online publication" then
173 -- TODO: get_locale_term("advance online publication" )
174 item.status = "Advance online publication"
175 elseif howpublished == "manunpub" then
176 -- biblatex-apa
177 item.genre = "Unpublished manuscript"
178 elseif howpublished == "maninprep" then
179 -- biblatex-apa
180 item.genre = "Manuscript in preparation"
181 elseif howpublished == "mansub" then
182 -- biblatex-apa
183 item.genre = "Manuscript submitted for publication"
184 end
185 end
186 if entry.fields.pubstate
187 and string.lower(entry.fields.pubstate) == "inpress" then
188 -- TODO: get_locale_term("advance online publication" )
189 item.status = "in press"
190 end
191 end
192
193
194 ---@param entry BibtexEntry
195 function bibtex2csl.process_titles(entry)
196 local fields = entry.fields
197 -- title and subtitle
198 if fields.subtitle then
199 if fields.title then
200 fields.title = util.join_title(fields.title, fields.subtitle)
201 if not fields.shorttitle then
202 fields.shorttitle = fields.title
203 end
204 else
205 fields.title = fields.subtitle
206 end
207 fields.subtitle = nil
208 end
209
210 -- booktitle and booksubtitle
211 if fields.booksubtitle then
212 if not fields["container-title-short"] then
213 fields["container-title-short"] = fields.booktitle
214 end
215 if fields.booktitle then
216 fields.booktitle = util.join_title(fields.booktitle, fields.booksubtitle)
217 else
218 fields.booktitle = fields.booksubtitle
219 end
220 fields.booksubtitle = nil
221 end
222
223 -- mainsubtitle
224 if fields.mainsubtitle then
225 if fields.maintitle then
226 fields.maintitle = util.join_title(fields.maintitle, fields.mainsubtitle)
227 else
228 fields.maintitle = fields.mainsubtitle
229 end
230 end
231
232 -- maintitle
233 if fields.maintitle then
234 if entry.type == "audio" or entry.type == "video" then
235 -- maintitle is the container-title
236 fields["container-title"] = fields.maintitle
237 elseif fields.booktitle then
238 -- maintitle is with booktitle
239 if not fields["volume-title"] then
240 fields["volume-title"] = fields.booktitle
241 fields.booktitle = fields.maintitle
242 end
243 else
244 -- maintitle is with title
245 if fields.title then
246 if not fields["volume-title"] then
247 fields["volume-title"] = fields.title
248 fields.title = fields.maintitle
249 end
250 else
251 -- This is unlikelu to happen.
252 fields.title = fields.maintitle
253 end
254 end
255 end
256
257 if fields.journalsubtitle then
258 if fields.journaltitle then
259 fields.journaltitle = util.join_title(fields.journaltitle, fields.journalsubtitle)
260 elseif fields.journal then
261 fields.journal = util.join_title(fields.journal, fields.journal)
262 end
263 fields.journalsubtitle = nil
264 end
265 if fields.issuesubtitle then
266 if fields.issuetitle then
267 fields.issuetitle = util.join_title(fields.issuetitle, fields.issuesubtitle)
268 else
269 fields.issuetitle = fields.issuesubtitle
270 end
271 fields.issuesubtitle = nil
272 end
273 end
274
275
276 ---Convert BibTeX field to CSL field
277 ---@param bib_field string
278 ---@param value string
279 ---@param keep_unknown_commands boolean?
280 ---@param case_protection boolean?
281 ---@param sentence_case_title boolean?
282 ---@param language string?
283 ---@param check_sentence_case boolean?
284 ---@return string? csl_field
285 ---@return string | table | number? csl_value
286 function bibtex2csl.convert_field(bib_field, value, keep_unknown_commands, case_protection, sentence_case_title,
287 language, check_sentence_case)
288 local field_data = bibtex_data.fields[bib_field]
289 if not field_data then
290 return nil, nil
291 end
292 local csl_field = field_data.csl
293 if not (csl_field and type(csl_field) == "string") then
294 return nil, nil
295 end
296
297 if using_luatex then
298 latex_parser = latex_parser or require("citeproc-latex-parser")
299 else
300 latex_parser = latex_parser or require("citeproc.latex-parser")
301 end
302
303 local field_type = field_data.type
304 local csl_value
305 if field_type == "name" then
306 -- 1. unicode 2. prify (remove LaTeX markups) 3. plain text 4. split name parts
307 value = latex_parser.latex_to_unicode(value)
308 local names = bibtex_parser.split_names(value)
309 csl_value = {}
310 for i, name_str in ipairs(names) do
311 local name_dict = bibtex_parser.split_name_parts(name_str)
312 csl_value[i] = bibtex2csl.convert_to_csl_name(name_dict)
313 end
314
315 elseif field_type == "date" then
316 if string.match(value, "\\") then
317 -- "{\noopsort{1973c}}1981"
318 value = latex_parser.latex_to_pseudo_html(value, false, false)
319 end
320 -- "-3000~" should not be converted to "-3000 "
321 csl_value = util.parse_edtf(value)
322
323 elseif bib_field == "title" or bib_field == "shorttitle"
324 or bib_field == "booktitle" or bib_field == "container-title-short" then
325 -- 1. unicode 2. sentence case 3. html tag
326 if sentence_case_title and (not language or util.startswith(language, "en")) then
327 csl_value = latex_parser.latex_to_sentence_case_pseudo_html(value, keep_unknown_commands, case_protection,
328 check_sentence_case)
329 else
330 csl_value = latex_parser.latex_to_pseudo_html(value, keep_unknown_commands, case_protection)
331 end
332
333 else
334 -- 1. unicode 2. html tag
335 csl_value = latex_parser.latex_to_pseudo_html(value, keep_unknown_commands, case_protection)
336 if csl_field == "volume" or csl_field == "page" then
337 csl_value = string.gsub(csl_value, util.unicode["en dash"], "-")
338 end
339 end
340
341 return csl_field, csl_value
342 end
343
344
345 local function clean_name_part(name_part)
346 if not name_part then
347 return nil
348 end
349 return string.gsub(name_part, "[{}]", "")
350 end
351
352
353 function bibtex2csl.convert_to_csl_name(bibtex_name)
354 if bibtex_name.last and not (bibtex_name.first or bibtex_name.von or bibtex_name.jr)
355 and string.match(bibtex_name.last, "^%b{}$") then
356 return {
357 literal = string.sub(bibtex_name.last, 2, -2),
358 }
359 end
360 local csl_name = {
361 family = clean_name_part(bibtex_name.last),
362 ["non-dropping-particle"] = clean_name_part(bibtex_name.von),
363 given = clean_name_part(bibtex_name.first),
364 suffix = clean_name_part(bibtex_name.jr),
365 }
366 return csl_name
367 end
368
369
370 local arxiv_url_prefix = "https://arxiv.org/abs/"
371 local pubmed_url_prefix = "https://www.ncbi.nlm.nih.gov/pubmed/"
372 local pubmed_central_url_prefix = "https://www.ncbi.nlm.nih.gov/pmc/articles/"
373
374
375 ---@param item CslItem
376 ---@param entry BibtexEntry
377 function bibtex2csl.post_process_special_fields(item, entry, disable_journal_abbreviation)
378 local bib_type = entry.type
379 local bib_fields = entry.fields
380
381 -- biblatex-apa
382 if item.type == "article-journal" and entry.fields.entrysubtype == "nonacademic" then
383 item.type = "article-magazine"
384 item.genre = nil
385
386 elseif item.type == "motion_picture" then
387 if entry.fields.entrysubtype == "tvseries" then
388 item.type = "broadcast"
389 if item.genre == "tvseries" then
390 item.genre = "TV series"
391 end
392 elseif entry.fields.entrysubtype == "tvepisode" then
393 item.type = "broadcast"
394 if item.genre == "tvepisode" then
395 item.genre = "TV series episode"
396 end
397 end
398
399 elseif item.type == "song" then
400 if entry.fields.entrysubtype == "podcast" then
401 item.type = "broadcast"
402 if item.genre == "podcast" then
403 item.genre = "Audio podcast"
404 end
405
406 elseif entry.fields.entrysubtype == "podcastepisode" then
407 item.type = "broadcast"
408 if item.genre == "podcastepisode" then
409 item.genre = "Audio podcast episode"
410 end
411
412 elseif entry.fields.entrysubtype == "interview" then
413 item.type = "interview"
414
415 elseif entry.fields.entrysubtype == "speech" then
416 item.type = "speech"
417
418 end
419
420 elseif item.type == "graphic" then
421 item["archive-place"] = item["publisher-place"]
422
423 if entry.fields.entrysubtype == "map" then
424 item.type = "map"
425 end
426
427 elseif item.type == "webpage" then
428
429 -- eprinttype is mapped to
430 -- - `archive` for Google books;
431 -- - `container-title` for twitter post;
432 -- - `publisher` for arXiv preprint;
433
434 local eprint_type_map = {
435 facebook = "post",
436 instagram = "post",
437 reddit = "post",
438 twitter = "post",
439 arxiv = "preprint",
440 psyarxiv = "preprint",
441 pubmed = "preprint",
442 ["pubmed central"] = "preprint",
443 }
444
445 -- Biblatex's `online` type can be mapped to `post`, `preprint`
446 -- local eprinttype = entry.fields.eprinttype or entry.fields.archiveprefix
447 if item.archive then
448 local eprint_type = eprint_type_map[string.lower(item.archive)]
449 if eprint_type then
450 item.type = eprint_type
451 elseif item.number then
452 item.type = "preprint"
453 elseif entry.fields.eprint then
454 item.type = "preprint"
455 item.numerb = entry.fields.eprint
456 elseif item.DOI then
457 item.type = "preprint"
458 elseif item.URL then
459 if util.startswith(item.URL, arxiv_url_prefix) then
460 item.type = "preprint"
461 elseif util.startswith(item.URL, pubmed_url_prefix) then
462 item.type = "preprint"
463 elseif util.startswith(item.URL, pubmed_central_url_prefix) then
464 item.type = "preprint"
465 end
466 end
467 if item.type == "preprint" then
468 if not item.publisher then
469 item.publisher = item.archive
470 item.archive = nil
471 end
472 if not item.number then
473 item.number = entry.fields.eprint
474 end
475 else
476 if not item["container-title"] then
477 item["container-title"] = item.archive
478 item.archive = nil
479 end
480 end
481 end
482
483 end
484
485 -- event-date
486 if item["event-date"] and not item.issued then
487 item.issued = util.deep_copy(item["event-date"])
488 end
489
490 -- event-title: for compatibility with CSL v1.0.1 and earlier versions
491 if item["event-title"] then
492 item.event = item["event-title"]
493 end
494
495 -- Jounal abbreviations
496 if not disable_journal_abbreviation then
497 if item.type == "article-journal" or item.type == "article-magazine"
498 or item.type == "article-newspaper" then
499 bibtex2csl.check_journal_abbreviations(item)
500 end
501 end
502
503 if not item.genre then
504 if bib_type == "phdthesis" then
505 -- from APA
506 item.genre = "Doctoral dissertation"
507 elseif bib_type == "mastersthesis" then
508 item.genre = "Master’s thesis"
509 end
510 end
511
512 -- month
513 -- local month = bib_fields.month
514 local month_text = bib_fields.month
515 if month_text then
516 month_text = latex_parser.latex_to_pseudo_html(month_text, false, false)
517 local month, day = uni_utf8.match(month_text, "^(%a+)%.?,?%s+(%d+)%a*$")
518 if not month then
519 day, month = uni_utf8.match(month_text, "^(%d+)%a*%s+(%a+)%.?$")
520 end
521 if not month then
522 month = string.match(month_text, "^(%a+)%.?$")
523 end
524 if month then
525 month = bibtex_data.months[unicode.casefold(month)]
526 end
527 if month and item.issued and item.issued["date-parts"] and
528 item.issued["date-parts"][1] and
529 item.issued["date-parts"][1][2] == nil then
530 item.issued["date-parts"][1][2] = tonumber(month)
531 if day then
532 item.issued["date-parts"][1][3] = tonumber(day)
533 end
534 end
535 end
536
537 -- number
538 if bib_fields.number then
539 if item.type == "article-journal" or item.type == "article-magazine" or
540 item.type == "article-newspaper" or item.type == "periodical" then
541 if not item.issue then
542 item.issue = bib_fields.number
543 end
544 elseif item["collection-title"] and not item["collection-number"] then
545 item["collection-number"] = bib_fields.number
546 elseif not item.number then
547 item.number = string.gsub(bib_fields.number, "([^-])%-([^-])", "%1\\-%2")
548 end
549 end
550
551 -- organization: the `organizer` that sponsors a conference or a `publisher` that publishes a `@manual` or `@online`.
552 if bib_fields.organization then
553 if item.publisher or bib_type == "inproceedings" or bib_type == "proceedings" then
554 if not item.organizer then
555 item.organizer = {
556 literal = bib_fields.organization,
557 }
558 end
559 elseif not item.publisher then
560 item.publisher = bib_fields.organization
561 end
562 end
563
564 -- DOI
565 if type(item.DOI) == "string" then
566 item.DOI = util.remove_prefix(item.DOI, "https://doi.org/")
567 item.DOI = util.remove_prefix(item.DOI, "doi.org/")
568 end
569
570 -- PMID
571 if bib_fields.eprint and type(bib_fields.eprinttype) == "string" and
572 string.lower(bib_fields.eprinttype) == "pubmed" and not item.PMID then
573 item.PMID = bib_fields.eprint
574 end
575
576 if item.URL then
577 if item.type == "preprint" and util.startswith(item.URL, arxiv_url_prefix) then
578 if not item.publisher then
579 item.publisher = "arXiv"
580 item.archive = nil
581 end
582 if not item.number then
583 item.number = util.remove_prefix(item.URL, pubmed_url_prefix)
584 end
585 end
586
587 if util.startswith(item.URL, pubmed_url_prefix) then
588 if not item.publisher then
589 item.publisher = "PubMed"
590 item.archive = nil
591 end
592 if not item.PMID then
593 item.PMID = util.remove_prefix(item.URL, pubmed_url_prefix)
594 end
595 end
596
597 if util.startswith(item.URL, pubmed_central_url_prefix) then
598 if not item.publisher then
599 item.publisher = "PubMed Central"
600 item.archive = nil
601 end
602 if not item.PMCID then
603 item.PMCID = util.remove_prefix(item.URL, pubmed_central_url_prefix)
604 end
605 end
606 end
607
608 -- `APA Education [@APAEducation], (2018, June 29). College students are forming menta/-health c/ubs-and they're making a difference @washingtonpost [Thumbnail with link attached]`
609 -- The `[Thumbnail with link attached]` should not be italicized.
610 -- if bib_fields.titleaddon and item.genre and item.genre ~= bib_fields.titleaddon then
611 -- if item.title then
612 -- item.title = string.format("%s [%s]", item.title, bib_fields.titleaddon)
613 -- end
614 -- end
615
616 end
617
618
619 function bibtex2csl.check_journal_abbreviations(item)
620 if item["container-title"] and not item["container-title-short"] then
621 if not journal_data then
622 if using_luatex then
623 journal_data = require("citeproc-journal-data")
624 else
625 journal_data = require("citeproc.journal-data")
626 end
627 end
628 local key = unicode.casefold(string.gsub(item["container-title"], "%.", ""))
629 local abbr = journal_data.abbrevs[key]
630 if abbr then
631 item["container-title-short"] = abbr
632 else
633 local full = journal_data.unabbrevs[key]
634 if full then
635 item["container-title-short"] = item["container-title"]
636 item["container-title"] = full
637 end
638 end
639 end
640 end
641
642
643 local original_field_dict = {
644 author = "original-author",
645 issued = "original-date",
646 publisher = "original-publisher",
647 ["publisher-place"] = "original-publisher-place",
648 title = "original-title",
649 }
650
651 local reviewed_field_dict = {
652 author = "reviewed-author",
653 genre = "reviewed-genre",
654 title = "reviewed-title",
655 }
656
657
658 ---@param csl_item_dict table<string, CslItem>
659 ---@param bib_entry_dict table<string, BibtexEntry>
660 function bibtex2csl.resolve_related(csl_item_dict, bib_entry_dict)
661 for _, entry in pairs(bib_entry_dict) do
662 local related_key = entry.fields.related
663 local related_type = entry.fields.relatedtype
664 if related_key then
665 local related_bib_entry = bib_entry_dict[unicode.casefold(related_key)]
666 if related_bib_entry then
667 local csl_item = csl_item_dict[entry.key]
668 local related_csl_item = csl_item_dict[related_bib_entry.key]
669 if related_type == "reprintof" or related_type == "reprintfrom" then
670 for original_field, new_field in pairs(original_field_dict) do
671 if not csl_item[new_field] and related_csl_item[original_field] then
672 csl_item[new_field] = util.deep_copy(related_csl_item[original_field])
673 end
674 end
675
676 elseif related_type == "translationof" or related_type == "translationfrom" then
677 for original_field, new_field in pairs(original_field_dict) do
678 if not csl_item[new_field] and related_csl_item[original_field] then
679 csl_item[new_field] = util.deep_copy(related_csl_item[original_field])
680 end
681 end
682
683 elseif related_type == "reviewof" then
684 for reviewed_field, new_field in pairs(reviewed_field_dict) do
685 if not csl_item[new_field] and related_csl_item[reviewed_field] then
686 csl_item[new_field] = util.deep_copy(related_csl_item[reviewed_field])
687 end
688 end
689
690 end
691 else
692 util.warning(string.format('Related entry "%s" of "%s" not found.', related_key, entry.key))
693 end
694 end
695 end
696 end
697
698
699 return bibtex2csl