コード例 #1
0
    def run(self):
        env = self.state.document.settings.env
        width = 600
        height = None

        if len(self.arguments) > 0:
            fn = search_image_for_language(self.arguments[0], env)
            relfn, excel_file = env.relfn2path(fn)
            env.note_dependency(relfn)
            if self.options:
                width = self.options.get('width', 600)
                height = self.options.get('height')
            book = pyexcel.get_book(file_name=excel_file)
        else:
            content = '\n'.join(self.content)
            if '---pyexcel' in content:
                multiple_sheets = True
            else:
                multiple_sheets = False
            book = pyexcel.get_book(file_content='\n'.join(self.content),
                                    multiple_sheets=multiple_sheets,
                                    lineterminator='\n',
                                    file_type='csv')
        html = self.render_html(book, width, height)
        return [docutils.nodes.raw('', html, format='html')]
コード例 #2
0
 def get_mm_code(self):
     if self.arguments:
         # try to load mermaid code from an external file
         document = self.state.document
         if self.content:
             return [
                 document.reporter.warning(
                     'Mermaid directive cannot have both content and '
                     'a filename argument',
                     line=self.lineno)
             ]
         env = self.state.document.settings.env
         argument = search_image_for_language(self.arguments[0], env)
         rel_filename, filename = env.relfn2path(argument)
         env.note_dependency(rel_filename)
         try:
             with codecs.open(filename, 'r', 'utf-8') as fp:
                 mmcode = fp.read()
         except (IOError, OSError):
             return [
                 document.reporter.warning(
                     'External Mermaid file %r not found or reading '
                     'it failed' % filename,
                     line=self.lineno)
             ]
     else:
         # inline mermaid code
         mmcode = '\n'.join(self.content)
         if not mmcode.strip():
             return [
                 self.state_machine.reporter.warning(
                     'Ignoring "mermaid" directive without content.',
                     line=self.lineno)
             ]
     return mmcode
コード例 #3
0
 def get_mm_code(self):
     if self.arguments:
         # try to load mermaid code from an external file
         document = self.state.document
         if self.content:
             return [document.reporter.warning(
                 'Mermaid directive cannot have both content and '
                 'a filename argument', line=self.lineno)]
         env = self.state.document.settings.env
         argument = search_image_for_language(self.arguments[0], env)
         rel_filename, filename = env.relfn2path(argument)
         env.note_dependency(rel_filename)
         try:
             with codecs.open(filename, 'r', 'utf-8') as fp:
                 mmcode = fp.read()
         except (IOError, OSError):
             return [document.reporter.warning(
                 'External Mermaid file %r not found or reading '
                 'it failed' % filename, line=self.lineno)]
     else:
         # inline mermaid code
         mmcode = '\n'.join(self.content)
         if not mmcode.strip():
             return [self.state_machine.reporter.warning(
                 'Ignoring "mermaid" directive without content.',
                 line=self.lineno)]
     return mmcode
コード例 #4
0
ファイル: asset.py プロジェクト: jrhauser/jrhauser
    def process_doc(self, app: Sphinx, doctree: nodes.document) -> None:
        """Process and rewrite image URIs."""
        docname = app.env.docname

        for node in doctree.findall(nodes.image):
            # Map the mimetype to the corresponding image.  The writer may
            # choose the best image from these candidates.  The special key * is
            # set if there is only single candidate to be used by a writer.
            # The special key ? is set for nonlocal URIs.
            candidates: Dict[str, str] = {}
            node['candidates'] = candidates
            imguri = node['uri']
            if imguri.startswith('data:'):
                candidates['?'] = imguri
                continue
            elif imguri.find('://') != -1:
                candidates['?'] = imguri
                continue

            if imguri.endswith(os.extsep + '*'):
                # Update `node['uri']` to a relative path from srcdir
                # from a relative path from current document.
                rel_imgpath, full_imgpath = app.env.relfn2path(imguri, docname)
                node['uri'] = rel_imgpath

                if app.config.language:
                    # Search language-specific figures at first
                    i18n_imguri = get_image_filename_for_language(
                        imguri, app.env)
                    _, full_i18n_imgpath = app.env.relfn2path(
                        i18n_imguri, docname)
                    self.collect_candidates(app.env, full_i18n_imgpath,
                                            candidates, node)

                self.collect_candidates(app.env, full_imgpath, candidates,
                                        node)
            else:
                if app.config.language:
                    # substitute imguri by figure_language_filename
                    # (ex. foo.png -> foo.en.png)
                    imguri = search_image_for_language(imguri, app.env)

                # Update `node['uri']` to a relative path from srcdir
                # from a relative path from current document.
                node['uri'], _ = app.env.relfn2path(imguri, docname)
                candidates['*'] = node['uri']

            # map image paths to unique image names (so that they can be put
            # into a single directory)
            for imgpath in candidates.values():
                app.env.dependencies[docname].add(imgpath)
                if not os.access(path.join(app.srcdir, imgpath), os.R_OK):
                    logger.warning(__('image file not readable: %s') % imgpath,
                                   location=node,
                                   type='image',
                                   subtype='not_readable')
                    continue
                app.env.images.add_file(docname, imgpath)
