Skip to content

Commit a2b5377

Browse files
committed
add markdown preprocessor to highlight code-blocks
1 parent 7e3ba8b commit a2b5377

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

rest_framework/schemas.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,7 +476,7 @@ def get_description(self, path, method, view):
476476
return formatting.dedent(smart_text(method_docstring))
477477

478478
description = view.get_view_description()
479-
lines = [line.strip() for line in description.splitlines()]
479+
lines = [line for line in description.splitlines()]
480480
current_section = ''
481481
sections = {'': ''}
482482

rest_framework/templatetags/rest_framework.py

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,45 @@ def form_for_link(link):
6666
return mark_safe(coreschema.render_to_form(schema))
6767

6868

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&nbsp;\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+
6999
@register.simple_tag
70100
def render_markdown(markdown_text):
71101
if not markdown:
72102
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))
74108

75109

76110
@register.simple_tag

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy