def action(key, value, fmt, meta):  # pylint: disable=unused-argument
    """Processes elements."""

    global replaced_figure_env  # pylint: disable=global-statement

    if is_figure(key, value):

        attrs = PandocAttributes(value[0]['c'][0], 'pandoc')

        # Convert figures with `marginfigure` class to marginfigures
        if 'marginfigure' in attrs.classes:

            if 'documentclass' in meta and \
              get_meta(meta, 'documentclass') in \
              ['tufte-book', 'tufte-handout']:

                replaced_figure_env = True

                # Get the marginfigure options
                offset = attrs['offset'] if 'offset' in attrs else '0pt'

                # LaTeX used to apply the environment
                pre = RawBlock('tex', r'\begin{marginfigure_}[%s]' % offset)
                post = RawBlock('tex', r'\end{marginfigure_}')

                return [pre, Para(value), post]

            if warninglevel:
                STDERR.write(WARNING)

    return None
Ejemplo n.º 2
0
def action(key, value, fmt, meta):  # pylint: disable=unused-argument
    """Processes elements."""

    if key == 'Div':

        attrs = PandocAttributes(value[0], 'pandoc')

        if 'marginnote' in attrs.classes:
            offset = attrs['offset'] if 'offset' in attrs else '0pt'

            if 'documentclass' in meta and \
              get_meta(meta, 'documentclass') in \
              ['tufte-book', 'tufte-handout']:

                pre = RawInline('tex', r'\marginnote[%s]{'%offset)
                post = RawInline('tex', r'}')

                assert value[1][0]['t'] == 'Para'
                assert value[1][-1]['t'] == 'Para'

                value[1][0]['c'].insert(0, pre)
                value[1][-1]['c'].append(post)

            elif warninglevel:
                STDERR.write(WARNING)
Ejemplo n.º 3
0
def add_tex(meta):
    """Adds tex to the meta data."""

    warnings = warninglevel == 2 and targets and \
               (pandocxnos.cleveref_required() or
                plusname_changed or starname_changed or numbersections or secoffset)
    if warnings:
        msg = textwrap.dedent("""\
                  pandoc-eqnos: Wrote the following blocks to
                  header-includes.  If you use pandoc's
                  --include-in-header option then you will need to
                  manually include these yourself.
              """)
        STDERR.write('\n')
        STDERR.write(textwrap.fill(msg))
        STDERR.write('\n')

    # Update the header-includes metadata.  Pandoc's
    # --include-in-header option will override anything we do here.  This
    # is a known issue and is owing to a design decision in pandoc.
    # See https://github.com/jgm/pandoc/issues/3139.

    if pandocxnos.cleveref_required() and targets:
        tex = """
            %%%% pandoc-eqnos: required package
            \\usepackage%s{cleveref}
        """ % ('[capitalise]' if capitalise else '')
        pandocxnos.add_to_header_includes(
            meta, 'tex', tex, regex=r'\\usepackage(\[[\w\s,]*\])?\{cleveref\}')

        if not eqref:
            pandocxnos.add_to_header_includes(meta, 'tex',
                                              DISABLE_CLEVEREF_BRACKETS_TEX)

    if plusname_changed and targets:
        tex = """
            %%%% pandoc-eqnos: change cref names
            \\crefname{equation}{%s}{%s}
        """ % (plusname[0], plusname[1])
        pandocxnos.add_to_header_includes(meta, 'tex', tex)

    if starname_changed and targets:
        tex = """
            %%%% pandoc-eqnos: change Cref names
            \\Crefname{equation}{%s}{%s}
        """ % (starname[0], starname[1])
        pandocxnos.add_to_header_includes(meta, 'tex', tex)

    if numbersections and targets:
        pandocxnos.add_to_header_includes(meta, 'tex', NUMBER_BY_SECTION_TEX)

    if secoffset and targets:
        pandocxnos.add_to_header_includes(meta,
                                          'tex',
                                          SECOFFSET_TEX % secoffset,
                                          regex=r'\\setcounter\{section\}')

    if warnings:
        STDERR.write('\n')
