def latex_figure(attr, filename, caption, alt):
    beginText = (u'\n' '\\begin{figure}[htbp]\n' '\\centering\n')
    endText = (u'}}\n'
               '\\label{{{id}}}\n'
               '\\end{{figure}}\n'.format(id=attr[0]))

    image = [pf.Image(attr, caption, (filename, alt))]

    if 'unnumbered' in attr[1]: star = True
    else: star = False

    if alt and not star:
        if alt.startswith('fig:'):
            alt = alt[
                4:]  # Not sure why pandoc adds this prefix, but we want to strip it for short captions.
        shortCaption = toFormat(alt, 'markdown', 'latex')
        latexCaption = '\n\\caption[{}]{{'.format(shortCaption)

    else:  # No short caption
        if star: latexCaption = '\\caption*{'
        else: latexCaption = '\\caption{'

    latexFigure = [RawInline('latex', beginText)]
    latexFigure += image
    latexFigure += [RawInline('latex', latexCaption)]
    latexFigure += caption
    latexFigure += [RawInline('latex', endText)]
    return pf.Para(latexFigure)

    return pf.Para([
        RawInline('latex', beginText), image,
        RawInline('latex', latexCaption), caption,
        RawInline('latex', endText)
    ])
Esempio n. 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
Esempio n. 3
0
def tbl_headers(s):
    if len(s[0]) >0 :
        result = s[0][0]['c'][:]
        for i in range(1, len(s)):
            result.append(inlatex(' & '))
            if len(s[i]) > 0 :
                result.extend(s[i][0]['c'])
        result.append(inlatex(r' \\\midrule'))
        return pf.Para(result)
    else :
        return pf.Para(s[0][:])
Esempio n. 4
0
def mergeImages(rv, elms):

    # ensure elms is/becomes a list
    if type(elms) != list: elms = [elms]
    # ensure rv is a list as well
    if type(rv) != list: return elms
    # if empty list, initialize first elm to empty Para
    if len(rv) == 0: rv.append(pf.Para([]))

    # check rv[-1]'s contents is a list of 0 or all Inline Image's
    try:
        images = rv[-1]['c']
        if any(x['t'] != 'Image' for x in images):
            return elms
    except:
        return elms

    residue = []
    for elm in elms:
        try:
            for img in elm['c']:
                if img['t'] == 'Image':
                    images.append(img)
                else:
                    residue.append(elm)
        except:
            residue.append(elm)

    return residue
Esempio n. 5
0
def tbl_headers(s):
    result = s[0][0]['c'][:]
    for i in range(1, len(s)):
        result.append(inlatex(' & '))
        result.extend(s[i][0]['c'])
    result.append(inlatex(r'\\' '\n'))
    return pf.Para(result)
Esempio n. 6
0
def tbl_contents(s):
    result = []

    root = s[0]
    if root['t'] != "TableBody":
        return

    results = []

    for row in root['c'][3]:
        row_cells = []
        if row['t'] != "Row":
            continue
        for cell in row['c'][1]:
            if type(cell) != dict or cell['t'] != "Cell":
                continue
            content = cell['c'][4][0]['c'][0]
            if type(content) != dict or content['t'] != "Str":
                continue
            row_cells.append(content['c'])

        results.append(row_cells)
    res = []
    for row_cells in results:
        for cn, val in enumerate(row_cells):
            res.append(
                inlatex(val + (" & " if cn < len(row_cells) - 1 else "")))
        res.append(inlatex(" \\\\ \n"))
    res.append(inlatex(r' \bottomrule'))
    res = pf.Para(res)
    return res
Esempio n. 7
0
def tbl_headers(s):
    root = s
    if root['t'] != "TableHead":
        return

    headers = []

    item = root['c'][1][0]
    if item['t'] != "Row":
        return
    for bit in item['c'][1]:
        if bit['t'] == "Cell":
            for cell_chunk in bit['c']:
                if type(cell_chunk) == list:
                    if type(cell_chunk[0]) == dict:
                        leaf = cell_chunk[0]['c'][0]
                        if leaf['t'] == "Str":
                            headers.append(leaf['c'])
                            # headers.append(leaf)

    result = []
    for cn, val in enumerate(headers):
        result.append(inlatex(val + (" & " if cn < len(headers) - 1 else "")))

    result.append(inlatex(r" \\\midrule"))
    res = pf.Para(result)
    return res
Esempio n. 8
0
def tbl_headers(s):
    result = s[0][0]["c"][:]
    for i in range(1, len(s)):
        result.append(inlatex(" & "))
        result.extend(s[i][0]["c"])
    result.append(inlatex(r" \\\midrule"))
    return pf.Para(result)
