如何引用我自定义的Sphinx扩展生成的索引?

4 投票
1 回答
778 浏览
提问于 2025-04-30 20:46

我正在开发一个 Sphinx 扩展,里面包含一个自定义索引,像这样:

from sphinx.domains import Index

class MyIndex(Index):
    """
    Index subclass to provide the Python module index.
    """

    name = 'funcindex'
    localname = 'Function Index'
    shortname = 'functions'

    def generate(self, docnames=None):

        collapse = False        
        content = []
        for o in self.domain.data['objects']:
            dirtype, name = o
            docname, anchor = self.domain.data['objects'][o]
            entries = [name, 0, docname, anchor, '','','']
            letter = name[0]
            content.append((letter, [entries]))
        return (content, collapse)

def setup(app):
    app.add_index_to_domain('std', MyIndex)

我该如何引用这个索引呢?

Sphinx 默认生成的索引列表看起来是这样的:

Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

我该如何把我自己的 MyIndex 加入到这个列表中呢?

Sphinx 确实生成了一个文件 std-funcindex.html,看起来不错。但我缺少的是引用这个文件的方法。我尝试了下面所有的组合,但都没有成功:

:ref:`funcindex`
:ref:`std-funcindex`
:ref:`std_funcindex`
暂无标签

1 个回答

2

很遗憾,在当前版本的Sphinx(1.2.3)中,使用add_index_to_domain时不会自动添加标签。下面的代码可以手动添加标签(继续之前的问题中的例子):

def setup(app):
    app.add_index_to_domain('std', MyIndex)
    StandardDomain.initial_data['labels']['funcindex'] = ('std-funcindex', '', 'Function Index')
    StandardDomain.initial_data['anonlabels']['funcindex'] = ('std-funcindex', '')

这样就可以启用

:ref:`funcindex`

作为自定义索引的引用。

撰写回答