コード例 #5
0
ファイル: graphviz_ext.py プロジェクト: QAlgebra/qalgebra
    def run(self):
        # type: () -> List[nodes.Node]
        if self.arguments:
            document = self.state.document
            if self.content:
                return [
                    document.reporter.warning(
                        __(
                            'Graphviz directive cannot have both content and '
                            'a filename argument'
                        ),
                        line=self.lineno,
                    )
                ]
            env = self.state.document.settings.env
            argument = search_image_for_language(self.arguments[0], env)
            rel_filename, filename = env.relfn2path(argument)
            env.note_dependency(rel_filename)
            try:
                with codecs.open(filename, 'r', 'utf-8') as fp:
                    dotcode = fp.read()
            except (IOError, OSError):
                return [
                    document.reporter.warning(
                        __(
                            'External Graphviz file %r not found or reading '
                            'it failed'
                        )
                        % filename,
                        line=self.lineno,
                    )
                ]
        else:
            dotcode = '\n'.join(self.content)
            if not dotcode.strip():
                return [
                    self.state_machine.reporter.warning(
                        __('Ignoring "graphviz" directive without content.'),
                        line=self.lineno,
                    )
                ]
        node = graphviz()
        node['code'] = dotcode
        node['options'] = {}
        if 'graphviz_dot' in self.options:
            node['options']['graphviz_dot'] = self.options['graphviz_dot']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']

        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, node, caption)

        self.add_name(node)
        return [node]
コード例 #6
0
def run(self):
    from sphinx.util.nodes import set_source_info
    from sphinx.util.i18n import search_image_for_language
    warning = self.state.document.reporter.warning
    env = self.state.document.settings.env
    if self.arguments and self.content:
        return [
            warning(
                'uml directive cannot have both content and '
                'a filename argument',
                line=self.lineno)
        ]
    if self.arguments:
        fn = search_image_for_language(self.arguments[0], env)
        relfn, absfn = env.relfn2path(fn)
        env.note_dependency(relfn)
        try:
            umlcode = sphinxcontrib.plantuml._read_utf8(absfn)
        except (IOError, UnicodeDecodeError) as err:
            return [
                warning('PlantUML file "%s" cannot be read: %s' % (fn, err),
                        line=self.lineno)
            ]
        source = absfn
        line = 1
    else:
        relfn = env.doc2path(env.docname, base=None)
        umlcode = '\n'.join(self.content)
        source, line = self.state_machine.get_source_and_line(
            self.content_offset)

    node = sphinxcontrib.plantuml.plantuml(self.block_text, **self.options)
    node['uml'] = umlcode
    node['incdir'] = os.path.dirname(relfn)
    node['filename'] = os.path.split(relfn)[1]
    node.source, node.line = source, line

    # XXX maybe this should be moved to _visit_plantuml functions. it
    # seems wrong to insert "figure" node by "plantuml" directive.
    if 'caption' in self.options or 'align' in self.options:
        node = nodes.figure('', node)
        if 'align' in self.options:
            node['align'] = self.options['align']
    if 'caption' in self.options:
        inodes, messages = self.state.inline_text(self.options['caption'],
                                                  self.lineno)
        caption_node = nodes.caption(self.options['caption'], '', *inodes)
        caption_node.extend(messages)
        set_source_info(self, caption_node)
        node += caption_node
    self.add_name(node)
    if 'html_format' in self.options:
        node['html_format'] = self.options['html_format']
    if 'latex_format' in self.options:
        node['latex_format'] = self.options['latex_format']

    return [node]
コード例 #7
0
    def process_doc(self, app, doctree):
        # type: (Sphinx, nodes.Node) -> None
        """Process and rewrite image URIs."""
        docname = app.env.docname

        for node in doctree.traverse(nodes.image):
            # Map the mimetype to the corresponding image.  The writer may
            # choose the best image from these candidates.  The special key * is
            # set if there is only single candidate to be used by a writer.
            # The special key ? is set for nonlocal URIs.
            candidates = {}  # type: Dict[unicode, unicode]
            node['candidates'] = candidates
            imguri = node['uri']
            if imguri.startswith('data:'):
                candidates['?'] = imguri
                continue
            elif imguri.find('://') != -1:
                candidates['?'] = imguri
                continue
            rel_imgpath, full_imgpath = app.env.relfn2path(imguri, docname)
            if app.config.language:
                # substitute figures (ex. foo.png -> foo.en.png)
                i18n_full_imgpath = search_image_for_language(
                    full_imgpath, app.env)
                if i18n_full_imgpath != full_imgpath:
                    full_imgpath = i18n_full_imgpath
                    rel_imgpath = relative_path(path.join(app.srcdir, 'dummy'),
                                                i18n_full_imgpath)
            # set imgpath as default URI
            node['uri'] = rel_imgpath
            if rel_imgpath.endswith(os.extsep + '*'):
                if app.config.language:
                    # Search language-specific figures at first
                    i18n_imguri = get_image_filename_for_language(
                        imguri, app.env)
                    _, full_i18n_imgpath = app.env.relfn2path(
                        i18n_imguri, docname)
                    self.collect_candidates(app.env, full_i18n_imgpath,
                                            candidates, node)

                self.collect_candidates(app.env, full_imgpath, candidates,
                                        node)
            else:
                candidates['*'] = rel_imgpath

            # map image paths to unique image names (so that they can be put
            # into a single directory)
            for imgpath in candidates.values():
                app.env.dependencies[docname].add(imgpath)
                if not os.access(path.join(app.srcdir, imgpath), os.R_OK):
                    logger.warning(__('image file not readable: %s') % imgpath,
                                   location=node,
                                   type='image',
                                   subtype='not_readable')
                    continue
                app.env.images.add_file(docname, imgpath)
