Exemplo n.º 1
0
    def read_with_encoding(self, filename, document, codec_info, encoding):
        f = None
        try:
            f = codecs.StreamReaderWriter(open(filename, "rb"), codec_info[2],
                                          codec_info[3], "strict")
            lines = f.readlines()
            lines = dedent_lines(lines, self.options.get("dedent"))
            return lines

        except (IOError, OSError):
            return [
                document.reporter.warning(
                    "Include file %r not found or reading it failed" %
                    filename,
                    line=self.lineno,
                )
            ]

        except UnicodeError:
            return [
                document.reporter.warning(
                    "Encoding %r used for reading included file %r seems to"
                    "be wrong, try giving an :encoding: option" %
                    (encoding, filename))
            ]

        finally:
            if f is not None:
                f.close()
Exemplo n.º 2
0
    def get_codeblock_node(self, code, language):
        """this is copied from sphinx.directives.code.CodeBlock.run

        it has been changed to accept code and language as an arguments instead
        of reading from self

        """

        document = self.state.document
        location = self.state_machine.get_source_and_line(self.lineno)

        linespec = self.options.get('emphasize-lines')
        if linespec:
            try:
                nlines = len(code.split('\n'))
                hl_lines = parselinenos(linespec, nlines)
                if any(i >= nlines for i in hl_lines):
                    log.warning(
                        __('line number spec is out of range(1-%d): %r') %
                        (nlines, self.options['emphasize-lines']),
                        location=location)

                hl_lines = [x + 1 for x in hl_lines if x < nlines]
            except ValueError as err:
                return [document.reporter.warning(str(err), line=self.lineno)]
        else:
            hl_lines = None

        if 'dedent' in self.options:
            location = self.state_machine.get_source_and_line(self.lineno)
            lines = code.split('\n')
            lines = dedent_lines(lines,
                                 self.options['dedent'],
                                 location=location)
            code = '\n'.join(lines)

        literal = nodes.literal_block(code, code)
        literal['language'] = language
        literal['linenos'] = 'linenos' in self.options or \
                             'lineno-start' in self.options
        literal['classes'] += self.options.get('class', [])
        extra_args = literal['highlight_args'] = {}
        if hl_lines is not None:
            extra_args['hl_lines'] = hl_lines
        if 'lineno-start' in self.options:
            extra_args['linenostart'] = self.options['lineno-start']
        set_source_info(self, literal)

        caption = self.options.get('caption')
        if caption:
            try:
                literal = container_wrapper(self, literal, caption)
            except ValueError as exc:
                return [document.reporter.warning(str(exc), line=self.lineno)]

        # literal will be note_implicit_target that is linked from caption and numref.
        # when options['name'] is provided, it should be primary ID.
        self.add_name(literal)

        return [literal]
Exemplo n.º 3
0
    def run(self):
        obj_name = self.arguments[0]

        try:
            prefixed_name, obj, parent, modname = import_by_name(obj_name)
        except ImportError:
            raise self.error(
                "Could not locate Python object {} ({} directive).".format(obj_name, self.name)
            )

        document = self.state.document
        code = str(obj)
        location = self.state_machine.get_source_and_line(self.lineno)

        linespec = self.options.get('emphasize-lines')
        if linespec:
            try:
                nlines = len(self.content)
                hl_lines = parselinenos(linespec, nlines)
                if any(i >= nlines for i in hl_lines):
                    logger.warning(__('line number spec is out of range(1-%d): %r') %
                                   (nlines, self.options['emphasize-lines']),
                                   location=location)

                hl_lines = [x + 1 for x in hl_lines if x < nlines]
            except ValueError as err:
                return [document.reporter.warning(str(err), line=self.lineno)]
        else:
            hl_lines = None

        if 'dedent' in self.options:
            location = self.state_machine.get_source_and_line(self.lineno)
            lines = code.split('\n')
            lines = dedent_lines(lines, self.options['dedent'], location=location)
            code = '\n'.join(lines)

        literal = nodes.literal_block(code, code)
        literal['language'] = self.options[LANGUAGE_OPTION]
        literal['linenos'] = 'linenos' in self.options or \
                             'lineno-start' in self.options
        literal['classes'] += self.options.get('class', [])
        extra_args = literal['highlight_args'] = {}
        if hl_lines is not None:
            extra_args['hl_lines'] = hl_lines
        if 'lineno-start' in self.options:
            extra_args['linenostart'] = self.options['lineno-start']
        set_source_info(self, literal)

        caption = self.options.get('caption')
        if caption:
            try:
                literal = container_wrapper(self, literal, caption)
            except ValueError as exc:
                return [document.reporter.warning(str(exc), line=self.lineno)]

        # literal will be note_implicit_target that is linked from caption and numref.
        # when options['name'] is provided, it should be primary ID.
        self.add_name(literal)

        return [literal]
