-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathbibtex-tidy.js
4576 lines (4550 loc) · 135 KB
/
bibtex-tidy.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
/**
* bibtex-tidy v1.14.0
* https://github.com/FlamingTempura/bibtex-tidy
*
* DO NOT EDIT THIS FILE. This file is automatically generated
* using `npm run build`. Edit files in './src' then rebuild.
**/
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
getEntries: () => getEntries,
tidy: () => tidy
});
module.exports = __toCommonJS(src_exports);
// src/months.ts
var MONTH_MACROS = [
"jan",
"feb",
"mar",
"apr",
"may",
"jun",
"jul",
"aug",
"sep",
"oct",
"nov",
"dec"
];
var MONTH_SET = new Set(MONTH_MACROS);
var MONTH_CONVERSIONS = {
"1": "jan",
"2": "feb",
"3": "mar",
"4": "apr",
"5": "may",
"6": "jun",
"7": "jul",
"8": "aug",
"9": "sep",
"10": "oct",
"11": "nov",
"12": "dec",
jan: "jan",
feb: "feb",
mar: "mar",
apr: "apr",
may: "may",
jun: "jun",
jul: "jul",
aug: "aug",
sep: "sep",
oct: "oct",
nov: "nov",
dec: "dec",
january: "jan",
february: "feb",
march: "mar",
april: "apr",
june: "jun",
july: "jul",
august: "aug",
september: "sep",
october: "oct",
november: "nov",
december: "dec"
};
// src/parsers/latexParser.ts
var BlockNode = class _BlockNode {
constructor(kind, parent, children = []) {
this.kind = kind;
this.parent = parent;
this.children = children;
this.type = "block";
if (parent instanceof _BlockNode) {
parent.children.push(this);
} else if (parent instanceof CommandNode) {
parent.args.push(this);
}
}
static {
__name(this, "BlockNode");
}
renderAsText() {
return this.children.map((child) => child.renderAsText()).join("");
}
};
var TextNode = class {
constructor(parent, text = "") {
this.parent = parent;
this.text = text;
this.type = "text";
parent.children.push(this);
}
static {
__name(this, "TextNode");
}
renderAsText() {
return this.text.replace(/"/g, "");
}
};
var CommandNode = class {
constructor(parent, command = "", args = []) {
this.parent = parent;
this.command = command;
this.args = args;
this.type = "command";
parent.children.push(this);
}
static {
__name(this, "CommandNode");
}
renderAsText() {
return this.args.map((arg) => arg.renderAsText()).join("");
}
};
function parseLaTeX(input) {
const rootNode = new BlockNode("root");
let node = rootNode;
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (!char) break;
switch (node.type) {
case "block": {
if (char === "\\") {
node = new CommandNode(node);
} else if (char === "{") {
node = new BlockNode("curly", node);
} else if ((char === "}" && node.kind === "curly" || char === "]" && node.kind === "square") && node.parent) {
node = node.parent;
} else {
node = new TextNode(node, char);
}
break;
}
case "text": {
if (char === "\\" || char === "{") {
node = node.parent;
i--;
} else if (char === "}" && node.parent.kind === "curly" || char === "]" && node.parent.kind === "square") {
node = node.parent;
i--;
} else {
node.text += char;
}
break;
}
case "command": {
if (char === "{") {
node = new BlockNode("curly", node);
} else if (char === "[") {
node = new BlockNode("square", node);
} else if (char === "}" && node.parent.kind === "curly" || char === "]" && node.parent.kind === "square" || /\s/.test(char) || node.args.length > 0) {
node = node.parent;
i--;
} else {
node.command += char;
}
}
}
}
return rootNode;
}
__name(parseLaTeX, "parseLaTeX");
function stringifyLaTeX(ast) {
return stringifyBlock(ast);
}
__name(stringifyLaTeX, "stringifyLaTeX");
function stringifyBlock(block) {
const content = block.children.map((node) => {
switch (node.type) {
case "block":
return stringifyBlock(node);
case "command":
return stringifyCommand(node);
case "text":
return node.text;
}
}).join("");
switch (block.kind) {
case "root":
return content;
case "curly":
return `{${content}}`;
case "square":
return `[${content}]`;
}
}
__name(stringifyBlock, "stringifyBlock");
function stringifyCommand(node) {
return `\\${node.command}${node.args.map(stringifyBlock).join("")}`;
}
__name(stringifyCommand, "stringifyCommand");
function flattenLaTeX(block) {
const newBlock = new BlockNode(block.kind);
for (const child of block.children) {
if (child.type === "block" && child.kind === "curly" && child.children.every((child2) => child2.type !== "command")) {
const newChild = flattenLaTeX(child);
newBlock.children.push(...newChild.children);
} else {
newBlock.children.push(child);
}
}
return newBlock;
}
__name(flattenLaTeX, "flattenLaTeX");
// src/utils.ts
function alphaNum(str) {
return str.replace(/[^0-9A-Za-z]/g, "").toLocaleLowerCase();
}
__name(alphaNum, "alphaNum");
function convertCRLF(str) {
return str.replace(/\r\n?/g, "\n");
}
__name(convertCRLF, "convertCRLF");
function wrapText(line, lineWidth) {
const words2 = line.split(" ");
const lines = [];
let currLine = "";
for (const [i, word] of words2.entries()) {
if (currLine.length + word.length + 1 > lineWidth && i > 0) {
lines.push(currLine.trim());
currLine = "";
}
currLine += `${word} `;
}
return [...lines, currLine.trim()];
}
__name(wrapText, "wrapText");
function unwrapText(str) {
return str.replace(/\s*\n\s*\n\s*/g, "<<BIBTEX_TIDY_PARA>>").replace(/\s*\n\s*/g, " ").replace(/<<BIBTEX_TIDY_PARA>>/g, "\n\n");
}
__name(unwrapText, "unwrapText");
function doubleEnclose(str) {
const latex = parseLaTeX(str);
const alreadyDoubleEnclosed = latex.children.length === 1 && latex.children[0]?.type === "block" && latex.children[0]?.kind === "curly" && latex.children[0].children.length === 1 && latex.children[0].children[0]?.type === "block" && latex.children[0].children[0]?.kind === "curly";
const result = stringifyLaTeX(latex);
return alreadyDoubleEnclosed ? result : `{${result}}`;
}
__name(doubleEnclose, "doubleEnclose");
function isEntryNode(node) {
return node.type !== "text" && node.block?.type === "entry";
}
__name(isEntryNode, "isEntryNode");
// src/format.ts
function formatBibtex(ast, options, replacementKeys) {
const { omit, tab, space } = options;
const indent = tab ? " " : " ".repeat(space);
const omitFields = new Set(omit);
let bibtex = ast.children.map(
(child) => formatNode(child, options, indent, omitFields, replacementKeys)
).join("").trimEnd();
if (!bibtex.endsWith("\n")) bibtex += "\n";
return bibtex;
}
__name(formatBibtex, "formatBibtex");
function formatNode(child, options, indent, omitFields, replacementKeys) {
if (child.type === "text") {
return formatComment(child.text, options);
}
if (!child.block) throw new Error("FATAL!");
switch (child.block.type) {
case "preamble":
case "string":
return `${child.block.raw}
${options.blankLines ? "\n" : ""}`;
case "comment":
return formatComment(child.block.raw, options);
case "entry":
return formatEntry(
child.command,
child.block,
options,
indent,
omitFields,
replacementKeys?.get(child.block)
) + (options.blankLines ? "\n" : "");
}
}
__name(formatNode, "formatNode");
function formatEntry(entryType, entry, options, indent, omitFields, replacementKey) {
const {
align,
trailingCommas,
removeDuplicateFields,
removeEmptyFields,
lowercase
} = options;
let bibtex = "";
const itemType = lowercase ? entryType.toLocaleLowerCase() : entryType;
bibtex += `@${itemType}{`;
const key = replacementKey ?? entry.key;
if (key) bibtex += `${key},`;
const fieldSeen = /* @__PURE__ */ new Set();
for (const [i, field] of entry.fields.entries()) {
const nameLowerCase = field.name.toLocaleLowerCase();
const name = lowercase ? nameLowerCase : field.name;
if (field.name === "") continue;
if (omitFields.has(nameLowerCase)) continue;
if (removeDuplicateFields && fieldSeen.has(nameLowerCase)) continue;
fieldSeen.add(nameLowerCase);
if (field.value.concat.length === 0) {
if (removeEmptyFields) continue;
bibtex += `
${indent}${name}`;
} else {
const value = formatValue(field, options);
if (removeEmptyFields && (value === "{}" || value === '""')) continue;
bibtex += `
${indent}${name.trim().padEnd(align - 1)} = ${value}`;
}
if (i < entry.fields.length - 1 || trailingCommas) bibtex += ",";
}
bibtex += "\n}\n";
return bibtex;
}
__name(formatEntry, "formatEntry");
function formatComment(comment, { stripComments, tidyComments }) {
if (stripComments) return "";
if (tidyComments) {
const trimmed = comment.trim();
if (trimmed === "") return "";
return `${trimmed}
`;
}
return comment.replace(/^[ \t]*\n|[ \t]*$/g, "");
}
__name(formatComment, "formatComment");
function formatValue(field, options) {
const { curly, numeric, align, wrap, tab, space, enclosingBraces } = options;
const nameLowerCase = field.name.toLocaleLowerCase();
const indent = tab ? " " : " ".repeat(space);
const enclosingBracesFields = new Set(
(enclosingBraces ?? []).map((field2) => field2.toLocaleLowerCase())
);
return field.value.concat.map(({ type, value }) => {
const isNumeric = value.match(/^[1-9][0-9]*$/);
if (isNumeric && curly) {
type = "braced";
}
if (type === "literal" || numeric && isNumeric) {
return value;
}
const dig3 = value.slice(0, 3).toLowerCase();
const isMonthAbbrv = nameLowerCase === "month" && MONTH_SET.has(dig3);
if (!curly && numeric && isMonthAbbrv) {
return dig3;
}
value = unwrapText(value);
if (enclosingBracesFields.has(nameLowerCase) && (type === "braced" || curly)) {
value = doubleEnclose(value);
}
if (type === "braced" && field.value.concat.length === 1) {
value = value.trim();
}
if (type === "braced" || curly) {
const lineLength = `${indent}${align}{${value}}`.length;
const multiLine = value.includes("\n\n");
if (wrap && lineLength > wrap || multiLine) {
let paragraphs = value.split("\n\n");
const valIndent = indent.repeat(2);
if (wrap) {
const wrapCol = wrap;
paragraphs = paragraphs.map(
(paragraph) => wrapText(paragraph, wrapCol - valIndent.length).join(
`
${valIndent}`
)
);
}
value = `
${valIndent}${paragraphs.join(`
${valIndent}`)}
${indent}`;
}
return doubleEnclose(value);
}
return `"${value}"`;
}).join(" # ");
}
__name(formatValue, "formatValue");
// src/optionDefinitions.ts
var DEFAULT_MERGE_CHECK = ["doi", "citation", "abstract"];
var DEFAULT_ALIGN = 14;
var DEFAULT_SPACE = 2;
var DEFAULT_WRAP = 80;
var DEFAULT_FIELD_SORT = [
"title",
"shorttitle",
"author",
"year",
"month",
"day",
"journal",
"booktitle",
"location",
"on",
"publisher",
"address",
"series",
"volume",
"number",
"pages",
"doi",
"isbn",
"issn",
"url",
"urldate",
"copyright",
"category",
"note",
"metadata"
];
var DEFAULT_SORT = ["key"];
var DEFAULT_KEY_TEMPLATE = "[auth:required:lower][year:required][veryshorttitle:lower][duplicateNumber]";
var optionDefinitions = [
{
key: "help",
cli: { "--help": true, "-h": true },
title: "Help",
description: ["Show help"],
type: "boolean"
},
{
key: "v2",
cli: { "--v2": true },
title: "Enable planned v2 CLI changes",
description: [
"Input files will no longer be modified by default. Instead, you will need to specify `--modify`/`-m` option to overwrite the file, or `--output`/`-o` to output to a different file."
],
type: "string",
defaultValue: void 0
},
{
key: "outputPath",
cli: { "--output": /* @__PURE__ */ __name((args) => args[0], "--output"), "-o": /* @__PURE__ */ __name((args) => args[0], "-o") },
title: "Output path",
description: [
"Write output to specified path. When omitted (and -m/--modify is not used), the result will be printed to stdout."
],
type: "string",
defaultValue: void 0
},
{
key: "modify",
cli: { "--modify": true, "-m": true, "--no-modify": false },
title: "Modify input files",
description: [
"Overwrite the original input files with the tidied result. This is enabled by default but will be disabled by default in v2. For v1, use --no-modify to output to stdout instead of overwriting the input files."
],
type: "boolean",
defaultValue: true
// TODO: In v2, switch this to false
},
{
key: "omit",
cli: {
"--omit": /* @__PURE__ */ __name((args) => {
if (args.length === 0) {
console.error("Expected a omit list");
process.exit(1);
}
return args;
}, "--omit")
},
toCLI: /* @__PURE__ */ __name((val) => Array.isArray(val) && val.length > 0 ? `--omit=${val.join(",")}` : void 0, "toCLI"),
title: "Remove fields",
description: ["Remove specified fields from bibliography entries."],
examples: ["--omit=id,name"],
type: "string[]",
defaultValue: []
},
{
key: "curly",
cli: { "--curly": true, "--no-curly": false },
toCLI: /* @__PURE__ */ __name((val) => val ? "--curly" : void 0, "toCLI"),
title: "Enclose values in braces",
description: [
'Enclose all property values in braces. Quoted values will be converted to braces. For example, "Journal of Tea" will become {Journal of Tea}.'
],
type: "boolean",
defaultValue: false
},
{
key: "numeric",
cli: { "--numeric": true, "--no-numeric": false },
toCLI: /* @__PURE__ */ __name((val) => val ? "--numeric" : void 0, "toCLI"),
title: "Use numeric values where possible",
description: [
"Strip quotes and braces from numeric/month values. For example, {1998} will become 1998."
],
type: "boolean",
defaultValue: false
},
{
key: "months",
cli: { "--months": true },
toCLI: /* @__PURE__ */ __name((val) => val ? "--months" : void 0, "toCLI"),
title: "Abbreviate months",
description: [
"Convert all months to three letter abbreviations (jan, feb, etc)."
],
type: "boolean",
defaultValue: false
},
{
key: "space",
cli: {
"--space": /* @__PURE__ */ __name((args) => args.length > 0 ? Number(args[0]) : true, "--space")
},
toCLI: /* @__PURE__ */ __name((val, opt) => {
if (opt.tab) return void 0;
if (typeof val === "number" && val !== DEFAULT_SPACE)
return `--space=${val}`;
if (val && val !== DEFAULT_SPACE) return "--space";
return void 0;
}, "toCLI"),
title: "Indent with spaces",
description: [
"Indent all fields with the specified number of spaces. Ignored if tab is set."
],
examples: ["--space=2 (default)", "--space=4"],
type: "boolean | number",
convertBoolean: { true: DEFAULT_SPACE, false: void 0 },
defaultValue: DEFAULT_SPACE
},
{
key: "tab",
cli: { "--tab": true, "--no-tab": false },
toCLI: /* @__PURE__ */ __name((val) => val ? "--tab" : void 0, "toCLI"),
title: "Indent with tabs",
description: ["Indent all fields with a tab."],
type: "boolean",
defaultValue: false
},
{
key: "align",
cli: {
"--align": /* @__PURE__ */ __name((args) => Number(args[0]), "--align"),
"--no-align": false
},
toCLI: /* @__PURE__ */ __name((val) => {
if (val === false || val === 1 || val === 0) return "--no-align";
if (typeof val === "number" && val !== DEFAULT_ALIGN)
return `--align=${val}`;
return void 0;
}, "toCLI"),
title: "Align values",
description: [
"Insert whitespace between fields and values so that values are visually aligned."
],
examples: ["--align=14 (default)"],
type: "boolean | number",
convertBoolean: { true: DEFAULT_ALIGN, false: 1 },
defaultValue: DEFAULT_ALIGN
},
{
key: "blankLines",
cli: { "--blank-lines": true, "--no-blank-lines": false },
toCLI: /* @__PURE__ */ __name((val) => val ? "--blank-lines" : void 0, "toCLI"),
title: "Insert blank lines",
description: ["Insert an empty line between each entry."],
type: "boolean"
},
{
key: "sort",
cli: {
"--sort": /* @__PURE__ */ __name((args) => args.length > 0 ? args : true, "--sort"),
"--no-sort": false
},
toCLI: /* @__PURE__ */ __name((val) => {
if (Array.isArray(val) && val.length > 0)
return `--sort=${val.join(",")}`;
if (val === true) return "--sort";
return void 0;
}, "toCLI"),
title: "Sort bibliography entries",
description: [
"Sort entries by the specified field names (citation key is used if no fields are specified). For descending order, prefix the field with a dash (-).",
"Multiple fields may be specified to sort everything by first field, then by the second field whenever the first field for entries are equal, etc.",
"The following additional fields are also permitted: key (entry citation key), type (sorts by the type of entry, e.g. article), and special (ensures that @string, @preamble, @set, and @xdata entries are first). "
],
examples: [
"--sort (sort by citation key)",
"--sort=-year,name (sort year descending then name ascending)",
"--sort=name,year"
],
type: "boolean | string[]",
convertBoolean: { true: DEFAULT_SORT, false: void 0 }
},
{
key: "duplicates",
cli: {
"--duplicates": /* @__PURE__ */ __name((args) => {
if (args.length === 0) return true;
for (const i of args) {
if (i !== "doi" && i !== "key" && i !== "abstract" && i !== "citation") {
console.error(`Invalid key for merge option: "${i}"`);
process.exit(1);
}
}
return args;
}, "--duplicates")
},
toCLI: /* @__PURE__ */ __name((val) => {
if (Array.isArray(val) && val.length > 0)
return `--duplicates=${val.join(",")}`;
if (val === true) return "--duplicates";
return void 0;
}, "toCLI"),
title: "Check for duplicates",
description: [
"Warn if duplicates are found, which are entries where DOI, abstract, or author and title are the same."
],
examples: [
"--duplicates doi (same DOIs)",
"--duplicates key (same IDs)",
"--duplicates abstract (similar abstracts)",
"--duplicates citation (similar author and titles)",
"--duplicates doi, key (identical DOI or keys)",
"--duplicates (same DOI, key, abstract, or citation)"
],
type: "boolean | ('doi' | 'key' | 'abstract' | 'citation')[]",
convertBoolean: { true: DEFAULT_MERGE_CHECK, false: void 0 },
defaultValue: /* @__PURE__ */ __name((options) => options.merge ? DEFAULT_MERGE_CHECK : void 0, "defaultValue")
},
{
key: "merge",
cli: {
"--merge": /* @__PURE__ */ __name((args) => {
if (args.length === 0) return true;
if (args[0] !== "first" && args[0] !== "last" && args[0] !== "combine" && args[0] !== "overwrite") {
console.error(`Invalid merge strategy: "${args[0]}"`);
process.exit(1);
}
return args[0];
}, "--merge"),
"--no-merge": false
},
toCLI: /* @__PURE__ */ __name((val) => {
if (typeof val === "string") return `--merge=${val}`;
if (val) return "--merge";
return void 0;
}, "toCLI"),
title: "Merge duplicate entries",
description: [
"Merge duplicates entries. Use the duplicates option to determine how duplicates are identified. There are different ways to merge:",
"- first: only keep the original entry",
"- last: only keep the last found duplicate",
"- combine: keep original entry and merge in fields of duplicates if they do not already exist",
"- overwrite: keep original entry and merge in fields of duplicates, overwriting existing fields if they exist"
],
type: "boolean | 'first' | 'last' | 'combine' | 'overwrite'",
convertBoolean: { true: "combine", false: void 0 }
},
{
key: "stripEnclosingBraces",
cli: { "--strip-enclosing-braces": true },
toCLI: /* @__PURE__ */ __name((val) => val ? "--strip-enclosing-braces" : void 0, "toCLI"),
title: "Strip double-braced values",
description: [
"Where an entire value is enclosed in double braces, remove the extra braces. For example, {{Journal of Tea}} will become {Journal of Tea}."
],
type: "boolean",
defaultValue: false
},
{
key: "dropAllCaps",
cli: { "--drop-all-caps": true },
toCLI: /* @__PURE__ */ __name((val) => val ? "--drop-all-caps" : void 0, "toCLI"),
title: "Drop all caps",
description: [
"Where values are all caps, make them title case. For example, {JOURNAL OF TEA} will become {Journal of Tea}. Roman numerals will be left unchanged."
],
type: "boolean",
defaultValue: false
},
{
key: "escape",
cli: { "--escape": true, "--no-escape": false },
toCLI: /* @__PURE__ */ __name((val) => val === false ? "--no-escape" : void 0, "toCLI"),
title: "Escape special characters",
description: [
"Escape special characters, such as umlaut. This ensures correct typesetting with latex. Enabled by default."
],
type: "boolean",
defaultValue: true
},
{
key: "sortFields",
cli: { "--sort-fields": /* @__PURE__ */ __name((args) => args.length > 0 ? args : true, "--sort-fields") },
toCLI: /* @__PURE__ */ __name((val) => {
if (Array.isArray(val) && val.length > 0) {
if (JSON.stringify(val) === JSON.stringify(DEFAULT_FIELD_SORT)) {
return "--sort-fields";
}
return `--sort-fields=${val.join(",")}`;
}
if (val === true) return "--sort-fields";
return void 0;
}, "toCLI"),
title: "Sort fields",
description: [
"Sort the fields within entries.",
"If no fields are specified fields will be sorted by: title, shorttitle, author, year, month, day, journal, booktitle, location, on, publisher, address, series, volume, number, pages, doi, isbn, issn, url, urldate, copyright, category, note, metadata"
],
examples: ["--sort-fields=name,author"],
type: "boolean | string[]",
convertBoolean: { true: DEFAULT_FIELD_SORT, false: void 0 },
defaultValue: void 0
},
{
key: "sortProperties",
cli: { "--sort-properties": /* @__PURE__ */ __name((args) => args.length > 0 ? args : true, "--sort-properties") },
title: "Sort properties",
description: ["Alias of sort fields (legacy)"],
type: "boolean | string[]",
deprecated: true
},
{
key: "stripComments",
cli: { "--strip-comments": true, "--no-strip-comments": false },
toCLI: /* @__PURE__ */ __name((val) => val ? "--strip-comments" : void 0, "toCLI"),
title: "Remove comments",
description: ["Remove all comments from the bibtex source."],
type: "boolean",
defaultValue: false
},
{
key: "trailingCommas",
cli: { "--trailing-commas": true, "--no-trailing-commas": true },
toCLI: /* @__PURE__ */ __name((val) => val ? "--trailing-commas" : void 0, "toCLI"),
title: "Trailing commas",
description: ["End the last key value pair in each entry with a comma."],
type: "boolean",
defaultValue: false
},
{
key: "encodeUrls",
cli: { "--encode-urls": true, "--no-encode-urls": true },
toCLI: /* @__PURE__ */ __name((val) => val ? "--encode-urls" : void 0, "toCLI"),
title: "Encode URLs",
description: [
"Replace invalid URL characters with percent encoded values."
],
type: "boolean",
defaultValue: false
},
{
key: "tidyComments",
cli: { "--tidy-comments": true, "--no-tidy-comments": false },
toCLI: /* @__PURE__ */ __name((val) => val === false ? "--no-tidy-comments" : void 0, "toCLI"),
title: "Tidy comments",
description: ["Remove whitespace surrounding comments."],
type: "boolean",
defaultValue: true
},
{
key: "removeEmptyFields",
cli: { "--remove-empty-fields": true, "--no-remove-empty-fields": false },
toCLI: /* @__PURE__ */ __name((val) => val ? "--remove-empty-fields" : void 0, "toCLI"),
title: "Remove empty fields",
description: ["Remove any fields that have empty values."],
type: "boolean",
defaultValue: false
},
{
key: "removeDuplicateFields",
cli: {
"--remove-dupe-fields": true,
"--no-remove-dupe-fields": false
},
toCLI: /* @__PURE__ */ __name((val) => val === false ? "--no-remove-dupe-fields" : void 0, "toCLI"),
title: "Remove duplicate fields",
description: [
"Only allow one of each field in each entry. Enabled by default."
],
type: "boolean",
defaultValue: true
},
{
key: "generateKeys",
cli: { "--generate-keys": /* @__PURE__ */ __name((args) => args.length > 0 ? args : true, "--generate-keys") },
toCLI: /* @__PURE__ */ __name((val) => {
if (val === true || val === DEFAULT_KEY_TEMPLATE)
return "--generate-keys";
if (typeof val === "string")
return `--generate-keys="${val.replace(/"/g, '\\"')}"`;
return void 0;
}, "toCLI"),
title: "Generate citation keys [Experimental]",
description: [
"For all entries replace the key with a new key of the form <author><year><title>. A JabRef citation pattern can be provided. This is an experimental option that may change without warning."
],
type: "boolean | string",
convertBoolean: {
true: DEFAULT_KEY_TEMPLATE,
false: void 0
},
defaultValue: void 0
},
{
key: "maxAuthors",
cli: { "--max-authors": /* @__PURE__ */ __name((args) => Number(args[0]), "--max-authors") },
toCLI: /* @__PURE__ */ __name((val) => val ? `--max-authors=${val}` : void 0, "toCLI"),
title: "Maximum authors",
description: [
'Truncate authors if above a given number into "and others".'
],
type: "number"
},
{
key: "lowercase",
cli: { "--no-lowercase": false },
toCLI: /* @__PURE__ */ __name((val) => val === false ? "--no-lowercase" : void 0, "toCLI"),
title: "Lowercase fields",
description: ["Lowercase field names and entry type. Enabled by default."],
type: "boolean",
defaultValue: true
},
{
key: "enclosingBraces",
cli: {
"--enclosing-braces": /* @__PURE__ */ __name((args) => args.length > 0 ? args : true, "--enclosing-braces")
},
toCLI: /* @__PURE__ */ __name((val) => {
if (Array.isArray(val) && val.length > 0)
return `--enclosing-braces=${val.join(",")}`;
if (val === true) return "--enclosing-braces";
return void 0;
}, "toCLI"),
title: "Enclose values in double braces",
description: [
"Enclose the given fields in double braces, such that case is preserved during BibTeX compilation."
],
examples: [
"--enclosing-braces=title,journal (output title and journal fields will be of the form {{This is a title}})",
"--enclosing-braces (equivalent to ---enclosing-braces=title)"
],
type: "boolean | string[]",
convertBoolean: { true: ["title"], false: void 0 }
},
{
key: "removeBraces",
cli: {
"--remove-braces": /* @__PURE__ */ __name((args) => args.length > 0 ? args : true, "--remove-braces")
},
toCLI: /* @__PURE__ */ __name((val) => {
if (Array.isArray(val) && val.length > 0)
return `--remove-braces=${val.join(",")}`;
if (val === true) return "--remove-braces";
return void 0;
}, "toCLI"),
title: "Remove braces",
description: [
"Remove any curly braces within the value, unless they are part of a command."
],
examples: [
"--remove-braces=title,journal",
"--remove-braces (equivalent to ---remove-braces=title)"
],
type: "boolean | string[]",
convertBoolean: { true: ["title"], false: void 0 }
},
{
key: "wrap",
cli: {
"--wrap": /* @__PURE__ */ __name((args) => args.length > 0 ? Number(args[0]) : true, "--wrap"),
"--no-wrap": false
},
toCLI: /* @__PURE__ */ __name((val) => val ? `--wrap=${val}` : void 0, "toCLI"),
title: "Wrap values",
description: ["Wrap long values at the given column"],
examples: ["--wrap (80 by default)", "--wrap=82"],
type: "boolean | number",
convertBoolean: { true: DEFAULT_WRAP, false: void 0 }
},
{
key: "version",
cli: { "--version": true, "-v": true },
title: "Version",
description: ["Show bibtex-tidy version."],
type: "boolean"
},
{
key: "quiet",
cli: { "--quiet": true },
title: "Quiet",
description: ["Suppress logs on stdout."],
type: "boolean"
},
{
key: "backup",
cli: { "--backup": true, "--no-backup": false },
title: "Backup",
description: [
"Make a backup <filename>.original. Enabled by default (unless --modify is explicitly provided or outputting to a different file/stdio). Deprecated but provided for backward compatibility."
],
type: "boolean",
defaultValue: true,
deprecated: true
}
];
// src/optionUtils.ts
function normalizeOptions(options) {
return Object.fromEntries(
optionDefinitions.map((def) => {
const key = def.key;
const value = options[key];
if (def.convertBoolean && typeof value === "boolean") {
return [
key,
value ? def.convertBoolean.true : def.convertBoolean.false
];
}
if (typeof value === "undefined" && def.defaultValue !== void 0) {
if (typeof def.defaultValue === "function") {
return [key, def.defaultValue(options)];
}
return [key, def.defaultValue];
}
return [key, value];
})
);
}
__name(normalizeOptions, "normalizeOptions");
// src/cache.ts
var Cache = class {
constructor(tidyOptions = normalizeOptions({})) {
this.tidyOptions = tidyOptions;
this.valueLookup = /* @__PURE__ */ new Map();
this.fieldLookup = /* @__PURE__ */ new Map();
this.renderValueLookup = /* @__PURE__ */ new Map();
}
static {
__name(this, "Cache");
}
lookupEntryValue(entry, field) {
const fieldName = field.toLocaleLowerCase();
let value = this.valueLookup.get(entry)?.get(field);
if (value === void 0) {
const field2 = this.lookupField(entry, fieldName);
if (!field2) {
value = "";
} else {
value = formatValue(field2, this.tidyOptions) ?? "";
}
this.valueLookup.set(entry, /* @__PURE__ */ new Map([[fieldName, value]]));
}
return value;
}
invalidateEntryValue(entry, field) {
this.valueLookup.get(entry)?.delete(field.toLocaleLowerCase());
this.renderValueLookup.get(entry)?.delete(field.toLocaleLowerCase());
}
lookupField(entry, fieldLc) {
let fieldNode = this.fieldLookup.get(entry)?.get(fieldLc);
if (fieldNode === void 0) {
fieldNode = entry.fields.find(
(field) => field.name.toLocaleLowerCase() === fieldLc
);
}
return fieldNode;
}
lookupRenderedEntryValue(entry, field) {
const fieldName = field.toLocaleLowerCase();
let value = this.renderValueLookup.get(entry)?.get(field);
if (value === void 0) {
const entryValue = this.lookupEntryValue(entry, fieldName);
value = parseLaTeX(entryValue).renderAsText();
this.renderValueLookup.set(entry, /* @__PURE__ */ new Map([[fieldName, value]]));