Last active
September 18, 2023 13:58
-
-
Save jepio/3ecaa6bba2a53ff74f2e to your computer and use it in GitHub Desktop.
Pandoc filter to use minted for syntax highlighting
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 python3 | |
''' | |
Filter to wrap Pandoc's CodeBlocks into minted blocks when using latex. | |
Pandoc's `fence_code_attributes` can be used to provide: | |
- the language (first class) | |
- minted's argumentless options (following classes) | |
- minted's options with arguments (attributes) | |
''' | |
from pandocfilters import toJSONFilter, RawBlock | |
TEMPLATE = r''' | |
\begin{{minted}}[{options}]{{{lang}}} | |
{cont} | |
\end{{minted}} | |
'''.strip() | |
def latex(x): | |
return RawBlock('latex', x) | |
def join_options(opts): | |
return ',\n'.join(opts) | |
def process_atts(kws): | |
'''Preprocess the attributes provided by pandoc - they come as a list of | |
2-lists, convert to a list of strings''' | |
return ['%s=%s' % (l, r) for l, r in kws] | |
def mintedify(key, value, format_, meta): | |
if key == 'CodeBlock': | |
(ident, classes, attributes), contents = value | |
if format_ == 'latex' and classes: | |
language, *pos = classes | |
atts = process_atts(attributes) | |
return [latex(TEMPLATE.format(lang=language, | |
options=join_options(pos+atts), | |
cont=contents))] | |
if __name__ == '__main__': | |
toJSONFilter(mintedify) |
This simple filter works perfectly fine for me, thanks a lot @jepio!
Glad to hear that. I last used this in 2016 for my master thesis.
To handle beamer output(I thought beamer is latex. 🤔 ), use
format_ in ['latex', 'beamer']
And add {.fragile}
following section title
# section 1 {.fragile}
I wonder if there is way to automatically add it
@iphilgood I figured out it is mint weirdness. If your output directory (contains .aux files) is not the same as where tex src is, you need to explicitly tell minted by,
\usepackage[outputdir=OUTDIR]{minted}
Now, I need to figure out how to pass the outdir from Makefile.
I wonder if there is way to automatically add it
I made a hacked filter for doing this here https://github.com/alexfanqi/pandoc_beamer_solarized/blob/master/fragile.py
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had to change:
to
with
pandocfilters==1.4.2
. The first element appears to be the string"sourceCode"
.