]> git.cameronkatri.com Git - cgit.git/blob - filters/syntax-highlighting.py
manpage: fix sorting order
[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 import io
25 from pygments import highlight
26 from pygments.util import ClassNotFound
27 from pygments.lexers import TextLexer
28 from pygments.lexers import guess_lexer
29 from pygments.lexers import guess_lexer_for_filename
30 from pygments.formatters import HtmlFormatter
31
32
33 sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8', errors='replace')
34 sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
35 data = sys.stdin.read()
36 filename = sys.argv[1]
37 formatter = HtmlFormatter(style='pastie', nobackground=True)
38
39 try:
40 lexer = guess_lexer_for_filename(filename, data)
41 except ClassNotFound:
42 # check if there is any shebang
43 if data[0:2] == '#!':
44 lexer = guess_lexer(data)
45 else:
46 lexer = TextLexer()
47 except TypeError:
48 lexer = TextLexer()
49
50 # highlight! :-)
51 # printout pygments' css definitions as well
52 sys.stdout.write('<style>')
53 sys.stdout.write(formatter.get_style_defs('.highlight'))
54 sys.stdout.write('</style>')
55 sys.stdout.write(highlight(data, lexer, formatter, outfile=None))