Beispiel #1
0
 def run(self):
     # get the argument
     fileName = self.arguments[0]
     # set the required language argument back
     self.arguments[0] = os.path.splitext(fileName)[1][1:]
     # set it as filename
     self.options['filename'] = fileName
     # encode the whole content
     self.content = [unicode(line) for line in self.content]
     # call parent class
     nodes = super(DownloadCode, self).run()
     # get the content and encode
     code = u'\n'.join(self.content)
     # get the path
     path = os.path.join(downloadCodeRoot, fileName)
     # check the path on duplicates
     path = self.checkPath(path)
     # the filename could be changed
     fileName = os.path.basename(path)
     self.options["filename"] = fileName
     # write to disk
     f = open(path, "w")
     f.write(code.encode("utf-8"))
     f.close()
     # add download links
     node = addnodes.download_reference()
     node['reftarget'] = "/downloads/" + fileName
     nodes.append(node)
     return nodes
Beispiel #2
0
    def run(self):
        self.arguments = ['']
        indigorenderer_options = dict([(k,v) for k,v in self.options.items()
                                      if k in self.own_option_spec])

        text = '\n'.join(self.content)
            
        (image_node,) = directives.images.Image.run(self)
        if isinstance(image_node, nodes.system_message):
            return [image_node, ]
        image_node.indigorenderer = dict(text=text, options=indigorenderer_options)
        if 'nocode' in self.options or len(text.strip()) == 0:
            return [image_node, ]
        blocks = []
        if indigorenderer_options['indigoobjecttype'] == 'code':
            literal = nodes.literal_block(text, text, line=self.lineno)
            #literal['linenos'] = True
            literal['language'] = 'python'
            blocks = [literal]
            if 'downloads' in self.options:
                blocks.append(nodes.Text('Input:     '))
                for file in self.options['downloads'].split(','):
                    download = addnodes.download_reference("", "")
                    download += nodes.literal(file, file)
                    download['reftarget'] = file
                    blocks.append(download)
                    blocks.append(nodes.Text('     '))
                blocks.append(nodes.line())
            
        blocks.append(image_node)
           
        return blocks
Beispiel #3
0
 def run(self):
     # get the argument
     fileName = self.arguments[0]
     # set the required language argument back
     self.arguments[0] = os.path.splitext(fileName)[1][1:]
     # set it as filename
     self.options['filename'] = fileName
     # encode the whole content
     self.content = [unicode(line) for line in self.content]
     # call parent class
     nodes = super(DownloadCode, self).run()
     # get the content and encode
     code = u'\n'.join(self.content)
     # get the path
     path = os.path.join(downloadCodeRoot, fileName)
     # check the path on duplicates
     path = self.checkPath(path)
     # the filename could be changed
     fileName = os.path.basename(path)
     self.options["filename"] = fileName
     # write to disk
     f = open(path, "w")
     f.write(code.encode("utf-8"))
     f.close()
     # add download links
     node = addnodes.download_reference()
     node['reftarget'] = "/downloads/" + fileName
     nodes.append(node)
     return nodes
 def run(self):
     reftarget = sphinx_abs_dir(self.env, self.target)
     node = download_reference(self.rawtext, reftarget=reftarget)
     self.set_source_info(node)
     title = self.title if self.has_explicit_title else self.target
     node += docnodes.literal(self.rawtext,
                              title,
                              classes=["xref", "download", "myst-nb"])
     return [node], []
Beispiel #5
0
 def run(self):
     # get the argument
     fileName = self.arguments[0]
     # set the required language argument back
     self.arguments[0] = os.path.splitext(fileName)[1][1:]
     # set it as filename
     self.options['filename'] = fileName
     # encode the whole content
     self.content = [line for line in self.content]
     # call parent class
     nodes = super(DownloadCode, self).run()
     # get the content and encode
     code = u'\n'.join(self.content)
     # get the path
     path = os.path.join(downloadCodeRoot, fileName)
     # check the path on duplicates
     path = self.checkPath(path)
     # the filename could be changed
     fileName = os.path.basename(path)
     self.options["filename"] = fileName
     # write to disk
     f = open(path, "w")
     f.write(code)
     f.close()
     # add example image if present
     imageBaseName, _ = os.path.splitext(fileName)
     imageFileName = "example_%s.png" % imageBaseName
     imagePath = os.path.join(imageSourceRoot, imageFileName)
     if os.path.exists(imagePath):
         imageDestPath = os.path.join(downloadCodeRoot, imageFileName)
         shutil.copy(imagePath, imageDestPath)
     else:
         imageFileName = ""
     # add download links
     node = addnodes.download_reference()
     node['reftarget'] = "/downloads/" + fileName
     node['imageFileName'] = imageFileName
     nodes.append(node)
     if imageFileName:
         node = addnodes.download_reference()
         node['reftarget'] = "/downloads/" + imageFileName
         node['dontShowThisNode'] = True
         nodes.append(node)
     return nodes
