colorsyntax 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. from bs4 import BeautifulSoup
  3. from pygments import highlight
  4. from pygments.lexers import CppLexer
  5. from pygments.token import Keyword
  6. from pygments.token import Name
  7. from pygments.formatters import HtmlFormatter
  8. import argparse
  9. import sys
  10. class Lexer(CppLexer):
  11. EXTRA_CLASSES = (
  12. 'istream_iterator',
  13. 'message',
  14. 'message_control',
  15. 'message_istream',
  16. 'message_ostream',
  17. 'message_streambuf',
  18. 'millisecond',
  19. 'other_string_type',
  20. 'poll_vector',
  21. 'poll_entry',
  22. 'nn_pollfd',
  23. 'second',
  24. 'socket',
  25. 'timeout_error',
  26. 'vector',
  27. )
  28. EXTRA_FUNCTIONS = (
  29. 'recv_int_vector',
  30. )
  31. EXTRA_NAMESPACES = (
  32. 'chrono',
  33. 'nnxx',
  34. 'std',
  35. 'X',
  36. )
  37. EXTRA_KEYWORDS = (
  38. 'noexcept',
  39. 'try',
  40. )
  41. def get_tokens_unprocessed(self, text):
  42. for index, token, value in super(Lexer, self).get_tokens_unprocessed(text):
  43. if token is not Name:
  44. yield index, token, value
  45. continue
  46. if value in self.EXTRA_KEYWORDS:
  47. yield index, Keyword, value
  48. elif value in self.EXTRA_NAMESPACES:
  49. yield index, Name.Namespace, value
  50. elif value in self.EXTRA_CLASSES:
  51. yield index, Name.Class, value
  52. elif value in self.EXTRA_FUNCTIONS:
  53. yield index, Name.Function, value
  54. elif is_constant(value):
  55. yield index, Name.Constant, value
  56. else:
  57. yield index, Name, value
  58. def is_constant(s):
  59. for c in s:
  60. if c != '_' and not c.isupper():
  61. return False
  62. return True
  63. def parse_arguments():
  64. parser = argparse.ArgumentParser()
  65. parser.add_argument('-s', '--style', default='default', help='The Pygments style to use')
  66. return parser.parse_args()
  67. args = parse_arguments()
  68. style = args.style
  69. doc = BeautifulSoup(sys.stdin)
  70. for pre in doc.find_all('pre'):
  71. code = pre.find('code')
  72. data = code.string
  73. pre.replace_with(BeautifulSoup(highlight(data, Lexer(), HtmlFormatter(style=style))))
  74. print doc