]> git.cameronkatri.com Git - cgit.git/blob - filters/syntax-highlighting.py
repolist: add owner-filter
[cgit.git] / filters / syntax-highlighting.py
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
23 import sys
24 from pygments import highlight
25 from pygments.util import ClassNotFound
26 from pygments.lexers import TextLexer
27 from pygments.lexers import guess_lexer
28 from pygments.lexers import guess_lexer_for_filename
29 from pygments.formatters import HtmlFormatter
30
31
32 # read stdin and decode to utf-8. ignore any unkown signs.
33 data = sys.stdin.read().decode(encoding='utf-8', errors='ignore')
34 filename = sys.argv[1]
35 formatter = HtmlFormatter(encoding='utf-8', style='pastie')
36
37 try:
38 lexer = guess_lexer_for_filename(filename, data, encoding='utf-8')
39 except 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')
45 except TypeError:
46 lexer = TextLexer(encoding='utf-8')
47
48 # highlight! :-)
49 # printout pygments' css definitions as well
50 sys.stdout.write('<style>')
51 sys.stdout.write(formatter.get_style_defs('.highlight'))
52 sys.stdout.write('</style>')
53 highlight(data, lexer, formatter, outfile=sys.stdout)