|
| 1 | +from sphinx.builders.html import StandaloneHTMLBuilder |
| 2 | +from sphinx.environment.adapters.indexentries import IndexEntries |
| 3 | + |
| 4 | +class DPYStandaloneHTMLBuilder(StandaloneHTMLBuilder): |
| 5 | + # This is mostly copy pasted from Sphinx. |
| 6 | + def write_genindex(self) -> None: |
| 7 | + # the total count of lines for each index letter, used to distribute |
| 8 | + # the entries into two columns |
| 9 | + genindex = IndexEntries(self.env).create_index(self, group_entries=False) |
| 10 | + indexcounts = [] |
| 11 | + for _k, entries in genindex: |
| 12 | + indexcounts.append(sum(1 + len(subitems) |
| 13 | + for _, (_, subitems, _) in entries)) |
| 14 | + |
| 15 | + genindexcontext = { |
| 16 | + 'genindexentries': genindex, |
| 17 | + 'genindexcounts': indexcounts, |
| 18 | + 'split_index': self.config.html_split_index, |
| 19 | + } |
| 20 | + |
| 21 | + if self.config.html_split_index: |
| 22 | + self.handle_page('genindex', genindexcontext, |
| 23 | + 'genindex-split.html') |
| 24 | + self.handle_page('genindex-all', genindexcontext, |
| 25 | + 'genindex.html') |
| 26 | + for (key, entries), count in zip(genindex, indexcounts): |
| 27 | + ctx = {'key': key, 'entries': entries, 'count': count, |
| 28 | + 'genindexentries': genindex} |
| 29 | + self.handle_page('genindex-' + key, ctx, |
| 30 | + 'genindex-single.html') |
| 31 | + else: |
| 32 | + self.handle_page('genindex', genindexcontext, 'genindex.html') |
| 33 | + |
| 34 | +def get_builder(app): |
| 35 | + """This is necessary because RTD injects their own for some reason.""" |
| 36 | + try: |
| 37 | + original = app.registry.builders['readthedocs'] |
| 38 | + except KeyError: |
| 39 | + return DPYStandaloneHTMLBuilder |
| 40 | + else: |
| 41 | + injected_mro = tuple(base if base is not StandaloneHTMLBuilder else DPYStandaloneHTMLBuilder |
| 42 | + for base in original.mro()[1:]) |
| 43 | + return type(original.__name__, injected_mro, {'name': 'readthedocs'}) |
| 44 | + |
| 45 | +def setup(app): |
| 46 | + app.add_builder(get_builder(app), override=True) |
0 commit comments