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
def svg_to_any(key, value, fmt, meta): if key == 'Image': attrs, alt, [src, title] = value mimet, _ = mimetypes.guess_type(src) # option = fmt_to_option.get(fmt, ("--export-pdf", "pdf")) option = fmt_to_option.get(fmt, ("--export-png", "png")) if mimet == 'image/svg+xml' and option: base_name, _ = os.path.splitext(src) eps_name = base_name + "." + option[1] eps_name = eps_name.replace("%20", "") src = src.replace("%20", " ") try: mtime = os.path.getmtime(eps_name) except OSError: mtime = -1 if mtime < os.path.getmtime(src): cmd_line = ['inkscape', option[0], eps_name, src] sys.stderr.write("Running %s\n" % " ".join(cmd_line)) subprocess.call(cmd_line, stdout=sys.stderr.fileno()) return Image(attrs, alt, [eps_name.replace("%20", " "), title])
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) filename = get_filename4code('DenemeProje2/webNdocs/static/images/Converted_Html', 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])])
def plantuml(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value if "plantuml" in classes: title, typef, keyvals = get_title(keyvals) filename = "plantuml-" + get_md5(code) if 'umlformat' in meta: filetype = meta['umlformat']['c'] else: filetype = 'svg' #if filetype != "eps" and filetype != "svg": # sys.stderr.write("Unsupported plantuml format: " + filetype + ". Defaulting to svg.") # filetype = "svg" src = filename + '.uml' dest = filename + '.' + filetype if not os.path.isfile(dest): #txt = code.encode(sys.getfilesystemencoding()) txt = code if not txt.startswith("@start"): txt = "@startuml\n" + txt + "\n@enduml\n" with open(src, "w") as f: f.write(txt) p = Popen(["plantuml", "-t" + filetype, src], stderr=PIPE, stdout=PIPE) (stdout, stderr) = p.communicate() if stderr.decode() != "": sys.stderr.write("WARNING: failed to run plantuml: " + stderr.decode() + "\n") else: sys.stderr.write("Created image %s\n" % dest) #call(["plantuml", "-t"+filetype, src]) #sys.stderr.write('Created image ' + dest + '\n') return Para([Image([ident, [], keyvals], title, [dest, typef])])
def tikz(key, value, format, meta): if key == 'RawBlock': [fmt, code] = value if fmt == "latex" and re.match("\\\\begin{tikzpicture}", code): outfile = imagedir + '/' + sha1(code) if format == "html": filetype = "png" elif format == "latex": filetype = "pdf" else: filetype = "png" src = outfile + '.' + filetype if not os.path.isfile(src): try: os.mkdir(imagedir) sys.stderr.write('Created directory ' + imagedir + '\n') except OSError: pass tikz2image(code, filetype, outfile) sys.stderr.write('Created image ' + src + '\n') return Para([Image([], [src, ""])])
def abc(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value if "abc" in classes: outfile = imagedir + '/' + sha1(code) if format == "html": filetype = "png" elif format == "latex": filetype = "pdf" else: filetype = "png" src = outfile + '.' + filetype if not os.path.isfile(src): try: os.mkdir(imagedir) sys.stderr.write('Created directory ' + imagedir + '\n') except OSError: pass abc2eps(code.encode("utf-8"), filetype, outfile) sys.stderr.write('Created image ' + src + '\n') return Para([Image([], [src, ""])])
def replace_tikz_images(key, val, fmt, meta): ''' Replace tikzpictures with SVGs and change the div format generated by our pandoc fork to match that of images. ''' if (key == 'Div' and 'tikzpicture' in val[0][1] and val[1] and val[1][0] and isinstance(val[1][0], dict) and val[1][0]['t'] == 'RawBlock'): code = val[1][0]['c'][1] if re.match(r'\\begin\{tikzpicture\}', code): prefix = 'tikz-%s' % str(uuid.uuid4()) svg_filename = '%s.svg' % prefix tikz2image(code, prefix) if len(val[1]) > 1: caption = val[1][1]['c'] else: caption = [] return Para([Image(['', [], []], caption, [svg_filename, ''])])
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])])
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) #filetype = get_extension(format, "png", html5="svg", html="svg", latex="eps") filetype = get_extension(format, "png", html5="svg", html="svg", latex="png") 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]) sys.stderr.write('Created image ' + dest + '\n') return Para([Image([ident, [], keyvals], caption, [dest, typef])])
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])])
def remove_caption_filter(key, value, format_, meta): if key == 'Image': """ markdown: ![alt](path "title") json: [[u'', [], []], [{u'c': u'alt', u't': u'Str'}], [u'path', u'fig:title']] """ try: alt = value[1][0].get("c") except IndexError: alt = None value[1] = [] if alt: value[2][1] = u"fig:{}".format(alt) return Image(*value) elif key == "Link": """ markdown: [node](node_api.md) json: [[u'', [], []], [{u'c': u'node', u't': u'Str'}], [u'node_api.md', u'']] """ link_path = value[2][0] if not bool(urlparse.urlparse(link_path).netloc): name, ext = os.path.splitext(link_path) if ext and ext.lower() == ".md": link_name = value[1][0]["c"] if link_name: return RawInline(u'rst', u':doc:`{} <{}>`'.format(link_name, name)) return RawInline(u'rst', u':doc:`{}`'.format(name)) return Link(*value)
def plantuml(key, value, format_, _): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value if "plantuml" in classes: caption, typef, keyvals = _get_caption(keyvals, format_) filename = get_filename4code("plantuml", code) filetype = get_extension(format_, "png", html5="svg", latex="svg", context="svg") 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) # The PlantUML complementary jars (PDF modules) have log messages to stdout that corrupt the JSON stream with open('plantUMLErrors.log', "a+") as log_file: subprocess.check_call(PLANTUML_BIN.split() + ["-t" + filetype, src], stdout=log_file, stderr=log_file) 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 # print('Caption: ', caption, file=sys.stderr) return Para([Image([ident, [], keyvals], caption, [dest, typef])])
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 if not txt.startswith("@start"): txt = "@startuml\n" + txt + "\n@enduml\n" with open(src, "w") as f: f.write(txt) call(["java", "-jar", sys.argv[1], "-t" + filetype, src]) sys.stderr.write('Created image ' + dest + '\n') return Para([Image([ident, [], keyvals], caption, [dest, typef])])
def wrapfig(key, val, fmt, meta): if key == 'Image': attrs, caption, target = val if FLAG_PAT.match(stringify(caption)): # Strip tag size = FLAG_PAT.match(caption[-1]['c']).group(1) stripped_caption = caption[:-2] if fmt == 'latex': latex_begin = r'\begin{wrapfigure}{r}{' + size + 'in}' if len(stripped_caption) > 0: latex_fig = r'\centering\includegraphics{' + target[0] \ + '}\caption{' latex_end = r'}\end{wrapfigure}' return [RawInline(fmt, latex_begin + latex_fig)] \ + stripped_caption + [RawInline(fmt, latex_end)] else: latex_fig = r'\centering\includegraphics{' + target[0] \ + '}' latex_end = r'\end{wrapfigure}' return [RawInline(fmt, latex_begin + latex_fig)] \ + [RawInline(fmt, latex_end)] else: return Image(attrs, stripped_caption, target)
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, "png", html="png", latex="pdf") dest = get_filename4code("graphviz", code, filetype) filename = "" for a,fname in keyvals: if(a == "filename"): valid_chars = "-_ %s%s" % (string.ascii_letters, string.digits) fname = ''.join(x for x in fname if x in valid_chars) if fname != "": filename = "graphviz-images/"+fname+"."+filetype dest = filename if (filename != "") or (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])])
def graphviz(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value dic = dict(keyvals) caption = "caption" if "graphviz" in classes: if format == "html": filetype = "png" elif format == "beamer": filetype = "pdf" elif format == "latex": filetype = "pdf" else: filetype = "png" G = pygraphviz.AGraph(string=cpp(code, filetype)) G.layout() filename = sha1(code) alt = Str(caption) src = imagedir + '/' + filename + '.' + filetype if not os.path.isfile(src): try: os.mkdir(imagedir) sys.stderr.write('Created directory ' + imagedir + '\n') except OSError: pass G.draw(src, prog=('dot' if 'prog' not in dic else dic['prog'])) sys.stderr.write('Created image ' + src + '\n') tit = "" if format in ['html', 'html5']: return Para([Image([alt], [src, tit])]) else: width = dic['width'] if 'width' in dic else '0.5' height = dic['height'] if 'height' in dic else '0.5' #str = "\\includegraphics[width=%s\\maxwidth,height=%s\\maxheight]{%s}" str ="\\includegraphics[width=%s\\linewidth,height=%s\\textheight,keepaspectratio]{%s}" \ % (width, height, src) return Para([RawInline("tex", str)])
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(" ".join([ "java", "-jar", PLANTUML_BIN, "-charset utf-8", "-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])])
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 graphviz_class in ["dot", "neato", "twopi", "circo", "fdp"]: if graphviz_class in classes: caption, typef, keyvals = get_caption(keyvals) if output_format in PANDOC_HTML_FORMATS: _, relpath = self.generate_file( graphviz_class, code, "svg") image_ref = self.temp_link + relpath else: image_ref, _ = self.generate_file( graphviz_class, code, "png") return Para( [Image([ident, [], keyvals], caption, [image_ref, typef])]) if "graphviz" in classes: new_classes = [ "dot" if cls == "graphviz" else cls for cls in classes] return CodeBlock([ident, new_classes, keyvals], code) return None
def ditaa(key, value, format, _): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value if "ditaa" in classes: caption, typef, keyvals = get_caption(keyvals) filename = get_filename4code("ditaa", code) filetype = get_extension(format, "png", html="svg", latex="eps") src = filename + '.txt' dest = filename + '.' + filetype if not os.path.isfile(dest): with open(src, "w") as f: f.write(code) call(["java", "-jar", "ditaa.jar", src]) pprint.pprint([ 'Created image ', dest, 'typef=', typef, 'ident=', ident, 'keyvals=', keyvals, 'caption=', caption ], sys.stderr) return Para([Image([ident, [], keyvals], caption, [dest, typef])])
def textohtml(key, value, format, meta): if key == 'RawInline': fmt, s = value if fmt == "tex": for x in trans: m = x['re'].match(s) if m: return [ Span(attributes({'class': x['class']}), [ Str(x['cont'] if x['key'] == 'Str' else m.group(x['cont'])) ]), Space() ] if cboxStart.match(s): return RawInline("html", "<span class='cbox'>") if cboxEnd.match(s): return RawInline("html", "</span>") if image.match(s): m = image.match(s) # return Image([Str("description")], [m.group(1),""]) # works only for pandocfilters < 1.3.0 return Image( ['', [], []], [Str("description")], [m.group(1), ""]) # should work for pandocfilter >= 1.3.0
def graphviz(key, value, format, _): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value if "graph" 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(document_name(), code, filetype) # If name attribute exists, overwrite standard filename for eachKeys in keyvals: if 'name' in eachKeys[0]: filename = "graph-images/" + eachKeys[1][:-4] dest = filename + '.' + 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') image = Image([ident, classes, keyvals], caption, [dest, typef]) return Para([image])
def filter(key, value, format, meta): global base_url, version global count if key == 'Math': # grab equation par = False if value[0]['t'] == 'InlineMath': formula = '$' + value[1] + '$' caption = value[1] else: par = True formula = r'\begin{align*}' + value[1] + r'\end{align*}' caption = '' # typeset formula count += 1 latex(formula, count) # replace by image return Image(['', [], []], [Str(caption)], [base_url + version + '/eqn_{}.png'.format(count), ''])
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", beamer="eps") 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])])
def gabc(key, value, fmt, meta): # pylint:disable=I0011,W0613 """Handle gabc file inclusion and gabc code block.""" if key == 'Code': [[ident, classes, kvs], contents] = value # pylint:disable=I0011,W0612 kvs = {key: value for key, value in kvs} if "gabc" in classes: staffsize, initiallines = properties(meta) if fmt == "latex": if ident == "": label = "" else: label = '\\label{' + ident + '}' return latex( "\n\\smallskip\n{%\n" + latexsnippet( '\\gregorioscore{' + contents + '}', kvs, staffsize, initiallines ) + "%\n}" + label ) else: infile = contents + ( '.gabc' if '.gabc' not in contents else '' ) with open(infile, 'r') as doc: code = doc.read().split('%%\n')[1] return [Image(['', [], []], [], [ png( contents, latexsnippet( '\\gregorioscore', kvs, staffsize, initiallines ) ), "" ])] elif key == 'CodeBlock': [[ident, classes, kvs], contents] = value kvs = {key: value for key, value in kvs} if "gabc" in classes: staffsize, initiallines = properties(meta) if fmt == "latex": if ident == "": label = "" else: label = '\\label{' + ident + '}' return [latexblock( "\n\\smallskip\n{%\n" + latexsnippet( '\\gabcsnippet{' + contents + '}', kvs, staffsize, initiallines ) + "%\n}" + label )] else: return Para([Image(['', [], []], [], [ png( contents, latexsnippet( '\\gabcsnippet', kvs, staffsize, initiallines ) ), "" ])])
def repl_path(key, value, format, meta): if key == 'Image': alt, [src, tit] = value return Image(alt, [PATH_HASH + src, tit])
def process_images(key, val, fmt, meta): """Runs through figures in the document, counting figures of a particular type. For LaTeX, adds appropriate code for non-"figure" environments and leaves normal figures untouched (\label commands are added automatically already). If the wwidth attribute is passed to the figure, hardcodes the appropriate LaTeX code for the wrapfig package through the wrapfloat environment. For other formats, adds preamble to caption with figure type and number. """ if key == 'Image': attrs, caption, target = val if attrs[1] and caption: cls = attrs[1][0] # Class attribute for the image if cls in known_classes: known_classes[cls] += 1 else: known_classes[cls] = 1 # Assign figure/scheme/chart/graph number. known_ids[attrs[0]] = str(known_classes[cls]) # Loop through image attributes to locate wrapfig-relevant # attributes. If found, set latex_wrap to True and read # size and position (optional). latex_wrap = False latex_wrap_pos = 'r' # Default position latex_fig_place = False latex_suffix = "" for other_atr in attrs[2]: if other_atr[0] == 'wwidth': latex_wrap = True latex_size = other_atr[1] elif other_atr[0] == 'wpos': latex_wrap_pos = other_atr[1] elif other_atr[0] == 'lpos': latex_fig_place = True latex_fig_place_pos = other_atr[1] elif other_atr[0] == 'lts': latex_suffix = other_atr[1] if fmt in ['latex', 'pdf']: # Only use "\caption" command if caption is not empty. if caption != []: caption_text = ([RawInline(fmt, r"\caption{")] + caption + [RawInline(fmt, r"}")]) else: caption_text = [] if latex_wrap: return ([ RawInline( fmt, textwrap.dedent(r""" \begin{{wrapfloat}}{{{cls}}}{{{pos}}}{{{size}}} \centering \includegraphics{{{file}}} """.format(cls=cls + latex_suffix, file=target[0], size=latex_size, pos=latex_wrap_pos))) ] + caption_text + [ RawInline( fmt, textwrap.dedent(r""" \label{{{id_tag}}} \end{{wrapfloat}} """.format(cls=cls + latex_suffix, id_tag=attrs[0]))) ]) elif latex_fig_place: return ([ RawInline( fmt, textwrap.dedent(r""" \begin{{{cls}}}[{pos}] \centering \includegraphics{{{file}}}""".format( cls=cls + latex_suffix, pos=latex_fig_place_pos, file=target[0]))) ] + caption_text + [ RawInline( fmt, textwrap.dedent(r""" \label{{{id_tag}}} \end{{{cls}}} """.format(cls=cls + latex_suffix, id_tag=attrs[0]))) ]) else: return ([ RawInline( fmt, textwrap.dedent(r""" \begin{{{cls}}} \centering \includegraphics{{{file}}}""".format( cls=cls + latex_suffix, file=target[0]))) ] + caption_text + [ RawInline( fmt, textwrap.dedent(r""" \label{{{id_tag}}} \end{{{cls}}} """.format(cls=cls + latex_suffix, id_tag=attrs[0]))) ]) else: # Add label to caption for non-LaTeX output. # Default labels, suffix, and format label = [Strong([Str(cls.capitalize() + " ")])] suffix = [Strong([Str(". ")])] if 'fig-abbr' in meta: if cls in meta['fig-abbr']['c']: label = meta['fig-abbr']['c'][cls]['c'] if 'suffix' in meta['fig-abbr']['c']: suffix = meta['fig-abbr']['c']['suffix']['c'] # Label takes format of abbreviation. if label[0]['t'] == 'Strong': number = [Strong([Str(known_ids[attrs[0]])])] elif label[0]['t'] == 'Emph': number = [Emph([Str(known_ids[attrs[0]])])] else: number = [Str(known_ids[attrs[0]])] new_caption = label + number + suffix + caption return Image(attrs, new_caption, target)
def process_image(key, value, oformat, meta): r''' Rewrite filename in Image AST object--adding paths from the meta information and/or LaTeX `\graphicspaths` directive. This can be used to reassign paths to image file names when the meta information has only one entry. It will also wrap LaTeX-labeled Image objects in a Span--for later referencing/linking, say. ''' if key != "Image": return None global figure_dirs, fig_fname_ext, processed_figures # TODO: Find and use labels. # TODO: Perhaps check that it's a valid file? new_value = copy(value[2]) new_fig_fname = rename_find_fig(new_value[0], figure_dirs, fig_fname_ext) pandoc_logger.debug("figure_dirs: {}\tfig_fname_ext: {}\n".format( figure_dirs, fig_fname_ext)) pandoc_logger.debug("new_value: {}\tnew_fig_fname: {}\n".format( new_value, new_fig_fname)) # XXX: Avoid an endless loop of Image replacements. if new_fig_fname in processed_figures.keys(): return None processed_figures[new_fig_fname] = [None, None] new_value[0] = new_fig_fname # Wrap the image in a div with an `id`, so that we can # reference it in HTML. new_image = Image(value[0], value[1], new_value) wrapped_image = new_image try: fig_label_obj = value[1][-1]['c'][0][-1][0] pandoc_logger.debug("fig_label_obj: {}\n".format(fig_label_obj)) if fig_label_obj[0] == 'data-label': fig_label = fig_label_obj[1] processed_figures[new_fig_fname][0] = fig_label env_num = len(processed_figures) processed_figures[new_fig_fname][1] = env_num hack_span = label_to_mathjax(fig_label, env_tag=env_num) wrapped_image = Span([copy(fig_label), [], []], [hack_span, new_image]) except: pass pandoc_logger.debug("wrapped_image: {}\n".format(wrapped_image)) return [wrapped_image]
def img_to_zoomable_link(key, value, format, meta): # I'm not really sure what 'format' and 'meta' are. # 'key' is a string telling you what kind of element you're processing, and # 'value' is some JSON list/object/something, depending on what 'key' is. # print("Hello world from pandoc filter!") # NO: stdout kills pandoc, since it's stream-based. Use stderr instead. # sys.stderr.write("key: {}\n".format(key)) # sys.stderr.write("value: {}\n".format(value)) if key != 'Image': return None # no processing required sys.stderr.write("Running img-to-zoomable-link.py\n") # sys.stderr.write("key: {}\n".format(key)) # sys.stderr.write("value: {}\n".format(value)) (identifier, classes, img_attributes), alt_text_shit, (img_path, img_caption) = value # sys.stderr.write("identifier: {}\n".format(identifier)) # sys.stderr.write("alt_text_shit: {}\n".format(alt_text_shit)) # sys.stderr.write("img_path: {}\n".format(img_path)) # sys.stderr.write("img_caption: {}\n".format(img_caption)) # replacement = Code(['', [], []], 'ls -l') # works # replacement = Image( ("",[],[("width","200px")]), [],[img_path,"fig:blah"] ) # works # replacement = Link( ("",[],[]), ["click","here!"], ["http://google.com",""] ) # no # replacement = Link( ["",[],[]], ["click","here!"], ["http://google.com",""] ) # no # replacement = Link( ["",[],[]], [Str('Click here!')], ["http://google.com",""] ) # yes # replacement = Link( ["",[],[]], [Image( ("",[],[("width","200px")]), [],[img_path,"fig:blah"] )], [img_path,""] ) # yes # replacement = Para([Code(['', [], []], 'ls -lt')]) # no # replacement = Code(['', [], []], 'ls -lt') # yes # replacement = Para([Str('wtf!!')]) # no # replacement = Para([Image(['', [], []], [], [img_path, ""])]) # no: can't wrap an img in a para, recursion error. replacement = Link( ["", [], [("onclick", "return hs.expand(this)")]], [Image(("", [], [("width", "400px")]), [], [img_path, "fig:blah"])], [img_path, ""]) # sys.stderr.write("replacement: {}\n".format(replacement)) # target = strip_universal_leading_whitespace(target) # Create the Pandoc block element that will replace the code block. # (Note: Pandoc distinguishes between "inline" elements and "block" elements, # and gives some sort of "no such element" error if you return an inline when it expects a block.) # I'm going to make a bulleted list. (Each bullet is itself a list of Pandoc block elements.) # bullet_points = [ # [Para([Code(['', [], []], 'ls -l')]), # CodeBlock(['', [], []], '...\noutput\n...')], # [Para([Code(['', [], []], 'ls -lt')]), # CodeBlock(['', [], []], '...\nmore output\n...')]] # replacement = BulletList(bullet_points) return replacement
def pandoc_wmftosvgpng(key, value, format, meta): if key == 'Image': if len(value) == 2: # before pandoc 1.16 alt, [src, title] = value attrs = None else: attrs, alt, [src, title] = value mediainfopath = os.environ['pandoc_mapmedia_info'] mediainfo = json.load(file(mediainfopath)) srcfolder = mediainfo['srcfull'] dstfolder = mediainfo['dstfull'] srcsubstr = mediainfo['srcsubstr'] dstsubstr = mediainfo['dstsubstr'] mediamap = mediainfo['map'] keepdim = mediainfo.get('keepdim', False) newsrc = src srcfn = os.path.basename(src) mapfn = mediamap.get(srcfn, srcfn) dstfn = mapfn dstbase, dstext = os.path.splitext(mapfn) prefix = mediainfo['prefix'] newbase = dstbase[5:].zfill(4) suffix = "" altstr = "" if alt: if len(alt) > 0: for e in alt: if e[u't'] == u'Str': altstr += e[u'c'].encode('ascii', 'ignore') elif e[u't'] == u'Space': altstr += ' ' altstr = ExtractAlphanumeric(altstr)[-30:] suffix = "_" + altstr dstfn = prefix + "_" + newbase + suffix + dstext if altstr: altstr = prefix + "_" + altstr else: altstr = prefix + "_" + newbase alt = [{u'c': unicode(altstr), u't': u'Str'}] if not title: title = unicode(altstr) newsrc = os.path.join(dstsubstr, dstfn) srcpath = os.path.join(srcfolder, mapfn) dstpath = os.path.join(dstfolder, dstfn) if os.path.exists(dstpath): os.remove(dstpath) shutil.copyfile(srcpath, dstpath) src = unicode(newsrc) if attrs and not keepdim: attrs[2] = [] # Remove image dimensions if attrs: return Image(attrs, alt, [src, title]) else: return Image(alt, [src, title])
def pandoc_wmftosvgpng(key, value, format, meta): """ Args: key (): value (): format (): meta (): Returns: pandocfilters.Image() """ if key == 'Image': attrs, alt, [src, title] = value mediainfopath = os.environ.get('pandoc_filter_mapmedia', None) if not mediainfopath: return Image(attrs, alt, [src, title]) mediainfo = json.load(file(mediainfopath)) srcfolder = mediainfo['srcfull'] dstfolder = mediainfo['dstfull'] srcsubstr = mediainfo['srcsubstr'] dstsubstr = mediainfo['dstsubstr'] mediamap = mediainfo['map'] newsrc = src srcfn = os.path.basename(src) mapfn = mediamap.get(srcfn, srcfn) dstfn = mapfn dstbase, dstext = os.path.splitext(mapfn) prefix = mediainfo['prefix'] newbase = dstbase[5:].zfill(4) suffix = "" altstr = "" if alt: altstr = stringify(alt) altstr = extractAlphanumeric(altstr)[-30:] suffix = "_" + altstr dstfn = prefix + "_" + newbase + suffix + dstext if altstr: altstr = prefix + "_" + altstr else: altstr = prefix + "_" + newbase alt = [Str(altstr)] if not title: title = unicode(altstr) newsrc = os.path.join(dstsubstr, dstfn) srcpath = os.path.join(srcfolder, mapfn) dstpath = os.path.join(dstfolder, dstfn) if os.path.exists(dstpath): os.remove(dstpath) shutil.copyfile(srcpath, dstpath) src = unicode(newsrc) return Image(attrs, alt, [src, title])