Ejemplo n.º 4
0
def add_tex(meta):
    """Adds tex to the meta data."""

    warnings = warninglevel == 2 and targets and \
      (pandocxnos.cleveref_required() or len(names) or secoffset or \
       numbersections)
    if warnings:
        msg = textwrap.dedent("""\
                  pandoc-theoremnos: Wrote the following blocks to
                  header-includes.  If you use pandoc's
                  --include-in-header option then you will need to
                  manually include these yourself.
              """)
        STDERR.write('\n')
        STDERR.write(textwrap.fill(msg))
        STDERR.write('\n')

    # Update the header-includes metadata.  Pandoc's
    # --include-in-header option will override anything we do here.  This
    # is a known issue and is owing to a design decision in pandoc.
    # See https://github.com/jgm/pandoc/issues/3139.

    if pandocxnos.cleveref_required() and targets:
        tex = """
            %%%% pandoc-theoremnos: required package
            \\usepackage{amsthm}
            \\usepackage%s{cleveref}
        """ % ('[capitalise]' if capitalise else '')
        pandocxnos.add_to_header_includes(
            meta, 'tex', tex, regex=r'\\usepackage(\[[\w\s,]*\])?\{cleveref\}')

    if secoffset and targets:
        pandocxnos.add_to_header_includes(meta,
                                          'tex',
                                          SECOFFSET_TEX % secoffset,
                                          regex=r'\\setcounter\{section\}')

    if names:
        tex = """
            %% pandoc-theoremnos: set theorem types
            """
        firstid = None
        for thid, thname in names.items():
            tex += """\\newtheorem{%s}%s{%s}%s
            """ % (thid, '[%s]' % firstid if firstid is not None else '',
                   thname, '[section]' if numbersections and firstid is None \
                   else '')

            if sharedcounter and firstid is None:
                firstid = thid

        pandocxnos.add_to_header_includes(meta, 'tex', tex)

    if warnings:
        STDERR.write('\n')
Ejemplo n.º 5
0
def action(key, value, fmt, meta):  # pylint: disable=unused-argument
    """Processes elements."""

    if key == 'Span':

        attrs = PandocAttributes(value[0], 'pandoc')

        if 'newthought' in attrs.classes:
            if 'documentclass' in meta and \
              get_meta(meta, 'documentclass') in \
              ['tufte-book', 'tufte-handout']:

                pre = RawInline('tex', r'\newthought{')
                post = RawInline('tex', r'}')

                value[1].insert(0, pre)
                value[1].append(post)

            elif warninglevel:
                STDERR.write(WARNING)
Ejemplo n.º 6
0
def add_html(meta, fmt):
    """Adds html to the meta data."""

    warnings = warninglevel == 2 and targets

    if warnings:
        msg = textwrap.dedent("""\
                  pandoc-eqnos: Wrote the following blocks to
                  header-includes.  If you use pandoc's
                  --include-in-header option then you will need to
                  manually include these yourself.
              """)
        STDERR.write('\n')
        STDERR.write(textwrap.fill(msg))
        STDERR.write('\n')

    # Update the header-includes metadata.  Pandoc's
    # --include-in-header option will override anything we do here.  This
    # is a known issue and is owing to a design decision in pandoc.
    # See https://github.com/jgm/pandoc/issues/3139.

    if targets:
        cond = fmt == 'html4' or \
               (fmt == 'html' and version(PANDOCVERSION) < version('2.0'))
        attr = ' type="text/css"' if cond else ''
        pandocxnos.add_to_header_includes(meta, 'html',
                                          EQUATION_STYLE_HTML % attr)
Ejemplo n.º 7
0
def main():
    """Main program"""

    # Read the command-line arguments
    parser = argparse.ArgumentParser(description='Pandoc latex extensions.')
    version = '%(prog)s {version}'.format(version=__version__)
    parser.add_argument('--version', action='version', version=version)
    parser.add_argument('fmt')
    args = parser.parse_args()

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # This filter only operates on latex documents
    if fmt != 'latex':
        json.dump(doc, STDOUT)
        STDOUT.flush()

    # Chop up the doc
    meta = doc['meta']
    blocks = doc['blocks']

    # Get the warning level
    warninglevel = 2  # 0 - no warnings; 1 - some warnings; 2 - all warnings
    for name in [
            'pandoc-latex-extensions-warning-level', 'xnos-warning-level'
    ]:
        if name in meta:
            warninglevel = int(get_meta(meta, name))
            break

    # Set the warninglevel in each plugin
    for plugin in PLUGINS:
        plugin.warninglevel = warninglevel

    # Apply the actions
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               ACTIONS, blocks)
    # Apply the processors
    if warninglevel == 2:
        msg = textwrap.dedent("""\
                 pandoc-latex-extensions: Wrote the following blocks to
                 header-includes.  If you use pandoc's
                  --include-in-header option then you will need to
                  manually include these yourself.
              """)
        STDERR.write('\n')
        STDERR.write(textwrap.fill(msg))
        STDERR.write('\n')
    for processor in PROCESSORS:
        processor(meta, altered)

    # Finish up
    doc['blocks'] = altered
    json.dump(doc, STDOUT)
    STDOUT.flush()
