Exemple #1
0
def main():
    toJSONFilters([
        remove_includes,
        promote_and_capitalize_sections,
        demote_net_core_1_2,
        remove_references,
    ])
def main():
    toJSONFilters([
        remove_includes,
        promote_and_capitalize_sections,
        demote_net_core_1_2,
        remove_references,
    ])
Exemple #3
0
def main():
    toJSONFilters([
        fail_on_includes,
        promote_and_capitalize_sections,
        demote_net_core_1_2,
        fix_space_in_command_names,
        remove_markers,
    ])
def main():
    toJSONFilters([process_images, parse_refs])
Exemple #5
0
#! /usr/bin/env python3

from pandocfilters import toJSONFilters
from codimd.containers import containers
from codimd.crossrefs import crossrefs
from codimd.emojis import emojis
from codimd.images import images

from extern import graphviz, plantuml


if __name__ == '__main__':
    toJSONFilters([ containers, crossrefs, emojis, images, graphviz, plantuml ])

Exemple #6
0
import sys
import re
import os


def processCustomImageSize(key, value, _format, _meta):
    if key == "Image":
        [attrs, _inline, _target] = value
        width = height = cw = ch = None
        for attr in attrs[2]:
            if attr[0] == 'width':
                width = attr[1]
            if attr[0] == 'height':
                height = attr[1]
            if attr[0] == 'cw':
                cw = attr[1]
            if attr[0] == 'ch':
                ch = attr[1]
        if not width and not height:
            if cw or ch:
                newAttrs = []
                if cw:
                    newAttrs.append(['width', cw])
                if ch:
                    newAttrs.append(['height', ch])
                attrs[2] = newAttrs


if __name__ == "__main__":
    toJSONFilters([processCustomImageSize])
Exemple #7
0
def main():
    toJSONFilters([environment])
def main():
    toJSONFilters([environment])
Exemple #9
0
def main():
    toJSONFilters([
        fail_on_includes,
        promote_and_capitalize_sections,
        demote_net_core_1_2,
    ])
Exemple #10
0
def main():
    # Starts the numbering at 1
    header_numbering.count = 1
    toJSONFilters([header_numbering])
Exemple #11
0
        urlOrPath = v[2][0]
        if 'http' in urlOrPath:
            url = urlOrPath
            path = download_image_from_url(url)
            log("[INFO ] Replacing url %s with downloaded file %s" %
                (url, path))
            v[2][0] = path
            return Image(*v)


def image_with_standalone(k, v, fmt, meta):
    if k == 'Image':
        desc = v[2][0]
        if r'\documentclass' in desc:
            code = desc
            outfile = get_filename4code("tikz", code)
            filetype = get_extension(format, "png", html="png", latex="pdf")
            src = outfile + '.' + filetype
            if not os.path.isfile(src):
                tikz2image(code, filetype, outfile)
            return Para([Image(['', [], []], [], [src, ""])])


if __name__ == "__main__":
    toJSONFilters([
        image_with_url, image_with_standalone, comment, theorem.theorems,
        code_blocks.codeblocks
        # This one is fragile.
        #  , table.do_filter
    ])
Exemple #12
0
		-f native \
		--filter ./unmathsub.py \
		--reference-docx ref.docx
		-o output.docx
