tardyp / sphinx-jinja

MIT License
28 stars 22 forks source link

Emit event on expansion #17

Open flying-sheep opened 3 years ago

flying-sheep commented 3 years ago

It could be similar to the source-read(app, docname, source) event:

jinja-expanded(app: Sphinx, docname: str, expanded: list[str], orig_range: slice)

This event can e.g. be useful for making this extension work with autosummary_generate:

  1. autosummary runs on the builder-inited event, i.e. before any directives are run
  2. autosummary parses all files recursively for code that looks like a autosummary directive (without expanding directives)
  3. the sphinx-jinja directive gets run and generated autosummary directives get expanded, but no stubs have been generated for them.

If we have this event, and a way to hook into sphinx.ext.autosummary.generate.find_autosummary_in_files, then we could integrate the two:

from sphinx.io import read_doc
from sphinx.util.logging import suppress_logging

def find_in_expanded(app: 'Sphinx', file_path: `pathlib.Path`, lines: list[str]):
    def replace_expanded(app: 'Sphinx', docname: str, expanded: list[str], orig_range: slice):
        lines[orig_range] = expanded
    listener = app.connect('jinja-expanded', replace_expanded)
    app.env.prepare_settings(str(file_path.relative_to(app.srcdir).with_suffix('')))
    with suppress_logging():
        # Not ideal. It would be best to read from `lines`
        # so multiple extensions can modify them subsequently
        read_doc(app, app.env, filename)
    app.disconnect(listener)

app.connect('autosummary-file-found', find_in_expanded)