|
| 1 | +"""Extension that enables docutils' MathML-based math rendering.""" |
| 2 | + |
| 3 | +import docutils.nodes |
| 4 | +import docutils.utils.math |
| 5 | +from docutils.writers._html_base import HTMLTranslator as BaseHTMLTranslator |
| 6 | +from sphinx.application import Sphinx |
| 7 | + |
| 8 | +# Sphinx overrides Docutils' math rendering. Here, we override Sphinx's |
| 9 | +# override to revert to docutils' math rendering. |
| 10 | + |
| 11 | + |
| 12 | +def visit_math(self: BaseHTMLTranslator, node: docutils.nodes.math): |
| 13 | + self.math_output = "mathml" |
| 14 | + self.math_output_options = [] |
| 15 | + BaseHTMLTranslator.visit_math(self, node) |
| 16 | + |
| 17 | + |
| 18 | +def visit_math_block(self: BaseHTMLTranslator, node: docutils.nodes.math_block): |
| 19 | + self.math_output = "mathml" |
| 20 | + self.math_output_options = [] |
| 21 | + # Note: We can't call `BaseHTMLTranslator.visit_math_block` here, because |
| 22 | + # that just forwards to `self.visit_math`, which ultimately calls back into |
| 23 | + # our `visit_math` function defined above but without the `math_env` |
| 24 | + # argument. |
| 25 | + BaseHTMLTranslator.visit_math( |
| 26 | + self, node, math_env=docutils.utils.math.pick_math_environment(node.astext()) |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +def setup(app: Sphinx): |
| 31 | + """Setup the extension.""" |
| 32 | + app.add_html_math_renderer( |
| 33 | + "mathml", |
| 34 | + (visit_math, None), # type: ignore[arg-type] |
| 35 | + (visit_math_block, None), # type: ignore[arg-type] |
| 36 | + ) |
| 37 | + return { |
| 38 | + "parallel_read_safe": True, |
| 39 | + "parallel_write_safe": True, |
| 40 | + } |
0 commit comments