'''

from pandocfilters import toJSONFilters, Str, Subscript, Superscript

def unmathsub(key, value, format, meta):
	if (key == 'Math'
		and len(value) == 2
		and '_{' in (x[:2] for x in value if isinstance(x, str))
		and 'InlineMath' in (x['t'] for x in value if 't' in x)):
			for x in value:
				if isinstance(x, str):
					x = Str(x.split('_{')[1].split('}')[0])
					return Subscript([x])

def unmathsup(key, value, format, meta):
	if (key == 'Math'
		and len(value) == 2
		and '^{' in (x[:2] for x in value if isinstance(x, str))
		and 'InlineMath' in (x['t'] for x in value if 't' in x)):
			for x in value:
				if isinstance(x, str):
					x = Str(x.split('^{')[1].split('}')[0])
					return Superscript([x])

if __name__ == "__main__":
    toJSONFilters([unmathsub, unmathsup])
Exemple #13
0
    if code[right] == '}' and code[right-1] != '\\':
      count -= 1
    elif code [right] == '{' and code[right-1] != '\\':
      count += 1

    if count < 0:
      rightEnd = right
      break

    right += 1
  
  rightStr = code[rightStart:rightEnd+1]
  if count < 0:
    rightStr = '{' + rightStr
  else:
    rightStr = '{' + rightStr + '}'

  # print(code[leftStart:leftEnd+1])
  # print(leftStr)
  # print(code[rightStart:rightEnd+1])
  # print(rightStr)

  if count < 0:
    return code[:leftStart]+'{'+'\\frac'+leftStr+rightStr+'}'+code[rightEnd+1:]
  else:
    return code[:leftStart]+'\\frac'+leftStr+rightStr+code[rightEnd+1:]


if __name__ == "__main__":
  toJSONFilters([processImage, processImageInTable, processMathTag, processMathOverToFrac, processMathDoubleBackslash])
Exemple #14
0
def main():
    toJSONFilters([collect, listof])
Exemple #15
0
def main():
    pandocfilters.toJSONFilters([filter_env])
Exemple #16
0
        return pf.Div(attr, [table])

    return None


# Interpret -- as an em-dash in html, unless it is between two words
# (without blanks), in which case it is interpreted as an en-dash
def html_dashes(key, value, fmt, meta):
    def fix_dash(s):
        s = re.sub('([^ ])--([^ ])', '\\1&ndash;\\2', s)
        s = s.replace('--', '&mdash;')
        return s

    if key == 'Str' and fmt == 'html':
        return pf.RawInline(fmt, fix_dash(value))
    elif key == 'RawInline' and fmt == 'html':
        return pf.RawInline(value[0], fix_dash(value[1]))
    else:
        return None

if __name__ == '__main__':
    pf.toJSONFilters([bidding_divs,
                      inline_hands,
                      block_hands,
                      block_bids,
                      suit_symbols,
                      html_dashes])

# pandoc src\defence.md --filter bridge.py -H bridge-header.tex -o defence.pdf
# cat src\onent.md | sed "s/--/\&mdash;/g" | pandoc --filter bridge.py -o onent.htm -H base.html
Exemple #17
0
# def wideTables(key, value, format, meta):
#   if key == 'Table' and format == 'latex':
#     p("hellllllllllllllo")
#     p(json.dumps(value))
#     # if stringify(value[0]) == ":wide":
#     #   p("IT IS WIDE")
#     #   # return value
#     #   # p(json.dumps([latex("\\hspace{-2cm}\\begin{minipage}[c]{1.3\\linewidth}")] + [Str("HELLO")] + [latex("\\end{minipage}")]))
#     return  [latex("\\begin{"       + "minipage" +"}")] + value + [latex("\\end{"+ "minipage" +"}")]


def hmmmm(key, value, format, meta):
    p(json.dumps(key))
    if key == 'Header' and format == 'latex':
        value[1][0] = ''
        p(json.dumps(value))
    #   p("hellllllllllllllo")
    # # if stringify(value[0]) == ":wide":
    # #   p("IT IS WIDE")
    # #   # return value
    # #   # p(json.dumps([latex("\\hspace{-2cm}\\begin{minipage}[c]{1.3\\linewidth}")] + [Str("HELLO")] + [latex("\\end{minipage}")]))
    # return  [latex("\\begin{"       + "minipage" +"}")] + value + [latex("\\end{"+ "minipage" +"}")]


filters = [titlizeHeadings, noteQuote, commentQuote, hmmmm]

if __name__ == "__main__":
    toJSONFilters(filters)
    debugFile.close()
Exemple #18
0
            if val is not None:
                changed = True
                new_values.append(val)
            else:
                new_values.append(link_string)
        if changed:
            return Link(link_info, new_texts, new_values)
        return None

    def process_str(
            self,
            value: str,
            output_format: str,
            meta: Dict[str, Dict[str, Any]]) -> Any:
        # pylint: disable=unused-argument
        """Process all string elements."""
        val = self.replace_metavar(value, meta, self._metavar_pattern_text)
        return Str(val) if val is not None else None


if __name__ == '__main__':
    TEMP_DIR = os.environ["SLIDER_TEMPDIR"]
    TEMP_LINK = os.environ["SLIDER_TEMPLINK"]
    toJSONFilters([
        MetaVarFilter(),
        GermanQuotesFilter(),
        GraphvizFilter(TEMP_DIR, TEMP_LINK),
        BlockdiagFilter(TEMP_DIR, TEMP_LINK),
        SvgFilter(TEMP_DIR, TEMP_LINK),
    ])
Exemple #19
0
    global incomment
    if k == 'RawBlock':
        fmt, s = v
        if fmt == "html":
            if re.search("<!-- BEGIN COMMENT -->", s):
                incomment = True
                return []
            elif re.search("<!-- END COMMENT -->", s):
                incomment = False
                return []
    if incomment:
        return []  # suppress anything in a comment


def image_with_url(k, v, fmt, meta):
    if k == 'Image':
        urlOrPath = v[2][0]
        if 'http' in urlOrPath:
            url = urlOrPath
            path = download_image_from_url(url)
            log("[INFO ] Replacing url %s with downloaded file %s" %
                (url, path))
            v[2][0] = path
            return Image(*v)


if __name__ == "__main__":
    toJSONFilters([
        image_with_url, comment, theorem.theorems, tikz, code_blocks.codeblocks
    ])
Exemple #20
0
    assert format == 'html'
    if key == 'Link':
        attr, inlines, target = value
        url, title = target
        src, _, ratio = url.rpartition('::')
        _, ext = splitext(src)
        if ext == '.pdf' and ratio in ('16by9', '4by3'):
            src = media(src)
            return pf.RawInline(
                format,
                dedent(f'''\
            <div class="embed embed-{ratio}">
                <iframe src="{src}"
                        type="application/pdf"
                        allowfullscreen>
                <a href="{src}">{src}</a>
                </iframe>
            </div>
            '''))


# =============================================================================

if __name__ == '__main__':
    pf.toJSONFilters(
        filter(None, [
            handle_debug if DEBUG else None,
            handle_image,
            handle_pdf,
        ]))
Exemple #21
0
#!/usr/bin/env python

from pandocfilters import toJSONFilters, Str, Link, Header


def headinglinks(k, v, fmt, meta):
    if k == "Header":
        #[level, attrs, contents] = v
        #return Header(level, attrs, [ Link([], contents, [attrs[0]]) ])
        return Header()


if __name__ == "__main__":
    toJSONFilters(headinglinks)
Exemple #22
0
    if format != 'beamer':
        return

    if key == 'Header':
        level, meta, contents = value
        # Add the attribute
        meta[1].append('fragile')
        return Header(level, meta, contents)


def minted(key, value, format, meta):
    """Use minted for code in LaTeX."""
    if format != 'latex' and format != 'beamer':
        return

    if key == 'CodeBlock':
        template = Template('\\begin{minted}[$attributes]{$language}\n$contents\n\end{minted}')
        Element = RawBlock
    elif key == 'Code':
        template = Template('\\mintinline[$attributes]{$language}{$contents}')
        Element = RawInline
    else:
        return

    text = template.substitute(unpack_code(value))
    return Element('latex', text)


if __name__ == '__main__':
    toJSONFilters([fragile, minted])
Exemple #23
0
    elif key == 'Para':
        if value[0]['t'] == 'RawInline':
            fmt, content = value[0]['c']
            if fmt == 'html' and '<img' in content:
                src = re.search(r'src="(img/.+?)"', content).group(1)
                cls = re.search(r'class="(.+?)"', content)
                if cls:
                    cls = cls.group(1)
                width = re.search(r'style="width: *(\d+)%;?', content)
                if width:
                    width = float(width.group(1)) / 100
                return mkFigure(src, align=cls, scale=width)
            elif fmt == 'html' and 'class="caption"' in content:
                return [Para(value), RawBlock('latex', r'\vspace{1em}')]
            elif fmt == 'html' and 'class="filename"' in content:
                return [RawBlock('latex', r'\vspace{1em}'), Para(value)]


def filter1(key, value, fmt, meta):
    if key == 'RawBlock' and value[0] == 'header-json':
        value = json.loads(value[1])
        [level, _, _] = value
        if level == 1:
            file_name = os.getenv('FILENAME', "FILE_DOES_NOT_EXIST")
            value[1][0] = file_name
        return {'t': 'Header', 'c': value}


if __name__ == "__main__":
    toJSONFilters((filter, filter1))
Exemple #24
0
#! /usr/bin/env python

from __future__ import print_function

import mimetypes
import subprocess
import os
import sys
import re
from pandocfilters import toJSONFilters, RawBlock, Header, Image

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def headers(key, value, fmt, meta):
    if key == 'Header' and value[0] == 1 and not re.match('Chapter|Disclaimer',value[2][0]['c'].encode('ascii','ignore')):
        return [Header(value[0]+1, value[1], value[2])]

def links_to_local(key, value, fmt, meta):
    if key == 'Link':
        if value[2][0][-3:] == '.md':
            with open(value[2][0], 'r') as f:
                first_line = f.readline()
                if first_line[0] == '#':
                    value[2][0] = '#' + first_line[2:].lower().replace(' ', '-').strip()
                else:
                    value[2][0] = '#' + value[2][0][:-3]

if __name__ == "__main__":
  toJSONFilters([headers,links_to_local])
Exemple #25
0
            return Para([Image(['', [], []], [], [src, ""])])

def comment(k, v, fmt, meta):
    global incomment
    if k == 'RawBlock':
        fmt, s = v
        if fmt == "html":
            if re.search("<!-- BEGIN COMMENT -->", s):
                incomment = True
                return []
            elif re.search("<!-- END COMMENT -->", s):
                incomment = False
                return []
    if incomment:
        return []  # suppress anything in a comment

def image_with_url( k, v, fmt, meta ):
    if k == 'Image':
        urlOrPath = v[2][0]
        if 'http' in urlOrPath:
            url = urlOrPath
            path = download_image_from_url( url )
            log( "[INFO ] Replacing url %s with downloaded file %s" % (url, path) )
            v[2][0] = path
            return Image( *v )

if __name__ == "__main__":
    toJSONFilters( 
        [ image_with_url, comment, theorem.theorems, tikz, code_blocks.codeblocks ] 
        ) 
Exemple #26
0
def main():
    toJSONFilters([collect, listof])