コード例 #8
0
    def run(self) -> List[Node]:
        if self.arguments:
            document = self.state.document
            if self.content:
                return [
                    document.reporter.warning(__(
                        'Graphviz directive cannot have both content and '
                        'a filename argument'),
                                              line=self.lineno)
                ]
            argument = search_image_for_language(self.arguments[0], self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, encoding='utf-8') as fp:
                    dotcode = fp.read()
            except OSError:
                return [
                    document.reporter.warning(
                        __('External Graphviz file %r not found or reading '
                           'it failed') % filename,
                        line=self.lineno)
                ]
        else:
            dotcode = '\n'.join(self.content)
            rel_filename = None
            if not dotcode.strip():
                return [
                    self.state_machine.reporter.warning(
                        __('Ignoring "graphviz" directive without content.'),
                        line=self.lineno)
                ]
        node = graphviz()
        node['code'] = dotcode
        node['options'] = {'docname': self.env.docname}

        if 'graphviz_dot' in self.options:
            node['options']['graphviz_dot'] = self.options['graphviz_dot']
        if 'layout' in self.options:
            node['options']['graphviz_dot'] = self.options['layout']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']
        if 'class' in self.options:
            node['classes'] = self.options['class']
        if rel_filename:
            node['filename'] = rel_filename

        if 'caption' not in self.options:
            self.add_name(node)
            return [node]
        else:
            figure = figure_wrapper(self, node, self.options['caption'])
            self.add_name(figure)
            return [figure]
コード例 #9
0
    def run(self):
        if self.arguments:
            # Read code from file
            document = self.state.document
            if self.content:
                return [document.reporter.warning(
                    __('wavedrom directive cannot have both content and '
                       'a filename argument'), line=self.lineno)]
            argument = search_image_for_language(self.arguments[0], self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, 'r') as fp:  # type: ignore
                    code = fp.read()
            except (IOError, OSError):
                return [document.reporter.warning(
                    __('External wavedrom json file %r not found or reading '
                       'it failed') % filename, line=self.lineno)]
        else:
            # Read code from given content
            code = "\n".join(self.content)
            if not code.strip():
                return [self.state_machine.reporter.warning(
                    __('Ignoring "wavedrom" directive without content.'),
                    line=self.lineno)]

        # For html output with inline JS enabled, just return plain HTML
        if (self.env.app.builder.name in ('html', 'dirhtml', 'singlehtml')
            and self.config.wavedrom_html_jsinline):
            text = WAVEDROM_HTML.format(content=code)
            content = nodes.raw(text=text, format='html')
            return [content]

        # Store code in a special docutils node and pick up at rendering
        node = wavedromnode()

        node['code'] = code
        wd_node = node # point to the actual wavedrom node

        # A caption option turns this image into a Figure
        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, wd_node, caption)
            self.add_name(node)

        # Run image directive processing for the options, supply dummy argument, otherwise will fail.
        # We don't actually replace this node by the image_node and will also not make it a child,
        # because intermediate steps, like converters, depend on the file being in sources. We don't
        # want to generate any files in the user sources. Store the image_node private to this node
        # and not in the docutils tree and use it later. Revisit this when the situation changes.
        self.arguments = ["dummy"]
        (wd_node['image_node'],) = Image.run(self)

        return [node]
コード例 #10
0
ファイル: asset.py プロジェクト: nwf/sphinx
    def process_doc(self, app, doctree):
        # type: (Sphinx, nodes.Node) -> None
        """Process and rewrite image URIs."""
        docname = app.env.docname

        for node in doctree.traverse(nodes.image):
            # Map the mimetype to the corresponding image.  The writer may
            # choose the best image from these candidates.  The special key * is
            # set if there is only single candidate to be used by a writer.
            # The special key ? is set for nonlocal URIs.
            candidates = {}  # type: Dict[unicode, unicode]
            node['candidates'] = candidates
            imguri = node['uri']
            if imguri.startswith('data:'):
                logger.warning('image data URI found. some builders might not support',
                               location=node, type='image', subtype='data_uri')
                candidates['?'] = imguri
                continue
            elif imguri.find('://') != -1:
                logger.warning('nonlocal image URI found: %s' % imguri,
                               location=node,
                               type='image', subtype='nonlocal_uri')
                candidates['?'] = imguri
                continue
            rel_imgpath, full_imgpath = app.env.relfn2path(imguri, docname)
            if app.config.language:
                # substitute figures (ex. foo.png -> foo.en.png)
                i18n_full_imgpath = search_image_for_language(full_imgpath, app.env)
                if i18n_full_imgpath != full_imgpath:
                    full_imgpath = i18n_full_imgpath
                    rel_imgpath = relative_path(path.join(app.srcdir, 'dummy'),
                                                i18n_full_imgpath)
            # set imgpath as default URI
            node['uri'] = rel_imgpath
            if rel_imgpath.endswith(os.extsep + '*'):
                if app.config.language:
                    # Search language-specific figures at first
                    i18n_imguri = get_image_filename_for_language(imguri, app.env)
                    _, full_i18n_imgpath = app.env.relfn2path(i18n_imguri, docname)
                    self.collect_candidates(app.env, full_i18n_imgpath, candidates, node)

                self.collect_candidates(app.env, full_imgpath, candidates, node)
            else:
                candidates['*'] = rel_imgpath

            # map image paths to unique image names (so that they can be put
            # into a single directory)
            for imgpath in itervalues(candidates):
                app.env.dependencies[docname].add(imgpath)
                if not os.access(path.join(app.srcdir, imgpath), os.R_OK):
                    logger.warning('image file not readable: %s' % imgpath,
                                   location=node, type='image', subtype='not_readable')
                    continue
                app.env.images.add_file(docname, imgpath)
