Debian Codegraph @

src/globus_sdk/_internal/extensions/sphinxext/directives/add_content_directive.py

raw
1 import typing as t
2
3 from docutils import nodes
4 from docutils.nodes import Node
5 from docutils.parsers.rst import Directive
6 from docutils.statemachine import StringList
7 from sphinx.util.nodes import nested_parse_with_titles
8
9
10 class AddContentDirective(Directive):
11 # Directive source:
12 # https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/parsers/rst/__init__.py
13 #
14 # for information on how to write directives, see also:
15 # https://docutils.sourceforge.io/docs/howto/rst-directives.html#the-directive-class
16 def gen_rst(self) -> t.Iterator[str]:
17 yield from []
18
19 def run(self) -> t.Sequence[Node]:
20 # implementation is based on the docs for parsing directive content as ReST doc:
21 # https://www.sphinx-doc.org/en/master/extdev/markupapi.html#parsing-directive-content-as-rest
22 # which is how we will create rst here and have sphinx parse it
23
24 # we need to add content lines into a ViewList which represents the content
25 # of this directive, each one is appended with a "source" name
26 # the best documentation for docutils is the source, so for ViewList, see...
27 # https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/statemachine.py
28 # writing the source name with angle-brackets seems to be the norm, but it's not
29 # clear why -- perhaps docutils will care about the source in some way
30 viewlist = StringList()
31 linemarker = "<" + self.__class__.__name__.lower() + ">"
32 for line in self.gen_rst():
33 viewlist.append(line, linemarker)
34
35 # create a section node (it doesn't really matter what node type we use here)
36 # and add the viewlist we just created as the children of the new node via the
37 # nested_parse method
38 # then return the children (i.e. discard the docutils node)
39 node = nodes.section()
40 node.document = self.state.document
41 nested_parse_with_titles(self.state, viewlist, node)
42 return node.children