Exemple #1
0
    def test_process_refs_factory_2(self):
        """Tests process_refs_factory() #2."""

        ## test.md: (@eq:one) ##

        # Command: pandoc test.md -t json
        src = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"("},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"eq:one","citationHash":0}],[{"t":"Str","c":"@eq:one"}]]},{"t":"Str","c":")"}]}],"pandoc-api-version":[1,17,3],"meta":{}}'''
        )

        # Check src against current pandoc
        md = subprocess.Popen(('echo', '(@eq:one)'), stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output('pandoc -t json'.split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded (attributes added)
        expected = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"("},{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"eq:one","citationHash":0}],[{"t":"Str","c":"@eq:one"}]]},{"t":"Str","c":")"}]}],"pandoc-api-version":[1,17,3],"meta":{}}'''
        )

        # Make the comparison
        process_refs = process_refs_factory(['eq:one'])
        self.assertEqual(walk(src, process_refs, '', {}), expected)
Exemple #2
0
    def test_process_refs_factory_1(self):
        """Tests process_refs_factory() #1."""

        ## test.md: As shown in @fig:one. ##

        # Command: pandoc test.md -t json
        src = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"As"},{"t":"Space"},{"t":"Str","c":"shown"},{"t":"Space"},{"t":"Str","c":"in"},{"t":"Space"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":1,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"fig:one","citationHash":0}],[{"t":"Str","c":"@fig:one"}]]},{"t":"Str","c":"."}]}],"pandoc-api-version":[%s],"meta":{}}'''
            % PANDOC_API_VERSION)

        # Check src against current pandoc
        md = subprocess.Popen(('echo', 'As shown in @fig:one.'),
                              stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output((PANDOC + ' -t json').split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded (added empty attributes)
        expected = eval(
            r'''{"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"As"},{"t":"Space"},{"t":"Str","c":"shown"},{"t":"Space"},{"t":"Str","c":"in"},{"t":"Space"},{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":1,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"fig:one","citationHash":0}],[{"t":"Str","c":"@fig:one"}]]},{"t":"Str","c":"."}]}],"pandoc-api-version":[%s]}'''
            % PANDOC_API_VERSION)

        # Make the comparison
        process_refs = process_refs_factory(None, ['fig:one'], 0)
        self.assertEqual(walk(src, process_refs, '', {}), expected)
Exemple #3
0
    def test_process_refs_factory_7(self):
        """Tests process_refs_factory() #7."""

        ## test.md: See [+@eq:1]. ##

        # Command: pandoc test.md -t json
        src = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"See"},{"t":"Space"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":1,"citationMode":{"t":"NormalCitation"},"citationPrefix":[{"t":"Str","c":"+"}],"citationId":"eq:1","citationHash":0}],[{"t":"Str","c":"[+@eq:1]"}]]},{"t":"Str","c":"."}]}],"pandoc-api-version":[%s],"meta":{}}'''
            % PANDOC_API_VERSION)

        # Check src against current pandoc
        md = subprocess.Popen(('echo', 'See [+@eq:1].'),
                              stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output((PANDOC + ' -t json').split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded (modifier extracted, attributes added)
        expected = eval(
            r'''{"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"See"},{"t":"Space"},{"t":"Cite","c":[["",[],[["modifier","+"]]],[{"citationSuffix":[],"citationNoteNum":1,"citationMode":{"t":"NormalCitation"},"citationPrefix":[],"citationId":"eq:1","citationHash":0}],[{"t":"Str","c":"[+@eq:1]"}]]},{"t":"Str","c":"."}]}],"pandoc-api-version":[%s]}'''
            % PANDOC_API_VERSION)

        # Make the comparison
        process_refs = process_refs_factory(None, ['eq:1'], 0)
        self.assertEqual(walk(src, process_refs, '', {}), expected)
Exemple #4
0
    def test_process_refs_factory_9(self):
        """Tests process_refs_factory() #9."""

        ## test.md: {@fig:1}:

        # See previous unit test

        # Command: pandoc-1.15.2 test.md -t json
        src = eval(
            r'''[{"unMeta":{}},[{"t":"Para","c":[{"t":"Str","c":"{"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText","c":[]},"citationPrefix":[],"citationId":"fig:1","citationHash":0}],[{"t":"Str","c":"@fig:1"}]]},{"t":"Str","c":"}:"}]}]]'''
        )

        # Check against pandoc-1.15.2
        md = subprocess.Popen(('echo', '{@fig:1}:'), stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output((PANDOC1p15 + ' -t json').split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded
        expected = eval(
            r'''[{"unMeta":{}},[{"t":"Para","c":[{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText","c":[]},"citationPrefix":[],"citationId":"fig:1","citationHash":0}],[{"t":"Str","c":"@fig:1"}]]},{"t":"Str","c":":"}]}]]'''
        )

        # Make the comparison
        process_refs = process_refs_factory(['fig:1'])
        self.assertEqual(walk(src, process_refs, {}, ''), expected)
Exemple #5
0
    def test_use_refs_factory_8(self):
        """Tests use_refs_factory() #8."""

        ## test.md: @fig:1:

        # pandoc-1.15.2 doesn't detect references that end in a colon.  This
        # was fixed in subsequent versions of pandoc.  There is a trivial
        # workaround; use "{@fig:1}:" instead.  This is demonstrated in the
        # next unit test.  Given that there is a trivial work-around, this is
        # probably not worth fixing.

        # Command: pandoc-1.15.2 test.md -t json
        src = eval(
            r'''[{"unMeta":{}},[{"t":"Para","c":[{"t":"Str","c":"@fig:1:"}]}]]'''
        )

        # Check against pandoc-1.15.2
        md = subprocess.Popen(('echo', '@fig:1:'), stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output((PANDOC1p15 + ' -t json').split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Generate expected using current pandoc
        md = subprocess.Popen(('echo', '@fig:1:'), stdout=subprocess.PIPE)
        expected = eval(
            subprocess.check_output('pandoc -t json'.split(),
                                    stdin=md.stdout).strip())

        # Make the comparison
        process_refs = process_refs_factory(['fig:1'])
        self.assertEqual(walk(src, process_refs, {}, ''), expected)
def main():
    """Filters the document AST."""

    # Get the output format, document and metadata
    fmt = args.fmt
    doc = json.loads(STDIN.read())
    meta = doc[0]['unMeta']

    # Process the metadata variables
    process(meta)

    # First pass
    altered = functools.reduce(
        lambda x, action: walk(x, action, fmt, meta),
        [attach_attrs_math, process_equations, detach_attrs_math], doc)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references, cleveref_default, plusname,
                                        starname, 'equation')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Dump the results
    json.dump(altered, STDOUT)

    # Flush stdout
    STDOUT.flush()
Exemple #7
0
    def test_use_refs_factory_8(self):
        """Tests use_refs_factory() #8."""

        ## test.md: @fig:1:

        # pandoc-1.15.2 doesn't detect references that end in a colon.  This
        # was fixed in subsequent versions of pandoc.  There is a trivial
        # workaround; use "{@fig:1}:" instead.  This is demonstrated in the
        # next unit test.  Given that there is a trivial work-around, this is
        # probably not worth fixing.

        # Command: pandoc-1.15.2 test.md -t json
        src = eval(r'''[{"unMeta":{}},[{"t":"Para","c":[{"t":"Str","c":"@fig:1:"}]}]]''')

        # Check against pandoc-1.15.2
        md = subprocess.Popen(('echo', '@fig:1:'), stdout=subprocess.PIPE)
        output = eval(subprocess.check_output(
            (PANDOC1p15 + ' -t json').split(), stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Generate expected using current pandoc
        md = subprocess.Popen(('echo', '@fig:1:'), stdout=subprocess.PIPE)
        expected = eval(subprocess.check_output(
            'pandoc -t json'.split(), stdin=md.stdout).strip())

        # Make the comparison
        process_refs = process_refs_factory(['fig:1'])
        self.assertEqual(walk(src, process_refs, {}, ''), expected)
Exemple #8
0
    def test_use_refs_factory_7(self):
        """Tests use_refs_factory() #7."""

        ## test.md: {+@tbl:one}-{@tbl:four} provide the data. ##

        # Command: pandoc test.md -t json
        src = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"{+"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:one","citationHash":0}],[{"t":"Str","c":"@tbl:one"}]]},{"t":"Str","c":"}-{"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:four","citationHash":0}],[{"t":"Str","c":"@tbl:four"}]]},{"t":"Str","c":"}"},{"t":"Space"},{"t":"Str","c":"provide"},{"t":"Space"},{"t":"Str","c":"the"},{"t":"Space"},{"t":"Str","c":"data."}]}],"pandoc-api-version":[1,17,3],"meta":{}}'''
        )

        # Check src against current pandoc
        md = subprocess.Popen(
            ('echo', '{+@tbl:one}-{@tbl:four} provide the data.'),
            stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output('pandoc -t json'.split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded
        expected = eval(
            r'''{"meta":{},"blocks":[{"t":"Para","c":[{"t":"Cite","c":[["",[],[["modifier","+"]]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:one","citationHash":0}],[{"t":"Str","c":"@tbl:one"}]]},{"t":"Str","c":"-"},{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:four","citationHash":0}],[{"t":"Str","c":"@tbl:four"}]]},{"t":"Space"},{"t":"Str","c":"provide"},{"t":"Space"},{"t":"Str","c":"the"},{"t":"Space"},{"t":"Str","c":"data."}]}],"pandoc-api-version":[1,17,3]}'''
        )

        # Make the comparison
        process_refs = process_refs_factory(['tbl:one', 'tbl:four'])
        self.assertEqual(walk(src, process_refs, '', {}), expected)
Exemple #9
0
    def test_process_refs_factory_6(self):
        """Tests process_refs_factory() #6."""

        ## test.md: See xxx{+@tbl:1}xxx. ##

        # Command: pandoc test.md -t json
        src = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"See"},{"t":"Space"},{"t":"Str","c":"xxx{+"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:1","citationHash":0}],[{"t":"Str","c":"@tbl:1"}]]},{"t":"Str","c":"}xxx."}]}],"pandoc-api-version":[1,17,3],"meta":{}}'''
        )

        # Check src against current pandoc
        md = subprocess.Popen(('echo', 'See xxx{+@tbl:1}xxx.'),
                              stdout=subprocess.PIPE)
        output = eval(
            subprocess.check_output('pandoc -t json'.split(),
                                    stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded (braces stripped, modifier extracted, attributes added)
        expected = eval(
            r'''{"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"See"},{"t":"Space"},{"t":"Str","c":"xxx"},{"t":"Cite","c":[["",[],[["modifier","+"]]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:1","citationHash":0}],[{"t":"Str","c":"@tbl:1"}]]},{"t":"Str","c":"xxx."}]}],"pandoc-api-version":[1,17,3]}'''
        )

        # Make the comparison
        process_refs = process_refs_factory(['tbl:1'])
        self.assertEqual(walk(src, process_refs, '', {}), expected)
Exemple #10
0
def main():
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrMath

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

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrMath = elt('Math', 3)

    # 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)

    # First pass
    attach_attrs_math = attach_attrs_factory(Math, allow_space=True)
    detach_attrs_math = detach_attrs_factory(Math)
    insert_secnos = insert_secnos_factory(Math)
    delete_secnos = delete_secnos_factory(Math)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_math, insert_secnos,
                                process_equations, delete_secnos,
                                detach_attrs_math], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, use_eqref,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'equation')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # 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()