Esempio n. 9
0
 def render(self, watcher, inline):
     result = []
     betweenframes = False
     for i, f in enumerate(self._filenames):
         anim = self._anims[i]
         [options, slide] = self._mangleoptions(self._options[i])
         if slide:
             result.append(
                 li('\\slidefig{%s}{%s}' %
                    ('<' + anim + '>' if len(anim) > 0 else '', f)))
             betweenframes = True
             continue
         if i == 0 and len(self._caption) > 0:
             result.append(li('\\begin{%s}\n' % self._figtype))
         if i == 0 and len(self._caption) == 0 and not inline:
             result.append(li('{\\centering'))
         result.append(fig(f, options, anim))
         if i + 1 == len(self._filenames) and len(self._caption) > 0:
             result.extend([li('\\caption{'), li(self._caption), li('}\n')])
             result.append(li('\\end{%s}' % self._figtype))
         if i + 1 == len(self._filenames) and len(
                 self._caption) == 0 and not inline:
             result.append(li('\par}'))
     if inline:
         if betweenframes:
             return pf.Str('Unable to return paragraph when in inline mode')
         return result
     result = pf.Para(result)
     return watcher.betweenframes(result) if betweenframes else result
Esempio n. 10
0
def tbl_headers(s, delimiter):
    result = s[0][0]['c'][:]
    for i in range(1, len(s)):
        result.append(inlatex(' & '))
        if len(s[i]) > 0:
            result.extend(s[i][0]['c'])
    result.append(inlatex(delimiter))
    return pf.Para(result)
Esempio n. 11
0
def tbl_contents(s):
    result = []
    for row in s:
        para = []
        for col in row:
            para.extend(col[0]['c'])
            para.append(inlatex(' & '))
        result.extend(para)
        result[-1] = inlatex(r' \\ \hline' '\n')
    return pf.Para(result)
Esempio n. 12
0
def tbl_headers(s, delimiter):
    result = [inlatex(r'{')]
    result.extend(s[0][0]['c'][:])
    result.append(inlatex('}'))
    for i in range(1, len(s)):
        result.append(inlatex(r' & {'))
        result.extend(s[i][0]['c'])
        result.append(inlatex('}'))
    result.append(inlatex(delimiter + r'\hline'))
    return pf.Para(result)
Esempio n. 13
0
def tbl_contents(s, delimiter):
    result = []
    for row in s:
        para = []
        for col in row:
            para.extend(col[0]['c'])
            para.append(inlatex(' & '))
        result.extend(para)
        result[-1] = inlatex(delimiter + '\n')
    return pf.Para(result)
Esempio n. 14
0
def tbl_contents(s):
    result = []
    for row in s:
        para = []
        for col in row:
            if len(col) > 0:
                para.extend(col[0]["c"])
            para.append(inlatex(" & "))
        result.extend(para)
        result[-1] = inlatex(r" \\" "\n")
    return pf.Para(result)
Esempio n. 15
0
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)])]
Esempio n. 16
0
def tbl_headers(s):
    try:
        result = s[0][0]['c'][:]
    except IndexError:
        result = []
    for i in range(1, len(s)):
        result.append(inlatex(' & '))
        try:
            result.extend(s[i][0]['c'])
        except IndexError:
            pass
    result.append(inlatex(r' \\\midrule'))
    return pf.Para(result)
Esempio n. 17
0
def tbl_headers(s):
    #print(s, s[0], len(s), file=sys.stderr)
    if s[0]:
        start = 1
        result = s[0][0]['c'][:]
    else:
        start = 2
        result = s[1][0]['c'][:]
    for i in range(start, len(s)):
        result.append(inlatex(' & '))
        result.extend(s[i][0]['c'])
    result.append(inlatex(r' \\\midrule'))
    return pf.Para(result)