コード例 #11
0
 def run(self):
     node = super(DispatcherSphinxDirective, self).run()[0]
     # noinspection PyUnresolvedReferences
     node = dsp(node.rawsource, *node.children, **node.attributes)
     node['img_opt'] = sh.selector(self.img_opt,
                                   self.options,
                                   allow_miss=True)
     node['index'] = self.options.get('index', False)
     env = self.state.document.settings.env
     argument = search_image_for_language(self.arguments[0], env)
     dirpath = osp.dirname(env.relfn2path(argument)[1])
     node['dirpath'] = dirpath if osp.isdir(dirpath) else None
     return [node]
コード例 #12
0
ファイル: plantuml.py プロジェクト: bosonogi/plantuml
    def run(self):
        warning = self.state.document.reporter.warning
        env = self.state.document.settings.env
        if self.arguments and self.content:
            return [
                warning(
                    'uml directive cannot have both content and '
                    'a filename argument',
                    line=self.lineno)
            ]
        if self.arguments:
            fn = search_image_for_language(self.arguments[0], env)
            relfn, absfn = env.relfn2path(fn)
            env.note_dependency(relfn)
            try:
                umlcode = _read_utf8(absfn)
            except (IOError, UnicodeDecodeError) as err:
                return [
                    warning('PlantUML file "%s" cannot be read: %s' %
                            (fn, err),
                            line=self.lineno)
                ]
        else:
            relfn = env.doc2path(env.docname, base=None)
            umlcode = '\n'.join(self.content)

        node = plantuml(self.block_text, **self.options)
        node['uml'] = umlcode
        node['incdir'] = os.path.dirname(relfn)
        node['filename'] = os.path.split(relfn)[1]

        # XXX maybe this should be moved to _visit_plantuml functions. it
        # seems wrong to insert "figure" node by "plantuml" directive.
        if 'caption' in self.options or 'align' in self.options:
            node = nodes.figure('', node)
            if 'align' in self.options:
                node['align'] = self.options['align']
        if 'caption' in self.options:
            import docutils.statemachine
            cnode = nodes.Element()  # anonymous container for parsing
            sl = docutils.statemachine.StringList([self.options['caption']],
                                                  source='')
            self.state.nested_parse(sl, self.content_offset, cnode)
            caption = nodes.caption(self.options['caption'], '', *cnode)
            node += caption
        if 'html_format' in self.options:
            node['html_format'] = self.options['html_format']
        if 'latex_format' in self.options:
            node['latex_format'] = self.options['latex_format']

        return [node]
コード例 #13
0
    def run(self) -> List[Node]:
        document = self.state.document
        if self.arguments:
            if self.content:
                return [
                    document.reporter.warning(
                        __("Only explicit path supported"), line=self.lineno)
                ]
            argument = search_image_for_language(self.arguments[0], self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, encoding="utf-8") as fp:
                    diagram_code = fp.read()
            except OSError:
                return [
                    document.reporter.warning(
                        __("External Diagrams file %r not found or reading "
                           "it failed") % filename,
                        line=self.lineno,
                    )
                ]
        else:
            diagram_code = "\n".join(self.content)
            filename = self.env.docname + sha1(
                diagram_code.encode("utf-8")).hexdigest()
            if not diagram_code.strip():
                return [
                    self.state_machine.reporter.warning(
                        __('Ignoring "diagrams" directive without content.'),
                        line=self.lineno,
                    )
                ]
        node = diagrams()
        node["code"] = diagram_code
        node["options"] = {"docname": self.env.docname}
        if OPTION_FILENAME not in self.options:
            inferred_filename = f"{Path(filename).stem}.png"
            node["options"][OPTION_FILENAME] = inferred_filename
            document.reporter.info(
                __(":filename: argument not pass assuming "
                   f"the output file is named.'{inferred_filename}'"),
                line=self.lineno,
            )
        else:
            node["options"][OPTION_FILENAME] = self.options[OPTION_FILENAME]

        return [node]
