コード例 #1
0
ファイル: code_blocks.py プロジェクト: wachin/Scripts
def process(value, format):
    [[ident, classes, keyvals], code] = value

    if "graphviz" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        filetype = get_extension(format, "png", html="png", latex="pdf")
        dest = get_filename4code("graphviz", code, filetype)

        if not os.path.isfile(dest):
            import pygraphviz
            g = pygraphviz.AGraph(string=code)
            g.layout()
            g.draw(dest)
            print1('INFO', 'Created image ' + dest + '\n')

        return Para([Image([ident, [], keyvals], caption, [dest, typef])])

    elif "standalone" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        filetype = get_extension(format, "png", html="png", latex="pdf")
        dest = get_filename4code("standalone", code, filetype)
        if not os.path.isfile(dest):
            success = gen_standalone(code, dest)
            if not success:
                return Para(
                    [Str(">>> Error: This image could not be generated.")])
        return Para([Image([ident, [], keyvals], caption, [dest, typef])])

    elif "include" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        keyvalDict = dict(keyvals)

        listing = ''
        with open(keyvalDict['src'], 'r') as f:
            listing = f.read()

        lang = keyvalDict.get('lang', 'python')
        code = 'Failed to find any listing.'
        if 'start' in keyvalDict:
            # Assume that both start and end are line numbers.
            start = int(keyvalDict['start'])
            end = int(keyvalDict['end'])
            code = '\n'.join(listing.split('\n')[start:end])
        elif 'pat' in keyvalDict:
            pat = r'%s' % keyvalDict['pat']
            print1(pat)
            m = re.search(pat, listing, re.DOTALL)
            if m:
                code = m.group(0)
            else:
                code = "Pattern '%s' not found in '%s'" % (pat,
                                                           keyvalDict['src'])
        else:
            code = 'No listing found.'
        return CodeBlock([ident, [], keyvals], code)
コード例 #2
0
ファイル: code_blocks.py プロジェクト: dilawar/Scripts
def process( value, format ):
    [[ident, classes, keyvals], code] = value

    if "graphviz" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        filetype = get_extension(format, "png", html="png", latex="pdf")
        dest = get_filename4code("graphviz", code, filetype)

        if not os.path.isfile(dest):
            import pygraphviz
            g = pygraphviz.AGraph(string=code)
            g.layout()
            g.draw(dest)
            print1('INFO', 'Created image ' + dest + '\n')

        return Para([Image([ident, [], keyvals], caption, [dest, typef])])

    elif "standalone" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        filetype = get_extension(format, "png", html="png", latex="pdf")
        dest = get_filename4code("standalone", code, filetype)
        if not os.path.isfile(dest):
            success = gen_standalone(code, dest)
            if not success:
                return Para([ Str(">>> Error: This image could not be generated.")] )
        return Para([Image([ident, [], keyvals], caption, [dest, typef])])

    elif "include" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        keyvalDict = dict(keyvals)

        listing = ''
        with open( keyvalDict['src'], 'r' ) as f:
            listing = f.read() 

        lang = keyvalDict.get( 'lang', 'python')
        code = 'Failed to find any listing.'
        if 'start' in keyvalDict:
            # Assume that both start and end are line numbers.
            start = int( keyvalDict['start'] )
            end = int( keyvalDict['end'] )
            code = '\n'.join( listing.split('\n')[start:end] )
        elif 'pat' in keyvalDict:
            pat = r'%s' % keyvalDict['pat']
            print1( pat )
            m = re.search( pat, listing, re.DOTALL )
            if m:
                code = m.group(0)
            else:
                code = "Pattern '%s' not found in '%s'" % (pat, keyvalDict['src'])
        else:
            code = 'No listing found.'
        return CodeBlock([ident, [], keyvals], code)
