Python docutils.nodes() Examples

The following are 30 code examples of docutils.nodes(). 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 , or try the search function .
Example #1
Source File: extraction.py    From corobo with MIT License 6 votes vote down vote up
def handle_non_section_nodes(section_node, non_section_child_nodes, doc_name,
                             data):
    """
    All the nodes that are not section nodes are parsed here.
    """
    non_code_nodes = filter(
        lambda x: type(x) not in [docutils.nodes.literal_block],
        non_section_child_nodes
    )
    code_nodes = filter(lambda x: type(x) in [docutils.nodes.literal_block],
                        non_section_child_nodes)
    code = '\n'.join(map(lambda x: x.astext(), code_nodes))
    text = '\n'.join(map(lambda x: x.astext(), non_code_nodes))

    data[section_node.get('ids')[0]] = {
        "code": code,
        "text": (text + '\n' + doc_name[:-4] + '.html#' +
                 section_node.get('ids')[0]),
        "file": doc_name
    } 
Example #2
Source File: genelements.py    From rst2pdf with MIT License 6 votes vote down vote up
def gather_elements(self, client, node, style):
        odd = []
        even = []
        if node.children:
            if isinstance(node.children[0], docutils.nodes.paragraph):
                if node.children[0].get('classes'):
                    s = client.styles[node.children[0].get('classes')[0]]
                else:
                    s = style
                odd = [Paragraph(client.gather_pdftext(node.children[0]), s)]
            else:
                # A compound element
                odd = client.gather_elements(node.children[0])
        if len(node.children) > 1:
            if isinstance(node.children[1], docutils.nodes.paragraph):
                if node.children[1].get('classes'):
                    s = client.styles[node.children[1].get('classes')[0]]
                else:
                    s = style
                even = [Paragraph(client.gather_pdftext(node.children[1]), s)]
            else:
                even = client.gather_elements(node.children[1])

        return [OddEven(odd=odd, even=even)] 
Example #3
Source File: genelements.py    From rst2pdf with MIT License 6 votes vote down vote up
def gather_elements(self, client, node, style):
        # line nodes have no classes, they have to inherit from the outermost lineblock (sigh)
        # For more info see Issue 471 and its test case.

        parent = node
        while isinstance(
            parent.parent, (docutils.nodes.line, docutils.nodes.line_block)
        ):
            parent = parent.parent
        p_class = (parent.get('classes') or ['line'])[0]
        qstyle = copy(client.styles[p_class])
        # Indent .5em per indent unit
        i = node.__dict__.get('indent', 0)
        # qstyle = copy(client.styles['line'])
        qstyle.leftIndent += client.styles.adjustUnits("0.5em") * i
        text = client.gather_pdftext(node)
        if not text:  # empty line
            text = u"<nobr>\xa0</nobr>"
        return [Paragraph(text, style=qstyle)] 
Example #4
Source File: genelements.py    From rst2pdf with MIT License 6 votes vote down vote up
def gather_elements(self, client, node, style):
        if isinstance(node.parent, docutils.nodes.sidebar):
            elements = [
                Paragraph(client.gen_pdftext(node), client.styles['sidebar-subtitle'])
            ]
        elif isinstance(node.parent, docutils.nodes.document):
            # elements = [Paragraph(client.gen_pdftext(node),
            # client.styles['subtitle'])]
            # The visible output is now done by the cover template
            elements = []
            # FIXME: looks like subtitles don't have a rawsource like
            # titles do.
            # That means that literals and italics etc in subtitles won't
            # work.
            client.doc_subtitle = getattr(node, 'rawtext', node.astext()).strip()
        else:
            elements = node.elements  # FIXME Can we get here???
        return elements 
Example #5
Source File: dochelpers.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_section(self, node):
        """ Checks if the visited sub-command section nodes exists and it
            options are in sync.

            Uses :py:class:`OptionsCheckVisitor` for checking
            sub-commands options
        """
        # pylint: disable=no-self-use
        title = str(node[0][0])
        if title.upper() == SUBCOMMANDS_TITLE:
            return

        sub_cmd = self.command + ' ' + title

        try:
            args = self.sub_commands[title]
            options_visitor = OptionsCheckVisitor(sub_cmd, args, self.document)
            node.walkabout(options_visitor)
            options_visitor.check_undocumented_arguments(
                {'--help', '--quiet', '--verbose', '-h', '-q', '-v'})
            del self.sub_commands[title]
        except KeyError:
            raise sphinx.errors.SphinxError(
                'No such sub-command {!r}'.format(sub_cmd)) 
