PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/gluon/highlight.py

https://github.com/gokceneraslan/web2py
Python | 346 lines | 309 code | 13 blank | 24 comment | 22 complexity | 0f5bea47de258d60c0dd82eb46dceca0 MD5 | raw file
Possible License(s): BSD-2-Clause, MIT, BSD-3-Clause
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. This file is part of the web2py Web Framework
  5. Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
  6. License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
  7. """
  8. import re
  9. import cgi
  10. __all__ = ['highlight']
  11. class Highlighter(object):
  12. """
  13. Do syntax highlighting.
  14. """
  15. def __init__(
  16. self,
  17. mode,
  18. link=None,
  19. styles=None,
  20. ):
  21. """
  22. Initialise highlighter:
  23. mode = language (PYTHON, WEB2PY,C, CPP, HTML, HTML_PLAIN)
  24. """
  25. styles = styles or {}
  26. mode = mode.upper()
  27. if link and link[-1] != '/':
  28. link = link + '/'
  29. self.link = link
  30. self.styles = styles
  31. self.output = []
  32. self.span_style = None
  33. if mode == 'WEB2PY':
  34. (mode, self.suppress_tokens) = ('PYTHON', [])
  35. elif mode == 'PYTHON':
  36. self.suppress_tokens = ['GOTOHTML']
  37. elif mode == 'CPP':
  38. (mode, self.suppress_tokens) = ('C', [])
  39. elif mode == 'C':
  40. self.suppress_tokens = ['CPPKEYWORD']
  41. elif mode == 'HTML_PLAIN':
  42. (mode, self.suppress_tokens) = ('HTML', ['GOTOPYTHON'])
  43. elif mode == 'HTML':
  44. self.suppress_tokens = []
  45. else:
  46. raise SyntaxError('Unknown mode: %s' % mode)
  47. self.mode = mode
  48. def c_tokenizer(
  49. self,
  50. token,
  51. match,
  52. style,
  53. ):
  54. """
  55. Callback for C specific highlighting.
  56. """
  57. value = cgi.escape(match.group())
  58. self.change_style(token, style)
  59. self.output.append(value)
  60. def python_tokenizer(
  61. self,
  62. token,
  63. match,
  64. style,
  65. ):
  66. """
  67. Callback for python specific highlighting.
  68. """
  69. value = cgi.escape(match.group())
  70. if token == 'MULTILINESTRING':
  71. self.change_style(token, style)
  72. self.output.append(value)
  73. self.strMultilineString = match.group(1)
  74. return 'PYTHONMultilineString'
  75. elif token == 'ENDMULTILINESTRING':
  76. if match.group(1) == self.strMultilineString:
  77. self.output.append(value)
  78. self.strMultilineString = ''
  79. return 'PYTHON'
  80. if style and style[:5] == 'link:':
  81. self.change_style(None, None)
  82. (url, style) = style[5:].split(';', 1)
  83. if url == 'None' or url == '':
  84. self.output.append('<span style="%s">%s</span>'
  85. % (style, value))
  86. else:
  87. self.output.append('<a href="%s%s" style="%s">%s</a>'
  88. % (url, value, style, value))
  89. else:
  90. self.change_style(token, style)
  91. self.output.append(value)
  92. if token == 'GOTOHTML':
  93. return 'HTML'
  94. return None
  95. def html_tokenizer(
  96. self,
  97. token,
  98. match,
  99. style,
  100. ):
  101. """
  102. Callback for HTML specific highlighting.
  103. """
  104. value = cgi.escape(match.group())
  105. self.change_style(token, style)
  106. self.output.append(value)
  107. if token == 'GOTOPYTHON':
  108. return 'PYTHON'
  109. return None
  110. all_styles = {
  111. 'C': (c_tokenizer, (
  112. ('COMMENT', re.compile(r'//.*\r?\n'),
  113. 'color: green; font-style: italic'),
  114. ('MULTILINECOMMENT', re.compile(r'/\*.*?\*/', re.DOTALL),
  115. 'color: green; font-style: italic'),
  116. ('PREPROCESSOR', re.compile(r'\s*#.*?[^\\]\s*\n',
  117. re.DOTALL), 'color: magenta; font-style: italic'),
  118. ('PUNC', re.compile(r'[-+*!&|^~/%\=<>\[\]{}(),.:]'),
  119. 'font-weight: bold'),
  120. ('NUMBER',
  121. re.compile(r'0x[0-9a-fA-F]+|[+-]?\d+(\.\d+)?([eE][+-]\d+)?|\d+'),
  122. 'color: red'),
  123. ('KEYWORD', re.compile(r'(sizeof|int|long|short|char|void|'
  124. + r'signed|unsigned|float|double|'
  125. + r'goto|break|return|continue|asm|'
  126. + r'case|default|if|else|switch|while|for|do|'
  127. + r'struct|union|enum|typedef|'
  128. + r'static|register|auto|volatile|extern|const)(?![a-zA-Z0-9_])'),
  129. 'color:#185369; font-weight: bold'),
  130. ('CPPKEYWORD',
  131. re.compile(r'(class|private|protected|public|template|new|delete|'
  132. + r'this|friend|using|inline|export|bool|throw|try|catch|'
  133. + r'operator|typeid|virtual)(?![a-zA-Z0-9_])'),
  134. 'color: blue; font-weight: bold'),
  135. ('STRING', re.compile(r'r?u?\'(.*?)(?<!\\)\'|"(.*?)(?<!\\)"'),
  136. 'color: #FF9966'),
  137. ('IDENTIFIER', re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*'),
  138. None),
  139. ('WHITESPACE', re.compile(r'[ \r\n]+'), 'Keep'),
  140. )),
  141. 'PYTHON': (python_tokenizer, (
  142. ('GOTOHTML', re.compile(r'\}\}'), 'color: red'),
  143. ('PUNC', re.compile(r'[-+*!|&^~/%\=<>\[\]{}(),.:]'),
  144. 'font-weight: bold'),
  145. ('NUMBER',
  146. re.compile(r'0x[0-9a-fA-F]+|[+-]?\d+(\.\d+)?([eE][+-]\d+)?|\d+'
  147. ), 'color: red'),
  148. ('KEYWORD',
  149. re.compile(r'(def|class|break|continue|del|exec|finally|pass|'
  150. + r'print|raise|return|try|except|global|assert|lambda|'
  151. + r'yield|for|while|if|elif|else|and|in|is|not|or|import|'
  152. + r'from|True|False)(?![a-zA-Z0-9_])'),
  153. 'color:#185369; font-weight: bold'),
  154. ('WEB2PY',
  155. re.compile(r'(request|response|session|cache|redirect|local_import|HTTP|TR|XML|URL|BEAUTIFY|A|BODY|BR|B|CAT|CENTER|CODE|COL|COLGROUP|DIV|EM|EMBED|FIELDSET|LEGEND|FORM|H1|H2|H3|H4|H5|H6|IFRAME|HEAD|HR|HTML|I|IMG|INPUT|LABEL|LI|LINK|MARKMIN|MENU|META|OBJECT|OL|ON|OPTION|P|PRE|SCRIPT|SELECT|SPAN|STYLE|TABLE|THEAD|TBODY|TFOOT|TAG|TD|TEXTAREA|TH|TITLE|TT|T|UL|XHTML|IS_SLUG|IS_STRONG|IS_LOWER|IS_UPPER|IS_ALPHANUMERIC|IS_DATETIME|IS_DATETIME_IN_RANGE|IS_DATE|IS_DATE_IN_RANGE|IS_DECIMAL_IN_RANGE|IS_EMAIL|IS_EXPR|IS_FLOAT_IN_RANGE|IS_IMAGE|IS_INT_IN_RANGE|IS_IN_SET|IS_IPV4|IS_LIST_OF|IS_LENGTH|IS_MATCH|IS_EQUAL_TO|IS_EMPTY_OR|IS_NULL_OR|IS_NOT_EMPTY|IS_TIME|IS_UPLOAD_FILENAME|IS_URL|CLEANUP|CRYPT|IS_IN_DB|IS_NOT_IN_DB|DAL|Field|SQLFORM|SQLTABLE|xmlescape|embed64)(?![a-zA-Z0-9_])'
  156. ), 'link:%(link)s;text-decoration:None;color:#FF5C1F;'),
  157. ('MAGIC', re.compile(r'self|None'),
  158. 'color:#185369; font-weight: bold'),
  159. ('MULTILINESTRING', re.compile(r'r?u?(\'\'\'|""")'),
  160. 'color: #FF9966'),
  161. ('STRING', re.compile(r'r?u?\'(.*?)(?<!\\)\'|"(.*?)(?<!\\)"'
  162. ), 'color: #FF9966'),
  163. ('IDENTIFIER', re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*'),
  164. None),
  165. ('COMMENT', re.compile(r'\#.*\r?\n'),
  166. 'color: green; font-style: italic'),
  167. ('WHITESPACE', re.compile(r'[ \r\n]+'), 'Keep'),
  168. )),
  169. 'PYTHONMultilineString': (python_tokenizer,
  170. (('ENDMULTILINESTRING',
  171. re.compile(r'.*?("""|\'\'\')',
  172. re.DOTALL), 'color: darkred'), )),
  173. 'HTML': (html_tokenizer, (
  174. ('GOTOPYTHON', re.compile(r'\{\{'), 'color: red'),
  175. ('COMMENT', re.compile(r'<!--[^>]*-->|<!>'),
  176. 'color: green; font-style: italic'),
  177. ('XMLCRAP', re.compile(r'<![^>]*>'),
  178. 'color: blue; font-style: italic'),
  179. ('SCRIPT', re.compile(r'<script .*?</script>', re.IGNORECASE
  180. + re.DOTALL), 'color: black'),
  181. ('TAG', re.compile(r'</?\s*[a-zA-Z0-9]+'),
  182. 'color: darkred; font-weight: bold'),
  183. ('ENDTAG', re.compile(r'/?>'),
  184. 'color: darkred; font-weight: bold'),
  185. )),
  186. }
  187. def highlight(self, data):
  188. """
  189. Syntax highlight some python code.
  190. Returns html version of code.
  191. """
  192. i = 0
  193. mode = self.mode
  194. while i < len(data):
  195. for (token, o_re, style) in Highlighter.all_styles[mode][1]:
  196. if not token in self.suppress_tokens:
  197. match = o_re.match(data, i)
  198. if match:
  199. if style:
  200. new_mode = \
  201. Highlighter.all_styles[mode][0](self,
  202. token, match, style
  203. % dict(link=self.link))
  204. else:
  205. new_mode = \
  206. Highlighter.all_styles[mode][0](self,
  207. token, match, style)
  208. if not new_mode is None:
  209. mode = new_mode
  210. i += max(1, len(match.group()))
  211. break
  212. else:
  213. self.change_style(None, None)
  214. self.output.append(data[i])
  215. i += 1
  216. self.change_style(None, None)
  217. return ''.join(self.output).expandtabs(4)
  218. def change_style(self, token, style):
  219. """
  220. Generate output to change from existing style to another style only.
  221. """
  222. if token in self.styles:
  223. style = self.styles[token]
  224. if self.span_style != style:
  225. if style != 'Keep':
  226. if not self.span_style is None:
  227. self.output.append('</span>')
  228. if not style is None:
  229. self.output.append('<span style="%s">' % style)
  230. self.span_style = style
  231. def highlight(
  232. code,
  233. language,
  234. link='/examples/globals/vars/',
  235. counter=1,
  236. styles=None,
  237. highlight_line=None,
  238. context_lines=None,
  239. attributes=None,
  240. ):
  241. styles = styles or {}
  242. attributes = attributes or {}
  243. if not 'CODE' in styles:
  244. code_style = """
  245. font-size: 11px;
  246. font-family: Bitstream Vera Sans Mono,monospace;
  247. background-color: transparent;
  248. margin: 0;
  249. padding: 5px;
  250. border: none;
  251. overflow: auto;
  252. white-space: pre !important;\n"""
  253. else:
  254. code_style = styles['CODE']
  255. if not 'LINENUMBERS' in styles:
  256. linenumbers_style = """
  257. font-size: 11px;
  258. font-family: Bitstream Vera Sans Mono,monospace;
  259. background-color: transparent;
  260. margin: 0;
  261. padding: 5px;
  262. border: none;
  263. color: #A0A0A0;\n"""
  264. else:
  265. linenumbers_style = styles['LINENUMBERS']
  266. if not 'LINEHIGHLIGHT' in styles:
  267. linehighlight_style = "background-color: #EBDDE2;"
  268. else:
  269. linehighlight_style = styles['LINEHIGHLIGHT']
  270. if language and language.upper() in ['PYTHON', 'C', 'CPP', 'HTML',
  271. 'WEB2PY']:
  272. code = Highlighter(language, link, styles).highlight(code)
  273. else:
  274. code = cgi.escape(code)
  275. lines = code.split('\n')
  276. if counter is None:
  277. linenumbers = [''] * len(lines)
  278. elif isinstance(counter, str):
  279. linenumbers = [cgi.escape(counter)] * len(lines)
  280. else:
  281. linenumbers = [str(i + counter) + '.' for i in
  282. xrange(len(lines))]
  283. if highlight_line:
  284. if counter and not isinstance(counter, str):
  285. lineno = highlight_line - counter
  286. else:
  287. lineno = highlight_line
  288. if lineno < len(lines):
  289. lines[lineno] = '<div style="%s">%s</div>' % (
  290. linehighlight_style, lines[lineno])
  291. linenumbers[lineno] = '<div style="%s">%s</div>' % (
  292. linehighlight_style, linenumbers[lineno])
  293. if context_lines:
  294. if lineno + context_lines < len(lines):
  295. del lines[lineno + context_lines:]
  296. del linenumbers[lineno + context_lines:]
  297. if lineno - context_lines > 0:
  298. del lines[0:lineno - context_lines]
  299. del linenumbers[0:lineno - context_lines]
  300. code = '<br/>'.join(lines)
  301. numbers = '<br/>'.join(linenumbers)
  302. items = attributes.items()
  303. fa = ' '.join([key[1:].lower() for (key, value) in items if key[:1]
  304. == '_' and value is None] + ['%s="%s"'
  305. % (key[1:].lower(), str(value).replace('"', "'"))
  306. for (key, value) in attributes.items() if key[:1]
  307. == '_' and value])
  308. if fa:
  309. fa = ' ' + fa
  310. return '<table%s><tr style="vertical-align:top;"><td style="width:40px; text-align: right;"><pre style="%s">%s</pre></td><td><pre style="%s">%s</pre></td></tr></table>'\
  311. % (fa, linenumbers_style, numbers, code_style, code)
  312. if __name__ == '__main__':
  313. import sys
  314. argfp = open(sys.argv[1])
  315. data = argfp.read()
  316. argfp.close()
  317. print '<html><body>' + highlight(data, sys.argv[2])\
  318. + '</body></html>'