fork/mons

git clone https://git.julia.blue/fork/mons

coloursofnoiseUpdate pre-commit hooks, include docs in auto-formatting17b9303

main
1.8 KiB68 linesraw
1import textwrap
2
3from docutils import nodes
4from docutils.statemachine import StringList
5from sphinx.application import Sphinx
6from sphinx.domains.std import Glossary
7
8
9class NodeReprVisitor(nodes.NodeVisitor):
10    content_indent = "   "
11
12    def __init__(self, document):
13        super().__init__(document)
14        self.content = ""
15        self.indent = 0
16
17    def visit_bullet_list(self, node):
18        self.bullet = node["bullet"]
19        self.content += "\n"
20        self.indent += 1
21
22    def depart_bullet_list(self, node):
23        self.content += "\n"
24        self.indent -= 1
25
26    def visit_list_item(self, node):
27        self.content += f"{self.content_indent*self.indent} {self.bullet} "
28
29    def visit_paragraph(self, node):
30        self.content += node.astext() + "\n\n"
31
32    def unknown_visit(self, node):
33        pass
34
35    def unknown_departure(self, node):
36        pass
37
38
39class GlossaryGen(Glossary):
40    def run(self) -> list[nodes.Node]:
41        def parse_content(node: nodes.Node):
42            assert node.document
43            visitor = NodeReprVisitor(node.document)
44            node.walkabout(visitor)
45            return visitor.content
46
47        node = nodes.Element()
48        self.state.nested_parse(
49            self.content, self.content_offset, node, match_titles=True
50        )
51
52        parsed_content = [""]
53        for child in node.children:
54            if len(child.children) == 2:
55                term, content = child.children[:2]
56                parsed_content.append(term.astext())
57                parsed_content.append(
58                    textwrap.indent(parse_content(content), "   ") + "\n"
59                )
60
61        content = "\n".join(parsed_content).splitlines()
62        self.content = StringList(content, content)
63
64        return super().run()
65
66
67def setup(app: Sphinx):
68    app.add_directive("glossarygen", GlossaryGen)