コード例 #14
0
    def run(self):
        env = self.state.document.settings.env
        fn = search_image_for_language('pie.csv', env)
        relfn, excel_file = env.relfn2path(fn)
        working_path = os.path.dirname(excel_file)
        content = ["import os", "os.chdir('%s')" % working_path]
        content += list(self.content)
        code = '\n'.join(content)
        scope = {'pyexcel': pyexcel}
        try:
            exec(code, scope)
        except Exception:
            print(code)
            print_exc()
            return [
                docutils.nodes.system_message(
                    'An exception as occured during code parsing:'
                    ' \n %s' % format_exc(),
                    type='ERROR',
                    source='/',
                    level=3)
            ]
        chart = None
        for key, value in scope.items():
            if isinstance(value, BytesIO):
                chart = value
                break
        if chart is None:
            return [
                docutils.nodes.system_message('No instance of graph found',
                                              level=3,
                                              type='ERROR',
                                              source='/')
            ]

        try:
            svg = "%s" % chart.getvalue().decode('utf-8')
        except Exception:
            return [
                docutils.nodes.system_message(
                    'An exception as occured during graph generation:'
                    ' \n %s' % format_exc(),
                    type='ERROR',
                    source='/',
                    level=3)
            ]
        return [docutils.nodes.raw('', svg, format='html')]
コード例 #15
0
    def run(self):
        # type: () -> List[nodes.Node]

        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)

        print("verilog-diagram", self)

        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        if self.arguments:
            verilog_file = self.arguments[0]

            outname = verilog_diagram_name(
                *self.state_machine.get_source_and_line(), verilog_file)

            # self.state.document.settings.record_dependencies.add(verilog_path)

            env = self.state.document.settings.env
            argument = search_image_for_language(verilog_file, env)
            rel_filename, filename = env.relfn2path(verilog_file)
            env.note_dependency(rel_filename)
        else:
            assert False, "TODO!"
            # TODO: ????
            verilog_diagram_code = '\n'.join(self.content)

        node = verilog_diagram()
        node['code'] = filename
        node['options'] = {}
        node['options']['outname'] = outname
        node['options']['flatten'] = 'flatten' in self.options
        node['options']['module'] = self.options.get('module', 'top')
        node['options']['type'] = self.options.get('type', 'netlistsvg')

        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']

        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, node, caption)

        self.add_name(node)
        return [node]
コード例 #16
0
ファイル: graphviz.py プロジェクト: Felix-neko/sphinx
    def run(self):
        # type: () -> List[nodes.Node]
        if self.arguments:
            document = self.state.document
            if self.content:
                return [document.reporter.warning(
                    'Graphviz directive cannot have both content and '
                    'a filename argument', line=self.lineno)]
            env = self.state.document.settings.env
            argument = search_image_for_language(self.arguments[0], env)
            rel_filename, filename = env.relfn2path(argument)
            env.note_dependency(rel_filename)
            try:
                with codecs.open(filename, 'r', 'utf-8') as fp:
                    dotcode = fp.read()
            except (IOError, OSError):
                return [document.reporter.warning(
                    'External Graphviz file %r not found or reading '
                    'it failed' % filename, line=self.lineno)]
        else:
            dotcode = '\n'.join(self.content)
            if not dotcode.strip():
                return [self.state_machine.reporter.warning(
                    'Ignoring "graphviz" directive without content.',
                    line=self.lineno)]
        node = graphviz()
        node['code'] = dotcode
        node['options'] = {}
        if 'graphviz_dot' in self.options:
            node['options']['graphviz_dot'] = self.options['graphviz_dot']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']
        if 'inline' in self.options:
            node['inline'] = True

        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, node, caption)

        self.add_name(node)
        return [node]
コード例 #17
0
ファイル: graphviz.py プロジェクト: lmregus/Portfolio
    def run(self):
        # type: () -> List[nodes.Node]
        if self.arguments:
            document = self.state.document
            if self.content:
                return [document.reporter.warning(
                    __('Graphviz directive cannot have both content and '
                       'a filename argument'), line=self.lineno)]
            argument = search_image_for_language(self.arguments[0], self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, encoding='utf-8') as fp:
                    dotcode = fp.read()
            except OSError:
                return [document.reporter.warning(
                    __('External Graphviz file %r not found or reading '
                       'it failed') % filename, line=self.lineno)]
        else:
            dotcode = '\n'.join(self.content)
            if not dotcode.strip():
                return [self.state_machine.reporter.warning(
                    __('Ignoring "graphviz" directive without content.'),
                    line=self.lineno)]
        node = graphviz()
        node['code'] = dotcode
        node['options'] = {'docname': self.env.docname}

        if 'graphviz_dot' in self.options:
            node['options']['graphviz_dot'] = self.options['graphviz_dot']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']

        if 'caption' not in self.options:
            self.add_name(node)
            return [node]
        else:
            figure = figure_wrapper(self, node, self.options['caption'])
            self.add_name(figure)
            return [figure]
