/
sample_insert.js
80 lines (69 loc) · 1.91 KB
/
sample_insert.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
import {fromMarkdown} from 'mdast-util-from-markdown'
import {frontmatter} from 'micromark-extension-frontmatter'
import {toMarkdown} from 'mdast-util-to-markdown'
import {frontmatterFromMarkdown, frontmatterToMarkdown} from 'mdast-util-frontmatter'
import * as fs from 'fs'
import { dir } from 'console';
const createContentsAst = (contents) => {
const items = contents.map((item) => {
return {
type: 'listItem',
spread: false,
checked: null,
children: [
{
type: 'paragraph',
children: [
{
type: 'text',
value: item.name,
},
],
},
],
}
});
return {
type: 'list',
spread: false,
children: items,
}
}
const contentsHeadingAst = {
type: "heading",
depth: 2,
children: [
{
type: "text",
value: "Contents",
},
],
};
const contents = [
{name: 'Seal'},
{name: 'Zebra'},
{name: 'Bear'},
]
const ast = fromMarkdown(fs.readFileSync('sample.md'), {
extensions: [frontmatter(['yaml'])],
mdastExtensions: [frontmatterFromMarkdown(['yaml'])]
});
dir(ast, {depth: null});
const targetHeaderIndex = ast.children.findIndex(node => node.type === 'heading' && node.children[0]?.value === 'Tasks');
const contentsAst = createContentsAst(contents);
const children = targetHeaderIndex === -1 ? [...ast.children, contentsHeadingAst, contentsAst] : [
...ast.children.slice(0, targetHeaderIndex),
contentsHeadingAst,
contentsAst,
...ast.children.slice(targetHeaderIndex),
]
const afterAst = { ...ast, ...{children}};
const options = {
bullet: '-',
extensions: [frontmatterToMarkdown(['yaml'])]
}
const replacer = (str) => {
return str.replace(/\\\[/g, '[').replace(/\\_/g, '_').replace(/\\&/g, '&').replace(/\\\*/g, '*');
}
console.log(replacer(toMarkdown(afterAst, options)))
fs.writeFileSync('sample_stored.md', replacer(toMarkdown(afterAst, options)));