from django.core.urlresolvers import reverse import markdown from markdown.inlinepatterns import Pattern from markdown.util import etree import boards __author__ = 'neko259' class AutolinkPattern(Pattern): def handleMatch(self, m): link_element = etree.Element('a') href = m.group(2) link_element.set('href', href) link_element.text = href return link_element class QuotePattern(Pattern): def handleMatch(self, m): quote_element = etree.Element('span') quote_element.set('class', 'quote') quote_element.text = m.group(2) return quote_element class ReflinkPattern(Pattern): def handleMatch(self, m): ref_element = etree.Element('a') post_id = m.group(4) ref_element.set('href', reverse(boards.views.jump_to_post, kwargs={'post_id': post_id})) ref_element.text = m.group(2) return ref_element class SpoilerPattern(Pattern): def handleMatch(self, m): quote_element = etree.Element('span') quote_element.set('class', 'spoiler') quote_element.text = m.group(2) return quote_element class CommentPattern(Pattern): def handleMatch(self, m): quote_element = etree.Element('span') quote_element.set('class', 'comment') quote_element.text = '//' + m.group(3) return quote_element class NeboardMarkdown(markdown.Extension): AUTOLINK_PATTERN = r'(https?://\S+)' QUOTE_PATTERN = r'^(?)(>[^>]+)$' REFLINK_PATTERN = r'((>>)(\d+))' SPOILER_PATTERN = r'%%(.+)%%' COMMENT_PATTERN = r'^(//(.+))' def extendMarkdown(self, md, md_globals): self._add_neboard_patterns(md) self._delete_patterns(md) def _delete_patterns(self, md): del md.parser.blockprocessors['quote'] del md.inlinePatterns['image_link'] del md.inlinePatterns['image_reference'] def _add_neboard_patterns(self, md): autolink = AutolinkPattern(self.AUTOLINK_PATTERN, md) quote = QuotePattern(self.QUOTE_PATTERN, md) reflink = ReflinkPattern(self.REFLINK_PATTERN, md) spoiler = SpoilerPattern(self.SPOILER_PATTERN, md) comment = CommentPattern(self.COMMENT_PATTERN, md) md.inlinePatterns[u'autolink_ext'] = autolink md.inlinePatterns[u'spoiler'] = spoiler md.inlinePatterns[u'comment'] = comment md.inlinePatterns[u'reflink'] = reflink md.inlinePatterns[u'quote'] = quote def makeExtension(configs=None): return NeboardMarkdown(configs=configs) neboard_extension = makeExtension() def markdown_extended(markup): return markdown.markdown(markup, [neboard_extension], safe_mode=True)