Beispiel #6
0
 def run(self):
     # get the argument
     fileName = self.arguments[0]
     # set the required language argument back
     self.arguments[0] = os.path.splitext(fileName)[1][1:]
     # set it as filename
     self.options['filename'] = fileName
     # encode the whole content
     self.content = [line for line in self.content]
     # call parent class
     nodes = super(DownloadCode, self).run()
     # get the content and encode
     code = u'\n'.join(self.content)
     # get the path
     path = os.path.join(downloadCodeRoot, fileName)
     # check the path on duplicates
     path = self.checkPath(path)
     # the filename could be changed
     fileName = os.path.basename(path)
     self.options["filename"] = fileName
     # write to disk
     f = open(path, "w")
     f.write(code)
     f.close()
     # add example image if present
     imageBaseName, _ = os.path.splitext(fileName)
     imageFileName = "example_%s.png" % imageBaseName
     imagePath = os.path.join(imageSourceRoot, imageFileName)
     if os.path.exists(imagePath):
         imageDestPath = os.path.join(downloadCodeRoot, imageFileName)
         shutil.copy(imagePath, imageDestPath)
     else:
         imageFileName = ""
     # add download links
     node = addnodes.download_reference()
     node['reftarget'] = "/downloads/" + fileName
     node['imageFileName'] = imageFileName
     nodes.append(node)
     if imageFileName:
         node = addnodes.download_reference()
         node['reftarget'] = "/downloads/" + imageFileName
         node['dontShowThisNode'] = True
         nodes.append(node)
     return nodes
Beispiel #7
0
    def render_internal_link(self, token: SyntaxTreeNode) -> None:
        """Render link token `[text](link "title")`,
        where the link has not been identified as an external URL.
        """
        destination = unquote(cast(str, token.attrGet("href") or ""))

        # make the path relative to an "including" document
        # this is set when using the `relative-docs` option of the MyST `include` directive
        relative_include = self.md_env.get("relative-docs", None)
        if relative_include is not None and destination.startswith(
                relative_include[0]):
            source_dir, include_dir = relative_include[1:]
            destination = os.path.relpath(
                os.path.join(include_dir, os.path.normpath(destination)),
                source_dir)

        potential_path = (
            Path(self.doc_env.doc2path(self.doc_env.docname)).parent /
            destination
            if self.doc_env.srcdir  # not set in some test situations
            else None)
        if (potential_path and potential_path.is_file() and not any(
                destination.endswith(suffix)
                for suffix in self.doc_env.config.source_suffix)):
            wrap_node = addnodes.download_reference(
                refdoc=self.doc_env.docname,
                reftarget=destination,
                reftype="myst",
                refdomain=None,  # Added to enable cross-linking
                refexplicit=len(token.children or []) > 0,
                refwarn=False,
            )
            classes = ["xref", "download", "myst"]
            text = destination if not token.children else ""
        else:
            wrap_node = addnodes.pending_xref(
                refdoc=self.doc_env.docname,
                reftarget=destination,
                reftype="myst",
                refdomain=None,  # Added to enable cross-linking
                refexplicit=len(token.children or []) > 0,
                refwarn=True,
            )
            classes = ["xref", "myst"]
            text = ""

        self.add_line_and_source_path(wrap_node, token)
        title = token.attrGet("title")
        if title:
            wrap_node["title"] = title
        self.current_node.append(wrap_node)

        inner_node = nodes.inline("", text, classes=classes)
        wrap_node.append(inner_node)
        with self.current_node_context(inner_node):
            self.render_children(token)
