From a3b5366573d9d6ba2299cd021842ab516856327c Mon Sep 17 00:00:00 2001 From: pablu Date: Sat, 19 Sep 2026 14:30:18 +0200 Subject: feat: add pygments support --- syntax-highlighting.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 syntax-highlighting.py (limited to 'syntax-highlighting.py') diff --git a/syntax-highlighting.py b/syntax-highlighting.py new file mode 100644 index 0000000..2186c35 --- /dev/null +++ b/syntax-highlighting.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 + +"""Render cgit source blobs as syntax-highlighted, HTML-escaped markup.""" + +import io +import sys + +from pygments import highlight +from pygments.formatters import HtmlFormatter +from pygments.lexers import TextLexer, guess_lexer, guess_lexer_for_filename +from pygments.util import ClassNotFound + + +sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace") +sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace") + +source = sys.stdin.read() +filename = sys.argv[1] +formatter = HtmlFormatter(style="monokai", nobackground=True) + +try: + lexer = guess_lexer_for_filename(filename, source) +except (ClassNotFound, TypeError): + if source.startswith("#!"): + try: + lexer = guess_lexer(source) + except ClassNotFound: + lexer = TextLexer() + else: + lexer = TextLexer() + +sys.stdout.write("") +sys.stdout.write(highlight(source, lexer, formatter)) -- cgit 1.3.1