1# 2# This is a Sphinx documentation tool extension which makes .only:: 3# directives be eagerly processed early in the parsing stage. This 4# makes sure that content in .only:: blocks gets actually excluded 5# as a typical user expects, instead of bits of information in 6# these blocks leaking to documentation in various ways (e.g., 7# indexes containing entries for functions which are actually in 8# .only:: blocks and thus excluded from documentation, etc.) 9# Note that with this extension, you may need to completely 10# rebuild a doctree when switching builders (i.e. completely 11# remove _build/doctree dir between generation of HTML vs PDF 12# documentation). 13# 14# This extension works by monkey-patching Sphinx core, so potentially 15# may not work with untested Sphinx versions. It tested to work with 16# 1.2.2 and 1.4.2 17# 18# Copyright (c) 2016 Paul Sokolovsky 19# Based on idea by Andrea Cassioli: 20# https://github.com/sphinx-doc/sphinx/issues/2150#issuecomment-171912290 21# Licensed under the terms of BSD license, see LICENSE file. 22# 23import sphinx 24from docutils.parsers.rst import directives 25 26 27class EagerOnly(sphinx.directives.other.Only): 28 29 def run(self, *args): 30 # Evaluate the condition eagerly, and if false return no nodes right away 31 env = self.state.document.settings.env 32 env.app.builder.tags.add('TRUE') 33 34 if not env.app.builder.tags.eval_condition(self.arguments[0]): 35 return [] 36 37 # Otherwise, do the usual processing 38 nodes = super(EagerOnly, self).run() 39 if len(nodes) == 1: 40 nodes[0]['expr'] = 'TRUE' 41 return nodes 42 43 44def setup(app): 45 directives.register_directive('only', EagerOnly) 46 47 # The tags.add call above is setting tags.tags['TRUE'] = True. 48 # The operation is idempotent and will have taken effect before 49 # the next eval_condition() which may rely on it so this is thread 50 # safe both for read and writes (all other operations are local to 51 # the local nodes variable). 52 return { 53 'parallel_read_safe': True, 54 'parallel_write_safe': True, 55 } 56