コード例 #1
0
    def image(self, fmt=None):
        'return documentation in a CodeBlock'
        # CodeBlock value = [(Identity, [classes], [(key, val)]), code]
        if not self.code:
            return pf.CodeBlock(('', [], []), __doc__)
        elif self.code == 'classes':
            classes = wrap(', '.join(sorted(Handler.workers.keys())), 78)
            return pf.CodeBlock(('', [], []), '\n'.join(classes))

        doc = []
        for name in self.code.splitlines():
            name = name.lower()
            worker = self.workers.get(name, None)
            doc.append(name)
            if worker is None:
                doc.append('No worker found for %s' % name)
                continue
            if worker.__doc__:
                doc.append(worker.__doc__)
                doc.append('    ' + worker.image.__doc__)
            else:
                doc.append('No help available.')
            doc.append('\n')

        return pf.CodeBlock(('', [], []), '\n'.join(doc))
コード例 #2
0
    def result(self):
        'return FCB, Para(url()) and/or CodeBlock(stdout) as ordered'
        rv = []
        enc = sys.getdefaultencoding()  # result always unicode
        for output_elm in self.im_out:
            if output_elm == 'img':
                if os.path.isfile(self.outfile):
                    rv.append(pf.Para([self.url()]))
                else:
                    msg = '?? missing %s' % self.outfile
                    self.msg(1, '>>:', msg)
                    rv.append(pf.Para([pf.Str(msg)]))

            elif output_elm == 'fcb':
                rv.append(self.anon_codeblock())

            elif output_elm == 'stdout':
                if self.stdout:
                    attr = ['', self.classes, self.keyvals]
                    rv.append(pf.CodeBlock(attr, to_str(self.stdout, enc)))
                else:
                    self.msg(1, '>>:', 'stdout requested, but saw nothing')

            elif output_elm == 'stderr':
                if self.stderr:
                    attr = ['', self.classes, self.keyvals]
                    rv.append(pf.CodeBlock(attr, to_str(self.stderr, enc)))
                else:
                    self.msg(1, '>>:', 'stderr requested, but saw nothing')

        if not rv:
            return None  # no results; None keeps original FCB
        if len(rv) > 1:
            return rv  # multiple results
        return rv[0]  # just 1 block level element
コード例 #3
0
 def convert(self, key, value, format, meta):
     if key == "CodeBlock":
         (ident, classes, keyvals), code = value
         try:
             fmt = [i for i in classes if i in INTERPRETERS][0]
         except IndexError:
             return
         try:
             interpreter = self.interpreters[fmt]
         except KeyError:
             self.interpreters[fmt] = INTERPRETERS[fmt]()
             interpreter = self.interpreters[fmt]
         text = interpreter.communicate(code)
         return [pdf.CodeBlock(*value), pdf.CodeBlock(("", [], []), text)]
コード例 #4
0
    def image(self):
        'returns documentation in a CodeBlock'
        # CodeBlock value = [(Identity, [classes], [(key, val)]), code]
        if not self.code:
            return pf.CodeBlock(('', [], []), __doc__)
        elif self.code == 'classes':
            classes = wrap(', '.join(sorted(Handler.workers.keys())), 78)
            return pf.CodeBlock(('', [], []), '\n'.join(classes))

        doc = []
        for name in self.code.splitlines():
            name = name.lower()
            worker = self.workers.get(name, None)
            doc.append("Codeblock class: " + name)
            if worker is None:
                doc.append('No worker found for %s' % name)
                continue
            if worker.__doc__:
                doc.append(worker.__doc__)
                doc.append("    runs:")
                doc.append('    > ' + worker.image.__doc__)
            else:
                doc.append('No help available.')

            doc.append("\n    class->cmd")
            for k, v in worker.cmdmap.items():
                doc.append("      {} -> {}".format(k, v))

            # -- document class metadata options
            klass_opts, glob_opts = [], []
            for k, v in self.md_opts.items():
                if k not in self.workers:
                    glob_opts.append("    imagine.{}: {}".format(k, v))
                else:  # elif k == name:
                    for kk, vv in self.md_opts.get(name, {}).items():
                        klass_opts.append("    imagine.{}.{}: {}".format(
                            k, kk, vv))
            if klass_opts or glob_opts:
                doc.append("\nMetadata options")
                # doc.append("    ---")
                doc.extend(glob_opts + klass_opts)
                # doc.append("    ...")

            doc.append('\n')

        return pf.CodeBlock(('', [], []), '\n'.join(doc))