Beispiel #8
0
 def addDownloadsNodes():
     if 'downloads' in self.options:
         blocks.append(nodes.Text('Input:     '))
         for file in self.options['downloads'].split(','):
             download = addnodes.download_reference("", "")
             download += nodes.literal(file, file)
             download['reftarget'] = file
             blocks.append(download)
             blocks.append(nodes.Text('     '))
         blocks.append(nodes.line())
Beispiel #9
0
 def addDownloadsNodes ():
     if 'downloads' in self.options:
         blocks.append(nodes.Text('Input:     '))
         for file in self.options['downloads'].split(','):
             download = addnodes.download_reference("", "")
             download += nodes.literal(file, file)
             download['reftarget'] = file
             blocks.append(download)
             blocks.append(nodes.Text('     '))
         blocks.append(nodes.line())
Beispiel #10
0
def jupyter_download_role(name, rawtext, text, lineno, inliner):
    _, filetype = name.split(":")
    assert filetype in ("notebook", "script")
    ext = ".ipynb" if filetype == "notebook" else ".py"
    output_dir = sphinx_abs_dir(inliner.document.settings.env)
    download_file = text + ext
    node = download_reference(download_file,
                              download_file,
                              reftarget=os.path.join(output_dir,
                                                     download_file))
    return [node], []
Beispiel #11
0
def jupyter_download_role(name, rawtext, text, lineno, inliner):
    _, filetype = name.split(':')
    assert filetype in ('notebook', 'script')
    ext = '.ipynb' if filetype == 'notebook' else '.py'
    output_dir = sphinx_abs_dir(inliner.document.settings.env)
    download_file = text + ext
    node = download_reference(
        download_file, download_file,
        reftarget=os.path.join(output_dir, download_file)
    )
    return [node], []
Beispiel #12
0
    def run(self):
        _, filetype = self.name.split(":")

        assert filetype in ("notebook", "nb", "script")
        ext = ".ipynb" if filetype in ("notebook", "nb") else ".py"
        download_file = self.target + ext
        reftarget = sphinx_abs_dir(self.env, download_file)
        node = download_reference(self.rawtext, reftarget=reftarget)
        self.set_source_info(node)
        title = self.title if self.has_explicit_title else download_file
        node += literal(self.rawtext, title, classes=["xref", "download"])
        return [node], []
 def apply(self, **kwargs):
     for old_node in self.document.traverse(pending_xref):
         if not isfile(join(dirname(old_node.source),
                            old_node['reftarget'])):
             continue
         node1 = nodes.literal('',
                               '',
                               *old_node.children[0].children,
                               classes=['xref', 'download'])
         old_node.replace(old_node.children[0], node1)
         new_node = download_reference(old_node.rawsource, '',
                                       *old_node.children,
                                       **old_node.attributes)
         old_node.parent.replace(old_node, new_node)
Beispiel #14
0
 def make_download_link(self, path):
     node = addnodes.download_reference(
             refdoc=self.state.document.settings.env.docname,
             refdomain='',
             refexplicit=False,
             reftarget=str(path),
             reftype='download',
             refwarn=True,
     )
     node += nodes.literal(
             '', str(path),
             classes=['xref', 'download'],
     )
     return node
Beispiel #15
0
 def make_download_link(self, path):
     node = addnodes.download_reference(
         refdoc=self.state.document.settings.env.docname,
         refdomain='',
         refexplicit=False,
         reftarget=str(path),
         reftype='download',
         refwarn=True,
     )
     node += nodes.literal(
         '',
         str(path),
         classes=['xref', 'download'],
     )
     return node
Beispiel #16
0
 def run(self):
     """Run the role."""
     # get a path relative to the current document
     self.env: BuildEnvironment
     path = Path(self.env.mystnb_config.output_folder).joinpath(  # type: ignore
         *(self.env.docname.split("/")[:-1] + self.target.split("/"))
     )
     reftarget = (
         path.as_posix()
         if os.name == "nt"
         else ("/" + os.path.relpath(path, self.env.app.srcdir))
     )
     node = download_reference(self.rawtext, reftarget=reftarget)
     self.set_source_info(node)
     title = self.title if self.has_explicit_title else self.target
     node += nodes.literal(
         self.rawtext, title, classes=["xref", "download", "myst-nb"]
     )
     return [node], []
