eager_only.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. #
  23. import sphinx
  24. from docutils.parsers.rst import directives
  25. class EagerOnly(sphinx.directives.other.Only):
  26. def run(self, *args):
  27. # Evaluate the condition eagerly, and if false return no nodes right away
  28. env = self.state.document.settings.env
  29. env.app.builder.tags.add('TRUE')
  30. #print(repr(self.arguments[0]))
  31. if not env.app.builder.tags.eval_condition(self.arguments[0]):
  32. return []
  33. # Otherwise, do the usual processing
  34. nodes = super(EagerOnly, self).run()
  35. if len(nodes) == 1:
  36. nodes[0]['expr'] = 'TRUE'
  37. return nodes
  38. def setup(app):
  39. directives.register_directive('only', EagerOnly)