Python docutils.nodes.document() Examples

The following are 30 code examples of docutils.nodes.document(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module docutils.nodes , or try the search function .
Example #1
Source File: misc.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def apply(self):
        pending = self.startnode
        parent = pending.parent
        child = pending
        while parent:
            # Check for appropriate following siblings:
            for index in range(parent.index(child) + 1, len(parent)):
                element = parent[index]
                if (isinstance(element, nodes.Invisible) or
                    isinstance(element, nodes.system_message)):
                    continue
                element['classes'] += pending.details['class']
                pending.parent.remove(pending)
                return
            else:
                # At end of section or container; apply to sibling
                child = parent
                parent = parent.parent
        error = self.document.reporter.error(
            'No suitable element following "%s" directive'
            % pending.details['directive'],
            nodes.literal_block(pending.rawsource, pending.rawsource),
            line=pending.line)
        pending.replace_self(error) 
Example #2
Source File: manpage.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def visit_title(self, node):
        if isinstance(node.parent, nodes.topic):
            self.body.append(self.defs['topic-title'][0])
        elif isinstance(node.parent, nodes.sidebar):
            self.body.append(self.defs['sidebar-title'][0])
        elif isinstance(node.parent, nodes.admonition):
            self.body.append('.IP "')
        elif self.section_level == 0:
            self._docinfo['title'] = node.astext()
            # document title for .TH
            self._docinfo['title_upper'] = node.astext().upper()
            raise nodes.SkipNode
        elif self.section_level == 1:
            self.body.append('.SH %s\n' % self.deunicode(node.astext().upper()))
            raise nodes.SkipNode
        else:
            self.body.append('.SS ') 
Example #3
Source File: misc.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def apply(self):
        pending = self.startnode
        parent = pending.parent
        child = pending
        while parent:
            # Check for appropriate following siblings:
            for index in range(parent.index(child) + 1, len(parent)):
                element = parent[index]
                if (isinstance(element, nodes.Invisible) or
                    isinstance(element, nodes.system_message)):
                    continue
                element['classes'] += pending.details['class']
                pending.parent.remove(pending)
                return
            else:
                # At end of section or container; apply to sibling
                child = parent
                parent = parent.parent
        error = self.document.reporter.error(
            'No suitable element following "%s" directive'
            % pending.details['directive'],
            nodes.literal_block(pending.rawsource, pending.rawsource),
            line=pending.line)
        pending.replace_self(error) 
Example #4
Source File: manpage.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def astext(self):
        """Return the final formatted document as a string."""
        if not self.header_written:
            # ensure we get a ".TH" as viewers require it.
            self.append_header()
        # filter body
        for i in range(len(self.body)-1, 0, -1):
            # remove superfluous vertical gaps.
            if self.body[i] == '.sp\n':
                if self.body[i - 1][:4] in ('.BI ','.IP '):
                    self.body[i] = '.\n'
                elif (self.body[i - 1][:3] == '.B ' and
                    self.body[i - 2][:4] == '.TP\n'):
                    self.body[i] = '.\n'
                elif (self.body[i - 1] == '\n' and
                    not self.possibly_a_roff_command.match(self.body[i - 2]) and
                    (self.body[i - 3][:7] == '.TP\n.B '
                        or self.body[i - 3][:4] == '\n.B ')
                     ):
                    self.body[i] = '.\n'
        return ''.join(self.head + self.body + self.foot) 
Example #5
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def new_reporter(source_path, settings):
    """
    Return a new Reporter object.

    :Parameters:
        `source` : string
            The path to or description of the source text of the document.
        `settings` : optparse.Values object
            Runtime settings.
    """
    reporter = Reporter(
        source_path, settings.report_level, settings.halt_level,
        stream=settings.warning_stream, debug=settings.debug,
        encoding=settings.error_encoding,
        error_handler=settings.error_encoding_error_handler)
    return reporter 
Example #6
Source File: __init__.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def new_reporter(source_path, settings):
    """
    Return a new Reporter object.

    :Parameters:
        `source` : string
            The path to or description of the source text of the document.
        `settings` : optparse.Values object
            Runtime settings.
    """
    reporter = Reporter(
        source_path, settings.report_level, settings.halt_level,
        stream=settings.warning_stream, debug=settings.debug,
        encoding=settings.error_encoding,
        error_handler=settings.error_encoding_error_handler)
    return reporter 
Example #7
Source File: manpage.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def astext(self):
        """Return the final formatted document as a string."""
        if not self.header_written:
            # ensure we get a ".TH" as viewers require it.
            self.append_header()
        # filter body
        for i in range(len(self.body)-1, 0, -1):
            # remove superfluous vertical gaps.
            if self.body[i] == '.sp\n':
                if self.body[i - 1][:4] in ('.BI ','.IP '):
                    self.body[i] = '.\n'
                elif (self.body[i - 1][:3] == '.B ' and
                    self.body[i - 2][:4] == '.TP\n'):
                    self.body[i] = '.\n'
                elif (self.body[i - 1] == '\n' and
                    not self.possibly_a_roff_command.match(self.body[i - 2]) and
                    (self.body[i - 3][:7] == '.TP\n.B '
                        or self.body[i - 3][:4] == '\n.B ')
                     ):
                    self.body[i] = '.\n'
        return ''.join(self.head + self.body + self.foot) 
Example #8
Source File: manpage.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def visit_title(self, node):
        if isinstance(node.parent, nodes.topic):
            self.body.append(self.defs['topic-title'][0])
        elif isinstance(node.parent, nodes.sidebar):
            self.body.append(self.defs['sidebar-title'][0])
        elif isinstance(node.parent, nodes.admonition):
            self.body.append('.IP "')
        elif self.section_level == 0:
            self._docinfo['title'] = node.astext()
            # document title for .TH
            self._docinfo['title_upper'] = node.astext().upper()
            raise nodes.SkipNode
        elif self.section_level == 1:
            self.body.append('.SH %s\n' % self.deunicode(node.astext().upper()))
            raise nodes.SkipNode
        else:
            self.body.append('.SS ') 
Example #9
Source File: _html_base.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def stylesheet_call(self, path):
        """Return code to reference or embed stylesheet file `path`"""
        if self.settings.embed_stylesheet:
            try:
                content = io.FileInput(source_path=path,
                                       encoding='utf-8').read()
                self.settings.record_dependencies.add(path)
            except IOError as err:
                msg = "Cannot embed stylesheet '%s': %s." % (
                                path, SafeString(err.strerror))
                self.document.reporter.error(msg)
                return '<--- %s --->\n' % msg
            return self.embedded_stylesheet % content
        # else link to style file:
        if self.settings.stylesheet_path:
            # adapt path relative to output (cf. config.html#stylesheet-path)
            path = utils.relative_path(self.settings._destination, path)
        return self.stylesheet_link % self.encode(path) 
Example #10
Source File: _html_base.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def check_simple_list(self, node):
        """Check for a simple list that can be rendered compactly."""
        visitor = SimpleListChecker(self.document)
        try:
            node.walk(visitor)
        except nodes.NodeFound:
            return False
        else:
            return True

    # Compact lists
    # ------------
    # Include definition lists and field lists (in addition to ordered
    # and unordered lists) in the test if a list is "simple"  (cf. the
    # html4css1.HTMLTranslator docstring and the SimpleListChecker class at
    # the end of this file). 
Example #11
Source File: _html_base.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def depart_document(self, node):
        self.head_prefix.extend([self.doctype,
                                 self.head_prefix_template %
                                 {'lang': self.settings.language_code}])
        self.html_prolog.append(self.doctype)
        self.meta.insert(0, self.content_type % self.settings.output_encoding)
        self.head.insert(0, self.content_type % self.settings.output_encoding)
        if self.math_header:
            if self.math_output == 'mathjax':
                self.head.extend(self.math_header)
            else:
                self.stylesheet.extend(self.math_header)
        # skip content-type meta tag with interpolated charset value:
        self.html_head.extend(self.head[1:])
        self.body_prefix.append(self.starttag(node, 'div', CLASS='document'))
        self.body_suffix.insert(0, '</div>\n')
        self.fragment.extend(self.body) # self.fragment is the "naked" body
        self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
                              + self.docinfo + self.body
                              + self.body_suffix[:-1])
        assert not self.context, 'len(context) = %s' % len(self.context) 
Example #12
Source File: misc.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def apply(self):
        pending = self.startnode
        parent = pending.parent
        child = pending
        while parent:
            # Check for appropriate following siblings:
            for index in range(parent.index(child) + 1, len(parent)):
                element = parent[index]
                if (isinstance(element, nodes.Invisible) or
                    isinstance(element, nodes.system_message)):
                    continue
                element['classes'] += pending.details['class']
                pending.parent.remove(pending)
                return
            else:
                # At end of section or container; apply to sibling
                child = parent
                parent = parent.parent
        error = self.document.reporter.error(
            'No suitable element following "%s" directive'
            % pending.details['directive'],
            nodes.literal_block(pending.rawsource, pending.rawsource),
            line=pending.line)
        pending.replace_self(error) 
Example #13
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def translate(self):
        visitor = self.translator_class(self.document)
        self.document.walkabout(visitor)
        # copy parts
        for part in self.visitor_attributes:
            setattr(self, part, getattr(visitor, part))
        # get template string from file
        try:
            template_file = open(self.document.settings.template, 'rb')
        except IOError:
            template_file = open(os.path.join(self.default_template_path,
                                     self.document.settings.template), 'rb')
        template = string.Template(str(template_file.read(), 'utf-8'))
        template_file.close()
        # fill template
        self.assemble_parts() # create dictionary of parts
        self.output = template.substitute(self.parts) 
