Python docutils.parsers.rst.Directive() Examples

The following are 26 code examples of docutils.parsers.rst.Directive(). 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.parsers.rst , or try the search function .
Example #1
Source File: directive.py    From datatemplates with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def unknown_option(argument):
    """
    Check for a valid flag option (no argument) and return ``True``,
    else return argument stripped.
    (Directive option conversion function.)

    For unknown options we cannot know if they should be
    passed to the loader as flags or strings.
    We could pass ``None`` if the option string contains nothing
    except whitespace but this would not be intuitive for
    keyword argument flags as ``bool(None) is False``.
    """
    if argument:
        stripped = argument.strip()
        if stripped:
            return stripped
    return True 
Example #2
Source File: misc.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #3
Source File: states.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish 
Example #4
Source File: misc.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #5
Source File: directive.py    From datatemplates with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def flag_true(argument):
    """
    Check for a valid flag option (no argument) and return ``True``.
    (Directive option conversion function.)
    Raise ``ValueError`` if an argument is found.
    """
    if argument and argument.strip():
        raise ValueError('no argument is allowed; "%s" supplied' % argument)
    else:
        return True 
Example #6
Source File: states.py    From aws-extender with MIT License 5 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish 
Example #7
Source File: misc.py    From aws-extender with MIT License 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #8
Source File: misc.py    From blackmamba with MIT License 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #9
Source File: misc.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #10
Source File: symbolator_sphinx.py    From symbolator with MIT License 5 votes vote down vote up
def figure_wrapper(directive, node, caption):
    # type: (Directive, nodes.Node, unicode) -> nodes.figure
    figure_node = nodes.figure('', node)
    if 'align' in node:
        figure_node['align'] = node.attributes.pop('align')

    parsed = nodes.Element()
    directive.state.nested_parse(ViewList([caption], source=''),
                                 directive.content_offset, parsed)
    caption_node = nodes.caption(parsed[0].rawsource, '',
                                 *parsed[0].children)
    caption_node.source = parsed[0].source
    caption_node.line = parsed[0].line
    figure_node += caption_node
    return figure_node 
Example #11
Source File: states.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish 
Example #12
Source File: misc.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #13
Source File: misc.py    From bash-lambda-layer with MIT License 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #14
Source File: custom_directives.py    From pyimgui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def flag(argument):
    """Reimplement directives.flag to return True instead of None
    Check for a valid flag option (no argument) and return ``None``.
    (Directive option conversion function.)

    Raise ``ValueError`` if an argument is found.
    """
    if argument and argument.strip():
        raise ValueError('no argument is allowed; "%s" supplied' % argument)
    else:
        return True 
Example #15
Source File: misc.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #16
Source File: states.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError, detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish 
Example #17
Source File: misc.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #18
Source File: misc.py    From faces with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        if self.content:
            text = '\n'.join(self.content)
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content:' % (self.name, self.arguments, self.options),
                nodes.literal_block(text, text), line=self.lineno)
        else:
            info = self.state_machine.reporter.info(
                'Directive processed. Type="%s", arguments=%r, options=%r, '
                'content: None' % (self.name, self.arguments, self.options),
                line=self.lineno)
        return [info]

# Old-style, functional definition:
#
# def directive_test_function(name, arguments, options, content, lineno,
#                             content_offset, block_text, state, state_machine):
#     """This directive is useful only for testing purposes."""
#     if content:
#         text = '\n'.join(content)
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content:' % (name, arguments, options),
#             nodes.literal_block(text, text), line=lineno)
#     else:
#         info = state_machine.reporter.info(
#             'Directive processed. Type="%s", arguments=%r, options=%r, '
#             'content: None' % (name, arguments, options), line=lineno)
#     return [info]
#
# directive_test_function.arguments = (0, 1, 1)
# directive_test_function.options = {'option': directives.unchanged_required}
# directive_test_function.content = 1 
Example #19
Source File: states.py    From bash-lambda-layer with MIT License 4 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank()) 
Example #20
Source File: states.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 4 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank()) 
Example #21
Source File: states.py    From AWS-Transit-Gateway-Demo-MultiAccount with MIT License 4 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank()) 
Example #22
Source File: _simple.py    From flocker with Apache License 2.0 4 votes vote down vote up
def create_simple_html_directive(name, pre, post,
                                 has_content=True, match_titles=False):
    """
    Creates a node class, directive class and setup method for the given
    parameters.

    :param name: String representing the RST directive to add.
    :param pre: String representing HTML to come before directive content.
    :param post: String representing HTML to come after directive content.
    :param has_content: Boolean indicating whether the directive accepts
        a content block.
    :param match_titles: Boolean indicating whether headings and titles may
        be included in the block contained within this directive.
    """
    node_class = type(
        name.replace('-', '_'), (nodes.General, nodes.Element), {}
    )

    def visit_html(self, node):
        self.body.append(pre)

    def depart_html(self, node):
        self.body.append(post)

    def run_directive(self):
        node = node_class()
        if has_content:
            text = self.content
            self.state.nested_parse(text, self.content_offset,
                                    node, match_titles=match_titles)
        # FIXME: This should add more stuff.
        self.state.document.settings.record_dependencies.add(__file__)
        return [node]

    directive_class = type(name.title() + 'Directive', (Directive,), {
        "has_content": has_content,
        "run": run_directive,
    })

    def setup(app):
        app.add_node(node_class,
                     html=(visit_html, depart_html))
        app.add_directive(name, directive_class)

    return node_class, directive_class, setup 
