|
| 1 | +"""Sphinx extensions for performant PEP processing""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from sphinx.environment import default_settings |
| 8 | +from docutils.writers.html5_polyglot import HTMLTranslator |
| 9 | + |
| 10 | +from pep_sphinx_extensions.pep_processor.html import pep_html_translator |
| 11 | +from pep_sphinx_extensions.pep_processor.parsing import pep_parser |
| 12 | +from pep_sphinx_extensions.pep_processor.parsing import pep_role |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from sphinx.application import Sphinx |
| 16 | + |
| 17 | +# Monkeypatch sphinx.environment.default_settings as Sphinx doesn't allow custom settings or Readers |
| 18 | +default_settings |= { |
| 19 | + "pep_references": True, |
| 20 | + "rfc_references": True, |
| 21 | + "pep_base_url": "", |
| 22 | + "pep_file_url_template": "pep-%04d.html", |
| 23 | + "_disable_config": True, # disable using docutils.conf whilst running both PEP generators |
| 24 | +} |
| 25 | + |
| 26 | + |
| 27 | +def _depart_maths(): |
| 28 | + pass # No-op callable for the type checker |
| 29 | + |
| 30 | + |
| 31 | +def setup(app: Sphinx) -> dict[str, bool]: |
| 32 | + """Initialize Sphinx extension.""" |
| 33 | + |
| 34 | + # Register plugin logic |
| 35 | + app.add_source_parser(pep_parser.PEPParser) # Add PEP transforms |
| 36 | + app.add_role("pep", pep_role.PEPRole(), override=True) # Transform PEP references to links |
| 37 | + app.set_translator("html", pep_html_translator.PEPTranslator) # Docutils Node Visitor overrides |
| 38 | + |
| 39 | + # Mathematics rendering |
| 40 | + inline_maths = HTMLTranslator.visit_math, _depart_maths |
| 41 | + block_maths = HTMLTranslator.visit_math_block, _depart_maths |
| 42 | + app.add_html_math_renderer("maths_to_html", inline_maths, block_maths) # Render maths to HTML |
| 43 | + |
| 44 | + # Parallel safety: https://www.sphinx-doc.org/en/master/extdev/index.html#extension-metadata |
| 45 | + return {"parallel_read_safe": True, "parallel_write_safe": True} |
0 commit comments