Exemplo n.º 4
0
    def run(self) -> List[Node]:
        document = self.state.document

        try:
            location = self.state_machine.get_source_and_line(self.lineno)
            rel_filename, filename = self.env.relfn2path(self.arguments[0])
            self.env.note_dependency(rel_filename)
            reader = LiteralIncludeReader(filename, self.options, self.config)
            text, lines = reader.read(location=location)
            lines = text.split("\n")

            if not 'php_opening_tag' in self.options:
                lines = self.removeOpeningTag(lines)

            if 'sections' in self.options:
                lines = self.filter(lines, self.options['sections'].split(','))

            lines = self.filterSections(lines)

            if 'dedent' in self.options:
                location = self.state_machine.get_source_and_line(self.lineno)
                lines = dedent_lines(lines,
                                     self.options['dedent'],
                                     location=location)

            text = "\n".join(lines)
            retnode = nodes.literal_block(
                text, text, source=filename,
                language=self.options['language'])  # type: Element

            return [retnode]
        except Exception as exc:
            return [document.reporter.warning(exc, line=self.lineno)]
Exemplo n.º 5
0
 def dedent_filter(self, lines, location=None):
     # type: (List[unicode], Any) -> List[unicode]
     if "dedent" in self.options:
         return dedent_lines(lines,
                             self.options.get("dedent"),
                             location=location)
     else:
         return lines
Exemplo n.º 6
0
 def dedent_filter(self, lines, location=None):
     # type: (List[str], Tuple[str, int]) -> List[str]
     if 'dedent' in self.options:
         return dedent_lines(lines,
                             self.options.get('dedent'),
                             location=location)
     else:
         return lines
Exemplo n.º 7
0
 def autodedent_filter(self, lines, location=None):
     # type: (List[unicode], Any) -> List[unicode]
     if 'no-auto-dedent' in self.options:
         return lines
     else:
         dedent_level = get_min_indent_nonempty_line(lines)
         logger.debug(__('autodedent: %d' % dedent_level),
                      location=location)
         return dedent_lines(lines, dedent_level, location=location)
Exemplo n.º 8
0
 def read_with_encoding(self, filename, document, codec_info, encoding):
     try:
         with codecs.StreamReaderWriter(open(filename, 'rb'), codec_info[2],
                                        codec_info[3], 'strict') as f:
             lines = ["%s\n" % line.strip("\r\n") for line in f.readlines()]
             lines = dedent_lines(lines, self.options.get('dedent'))
             return [line.rstrip(" ") for line in lines]
     except (IOError, OSError):
         return [document.reporter.warning(
             'Include file %r not found or reading it failed' % filename,
             line=self.lineno)]
     except UnicodeError:
         return [document.reporter.warning(
             'Encoding %r used for reading included file %r seems to '
             'be wrong, try giving an :encoding: option' %
             (encoding, filename))]
Exemplo n.º 9
0
Arquivo: code.py Projeto: nyergler/tut
    def read_file(self, filename, location=None):
        # type: (unicode, Any) -> List[unicode]

        try:
            text = self._tut.file(self._gitref, self.filename[len(self._tut.path) + 1:]).decode(self.encoding)

            if 'tab-width' in self.options:
                text = text.expandtabs(self.options['tab-width'])

            lines = text.splitlines(True)
            if 'dedent' in self.options:
                return dedent_lines(lines, self.options.get('dedent'), location=location)
            else:
                return lines
        except (IOError, OSError):
            raise IOError(_('Include file %r not found or reading it failed') % filename)
        except UnicodeError:
            raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
                                 'be wrong, try giving an :encoding: option') %
                               (self.encoding, filename))
