Last active
January 6, 2016 19:29
-
-
Save bpj/f67d274c9a0688014ad9 to your computer and use it in GitHub Desktop.
Pandoc filter to wrap Span/Div in LaTeX based on classes
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 wrap Span/Div in LaTeX based on classes | |
""" | |
import pandocfilters as pf | |
import re | |
begin_command = None | |
end_command = None | |
want_latex = None | |
cmd_env_re = re.compile(r'(?u)^(\w+)-(cmd|env)$') | |
constructor_for = { 'Span': None, 'Div': None } | |
latex_for = { | |
'Span': { | |
'cmd': { | |
'begin': lambda c, n: pf.RawInline('tex', '\\' + n), | |
'end': lambda c, n: None, | |
}, | |
'env': { | |
'begin': lambda c, n: pf.RawInline('tex', r'\%s{%s} ' % (c, n)), | |
'end': lambda c, n: pf.RawInline('tex', r'\%s{%s}' % (c, n)), | |
}, | |
}, | |
'Div': { | |
'cmd': { | |
'begin': lambda c, n: pf.RawBlock('tex', r'\%s{' % n), | |
'end': lambda c, n: pf.RawBlock('tex', r'}'), | |
}, | |
'env': { | |
'begin': lambda c, n: pf.RawBlock('tex', r'\%s{%s}' % (c, n)), | |
'end': lambda c, n: pf.RawBlock('tex', r'\%s{%s}' % (c, n)), | |
}, | |
} | |
} | |
def expand(key, val, format, meta): | |
global begin_command, end_command, want_latex | |
if want_latex == None: | |
want_latex = format == 'latex' or meta.get('expand_latex', False) | |
if not want_latex or not key in ['Span', 'Div']: | |
return None | |
else: | |
cmd_env = dict([(c, m) for c in val[0][1] # classes | |
for m in [cmd_env_re.search(c)] if m]) | |
if not len(cmd_env): | |
return None | |
if begin_command == None: | |
begin_command = pf.stringify([meta.get('expand_begin')]) or 'begin' | |
if end_command == None: | |
end_command = pf.stringify([meta.get('expand_end')]) or 'end' | |
if constructor_for[key] == None: | |
constructor_for[key] = getattr(pf, key) | |
constructor = constructor_for[key] | |
val = list(val) # why is it a tuple? | |
val[0][1] = [c for c in val[0][1] if not c in cmd_env] | |
ret = [] | |
for (cls, match) in cmd_env.items(): | |
(name, cmd_or_env) = match.groups() | |
begin = latex_for[key][cmd_or_env]['begin'](begin_command, name) | |
end = latex_for[key][cmd_or_env]['end'](end_command, name) | |
if len(ret): | |
elem = constructor(["",[cls],[]], ret) | |
else: | |
val[0][1].append(cls) | |
elem = constructor(*val) | |
ret = [e for e in [begin, elem, end] if isinstance(e, dict) and 't' in e] | |
return ret | |
if __name__ == "__main__": | |
pf.toJSONFilter(expand) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment