summaryrefslogtreecommitdiff
path: root/syntax-highlighting.py
blob: 2186c35b6344c53b4a32b2b89bd5fe13990c6049 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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("<style>")
sys.stdout.write(formatter.get_style_defs(".highlight"))
sys.stdout.write("</style>")
sys.stdout.write(highlight(source, lexer, formatter))