Exemplo n.º 10
0
 def read_with_encoding(self, filename, document, codec_info, encoding):
     f = None
     try:
         f = codecs.StreamReaderWriter(open(filename, 'rb'), codec_info[2],
                                       codec_info[3], 'strict')
         lines = f.readlines()
         lines = dedent_lines(lines, self.options.get('dedent'))
         lines = indent_lines(lines, self.options.get('indent'))
         return lines
     except (IOError, OSError):
         return [document.reporter.warning(
             'Include file %r not found or reading it failed' % filename,
             line=self.lineno)]
     except UnicodeError:
         return [document.reporter.warning(
             'Encoding %r used for reading included file %r seems to '
             'be wrong, try giving an :encoding: option' %
             (encoding, filename))]
     finally:
         if f is not None:
             f.close()
Exemplo n.º 11
0
    def run(self) -> List[Node]:  # noqa: C901
        """Implement option method."""
        document = self.state.document
        code = "\n".join(self.content)
        location = self.state_machine.get_source_and_line(self.lineno)

        linespec = self.options.get("emphasize-lines")
        if linespec:
            try:
                nlines = len(self.content)
                hl_lines = parselinenos(linespec, nlines)
                if any(i >= nlines for i in hl_lines):
                    logger.warning(
                        __("line number spec is out of range(1-%d): %r") %
                        (nlines, self.options["emphasize-lines"]),
                        location=location,
                    )

                hl_lines = [x + 1 for x in hl_lines if x < nlines]
            except ValueError as err:
                return [document.reporter.warning(err, line=self.lineno)]
        else:
            hl_lines = None

        # add parsing for hl_added and hl_removed
        linespec = self.options.get("emphasize-added")
        if linespec:
            try:
                nlines = len(self.content)
                hl_added = parselinenos(linespec, nlines)
                if any(i >= nlines for i in hl_added):
                    logger.warning(
                        __("line number spec is out of range(1-%d): %r") %
                        (nlines, self.options["emphasize-added"]),
                        location=location,
                    )
                hl_added = [x + 1 for x in hl_added if x < nlines]
            except ValueError as err:
                return [document.reporter.warning(err, line=self.lineno)]
        else:
            hl_added = None

        # add parsing for hl_added and hl_removed
        linespec = self.options.get("emphasize-removed")
        if linespec:
            try:
                nlines = len(self.content)
                hl_removed = parselinenos(linespec, nlines)
                if any(i >= nlines for i in hl_removed):
                    logger.warning(
                        __("line number spec is out of range(1-%d): %r") %
                        (nlines, self.options["emphasize-removed"]),
                        location=location,
                    )
                hl_removed = [x + 1 for x in hl_removed if x < nlines]
            except ValueError as err:
                return [document.reporter.warning(err, line=self.lineno)]
        else:
            hl_removed = None

        if "dedent" in self.options:
            location = self.state_machine.get_source_and_line(self.lineno)
            lines = code.split("\n")
            lines = dedent_lines(lines,
                                 self.options["dedent"],
                                 location=location)
            code = "\n".join(lines)

        literal = nodes.literal_block(code, code)
        if "linenos" in self.options or "lineno-start" in self.options:
            literal["linenos"] = True
        literal["classes"] += self.options.get("class", [])
        literal["force"] = "force" in self.options
        if self.arguments:
            # highlight language specified
            literal["language"] = self.arguments[0]
        else:
            # no highlight language specified.  Then this directive refers the current
            # highlight setting via ``highlight`` directive or ``highlight_language``
            # configuration.
            literal["language"] = self.env.temp_data.get(
                "highlight_language", self.config.highlight_language)
        extra_args = literal["highlight_args"] = {}
        if hl_lines is not None:
            extra_args["hl_lines"] = hl_lines
        if hl_added is not None:
            extra_args["hl_added"] = hl_added
        if hl_removed is not None:
            extra_args["hl_removed"] = hl_removed
        if "lineno-start" in self.options:
            extra_args["linenostart"] = self.options["lineno-start"]
        self.set_source_info(literal)

        # if there is a caption, we need to wrap this node in a container
        caption = self.options.get("caption")
        if caption:
            try:
                literal = container_wrapper(self, literal, caption)
            except ValueError as exc:
                return [document.reporter.warning(exc, line=self.lineno)]

        self.add_name(literal)

        return [literal]