Ejemplo n.º 8
0
def add_html(meta):
    """Adds html to the meta data."""

    warnings = warninglevel == 2 and references

    if warnings:
        msg = textwrap.dedent("""\
                  pandoc-eqnos: Wrote the following blocks to
                  header-includes.  If you use pandoc's
                  --include-in-header option then you will need to
                  manually include these yourself.
              """)
        STDERR.write('\n')
        STDERR.write(textwrap.fill(msg))
        STDERR.write('\n')

    # Update the header-includes metadata.  Pandoc's
    # --include-in-header option will override anything we do here.  This
    # is a known issue and is owing to a design decision in pandoc.
    # See https://github.com/jgm/pandoc/issues/3139.

    if references:
        pandocxnos.add_to_header_includes(meta, 'html', EQUATION_STYLE_HTML)
Ejemplo n.º 9
0
def add_tex(meta):
    """Adds tex to the meta data."""

    # pylint: disable=too-many-boolean-expressions
    warnings = warninglevel == 2 and targets and \
      (pandocxnos.cleveref_required() or has_unnumbered_figures or
       plusname_changed or starname_changed or has_tagged_figures or
       captionname_changed or numbersections or secoffset)
    if warnings:
        msg = textwrap.dedent("""\
                  pandoc-fignos: Wrote the following blocks to
                  header-includes.  If you use pandoc's
                  --include-in-header option then you will need to
                  manually include these yourself.
              """)
        STDERR.write('\n')
        STDERR.write(textwrap.fill(msg))
        STDERR.write('\n')

    # Update the header-includes metadata.  Pandoc's
    # --include-in-header option will override anything we do here.  This
    # is a known issue and is owing to a design decision in pandoc.
    # See https://github.com/jgm/pandoc/issues/3139.

    if pandocxnos.cleveref_required() and targets:
        tex = """
            %%%% pandoc-fignos: required package
            \\usepackage%s{cleveref}
        """ % ('[capitalise]' if capitalise else '')
        pandocxnos.add_to_header_includes(
            meta, 'tex', tex, regex=r'\\usepackage(\[[\w\s,]*\])?\{cleveref\}')

    if has_unnumbered_figures or (separator_changed and targets):
        tex = """
            %%%% pandoc-fignos: required package
            \\usepackage{caption}
        """
        pandocxnos.add_to_header_includes(
            meta, 'tex', tex, regex=r'\\usepackage(\[[\w\s,]*\])?\{caption\}')

    if plusname_changed and targets:
        tex = """
            %%%% pandoc-fignos: change cref names
            \\crefname{figure}{%s}{%s}
        """ % (plusname[0], plusname[1])
        pandocxnos.add_to_header_includes(meta, 'tex', tex)

    if starname_changed and targets:
        tex = """
            %%%% pandoc-fignos: change Cref names
            \\Crefname{figure}{%s}{%s}
        """ % (starname[0], starname[1])
        pandocxnos.add_to_header_includes(meta, 'tex', tex)

    if has_unnumbered_figures:
        pandocxnos.add_to_header_includes(meta, 'tex',
                                          NO_PREFIX_CAPTION_ENV_TEX)

    if has_tagged_figures and targets:
        pandocxnos.add_to_header_includes(meta, 'tex', TAGGED_FIGURE_ENV_TEX)

    if captionname_changed and targets:
        pandocxnos.add_to_header_includes(meta, 'tex',
                                          CAPTION_NAME_TEX % captionname)

    if separator_changed and targets:
        pandocxnos.add_to_header_includes(meta, 'tex',
                                          CAPTION_SEPARATOR_TEX % separator)

    if numbersections and targets:
        pandocxnos.add_to_header_includes(meta, 'tex', NUMBER_BY_SECTION_TEX)

    if secoffset and targets:
        pandocxnos.add_to_header_includes(meta,
                                          'tex',
                                          SECOFFSET_TEX % secoffset,
                                          regex=r'\\setcounter\{section\}')

    if warnings:
        STDERR.write('\n')
