Last active
December 13, 2021 22:40
-
-
Save DoomHammer/22b54b207c903f4f868e to your computer and use it in GitHub Desktop.
Quick-and-dirty pandoc filter to pass all code blocks through pygments highlighter
This file contains 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 pass all code blocks through pygments highlighter. | |
""" | |
from pandocfilters import toJSONFilter, RawBlock | |
from pygments import highlight | |
from pygments.lexers import (get_lexer_by_name, guess_lexer, TextLexer) | |
from pygments.formatters import get_formatter_by_name | |
def pygmentize(key, value, format, meta): | |
if key == 'CodeBlock': | |
[[ident, classes, keyvals], code] = value | |
lexer = None | |
for klass in classes: | |
try: | |
lexer = get_lexer_by_name(klass) | |
break | |
except: | |
pass | |
if lexer is None: | |
try: | |
lexer = guess_lexer(code) | |
except: | |
lexer = TextLexer() | |
return [RawBlock(format, highlight(code, lexer, get_formatter_by_name(format)))] | |
if __name__ == "__main__": | |
toJSONFilter(pygmentize) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment