-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.ts
1466 lines (1256 loc) · 45.2 KB
/
index.ts
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
/* eslint-disable no-underscore-dangle */
import { Root, Macro, String as StringNode, Node, Argument, Group, Environment } from '@unified-latex/unified-latex-types'
import { replaceNode } from '@unified-latex/unified-latex-util-replace'
import { LatexPegParser } from '@unified-latex/unified-latex-util-pegjs'
import { visit } from '@unified-latex/unified-latex-util-visit'
import { printRaw } from '@unified-latex/unified-latex-util-print-raw'
import { latex2unicode as latex2unicodemap, combining } from 'unicode2latex'
import * as bibtex from './verbatim'
import * as JabRef from './jabref'
export { JabRefMetadata } from './jabref'
export { ParseError } from './verbatim'
import { toSentenceCase } from './sentence-case'
export { toSentenceCase } from './sentence-case'
import { tokenize, Token } from './tokenizer'
export { tokenize, Token } from './tokenizer'
import { playnice } from './yield'
import CrossRef from './crossref.json'
import allowed from './fields.json'
import { merge } from './merge'
function latexMode(node: Node | Argument): 'math' | 'text' {
return node._renderInfo.mode as 'math' | 'text'
}
function latex2unicode(tex: string, node: Node): string {
const text: string | Record<string, string> = latex2unicodemap[tex]
if (typeof text === 'string') return text
return text && text[latexMode(node)]
}
const open: Record<string, string> = {}
const close: Record<string, string> = {}
for (const tag of ['i', 'b', 'sc', 'nc', 'ncx', 'br', 'p', 'li', 'code']) {
open[tag] = `\x0E${tag}\x0F`
close[tag] = `\x0E/${tag}\x0F`
}
const collapsable = /\x0E\/([a-z]+)\x0F(\s*)\x0E\1\x0F/ig
type CreatorFields = {
author?: Creator[]
bookauthor?: Creator[]
collaborator?: Creator[]
commentator?: Creator[]
director?: Creator[]
editor?: Creator[]
editora?: Creator[]
editorb?: Creator[]
editors?: Creator[]
holder?: Creator[]
scriptwriter?: Creator[]
translator?: Creator[]
}
type ArrayFields = {
keywords?: string[]
institution?: string[]
publisher?: string[]
origpublisher?: string[]
organization?: string[]
location?: string[]
origlocation?: string[]
}
type TypedFields = CreatorFields & ArrayFields
type Fields = TypedFields & Omit<Record<string, string>, keyof TypedFields>
export type Entry = {
type: string
key: string
fields: Fields
mode: Record<string, ParseMode>
crossref?: {
inherited: string[]
donated: string[]
}
input: string
}
const Month = {
jan: '1',
january: '1',
feb: '2',
february: '2',
mar: '3',
march: '3',
apr: '4',
april: '4',
may: '5',
jun: '6',
june: '6',
jul: '7',
july: '7',
aug: '8',
august: '8',
sep: '9',
september: '9',
oct: '10',
october: '10',
nov: '11',
november: '11',
dec: '12',
december: '12',
}
export interface Library {
/**
* errors found while parsing
*/
errors: bibtex.ParseError[]
/**
* entries in the order in which they are found, omitting those which could not be parsed.
*/
entries: Entry[]
/**
* `@comment`s found in the bibtex file.
*/
comments: string[]
/**
* `@string`s found in the bibtex file.
*/
strings: Record<string, string>
/**
* `@preamble` declarations found in the bibtex file
*/
preamble: string[]
/**
* jabref metadata (such as groups information) found in the bibtex file
*/
jabref: JabRef.JabRefMetadata
}
export interface Options {
/**
* Bib(La)TeX handles entries that are in English differently from emtries in other languages. For English-like entries,
* it expects titles in title-case. Words within braces are recognized as "case-protected" and their original casing is preserved during
* rendering. For non-English entries, the casing as entered in the entries is rendered as entered. Other reference managers, such as
* Zotero, expect all titles to be in sentence-case. In this parser you can specify which `langid` values mark an entry to be English so
* that it can convert those titles to sentence-case, and to carry over case-protection. If no `langid` is present an entry is
* assumed to be English by bib(la)tex, and the parser follows that convention. Note that sentence-casing uses heuristics and
* does not employ any kind of natural language processing, so you should always inspect the results. If you offer your own list
* of english-langids here, do not forget to include the empty string, stands for "`langid` absent". Default languages to sentenceCase
* are the empty string, plus:
*
* - american
* - british
* - canadian
* - english
* - australian
* - newzealand
* - usenglish
* - ukenglish
* - en
* - eng
* - en-au
* - en-bz
* - en-ca
* - en-cb
* - en-gb
* - en-ie
* - en-jm
* - en-nz
* - en-ph
* - en-tt
* - en-us
* - en-za
* - en-zw
*
* If you pass an empty array, or `false`, no sentence casing will be applied (even when there's no language field).
*/
english?: string[] | boolean
/**
* By default, `langid` and `hyphenation` are used to determine whether an entry is English, but some sources (ab)use the `language` field
* for this. If you turn on this option, this field will also be taken into account as a source for `langid`.
*/
languageAsLangid?: boolean
sentenceCase?: false | {
/**
* Some bibtex files will have English titles in sentence case, or all-uppercase. If this is on, and there is a field that would
* normally have sentence-casing applied in which there are all-lowercase words that are not prepositions (where `X` is either
* lower or upper) than mixed-case, it is assumed that you want them this way, and no sentence-casing will be applied to that field
*/
guess?: boolean
/**
* Retain Capitalised words in sub-sentences after colons. Given the input title "Structured Interviewing For OCB: Construct Validity,
* Faking, And The Effects Of Question Type":
* - when `true`, sentence-cases to "Structured interviewing for OCB: Construct validity, faking, and the effects of question type"
* - when `false`, sentence-cases to "Structured interviewing for OCB: construct validity, faking, and the effects of question type"
*/
subSentence?: boolean
/**
* If you have sentence-casing on, you can independently choose whether quoted titles within a title are preserved as-is (true)
* or also sentence-cased (false).
*/
preserveQuoted?: boolean
}
/**
* translate braced parts of English-entry titles into a case-protected counterpart; Default == true == as-needed.
* In as-needed mode the parser will assume that words that have capitals in them imply "nocase" behavior in the consuming application. If you don't want this, turn this option on, and you'll get
* case protection exactly as the input has it
*/
caseProtection?: 'as-needed' | 'strict' | boolean
/**
* By default, when a TeX command is encountered which the parser does not know about, the parser will throw an error. You can pass a function here to return the appropriate text output for the command.
*/
unsupported?: 'ignore' | unsupportedHandler
/**
* Some fields such as `url` are parsed in what is called "verbatim mode" where pretty much everything except braces is treated as regular text, not TeX commands. You can change the default list here if you want,
* for example to help parse Mendeley `file` fields, which against spec are not in verbatim mode.
*/
verbatimFields?: (string | RegExp)[]
/**
* In the past many bibtex entries would just always wrap a field in double braces, likely because whomever was writing them couldn't figure out the case meddling rules (and who could
* blame them). Fields listed here will either have one outer layer of braces treated as case-preserve, or have the outer braced be ignored completely, if this is detected.
*/
removeOuterBraces?: string[]
/**
* Specify parsing mode for specific fields
*/
fieldMode?: Record<string, ParseMode>
/**
* If this flag is set entries will be returned without conversion of LaTeX to unicode equivalents.
*/
raw?: boolean
/**
* You can pass in an existing `@string` dictionary
*/
strings?: Record<string, string> | string
/**
* Apply crossref inheritance
*/
applyCrossRef?: boolean
}
export interface Creator {
name?: string
lastName?: string
firstName?: string
prefix?: string
suffix?: string
initial?: string
useprefix?: boolean
juniorcomma?: boolean
}
export const FieldMode = {
creatorlist: [
'author',
'bookauthor',
'collaborator',
'commentator',
'director',
'editor',
'editora',
'editorb',
'editors',
'holder',
'scriptwriter',
'translator',
],
title: [
'title',
'subtitle',
'series',
'shorttitle',
'booktitle',
// 'type',
'origtitle',
'maintitle',
'eventtitle',
],
verbatim: [
'doi',
'eprint',
'file',
'files',
'pdf',
'groups', // jabref unilaterally decided to make this non-standard field verbatim
'ids',
'url',
'verba',
'verbb',
'verbc',
/^keywords([+]duplicate-\d+)?$/,
/^citeulike-linkout-[0-9]+$/,
/^bdsk-url-[0-9]+$/,
],
richtext: [
'annotation',
'comment',
'annote',
'review',
'notes',
'note',
],
literallist: [
'institution',
'publisher',
'origpublisher',
'organization',
'location',
'origlocation',
],
}
type ParseMode = keyof typeof FieldMode | 'literal' | 'verbatimlist'
export const English = [
'',
'american',
'british',
'canadian',
'english',
'australian',
'newzealand',
'usenglish',
'ukenglish',
'en',
'eng',
'en-au',
'en-bz',
'en-ca',
'en-cb',
'en-gb',
'en-ie',
'en-jm',
'en-nz',
'en-ph',
'en-tt',
'en-us',
'en-za',
'en-zw',
'anglais', // don't do this people
]
const FieldAction = {
removeOuterBraces: [
'doi',
// 'publisher',
// 'location',
],
parseInt: [
'year',
'month',
],
noCrossRef: [
'file',
],
}
const narguments = {
advance: 1,
ElsevierGlyph: 1,
bar: 1,
bibcyr: 1,
bibstring: 1,
chsf: 1,
cite: 1,
citeauthor: 1,
cyrchar: 1,
ding: 1,
emph: 1,
enquote: 1,
frac: 2,
hbox: 1,
href: 2,
hskip: 1,
hspace: 1,
ht: 1,
mathrm: 1,
mbox: 1,
mkbibbold: 1,
mkbibemph: 1,
mkbibitalic: 1,
mkbibquote: 1,
newcommand: 2,
noopsort: 1,
ocirc: 1,
overline: 1,
ProvideTextCommandDefault: 2,
rlap: 1,
sb: 1,
section: 1,
sp: 1,
subsection: 1,
subsubsection: 1,
subsubsubsection: 1,
t: 1,
textbf: 1,
textcite: 1,
textit: 1,
textrm: 1,
textsc: 1,
textsl: 1,
textsubscript: 1,
textsuperscript: 1,
texttt: 1,
textup: 1,
url: 1,
vphantom: 1,
vspace: 1,
wd: 1,
// math
'math\t_': 1,
'math\t^': 1,
}
for (const m in combining.tounicode) { // eslint-disable-line guard-for-in
narguments[m] = 1
}
type unsupportedHandler = (node: Node, tex: string, entry: Entry) => string
type Context = {
mode: ParseMode
caseProtected?: boolean
}
/*
async function* asyncGenerator<T>(array: T[]): AsyncGenerator<T, void, unknown> {
for (const item of array) {
yield await Promise.resolve(item)
}
}
*/
class BibTeXParser {
private fallback: unsupportedHandler
private current: Entry
private english: boolean
private options: Options
private fieldMode: typeof FieldMode
private newcommands: Record<string, Argument> = {}
private bib: Library
private unhandled: Set<string> = new Set
private split(ast: Group | Root, sep: RegExp, split: RegExp): Root[] {
const roots: Root[] = []
const nodes = [...ast.content]
const types = nodes.map(node => {
if (node.type === 'whitespace') return ' '
if (node.type === 'string' && node.content.match(sep)) return '&'
return '.'
}).join('')
types.split(split).forEach((match, i) => {
const content = match.length ? nodes.splice(0, match.length) : []
if ((i % 2) === 0) roots.push({ type: 'root', content })
})
return roots
}
private trimCreator(cr: Creator): Creator {
// trims strings but coincidentally removes undefined fields
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return JSON.parse(JSON.stringify(cr, (k, v) => typeof v === 'string' ? (v.trim() || undefined) : v)) as Creator
}
private parseCreator(ast: Root): Creator {
if (ast.content.length === 1 && ast.content[0].type === 'group') return this.trimCreator({ name: this.stringify(ast, { mode: 'creatorlist' }) })
const { parts, extended } = this.commaSeparatedCreator(ast)
if (extended) {
const name: Creator = {}
for (const [attr, value] of Object.entries(extended)) {
const rendered = this.stringify(value, { mode: 'creatorlist' }).trim()
switch (attr) {
case '':
break
case 'given':
name.firstName = rendered
break
case 'family':
name.lastName = rendered
break
case 'given-i':
name.initial = rendered
break
case 'useprefix':
case 'juniorcomma':
name[attr] = rendered.toLowerCase() === 'true'
break
default:
name[attr] = rendered
break
}
}
return this.trimCreator(name)
}
else if (parts.length) {
const nameparts: string[] = parts.map((part: Node) => this.stringify(part, { mode: 'creatorlist' }).trim())
if (nameparts.length === 3 && nameparts[2] === '') nameparts.pop()
if (nameparts.length > 3) {
const key = this.current.key ? `@${this.current.key}: ` : ''
this.bib.errors.push({
error: `${key}unexpected ${nameparts.length}-part name "${nameparts.join(', ')}", dropping "${nameparts.slice(3).join(', ')}"`,
input: nameparts.join(', '),
})
}
let [lastName, suffix, firstName] = (nameparts.length === 2)
? [nameparts[0], undefined, nameparts[1]]
// > 3 parts are invalid and are dropped
: nameparts.slice(0, 3)
let prefix
const m = lastName.match(/^([a-z'. ]+) (.+)/)
if (m) {
prefix = m[1]
lastName = m[2]
}
return this.trimCreator({
lastName,
firstName,
prefix,
suffix,
})
}
else { // first-last mode
const nameparts = this.split(ast, /^$/, /( )/).map(part => this.stringify(part, { mode: 'creatorlist' })).filter(n => n)
if (nameparts.length === 1) return this.trimCreator({ lastName: nameparts[0] })
const prefix = nameparts.findIndex(n => n.match(/^[a-z]/))
const postfix = prefix <= 0 ? -1 : nameparts.findIndex((n, i) => i > prefix && !n.match(/^[a-z]/))
if (postfix === -1) {
const lastName = nameparts.pop()
return this.trimCreator({ lastName, firstName: nameparts.join(' ') })
}
return this.trimCreator({
firstName: nameparts.slice(0, prefix).join(' '),
prefix: nameparts.slice(prefix, postfix).join(' '),
lastName: nameparts.slice(postfix).join(' '),
})
}
}
private ligature(nodes: Node[]): StringNode {
if (latexMode(nodes[0]) !== 'text') return null
const max = 3
const slice = nodes.slice(0, max)
const type = slice.map(n => n.type === 'string' ? 's' : ' ').join('')
if (type[0] !== 's') return null
const content = slice.map(n => n.type === 'string' ? n.content : '')
let latex: string
while (content.length) {
if (type.startsWith('s'.repeat(content.length)) && (latex = latex2unicode(content.join(''), slice[0]))) {
try {
return { type: 'string', content: latex, _renderInfo: {} }
}
finally {
nodes.splice(0, content.length)
}
}
content.pop()
}
return null
}
private wraparg(node: Node, macro: Macro) : Argument {
if (macro.content.match(/^(itshape|textsl|textit|emph|mkbibemph)$/)) node._renderInfo.emph = true
if (macro.content.match(/^(textbf|mkbibbold|bfseries)$/)) node._renderInfo.bold = true
if (macro.content.match(/^(textsc)$/)) node._renderInfo.smallCaps = true
if (macro.content.match(/^(texttt)$/)) node._renderInfo.code = true
return { type: 'argument', content: [ node ], openMark: '', closeMark: '', _renderInfo: { mode: node._renderInfo.mode } }
}
private argtogroup(node: Argument): Group {
if (node.content.length === 1 && node.content[0].type === 'group') return node.content[0]
return { type: 'group', content: node.content }
}
private argument(nodes: Node[], macro: Macro): Argument {
if (!nodes.length) return null
if (nodes[0].type === 'whitespace') nodes.shift()
if (!nodes.length) return null
if (nodes[0].type === 'string') {
const char = nodes[0].content[0]
nodes[0].content = nodes[0].content.substr(1)
const arg = { ...nodes[0], content: char }
if (!nodes[0].content) nodes.shift()
return this.wraparg(arg, macro)
}
return this.wraparg(nodes.shift(), macro)
}
private unsupported(node: Node): string {
const tex = printRaw(node)
if (this.fallback) return this.fallback(node, tex, this.current) ?? ''
let id: string
switch (node.type) {
case 'macro':
id = `${node.type}.${node.content}`
if (!this.unhandled.has(id)) {
this.unhandled.add(id)
this.bib.errors.push({ error: `unhandled ${node.type} ${printRaw(node)}`, input: printRaw(node) })
}
break
case 'environment':
id = `${node.type}.${node.env}`
if (!this.unhandled.has(id)) {
this.unhandled.add(id)
this.bib.errors.push({ error: `unhandled ${node.type} ${node.env} (${printRaw(node)})`, input: printRaw(node) })
}
break
default:
this.bib.errors.push({ error: `unhandled ${node.type} (${printRaw(node)})`, input: printRaw(node) })
break
}
return tex
}
private wrap(text: string, tag, wrap=true): string {
if (!text || !wrap) return text || ''
return `\x0E${tag}\x0F${text}\x0E/${tag}\x0F`
}
private registercommand(node: Macro): string {
const types = (nodes: Node[]) => nodes.map(n => n.type).join('.')
const group = (arg: Argument, kind: string): Node[] => {
if (!arg) throw new Error(`missing ${kind} for ${printRaw(node)} @ ${JSON.stringify(node.position)}`)
if (types(arg.content) !== 'group') throw new Error(`Malformed ${kind} for ${printRaw(node)} @ ${JSON.stringify(node.position)}`)
return (<Group>arg.content[0]).content
}
if (!node.args) throw new Error(`No arguments for ${printRaw(node)} @ ${JSON.stringify(node.position)}`)
const namearg = group(node.args[0], 'name')
if (types(namearg) !== 'macro') throw new Error(`Unexpected name for ${printRaw(node)} @ ${JSON.stringify(node.position)}`)
this.newcommands[(<Macro>namearg[0]).content] = node.args[1]
return ''
}
private subp(text: string, macro: string) {
let subp = ''
for (let char of text) {
char = latex2unicodemap[`${macro}{${char}}`]
if (char) {
subp += char
}
else {
const tag = {_: 'sub', '^': 'sup'}[macro]
return `\x0E${tag}\x0F${text}\x0E/${tag}\x0F`
}
}
return subp
}
private macro(node: Macro, context: Context): string {
const text = latex2unicode(printRaw(node), node)
if (text) return text
let url: Argument
let label: Argument
let arg: string[]
let resolved: string
switch (node.content) {
case 'newcommand':
case 'ProvideTextCommandDefault':
return this.registercommand(node)
// too complex to deal with these
case 'raise':
case 'accent':
case 'def':
case 'hss':
case 'ifmmode':
case 'makeatletter':
case 'makeatother':
case 'scriptscriptstyle':
case 'setbox':
case 'dimen':
case 'advance':
return ''
case 'vphantom':
case 'noopsort':
case 'left':
case 'right':
case 'ensuremath':
case 'wd':
case 'ht':
return ''
case 'path':
return '' // until https://github.com/siefkenj/unified-latex/issues/94 is fixed
case 'hspace':
case 'hskip':
if (node.args && node.args.length) {
if (printRaw(node.args).match(/^[{]?0[a-z]*$/)) return ''
return ' '
}
return ''
case 'overline':
case 'bar':
return node.args.map(a => this.stringify(a, context)).join('').replace(/[a-z0-9]/ig, m => `${m}\u0305`)
// accents dealt with by preprocessor
case 'textup':
case 'textsc':
case 'textrm':
case 'texttt':
case 'mathrm':
case 'mbox':
case 'hbox':
case 'rlap':
return node.args.map(n => this.stringify(n, context)).join('')
case 'href':
case 'url':
if (node.args) {
url = node.args[0]
label = node.args[node.content === 'url' ? 0 : 1]
}
return `<a href="${this.stringify(url, context)}">${this.stringify(label, context)}</a>`
case 'relax':
case 'aftergroup':
case 'ignorespaces':
case 'em':
case 'it':
case 'tt':
case 'sl':
return ''
case 'rm':
case 'sc':
return ''
// bold/emph/smallcaps is handled in the wrapper
case 'textbf':
case 'mkbibbold':
case 'textit':
case 'emph':
case 'mkbibemph':
return this.stringify(node.args?.[0], context)
case 'textsuperscript':
return this.subp(this.stringify(node.args?.[0], context), '^')
case 'textsubscript':
return this.subp(this.stringify(node.args?.[0], context), '_')
case '_':
case '^':
switch (latexMode(node)) {
case 'math':
return this.subp(this.stringify(node.args?.[0], context), node.content)
default:
return node.content
}
case 'LaTeX':
return this.wrap(`L${this.subp('A', '^')}T${this.subp('E', '_')}X`, 'ncx')
case 'enquote':
case 'mkbibquote':
return this.wrap(this.stringify(node.args?.[0], context), 'enquote')
case '\\':
return context.mode === 'richtext' ? open.br : ' '
case 'par':
return context.mode === 'richtext' ? open.p : ' '
case 'item':
return context.mode === 'richtext' ? open.li : ' '
case 'section':
case 'subsection':
case 'subsubsection':
case 'subsubsubsection':
return this.wrap(this.stringify(node.args?.[0], context), `h${node.content.split('sub').length}`)
case 'frac':
arg = node.args.map(a => this.stringify(a, context))
if (arg.length === 2 && (resolved = latex2unicodemap[`\\frac${arg.map(a => `{${a}}`).join('')}`])) return resolved
return arg.map((part, i) => this.subp(part, i ? '_' : '^')).join('\u2044')
case 'chsf':
case 'bibstring':
case 'cite':
case 'textcite':
case 'citeauthor':
// ncx protects but will be stripped later
return this.wrap(this.stringify(node.args?.[0], context), 'ncx', context.mode === 'title')
default:
if (this.newcommands[node.content]) return this.stringify(this.newcommands[node.content], context)
return this.unsupported(node)
}
}
private what(node: Node) {
if (!node) return ''
switch (node.type) {
case 'macro': return `macro:${<string>node._renderInfo.mode ?? 'text'}:${node.content}`
case 'environment': return `env:${node.env}`
default: return node.type
}
}
private environment(node: Environment, context: Context) {
while (node.content.length && this.what(node.content[0]).match(/^parbreak|whitespace|macro:text:par$/)) node.content.shift()
while (node.content.length && this.what(node.content[node.content.length - 1]).match(/^parbreak|whitespace|macro:text:par$/)) node.content.pop()
switch (node.env) {
case 'quotation':
return this.wrap(node.content.map(n => this.stringify(n, context)).join(''), 'blockquote', context.mode === 'richtext')
case 'itemize':
return this.wrap(node.content.map(n => this.stringify(n, context)).join(''), 'ul', context.mode === 'richtext')
case 'em':
return this.wrap(node.content.map(n => this.stringify(n, context)).join(''), 'i', context.mode === 'richtext')
default:
return this.unsupported(node)
}
}
private stringify(node: Node | Argument, context: Context): string {
let content = this.stringifyContent(node, context)
if (content && node._renderInfo) {
if (node._renderInfo.emph) content = `${open.i}${content}${close.i}`
if (node._renderInfo.bold) content = `${open.b}${content}${close.b}`
if (node._renderInfo.smallCaps) content = `${open.sc}${content}${close.sc}`
if (node._renderInfo.code) content = `${open.code}${content}${close.code}`
if (this.english && node._renderInfo.protectCase) content = `${open.nc}${content}${close.nc}`
}
return content
}
private stringifyContent(node: Node | Argument, context: Context): string {
if (!node) return ''
switch (node.type) {
case 'root':
case 'argument':
case 'group':
case 'inlinemath':
return node.content.map(n => this.stringify(n, context)).join('')
case 'string':
case 'verbatim':
return node.content
case 'macro':
return this.macro(node, context)
case 'parbreak':
return context.mode === 'richtext' ? open.p : ' '
case 'whitespace':
return node._renderInfo.mode === 'math' ? '' : ' '
case 'comment':
return ''
case 'environment':
return this.environment(node, context)
case 'verb':
return node.content
default:
return this.unsupported(node)
}
}
private protect(node) {
if (node.type === 'inlinemath') return true
if (node.type !== 'group') return false
if (!node.content.length) return false
return (node.content[0].type !== 'macro')
}
private mode(field: string): ParseMode {
if (this.options.verbatimFields && this.options.verbatimFields.find(name => typeof name === 'string' ? (name === field) : field.match(name))) return 'verbatim'
let mode: ParseMode = 'literal'
for (const [selected, fields] of Object.entries(this.fieldMode)) {
if (fields.find(match => typeof match === 'string' ? field === match : field.match(match))) mode = <ParseMode>selected
}
return mode
}
private restoreMarkup(s: string): string {
if (!s.includes('\x0E')) return s
const restored: string[] = [s.replace(/\x0E\/?ncx\x0F/ig, '')]
while (restored[0] !== restored[1]) {
restored.unshift(restored[0].replace(collapsable, '$2'))
}
return restored[0]
.replace(/(\x0Ep\x0F\s*){2,}/ig, '\x0Ep\x0F')
.replace(/\s*(\x0E\/p\x0F){2,}/ig, '\x0E/p\x0F')
.replace(/\x0Eenquote\x0F/ig, '\u201C').replace(/\x0E\/enquote\x0F/ig, '\u201D')
.replace(/\x0Esc\x0F/ig, '<span style="font-variant:small-caps;">').replace(/\x0E\/sc\x0F/ig, '</span>')
.replace(/\x0Enc\x0F/ig, '<span class="nocase">').replace(/\x0E\/nc\x0F/ig, '</span>')
.replace(/\x0E/ig, '<').replace(/\x0F/ig, '>')
}
private stringField(field: string, value: string, mode: string, guessSC: boolean): string {
if (field === 'crossref') return value
if (FieldAction.parseInt.includes(field) && value.trim().match(/^-?\d+$/)) return `${parseInt(value)}`
if (this.english && mode === 'title') {
value = toSentenceCase(value, {
preserveQuoted: this.options.sentenceCase && this.options.sentenceCase.preserveQuoted,
subSentenceCapitalization: this.options.sentenceCase && this.options.sentenceCase.subSentence,
markup: /\x0E\/?([a-z]+)\x0F/ig,
nocase: /\x0E(ncx?)\x0F.*?\x0E\/\1\x0F/ig,
guess: guessSC,
})
let cancel = (_match: string, stripped: string) => stripped
switch (this.options.caseProtection) {
case 'strict':
cancel = (match: string, _stripped: string) => match
break
case 'as-needed':
cancel = (match: string, stripped: string) => {
const words: Token[] = tokenize(stripped, /\x0E\/?([a-z]+)\x0F/ig)
return words.find(w => w.shape.match(/^(?!.*X).*x.*$/)) ? match : this.wrap(stripped, 'ncx')
}
break
}
return value.replace(/\x0Enc\x0F(.*?)\x0E\/nc\x0F/ig, cancel)
}
return value
}
private commaSeparatedCreator(ast: Root): { parts: Root[], extended?: Record<string, Root> } {
const result: { parts: Root[], extended?: Record<string, Root> } = {
parts: [],
}
if (!ast.content.find(node => node.type === 'string' && node.content === ',')) return result
result.parts = this.split(ast, /^,$/, /(&)/)
result.extended = {}
for (const part of result.parts) {
const start = part.content[0]?.type === 'whitespace' ? 1 : 0
let signature = part.content
.slice(start, start + 4)
.map((node, i) => node._renderInfo.mode === 'text' && node.type === 'string' ? node.content.replace(i % 2 ? /[^=-]/g : /[^a-z]/gi, '.') : '.')
.join('')
if (signature.match(/^[a-z]+(-[a-z]+)?=/i)) {
signature = signature.replace(/=.*/, '').toLowerCase()
result.extended[signature] = { type: 'root', content: part.content.slice(signature.includes('-') ? start + 4 : start + 2) }
}
else {
delete result.extended
break
}
}
return result