summaryrefslogtreecommitdiff
path: root/syntax-highlighting.py
blob: 6c8edf1b35823558ae75f3dd3b0489f36bfc1bc0 (plain)
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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()