v2 / cmd / tools / vdoc / markdown.v
57 lines · 54 sloc · 1.66 KB · e7905ea841b62effc3aaba5bcc40d4408737945a
Raw
1module main
2
3import strings
4import document as doc
5
6fn (vd &VDoc) gen_markdown(d doc.Doc, with_toc bool) string {
7 cfg := vd.cfg
8 mut hw := strings.new_builder(200)
9 mut cw := strings.new_builder(200)
10 hw.writeln('# ${d.head.content}')
11 if d.head.comments.len > 0 && cfg.include_comments {
12 comments := if vd.cfg.include_examples {
13 d.head.merge_comments()
14 } else {
15 d.head.merge_comments_without_examples()
16 }
17 hw.writeln('${comments}')
18 }
19 hw.writeln('\n')
20 if with_toc {
21 hw.writeln('## Contents')
22 }
23 vd.write_markdown_content(d.contents.arr(), mut cw, mut hw, 0, with_toc)
24 footer_text := gen_footer_text(d, !vd.cfg.no_timestamp)
25 cw.writeln('#### ${footer_text}')
26 return hw.str() + '\n' + cw.str()
27}
28
29fn (vd &VDoc) write_markdown_content(contents []doc.DocNode, mut cw strings.Builder, mut hw strings.Builder,
30 indent int, with_toc bool) {
31 for cn in contents {
32 if with_toc && cn.name != '' {
33 hw.writeln(' '.repeat(2 * indent) + '- [${slug(cn.name)}](#${cn.name})')
34 cw.writeln('## ${cn.name}')
35 }
36 if cn.content.len > 0 {
37 cw.writeln('```v\n${cn.content}\n```\n')
38 if cn.comments.len > 0 {
39 comments := cn.merge_comments_without_examples()
40 cw.writeln('${comments}\n')
41 }
42 // Write examples if any found
43 examples := cn.examples()
44 if vd.cfg.include_examples && examples.len > 0 {
45 example_title := if examples.len > 1 { 'Examples' } else { 'Example' }
46 cw.writeln('${example_title}\n```v\n')
47 for example in examples {
48 cw.writeln('${example}\n')
49 }
50 cw.writeln('```\n')
51 }
52 cw.writeln(r'[[Return to contents]](#Contents)')
53 cw.writeln('')
54 }
55 vd.write_markdown_content(cn.children, mut cw, mut hw, indent + 1, with_toc)
56 }
57}
58