all repos — cgit @ v1.0

a hyperfast web frontend for git written in c

filters/syntax-highlighting.py (view raw)

 1#!/usr/bin/env python3
 2
 3# This script uses Pygments and Python3. You must have both installed
 4# for this to work.
 5#
 6# http://pygments.org/
 7# http://python.org/
 8#
 9# It may be used with the source-filter or repo.source-filter settings
10# in cgitrc.
11#
12# The following environment variables can be used to retrieve the
13# configuration of the repository for which this script is called:
14# CGIT_REPO_URL        ( = repo.url       setting )
15# CGIT_REPO_NAME       ( = repo.name      setting )
16# CGIT_REPO_PATH       ( = repo.path      setting )
17# CGIT_REPO_OWNER      ( = repo.owner     setting )
18# CGIT_REPO_DEFBRANCH  ( = repo.defbranch setting )
19# CGIT_REPO_SECTION    ( = section        setting )
20# CGIT_REPO_CLONE_URL  ( = repo.clone-url setting )
21
22
23import sys
24import io
25from pygments import highlight
26from pygments.util import ClassNotFound
27from pygments.lexers import TextLexer
28from pygments.lexers import guess_lexer
29from pygments.lexers import guess_lexer_for_filename
30from pygments.formatters import HtmlFormatter
31
32
33sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
34sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
35data = sys.stdin.read()
36filename = sys.argv[1]
37formatter = HtmlFormatter(style='pastie')
38
39try:
40	lexer = guess_lexer_for_filename(filename, data)
41except ClassNotFound:
42	# check if there is any shebang
43	if data[0:2] == '#!':
44		lexer = guess_lexer(data)
45	else:
46		lexer = TextLexer()
47except TypeError:
48	lexer = TextLexer()
49
50# highlight! :-)
51# printout pygments' css definitions as well
52sys.stdout.write('<style>')
53sys.stdout.write(formatter.get_style_defs('.highlight'))
54sys.stdout.write('</style>')
55sys.stdout.write(highlight(data, lexer, formatter, outfile=None))