Example #14
Source File: check.py    From oss-ftp with MIT License 6 votes vote down vote up
def _check_rst_data(self, data):
        """Returns warnings when the provided data doesn't compile."""
        source_path = StringIO()
        parser = Parser()
        settings = frontend.OptionParser().get_default_values()
        settings.tab_width = 4
        settings.pep_references = None
        settings.rfc_references = None
        reporter = SilentReporter(source_path,
                          settings.report_level,
                          settings.halt_level,
                          stream=settings.warning_stream,
                          debug=settings.debug,
                          encoding=settings.error_encoding,
                          error_handler=settings.error_encoding_error_handler)

        document = nodes.document(settings, reporter, source=source_path)
        document.note_source(source_path, -1)
        try:
            parser.parse(data, document)
        except AttributeError:
            reporter.messages.append((-1, 'Could not finish the parsing.',
                                      '', {}))

        return reporter.messages 
Example #15
Source File: check.py    From Computable with MIT License 6 votes vote down vote up
def _check_rst_data(self, data):
        """Returns warnings when the provided data doesn't compile."""
        source_path = StringIO()
        parser = Parser()
        settings = frontend.OptionParser().get_default_values()
        settings.tab_width = 4
        settings.pep_references = None
        settings.rfc_references = None
        reporter = SilentReporter(source_path,
                          settings.report_level,
                          settings.halt_level,
                          stream=settings.warning_stream,
                          debug=settings.debug,
                          encoding=settings.error_encoding,
                          error_handler=settings.error_encoding_error_handler)

        document = nodes.document(settings, reporter, source=source_path)
        document.note_source(source_path, -1)
        try:
            parser.parse(data, document)
        except AttributeError:
            reporter.messages.append((-1, 'Could not finish the parsing.',
                                      '', {}))

        return reporter.messages 
