-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
convert-inline-footnotes.js
96 lines (82 loc) · 3.21 KB
/
convert-inline-footnotes.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
import { visit } from 'unist-util-visit';
function convertInlineFootnotes() {
return (tree) => {
let footnoteCount = 1;
const footnotes = [];
const existingFootnotes = new Set();
// Collect existing footnote definitions and references
visit(tree, 'footnoteDefinition', (node) => {
const footnoteId = parseInt(node.identifier, 10);
if (!isNaN(footnoteId)) {
existingFootnotes.add(footnoteId);
footnoteCount = Math.max(footnoteCount, footnoteId + 1);
}
});
visit(tree, 'footnoteReference', (node) => {
const footnoteId = parseInt(node.identifier, 10);
if (!isNaN(footnoteId)) {
existingFootnotes.add(footnoteId);
footnoteCount = Math.max(footnoteCount, footnoteId + 1);
}
});
// Process inline footnotes
visit(tree, 'text', (node, index, parent) => {
const inlineFootnoteRegex = /\^\[(.+?)\]/g;
let match;
let lastIndex = 0;
const newChildren = [];
while ((match = inlineFootnoteRegex.exec(node.value)) !== null) {
const footnoteText = match[1];
let footnoteId = footnoteCount;
// Find the next available footnote ID
while (existingFootnotes.has(footnoteId)) {
footnoteId++;
}
existingFootnotes.add(footnoteId);
footnoteCount = footnoteId + 1;
// Add text before the footnote
if (match.index > lastIndex) {
newChildren.push({
type: 'text',
value: node.value.slice(lastIndex, match.index),
});
}
// Add the footnote reference
newChildren.push({
type: 'footnoteReference',
identifier: String(footnoteId),
label: String(footnoteId),
});
// Collect the footnote definition
footnotes.push({
type: 'footnoteDefinition',
identifier: String(footnoteId),
label: String(footnoteId),
children: [{
type: 'paragraph',
children: [{
type: 'text',
value: footnoteText,
}],
}],
});
lastIndex = inlineFootnoteRegex.lastIndex;
}
// Add remaining text after the last footnote
if (lastIndex < node.value.length) {
newChildren.push({
type: 'text',
value: node.value.slice(lastIndex),
});
}
if (newChildren.length > 0) {
parent.children.splice(index, 1, ...newChildren);
}
});
// Append the collected footnotes at the end of the document
if (footnotes.length > 0) {
tree.children.push(...footnotes);
}
};
}
export default convertInlineFootnotes;