Python docutils.statemachine.string2lines() Examples

The following are 20 code examples of docutils.statemachine.string2lines(). 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.statemachine , or try the search function .
Example #1
Source File: ext.py    From sphinx-click with MIT License 6 votes vote down vote up
def _format_description(ctx):
    """Format the description for a given `click.Command`.

    We parse this as reStructuredText, allowing users to embed rich
    information in their help messages if they so choose.
    """
    help_string = ctx.command.help or ctx.command.short_help
    if not help_string:
        return

    bar_enabled = False
    for line in statemachine.string2lines(help_string,
                                          tab_width=4,
                                          convert_whitespace=True):
        if line == '\b':
            bar_enabled = True
            continue
        if line == '':
            bar_enabled = False
        line = '| ' + line if bar_enabled else line
        yield line
    yield '' 
Example #2
Source File: conf.py    From saxo_openapi with MIT License 6 votes vote down vote up
def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            return [nodes.error(None, nodes.paragraph(text = "Unable to execute python code at %s:%d:" % (basename(source), self.lineno)), nodes.paragraph(text = str(sys.exc_info()[1])))]
        finally:
            sys.stdout = oldStdout 
Example #3
Source File: make_cli_rst.py    From cooler with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _format_description(ctx):
    """Format the description for a given `click.Command`.
    We parse this as reStructuredText, allowing users to embed rich
    information in their help messages if they so choose.
    """
    help_string = ctx.command.help or ctx.command.short_help
    if not help_string:
        return

    bar_enabled = False
    for line in statemachine.string2lines(
            help_string, tab_width=4, convert_whitespace=True):
        if line == '\b':
            bar_enabled = True
            continue
        if line == '':
            bar_enabled = False
        line = '| ' + line if bar_enabled else line
        yield line
    yield '' 
Example #4
Source File: ext.py    From sphinx-click with MIT License 6 votes vote down vote up
def _format_subcommand(command):
    """Format a sub-command of a `click.Command` or `click.Group`."""
    yield '.. object:: {}'.format(command.name)

    # click 7.0 stopped setting short_help by default
    if CLICK_VERSION < (7, 0):
        short_help = command.short_help
    else:
        short_help = command.get_short_help_str()

    if short_help:
        yield ''
        for line in statemachine.string2lines(short_help,
                                              tab_width=4,
                                              convert_whitespace=True):
            yield _indent(line) 
Example #5
Source File: conf.py    From veros with MIT License 6 votes vote down vote up
def run(self):
        old_stdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            warn_text = "Unable to execute python code at %s:%d" % (basename(source), self.lineno)
            warning = self.state_machine.reporter.warning(warn_text)
            return [warning, nodes.error(None, nodes.paragraph(text=warn_text), nodes.paragraph(text=str(sys.exc_info()[1])))]
        finally:
            sys.stdout = old_stdout 
Example #6
Source File: sphinxext.py    From cliff with Apache License 2.0 6 votes vote down vote up
def _format_optional_action(action):
    """Format an optional action."""
    if action.help == argparse.SUPPRESS:
        return

    if action.nargs == 0:
        yield '.. option:: {}'.format(', '.join(action.option_strings))
    else:
        # TODO(stephenfin): At some point, we may wish to provide more
        # information about the options themselves, for example, if nargs is
        # specified
        option_strings = [' '.join(
            [x, action.metavar or '<{}>'.format(action.dest.upper())])
            for x in action.option_strings]
        yield '.. option:: {}'.format(', '.join(option_strings))

    if action.help:
        yield ''
        for line in statemachine.string2lines(
                action.help, tab_width=4, convert_whitespace=True):
            yield _indent(line) 
Example #7
Source File: conf.py    From oanda-api-v20 with MIT License 6 votes vote down vote up
def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            return [nodes.error(None, nodes.paragraph(text = "Unable to execute python code at %s:%d:" % (basename(source), self.lineno)), nodes.paragraph(text = str(sys.exc_info()[1])))]
        finally:
            sys.stdout = oldStdout 
Example #8
Source File: exec_directive.py    From ms_deisotope with Apache License 2.0 6 votes vote down vote up
def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            return [nodes.error(
                None,
                nodes.paragraph(text="Unable to execute python code at %s:%d:" % (
                    basename(source), self.lineno)),
                nodes.paragraph(text=str(sys.exc_info()[1])))]
        finally:
            sys.stdout = oldStdout 
