diff options
author | HampusM <hampus@hampusmat.com> | 2021-12-14 12:38:33 +0100 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2021-12-14 12:38:33 +0100 |
commit | 362c3265031b91eb78890a515da48b47ca20376d (patch) | |
tree | c437a9c15c828c584b255779596f6b43f77c2caa /syntax-highlighting.py | |
parent | 5b2643bbbc53fabf4a49e5eb4df52ffe88c150e7 (diff) |
Diffstat (limited to 'syntax-highlighting.py')
-rw-r--r-- | syntax-highlighting.py | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/syntax-highlighting.py b/syntax-highlighting.py new file mode 100644 index 0000000..6c8edf1 --- /dev/null +++ b/syntax-highlighting.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +import sys +import io + +from pygments import highlight +from pygments.util import ClassNotFound +from pygments.lexers import TextLexer +from pygments.lexers import guess_lexer +from pygments.lexers import guess_lexer_for_filename +from pygments.formatters import HtmlFormatter + +from utils import configure_io, write_style +from markdown_filter import markdown_style, write_markdown_as_html + +def main(): + configure_io() + + data = sys.stdin.read() + filename = sys.argv[1] + + formatter = HtmlFormatter(style="fruity", nobackground=True) + + if filename.endswith(".md"): + # Dirty workaround to get markdown to display properly + sys.stdout.write("</code></pre></td></tr></tbody></table>") + + write_style(formatter, markdown_style) + + write_markdown_as_html(data) + sys.stdout.flush() + return + + write_style(formatter) + + try: + lexer = guess_lexer_for_filename(filename, data) + except ClassNotFound: + # check if there is any shebang + if data[0:2] == '#!': + lexer = guess_lexer(data) + else: + lexer = TextLexer() + except TypeError: + lexer = TextLexer() + + sys.stdout.write(highlight(data, lexer, formatter, outfile=None)) + + +if __name__ == "__main__": + main() |