-
Notifications
You must be signed in to change notification settings - Fork 48
/
tokensToMyst.ts
627 lines (605 loc) · 16.1 KB
/
tokensToMyst.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
import he from 'he';
import type Token from 'markdown-it/lib/token.js';
import type { GenericNode, GenericParent } from 'myst-common';
import { liftChildren, normalizeLabel, setTextAsChild } from 'myst-common';
import { visit } from 'unist-util-visit';
import { remove } from 'unist-util-remove';
import { selectAll } from 'unist-util-select';
import { u } from 'unist-builder';
import { MarkdownParseState, withoutTrailingNewline } from './fromMarkdown.js';
import type { MdastOptions, TokenHandlerSpec } from './fromMarkdown.js';
export function computeAmsmathTightness(
src: string,
map: [number, number] | null | undefined,
): boolean | 'before' | 'after' {
const lines = src.split('\n');
const tightBefore =
typeof map?.[0] === 'number' && map[0] > 0 ? lines[map[0] - 1].trim() !== '' : false;
// Note: The end line might be different/wrong for AMS math. If that is updated, remove the `+1` that shifts the index
const last = typeof map?.[1] === 'number' ? map?.[1] + 1 : undefined;
const tightAfter =
typeof last === 'number' && last < lines.length ? lines[last]?.trim() !== '' : false;
const tight =
tightBefore && tightAfter ? true : tightBefore ? 'before' : tightAfter ? 'after' : false;
return tight;
}
const NUMBERED_CLASS = /^numbered$/;
const ALIGN_CLASS = /(?:(?:align-)|^)(left|right|center)/;
function getClassName(token: Token, exclude?: RegExp[]): string | undefined {
const allClasses = new Set([
// Grab the trimmed classes from the token
...(token.attrGet('class') ?? '')
.split(' ')
.map((c) => c.trim())
.filter((c) => c),
// Add any from the meta information (these are often repeated)
...(token.meta?.class ?? []),
]);
const className: string = [...allClasses].join(' ');
if (!className) return undefined;
return (
className
.split(' ')
.map((c) => c.trim())
.filter((c) => {
if (!c) return false;
if (!exclude) return true;
return !exclude.reduce((doExclude, test) => doExclude || !!c.match(test), false);
})
.join(' ') || undefined
);
}
function hasClassName(token: Token, matcher: RegExp): false | RegExpMatchArray {
const className = getClassName(token);
if (!className) return false;
const matches = className
.split(' ')
.map((c) => c.match(matcher))
.filter((c) => c);
if (matches.length === 0) return false;
return matches[0] as RegExpMatchArray;
}
function getLang(t: Token) {
return he.decode(t.info).trim().split(' ')[0].replace('\\', '');
}
function getColAlign(t: Token) {
if (t.attrs?.length) {
for (const attrPair of t.attrs) {
if (attrPair[0] === 'style') {
const match = attrPair[1].match(/text-align:(left|right|center)/);
if (match) {
return match[1];
}
}
}
}
}
const defaultMdast: Record<string, TokenHandlerSpec> = {
heading: {
type: 'heading',
getAttrs(token) {
return {
depth: Number(token.tag[1]),
enumerated: token.meta?.enumerated,
};
},
},
hr: {
type: 'thematicBreak',
noCloseToken: true,
isLeaf: true,
},
paragraph: {
type: 'paragraph',
},
blockquote: {
type: 'blockquote',
},
ordered_list: {
type: 'list',
getAttrs(token, tokens, index) {
const info = tokens[index + 1]?.info;
const start = Number(tokens[index + 1]?.info);
return {
ordered: true,
start: isNaN(start) || !info ? 1 : start,
spread: false,
};
},
},
bullet_list: {
type: 'list',
attrs: {
ordered: false,
spread: false,
},
},
list_item: {
type: 'listItem',
getAttrs(t) {
const attrs = { spread: true } as Record<string, any>;
if (t.attrGet('class') === 'task-list-item') {
// This is a temporary property used to clean up the AST in a subsequent pass
attrs.__taskList = true;
}
return attrs;
},
},
em: {
type: 'emphasis',
},
strong: {
type: 'strong',
},
colon_fence: {
type: 'code',
isLeaf: true,
noCloseToken: true,
getAttrs(t) {
return { lang: getLang(t), value: withoutTrailingNewline(t.content) };
},
},
fence: {
type: 'code',
isLeaf: true,
getAttrs(t) {
const name = t.meta?.name || undefined;
const showLineNumbers = !!(
t.meta?.linenos ||
t.meta?.linenos === null || // Weird docutils implementation
t.meta?.['number-lines'] ||
// If lineno-start is present, linenos option is also automatically activated
// https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-option-code-block-lineno-start
t.meta?.['lineno-start']
);
const lineno = t.meta?.['lineno-start'] ?? t.meta?.['number-lines'];
const startingLineNumber =
lineno && lineno !== 1 && !isNaN(Number(lineno)) ? Number(lineno) : undefined;
const emphasizeLines = t.meta?.['emphasize-lines']
? t.meta?.['emphasize-lines']
.split(',')
.map((n: string) => Number(n.trim()))
.filter((n: number) => !isNaN(n) && n > 0)
: undefined;
return {
lang: getLang(t),
...normalizeLabel(name),
class: getClassName(t),
showLineNumbers: showLineNumbers || undefined, // Only add to MDAST if true
startingLineNumber: showLineNumbers ? startingLineNumber : undefined, // Only if showing line numbers!
emphasizeLines,
value: withoutTrailingNewline(t.content),
};
},
},
code_block: {
type: 'code',
isLeaf: true,
getAttrs(t) {
return { lang: getLang(t), value: withoutTrailingNewline(t.content) };
},
},
code_inline: {
type: 'inlineCode',
noCloseToken: true,
isText: true,
},
hardbreak: {
type: 'break',
noCloseToken: true,
isLeaf: true,
},
link: {
type: 'link',
getAttrs(token) {
return {
url: token.attrGet('href'),
title: token.attrGet('title') ?? undefined,
};
},
},
image: {
type: 'image',
noCloseToken: true,
isLeaf: true,
getAttrs(token) {
const alt = token.attrGet('alt') || token.children?.reduce((i, t) => i + t?.content, '');
const alignMatch = hasClassName(token, ALIGN_CLASS);
const align = alignMatch ? alignMatch[1] : undefined;
return {
url: token.attrGet('src'),
alt: alt || undefined,
title: token.attrGet('title') || undefined,
class: getClassName(token, [ALIGN_CLASS]),
width: token.attrGet('width') || undefined,
height: token.attrGet('height') || undefined,
align,
};
},
},
dl: {
type: 'definitionList',
},
dt: {
type: 'definitionTerm',
},
dd: {
type: 'definitionDescription',
},
table: {
type: 'table',
getAttrs(token) {
const name = token.meta?.name || undefined;
return {
kind: undefined,
...normalizeLabel(name),
enumerated: token.meta?.enumerated,
class: getClassName(token, [NUMBERED_CLASS, ALIGN_CLASS]),
align: token.meta?.align || undefined,
};
},
},
// table_caption: {
// type: 'caption',
// },
thead: {
type: '_lift',
},
tbody: {
type: '_lift',
},
tr: {
type: 'tableRow',
},
th: {
type: 'tableCell',
getAttrs(t) {
return { header: true, align: getColAlign(t) || undefined };
},
},
td: {
type: 'tableCell',
getAttrs(t) {
return { align: getColAlign(t) || undefined };
},
},
math_inline: {
type: 'inlineMath',
noCloseToken: true,
isText: true,
},
math_inline_double: {
type: 'math',
noCloseToken: true,
isText: true,
getAttrs(t) {
return {
enumerated: t.meta?.enumerated,
};
},
},
math_block: {
type: 'math',
noCloseToken: true,
isText: true,
getAttrs(t) {
const name = t.info || undefined;
return {
...normalizeLabel(name),
enumerated: t.meta?.enumerated,
};
},
},
math_block_label: {
type: 'math',
noCloseToken: true,
isText: true,
getAttrs(t) {
const name = t.info || undefined;
return {
...normalizeLabel(name),
enumerated: t.meta?.enumerated,
};
},
},
amsmath: {
type: 'math',
noCloseToken: true,
isText: true,
getAttrs(t, tokens, index, state) {
const tight = computeAmsmathTightness(state.src, t.map);
const attrs = {
enumerated: t.meta?.enumerated,
} as Record<string, any>;
if (tight) attrs.tight = tight;
return attrs;
},
},
footnote_ref: {
type: 'footnoteReference',
noCloseToken: true,
isLeaf: true,
getAttrs(t) {
const { identifier, label } = normalizeLabel(t?.meta?.label) || {};
return { identifier, label };
},
},
footnote_anchor: {
type: '_remove',
noCloseToken: true,
},
footnote_block: {
// The footnote block is a view concern, not AST
// Lift footnotes out of the tree
type: '_lift',
},
footnote: {
type: 'footnoteDefinition',
getAttrs(t) {
const { identifier, label } = normalizeLabel(t?.meta?.label) || {};
return { identifier, label };
},
},
cite: {
type: 'cite',
noCloseToken: true,
isLeaf: true,
getAttrs(t) {
const { identifier, label } = normalizeLabel(t?.meta?.label) || {};
return {
identifier,
label,
kind: t.meta.kind,
partial: t.meta.partial, // author or year
// TODO: can use the parsed version in the future
prefix: t.meta.prefix?.[0].content,
suffix: t.meta.suffix?.[0].content,
};
},
},
cite_group: {
type: 'citeGroup',
getAttrs(t) {
return { kind: t.meta.kind };
},
},
parsed_directive: {
type: 'mystDirective',
getAttrs(t) {
return {
name: t.info,
args: t.meta?.arg,
options: t.meta?.options,
value: t.content || undefined,
tight: t.meta?.tight || undefined,
processed: false,
};
},
},
directive_arg: {
type: 'mystDirectiveArg',
getAttrs(t) {
return {
value: t.content,
};
},
},
directive_option: {
type: 'mystDirectiveOption',
getAttrs(t) {
return {
name: t.info,
value: t.content,
};
},
},
directive_body: {
type: 'mystDirectiveBody',
getAttrs(t) {
return {
value: t.content,
};
},
},
directive_error: {
type: 'mystDirectiveError',
noCloseToken: true,
},
parsed_role: {
type: 'mystRole',
getAttrs(t) {
return {
name: t.info,
value: t.content,
processed: false,
};
},
},
role_body: {
type: 'mystRoleBody',
getAttrs(t) {
return {
value: t.content,
};
},
},
role_error: {
type: 'mystRoleError',
noCloseToken: true,
isLeaf: true,
getAttrs(t) {
return {
value: t.content,
};
},
},
myst_target: {
type: 'mystTarget',
noCloseToken: true,
isLeaf: true,
getAttrs(t) {
return {
label: t.content,
};
},
},
html_inline: {
type: 'html',
noCloseToken: true,
isText: true,
},
html_block: {
type: 'html',
noCloseToken: true,
isText: true,
},
myst_block_break: {
type: 'blockBreak',
noCloseToken: true,
isLeaf: true,
getAttrs(t) {
return {
meta: t.content || undefined,
};
},
},
myst_line_comment: {
type: 'comment',
noCloseToken: true,
isLeaf: true,
getAttrs(t) {
return {
value: t.content.trim() || undefined,
};
},
},
};
function hoistSingleImagesOutofParagraphs(tree: GenericParent) {
// Hoist up all paragraphs with a single image
visit(tree, 'paragraph', (node: GenericParent) => {
if (!(node.children?.length === 1 && node.children?.[0].type === 'image')) return;
const child = node.children[0];
Object.keys(node).forEach((k) => {
delete (node as any)[k];
});
Object.assign(node, child);
});
}
function nestSingleImagesIntoParagraphs(tree: GenericParent) {
tree.children = tree.children.map((node) => {
if (node.type === 'image') {
return { type: 'paragraph', children: [node] };
} else {
return node;
}
});
}
const defaultOptions: MdastOptions = {
handlers: defaultMdast,
hoistSingleImagesOutofParagraphs: true,
nestBlocks: true,
};
export function tokensToMyst(
src: string,
tokens: Token[],
options = defaultOptions,
): GenericParent {
const opts = {
...defaultOptions,
...options,
handlers: { ...defaultOptions.handlers, ...options?.handlers },
};
const state = new MarkdownParseState(src, opts.handlers);
state.parseTokens(tokens);
let tree: GenericParent;
do {
tree = state.closeNode() as GenericParent;
} while (state.stack.length);
// Remove all redundant nodes marked for removal
remove(tree, '_remove');
// Lift up all nodes that are named "lift"
liftChildren(tree, '_lift');
// Remove unnecessary admonition titles from AST
// These are up to the serializer to put in
// visit(tree, 'admonition', (node: Admonition) => {
// const { kind, children } = node;
// if (!kind || !children || kind === AdmonitionKind.admonition) return;
// const expectedTitle = admonitionKindToTitle(kind);
// const titleNode = children[0];
// if (titleNode.type === 'admonitionTitle' && titleNode.children?.[0]?.value === expectedTitle)
// node.children = children.slice(1);
// });
// Change all task lists to checked
selectAll('listItem[__taskList=true]', tree).forEach((node: GenericNode) => {
delete node.__taskList;
const html = node.children?.slice(0, 1);
if (html && html[0].type === 'html' && html[0].value?.includes('task-list-item-checkbox')) {
node.checked = html[0].value.includes('checked=""');
// Remove the inline html
node.children?.splice(0, 1);
if (node.children?.[0].type === 'text') {
// Ensure that the parsing is the same as other text lists, that strip leading whitespace
node.children[0].value = (node.children[0].value as string).replace(/^\s/, '');
}
}
});
// Move crossReference text value to children
visit(tree, 'crossReference', (node: GenericNode) => {
delete node.children;
if (node.value) {
setTextAsChild(node, node.value);
delete node.value;
}
});
// Nest block content inside of a block
if (opts.nestBlocks) {
const newTree = u('root', [] as GenericNode[]);
let lastBlock: GenericNode | undefined;
const pushBlock = () => {
if (!lastBlock) return;
newTree.children.push(lastBlock);
};
(tree as GenericNode).children?.forEach((node) => {
if (node.type === 'blockBreak') {
pushBlock();
lastBlock = node;
node.type = 'block';
node.children = node.children ?? [];
return;
}
const stack = lastBlock ? lastBlock : newTree;
stack.children?.push(node);
});
pushBlock();
tree = newTree as GenericParent;
}
// ensureCaptionIsParagraph(tree);
// Replace "table node with caption" with "figure node with table and caption"
// TODO: Clean up when we update to typescript > 4.6.2 and we have access to
// parent in visitor function.
// i.e. visit(tree, 'table', (node, index parent) => {...})
// https://github.com/microsoft/TypeScript/issues/46900
// selectAll('table', tree).forEach((node: GenericNode) => {
// const captionChildren = node.children?.filter((n: GenericNode) => n.type === 'caption');
// if (captionChildren?.length) {
// const tableChildren = node.children?.filter((n: GenericNode) => n.type !== 'caption');
// const newTableNode: GenericNode = {
// type: 'table',
// align: node.align,
// children: tableChildren,
// };
// node.type = 'container';
// node.kind = 'table';
// node.children = [...captionChildren, newTableNode];
// delete node.align;
// } else {
// delete node.enumerated;
// }
// });
if (opts.hoistSingleImagesOutofParagraphs) {
hoistSingleImagesOutofParagraphs(tree);
} else {
nestSingleImagesIntoParagraphs(tree);
}
return tree;
}