Example #9
Source File: conf.py    From viznet with MIT License 6 votes vote down vote up
def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get(
            'tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(
                text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            return [nodes.error(None, nodes.paragraph(text="Unable to execute python code at %s:%d:" % (basename(source), self.lineno)), nodes.paragraph(text=str(sys.exc_info()[1])))]
        finally:
            sys.stdout = oldStdout 
Example #10
Source File: sphinxext.py    From cliff with Apache License 2.0 5 votes vote down vote up
def _format_epilog(parser):
    """Get parser epilog.

    We parse this as reStructuredText, allowing users to embed rich
    information in their help messages if they so choose.
    """
    for line in statemachine.string2lines(
            parser.epilog, tab_width=4, convert_whitespace=True):
        yield line 
Example #11
Source File: sphinxext.py    From cliff with Apache License 2.0 5 votes vote down vote up
def _format_positional_action(action):
    """Format a positional action."""
    if action.help == argparse.SUPPRESS:
        return

    # NOTE(stephenfin): We strip all types of brackets from 'metavar' because
    # the 'option' directive dictates that only option argument names should be
    # surrounded by angle brackets
    yield '.. option:: {}'.format(
        (action.metavar or action.dest).strip('<>[]() '))
    if action.help:
        yield ''
        for line in statemachine.string2lines(
                action.help, tab_width=4, convert_whitespace=True):
            yield _indent(line) 
Example #12
Source File: sphinxext.py    From cliff with Apache License 2.0 5 votes vote down vote up
def _format_description(parser):
    """Get parser description.

    We parse this as reStructuredText, allowing users to embed rich
    information in their help messages if they so choose.
    """
    for line in statemachine.string2lines(
            parser.description, tab_width=4, convert_whitespace=True):
        yield line 
Example #13
Source File: ext.py    From sphinx-click with MIT License 5 votes vote down vote up
def _format_option(opt):
    """Format the output for a `click.Option`."""
    opt = _get_help_record(opt)

    yield '.. option:: {}'.format(opt[0])
    if opt[1]:
        yield ''
        for line in statemachine.string2lines(opt[1],
                                              tab_width=4,
                                              convert_whitespace=True):
            yield _indent(line) 
Example #14
Source File: conf.py    From pyuvdata with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get(
            "tab-width", self.state.document.settings.tab_width
        )
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1
        )

        try:
            exec("\n".join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            return [
                nodes.error(
                    None,
                    nodes.paragraph(
                        text="Unable to execute python "
                        "code at {file}:{line}".format(
                            file=os.path.basename(source), line=self.lineno
                        )
                    ),
                    nodes.paragraph(text=str(sys.exc_info()[1])),
                )
            ]
        finally:
            sys.stdout = oldStdout 
Example #15
Source File: make_cli_rst.py    From cooler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_option(opt):
    """Format the output for a `click.Option`."""
    opt = _get_help_record(opt)

    yield '.. option:: {}'.format(opt[0])
    if opt[1]:
        yield ''
        for line in statemachine.string2lines(
                opt[1], tab_width=4, convert_whitespace=True):
            yield _indent(line) 
Example #16
Source File: make_cli_rst.py    From cooler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _format_subcommand(command):
    """Format a sub-command of a `click.Command` or `click.Group`."""
    yield '.. object:: {}'.format(command.name)

    if command.short_help:
        yield ''
        for line in statemachine.string2lines(
                command.short_help, tab_width=4, convert_whitespace=True):
            yield _indent(line) 
Example #17
Source File: conf.py    From terracotta with MIT License 5 votes vote down vote up
def run(self):
        old_stdout, sys.stdout = sys.stdout, StringIO()

        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        try:
            exec('\n'.join(self.content))
            text = sys.stdout.getvalue()
            lines = statemachine.string2lines(text, tab_width, convert_whitespace=True)
            self.state_machine.insert_input(lines, source)
            return []
        except Exception:
            warn_text = f'Unable to execute python code at {basename(source)}:{self.lineno}'
            warning = self.state_machine.reporter.warning(warn_text)
            return [
                warning,
                nodes.error(
                    None,
                    nodes.paragraph(text=warn_text),
                    nodes.paragraph(text=str(sys.exc_info()[1]))
                )
            ]
        finally:
            sys.stdout = old_stdout


# -- Setup function ---------------------------------------------------------- 
Example #18
Source File: briandoc.py    From brian2genn with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        # The section that should be documented
        if len(self.arguments):
            section = self.arguments[0]
        else:
            section = None
        link_targets = not ('nolinks' in self.options)
        rawtext = prefs.get_documentation(section, link_targets)
        include_lines = statemachine.string2lines(rawtext,
                                                  convert_whitespace=True)
        self.state_machine.insert_input(include_lines, 'Brian preferences')
        return [] 
Example #19
Source File: directives.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def run(self):
        # Respect the same disabling options as the `raw` directive
        if (not self.state.document.settings.raw_enabled
                or not self.state.document.settings.file_insertion_enabled):
            raise self.warning('"%s" directive disabled.' % self.name)

        # Retrieve the backreferences directory
        config = self.state.document.settings.env.config
        backreferences_dir = config.sphinx_gallery_conf['backreferences_dir']

        # Parse the argument into the individual objects
        obj_list = self.arguments[0].split()

        lines = []

        # Add a heading if requested
        if 'add-heading' in self.options:
            heading = self.options['add-heading']
            if heading == "":
                if len(obj_list) == 1:
                    heading = 'Examples using ``{}``'.format(obj_list[0])
                else:
                    heading = 'Examples using one of multiple objects'
            lines.append(heading)
            heading_level = self.options.get('heading-level', '^')
            lines.append(heading_level * len(heading))

        # Insert the backreferences file(s) using the `include` directive
        for obj in obj_list:
            path = os.path.join('/',  # Sphinx treats this as the source dir
                                backreferences_dir,
                                '{}.examples'.format(obj))

            # Always remove the heading (first 5 lines) from the file
            lines.append('.. include:: {}\n    :start-line: 5'.format(path))

        # Insert the end for the gallery using the `raw` directive
        lines.append('.. raw:: html\n\n    <div class="sphx-glr-clear"></div>')

        # Parse the assembly of `include` and `raw` directives
        text = '\n'.join(lines)
        include_lines = statemachine.string2lines(text,
                                                  convert_whitespace=True)
        self.state_machine.insert_input(include_lines, path)

        return [] 
Example #20
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 []