Ejemplo n.º 10
0
def process(meta):
    """Saves metadata fields in global variables and returns a few
    computed fields."""

    # pylint: disable=global-statement
    global captionname  # The caption name
    global separator  # The caption separator
    global cleveref  # Flags that clever references should be used
    global capitalise  # Flags that plusname should be capitalised
    global plusname  # Sets names for mid-sentence references
    global starname  # Sets names for references at sentence start
    global numbersections  # Flags that sections should be numbered by section
    global secoffset  # Section number offset
    global warninglevel  # 0 - no warnings; 1 - some; 2 - all
    global captionname_changed  # Flags the caption name changed
    global separator_changed  # Flags the caption separator changed
    global plusname_changed  # Flags that the plus name changed
    global starname_changed  # Flags that the star name changed

    # Read in the metadata fields and do some checking

    for name in ['fignos-warning-level', 'xnos-warning-level']:
        if name in meta:
            warninglevel = int(get_meta(meta, name))
            pandocxnos.set_warning_level(warninglevel)
            break

    metanames = [
        'fignos-warning-level', 'xnos-warning-level', 'fignos-caption-name',
        'fignos-caption-separator', 'xnos-caption-separator',
        'fignos-cleveref', 'xnos-cleveref', 'xnos-capitalise',
        'xnos-capitalize', 'fignos-plus-name', 'fignos-star-name',
        'fignos-number-by-section', 'xnos-number-by-section',
        'xnos-number-offset'
    ]

    if warninglevel:
        for name in meta:
            if (name.startswith('fignos') or name.startswith('xnos')) and \
              name not in metanames:
                msg = textwrap.dedent("""
                          pandoc-fignos: unknown meta variable "%s"
                      """ % name)
                STDERR.write(msg)

    if 'fignos-caption-name' in meta:
        old_captionname = captionname
        captionname = get_meta(meta, 'fignos-caption-name')
        captionname_changed = captionname != old_captionname
        assert isinstance(captionname, STRTYPES)

    for name in ['fignos-caption-separator', 'xnos-caption-separator']:
        if name in meta:
            old_separator = separator
            separator = get_meta(meta, name)
            if separator not in \
              ['none', 'colon', 'period', 'space', 'quad', 'newline']:
                msg = textwrap.dedent("""
                          pandoc-fignos: caption separator must be one of
                          none, colon, period, space, quad, or newline.
                      """ % name)
                STDERR.write(msg)
                continue
            separator_changed = separator != old_separator
            break

    for name in ['fignos-cleveref', 'xnos-cleveref']:
        # 'xnos-cleveref' enables cleveref in all 3 of fignos/eqnos/tablenos
        if name in meta:
            cleveref = check_bool(get_meta(meta, name))
            break

    for name in ['xnos-capitalise', 'xnos-capitalize']:
        # 'xnos-capitalise' enables capitalise in all 3 of
        # fignos/eqnos/tablenos.  Since this uses an option in the caption
        # package, it is not possible to select between the three (use
        # 'fignos-plus-name' instead.  'xnos-capitalize' is an alternative
        # spelling
        if name in meta:
            capitalise = check_bool(get_meta(meta, name))
            break

    if 'fignos-plus-name' in meta:
        tmp = get_meta(meta, 'fignos-plus-name')
        old_plusname = copy.deepcopy(plusname)
        if isinstance(tmp, list):  # The singular and plural forms were given
            plusname = tmp
        else:  # Only the singular form was given
            plusname[0] = tmp
        plusname_changed = plusname != old_plusname
        assert len(plusname) == 2
        for name in plusname:
            assert isinstance(name, STRTYPES)
        if plusname_changed:
            starname = [name.title() for name in plusname]

    if 'fignos-star-name' in meta:
        tmp = get_meta(meta, 'fignos-star-name')
        old_starname = copy.deepcopy(starname)
        if isinstance(tmp, list):
            starname = tmp
        else:
            starname[0] = tmp
        starname_changed = starname != old_starname
        assert len(starname) == 2
        for name in starname:
            assert isinstance(name, STRTYPES)

    for name in ['fignos-number-by-section', 'xnos-number-by-section']:
        if name in meta:
            numbersections = check_bool(get_meta(meta, name))
            break

    if 'xnos-number-offset' in meta:
        secoffset = int(get_meta(meta, 'xnos-number-offset'))
