@@ -66,11 +66,45 @@ def form_for_link(link):
66
66
return mark_safe (coreschema .render_to_form (schema ))
67
67
68
68
69
+ from markdown .preprocessors import Preprocessor
70
+ from pygments .formatters import HtmlFormatter
71
+ from pygments .lexers import get_lexer_by_name , TextLexer
72
+ from pygments import highlight
73
+ import pygments
74
+ import re
75
+
76
+ # starting from this blogpost and modified to support current markdown extensions API
77
+ # https://zerokspot.com/weblog/2008/06/18/syntax-highlighting-in-markdown-with-pygments/
78
+ class CodeBlockPreprocessor (Preprocessor ):
79
+ pattern = re .compile (
80
+ r'^\s*@@ (.+?) @@\s*(.+?)^\s*@@' , re .M | re .S )
81
+
82
+ formatter = HtmlFormatter ()
83
+
84
+ def run (self , lines ):
85
+ def repl (m ):
86
+ try :
87
+ lexer = get_lexer_by_name (m .group (1 ))
88
+ except (ValueError , NameError ):
89
+ lexer = TextLexer ()
90
+ code = m .group (2 ).replace ('\t ' ,' ' )
91
+ code = pygments .highlight (code , lexer , self .formatter )
92
+ code = code .replace ('\n \n ' , '\n \n ' ).replace ('\n ' , '<br />' ).replace ('\\ @' ,'@' )
93
+ return '\n \n %s\n \n ' % code
94
+ # import ipdb ; ipdb.set_trace()
95
+ ret = self .pattern .sub (repl , "\n " .join (lines ))
96
+ return ret .split ("\n " )
97
+
98
+
69
99
@register .simple_tag
70
100
def render_markdown (markdown_text ):
71
101
if not markdown :
72
102
return markdown_text
73
- return mark_safe (markdown .markdown (markdown_text ))
103
+ md = markdown .Markdown ()
104
+ md .preprocessors .add ('highlight' , CodeBlockPreprocessor (), "_begin" )
105
+
106
+ a = md .convert (markdown_text )
107
+ return mark_safe (md .convert (markdown_text ))
74
108
75
109
76
110
@register .simple_tag
0 commit comments