filters/syntax-highlighting.py (view raw)
1#!/usr/bin/env python2
2
3# This script uses Pygments and Python2. 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
24from pygments import highlight
25from pygments.util import ClassNotFound
26from pygments.lexers import TextLexer
27from pygments.lexers import guess_lexer
28from pygments.lexers import guess_lexer_for_filename
29from pygments.formatters import HtmlFormatter
30
31
32# read stdin and decode to utf-8. ignore any unkown signs.
33data = sys.stdin.read().decode(encoding='utf-8', errors='ignore')
34filename = sys.argv[1]
35formatter = HtmlFormatter(encoding='utf-8', style='pastie')
36
37try:
38 lexer = guess_lexer_for_filename(filename, data, encoding='utf-8')
39except ClassNotFound:
40 # check if there is any shebang
41 if data[0:2] == '#!':
42 lexer = guess_lexer(data, encoding='utf-8')
43 else:
44 lexer = TextLexer(encoding='utf-8')
45except TypeError:
46 lexer = TextLexer(encoding='utf-8')
47
48# highlight! :-)
49# printout pygments' css definitions as well
50sys.stdout.write('<style>')
51sys.stdout.write(formatter.get_style_defs('.highlight'))
52sys.stdout.write('</style>')
53highlight(data, lexer, formatter, outfile=sys.stdout)