Ejemplo n.º 11
0
def process(meta):
    """Saves metadata fields in global variables and returns a few
    computed fields."""

    # pylint: disable=global-statement
    global cleveref  # Flags that clever references should be used
    global capitalise  # Flags that plusname should be capitalised
    global plusname  # Sets names for mid-sentence references
    global starname  # Sets names for references at sentence start
    global numbersections  # Flags that sections should be numbered by section
    global secoffset  # Section number offset
    global warninglevel  # 0 - no warnings; 1 - some; 2 - all
    global plusname_changed  # Flags that the plus name changed
    global starname_changed  # Flags that the star name changed
    global eqref  # Flags that \eqref should be used
    global default_env  # Default equations environment

    # Read in the metadata fields and do some checking

    for name in ['eqnos-warning-level', 'xnos-warning-level']:
        if name in meta:
            warninglevel = int(get_meta(meta, name))
            pandocxnos.set_warning_level(warninglevel)
            break

    metanames = [
        'eqnos-warning-level',
        'xnos-warning-level',
        'eqnos-cleveref',
        'xnos-cleveref',
        'xnos-capitalise',
        'xnos-capitalize',
        'xnos-caption-separator',  # Used by pandoc-fignos/tablenos
        'eqnos-plus-name',
        'eqnos-star-name',
        'eqnos-number-by-section',
        'xnos-number-by-section',
        'xnos-number-offset',
        'eqnos-eqref',
        'eqnos-default-env'
    ]

    if warninglevel:
        for name in meta:
            if (name.startswith('eqnos') or name.startswith('xnos')) and \
                    name not in metanames:
                msg = textwrap.dedent("""
                          pandoc-eqnos: unknown meta variable "%s"\n
                      """ % name)
                STDERR.write(msg)

    for name in ['eqnos-cleveref', 'xnos-cleveref']:
        # 'xnos-cleveref' enables cleveref in all 3 of fignos/eqnos/tablenos
        if name in meta:
            cleveref = check_bool(get_meta(meta, name))
            break

    for name in ['xnos-capitalise', 'xnos-capitalize']:
        # 'xnos-capitalise' enables capitalise in all 3 of
        # fignos/eqnos/tablenos.  Since this uses an option in the caption
        # package, it is not possible to select between the three (use
        # 'eqnos-plus-name' instead.  'xnos-capitalize' is an alternative
        # spelling
        if name in meta:
            capitalise = check_bool(get_meta(meta, name))
            break

    if 'eqnos-plus-name' in meta:
        tmp = get_meta(meta, 'eqnos-plus-name')
        old_plusname = copy.deepcopy(plusname)
        if isinstance(tmp, list):  # The singular and plural forms were given
            plusname = tmp
        else:  # Only the singular form was given
            plusname[0] = tmp
        plusname_changed = plusname != old_plusname
        assert len(plusname) == 2
        for name in plusname:
            assert isinstance(name, STRTYPES)
        if plusname_changed:
            starname = [name.title() for name in plusname]

    if 'eqnos-star-name' in meta:
        tmp = get_meta(meta, 'eqnos-star-name')
        old_starname = copy.deepcopy(starname)
        if isinstance(tmp, list):
            starname = tmp
        else:
            starname[0] = tmp
        starname_changed = starname != old_starname
        assert len(starname) == 2
        for name in starname:
            assert isinstance(name, STRTYPES)

    for name in ['eqnos-number-by-section', 'xnos-number-by-section']:
        if name in meta:
            numbersections = check_bool(get_meta(meta, name))
            break

    if 'xnos-number-offset' in meta:
        secoffset = int(get_meta(meta, 'xnos-number-offset'))

    if 'eqnos-eqref' in meta:
        eqref = check_bool(get_meta(meta, 'eqnos-eqref'))
        # Note: Eqref and cleveref are mutually exclusive.  If both are
        # enabled, then cleveref will be used but with bracketed equation
        # numbers.

    if 'eqnos-default-env' in meta:
        default_env = get_meta(meta, 'eqnos-default-env')
