| 1 | from django import template |
|---|
| 2 | from django.utils.tzinfo import LocalTimezone |
|---|
| 3 | from markdown import markdown |
|---|
| 4 | from pygments import highlight |
|---|
| 5 | from pygments.lexers import get_lexer_for_mimetype |
|---|
| 6 | from pygments.formatters import HtmlFormatter |
|---|
| 7 | from bitstructures.substructure.codeblocks import MarkdownCodeblocksParser |
|---|
| 8 | |
|---|
| 9 | def rfc3339(dt): |
|---|
| 10 | if dt.tzinfo == None: |
|---|
| 11 | dt_out = dt.replace(tzinfo=LocalTimezone(dt), microsecond=0) |
|---|
| 12 | else: |
|---|
| 13 | dt_out = dt.replace(microsecond=0) |
|---|
| 14 | return dt_out.isoformat() |
|---|
| 15 | |
|---|
| 16 | def syntax_highlighted_markdown(markdown_text): |
|---|
| 17 | parser = MarkdownCodeblocksParser() |
|---|
| 18 | formatter = HtmlFormatter() |
|---|
| 19 | sections = parser.parse(markdown_text) |
|---|
| 20 | for_markdown = list() |
|---|
| 21 | html = list() |
|---|
| 22 | for section in sections: |
|---|
| 23 | if section.is_codeblock() and section.content_type: |
|---|
| 24 | # run Markdown on any text that isn't to be syntax highlighted |
|---|
| 25 | if for_markdown: |
|---|
| 26 | html.append(markdown(''.join(for_markdown))) |
|---|
| 27 | for_markdown = list() |
|---|
| 28 | # run Pygments on code to be syntax highlighted |
|---|
| 29 | html.append(highlight(section.get_code(), |
|---|
| 30 | get_lexer_for_mimetype(section.content_type), formatter)) |
|---|
| 31 | else: |
|---|
| 32 | for_markdown.append(section.get_text()) |
|---|
| 33 | # run Markdown on any remaining text that isn't to be syntax highlighted |
|---|
| 34 | if for_markdown: |
|---|
| 35 | html.append(markdown(''.join(for_markdown))) |
|---|
| 36 | return ''.join(html) |
|---|
| 37 | |
|---|
| 38 | register = template.Library() |
|---|
| 39 | register.filter('rfc3339', rfc3339) |
|---|
| 40 | register.filter('syntax_highlighted_markdown', syntax_highlighted_markdown) |
|---|