|
1 # |
|
2 # Jasy - Web Tooling Framework |
|
3 # Copyright 2010-2012 Zynga Inc. |
|
4 # Copyright 2013-2014 Sebastian Werner |
|
5 # |
|
6 |
|
7 from __future__ import unicode_literals |
|
8 |
|
9 import re |
|
10 |
|
11 |
|
12 # |
|
13 # MARKDOWN TO HTML |
|
14 # |
|
15 |
|
16 try: |
|
17 # import hoedown |
|
18 # |
|
19 # hoedownExt = hoedown.EXT_AUTOLINK | hoedown.EXT_NO_INTRA_EMPHASIS | hoedown.EXT_FENCED_CODE | hoedown.EXT_TABLES | hoedown.EXT_FOOTNOTES | hoedown.EXT_QUOTE | hoedown.EXT_STRIKETHROUGH | hoedown.EXT_UNDERLINE | hoedown.EXT_HIGHLIGHT |
|
20 # hoedownExt = hoedown.EXT_AUTOLINK |
|
21 # hoedownRender = hoedown.HTML_SKIP_STYLE | hoedown.HTML_SMARTYPANTS |
|
22 |
|
23 import misaka |
|
24 |
|
25 hoedownExt = misaka.EXT_AUTOLINK | misaka.EXT_NO_INTRA_EMPHASIS | misaka.EXT_FENCED_CODE |
|
26 hoedownRender = misaka.HTML_SKIP_STYLE | misaka.HTML_SMARTYPANTS |
|
27 hoedown = misaka |
|
28 |
|
29 supportsMarkdown = True |
|
30 |
|
31 except: |
|
32 supportsMarkdown = False |
|
33 |
|
34 def markdownToHtml(markdownStr): |
|
35 """ |
|
36 Converts Markdown to HTML. Supports GitHub's fenced code blocks, |
|
37 auto linking and typographic features by SmartyPants. |
|
38 """ |
|
39 |
|
40 return hoedown.html(markdownStr, hoedownExt, hoedownRender) |
|
41 |
|
42 |
|
43 # |
|
44 # HIGHLIGHT CODE BLOCKS |
|
45 # |
|
46 |
|
47 try: |
|
48 from pygments import highlight |
|
49 from pygments.formatters import HtmlFormatter |
|
50 from pygments.lexers import get_lexer_by_name |
|
51 |
|
52 # By http://misaka.61924.nl/#toc_3 |
|
53 codeblock = re.compile(r'<pre(?: lang="([a-z0-9]+)")?><code(?: class="([a-z0-9]+).*?")?>(.*?)</code></pre>', re.IGNORECASE | re.DOTALL) |
|
54 |
|
55 supportsHighlighting = True |
|
56 |
|
57 except ImportError: |
|
58 |
|
59 supportsHighlighting = False |
|
60 |
|
61 def highlightCodeBlocks(html, tabsize=2, defaultlang="javascript"): |
|
62 """ |
|
63 Patches 'code' elements in HTML to apply HTML based syntax highlighting. Automatically |
|
64 chooses the matching language detected via a CSS class of the 'code' element. |
|
65 """ |
|
66 |
|
67 def unescape(html): |
|
68 html = html.replace('<', '<') |
|
69 html = html.replace('>', '>') |
|
70 html = html.replace('&', '&') |
|
71 html = html.replace('"', '"') |
|
72 return html.replace(''', "'") |
|
73 |
|
74 def replace(match): |
|
75 language, classname, code = match.groups() |
|
76 if language is None: |
|
77 language = classname if classname else defaultlang |
|
78 |
|
79 lexer = get_lexer_by_name(language, tabsize=tabsize) |
|
80 formatter = HtmlFormatter(linenos="table") |
|
81 |
|
82 code = unescape(code) |
|
83 |
|
84 # for some reason pygments escapes our code once again so we need to reverse it twice |
|
85 return unescape(highlight(code, lexer, formatter)) |
|
86 |
|
87 return codeblock.sub(replace, html) |