Ejemplo n.º 12
0
def process(meta):
    """Saves metadata fields in global variables and returns a few
    computed fields."""

    # pylint: disable=global-statement
    global cleveref      # Flags that clever references should be used
    global capitalise    # Flags that plusname should be capitalised
    global plusname      # Sets names for mid-sentence references
    global starname      # Sets names for references at sentence start
    global secoffset     # Section number offset
    global warninglevel  # 0 - no warnings; 1 - some; 2 - all

    # Read in the metadata fields and do some checking

    for name in ['secnos-warning-level', 'xnos-warning-level']:
        if name in meta:
            warninglevel = int(get_meta(meta, name))
            pandocxnos.set_warning_level(warninglevel)
            break

    metanames = ['secnos-warning-level', 'xnos-warning-level',
                 'secnos-cleveref', 'xnos-cleveref',
                 'xnos-capitalise', 'xnos-capitalize',
                 'xnos-caption-separator', # Used by pandoc-fignos/tablenos
                 'secnos-plus-name', 'secnos-star-name',
                 'xnos-number-by-section', 'xnos-number-offset']

    if warninglevel:
        for name in meta:
            if (name.startswith('secnos') or name.startswith('xnos')) and \
              name not in metanames:
                msg = textwrap.dedent("""
                          pandoc-secnos: unknown meta variable "%s"\n
                      """ % name)
                STDERR.write(msg)

    for name in ['secnos-cleveref', 'xnos-cleveref']:
        # 'xnos-cleveref' enables cleveref in all four of
        # fignos/eqnos/tablenos/secnos
        if name in meta:
            cleveref = check_bool(get_meta(meta, name))
            break

    for name in ['xnos-capitalise', 'xnos-capitalize']:
        # 'xnos-capitalise' enables capitalise in all four of
        # fignos/eqnos/tablenos/secnos.  Since this uses an option in the
        # caption package, it is not possible to select between the three (use
        # 'secnos-plus-name' instead.  'xnos-capitalize' is an alternative
        # spelling
        if name in meta:
            capitalise = check_bool(get_meta(meta, name))
            break

    if 'secnos-plus-name' in meta:

        value = get_meta(meta, 'secnos-plus-name')

        if isinstance(value, str):
            try:
                value_ = \
                  dict(itemstr.split(':') for itemstr in value.split(','))
                for division in value_:
                    set_name('plus', division, value_[division])
            except ValueError:
                set_name('plus', 'section', value)
        else:  # Dict expected
            for division in value:
                set_name('plus', division, value[division])

    if 'secnos-star-name' in meta:

        value = get_meta(meta, 'secnos-star-name')

        if isinstance(value, str):
            try:
                value_ = \
                  dict(itemstr.split(':') for itemstr in value.split(','))
                for division in value_:
                    set_name('star', division, value_[division])
            except ValueError:
                set_name('star', 'section', value)
        else:  # Dict expected
            for division in value:
                set_name('star', division, value[division])

    if 'xnos-number-offset' in meta:
        secoffset = int(get_meta(meta, 'xnos-number-offset'))
Ejemplo n.º 13
0
def main(stdin=STDIN, stdout=STDOUT, stderr=STDERR):
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION

    # Read the command-line arguments
    parser = argparse.ArgumentParser(\
      description='Pandoc theorem numbers filter.')
    parser.add_argument(\
      '--version', action='version',
      version='%(prog)s {version}'.format(version=__version__))
    parser.add_argument('fmt')
    parser.add_argument('--pandocversion', help='The pandoc version.')
    args = parser.parse_args()

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(stdin.read())

    # Initialize pandocxnos
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    if LABEL_PATTERN:
        # First pass
        insert_secnos = insert_secnos_factory(Span)
        delete_secnos = delete_secnos_factory(Span)
        altered = functools.reduce(
            lambda x, action: walk(x, action, fmt, meta),
            [insert_secnos, process_theorems, delete_secnos], blocks)

        # Second pass
        if fmt in ('latex', 'beamer'):
            process_refs = process_refs_factory(LABEL_PATTERN, targets.keys())

            STDERR.write('\n')
            STDERR.write(str(LABEL_PATTERN))
            STDERR.write('\n')

            # Latex takes care of inserting the correct plusname/starname
            replace_refs = replace_refs_factory(targets, cleveref, False,
                                                ['UNUSED'], ['UNUSED'])

            process_all_refs = [process_refs, replace_refs]
        else:
            # Replace each theorem type separately (to insert the correct names)
            process_all_refs = []

            for thid, thname in names.items():
                refs = {}
                for key, value in targets.items():
                    if key.split(':')[0] == thid:
                        refs[key] = value
                if refs:

                    PATTERN = re.compile("%s:%s" % (thid, r'[\w/-]*'))
                    process_refs = process_refs_factory(PATTERN, refs.keys())
                    replace_refs = replace_refs_factory(
                        refs, cleveref, False, [thname], [thname])

                    process_all_refs.append(process_refs)
                    process_all_refs.append(replace_refs)

        attach_attrs_span = attach_attrs_factory('pandoc-theoremnos',
                                                 Span,
                                                 replace=True)
        altered = functools.reduce(
            lambda x, action: walk(x, action, fmt, meta),
            [repair_refs] + process_all_refs + [attach_attrs_span], altered)

        if fmt in ['latex', 'beamer']:
            add_tex(meta)

        # Update the doc
        if PANDOCVERSION >= '1.18':
            doc['blocks'] = altered
        else:
            doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, stdout)

    # Flush stdout
    stdout.flush()