Example #16
Source File: check.py    From BinderFilter with MIT License 6 votes vote down vote up
def _check_rst_data(self, data):
        """Returns warnings when the provided data doesn't compile."""
        source_path = StringIO()
        parser = Parser()
        settings = frontend.OptionParser().get_default_values()
        settings.tab_width = 4
        settings.pep_references = None
        settings.rfc_references = None
        reporter = SilentReporter(source_path,
                          settings.report_level,
                          settings.halt_level,
                          stream=settings.warning_stream,
                          debug=settings.debug,
                          encoding=settings.error_encoding,
                          error_handler=settings.error_encoding_error_handler)

        document = nodes.document(settings, reporter, source=source_path)
        document.note_source(source_path, -1)
        try:
            parser.parse(data, document)
        except AttributeError:
            reporter.messages.append((-1, 'Could not finish the parsing.',
                                      '', {}))

        return reporter.messages 
Example #17
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def new_reporter(source_path, settings):
    """
    Return a new Reporter object.

    :Parameters:
        `source` : string
            The path to or description of the source text of the document.
        `settings` : optparse.Values object
            Runtime settings.
    """
    reporter = Reporter(
        source_path, settings.report_level, settings.halt_level,
        stream=settings.warning_stream, debug=settings.debug,
        encoding=settings.error_encoding,
        error_handler=settings.error_encoding_error_handler)
    return reporter 
Example #18
Source File: __init__.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def depart_literal_block(self, node):
        self.insert_non_breaking_blanks = False
        self.insert_newline = False
        self.literal = False
        self.verbatim = False
        self.alltt = False
        self.out.append(self.context.pop())
        self.out.append(self.context.pop())

    ## def visit_meta(self, node):
    ##     self.out.append('[visit_meta]\n')
        # TODO: set keywords for pdf?
        # But:
        #  The reStructuredText "meta" directive creates a "pending" node,
        #  which contains knowledge that the embedded "meta" node can only
        #  be handled by HTML-compatible writers. The "pending" node is
        #  resolved by the docutils.transforms.components.Filter transform,
        #  which checks that the calling writer supports HTML; if it doesn't,
        #  the "pending" node (and enclosed "meta" node) is removed from the
        #  document.
        #  --- docutils/docs/peps/pep-0258.html#transformer

    ## def depart_meta(self, node):
    ##     self.out.append('[depart_meta]\n') 
Example #19
Source File: check.py    From meddle with MIT License 6 votes vote down vote up
def _check_rst_data(self, data):
        """Returns warnings when the provided data doesn't compile."""
        source_path = StringIO()
        parser = Parser()
        settings = frontend.OptionParser().get_default_values()
        settings.tab_width = 4
        settings.pep_references = None
        settings.rfc_references = None
        reporter = SilentReporter(source_path,
                          settings.report_level,
                          settings.halt_level,
                          stream=settings.warning_stream,
                          debug=settings.debug,
                          encoding=settings.error_encoding,
                          error_handler=settings.error_encoding_error_handler)

        document = nodes.document(settings, reporter, source=source_path)
        document.note_source(source_path, -1)
        try:
            parser.parse(data, document)
        except AttributeError:
            reporter.messages.append((-1, 'Could not finish the parsing.',
                                      '', {}))

        return reporter.messages 
Example #20
Source File: manpage.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def visit_substitution_reference(self, node):
        self.document.reporter.warning('"substitution_reference" not supported',
                base_node=node) 
Example #21
Source File: parts.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def apply(self):
        try: # let the writer (or output software) build the contents list?
            toc_by_writer = self.document.settings.use_latex_toc
        except AttributeError:
            toc_by_writer = False
        details = self.startnode.details
        if 'local' in details:
            startnode = self.startnode.parent.parent
            while not (isinstance(startnode, nodes.section)
                       or isinstance(startnode, nodes.document)):
                # find the ToC root: a direct ancestor of startnode
                startnode = startnode.parent
        else:
            startnode = self.document
        self.toc_id = self.startnode.parent['ids'][0]
        if 'backlinks' in details:
            self.backlinks = details['backlinks']
        else:
            self.backlinks = self.document.settings.toc_backlinks
        if toc_by_writer:
            # move customization settings to the parent node
            self.startnode.parent.attributes.update(details)
            self.startnode.parent.remove(self.startnode)
        else:
            contents = self.build_contents(startnode)
            if len(contents):
                self.startnode.replace_self(contents)
            else:
                self.startnode.parent.parent.remove(self.startnode.parent) 