Example #6
Source File: frontend.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def validate_strip_class(setting, value, option_parser,
                         config_parser=None, config_section=None):
    # value is a comma separated string list:
    value = validate_comma_separated_list(setting, value, option_parser,
                                          config_parser, config_section)
    # validate list elements:
    for cls in value:
        normalized = docutils.nodes.make_id(cls)
        if cls != normalized:
            raise ValueError('Invalid class value %r (perhaps %r?)'
                             % (cls, normalized))
    return value 
Example #7
Source File: rst-link-check.py    From code-for-blog with The Unlicense 5 votes vote down vote up
def visit_reference(self, node):
        # Catch reference nodes for link-checking.
        check_link(node['refuri']) 
Example #8
Source File: rst-link-check.py    From code-for-blog with The Unlicense 5 votes vote down vote up
def default_visit(self, node):
        # Pass all other nodes through.
        pass 
Example #9
Source File: dochelpers.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, command, args, document):
        assert isinstance(args, set)
        docutils.nodes.SparseNodeVisitor.__init__(self, document)
        self.command = command
        self.args = args 
Example #10
Source File: dochelpers.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
def visit_desc(self, node):
        """ Skips all but 'option' elements """
        # pylint: disable=no-self-use
        if not node.get('desctype', None) == 'option':
            raise docutils.nodes.SkipChildren 
Example #11
Source File: dochelpers.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
def visit_desc_name(self, node):
        """ Checks if the option is defined `self.args` """
        if not isinstance(node[0], docutils.nodes.Text):
            raise sphinx.errors.SphinxError('first child should be Text')

        arg = str(node[0])
        try:
            self.args.remove(arg)
        except KeyError:
            raise sphinx.errors.SphinxError(
                'No such argument for {!r}: {!r}'.format(self.command, arg)) 
Example #12
Source File: dochelpers.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, command, sub_commands, document):
        docutils.nodes.SparseNodeVisitor.__init__(self, document)
        self.command = command
        self.sub_commands = sub_commands 
Example #13
Source File: frontend.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def validate_strip_class(setting, value, option_parser,
                         config_parser=None, config_section=None):
    # value is a comma separated string list:
    value = validate_comma_separated_list(setting, value, option_parser,
                                          config_parser, config_section)
    # validate list elements:
    for cls in value:
        normalized = docutils.nodes.make_id(cls)
        if cls != normalized:
            raise ValueError('invalid class value %r (perhaps %r?)'
                             % (cls, normalized))
    return value 
Example #14
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def __init__(self, document):
        docutils.nodes.SparseNodeVisitor.__init__(self, document)
        self.toc = None
        # For some reason, when called via sphinx,
        # .. contents:: ends up trying to call
        # visitor.document.reporter.debug
        # so we need a valid document here.
        self.document = docutils.utils.new_document('') 
Example #15
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        if isinstance(node.parent, docutils.nodes.authors):
            # Is only one of multiple authors. Return a paragraph
            node.elements = [Paragraph(client.gather_pdftext(node), style=style)]
            if client.doc_author:
                client.doc_author += (
                    client.author_separator(style=style) + node.astext().strip()
                )
            else:
                client.doc_author = node.astext().strip()
        else:
            # A single author: works like a field
            fb = client.gather_pdftext(node)

            t_style = TableStyle(client.styles['field-list'].commands)
            colWidths = [
                client.styles.adjustUnits(x)
                for x in client.styles['field-list'].colWidths
            ]

            node.elements = [
                Table(
                    [
                        [
                            Paragraph(
                                client.text_for_label("author", style) + ":",
                                style=client.styles['fieldname'],
                            ),
                            Paragraph(fb, style),
                        ]
                    ],
                    style=t_style,
                    colWidths=colWidths,
                )
            ]
            client.doc_author = node.astext().strip()
        return node.elements 
