refinclude.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. """
  3. :copyright: (c) 2010-2012 Fabien Potencier
  4. :license: MIT, see LICENSE for more details.
  5. """
  6. from docutils.parsers.rst import Directive, directives
  7. from docutils import nodes
  8. class refinclude(nodes.General, nodes.Element):
  9. pass
  10. class RefInclude(Directive):
  11. has_content = False
  12. required_arguments = 1
  13. optional_arguments = 0
  14. final_argument_whitespace = False
  15. option_spec = {}
  16. def run(self):
  17. document = self.state.document
  18. if not document.settings.file_insertion_enabled:
  19. return [document.reporter.warning('File insertion disabled',
  20. line=self.lineno)]
  21. env = self.state.document.settings.env
  22. target = self.arguments[0]
  23. node = refinclude()
  24. node['target'] = target
  25. return [node]
  26. def process_refinclude_nodes(app, doctree, docname):
  27. env = app.env
  28. for node in doctree.traverse(refinclude):
  29. docname, labelid, sectname = env.domaindata['std']['labels'].get(node['target'],
  30. ('','',''))
  31. if not docname:
  32. return [document.reporter.error('Unknown target name: "%s"' % node['target'],
  33. line=self.lineno)]
  34. resultnode = None
  35. dt = env.get_doctree(docname)
  36. for n in dt.traverse(nodes.section):
  37. if labelid in n['ids']:
  38. node.replace_self([n])
  39. break
  40. def setup(app):
  41. app.add_node(refinclude)
  42. app.add_directive('include-ref', RefInclude)
  43. app.connect('doctree-resolved', process_refinclude_nodes)