Include a custom directive into another custom directive

Viewed 65

Following Sphinx TODO directive tutorial, I have made a Sphinx custom directive (let's call it A) that takes a file path as input, extracts information from this file, and produce nodes accordingly.

I want to create a new custom directive (let's call it B) that takes a directory as input, calls directive A on all files inside the directory (the search for files is actually a bit more involved than that, but it has no relevance to my issue) and appends the produced nodes.

I cannot find how to do that. I have started to write the Python file for this directive B, but I do not know how to get a hold of a node class corresponding to directive A. I'd like to write something like this:

def run(self):
    nodes = []
    directory = self.arguments[0]
    for filepath in directory:
        nodes += nodes.mydirectiveA("path/to/file") #not proper code
    return nodes

What am I missing here?

Note: I have found this question whose title was promissing, but I do not have this inheritance relationship in my case.

1 Answers

IMO, you may not need to "get a hold of a node class corresponding to directive A". Directive class only helps you parse rST to arguments and options, it does not relate to the node creation.

As directive A is implemented by yourself, you can create a common helper function shared by both A and B for creating nodes, like this:

From:

class A(SphinxDirecitve):
  # ...
  def run(self) -> list[nodes.Node]
    # do sth
    pass

To:

def add_files_nodes(options) -> list[nodes.Node]:
   # do sth
   pass
class A(SphinxDirecitve):
  # ...
  def run(self) -> list[nodes.Node]
    opts = """convert self.options to function arguments"""
    return add_files_nodes(opts)
Related