Example #16
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def gather_elements(self, client, node, style):
        # I need to catch the classifiers here
        tt = []
        dt = []
        ids = []
        for n in node.children:
            if isinstance(n, docutils.nodes.term):
                for i in n['ids']:  # Used by sphinx glossary lists
                    if i not in client.targets:
                        ids.append('<a name="%s"/>' % i)
                        client.targets.append(i)
                o, c = client.styleToTags("definition-list-term")
                tt.append(o + client.gather_pdftext(n) + c)
            elif isinstance(n, docutils.nodes.classifier):
                o, c = client.styleToTags("definition-list-classifier")
                tt.append(o + client.gather_pdftext(n) + c)
            else:
                dt.extend(client.gen_elements(n, style))

        # FIXME: make this configurable from the stylesheet
        t_style = TableStyle(client.styles['definition'].commands)
        cw = getattr(client.styles['definition'], 'colWidths', [])

        if client.splittables:
            node.elements = [
                Paragraph(
                    ''.join(ids) + ' : '.join(tt),
                    client.styles['definition-list-term'],
                ),
                SplitTable([['', dt]], colWidths=cw, style=t_style),
            ]
        else:
            node.elements = [
                Paragraph(
                    ''.join(ids) + ' : '.join(tt),
                    client.styles['definition-list-term'],
                ),
                DelayedTable([['', dt]], colWidths=[10, None], style=t_style),
            ]

        return node.elements 
Example #17
Source File: genelements.py    From rst2pdf with MIT License 5 votes vote down vote up
def getelements(self, client, node, style):
        parent = node.parent
        if not isinstance(parent, (docutils.nodes.header, docutils.nodes.footer)):
            return NodeHandler.getelements(self, client, node, style)
        return self.gather_elements(client, node, style) 
Example #18
Source File: createpdf.py    From rst2pdf with MIT License 5 votes vote down vote up
def styleToTags(self, style):
        '''Takes a style name, returns a pair of opening/closing tags for it, like
        "<font face=helvetica size=14 color=red>". Used for inline
        nodes (custom interpreted roles)'''

        try:
            s = self.styles[style]
            r1 = [
                '<font face="%s" color="#%s" ' % (s.fontName, s.textColor.hexval()[2:])
            ]
            bc = s.backColor
            if bc:
                r1.append('backColor="#%s"' % bc.hexval()[2:])
            if s.trueFontSize:
                r1.append('size="%d"' % s.fontSize)
            r1.append('>')
            r2 = ['</font>']

            if s.strike:
                r1.append('<strike>')
                r2.insert(0, '</strike>')
            if s.underline:
                r1.append('<u>')
                r2.insert(0, '</u>')

            return [''.join(r1), ''.join(r2)]
        except KeyError:
            log.warning('Unknown class %s', style)
            return None 
Example #19
Source File: dochelpers.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, app, command, document):
        docutils.nodes.SparseNodeVisitor.__init__(self, document)
        try:
            parser = qubes.tools.get_parser_for_command(command)
        except ImportError:
            msg = 'cannot import module for command'
            if log:
                log.warning(msg)
            else:
                # Handle legacy
                app.warn(msg)

            self.parser = None
            return
        except AttributeError:
            raise sphinx.errors.SphinxError('cannot find parser in module')

        self.command = command
        self.parser = parser
        self.options = set()
        self.sub_commands = {}
        self.app = app

        # pylint: disable=protected-access
        for action in parser._actions:
            if action.help == argparse.SUPPRESS:
                continue

            if issubclass(action.__class__,
                          qubes.tools.AliasedSubParsersAction):
                for cmd, cmd_parser in action._name_parser_map.items():
                    self.sub_commands[cmd] = set()
                    for sub_action in cmd_parser._actions:
                        if sub_action.help != argparse.SUPPRESS:
                            self.sub_commands[cmd].update(
                                sub_action.option_strings)
            else:
                self.options.update(action.option_strings) 
Example #20
Source File: frontend.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def validate_strip_class(setting, value, option_parser,
                         config_parser=None, config_section=None):
    # value is a comma separated string list:
    value = validate_comma_separated_list(setting, value, option_parser,
                                          config_parser, config_section)
    # validate list elements:
    for cls in value:
        normalized = docutils.nodes.make_id(cls)
        if cls != normalized:
            raise ValueError('invalid class value %r (perhaps %r?)'
                             % (cls, normalized))
    return value 
Example #21
Source File: frontend.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def validate_strip_class(setting, value, option_parser,
                         config_parser=None, config_section=None):
    # value is a comma separated string list:
    value = validate_comma_separated_list(setting, value, option_parser,
                                          config_parser, config_section)
    # validate list elements:
    for cls in value:
        normalized = docutils.nodes.make_id(cls)
        if cls != normalized:
            raise ValueError('Invalid class value %r (perhaps %r?)'
                             % (cls, normalized))
    return value 
