-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpandoc-minted.py
executable file
·87 lines (63 loc) · 2.14 KB
/
pandoc-minted.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python
''' A pandoc filter that has the LaTeX writer use minted for typesetting code.
Usage:
pandoc --filter ./minted.py -o myfile.tex myfile.md
'''
from string import Template
from pandocfilters import toJSONFilter, RawBlock, RawInline
def unpack_code(value, language):
''' Unpack the body and language of a pandoc code element.
Args:
value contents of pandoc object
language default language
'''
[[_, classes, attributes], contents] = value
if len(classes) > 0:
language = classes[0]
attributes = ', '.join('='.join(x) for x in attributes)
return {'contents': contents, 'language': language,
'attributes': attributes}
def unpack_metadata(meta):
''' Unpack the metadata to get pandoc-minted settings.
Args:
meta document metadata
'''
settings = meta.get('pandoc-minted', {})
if settings.get('t', '') == 'MetaMap':
settings = settings['c']
# Get language.
language = settings.get('language', {})
if language.get('t', '') == 'MetaInlines':
language = language['c'][0]['c']
else:
language = None
return {'language': language}
else:
# Return default settings.
return {'language': 'text'}
def minted(key, value, format, meta):
''' Use minted for code in LaTeX.
Args:
key type of pandoc object
value contents of pandoc object
format target output format
meta document metadata
'''
if format != 'latex':
return
# Determine what kind of code object this is.
if key == 'CodeBlock':
template = Template(
'\\begin{minted}[$attributes]{$language}\n$contents\n\end{minted}'
)
Element = RawBlock
elif key == 'Code':
template = Template('\\mintinline[$attributes]{$language}{$contents}')
Element = RawInline
else:
return
settings = unpack_metadata(meta)
code = unpack_code(value, settings['language'])
return [Element(format, template.substitute(code))]
if __name__ == '__main__':
toJSONFilter(minted)