Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to replace one directive with another one

I would like to create a substitution (or similar) that transforms one directive into another.

For example:

In our sphinx based documentation, we use Admonitions to create certain note and warning boxes.

However, if we use

.. note:: This is a Note

The title of the box is Note, and This is a Note becomes the first paragraph.

In contrast, this directive

.. admonition:: This is a Note
   :class: note

produces a note box with the desired title.

To make it easier for other editors, I would like to create a substitution, that replaces the first with the second.

Is there anything this can be done with in sphinx?

like image 423
super-qua Avatar asked Oct 15 '25 16:10

super-qua


1 Answers

Yes, it can be done. You have to add a custom directive to Sphinx. Create a Python module (like mydirectives.py next to conf.py) with the following:

import os
import os.path
import re
import subprocess

import docutils.core
import docutils.nodes
import docutils.parsers.rst

class AbstractDirective(docutils.parsers.rst.Directive):
    has_content = True
    required_arguments = 0
    optional_arguments = 0
    option_spec = {}
    final_argument_whitespace = False

    node_class = docutils.nodes.container

    def run(self):
        self.assert_has_content()
        text = '\n'.join(self.content)
        admonition_node = self.node_class(rawsource=text)
        self.state.nested_parse(self.content, self.content_offset,
                                admonition_node)
        admonition_node.set_class("abstract")
        return [admonition_node]


def setup(app):
    app.add_directive('abstract', AbstractDirective)

There must be some way to add the title as well. Perhaps you need to add a title node yourself. The documentation is lacking there, best look at the source for admonitions and you will get a feel for the docutils.

With a custom text node you should be able to make up your own note directive.

like image 138
Martin Ueding Avatar answered Oct 18 '25 18:10

Martin Ueding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!