Skip to content

Instantly share code, notes, and snippets.

@DoomHammer
Last active December 13, 2021 22:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DoomHammer/22b54b207c903f4f868e to your computer and use it in GitHub Desktop.
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
#!/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