Exemple #11
0
def main(stdin=STDIN, stdout=STDOUT, stderr=STDERR):
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION

    # 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 version(PANDOCVERSION) >= version('1.18') \
      else doc[0]['unMeta']
    blocks = doc['blocks'] if version(PANDOCVERSION) >= version('1.18') \
      else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [process_sections], blocks)

    # Second pass
    process_refs = process_refs_factory(LABEL_PATTERN, targets.keys())
    replace_refs = \
      replace_refs_factory(targets, cleveref, False,
                           plusname['section'] if not capitalise or \
                           plusname_changed['section'] else \
                           [name.title() for name in plusname['section']],
                           starname['section'], allow_implicit_refs=True)
    attach_attrs_span = attach_attrs_factory(Span, replace=True)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs,
                                attach_attrs_span],
                               altered)

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

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

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

    # Flush stdout
    stdout.flush()
Exemple #12
0
def main():
    """Filters the document AST."""

    # Get the output format, document and metadata
    fmt = args.fmt
    doc = json.loads(STDIN.read())
    meta = doc[0]['unMeta']

    # Process the metadata variables
    process(meta)

    # First pass
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_image, process_figures,
                                detach_attrs_image], doc)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references, cleveref_default,
                                        plusname, starname, 'figure')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)


    # Insert supporting TeX
    if fmt == 'latex':

        rawblocks = []

        if has_unnumbered_figures:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Figure':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)


    # Dump the results
    json.dump(altered, STDOUT)

    # Flush stdout
    STDOUT.flush()
