From a2b53778dd8271365df50b20eaa8ba6f4ae07bae Mon Sep 17 00:00:00 2001 From: Matteo Nastasi Date: Thu, 31 Aug 2017 09:20:37 +0200 Subject: [PATCH] add markdown preprocessor to highlight code-blocks --- rest_framework/schemas.py | 2 +- rest_framework/templatetags/rest_framework.py | 36 ++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py index 437413355..902656f02 100644 --- a/rest_framework/schemas.py +++ b/rest_framework/schemas.py @@ -476,7 +476,7 @@ class SchemaGenerator(object): return formatting.dedent(smart_text(method_docstring)) description = view.get_view_description() - lines = [line.strip() for line in description.splitlines()] + lines = [line for line in description.splitlines()] current_section = '' sections = {'': ''} diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index a2ee5ccdd..0f355ac0d 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -66,11 +66,45 @@ def form_for_link(link): return mark_safe(coreschema.render_to_form(schema)) +from markdown.preprocessors import Preprocessor +from pygments.formatters import HtmlFormatter +from pygments.lexers import get_lexer_by_name, TextLexer +from pygments import highlight +import pygments +import re + +# starting from this blogpost and modified to support current markdown extensions API +# https://zerokspot.com/weblog/2008/06/18/syntax-highlighting-in-markdown-with-pygments/ +class CodeBlockPreprocessor(Preprocessor): + pattern = re.compile( + r'^\s*@@ (.+?) @@\s*(.+?)^\s*@@', re.M|re.S) + + formatter = HtmlFormatter() + + def run(self, lines): + def repl(m): + try: + lexer = get_lexer_by_name(m.group(1)) + except (ValueError, NameError): + lexer = TextLexer() + code = m.group(2).replace('\t',' ') + code = pygments.highlight(code, lexer, self.formatter) + code = code.replace('\n\n', '\n \n').replace('\n', '
').replace('\\@','@') + return '\n\n%s\n\n' % code + # import ipdb ; ipdb.set_trace() + ret = self.pattern.sub(repl, "\n".join(lines)) + return ret.split("\n") + + @register.simple_tag def render_markdown(markdown_text): if not markdown: return markdown_text - return mark_safe(markdown.markdown(markdown_text)) + md = markdown.Markdown() + md.preprocessors.add('highlight', CodeBlockPreprocessor(), "_begin") + + a = md.convert(markdown_text) + return mark_safe(md.convert(markdown_text)) @register.simple_tag