Beispiel #17
0
    def run(self):
        self.arguments[0] = "/../samples/" + self.arguments[0]
        self.options["language"] = "php"

        pattern = "[\s+]?(\<\?php.*?]\);)"

        code_block = super(Sample, self).run()[0]
        string = str(code_block[0])

        match = re.match(pattern, string, re.S)
        if match is None:
            return [code_block]

        auth_str = match.group(1).strip()
        main_str = re.sub(pattern, "", string, 0, re.S).strip()

        show_hide_btn = download_reference(reftarget=self.arguments[0])

        return [
            show_hide_btn,
            nodes.literal_block(auth_str, auth_str, language="php"),
            nodes.literal_block(main_str, main_str, language="php"),
        ]
Beispiel #18
0
    def run(self):
        self.arguments[0] = "/../samples/" + self.arguments[0]
        self.options['language'] = 'php'

        pattern = "[\s+]?(\<\?php.*?]\);)"

        code_block = super(Sample, self).run()[0]
        string = str(code_block[0])

        match = re.match(pattern, string, re.S)
        if match is None:
            return [code_block]

        auth_str = match.group(1).strip()
        main_str = re.sub(pattern, "", string, 0, re.S).strip()

        show_hide_btn = download_reference(reftarget=self.arguments[0])

        return [
            show_hide_btn,
            nodes.literal_block(auth_str, auth_str, language="php"),
            nodes.literal_block(main_str, main_str, language="php")
        ]
Beispiel #19
0
 def run(self):
     nodes = super(ShowCode, self).run()
     node = addnodes.download_reference()
     node['reftarget'] = self.arguments[0]
     nodes.append(node)
     return nodes
Beispiel #20
0
 def run(self):
     nodes = super(ShowCode, self).run()
     node = addnodes.download_reference()
     node['reftarget'] = self.arguments[0]
     nodes.append(node)
     return nodes
def replace_sphinx_toolbox_nodes(builder, doctree):
    """
    replace sphinx_toolbox nodes with compatible node types

    Various sphinx_toolbox nodes are pre-processed and replaced with compatible
    node types for a given doctree.

    Args:
        builder: the builder
        doctree: the doctree to replace nodes on
    """

    # allow users to disabled third-party implemented extension changes
    restricted = builder.config.confluence_adv_restricted
    if 'ext-sphinx_toolbox' in restricted:
        return

    if sphinx_toolbox_assets:
        for node in doctree.traverse(sphinx_toolbox_AssetNode):
            # mock a docname based off the configured sphinx_toolbox's asset
            # directory; which the processing of a download_reference will
            # strip and use the asset directory has the container folder to find
            # the file in
            mock_docname = path.join(builder.config.assets_dir, 'mock')
            new_node = addnodes.download_reference(
                node.astext(),
                node.astext(),
                refdoc=mock_docname,
                refexplicit=True,
                reftarget=node['refuri'],
            )
            node.replace_self(new_node)

    if sphinx_toolbox_collapse:
        for node in doctree.traverse(sphinx_toolbox_CollapseNode):
            new_node = confluence_expand(node.rawsource,
                                         title=node.label,
                                         *node.children,
                                         **node.attributes)
            node.replace_self(new_node)

    if sphinx_toolbox_github_issues:
        # note: using while loop since replacing issue nodes has observed to
        #  cause an exception while docutils is processing a doctree
        while True:
            node = first(
                itertools.chain(
                    doctree.traverse(sphinx_toolbox_IssueNode),
                    doctree.traverse(sphinx_toolbox_IssueNodeWithName)))
            if not node:
                break

            if isinstance(node, sphinx_toolbox_IssueNodeWithName):
                title = '{}#{}'.format(node.repo_name, node.issue_number)
            else:
                title = '#{}'.format(node.issue_number)

            new_node = nodes.reference(title, title, refuri=node.issue_url)
            node.replace_self(new_node)

    if sphinx_toolbox_github_repos_and_users:
        for node in doctree.traverse(sphinx_toolbox_GitHubObjectLinkNode):
            new_node = nodes.reference(node.name, node.name, refuri=node.url)
            node.replace_self(new_node)