コード例 #5
0
 def anon_codeblock(self):
     'reproduce the original CodeBlock inside an anonymous CodeBlock'
     (id_, klasses, keyvals), code = self.codec
     id_ = '#' + id_ if id_ else id_
     klasses = ' '.join('.%s' % c for c in klasses)
     keyvals = ' '.join('%s="%s"' % (k, v) for k, v in keyvals)
     attr = '{%s}' % ' '.join(a for a in [id_, klasses, keyvals] if a)
     # prefer ```cmd over ```{.cmd}
     attr = attr if attr.find(' ') > -1 else attr[2:-1]
     codeblock = '```%s\n%s\n```' % (attr, code)
     return pf.CodeBlock(['', [], []], codeblock)
コード例 #6
0
ファイル: include.py プロジェクト: Insper/insper-handout
def include_filter(k, v, f, m):
    if k == 'Div':
        [[ident, classes, attrs], content] = v
        if 'include' in classes:
            with open(ident, 'r') as f:
                content = f.read()
                if 'code' in classes:
                    return pf.CodeBlock(
                        (ident, [get_attr_in_list(attrs, 'language')], []),
                        content)
                else:
                    return [pf.Para([pf.Str(content)])]
コード例 #7
0
ファイル: errors.py プロジェクト: speezepearson/panfig
def make_diagnostic_code_block(key:str, value:Any, exception:Exception):
  paragraphs = [
    'Error! Offending element:',
    indent(make_pandoc_for_code_block(value) if key=='CodeBlock' else str((key,value))),
    'Traceback:',
    indent('\n'.join(traceback.format_exception(exception.__class__, exception, exception.__traceback__)))]
  if isinstance(exception, SubprocessFailed):
    try: stdout = exception.out.decode()
    except UnicodeDecodeError: stdout = repr(exception.out)
    try: stderr = exception.err.decode()
    except UnicodeDecodeError: stderr = repr(exception.err)
    paragraphs += ['Stdout:', indent(stdout), 'Stderr:', indent(stderr)]

  return pandocfilters.CodeBlock(['', [], []], '\n\n'.join(paragraphs))
コード例 #8
0
ファイル: filters.py プロジェクト: rowhit/thesis
def enclose_input_code(key, value, format, metadata):
    """Enclose any input code in a div to allow collapsing.

    'Input code' is a code block that has 'n' defined (the prompt
    number).
    """
    if key == 'CodeBlock':
        div_attr = {'classes': ['collapsible']}
        code_attr = PandocAttributes(value[0], format='pandoc')
        if 'n' not in code_attr.kvs:
            return
        else:
            button = pf.RawBlock('html', collapse_button(n=code_attr['n']))
            code = pf.CodeBlock(*value)
            content = [button, pf.Div(pf.attributes({}), [code])]
            return pf.Div(pf.attributes(div_attr), content)