Exemple #13
0
    def test_process_refs_factory_6(self):
        """Tests process_refs_factory() #6."""

        ## test.md: See xxx{+@tbl:1}xxx. ##

        # Command: pandoc test.md -t json
        src = eval(r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"See"},{"t":"Space"},{"t":"Str","c":"xxx{+"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:1","citationHash":0}],[{"t":"Str","c":"@tbl:1"}]]},{"t":"Str","c":"}xxx."}]}],"pandoc-api-version":[1,17,5,1],"meta":{}}''')

        # Check src against current pandoc
        md = subprocess.Popen(('echo', 'See xxx{+@tbl:1}xxx.'), stdout=subprocess.PIPE)
        output = eval(subprocess.check_output(
            'pandoc -t json'.split(), stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded (braces stripped, modifier extracted, attributes added)
        expected = eval(r'''{"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"See"},{"t":"Space"},{"t":"Str","c":"xxx"},{"t":"Cite","c":[["",[],[["modifier","+"]]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:1","citationHash":0}],[{"t":"Str","c":"@tbl:1"}]]},{"t":"Str","c":"xxx."}]}],"pandoc-api-version":[1,17,5,1]}''')

        # Make the comparison
        process_refs = process_refs_factory(['tbl:1'])
        self.assertEqual(walk(src, process_refs, '', {}), expected)
def main():
    """Filters the document AST."""

    # Get the output format, document and metadata
    fmt = args.fmt
    doc = json.loads(STDIN.read())
    meta = doc[0]['unMeta']

    # Process the metadata variables
    process(meta)

    # First pass
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_table, process_tables,
                                detach_attrs_table], doc)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references, cleveref_default,
                                        plusname, starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Assemble supporting TeX
    if fmt == 'latex':
        tex = ['% Tablenos directives']

        # Change caption name
        if captionname != 'Table':
            tex.append(r'\renewcommand{\tablename}{%s}'%captionname)

        if len(tex) > 1:
            altered[1] = [RawBlock('tex', '\n'.join(tex))] + altered[1]

    # Dump the results
    json.dump(altered, STDOUT)

    # Flush stdout
    STDOUT.flush()