Example #22
Source File: misc.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def apply(self):
        for node in self.document.traverse(nodes.transition):
            self.visit_transition(node) 
Example #23
Source File: _html_base.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def apply_template(self):
        template_file = open(self.document.settings.template, 'rb')
        template = str(template_file.read(), 'utf-8')
        template_file.close()
        subs = self.interpolation_dict()
        return template % subs 
Example #24
Source File: _html_base.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def interpolation_dict(self):
        subs = {}
        settings = self.document.settings
        for attr in self.visitor_attributes:
            subs[attr] = ''.join(getattr(self, attr)).rstrip('\n')
        subs['encoding'] = settings.output_encoding
        subs['version'] = docutils.__version__
        return subs 
Example #25
Source File: parts.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def build_contents(self, node, level=0):
        level += 1
        sections = [sect for sect in node if isinstance(sect, nodes.section)]
        entries = []
        autonum = 0
        depth = self.startnode.details.get('depth', sys.maxint)
        for section in sections:
            title = section[0]
            auto = title.get('auto')    # May be set by SectNum.
            entrytext = self.copy_and_filter(title)
            reference = nodes.reference('', '', refid=section['ids'][0],
                                        *entrytext)
            ref_id = self.document.set_id(reference)
            entry = nodes.paragraph('', '', reference)
            item = nodes.list_item('', entry)
            if ( self.backlinks in ('entry', 'top')
                 and title.next_node(nodes.reference) is None):
                if self.backlinks == 'entry':
                    title['refid'] = ref_id
                elif self.backlinks == 'top':
                    title['refid'] = self.toc_id
            if level < depth:
                subsects = self.build_contents(section, level)
                item += subsects
            entries.append(item)
        if entries:
            contents = nodes.bullet_list('', *entries)
            if auto:
                contents['classes'].append('auto-toc')
            return contents
        else:
            return [] 
Example #26
Source File: __init__.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def new_document(source_path, settings=None):
    """
    Return a new empty document object.

    :Parameters:
        `source_path` : string
            The path to or description of the source text of the document.
        `settings` : optparse.Values object
            Runtime settings.  If none are provided, a default core set will
            be used.  If you will use the document object with any Docutils
            components, you must provide their default settings as well.  For
            example, if parsing, at least provide the parser settings,
            obtainable as follows::

                settings = docutils.frontend.OptionParser(
                    components=(docutils.parsers.rst.Parser,)
                    ).get_default_values()
    """
    from docutils import frontend
    if settings is None:
        settings = frontend.OptionParser().get_default_values()
    source_path = decode_path(source_path)
    reporter = new_reporter(source_path, settings)
    document = nodes.document(settings, reporter, source=source_path)
    document.note_source(source_path, -1)
    return document 
Example #27
Source File: manpage.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def visit_target(self, node):
        # targets are in-document hyper targets, without any use for man-pages.
        raise nodes.SkipNode 
Example #28
Source File: manpage.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def depart_subtitle(self, node):
        # document subtitle calls SkipNode
        self.body.append(self.defs['strong'][1]+'\n.PP\n') 
Example #29
Source File: manpage.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def visit_subtitle(self, node):
        if isinstance(node.parent, nodes.sidebar):
            self.body.append(self.defs['strong'][0])
        elif isinstance(node.parent, nodes.document):
            self.visit_docinfo_item(node, 'subtitle')
        elif isinstance(node.parent, nodes.section):
            self.body.append(self.defs['strong'][0]) 
Example #30
Source File: _html_base.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def translate(self):
        self.visitor = visitor = self.translator_class(self.document)
        self.document.walkabout(visitor)
        for attr in self.visitor_attributes:
            setattr(self, attr, getattr(visitor, attr))
        self.output = self.apply_template()