]> git.cameronkatri.com Git - cgit.git/blob - filters/syntax-highlighting.py
filters: port syntax-highlighting.py to python 3.x
[cgit.git] / filters / syntax-highlighting.py
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
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 data = sys.stdin.read()
33 filename = sys.argv[1]
34 formatter = HtmlFormatter(style='pastie')
35
36 try:
37 lexer = guess_lexer_for_filename(filename, data)
38 except ClassNotFound:
39 # check if there is any shebang
40 if data[0:2] == '#!':
41 lexer = guess_lexer(data)
42 else:
43 lexer = TextLexer()
44 except TypeError:
45 lexer = TextLexer()
46
47 # highlight! :-)
48 # printout pygments' css definitions as well
49 sys.stdout.write('<style>')
50 sys.stdout.write(formatter.get_style_defs('.highlight'))
51 sys.stdout.write('</style>')
52 sys.stdout.write(highlight(data, lexer, formatter, outfile=None))