root/bitstructures/trunk/substructure/templatetags/substructure_tags.py

Revision 42, 1.5 kB (checked in by simon, 11 months ago)

implemented syntax highlighting for codeblocks

Line 
1from django import template
2from django.utils.tzinfo import LocalTimezone
3from markdown import markdown
4from pygments import highlight
5from pygments.lexers import get_lexer_for_mimetype
6from pygments.formatters import HtmlFormatter
7from bitstructures.substructure.codeblocks import MarkdownCodeblocksParser
8
9def 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
16def 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
38register = template.Library()
39register.filter('rfc3339', rfc3339)
40register.filter('syntax_highlighted_markdown', syntax_highlighted_markdown)
Note: See TracBrowser for help on using the browser.