Example #22
Source File: dochelpers.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def ticket(name, rawtext, text, lineno, inliner, options=None, content=None):
    """Link to qubes ticket

    :param str name: The role name used in the document
    :param str rawtext: The entire markup snippet, with role
    :param str text: The text marked with the role
    :param int lineno: The line number where rawtext appears in the input
    :param docutils.parsers.rst.states.Inliner inliner: The inliner instance \
        that called this function
    :param options: Directive options for customisation
    :param content: The directive content for customisation
    """  # pylint: disable=unused-argument

    if options is None:
        options = {}

    ticketno = text.lstrip('#')
    if not ticketno.isdigit():
        msg = inliner.reporter.error(
            'Invalid ticket identificator: {!r}'.format(text), line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    try:
        info = fetch_ticket_info(inliner.document.settings.env.app, ticketno)
    except urllib.error.HTTPError as e:
        msg = inliner.reporter.error(
            'Error while fetching ticket info: {!s}'.format(e), line=lineno)
        prb = inliner.problematic(rawtext, rawtext, msg)
        return [prb], [msg]

    docutils.parsers.rst.roles.set_classes(options)

    node = docutils.nodes.reference(
        rawtext,
        '#{} ({})'.format(info.number, info.summary),
        refuri=info.uri,
        **options)

    return [node], [] 
Example #23
Source File: dochelpers.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, command, args, document):
        assert isinstance(args, set)
        docutils.nodes.SparseNodeVisitor.__init__(self, document)
        self.command = command
        self.args = args 
Example #24
Source File: dochelpers.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def visit_desc(self, node):
        """ Skips all but 'option' elements """
        # pylint: disable=no-self-use
        if not node.get('desctype', None) == 'option':
            raise docutils.nodes.SkipChildren 
Example #25
Source File: dochelpers.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def visit_desc_name(self, node):
        """ Checks if the option is defined `self.args` """
        if not isinstance(node[0], docutils.nodes.Text):
            raise sphinx.errors.SphinxError('first child should be Text')

        arg = str(node[0])
        try:
            self.args.remove(arg)
        except KeyError:
            raise sphinx.errors.SphinxError(
                'No such argument for {!r}: {!r}'.format(self.command, arg)) 
Example #26
Source File: dochelpers.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, command, sub_commands, document):
        docutils.nodes.SparseNodeVisitor.__init__(self, document)
        self.command = command
        self.sub_commands = sub_commands 
Example #27
Source File: extraction.py    From corobo with MIT License 5 votes vote down vote up
def visit_section(self, node):
        non_section_childs = list(filter(
            lambda x: type(x) != docutils.nodes.section, node.children
        ))
        handle_non_section_nodes(node, non_section_childs, self.name, self.data) 
Example #28
Source File: ast.py    From jupyter-sphinx with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def apply(self):
        thebe_config = self.config.jupyter_sphinx_thebelab_config

        for cell_node in self.document.traverse(JupyterCellNode):
            (output_bundle_node,) = cell_node.traverse(CellOutputBundleNode)

            # Create doctree nodes for cell outputs.
            output_nodes = cell_output_to_nodes(
                output_bundle_node.outputs,
                self.config.jupyter_execute_data_priority,
                bool(cell_node.attributes["stderr"]),
                sphinx_abs_dir(self.env),
                thebe_config,
            )
            # Remove the outputbundlenode and we'll attach the outputs next
            attach_outputs(output_nodes, cell_node, thebe_config, cell_node.cm_language)

        # Image collect extra nodes from cell outputs that we need to process
        for node in self.document.traverse(image):
            # If the image node has `candidates` then it's already been processed
            # as in-line content, so skip it
            if "candidates" in node:
                continue
            # re-initialize an ImageCollector because the `app` imagecollector instance
            # is only available via event listeners.
            col = ImageCollector()
            col.process_doc(self.app, node) 
Example #29
Source File: frontend.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def validate_strip_class(setting, value, option_parser,
                         config_parser=None, config_section=None):
    # value is a comma separated string list:
    value = validate_comma_separated_list(setting, value, option_parser,
                                          config_parser, config_section)
    # validate list elements:
    for cls in value:
        normalized = docutils.nodes.make_id(cls)
        if cls != normalized:
            raise ValueError('Invalid class value %r (perhaps %r?)'
                             % (cls, normalized))
    return value 
Example #30
Source File: frontend.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate_strip_class(setting, value, option_parser,
                         config_parser=None, config_section=None):
    # value is a comma separated string list:
    value = validate_comma_separated_list(setting, value, option_parser,
                                          config_parser, config_section)
    # validate list elements:
    for cls in value:
        normalized = docutils.nodes.make_id(cls)
        if cls != normalized:
            raise ValueError('Invalid class value %r (perhaps %r?)'
                             % (cls, normalized))
    return value