Example #23
Source File: states.py    From blackmamba with MIT License 4 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank()) 
Example #24
Source File: states.py    From deepWordBug with Apache License 2.0 4 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank()) 
Example #25
Source File: m2r.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(self):
        """Most of this method is from ``docutils.parser.rst.Directive``.

        docutils version: 0.12
        """
        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)
        source_dir = os.path.dirname(os.path.abspath(source))
        path = rst.directives.path(self.arguments[0])
        path = os.path.normpath(os.path.join(source_dir, path))
        path = utils.relative_path(None, path)
        path = nodes.reprunicode(path)

        # get options (currently not use directive-specific options)
        encoding = self.options.get(
            'encoding', self.state.document.settings.input_encoding)
        e_handler = self.state.document.settings.input_encoding_error_handler
        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)

        # open the inclding file
        try:
            self.state.document.settings.record_dependencies.add(path)
            include_file = io.FileInput(source_path=path,
                                        encoding=encoding,
                                        error_handler=e_handler)
        except UnicodeEncodeError as error:
            raise self.severe('Problems with "%s" directive path:\n'
                              'Cannot encode input file path "%s" '
                              '(wrong locale?).' %
                              (self.name, SafeString(path)))
        except IOError as error:
            raise self.severe('Problems with "%s" directive path:\n%s.' %
                              (self.name, ErrorString(error)))

        # read from the file
        try:
            rawtext = include_file.read()
        except UnicodeError as error:
            raise self.severe('Problem with "%s" directive:\n%s' %
                              (self.name, ErrorString(error)))

        config = self.state.document.settings.env.config
        converter = M2R(
            no_underscore_emphasis=config.no_underscore_emphasis,
            parse_relative_links=config.m2r_parse_relative_links
        )
        include_lines = statemachine.string2lines(converter(rawtext),
                                                  tab_width,
                                                  convert_whitespace=True)
        self.state_machine.insert_input(include_lines, path)
        return [] 
Example #26
Source File: states.py    From faces with GNU General Public License v2.0 4 votes vote down vote up
def run_directive(self, directive, match, type_name, option_presets):
        """
        Parse a directive then run its directive function.

        Parameters:

        - `directive`: The class implementing the directive.  Must be
          a subclass of `rst.Directive`.

        - `match`: A regular expression match object which matched the first
          line of the directive.

        - `type_name`: The directive name, as used in the source text.

        - `option_presets`: A dictionary of preset options, defaults for the
          directive options.  Currently, only an "alt" option is passed by
          substitution definitions (value: the substitution name), which may
          be used by an embedded image directive.

        Returns a 2-tuple: list of nodes, and a "blank finish" boolean.
        """
        if isinstance(directive, (FunctionType, MethodType)):
            from docutils.parsers.rst import convert_directive_function
            directive = convert_directive_function(directive)
        lineno = self.state_machine.abs_line_number()
        initial_line_offset = self.state_machine.line_offset
        indented, indent, line_offset, blank_finish \
                  = self.state_machine.get_first_known_indented(match.end(),
                                                                strip_top=0)
        block_text = '\n'.join(self.state_machine.input_lines[
            initial_line_offset : self.state_machine.line_offset + 1])
        try:
            arguments, options, content, content_offset = (
                self.parse_directive_block(indented, line_offset,
                                           directive, option_presets))
        except MarkupError as detail:
            error = self.reporter.error(
                'Error in "%s" directive:\n%s.' % (type_name,
                                                   ' '.join(detail.args)),
                nodes.literal_block(block_text, block_text), line=lineno)
            return [error], blank_finish
        directive_instance = directive(
            type_name, arguments, options, content, lineno,
            content_offset, block_text, self, self.state_machine)
        try:
            result = directive_instance.run()
        except docutils.parsers.rst.DirectiveError as error:
            msg_node = self.reporter.system_message(error.level, error.msg,
                                                    line=lineno)
            msg_node += nodes.literal_block(block_text, block_text)
            result = [msg_node]
        assert isinstance(result, list), \
               'Directive "%s" must return a list of nodes.' % type_name
        for i in range(len(result)):
            assert isinstance(result[i], nodes.Node), \
                   ('Directive "%s" returned non-Node object (index %s): %r'
                    % (type_name, i, result[i]))
        return (result,
                blank_finish or self.state_machine.is_next_line_blank())