Skip to content

add markdown preprocessor to highlight code-blocks #5377

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rest_framework/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ def get_description(self, path, method, view):
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 = {'': ''}

Expand Down
36 changes: 35 additions & 1 deletion rest_framework/templatetags/rest_framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -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&nbsp;\n').replace('\n', '<br />').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
Expand Down