-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract-code-blocks.ts
More file actions
35 lines (27 loc) · 944 Bytes
/
Copy pathextract-code-blocks.ts
File metadata and controls
35 lines (27 loc) · 944 Bytes
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
import { remark } from 'remark';
import remarkParse from 'remark-parse';
import { visit } from 'unist-util-visit';
import type { Code } from 'mdast';
import type { CodeBlock } from '../types/index.js';
export async function extractCodeBlocks(markdown: string): Promise<CodeBlock[]> {
const tree = remark().use(remarkParse).parse(markdown);
const blocks: CodeBlock[] = [];
const lines = markdown.split(/\r?\n/);
visit(tree, 'code', (node) => {
const codeNode = node as Code;
const startLine = codeNode.position?.start.line;
if (startLine == null || !isFencedCodeBlock(lines[startLine - 1] ?? '')) {
return;
}
blocks.push({
index: blocks.length + 1,
lang: codeNode.lang ?? null,
code: codeNode.value,
meta: codeNode.meta ?? undefined,
});
});
return blocks;
}
function isFencedCodeBlock(openingLine: string): boolean {
return /^[ \t]{0,3}(```|~~~)/.test(openingLine);
}