Last active
March 4, 2016 14:23
-
-
Save rbdixon/f8072fc4db5605c3d92d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Pandoc filter to allow interpolation of metadata fields | |
into a document. %{fields} will be replaced by the field's | |
value, assuming it is of the type MetaInlines or MetaString. | |
""" | |
import sys | |
from pandocfilters import toJSONFilter, attributes, Span, Str, Table | |
import re | |
pattern = re.compile('([^%]*)%\{(.*)\}([^%]*)') | |
def metavars(key, value, format, meta): | |
if key == 'Str': | |
m = pattern.match(value) | |
if m: | |
pre = m.group(1) | |
field = m.group(2) | |
post = m.group(3) | |
result = meta.get(field, {}) | |
if result: | |
if 'MetaInlines' in result['t']: | |
return Span(attributes({'class': 'interpolated', | |
'field': field}), | |
[Str(pre)] + result['c'] + [Str(post)]) | |
elif 'MetaString' in result['t']: | |
return Str(result['c']) | |
elif 'MetaBlocks' in result['t']: | |
res = result['c'][0]['c'] | |
# res = Table( tab[0], tab[1], tab[2], tab[3], tab[4]) | |
sys.stderr.write("\n{0} -> {1}\n\n".format(field, repr(res))) | |
return res | |
else: | |
sys.stderr.write("\n\nError: Variable %{{{0}}} used but not declared in document.\n\n".format(field)) | |
exit(-1) | |
if __name__ == "__main__": | |
toJSONFilter(metavars) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment