0

In the Docutils document tree, a title node may occur inside a section, or inside the document itself.

For a particular Docutils NodeVisitor I am creating, I need to be able to distinguish whether the current title node is the document's title, or is instead within one of several sections in the document: if it's actually the title of the overall document, I just want to skip this title and move on.

I would have expected to be able to do this within Visitor.visit_title:

class DocumentTitleSkippingVisitor:

    # …

    def visit_title(self, node):
        document_node = section_node.parent
        if section_node is document_node:
            # This title is actually the document's top level title.
            raise self._docutils.nodes.SkipNode

That doesn't work, though: the visitor encounters the document's top level title inside another section node. Because of this, the above check (correctly) says the parent of the title is not the document node.

How can I tell, within the NodeVisitor, that the title is actually the special document title? Alternatively, how can I hook into Docutils such that the title is actually at the document level, to more easily distinguish it from a section title?

bignose
  • 30,281
  • 14
  • 77
  • 110

1 Answers1

0

You can add visit_section and depart_section:

class DocumentTitleSkippingVisitor:
    def __init__(self):
        self.in_section = False
    def visit_section(self, node):
        self.in_section = True
    def depart_section(self,node):
        self.in_section = False
    def visit_title(self, node):
        if self.in_section:
            pass # do something

For reStructuredText there is no way to specify a document title and subtitle explicitly. In this case:

  • You can first apply DocTitle
  • You should follow the algorithm used by DocTitle to find it.
napuzba
  • 6,033
  • 3
  • 21
  • 32
  • Have you confirmed this would work? My experience suggests it would fail in the same way: the visitor encounters the document-level title inside a `section`. – bignose Aug 07 '16 at 05:47