def test_urls(self): """Test handling of URLs""" markup = postmarkup.create() tests = [(u"http://example.com", "[url]http://example.com[/url]")] for test, result in tests: self.assertEqual(markup.tagify_urls(test), result)
def test_urls(self): """Test handling of URLs""" markup = postmarkup.create() tests = [(u"http://example.com", "[url]http://example.com[/url]") ] for test, result in tests: self.assertEqual(markup.tagify_urls(test), result)
def test_unknowntags(self): """Test unknown tags pass through correctly""" markup = postmarkup.create(annotate_links=False) tests = [(u'[REDACTED]', u'[REDACTED]'), (u'[REDACTED this]', u'[REDACTED this]'), (u'[REDACTED <b>]', u'[REDACTED <b>]')] for test, result in tests: self.assertEqual(markup(test, render_unknown_tags=True), result)
def test_unknowntags(self): """Test unknown tags pass through correctly""" markup = postmarkup.create(annotate_links=False) tests = [ (u'[REDACTED]', u'[REDACTED]'), (u'[REDACTED this]', u'[REDACTED this]'), (u'[REDACTED <b>]', u'[REDACTED <b>]') ] for test, result in tests: self.assertEqual(markup(test, render_unknown_tags=True), result)
def test_overlap(self): """Test overlapping tags produce correct output""" markup = postmarkup.create() tests = [ (u'[i][b]Hello[/i][/b]', u"<em><strong>Hello</strong></em>"), (u'[b]bold [u]both[/b] underline[/u]', u'<strong>bold <u>both</u></strong><u> underline</u>') ] for test, result in tests: self.assertEqual(markup(test), result)
def test_tabletag(self): """Test Table Tags""" markup = postmarkup.create() tests = [ (u"[table][tr][td]Row 1, Col 1[/td][td]Row 1, Col 2[/td][/tr][tr][td]Row 2, Col 1[/td][td]Row 2, Col 2[/td][/tr][/table]", u'<table><tr><td>Row 1, Col 1</td><td>Row 1, Col 2</td></tr><tr><td>Row 2, Col 1</td><td>Row 2, Col 2</td></tr></table>') ] for test, result in tests: self.assertEqual(markup(test), result)
def test_unicode(self): """Test unicode support""" markup = postmarkup.create() tests= [ (u'[b]Hello André[/b]', u"<strong>Hello André</strong>"), (u'[i]ɸβfvθðsz[/i]', u"<em>ɸβfvθðsz</em>"), ] for test, result in tests: self.assertEqual(markup(test), result)
def test_cleanuphtml(self): """Test cleanup_html""" markup = postmarkup.create() tests = [(u"""\n<p>\n </p>\n""", u""), (u"""<b>\n\n<i> </i>\n</b>Test""", u"Test"), (u"""<p id="test">Test</p>""", u"""<p id="test">Test</p>""")] for test, result in tests: self.assertEqual(markup.cleanup_html(test).strip(), result)
def test_overlap(self): """Test overlapping tags produce correct output""" markup = postmarkup.create() tests = [(u'[i][b]Hello[/i][/b]', u"<em><strong>Hello</strong></em>"), (u'[b]bold [u]both[/b] underline[/u]', u'<strong>bold <u>both</u></strong><u> underline</u>') ] for test, result in tests: self.assertEqual(markup(test), result)
def transformPostingText(text): weird_strings = set(re.findall("\[[^:]*(:[a-zA-Z0-9]+\])", text)) for str in weird_strings: text = re.sub(str,"]", text) pm = postmarkup.create(annotate_links=False) xhtml = pm.render_to_html(text, auto_urls=False, cosmetic_replace=False) #xhtml = render_bbcode(text) xhtml = pm.standard_unreplace(xhtml) # unescape html tags return xhtml
def test_quote(self): markup = postmarkup.create(annotate_links=False) tests = [(u'[quote]some text[/quote]', u'<blockquote>some text</blockquote>'), (u'[quote="user=name"]jibber[/quote]', u'<blockquote><em>user=name</em><br/>jibber</blockquote>'), (u'[quote=]jabber[/quote]', u'<blockquote>jabber</blockquote>'), ] for test, result in tests: self.assertEqual(markup(test), result)
def test_unicode(self): """Test unicode support""" markup = postmarkup.create() tests = [(u'[b]Hello André[/b]', u"<strong>Hello André</strong>"), (u'[i]ɸβfvθðsz[/i]', u"<em>ɸβfvθðsz</em>"), ] for test, result in tests: self.assertEqual(markup(test), result)
def test_cleanuphtml(self): """Test cleanup_html""" markup = postmarkup.create() tests = [(u"""\n<p>\n </p>\n""", u""), (u"""<b>\n\n<i> </i>\n</b>Test""", u"Test"), (u"""<p id="test">Test</p>""", u"""<p id="test">Test</p>"""),] for test, result in tests: self.assertEqual(markup.cleanup_html(test).strip(), result)
def test_tabletag(self): """Test Table Tags""" markup = postmarkup.create() tests = [( u"[table][tr][td]Row 1, Col 1[/td][td]Row 1, Col 2[/td][/tr][tr][td]Row 2, Col 1[/td][td]Row 2, Col 2[/td][/tr][/table]", u'<table><tr><td>Row 1, Col 1</td><td>Row 1, Col 2</td></tr><tr><td>Row 2, Col 1</td><td>Row 2, Col 2</td></tr></table>' )] for test, result in tests: self.assertEqual(markup(test), result)
def test_simpletag(self): "Test simple tags" markup = postmarkup.create() tests = [(u'[b]Hello[/b]', u"<strong>Hello</strong>"), (u'[i]Italic[/i]', u"<em>Italic</em>"), (u'[s]Strike[/s]', u"<strike>Strike</strike>"), (u'[u]underlined[/u]', u"<u>underlined</u>"), ] for test, result in tests: self.assertEqual(markup(test), result)
def test_links(self): """Test links produce correct output""" markup = postmarkup.create(annotate_links=False) tests = [(u'[link=http://www.willmcgugan.com]blog1[/link]', u'<a href="http://www.willmcgugan.com">blog1</a>'), (u'[link="http://www.willmcgugan.com"]blog2[/link]', u'<a href="http://www.willmcgugan.com">blog2</a>'), (u'[link http://www.willmcgugan.com]blog3[/link]', u'<a href="http://www.willmcgugan.com">blog3</a>'), (u'[link]http://www.willmcgugan.com[/link]', u'<a href="http://www.willmcgugan.com">http://www.willmcgugan.com</a>') ] for test, result in tests: self.assertEqual(markup(test), result)
def test_simpletag(self): "Test simple tags" markup = postmarkup.create() tests = [ (u'[b]Hello[/b]', u"<strong>Hello</strong>"), (u'[i]Italic[/i]', u"<em>Italic</em>"), (u'[s]Strike[/s]', u"<strike>Strike</strike>"), (u'[u]underlined[/u]', u"<u>underlined</u>"), ] for test, result in tests: self.assertEqual(markup(test), result)
def test_links(self): """Test links produce correct output""" markup = postmarkup.create(annotate_links=False) tests = [ (u'[link=http://www.willmcgugan.com]blog1[/link]', u'<a href="http://www.willmcgugan.com">blog1</a>'), (u'[link="http://www.willmcgugan.com"]blog2[/link]', u'<a href="http://www.willmcgugan.com">blog2</a>'), (u'[link http://www.willmcgugan.com]blog3[/link]', u'<a href="http://www.willmcgugan.com">blog3</a>'), (u'[link]http://www.willmcgugan.com[/link]', u'<a href="http://www.willmcgugan.com">http://www.willmcgugan.com</a>') ] for test, result in tests: self.assertEqual(markup(test), result)
def convert_message_text(self, message_text): class MyLinkTag(postmarkup.LinkTag): """ Overrides annotate_link behavior in LinkTag """ def __init__(self, name, **kwargs): postmarkup.LinkTag.__init__(self, name, annotate_links=False, **kwargs) markup = postmarkup.create(include=self.ALLOWED_MARKUP, use_pygments=False) markup.add_tag(MyLinkTag, u'url') return markup(message_text)
# * Neither the name of the University of California, Berkeley nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import postmarkup from unidecode import unidecode forumPostmarkup = postmarkup.create(use_pygments=True) def forum(text): return forumPostmarkup(text) descriptionPostmarkup = postmarkup.create(use_pygments=True) def torrentDescription(text): return descriptionPostmarkup(text) urlAvailableChars = '[a-zA-Z0-9_-]+' def getUrlPrettyName(name): return unidecode(name).replace(' ', '_')
#!/usr/bin/env python #!/usr/bin/env python import postmarkup import markuptags post_render = postmarkup.create(exlude=["url", "link"], annotate_links=False, auto_url=False) #post_render.add_tag(postmarkup.SectionTag, "in") # Auto register markup tags... for symbol in dir(markuptags): if symbol.startswith('__'): continue if symbol.endswith('Tag'): obj = getattr(markuptags, symbol) default_name = getattr(obj, 'DEFAULT_NAME', '') if default_name: post_render.add_tag(obj, default_name) if __name__ == "__main__": test = """[summary] This is a [b]summary[/b]...[/summary] Article [py]import postmarkup print postmarkup.__version__[/py] [eval safe]range(10)[/eval] [py]x=1[/py] X is [eval]x[/eval], [py]import datetime[/py][eval]datetime.datetime.now()[/eval]
VERSION = 1 try: import postmarkup except: print "Requires Postmarkup (http://code.google.com/p/postmarkup/)" raise post = postmarkup.create() feed = postmarkup.create()
def test_tags_with_spaces(self): markup = postmarkup.create() tests = [("[i]one[/i][i] [/i][i]two[/i][i] [/i][i]three[/i]", "<em>one</em> <em>two</em> <em>three</em>")] for test, result in tests: self.assertEqual(markup(test), result)
def __init__(self, *args, **kwargs): super(BBCodeFormatter, self).__init__(*args, **kwargs) import postmarkup self.pm = postmarkup.create()
def __init__(self): self.bbcode = postmarkup.create(annotate_links=False, use_pygments=False)
def __init__(self, renderer=None): if renderer is None: self.renderer = postmarkup.create()
def test_broken_img(self): markup = postmarkup.create() tests = [("[img]foo[/img", ""), ("[img]fo[o[/img]", "")] for test, result in tests: self.assertEqual(markup(test), result)
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.template import Library from django.utils.safestring import mark_safe import postmarkup register = Library() class NewWindowLinkTag(postmarkup.LinkTag): def render_open(self, parser, node_index, *args, **kwargs): return super(NewWindowLinkTag, self).render_open(parser, node_index, *args, **kwargs).replace('<a href', '<a rel="nofollow" ' 'target="_blank" href') bb_mark = postmarkup.create() bb_mark.add_tag(NewWindowLinkTag, 'link') bb_mark.add_tag(NewWindowLinkTag, 'url') @register.filter def bbcode(text): """Simply encode the BBCode within the text. Template tag available in ``common`` app's ``bbcode`` library. :param text: the string to render as BBCode""" return mark_safe(bb_mark(text))
# TODO: Remove, make db migration instead def rm_legacy_tags(text): "Replace legacy tags by bbcode" base_tags = [(r'ita', 'i'), (r'bold', 'b'), (r'under', 'u')] all_tags = ([(re.escape('[' + old + ']'), '[' + new + ']') for old, new in base_tags] + [(re.escape('[/' + old + ']'), '[/' + new + ']') for old, new in base_tags]) query = [(re.compile(old), new) for old, new in all_tags] for old_match, new in query: text = old_match.sub(new, text) return text # Rendering render_bbcode = postmarkup.create(use_pygments=False, annotate_links=False, exclude=["img"]) render_bbcode.add_tag(CustomImgTag, 'img') render_bbcode.add_tag(SpoilerTag, 'spoiler') render_bbcode.add_tag(VideoTag, 'video') def render(text, markup='bbcode'): if markup == 'bbcode': text = rm_legacy_tags(text) # TODO: make db migration instead return smilify(render_bbcode(text, cosmetic_replace=False)) elif markup == 'markdown': return markdown.markdown(text, safe_mode='escape')
from flask_wtf.file import file_allowed, file_required from flaskext.uploads import configure_uploads from sqlalchemy import create_engine from flask_wtf import Form, StringField, validators, TextAreaField, FileField from flask_wtf import Required from flask.globals import request import time, datetime, flask_wtf, os from werkzeug.utils import secure_filename from PIL import Image import helpers from postmarkup import render_bbcode import postmarkup if PYGMENTS_ENABLED: import pygments markup_engine = postmarkup.create(exclude=['img'], use_pygments=PYGMENTS_ENABLED) DATABASE_NAME = 'pytest' DEBUG = True SECRET_KEY = '\xd5\x01\xc8\x7f\xcb^,B\xe8zE\xc7\n\xa1\\4\x98\x93\xe1"\x9d\xf2\xd0@' DATABASE_USER = '******' DATABASE_PASSWORD = '******' DATABASE_HOST = 'localhost' UPLOADED_FILES_DEST = r'C:\Users\Andor\PycharmProjects\lohere-\static\images' UPLOADS_DEFAULT_DEST = r'C:\Users\Andor\PycharmProjects\lohere-\static\images' NOKO_STRING = 'noko' SAGE_STRING = 'sage' app = Flask(__name__) app.config.from_object(__name__)
def html(self, input_text): import postmarkup bbcode_markup = postmarkup.create() return bbcode_markup(input_text)
import postmarkup try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.template.loader import get_template, select_template from django.template.context import Context import re from collections import defaultdict import xml.etree.ElementTree as ET postmarkup_renderer = postmarkup.create() class ExtendedMarkupError(Exception): pass class Chunk(object): def __init__(self, text, chunk_type='text'): self.text = text self.chunk_type = chunk_type #self.vars = defaultdict(lambda: None) self.vars = {} def __str__(self): return "%s: %s, %s" % (self.chunk_type, repr(self.text), repr(
return '' class AsideTag(postmarkup.TagBase): def __init__(self, name): super(AsideTag, self).__init__(name) def render_open(self, parser, node_index): return '<div class="aside">' def render_close(self, parser, node_index): return '</div>' doccode = postmarkup.create() doccode.tag_factory.add_tag(FieldTag, "title") doccode.tag_factory.add_tag(FieldTag, "id") doccode.tag_factory.add_tag(FieldTag, "section") doccode.tag_factory.add_tag(AsideTag, "aside") def render(code): data = {} body = doccode(code.strip(), paragraphs=True, tag_data=data) doc = {} for k, v in data.items(): if k.startswith('doc.'): doc[k.split('.', 1)[-1]] = v doc['body'] = body return doc
return u'<img title="%s" src="%s"/>' % ( attach.description, url) class HTMLTag(TagBase): def render_open(self, parser, node_index): contents = self.get_contents(parser) contents = strip_bbcode(contents) self.skip_contents(parser) return clean_html(contents) pygments_available = True try: from pygments import highlight # NOQA from pygments.lexers import get_lexer_by_name, ClassNotFound # NOQA from pygments.formatters import HtmlFormatter # NOQA except ImportError: # Make Pygments optional pygments_available = False _postmarkup = create(use_pygments=pygments_available, annotate_links=False) _postmarkup.tag_factory.add_tag(LBQuoteTag, 'quote') _postmarkup.tag_factory.add_tag(ReplyViewTag, 'replyview') _postmarkup.tag_factory.add_tag(ReplyViewTag, 'hide') _postmarkup.tag_factory.add_tag(AttachTag, 'attach') _postmarkup.tag_factory.add_tag(AttachImgTag, 'attachimg') _postmarkup.tag_factory.add_tag(HTMLTag, 'html') _postmarkup.tag_factory.add_tag(VideoTag, 'video')
def __init__(self, name, **kwargs): TagBase.__init__(self, name, inline=True) def render_open(self, parser, node_index): contents = self.get_contents(parser) self.skip_contents(parser) try: attach = Attachment.objects.get(pk=contents) except: return u'[attachimg]%s[/attachimg]' % contents pass return u'<img title="%s" src="%s"/>' % (attach.description, \ attach.file.url) class HTMLTag(TagBase): def render_open(self, parser, node_index): contents = self.get_contents(parser) contents = strip_bbcode(contents) self.skip_contents(parser) return clean_html(contents) _postmarkup = create(use_pygments=False, annotate_links=False) _postmarkup.tag_factory.add_tag(LBQuoteTag, 'quote') _postmarkup.tag_factory.add_tag(ReplyViewTag, 'replyview') _postmarkup.tag_factory.add_tag(ReplyViewTag, 'hide') _postmarkup.tag_factory.add_tag(AttachTag, 'attach') _postmarkup.tag_factory.add_tag(AttachImgTag, 'attachimg') _postmarkup.tag_factory.add_tag(HTMLTag, 'html')
register = template.Library() #bbcode class LBQuoteTag(QuoteTag): def render_open(self, parser, node_index): if self.params: return u'<div class="quotebox"><cite>%s:</cite><blockquote><p>'%(PostMarkup.standard_replace(self.params)) else: return u'<div class="quotebox"><blockquote><p>' def render_close(self, parser, node_index): return u"</p></blockquote></div>" _postmarkup = create(use_pygments=False, annotate_links=False) _postmarkup.tag_factory.add_tag(LBQuoteTag, 'quote') @register.filter def bbcode(s): if not s: return "" return _postmarkup(s) #bbcode end @register.filter def form_all_error(form): errors = [] global_error = form.errors.get('__all__', '') if global_error: global_error = global_error.as_text()
class RedLineTag(postmarkup.TagBase): def __init__(self, name, **kwargs): super(RedLineTag, self).__init__(name, inline=True, auto_close=True) self.tag_key = 'RedLineTag.nest_level' def render_open(self, parser, node_index): return ' ' def render_close(self, parser, node_index): return '' _renderer = postmarkup.create(use_pygments=False, annotate_links=False) _renderer.tag_factory.add_tag(LinkTag, 'url', annotate_links=False) _renderer.tag_factory.add_tag(LinkTag, 'link', annotate_links=False) _renderer.tag_factory.add_tag(SpoilerTag, 'spoiler') _renderer.tag_factory.add_tag(HRTag, 'hr') _renderer.tag_factory.add_tag(LeftSquareBracketTag, 'lsb') _renderer.tag_factory.add_tag(RightSquareBracketTag, 'rsb') _renderer.tag_factory.add_tag(RedLineTag, 'rl') def render(*argv, **kwargs): try: kwargs['cosmetic_replace'] = False kwargs['encoding'] = 'utf-8' return _renderer.render_to_html(*argv, **kwargs) except:
class TableTag(TableBaseTag): def __init__(self, name, **kwargs): super(TableTag, self).__init__(name, 'table') class TableHeaderTag(TableBaseTag): def __init__(self, name, **kwargs): super(TableHeaderTag, self).__init__(name, 'th') class TableRowTag(TableBaseTag): def __init__(self, name, **kwargs): super(TableRowTag, self).__init__(name, 'tr') class TableDataTag(TableBaseTag): def __init__(self, name, **kwargs): super(TableDataTag, self).__init__(name, 'td') # Instantiate our BBCode converter. bbc_converter = postmarkup.create(use_pygments=False, exclude=[u'url']) bbc_converter.tag_factory.add_tag(PreviewImgTag, u'previewimg') bbc_converter.tag_factory.add_tag(ScreenshotTag, u'screenshot') bbc_converter.tag_factory.add_tag(PreviewYouTubeTag, u'previewyoutube') bbc_converter.tag_factory.add_tag(BulletedTag, u'h1', u'h3') bbc_converter.tag_factory.add_tag(GuideInterceptLinkTag, u'url', annotate_links=False) bbc_converter.tag_factory.add_tag(TableTag, u'table') bbc_converter.tag_factory.add_tag(TableHeaderTag, u'th') bbc_converter.tag_factory.add_tag(TableRowTag, u'tr') bbc_converter.tag_factory.add_tag(TableDataTag, u'td') # Simple context manager to push and pop working directory. @contextlib.contextmanager def visit_dir(dir): cwd = os.getcwd()
_safe_chars = postmarkup.LinkTag._safe_chars | frozenset('+') class RedLineTag(postmarkup.TagBase): def __init__(self, name, **kwargs): super(RedLineTag, self).__init__(name, inline=True, auto_close=True) self.tag_key = 'RedLineTag.nest_level' def render_open(self, parser, node_index): return ' ' def render_close(self, parser, node_index): return '' _renderer = postmarkup.create(use_pygments=False, annotate_links=False) _renderer.tag_factory.add_tag(LinkTag, 'url', annotate_links=False) _renderer.tag_factory.add_tag(LinkTag, 'link', annotate_links=False) _renderer.tag_factory.add_tag(SpoilerTag, 'spoiler') _renderer.tag_factory.add_tag(HRTag, 'hr') _renderer.tag_factory.add_tag(LeftSquareBracketTag, 'lsb') _renderer.tag_factory.add_tag(RightSquareBracketTag, 'rsb') _renderer.tag_factory.add_tag(RedLineTag, 'rl') _renderer.tag_factory.add_tag(YoutubeTag, 'youtube') def render(*argv, **kwargs): try: kwargs['cosmetic_replace'] = False kwargs['encoding'] = 'utf-8' return _renderer.render_to_html(*argv, **kwargs)
def markup(value, parser): esc = conditional_escape if parser == 1: import postmarkup from pygments import highlight from pygments.lexers import get_lexer_by_name, ClassNotFound #from pygments.lexers import guess_lexer from pygments.formatters import HtmlFormatter markup = postmarkup.create(annotate_links=False,exclude=["img", "code"],use_pygments=False) class ImgTag(postmarkup.TagBase): valid_params = ("left", "right") def __init__(self, name, **kwargs): postmarkup.TagBase.__init__(self, name, inline=True) def render_open(self, parser, node_index): contents = self.get_contents(parser) self.skip_contents(parser) contents = postmarkup.strip_bbcode(contents).replace(u'"', "%22") if self.params in self.valid_params: return u'<img class="float-%s" src="%s" alt="%s">' % (self.params, contents, contents) else: return u'<img src="%s" alt="%s">' % (contents, contents) class PygmentsCodeTag(postmarkup.TagBase): def __init__(self, name, pygments_line_numbers=True, **kwargs): postmarkup.TagBase.__init__(self, name, enclosed=True, strip_first_newline=True) self.line_numbers = pygments_line_numbers def render_open(self, parser, node_index): contents = self.get_contents(parser) self.skip_contents(parser) #if self.params: try: lexer = get_lexer_by_name(self.params, stripall=True) except ClassNotFound: contents = postmarkup._escape_no_breaks(contents) return '<div class="code"><pre>%s</pre></div>' % contents #Well, do we realy need lexer gues? #else: # lexer = guess_lexer(contents) formatter = HtmlFormatter(linenos='inline', cssclass="code") return highlight(contents, lexer, formatter) markup.add_tag(ImgTag, u'img') markup.add_tag(PygmentsCodeTag, u'code') markup.add_tag(postmarkup.SimpleTag, u'block', u'div class="mblock"') value = "<p>" + markup(value) + "</p>" return value elif parser == 2: from markdown import markdown value = esc(value) value = markdown(value) return value elif parser == 3: from wikimarkup import parselite value = parselite(value) elif parser == 4: from django.template.defaultfilters import removetags value = removetags(value, 'style html script applet form frame iframe map noframes noscript object var area input button select') value = linebreaks(value) else: value = esc(value) value = urlize(value) value = linebreaks(value) return value
if self.domain in self.iframe_domains: return ('<div class="embed-responsive embed-responsive-16by9">' '<iframe class="embed-responsive-item" src="{}" ' 'frameborder="0" allowfullscreen="true"></iframe></div>')\ .format(postmarkup.PostMarkup\ .standard_replace_no_break(self.url)) elif self.domain: return '<video loop="true" controls="true" src="{}"></video>'\ .format(postmarkup.PostMarkup\ .standard_replace_no_break(self.url)) else: return "" render_bbcode = postmarkup.create(use_pygments=False, annotate_links=False) render_bbcode.add_tag(SpoilerTag, 'spoiler') render_bbcode.add_tag(VideoTag, 'video') def convert_text_to_html(text, markup='bbcode'): if markup == 'bbcode': text = rm_legacy_tags(text) text = render_bbcode(text, cosmetic_replace=False) elif markup == 'markdown': text = markdown.markdown(text, safe_mode='escape') text = urlize(text) return text ### Smiley stuff ###
import postmarkup try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.template.loader import get_template, select_template from django.template.context import Context import re from collections import defaultdict import xml.etree.ElementTree as ET postmarkup_renderer = postmarkup.create() class ExtendedMarkupError(Exception): pass class Chunk(object): def __init__(self, text, chunk_type='text'): self.text = text self.chunk_type = chunk_type #self.vars = defaultdict(lambda: None) self.vars = {} def __str__(self): return "%s: %s, %s" % (self.chunk_type, repr(self.text), repr(self.vars))
def depart_document(self, node): self.fragment = self.body _w = Writer() _w.translator_class = CleanedHTMLTranslator def get_html_from_rst(rst): return core.publish_string(rst, writer=_w) def get_html_from_md(md): return misaka.html(md) _bbcode_markup = postmarkup.create() def get_html_from_bbcode(bbcode): return _bbcode_markup(bbcode) def get_html_from_textile(text): return textile.textile(text) def get_html_and_plain(text, text_input_type): if text_input_type == 'html': return text, get_plain_from_html(text) elif text_input_type == 'md': html = get_html_from_md(text)