コード例 #18
0
ファイル: plantuml.py プロジェクト: Lemma1/MINAMI
    def run(self):
        warning = self.state.document.reporter.warning
        env = self.state.document.settings.env
        if self.arguments and self.content:
            return [warning('uml directive cannot have both content and '
                            'a filename argument', line=self.lineno)]
        if self.arguments:
            fn = search_image_for_language(self.arguments[0], env)
            relfn, absfn = env.relfn2path(fn)
            env.note_dependency(relfn)
            try:
                umlcode = _read_utf8(absfn)
            except (IOError, UnicodeDecodeError) as err:
                return [warning('PlantUML file "%s" cannot be read: %s'
                                % (fn, err), line=self.lineno)]
        else:
            relfn = env.doc2path(env.docname, base=None)
            umlcode = '\n'.join(self.content)

        node = plantuml(self.block_text, **self.options)
        node['uml'] = umlcode
        node['incdir'] = os.path.dirname(relfn)

        # XXX maybe this should be moved to _visit_plantuml functions. it
        # seems wrong to insert "figure" node by "plantuml" directive.
        if 'caption' in self.options or 'align' in self.options:
            node = nodes.figure('', node)
            if 'align' in self.options:
                node['align'] = self.options['align']
        if 'caption' in self.options:
            import docutils.statemachine
            cnode = nodes.Element()  # anonymous container for parsing
            sl = docutils.statemachine.StringList([self.options['caption']],
                                                  source='')
            self.state.nested_parse(sl, self.content_offset, cnode)
            caption = nodes.caption(self.options['caption'], '', *cnode)
            node += caption

        return [node]
コード例 #19
0
    def run(self):
        if self.arguments:
            document = self.state.document
            if self.content:
                return [document.reporter.warning(
                        __('DiagramsAsCode directive cannot have both content and '
                           'a filename argument'), line=self.lineno)]
            argument = search_image_for_language(self.arguments[0], self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, encoding='utf-8') as fp:
                    dotcode = fp.read()
            except OSError:
                return [document.reporter.warning(
                        __('External DiagramsAsCode file %r not found or reading '
                           'it failed') % filename, line=self.lineno)]
        else:
            dotcode = '\n'.join(self.content)
            if not dotcode.strip():
                return [self.state_machine.reporter.warning(
                    __('Ignoring "graphviz" directive without content.'),
                    line=self.lineno)]
        node = DiagramNode()
        node['code'] = dotcode
        node['options'] = {'docname': self.env.docname}

        if 'layout' in self.options:
            node['options']['layout'] = self.options['layout']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']

        self.add_name(node)
        return [node]
コード例 #20
0
    def run(self):
        # type: () -> List[nodes.Node]
        env = self.state.document.settings.env
        argument = search_image_for_language(self.arguments[0], env)
        rel_filename, filename = env.relfn2path(argument)
        env.note_dependency(rel_filename)
        node = bitfields()
        node['filename'] = filename
        node['options'] = {}
        if 'bitfields_cmd' in self.options:
            node['options']['bitfields_cmd'] = self.options['bitfields_cmd']
        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']

        if 'vspace' in self.options:
            node['options']['vspace'] = self.options['vspace']
        if 'hspace' in self.options:
            node['options']['hspace'] = self.options['hspace']
        if 'lanes' in self.options:
            node['options']['lanes'] = self.options['lanes']
        if 'bits' in self.options:
            node['options']['bits'] = self.options['bits']
        if 'bigendian' in self.options:
            node['options']['bigendian'] = self.options['bigendian']
            
        if 'name' in self.options:
          node['options']['name'] = self.options['name']

        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, node, caption)

        self.add_name(node)
        return [node]
コード例 #21
0
ファイル: __init__.py プロジェクト: akhildp/newDoc
    def process_images(self, docname, doctree):
        """Process and rewrite image URIs."""
        def collect_candidates(imgpath, candidates):
            globbed = {}
            for filename in glob(imgpath):
                new_imgpath = relative_path(path.join(self.srcdir, 'dummy'),
                                            filename)
                try:
                    mimetype = guess_mimetype(filename)
                    if mimetype not in candidates:
                        globbed.setdefault(mimetype, []).append(new_imgpath)
                except (OSError, IOError) as err:
                    self.warn_node('image file %s not readable: %s' %
                                   (filename, err), node)
            for key, files in iteritems(globbed):
                candidates[key] = sorted(files, key=len)[0]  # select by similarity

        for node in doctree.traverse(nodes.image):
            # Map the mimetype to the corresponding image.  The writer may
            # choose the best image from these candidates.  The special key * is
            # set if there is only single candidate to be used by a writer.
            # The special key ? is set for nonlocal URIs.
            node['candidates'] = candidates = {}
            imguri = node['uri']
            if imguri.startswith('data:'):
                self.warn_node('image data URI found. some builders might not support', node,
                               type='image', subtype='data_uri')
                candidates['?'] = imguri
                continue
            elif imguri.find('://') != -1:
                self.warn_node('nonlocal image URI found: %s' % imguri, node,
                               type='image', subtype='nonlocal_uri')
                candidates['?'] = imguri
                continue
            rel_imgpath, full_imgpath = self.relfn2path(imguri, docname)
            if self.config.language:
                # substitute figures (ex. foo.png -> foo.en.png)
                i18n_full_imgpath = search_image_for_language(full_imgpath, self)
                if i18n_full_imgpath != full_imgpath:
                    full_imgpath = i18n_full_imgpath
                    rel_imgpath = relative_path(path.join(self.srcdir, 'dummy'),
                                                i18n_full_imgpath)
            # set imgpath as default URI
            node['uri'] = rel_imgpath
            if rel_imgpath.endswith(os.extsep + '*'):
                if self.config.language:
                    # Search language-specific figures at first
                    i18n_imguri = get_image_filename_for_language(imguri, self)
                    _, full_i18n_imgpath = self.relfn2path(i18n_imguri, docname)
                    collect_candidates(full_i18n_imgpath, candidates)

                collect_candidates(full_imgpath, candidates)
            else:
                candidates['*'] = rel_imgpath

            # map image paths to unique image names (so that they can be put
            # into a single directory)
            for imgpath in itervalues(candidates):
                self.dependencies.setdefault(docname, set()).add(imgpath)
                if not os.access(path.join(self.srcdir, imgpath), os.R_OK):
                    self.warn_node('image file not readable: %s' % imgpath,
                                   node)
                    continue
                self.images.add_file(docname, imgpath)
