如何在Python项目中隐藏Sphinx搜索索引中的_static目录?

时间:2012-09-21 18:23:20

标签: python python-sphinx

在Sphinx项目中,如何防止项目的_static目录中的文档出现在项目搜索结果中?

1 个答案:

答案 0 :(得分:2)

没有配置选项可以从搜索索引中排除特定目录中的文件。

但是,您可以通过修改IndexBuilder.feed()方法来完成此操作。此方法的一个参数是doctree(Docutils document类的一个实例)。正在处理的.rst文档的路径是doctree.attributes['source']的值。

将以下猴子补丁添加到 conf.py

from sphinx.search import IndexBuilder, WordCollector

def feed(self, filename, title, doctree):
    """Feed a doctree to the index."""

    # Patch: if '_static' is in the path, don't use the file to 
    # populate the search index
    source = doctree.attributes["source"]
    if "_static" in source:
        return

    self._titles[filename] = title

    visitor = WordCollector(doctree, self.lang)
    doctree.walk(visitor)

    def add_term(word, stem=self.lang.stem):
        word = stem(word)
        if self.lang.word_filter(word):
            self._mapping.setdefault(word, set()).add(filename)

    for word in self.lang.split(title):
        add_term(word)

    for word in visitor.found_words:
        add_term(word)

IndexBuilder.feed = feed

使用Sphinx 1.1.3测试。