コード例 #9
0
def do_filter(k, v, f, m):
    if k == "Para":
        value = pf.stringify(v)

        # Colunas no slide
        if f == 'beamer':
            if not _.is_columns:
                # Inicia bloco 'columns'
                if value == '<[columns]':
                    _.is_columns = True
                    return latex(r'\begin{columns}')
            else:
                # Termina bloco 'columns'
                if value == '[columns]>':
                    _.is_columns = False
                    return latex(r'\end{columns}')
                # Demarca uma coluna
                m = re.match(r'^\[\[\[ *(%s) *\]\]\]$' % RE_FLOAT, value)
                if m:
                    return latex(r'\column{%s\textwidth}' % m.group(1))

        # Subfiguras
        if not _.is_figure:
            if value == '<[figures]':
                _.is_figure = True
                return latex(r'\begin{figure}[tbp]' '\n' r'\centering')
        else:
            if value == '[figures]>':
                _.is_figure = False
                return latex(r'\end{figure}')
            if v[0]['t'] == "Str" and v[0]['c'] == "Caption:" \
                    and v[1]['t'] == "Space":
                return put_caption(v[2:])
            if len(v) >= 1 and v[0]['t'] == "Image":
                images = []
                for i in range(len(v)):
                    if v[i]['t'] == "Image":
                        uri = v[i]['c'][1][0]
                        caption = v[i]['c'][0]
                        images.append((uri, caption))
                return put_subfigures(images)

        # Imagens com largura informada
        if len(v) == 1 and v[0]['t'] == "Image":
            uri = v[0]['c'][1][0]
            caption = v[0]['c'][0]
            return put_figure(uri, caption)

    elif k == "RawInline" and v[0] == "html":
        # Anchor (\label)
        m = re.match(r'^<anchor:#(.*?)>', v[1])
        if m:
            return [inlatex(r'\label{%s}' % m.group(1))]

        # Reference link (\ref)
        m = re.match(r'^<ref:#(.*?)>', v[1])
        if m:
            return [inlatex(r'\ref{%s}' % m.group(1))]

        # Page reference link (\pageref)
        m = re.match(r'^<pageref:#(.*?)>', v[1])
        if m:
            return [inlatex(r'\pageref{%s}' % m.group(1))]

    # Math with anchors
    elif k == "Math" and v[0]['t'] == "DisplayMath":
        pos = v[1].find('#')
        # Return math without changes if no anchor was found
        if pos == -1:
            return
        # Return math inside an equation environment
        else:
            anchor = v[1][pos+1:].strip()
            math = v[1][:pos]
            return inlatex(r'\begin{equation}\label{%s}'
                           '\n%s\n'
                           r'\end{equation}' % (anchor, math))

    # Special citations
    elif k == "Cite":
        kind = ''
        citations = []
        for bib in v[0]:
            citeid, ki = split(bib['citationId'], '#', 1)
            kind = ki or kind
            citations.append(citeid)
            bib['citationId'] = citeid

        bibid = ','.join(citations)
        if kind:
            return inlatex(r'\cite%s{%s}' % (kind, bibid))
        else:
            return pf.Cite(*v)

    elif k == "Table":
        cap = v[0]
        # Coloca uma imagem como tabela
        tbl_image = get_table_option(cap, 'from')
        if tbl_image is not None:
            cap.pop(0)
            return [latex(r'\begin{table}[tbp]' '\n' r'\centering' '\n'),
                    tbl_caption(cap),
                    put_image(tbl_image, None),
                    latex(r'\end{table}')]
        # Usa longtable, mas a coloca na proxima pagina
        if has_table_option(cap, 'longtable'):
            cap.pop(0)
            return [latex(r'\afterpage{'),
                    pf.Table(*v),
                    latex(r'}')]
        # Coloca as tabelas em ambientes table comuns
        elif len(sys.argv) > 1 and sys.argv[1] == "--table":
            place = get_table_option(cap, 'place')
            if place is not None:
                cap.pop(0)
            else:
                place = 'tbp'
            return [latex(r'\begin{table}[%s]' '\n'
                          r'\centering' '\n' % place),
                    tbl_caption(cap),
                    latex(r'\begin{tabular}{@{}%s@{}}' %
                        tbl_alignment(v[1], v[3]) +
                        ('\n' r'\toprule')),
                    tbl_headers(v[3]),
                    tbl_contents(v[4]),
                    latex(r'\bottomrule' '\n' r'\end{tabular}'),
                    latex(r'\end{table}')]

    # Envolve codigos com caption no environment 'codigo'
    elif k == "CodeBlock":
        attrs = dict(v[0][2])
        if "caption" in attrs:
            objs = [latex(r'\begin{codigo}'), pf.CodeBlock(*v),
                   latex(r'\caption{%s}' % attrs["caption"])]
            if "label" in attrs:
                objs.append(latex(r'\label{%s}' % attrs["label"]))
            objs.append(latex(r'\end{codigo}'))
            return objs
コード例 #10
0
 def run_on_node(key, value, fmt, meta):
     if key != 'CodeBlock':
         return None
     [[_, classes, _], content] = value
     classes += [lang]
     return pandocfilters.CodeBlock(*value)