コード例 #22
0
    def run(self):
        if self.arguments:
            # Read code from file
            document = self.state.document
            if self.content:
                return [
                    document.reporter.warning(__(
                        'wavedrom directive cannot have both content and '
                        'a filename argument'),
                                              line=self.lineno)
                ]
            argument = search_image_for_language(self.arguments[0], self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, 'r') as fp:  # type: ignore
                    code = fp.read()
            except (IOError, OSError):
                return [
                    document.reporter.warning(__(
                        'External wavedrom json file %r not found or reading '
                        'it failed') % filename,
                                              line=self.lineno)
                ]
        else:
            # Read code from given content
            code = "\n".join(self.content)
            if not code.strip():
                return [
                    self.state_machine.reporter.warning(
                        __('Ignoring "wavedrom" directive without content.'),
                        line=self.lineno)
                ]

        # For html output with inline JS enabled, just return plain HTML
        if (self.env.app.builder.name in ('html', 'dirhtml', 'singlehtml')
                and self.config.wavedrom_html_jsinline):
            text = WAVEDROM_HTML.format(content=code)
            content = nodes.raw(text=text, format='html')
            return [content]

        # Store code in a special docutils node and pick up at rendering
        node = wavedromnode()

        node['code'] = code
        wd_node = node  # point to the actual wavedrom node

        # A caption option turns this image into a Figure
        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, wd_node, caption)
            self.add_name(node)

        # Run image directive processing for the options, supply dummy argument, otherwise will fail.
        # We don't actually replace this node by the image_node and will also not make it a child,
        # because intermediate steps, like converters, depend on the file being in sources. We don't
        # want to generate any files in the user sources. Store the image_node private to this node
        # and not in the docutils tree and use it later. Revisit this when the situation changes.
        self.arguments = ["dummy"]
        (wd_node['image_node'], ) = Image.run(self)

        return [node]
コード例 #23
0
    def run(self):
        # type: () -> List[nodes.Node]

        if not self.state.document.settings.file_insertion_enabled:
            raise self.warning('"%s" directive disabled.' % self.name)

        print("hdl-diagram", self)

        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        if self.arguments:
            hdl_file = self.arguments[0]

            outname = hdl_diagram_name(
                *self.state_machine.get_source_and_line(), hdl_file)

            # self.state.document.settings.record_dependencies.add(hdl_path)

            env = self.state.document.settings.env
            argument = search_image_for_language(hdl_file, env)
            rel_filename, filename = env.relfn2path(hdl_file)
            env.note_dependency(rel_filename)
        else:
            assert False, "TODO!"
            # TODO: ????
            hdl_diagram_code = '\n'.join(self.content)

        node = hdl_diagram()
        node['code'] = filename
        node['options'] = {}
        node['options']['outname'] = outname
        node['options']['flatten'] = 'flatten' in self.options
        node['options']['module'] = self.options.get('module', 'top')
        node['options']['type'] = self.options.get('type', 'netlistsvg')

        if 'alt' in self.options:
            node['alt'] = self.options['alt']
        if 'align' in self.options:
            node['align'] = self.options['align']

        yosys_script = self.options.get('yosys_script', None)
        if yosys_script not in [None, 'default']:
            _, yosys_script_filename = env.relfn2path(yosys_script)
            if not path.exists(yosys_script_filename):
                raise HDLDiagramError("Yosys script {} does not exist!".format(
                    yosys_script_filename))
            else:
                node['options']['yosys_script'] = yosys_script_filename
        else:
            node['options']['yosys_script'] = yosys_script

        skin = self.options.get('skin', None)
        if skin not in [None, 'default']:
            _, skin_filename = env.relfn2path(skin)
            if not os.path.exists(skin_filename):
                raise HDLDiagramError(
                    "Skin file {} does not exist!".format(skin_filename))
            else:
                node['options']['skin'] = skin_filename
        else:
            node['options']['skin'] = skin

        caption = self.options.get('caption')
        if caption:
            node = figure_wrapper(self, node, caption)

        self.add_name(node)
        return [node]
