示例#1
0
def speciesify(key, value, fmt, meta):
    global seen_dict
    if key == 'Emph':
        if len(value) == 3:
            if value[1]['t'] == 'Space':
                species_name = ' '.join([value[i]['c'] for i in [0, 2]])
                if species_name in species:
                    if seen_dict[species_name]:
                        return (Emph(walk(value, initialize, fmt, meta)))
                    else:
                        seen_dict[species_name] = True
                        return (Emph(value))
示例#2
0
def behead(key, value, format, meta):
    # sends function input to stderr
    # anything sent to stdout interferes with later processing
    #errcho("key:",key,"val:",value)
    # wraps the 'abstract' element in paragraph and emphasis markup
    # doesn't work, requires reader to read the abstract tag
    if key == 'abstract':
        return Para([Emph(value[2])])
示例#3
0
def behead(key, value, format_, meta):
    '''
    "[R]eplace all level 2+ headers in a markdown document with regular
    paragraphs, with text in italics."
    ( http://pandoc.org/scripting.html#a-simple-example )
    '''
    if key == "Header":
        # Here n is an int giving the level of the header, and xs is a list
        # with the actual header data. The discarded middle value contains the
        # slug data.
        n, _, xs = value
        if n >= 2:
            # Emph takes a list, so we can just pass it xs; however, Para also
            # takes a list, so we must envelop the Emph in a list first.
            return Para([Emph(xs)])
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)
示例#5
0
def behead(key, value, format, meta):
    if key == 'Header' and value[0] >= 2:
        return Para([Emph(value[2])])
示例#6
0
def filter_main(key, value, format, meta):
    # f.write(repr(key) + '\n')
    # f.write(repr(value) + '\n')
    # f.write('------\n')
    if key == 'CodeBlock':
        text = value[1]
        m = re.match(r'%%%%lyxblog-raw\n(.*)', text, flags=re.DOTALL | re.I)
        if m:
            return RawBlock('html', m[1])
    elif key == 'Math' and value[0]['t'] == 'DisplayMath':  # i.e. not inline
        # MathJax supports labels and eq. numbering only for AMS envs, so we
        # convert non-AMS envs into AMS envs.
        latex = value[1]
        if not latex.startswith(r'\begin{'):  # not AMS env
            # We assume there are no comments inside math blocks (if the file
            # is produced by LyX, there shouldn't be any).
            pos = latex.find(r'\label{')
            if pos == -1:  # no labels => no numbering
                fixed = r'\begin{align*}' + value[1] + r'\end{align*}'
            else:
                fixed = r'\begin{align}' + value[1] + r'\end{align}'
            return Math(value[0], fixed)
    elif key == 'Span':
        # This supports general labels (i.e. labels not in equations, captions
        # or section headers).
        id, classes, key_values = value[0]
        if len(key_values) == 1 and key_values[0][0] == 'label':
            # we remove the text from the label.
            return Span(value[0], [])
    elif key == 'Header':
        content = value[2]
        if content[-1]['t'] == 'Span':
            [id, classes, key_values], text = content[-1]['c']
            if len(key_values) == 1 and key_values[0][0] == 'label':
                # we label the header itself (id) and delete the label-span
                label_name = key_values[0][1]
                value[1][0] = label_name
                return Header(value[0], value[1], content[:-1])
    elif key == 'Math' and value[0]['t'] == 'InlineMath':
        if value[1].startswith('\\ref{') and value[1][-1] == '}':
            name = value[1][len('\\ref{'):-1]

            # We try to extract the text from the label itself.
            # (=00007B and =00007D represent '{' and '}' and are in the TeX
            # file produced by LyX.)
            m = re.match(r'.*=00007B([^}]+)=00007D$', name)
            if m:
                return RawInline('html',
                                 '<a href="#{}">{}</a>'.format(name, m[1]))

            # We only handle references to sections and images here.
            # (Mathjax already handles the equations.)
            num = sec_name_to_num.get(name, img_name_to_num.get(name, None))
            if num:
                return RawInline('html',
                                 '<a href="#{}">{}</a>'.format(name, num))

    elif key == 'Para' and value[0]['t'] == 'Image':
        # NOTE:
        #   In pandoc 2, a Para[Image] where Image.title is 'fig:' becomes
        #   a <figure> with a <figcaption>.

        [id, classes, style], alt, [src, title] = value[0]['c']
        style = {k: v for k, v in style}
        width = float(style.get('width', '100.0%')[:-1])
        margin = (100 - width) / 2

        global image_idx
        src = image_info[image_idx]
        image_idx += 1

        label = ''
        if alt[-1]['t'] == 'Span':
            id, classes, key_values = alt[-1]['c'][0]  # attr
            key_values = dict(key_values)
            if 'label' in key_values:
                # remove the label from the caption (it'll be put right before
                # the image).
                alt = alt[:-1]  # remove the label from the caption
                label = key_values['label']

        fake_class = '{}:{:.5}%'.format(UID2, margin)
        img_attrs = make_attrs(label, [fake_class], {'width': '100%'})
        caption = [Emph([Str('Figure {}.'.format(image_idx))])]
        if title == 'fig:':
            caption += [Space()] + alt

        para_content = [Image(img_attrs, caption, (src, 'fig:'))]

        return Para(para_content)