Ejemplo n.º 14
0
def process(meta):
    """Saves metadata fields in global variables and returns a few
    computed fields."""

    # pylint: disable=global-statement
    global cleveref  # Flags that clever references should be used
    global capitalise  # Flags that plusname should be capitalised
    global names  # Sets theorem types and names
    global warninglevel  # 0 - no warnings; 1 - some; 2 - all
    global LABEL_PATTERN
    global numbersections
    global secoffset
    global sharedcounter

    # Read in the metadata fields and do some checking

    for name in ['theoremnos-warning-level', 'xnos-warning-level']:
        if name in meta:
            warninglevel = int(get_meta(meta, name))
            pandocxnos.set_warning_level(warninglevel)
            break

    metanames = [
        'theoremnos-warning-level',
        'xnos-warning-level',
        'theoremnos-cleveref',
        'xnos-cleveref',
        'xnos-capitalise',
        'xnos-capitalize',
        'xnos-caption-separator',  # Used by pandoc-fignos/tablenos
        'theoremnos-names',
        'xnos-number-by-section',
        'theoremnos-shared-counter',
        'theoremnos-number-by-section',
        'xnos-number-offset'
    ]

    if warninglevel:
        for name in meta:
            if (name.startswith('theoremnos') or name.startswith('xnos')) and \
              name not in metanames:
                msg = textwrap.dedent("""
                          pandoc-theoremnos: unknown meta variable "%s"\n
                      """ % name)
                STDERR.write(msg)

    for name in ['theoremnos-cleveref', 'xnos-cleveref']:
        # 'xnos-cleveref' enables cleveref in all 3 of fignos/eqnos/tablenos
        if name in meta:
            cleveref = check_bool(get_meta(meta, name))
            break

    for name in ['xnos-capitalise', 'xnos-capitalize']:
        # 'xnos-capitalise' enables capitalise in all 4 of
        # fignos/eqnos/tablenos/theoremonos.  Since this uses an option in
        # the caption package, it is not possible to select between the four.
        # 'xnos-capitalize' is an alternative spelling
        if name in meta:
            capitalise = check_bool(get_meta(meta, name))
            break

    for name in ['theoremnos-number-by-section', 'xnos-number-by-section']:
        if name in meta:
            numbersections = check_bool(get_meta(meta, name))
            break

    if 'xnos-number-offset' in meta:
        secoffset = int(get_meta(meta, 'xnos-number-offset'))

    if 'theoremnos-shared-counter' in meta:
        sharedcounter = check_bool(get_meta(meta, 'theoremnos-shared-counter'))

    if 'theoremnos-names' in meta:
        assert meta['theoremnos-names']['t'] == 'MetaList'
        for entry in get_meta(meta, 'theoremnos-names'):
            assert isinstance(entry, dict), "%s is of type %s" % \
              (entry, type(entry))
            assert 'id' in entry and isinstance(entry['id'], STRTYPES)
            assert 'name' in entry and isinstance(entry['name'], STRTYPES)
            names[entry['id']] = entry['name']
            Ntargets[entry['id']] = 0

        Ntargets['shared'] = 0

    if names:
        LABEL_PATTERN = \
          re.compile("(%s):%s" % ('|'.join(names.keys()), r'[\w/-]*'))