|
| 1 | +from __future__ import annotations |
| 2 | +from typing import TYPE_CHECKING, override |
| 3 | + |
| 4 | +from sphinx.util.docutils import SphinxDirective, SphinxRole |
| 5 | +from sphinx.transforms import SphinxTransform |
| 6 | + |
| 7 | +from .utils import find_current_document, find_current_section |
| 8 | +from .utils.ctxproxy import proxy |
| 9 | +from .render import EXTRACTX_REGISTRY, ParsePhaseContextGenerator, FullPhaseContextGenerator, ParseCaller, Caller, pending_node |
| 10 | +from .template import Context |
| 11 | + |
| 12 | + |
| 13 | +class MarkupContextGenerator(ParsePhaseContextGenerator): |
| 14 | + @override |
| 15 | + def generate(self, caller: ParseCaller, n: pending_node) -> Context: |
| 16 | + isdir = isinstance(caller, SphinxDirective) |
| 17 | + return { |
| 18 | + 'type': 'directive' if isdir else 'role', |
| 19 | + 'name': caller.name, |
| 20 | + 'lineno': caller.lineno, |
| 21 | + 'rawtext': caller.block_text if isdir else caller.rawtext, |
| 22 | + } |
| 23 | + |
| 24 | +class DocContextGenerator(FullPhaseContextGenerator): |
| 25 | + @override |
| 26 | + def generate(self, caller: Caller, n: pending_node) -> Context: |
| 27 | + if isinstance(caller, SphinxDirective): |
| 28 | + return proxy(caller.state.document) |
| 29 | + elif isinstance(caller, SphinxRole): |
| 30 | + return proxy(caller.inliner.document) |
| 31 | + elif isinstance(caller, SphinxTransform): |
| 32 | + return proxy(caller.document) |
| 33 | + else: |
| 34 | + assert False |
| 35 | + |
| 36 | + |
| 37 | +class SectionContextGenerator(FullPhaseContextGenerator): |
| 38 | + @override |
| 39 | + def generate(self, caller: Caller, n: pending_node) -> Context: |
| 40 | + if n.parent: |
| 41 | + return proxy(find_current_section(n.parent)) |
| 42 | + elif isinstance(caller, SphinxDirective): |
| 43 | + return proxy(find_current_section(caller.state.parent)) |
| 44 | + elif isinstance(caller, SphinxRole): |
| 45 | + return proxy(caller.inliner.parent) |
| 46 | + else: |
| 47 | + assert False |
| 48 | + |
| 49 | + |
| 50 | +class SphinxEnvContextGenerator(FullPhaseContextGenerator): |
| 51 | + @override |
| 52 | + def generate(self, caller: Caller, n: pending_node) -> Context: |
| 53 | + return proxy(caller.env) |
| 54 | + |
| 55 | +class SphinxConfigContextGenerator(FullPhaseContextGenerator): |
| 56 | + @override |
| 57 | + def generate(self, caller: Caller, n: pending_node) -> Context: |
| 58 | + return proxy(caller.config) |
| 59 | + |
| 60 | +EXTRACTX_REGISTRY.add_parsing_phase_context('markup', MarkupContextGenerator()) |
| 61 | +EXTRACTX_REGISTRY.add_full_phase_context('doc', DocContextGenerator()) |
| 62 | +EXTRACTX_REGISTRY.add_full_phase_context('section',SectionContextGenerator()) |
| 63 | +EXTRACTX_REGISTRY.add_full_phase_context('env', SphinxEnvContextGenerator()) |
| 64 | +EXTRACTX_REGISTRY.add_full_phase_context('config', SphinxConfigContextGenerator()) |
0 commit comments