syntax-highlighting.py 1.8 KB

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