コード例 #24
0
    def run(self) -> List[Node]:
        document = self.state.document
        source: str = "\n".join(self.content)
        filename: Optional[str] = None
        diagram_type: Optional[str] = None
        output_format: Optional[str] = None

        for argument in self.arguments:
            if argument in types:
                diagram_type = argument
            elif argument in formats:
                output_format = argument
            else:
                filename = argument

        if "filename" in self.options:
            if filename is not None:
                return [
                    document.reporter.warning(
                        __("Kroki directive cannot have both filename option and "
                           "a filename argument"),
                        line=self.lineno,
                    )
                ]
            filename = self.options["filename"]

        if source.strip() and filename is not None:
            return [
                document.reporter.warning(
                    __("Kroki directive cannot have both content and "
                       "a filename argument"),
                    line=self.lineno,
                )
            ]

        if filename is not None:
            argument = search_image_for_language(filename, self.env)
            rel_filename, filename = self.env.relfn2path(argument)
            self.env.note_dependency(rel_filename)
            try:
                with open(filename, encoding="utf-8") as fp:
                    source = fp.read()
            except OSError:
                return [
                    document.reporter.warning(
                        __("External kroki file %r not found or reading "
                           "it failed") % filename,
                        line=self.lineno,
                    )
                ]

        if not source.strip():
            return [
                document.reporter.warning(
                    __("Ignoring kroki directive without content. It is necessary to specify "
                       "filename argument/option or content"),
                    line=self.lineno,
                )
            ]

        if "type" in self.options:
            if diagram_type is not None:
                return [
                    document.reporter.warning(
                        __("Kroki directive cannot have both type option and "
                           "a type argument"),
                        line=self.lineno,
                    )
                ]
            diagram_type = self.options["type"]

        if diagram_type is None:
            if filename is not None:
                diagram_type = extension_type_map.get(
                    path.splitext(filename)[1])

            if diagram_type is None:
                return [
                    document.reporter.warning(
                        __("Kroki directive has to define diagram type."),
                        line=self.lineno,
                    )
                ]

        if "format" in self.options:
            if output_format is not None:
                return [
                    document.reporter.warning(
                        __("Kroki directive cannot have both format option and "
                           "a format argument"),
                        line=self.lineno,
                    )
                ]
            output_format = self.options["format"]

        node = kroki()

        node["type"] = diagram_type
        if output_format is not None:
            node["format"] = output_format
        node["code"] = source
        node["options"] = {"docname": self.env.docname}
        if "align" in self.options:
            node["align"] = self.options["align"]
        if "class" in self.options:
            node["classes"] = self.options["class"]

        if "caption" not in self.options:
            self.add_name(node)
            return [node]
        else:
            figure = figure_wrapper(self, node, self.options["caption"])
            self.add_name(figure)
            return [figure]
コード例 #25
0
ファイル: __init__.py プロジェクト: techtonik/sphinx
    def process_images(self, docname, doctree):
        """Process and rewrite image URIs."""
        def collect_candidates(imgpath, candidates):
            globbed = {}
            for filename in glob(imgpath):
                new_imgpath = relative_path(path.join(self.srcdir, 'dummy'),
                                            filename)
                try:
                    mimetype = guess_mimetype(filename)
                    if mimetype not in candidates:
                        globbed.setdefault(mimetype, []).append(new_imgpath)
                except (OSError, IOError) as err:
                    self.warn_node('image file %s not readable: %s' %
                                   (filename, err), node)
            for key, files in iteritems(globbed):
                candidates[key] = sorted(files, key=len)[0]  # select by similarity

        for node in doctree.traverse(nodes.image):
            # Map the mimetype to the corresponding image.  The writer may
            # choose the best image from these candidates.  The special key * is
            # set if there is only single candidate to be used by a writer.
            # The special key ? is set for nonlocal URIs.
            node['candidates'] = candidates = {}
            imguri = node['uri']
            if imguri.startswith('data:'):
                self.warn_node('image data URI found. some builders might not support', node,
                               type='image', subtype='data_uri')
                candidates['?'] = imguri
                continue
            elif imguri.find('://') != -1:
                self.warn_node('nonlocal image URI found: %s' % imguri, node,
                               type='image', subtype='nonlocal_uri')
                candidates['?'] = imguri
                continue
            rel_imgpath, full_imgpath = self.relfn2path(imguri, docname)
            if self.config.language:
                # substitute figures (ex. foo.png -> foo.en.png)
                i18n_full_imgpath = search_image_for_language(full_imgpath, self)
                if i18n_full_imgpath != full_imgpath:
                    full_imgpath = i18n_full_imgpath
                    rel_imgpath = relative_path(path.join(self.srcdir, 'dummy'),
                                                i18n_full_imgpath)
            # set imgpath as default URI
            node['uri'] = rel_imgpath
            if rel_imgpath.endswith(os.extsep + '*'):
                if self.config.language:
                    # Search language-specific figures at first
                    i18n_imguri = get_image_filename_for_language(imguri, self)
                    _, full_i18n_imgpath = self.relfn2path(i18n_imguri, docname)
                    collect_candidates(full_i18n_imgpath, candidates)

                collect_candidates(full_imgpath, candidates)
            else:
                candidates['*'] = rel_imgpath

            # map image paths to unique image names (so that they can be put
            # into a single directory)
            for imgpath in itervalues(candidates):
                self.dependencies.setdefault(docname, set()).add(imgpath)
                if not os.access(path.join(self.srcdir, imgpath), os.R_OK):
                    self.warn_node('image file not readable: %s' % imgpath,
                                   node)
                    continue
                self.images.add_file(docname, imgpath)