Repository navigation
Expand file tree
/
Copy pathsections.mq
More file actions
65 lines (57 loc) · 1.96 KB
/
Copy pathsections.mq
File metadata and controls
65 lines (57 loc) · 1.96 KB
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
# Extracts sections from markdown
# Returns an array where each element is a dict with:
# - title: the heading text
# - level: the heading level (1-6)
# - content: array of markdown nodes in that section (including the heading)
import "section"
|
def extract_sections(md_nodes):
let section_list = section::sections(md_nodes)
| map(section_list, fn(s):
let heading = first(s[:header])
| let title = to_text(heading)
| let level = heading.level
| {"title": title, "level": level, "content": s[:children]}
end)
end
# Extracts code blocks from a section
def extract_code_blocks(section_content):
let code_blocks = filter(section_content, is_code)
| map(code_blocks, fn(code):
let lang = attr(code, "lang")
| let text = to_text(code)
| {"lang": lang, "code": text}
end)
end
# Extracts text from a section
def extract_description(section_content):
filter(section_content, is_text)
| first()
| if (is_none()): None else: to_text()
end
# Main query to extract sections with their code blocks
def sections_with_code(md_nodes):
let section_list = extract_sections(md_nodes)
| map(section_list, fn(section):
let title = section["title"]
| let level = section["level"]
| let content = section["content"]
| let codes = extract_code_blocks(content)
| let description = extract_description(content)
| {"title": title, "level": level, "codes": codes, "description": description}
end)
end
# Extracts code blocks that appear before the first heading, i.e. the
# document preamble. Used to declare document-wide task defaults (a `meta`
# block there applies to every task).
def global_code_blocks(md_nodes):
let n = len(md_nodes)
| if (n == 0):
[]
else:
do
let heading_indices = do foreach (i, range(n - 1)): if (is_h(md_nodes[i])): i; | compact();
| let first_heading = if (is_empty(heading_indices)): n else: first(heading_indices)
| extract_code_blocks(md_nodes[0:first_heading])
end
end