Exemple #15
0
    def test_process_refs_factory_9(self):
        """Tests process_refs_factory() #9."""

        ## test.md: {@fig:1}:

        # See previous unit test

        # Command: pandoc-1.15.2 test.md -t json
        src = eval(r'''[{"unMeta":{}},[{"t":"Para","c":[{"t":"Str","c":"{"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText","c":[]},"citationPrefix":[],"citationId":"fig:1","citationHash":0}],[{"t":"Str","c":"@fig:1"}]]},{"t":"Str","c":"}:"}]}]]''')

        # Check against pandoc-1.15.2
        md = subprocess.Popen(('echo', '{@fig:1}:'), stdout=subprocess.PIPE)
        output = eval(subprocess.check_output(
            (PANDOC1p15 + ' -t json').split(), stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded
        expected = eval(r'''[{"unMeta":{}},[{"t":"Para","c":[{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText","c":[]},"citationPrefix":[],"citationId":"fig:1","citationHash":0}],[{"t":"Str","c":"@fig:1"}]]},{"t":"Str","c":":"}]}]]''')

        # Make the comparison
        process_refs = process_refs_factory(['fig:1'])
        self.assertEqual(walk(src, process_refs, {}, ''), expected)
Exemple #16
0
    def test_use_refs_factory_7(self):
        """Tests use_refs_factory() #7."""

        ## test.md: {+@tbl:one}-{@tbl:four} provide the data. ##

        # Command: pandoc test.md -t json
        src = eval(r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"{+"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:one","citationHash":0}],[{"t":"Str","c":"@tbl:one"}]]},{"t":"Str","c":"}-{"},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:four","citationHash":0}],[{"t":"Str","c":"@tbl:four"}]]},{"t":"Str","c":"}"},{"t":"Space"},{"t":"Str","c":"provide"},{"t":"Space"},{"t":"Str","c":"the"},{"t":"Space"},{"t":"Str","c":"data."}]}],"pandoc-api-version":[1,17,5,1],"meta":{}}''')

        # Check src against current pandoc
        md = subprocess.Popen(
            ('echo', '{+@tbl:one}-{@tbl:four} provide the data.'),
            stdout=subprocess.PIPE)
        output = eval(subprocess.check_output(
            'pandoc -t json'.split(), stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded
        expected = eval(r'''{"meta":{},"blocks":[{"t":"Para","c":[{"t":"Cite","c":[["",[],[["modifier","+"]]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:one","citationHash":0}],[{"t":"Str","c":"@tbl:one"}]]},{"t":"Str","c":"-"},{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"tbl:four","citationHash":0}],[{"t":"Str","c":"@tbl:four"}]]},{"t":"Space"},{"t":"Str","c":"provide"},{"t":"Space"},{"t":"Str","c":"the"},{"t":"Space"},{"t":"Str","c":"data."}]}],"pandoc-api-version":[1,17,5,1]}''')

        # Make the comparison
        process_refs = process_refs_factory(['tbl:one', 'tbl:four'])
        self.assertEqual(walk(src, process_refs, '', {}), expected)
Exemple #17
0
    def test_process_refs_factory_2(self):
        """Tests process_refs_factory() #2."""

        ## test.md: (@eq:one) ##

        # Command: pandoc test.md -t json
        src = eval(
            r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"("},{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"eq:one","citationHash":0}],[{"t":"Str","c":"@eq:one"}]]},{"t":"Str","c":")"}]}],"pandoc-api-version":[1,17,5,1],"meta":{}}''')

        # Check src against current pandoc
        md = subprocess.Popen(('echo', '(@eq:one)'), stdout=subprocess.PIPE)
        output = eval(subprocess.check_output(
            'pandoc -t json'.split(),
            stdin=md.stdout).strip())
        self.assertEqual(src, output)

        # Hand-coded (attributes added)
        expected = eval(r'''{"blocks":[{"t":"Para","c":[{"t":"Str","c":"("},{"t":"Cite","c":[["",[],[]],[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"AuthorInText"},"citationPrefix":[],"citationId":"eq:one","citationHash":0}],[{"t":"Str","c":"@eq:one"}]]},{"t":"Str","c":")"}]}],"pandoc-api-version":[1,17,5,1],"meta":{}}''')

        # Make the comparison
        process_refs = process_refs_factory(['eq:one'])
        self.assertEqual(walk(src, process_refs, '', {}), expected)
def main():
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrTable

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

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrTable = elt('Table', 6)

    # 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)

    # First pass
    detach_attrs_table = detach_attrs_factory(Table)
    insert_secnos = insert_secnos_factory(Table)
    delete_secnos = delete_secnos_factory(Table)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_table, insert_secnos,
                                process_tables, delete_secnos,
                                detach_attrs_table], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, False,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt in ['latex']:

        rawblocks = []

        if has_unnumbered_tables:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Table':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)

    # 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()
Exemple #19
0
def main():
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrTable

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

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrTable = elt('Table', 6)

    # 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)

    # First pass
    detach_attrs_table = detach_attrs_factory(Table)
    insert_secnos = insert_secnos_factory(Table)
    delete_secnos = delete_secnos_factory(Table)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta), [
        attach_attrs_table, insert_secnos, process_tables, delete_secnos,
        detach_attrs_table
    ], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(
        references, use_cleveref_default, False,
        plusname if not capitalize else [name.title() for name in plusname],
        starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt in ['latex']:

        rawblocks = []

        if has_unnumbered_tables:
            rawblocks += [
                RawBlock('tex', TEX0),
                RawBlock('tex', TEX1),
                RawBlock('tex', TEX2)
            ]

        if captionname != 'Table':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(
            lambda x, action: walk(x, action, fmt, meta), [insert_rawblocks],
            altered)

    # 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()
Exemple #20
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()
Exemple #21
0
def main(stdin=STDIN, stdout=STDOUT, stderr=STDERR):
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrMath

    # Read the command-line arguments
    parser = argparse.ArgumentParser( \
        description='Pandoc equations 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)

    # Element primitives
    AttrMath = elt('Math', 3)

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

    # Process the metadata variables
    process(meta)

    # First pass
    attach_attrs_math = attach_attrs_factory(Math, allow_space=True)
    detach_attrs_math = detach_attrs_factory(Math)
    insert_secnos = insert_secnos_factory(Math)
    delete_secnos = delete_secnos_factory(Math)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta), [
        attach_attrs_math, insert_secnos, process_equations, delete_secnos,
        detach_attrs_math
    ], blocks)

    # Second pass
    process_refs = process_refs_factory(LABEL_PATTERN, targets.keys())
    replace_refs = replace_refs_factory(targets,
                                        cleveref, eqref,
                                        plusname if not capitalise or \
                                                    plusname_changed else
                                        [name.title() for name in plusname],
                                        starname)
    attach_attrs_span = attach_attrs_factory(Span, replace=True)
    altered = functools.reduce(
        lambda x, action: walk(x, action, fmt, meta),
        [repair_refs, process_refs, replace_refs, attach_attrs_span], altered)

    if fmt in ['latex', 'beamer']:
        add_tex(meta)
    elif fmt in ['html', 'html4', 'html5', 'epub', 'epub2', 'epub3']:
        add_html(meta, fmt)

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

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

    # Flush stdout
    stdout.flush()
Exemple #22
0
def main(stdin=STDIN, stdout=STDOUT, stderr=STDERR):
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global Image

    # Read the command-line arguments
    parser = argparse.ArgumentParser(\
      description='Pandoc figure 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)

    # Element primitives
    if PANDOCVERSION < '1.16':
        Image = elt('Image', 2)

    # 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)

    # First pass
    replace = PANDOCVERSION >= '1.16'
    attach_attrs_image = attach_attrs_factory(Image,
                                              extract_attrs=_extract_attrs,
                                              replace=replace)
    detach_attrs_image = detach_attrs_factory(Image)
    insert_secnos_img = insert_secnos_factory(Image)
    delete_secnos_img = delete_secnos_factory(Image)
    insert_secnos_div = insert_secnos_factory(Div)
    delete_secnos_div = delete_secnos_factory(Div)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta), [
        attach_attrs_image, insert_secnos_img, insert_secnos_div,
        process_figures, delete_secnos_img, delete_secnos_div,
        detach_attrs_image
    ], blocks)

    # Second pass
    process_refs = process_refs_factory(LABEL_PATTERN, targets.keys())
    replace_refs = replace_refs_factory(targets, cleveref, False,
                                        plusname if not capitalise \
                                        or plusname_changed else
                                        [name.title() for name in plusname],
                                        starname)
    attach_attrs_span = attach_attrs_factory(Span, replace=True)
    altered = functools.reduce(
        lambda x, action: walk(x, action, fmt, meta),
        [repair_refs, process_refs, replace_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()
def main():
    """Filters the document AST."""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global Image

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

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    if PANDOCVERSION < '1.16':
        Image = elt('Image', 2)

    # 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)

    # First pass
    attach_attrs_image = attach_attrs_factory(Image,
                                              extract_attrs=_extract_attrs)
    detach_attrs_image = detach_attrs_factory(Image)
    insert_secnos = insert_secnos_factory(Image)
    delete_secnos = delete_secnos_factory(Image)
    filters = [insert_secnos, process_figures, delete_secnos] \
      if PANDOCVERSION >= '1.16' else \
      [attach_attrs_image, insert_secnos, process_figures,
       delete_secnos, detach_attrs_image]
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               filters, blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references, cleveref_default, plusname,
                                        starname, 'figure')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt == 'latex':

        rawblocks = []

        if has_unnumbered_figures:
            rawblocks += [
                RawBlock('tex', TEX0),
                RawBlock('tex', TEX1),
                RawBlock('tex', TEX2)
            ]

        if captionname != 'Figure':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(
            lambda x, action: walk(x, action, fmt, meta), [insert_rawblocks],
            altered)

    # 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()