コード例 #3
0
ファイル: blockdiag.py プロジェクト: tex/vimpreviewpandoc
def blockdiag(key, value, fmt, meta):
  if key == 'CodeBlock':
    [[ident,classes,keyvals], code] = value
    found, cmd = isDiag(classes)
    if found == True:
      caption, typef, keyvals = get_caption(keyvals)
      path = os.path.dirname(os.path.abspath(__file__))
      filename = sha1(code)
      src = imagedir + '/' + filename + '.png'
      if not os.path.isfile(src):
        try:
            os.mkdir(imagedir)
        except OSError:
            pass
        tmp = save(code)
        p = subprocess.Popen([cmd, "-a", tmp, "-o", src],
                shell=False, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
        out = p.stdout.read().decode("utf-8")
        err = p.stderr.read().decode("utf-8")
        p.stderr.close()
        if (len(err) > 0):
            return Para([Str(out + " " + err)])
        os.remove(tmp)
      try:
        image = Image([ident, [], keyvals], caption, [src, typef])
        return Para([image])
      except:
        try:
          image = Image(caption, [src, typef])
          return Para([image])
        except:
          pass
コード例 #4
0
def plantuml(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format, "png", html="svg", latex="pdf")

            src = filename + '.puml'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith("@start"):
                    txt = "@startuml\n" + txt + "\n@enduml\n"
                with open(src, "w") as f:
                    f.write(txt)
                with open('plantUMLErrors.log', "w") as outfile:
                    call([
                        "java", "-jar", "filters/plantuml/plantuml.jar",
                        "-t" + filetype, src
                    ],
                         stdout=outfile)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #5
0
def ascii2svg(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "a2s" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("a2s", code)
            typepandoc = get_extension(format, "pdf")
            typea2s = "svg"

            src = filename + '.a2s'
            desta2s = filename + '.' + typea2s

            fontName = ""
            metaMonoFont = meta.get('monofont', None)
            if metaMonoFont:
                fontName = stringify(metaMonoFont['c'])

            if not os.path.isfile(desta2s):
                txt = code.encode(sys.getfilesystemencoding())
                txt = txt.decode('utf-8')
                with open(src, "w") as f:
                    f.write(txt)

                call(['a2s "-f%s" -i%s -o%s' % (fontName, src, desta2s)], shell=True)
                sys.stderr.write('Created image ' + desta2s + '\n')

            return Para([Image([ident, [], keyvals], caption, [desta2s, typef])])
コード例 #6
0
def plantuml(key, value, format_, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format_, "png", html="svg", latex="png")

            src = filename + '.uml'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith(b"@start"):
                    txt = b"@startuml\n" + txt + b"\n@enduml\n"
                with open(src, "wb") as f:
                    f.write(txt)

                subprocess.check_call(PLANTUML_BIN.split() +
                                      ["-t" + filetype, src])
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #7
0
def plantuml(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            sys.stderr.write('>>>>> Dealwith plantuml code in ' +
                             os.path.abspath(os.path.curdir) + '\n')
            sys.stderr.write('value[ident,[classes],[[keyvals]]],format == ' +
                             ident + str(classes) + str(keyvals) + format +
                             '\n')

            caption, typef, keyvals = get_caption(keyvals)
            filename = get_filename4code("plantuml", code)
            for k, v in keyvals:
                if 'title' == k:
                    filename = "plantuml-images/" + v
            filetype = get_extension(format,
                                     "png",
                                     html="svg",
                                     revealjs="svg",
                                     latex="eps")
            sys.stderr.write('filename: ' + filename + '\n')
            sys.stderr.write('filetype: ' + filetype + '\n')

            src = filename + '.uml'
            dest = filename + '.' + filetype

            if os.path.isfile(dest):
                os.remove(dest)

            sys.stderr.write('Creating .uml file: ' + src + '\n')

            if (sys.version.startswith('2')):
                txt = code.encode(sys.getfilesystemencoding())
                # python2:type(code)=unicode; type(txt)=str
            if (sys.version.startswith('3')):
                # txt = code.encode(sys.getfilesystemencoding())
                # python3:type(code)=str;     type(txt)=bytes
                txt = code
            # sys.stderr.write(str(type(code)) + " " + str(type(txt)))

            # Remove any char untile @,
            # because there are some characters like space, 0x10(backspace)... in txt
            txtx = re.sub('^[^@]', '', txt)
            if not txtx.startswith('@start'):
                txt = "@startuml\n" + txt + "\n@enduml\n"
            with open(src, "w") as f:
                f.write(txt)

            sys.stderr.write('Creating image: ' + dest + '\n')
            rootpath = os.path.dirname(os.path.abspath(__file__))
            call([
                "java", "-jar", rootpath + "/plantuml.jar", "-t" + filetype,
                src
            ])
            sys.stderr.write('Created image ' + dest + '\n')

            ret = Para([Image([ident, [], keyvals], caption, [dest, typef])])
            sys.stderr.write('Ret: ' + str(ret) + '\n')
            return ret
コード例 #8
0
def R(key, value, fmt, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], raw_code] = value
        if "r" in classes:
            path = os.path.dirname(os.path.abspath(__file__))
            caption, typef, keyvals = get_caption(keyvals)
            width, keyvals = get_value(keyvals, "width", 7)
            height, keyvals = get_value(keyvals, "height", 7)
            filename = sha1(raw_code + str(width) + str(height))
            src = imagedir + '/' + filename + '.png'
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                except OSError:
                    pass
                code = "ppi <- 100\npng('" + src + \
                        "', width=" + width + "*ppi, height=" + height + "*ppi, res=ppi)\n" + raw_code
                data, err = pipe(["R", "--no-save"], code)
                if (len(err) > 0):
                    return Para([Str(err)])
            try:
                image = Image([ident, [], keyvals], caption, [src, typef])
                return Para([image])
            except:
                try:
                    image = Image(caption, [src, typef])
                    return Para([image])
                except:
                    pass
コード例 #9
0
ファイル: blockdiag.py プロジェクト: jgm/pandocfilters
def blockdiag(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        all_kw = {
            "actdiag", "blockdiag", "nwdiag", "packetdiag", "rackdiag",
            "seqdiag"
        }
        kw = all_kw & set(classes)

        if len(kw) == 1:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("blockdiag", code)
            filetype = get_extension(format, "png", html="svg", latex="pdf")

            src = filename + '.diag'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                cmd = str(list(kw)[0])
                if not code.startswith(cmd):
                    code = cmd + "{\n" + code + "\n}\n"
                with open(src, "w") as f:
                    f.write(code)

                call([cmd, "-a", "-T" + filetype, src])
                sys.stderr.write('Created image (' + cmd + ") " + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #10
0
def plantuml(key, value, fmt, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            path = os.path.dirname(os.path.abspath(__file__))
            filename = sha1(code)
            src = imagedir + '/' + filename + '.png'
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                except OSError:
                    pass
                data, err = pipe(["plantuml", "-pipe", "-Tpng"], code)
                if (len(err) > 0):
                    return Para([Str(err)])
                with open(src, 'wb') as f:
                    f.write(data)
            try:
                image = Image([ident, [], keyvals], caption, [src, typef])
                return Para([image])
            except:
                try:
                    image = Image(caption, [src, typef])
                    return Para([image])
                except:
                    pass
コード例 #11
0
ファイル: ditaa.py プロジェクト: tex/vimpreviewpandoc
def ditaa(key, value, fmt, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "ditaa" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            path = os.path.dirname(os.path.abspath(__file__))
            filename = sha1(code)
            src = imagedir + '/' + filename + '.png'
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                except OSError:
                    pass
                tmp = save(code)
                p = subprocess.Popen(["ditaa", tmp, src],
                                     shell=False,
                                     stdin=subprocess.DEVNULL,
                                     stdout=subprocess.DEVNULL,
                                     stderr=subprocess.PIPE,
                                     close_fds=True)
                err = p.stderr.read().decode("utf-8")
                p.stderr.close()
                if (len(err) > 0):
                    return Para([Str(err)])
                os.remove(tmp)
            try:
                image = Image([ident, [], keyvals], caption, [src, typef])
                return Para([image])
            except:
                try:
                    image = Image(caption, [src, typef])
                    return Para([image])
                except:
                    pass
def mermaid(key, value, format_, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "mermaid" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("mermaid", code)
            filetype = get_extension(format_, "png", html="svg", latex="png")

            src = filename + '.mmd'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                with open(src, "wb") as f:
                    f.write(txt)

                # Default command to execute
                cmd = [MERMAID_BIN, "-i", src, "-o", dest, "-s", SCALE]

                if PUPPETEER_CFG is not None:
                    cmd.extend(["-p", PUPPETEER_CFG])

                if os.path.isfile('.puppeteer.json'):
                    cmd.extend(["-p", ".puppeteer.json"])

                subprocess.check_call(cmd)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #13
0
ファイル: R.py プロジェクト: tex/vimpreviewpandoc
def R(key, value, fmt, meta):
  if key == 'CodeBlock':
    [[ident,classes,keyvals], raw_code] = value
    if "r" in classes:
      path = os.path.dirname(os.path.abspath(__file__))
      caption, typef, keyvals = get_caption(keyvals)
      width, keyvals = get_value(keyvals, "width", 7)
      height, keyvals = get_value(keyvals, "height", 7)
      filename = sha1(raw_code + str(width) + str(height))
      src = imagedir + '/' + filename + '.png'
      if not os.path.isfile(src):
        try:
            os.mkdir(imagedir)
        except OSError:
            pass
        code = "ppi <- 100\npng('" + src + \
                "', width=" + width + "*ppi, height=" + height + "*ppi, res=ppi)\n" + raw_code
        data, err = pipe(["R", "--no-save"], code)
        if (len(err) > 0):
            return Para([Str(err)])
      try:
        image = Image([ident, [], keyvals], caption, [src, typef])
        return Para([image])
      except:
        try:
          image = Image(caption, [src, typef])
          return Para([image])
        except:
          pass
コード例 #14
0
def plantuml(key, value, format_, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format_, "png", html="svg", latex="png")

            src = filename + '.uml'
            dest = filename + '.' + filetype

            # Generate image only once
            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith(b"@start"):
                    txt = b"@startuml\n" + txt + b"\n@enduml\n"
                with open(src, "wb") as f:
                    f.write(txt)

                subprocess.check_call(PLANTUML_BIN.split() +
                                      ["-t" + filetype, src])
                sys.stderr.write('Created image ' + dest + '\n')

            # Update symlink each run
            for ind, keyval in enumerate(keyvals):
                if keyval[0] == 'plantuml-filename':
                    link = keyval[1]
                    keyvals.pop(ind)
                    rel_mkdir_symlink(dest, link)
                    dest = link
                    break

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #15
0
def wavedrom(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "wavedrom" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("wavedrom", code)
            filetype = get_extension(format,
                                     "png",
                                     html5="svg",
                                     html="svg",
                                     latex="eps")

            src = filename + '.json'
            svg = filename + '.svg'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                txt = code

                with open(src, mode="w") as f:
                    f.write(txt)

                subprocess.run(["wavedrompy", "--input", src, "--svg", svg],
                               stdout=subprocess.DEVNULL)
                subprocess.run(["inkscape", "-z", "-e", dest, svg],
                               stdout=subprocess.DEVNULL)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #16
0
ファイル: plantuml.py プロジェクト: tex/vimpreviewpandoc
def plantuml(key, value, fmt, meta):
  if key == 'CodeBlock':
    [[ident,classes,keyvals], code] = value
    if "plantuml" in classes:
      caption, typef, keyvals = get_caption(keyvals)
      path = os.path.dirname(os.path.abspath(__file__))
      filename = sha1(code)
      src = imagedir + '/' + filename + '.png'
      if not os.path.isfile(src):
        try:
            os.mkdir(imagedir)
        except OSError:
            pass
        data, err = pipe(["plantuml", "-pipe", "-Tpng"], code)
        if (len(err) > 0):
            return Para([Str(err)])
        with open(src, 'wb') as f:
          f.write(data)
      try:
        image = Image([ident, [], keyvals], caption, [src, typef])
        return Para([image])
      except:
        try:
          image = Image(caption, [src, typef])
          return Para([image])
        except:
          pass
コード例 #17
0
def plantuml(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes or "puml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            # HTML5を追加
            filetype = get_extension(format, "png", html5="svg", html="svg", latex="eps")

            src = filename + '.uml'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                # エンコード関連をコメントアウト
                # txt = code.encode(sys.getfilesystemencoding())
                # txt = str(code)
                txt = code

                if not txt.startswith("@start"):
                    txt = "@startuml\n" + txt + "\n@enduml\n"

                with open(src, "w") as f:
                    f.write(txt)

                # フィルターと同じディレクトリにplantuml.jarをおいておく
                plantuml_jar = os.path.join(os.path.dirname(__file__) , "plantuml.jar")

                # subprosess.callから変更
                subprocess.run(["java", "-jar", plantuml_jar, "-t"+filetype, src, "-charset", "UTF-8"])
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #18
0
def _get_caption(item, fmt : str):
    captions, typef, keyvals = get_caption(item)
    for caption in captions:
        if caption['c'] is None and caption['c']:
            continue
        caption['t'] = 'RawInline'
        caption['c'] = [fmt, to_format(caption['c'], fmt)]
    # print('Captions: ', captions, 'typef: ', typef, 'keyvals: ', keyvals, file=sys.stderr)
    return captions, typef, keyvals
コード例 #19
0
ファイル: plantuml.py プロジェクト: ccat3z/notebook
def index(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, kvs], contents] = value
        caption, typef, kvs = get_caption(kvs)
        if 'plantuml' in classes and 'embed' in classes:
            return Para([
                Image(
                    [ident, [], kvs],
                    caption,
                    [get_image(contents), typef]
                )
            ])
コード例 #20
0
def plantuml(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format, "png", html="svg", latex="pdf")

            src = filename + '.puml'
            plantuml_output = filename + '.' + filetype

            dest_spec = ""
            # Key to specify final destination the file
            for ind, keyval in enumerate(keyvals):
                if keyval[0] == 'plantuml-filename':
                    dest_spec = keyval[1]
                    keyvals.pop(ind)
                    break

            # Generate image only once
            if not os.path.isfile(plantuml_output):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith(b"@start"):
                    txt = b"@startuml\n" + txt + b"\n@enduml\n"
                with open(src, "wb") as f:
                    f.write(txt)
                # Must not let messages go to stdout, as it will corrupt JSON in filter
                with open('plantUMLErrors.log', "w") as log_file:
                    call([
                        "java", "-jar", "filters/plantuml/plantuml.jar",
                        "-t" + filetype, src
                    ],
                         stdout=log_file)
                sys.stderr.write('Created image ' + plantuml_output + '\n')
                if not dest_spec == "":
                    sys.stderr.write('Copying image from ' + plantuml_output +
                                     ' to ' + dest_spec + '\n')
                    shutil.copy2(plantuml_output, dest_spec)
                    plantuml_output = dest_spec

            for ind, keyval in enumerate(keyvals):
                if keyval[0] == 'hide-image':
                    if keyval[1] == 'true':
                        sys.stderr.write('INFO: Not showing image ' +
                                         plantuml_output + '\n')
                        return []  # surpress image in JSON

            return Para([
                Image([ident, [], keyvals], caption, [plantuml_output, typef])
            ])
コード例 #21
0
def tikz(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "tikz" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            # sys.stderr.write("{};; {};; {}".format(caption, typef, keyvals))
            outfile = get_filename4code("tikz", code)
            filetype = get_extension(format, "svg", html="svg", latex="pdf")
            dest = outfile + '.' + filetype
            if not os.path.isfile(dest):
                tikz2image(code, filetype, outfile)
                sys.stderr.write('Created image ' + dest + '\n')
            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #22
0
ファイル: abc.py プロジェクト: AugustH/pandocfilters
def abc(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "abc" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            outfile = get_filename4code("abc", code)
            filetype = get_extension(format, "png", html="png", latex="pdf")
            dest = outfile + '.' + filetype

            if not os.path.isfile(dest):
                abc2eps(code.encode("utf-8"), filetype, outfile)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #23
0
def abc(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "abc" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            outfile = get_filename4code("abc", code)
            filetype = get_extension(format, "png", html="png", latex="pdf")
            dest = outfile + '.' + filetype

            if not os.path.isfile(dest):
                abc2eps(code.encode("utf-8"), filetype, outfile)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #24
0
ファイル: graphviz.py プロジェクト: AugustH/pandocfilters
def graphviz(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "graphviz" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            filetype = get_extension(format, "png", html="png", latex="pdf")
            dest = get_filename4code("graphviz", code, filetype)

            if not os.path.isfile(dest):
                g = pygraphviz.AGraph(string=code)
                g.layout()
                g.draw(dest)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #25
0
ファイル: code_blocks.py プロジェクト: G48D/mypandoc
def process(value, format):
    [[ident, classes, keyvals], code] = value
    if "graphviz" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        filetype = get_extension(format, "png")
        dest = get_filename4code("graphviz", code, filetype)
        if not os.path.isfile(dest):
            import pygraphviz
            g = pygraphviz.AGraph(string=code)
            g.layout()
            g.draw(dest)
            sys.stderr.write('Created image ' + dest + '\n')

        return Para([Image([ident, [], keyvals], caption, [dest, typef])])

    elif "standalone" in classes:
        caption, typef, keyvals = get_caption(keyvals)
        filetype = get_extension(format, "png", html="png", latex="pdf")
        dest = get_filename4code("standalone", code, filetype)
        if not os.path.isfile(dest):
            gen_standalone(code, dest)
        else:
            print1('[INFO] Image file %s already generated' % dest)
        return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #26
0
def plantuml(key, value, format_, meta):

    if key == 'Header':
        if 'tikz' in (str(meta)):
            os.environ["PLANTUML_LATEX_EXPORT"] = 'latex'

    if key == 'CodeBlock':
        if os.getenv("DEBUG", "f").lower() in ("1", "true"):
            print("plantuml", key, value, format_, meta)

        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            if "PLANTUML_LATEX_EXPORT" in os.environ:
                latex_img_format = "latex"
            else:
                latex_img_format = "eps"

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format_,
                                     "png",
                                     html="svg",
                                     latex=latex_img_format,
                                     beamer=latex_img_format)

            src = filename + '.uml'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith(b"@start"):
                    txt = b"@startuml\n" + txt + b"\n@enduml\n"
                with open(src, "wb") as f:
                    f.write(txt)
                subprocess.check_call(PLANTUML_BIN.split() +
                                      ["-t" + filetype, src])
                sys.stderr.write('Created image ' + dest + '\n')
            if (filetype == "latex") and (latex_img_format == 'latex'):
                latex = open(dest).read()
                return RawBlock(
                    'latex',
                    latex.split("\\begin{document}")[-1].split(
                        "\\end{document}")[0])
            else:
                return Para(
                    [Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #27
0
ファイル: code2img.py プロジェクト: Ynn/xtdgift
def code(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        caption, typef, keyvals = get_caption(keyvals)
        # outfile = get_filename4code("pandoc_code", code)
        # dest = f"{outfile}.png"

        lexer = get_lexer_by_name(classes[0], stripall=True)
        code_img = highlight(code, lexer,
                             ImageFormatter(image_format="PNG", font_size=18))
        # with open(dest, "wb") as f:
        #     f.write(code_img)

        code_img = base64.b64encode(code_img).decode("ascii")
        return RawBlock("html",
                        f'<img src="data:image/png;base64,{code_img}">')
コード例 #28
0
def graphviz(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "graphviz" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            prog, keyvals = get_value(keyvals, u"prog", u"dot")
            filetype = get_extension(format, "svg", html="svg", latex="pdf")
            dest = get_filename4code("graphviz", code, filetype)

            if not os.path.isfile(dest):
                g = pygraphviz.AGraph(string=code)
                g.layout()
                g.draw(dest, prog=prog)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #29
0
def tex2png(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "tex2png" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            filetype = get_extension(format, "png", html="png", latex="pdf")
            dest = get_filename4code("tex2png", code, filetype)
            abs_dest = os.path.abspath(
                os.path.expanduser(os.path.expandvars(dest)))

            if not os.path.isfile(dest):
                # sys.stderr.write('DEBUG code="' + code + '"\n')
                p = subprocess.run(["tex2png.sh", abs_dest],
                                   text=True,
                                   input=code)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #30
0
def plantuml(key, value, format_, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        # print(value)
        # print("caga")
        sys.stderr.write(str(ident))

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            imageFolder = Klasor("den/plantuml")
            filename = get_filename4code(
                'DenemeProje2/webNdocs/static/images/Converted_Pdf', code)
            filetype = get_extension(format_, "png", html="svg", latex="png")

            src = filename + '.uml'
            dest = filename + '.' + filetype
            # print(src)

            # Generate image only once
            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith(b"@start"):
                    txt = b"@startuml\n" + txt + b"\n@enduml\n"
                with open(src, "wb") as f:
                    f.write(txt)

                subprocess.check_call(PLANTUML_BIN.split() +
                                      ["-t" + filetype, src])
                sys.stderr.write('Created image ' + dest + '\n')

            # Update symlink each run
            for ind, keyval in enumerate(keyvals):
                if keyval[0] == 'plantuml-filename':
                    link = keyval[1]
                    keyvals.pop(ind)
                    if os.path.islink(link):
                        os.remove(link)

                    os.symlink(dest, link)
                    dest = link
                    break

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #31
0
ファイル: slide_filter.py プロジェクト: t73fde/slider
 def process_codeblock(
         self,
         value: Tuple[Tuple[str, List[str], Dict[str, str]], str],
         output_format: str, meta: Dict[str, str]) -> Any:
     # pylint: disable=unused-argument
     """Fenced blocks are code blocks."""
     [[ident, classes, keyvals], code] = value
     for diag_class in self.FILTER_CLASSES:
         if diag_class in classes:
             caption, typef, keyvals = get_caption(keyvals)
             if output_format in PANDOC_HTML_FORMATS:
                 _, relpath = self.generate_file(
                     diag_class, code, "svg")
                 image_ref = self.temp_link + relpath
             else:
                 image_ref, _ = self.generate_file(
                     diag_class, code, "png")
             return Para(
                 [Image([ident, [], keyvals], caption, [image_ref, typef])])
     return None
コード例 #32
0
ファイル: mathplotlib.py プロジェクト: simeond/master_thesis
def plantuml(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plot" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plot", code)
            filetype = get_extension(format, "png", html="svg", latex="eps")

            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                src = code.encode(sys.getfilesystemencoding())
                src = src.decode('utf-8')

                df = pd.read_csv(src, skipinitialspace=True, iterator=False)

                # df.plot()
                plt.figure(dpi=None, facecolor="white")
コード例 #33
0
    def get_cb_opts(self, codec):
        'pickup user preferences from code block'
        # also removes imagine class/attributes from code block, by
        # retaining only non-Imagine stuff in self.classes and self.keyvals
        dct = {}
        opts = [x for x in dir(self) if x.startswith('im_')]

        (self.id_, self.classes, self.keyvals), self.code = codec
        self.caption, self.typef, self.keyvals = pf.get_caption(self.keyvals)

        # - remove all Imagine-related classes from codeblock attributes
        self.classes = [k for k in self.classes if k not in self.workers]

        for opt in opts:
            val, self.keyvals = pf.get_value(self.keyvals, opt, None)
            if val: dct[opt] = val

        self.cb_opts = dct
        self.msg(4, "codeblock:", dct)
        return dct
コード例 #34
0
def packetdiag(key, value, format_, _):
    if key != 'CodeBlock':
        return
    [[ident, classes, keyvals], code] = value
    target = set(CLASS_DICT.keys()) & set(classes)
    if len(target) == 0:
        return
    target = list(target)
    code_class = target[0]
    caption, typef, keyvals = get_caption(keyvals)
    filename = get_filename4code(code_class, code)
    src = filename + '.diag'
    dest = filename + '.svg'
    if not os.path.isfile(dest):
        txt = code.encode(sys.getfilesystemencoding())
        with open(src, "wb") as f:
            f.write(txt)
        bin = CLASS_DICT[code_class]
        subprocess.check_call([bin, "-T", "svg", src, "-o", dest])
        sys.stderr.write('Created image ' + dest + '\n')
    return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #35
0
    def __init__(self, codec):
        'init by decoding the CodeBlock-s value'
        # codeblock attributes: {#Identity .class1 .class2 k1=val1 k2=val2}
        self.codec = codec  # save original codeblock for later
        self.stdout = ''  # catches stdout by self.cmd, if any
        self.stderr = ''  # catches stderr by self.cmd, if any

        if codec is None:
            return  # initial dispatch creation

        (self.id_, self.classes, self.keyvals), self.code = codec
        self.caption, self.typef, self.keyvals = pf.get_caption(self.keyvals)

        # `Extract` Imagine keywords/keyvals from codeblock's attributes
        # - also remove any and all Imagine classes
        self.classes = [k for k in self.classes if k not in self.workers]
        self.options, self.keyvals = pf.get_value(self.keyvals, 'im_opt', '')
        self.options = self.options.split()
        self.prog, self.keyvals = pf.get_value(self.keyvals, 'im_prg', None)
        im_out, self.keyvals = pf.get_value(self.keyvals, 'im_out',
                                            self.output)
        self.im_out = im_out.lower().replace(',', ' ').split()
        outfmt, self.keyvals = pf.get_value(self.keyvals, 'im_fmt',
                                            self.outfmt)
        if outfmt in self.available_fmts:
            self.outfmt = outfmt

        # im_prg=cmd key-value trumps .cmd class attribute
        if not self.prog:
            self.prog = self.cmdmap.get(self.klass, None)
        if self.prog is None:
            self.msg(0, self.klass, 'not listed in', self.cmdmap)
            raise Exception('no workers found for %s' % self.klass)

        self.basename = pf.get_filename4code(IMG_BASEDIR, str(codec))
        self.outfile = self.basename + '.%s' % self.outfmt
        self.inpfile = self.basename + '.%s' % self.klass  # _name.lower()

        if not os.path.isfile(self.inpfile):
            self.write('w', self.code, self.inpfile)
コード例 #36
0
def mscgen(key, value, format, _):
    if key == 'CodeBlock':
        (ident, classes, keyvals), code = value
        if "mscgen" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            prog, keyvals = get_value(keyvals, "prog", "mscgen")
            filetype = get_extension(format, PICTURE_FORMAT)
            dest = get_filename4code("mscgen", code, filetype)

            if not os.path.isfile(dest):
                result = subprocess.run(
                    [
                        "mscgen",
                        "-T", "png",
                        "-o", dest,
                        "-",
                    ],
                    input=code.encode(),
                )
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #37
0
def plantuml(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format, "png", html="svg", latex="eps")

            src = filename + '.uml'
            dest = filename + '.' + filetype

            skinparams = [
                "skinparam monochrome true",
                "skinparam shadowing false",
            ]
            metaMonoFont = meta.get('monofont', None)
            if metaMonoFont:
                fontName = stringify(metaMonoFont['c'])
                skinparams.append("skinparam defaultFontName %s" % fontName)

            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                txt = txt.decode('utf-8')
                if not txt.startswith("@start"):
                    params = ""
                    for skinparam in skinparams:
                        params += "%s\n" % skinparam

                    txt = "@startuml\n" + params + txt + "\n@enduml\n"
                with open(src, "w") as f:
                    f.write(txt)

                call(["plantuml.jar -t%s %s" % (filetype, src)], shell=True)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #38
0
ファイル: plantuml.py プロジェクト: AugustH/pandocfilters
def plantuml(key, value, format, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format, "png", html="svg", latex="eps")

            src = filename + '.uml'
            dest = filename + '.' + filetype

            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith("@start"):
                    txt = "@startuml\n" + txt + "\n@enduml\n"
                with open(src, "w") as f:
                    f.write(txt)

                call(["java", "-jar", "plantuml.jar", "-t"+filetype, src])
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, [dest, typef])])
コード例 #39
0
def graphviz(key, value, format, _):
    if key == 'CodeBlock':
        (ident, classes, keyvals), code = value
        if "graphviz" in classes:
            caption, typef, keyvals = get_caption(keyvals)
            prog, keyvals = get_value(keyvals, "prog", "dot")
            filetype = get_extension(format, PICTURE_FORMAT)
            dest = get_filename4code("graphviz", code, filetype)

            if not os.path.isfile(dest):
                result = subprocess.run(
                    [
                        "dot",
                        "-T{}".format(PICTURE_FORMAT),
                        "-Gdpi=300",
                    ],
                    stdout=subprocess.PIPE,
                    input=code.encode(),
                )
                with open(dest, 'wb') as fd:
                    fd.write(result.stdout)
                sys.stderr.write('Created image ' + dest + '\n')

            return Para([Image([ident, [], keyvals], caption, ["/" + dest, typef])])