Esempio n. 18
0
  def build_replacement_pandoc_element(self):
    if not os.path.exists(self.image_path):
      os.makedirs(os.path.dirname(self.image_path), exist_ok=True)
      self.generate_image()
      if not os.path.exists(self.image_path):
        raise errors.NoFigureProduced()

    alt_text = pandocfilters.Code(['', [], []], errors.make_pandoc_for_block(self))
    image = pandocfilters.Image(
      [self.identifier, self.classes, list(self.attributes.items())],
      [alt_text],
      [self.image_path, errors.make_pandoc_for_block(self)])
    result = pandocfilters.Para([image])
    return result
    def figure_replacement(self, key, value, format, metadata):
        """Replace figures with appropriate representation.

        This works with Figure, which is our special type for images
        with attributes. This allows us to set an id in the attributes.

        The other way of doing it would be to pull out a '\label{(.*)}'
        from the caption of an Image and use that to update the references.
        """
        _caption, (filename, target), attrs = value
        caption = pf.stringify(_caption)

        attr = PandocAttributes(attrs)

        if 'unnumbered' in attr.classes:
            star = '*'
            fcaption = caption
        else:
            self.fig_replacement_count += 1
            if not attr.id:
                attr.id = self.auto_fig_id(self.fig_replacement_count)

            ref = self.references[attr.id]
            star = ''
            if caption:
                fcaption = u'Figure {n}: {caption}'.format(n=ref['id'],
                                                           caption=caption)
            else:
                fcaption = u'Figure {n}'.format(n=ref['id'])

        if 'figure' not in attr.classes:
            attr.classes.insert(0, 'figure')

        if format in self.formats:
            figure = self.figure_styles[format].format(attr=attr,
                                                       filename=filename,
                                                       alt=fcaption,
                                                       fcaption=fcaption,
                                                       caption=caption,
                                                       star=star).encode('utf-8')

            return RawBlock(format, figure)

        else:
            alt = [pf.Str(fcaption)]
            target = (filename, '')
            image = pf.Image(alt, target)
            figure = pf.Para([image])
            return pf.Div(attr.to_pandoc(), [figure])
Esempio n. 20
0
    def figure_replacement(self, key, value, format, metadata):
        """Replace figures with appropriate representation.

        This works with Figure, which is our special type for images
        with attributes. This allows us to set an id in the attributes.

        The other way of doing it would be to pull out a '\label{(.*)}'
        from the caption of an Image and use that to update the references.
        """
        caption, (filename, alt), attr = value

        if 'unnumbered' in attr[1]:
            fcaption = caption
        else:
            self.fig_replacement_count += 1
            if not attr[0]:
                attr[0] = self.auto_fig_id(self.fig_replacement_count)

            ref = self.references[attr[0]]
            if caption:
                fcaption = [
                    pf.Str('Figure'),
                    pf.Space(),
                    pf.Str(str(ref['id']) + ':'),
                    pf.Space()
                ] + caption
            else:
                fcaption = [
                    pf.Str('Figure'),
                    pf.Space(),
                    pf.Str(str(ref['id']))
                ]


#        if 'figure' not in attr[1]:
#            # FIXME: Currently adding this in html_figure() and html5_figure()
#            attr[1].append('figure')

        if format == 'latex' or format == 'beamer':
            return latex_figure(attr, filename, caption, alt)
        elif format == 'html':
            return html_figure(attr, filename, fcaption, alt)
        elif format == 'html5':
            return html5_figure(attr, filename, fcaption, alt)
        elif format == 'markdown':
            return markdown_figure(attr, filename, fcaption, alt)
        else:
            image = pf.Image(attr, fcaption, (filename, alt))
            return pf.Para([image])
Esempio n. 21
0
def tbl_headers(s):
    result = s[0][0]['c'][:]
    # Build the columns. Note how the every column value is bold.
    # We are still missing "\textbf{" for the first column
    # and a "}" for the last column.
    for i in range(1, len(s)):
        result.append(inlatex(r'} & \textbf{'))
        result.extend(s[i][0]['c'])
    # Don't forget to close the last column's "\textbf{" before newline
    result.append(inlatex(r'} \\ \hline'))
    # Put the missing "\textbf{" in front of the list
    result.insert(0, inlatex(r'\textbf{'))
    # Preprend the command to set the row color in front of everything
    result.insert(0, inlatex(r'\rowcolor{grey} '))
    return pf.Para(result)
Esempio n. 22
0
def tbl_caption(s):
    return pf.Para([inlatex(r'\caption{')] + s + [inlatex('}')])
Esempio n. 23
0
def put_caption(s):
    if s:
        return pf.Para([inlatex(r'\caption{')] + s + [inlatex('}')])
    else:
        return pf.Null()
Esempio n. 24
0
def tbl_caption(s):
    # check if there is no header
    if len(s) == 0:
        return pf.Para([])

    return pf.Para([inlatex(r'\caption{')] + s + [inlatex('}')])
Esempio n. 25
0
def markdown_figure(attr, filename, fcaption, alt):
    markdownFigure = [pf.Para([pf.Image(attr, fcaption, (filename, alt))])]
    return markdownFigure
Esempio n. 26
0
def tbl_caption(root):
    result = []
    caption = root['c'][1][0]['c']
    res = pf.Para([inlatex(r'\caption{')] + caption + [inlatex('}')])
    return res
Esempio n. 27
0
def tbl_caption(s):
    return pf.Para([inlatex(r"\caption{")] + s + [inlatex("}")])
Esempio n. 28
0
def structure_para(v, f, m):
    global marginnote
    if not len(marginnote) == 0:
        note = [li('\\m{%s}' % marginnote)]
        marginnote = ''
        return pf.Para(note + v)