Search code examples
python-sphinxrestructuredtextdocutils

How to add rst format in nodes for directive?


How I can use rst in nodes? For example I want to output icluded file about.rst

class Foo(Directive):

    def run(self):
        return [
            nodes.Text("**adad**"),  # <-- Must be a bold text
            nodes.Text(".. include:: about.rst"),  # <-- Must include file
        ]

Solution

  • You can construct a ViewList of your raw rst data (one line per entry), get Sphinx to parse that content, and then return the nodes Sphinx gives you. The following worked for me:

    from docutils import nodes
    from docutils.statemachine import ViewList
    from sphinx.util.compat import Directive
    from sphinx.util.nodes import nested_parse_with_titles
    
    class Foo(Directive):
        def run(self):
            rst = ViewList()
    
            # Add the content one line at a time.
            # Second argument is the filename to report in any warnings
            # or errors, third argument is the line number.            
            rst.append("**adad**", "fakefile.rst", 10)
            rst.append("", "fakefile.rst", 11)
            rst.append(".. include:: about.rst", "fakefile.rst", 12)
    
            # Create a node.
            node = nodes.section()
            node.document = self.state.document
    
            # Parse the rst.
            nested_parse_with_titles(self.state, rst, node)
    
            # And return the result.
            return node.children
    
    def setup(app):
        app.add_directive('foo', Foo)
    

    I had to do something similar for a project --- in lieu of any (easily found) relevant documentation I used the source of the inbuilt autodoc extension as a guide.