1. offline
  2. django-bbmarkup

Commits

Sergey Maranchuk  committed b8064b2

change html;added parser for [code] tag

  • Participants
  • Parent commits 374ab72
  • Branches default

Comments (0)

Files changed (1)

File bbmarkup/__init__.py

View file
 import re
 from django.conf import settings
+from django.utils.html import escape, linebreaks
+
 
 __all__ = ['BBCODE_RULES', 'bbcode']
 
         (r'\[IMG\](.+?)\[/IMG\]', r'<img src="\1">'),
         (r'\[IMG=(.+?)\](.+?)\[/IMG\]', r'<img src="\1" alt="\2">'),
         (r'\[color=(.+?)\](.+?)\[/color\]', r'<span style="color:\1">\2</span>'),
-        (r'\[b\](.+?)\[/b\]', r'<b>\1</b>'),
-        (r'\[i\](.+?)\[/i\]', r'<i>\1</i>'),
+        (r'\[b\](.+?)\[/b\]', r'<strong>\1</strong>'),
+        (r'\[i\](.+?)\[/i\]', r'<em>\1</em>'),
         (r'\[u\](.+?)\[/u\]', r'<u>\1</u>'),
-        (r'\[quote\](.+?)\[/quote\]', r'<div id="quote">\1</div>'),
-        (r'\[center\](.+?)\[/center\]', r'<div align="center">\1</div>'),
-        (r'\[code\](.+?)\[/code\]', r'<tt>\1</tt>'),
+        (r'\[s\](.+?)\[/s\]', r'<strike>\1</strike>'),
+        (r'\[quote\](.+?)\[/quote\]', r'<blockquote>\1</blockquote>'),
+        (r'\[center\](.+?)\[/center\]', r'<div style="text-align: center;">\1</div>'),
         (r'\[big\](.+?)\[/big\]', r'<big>\1</big>'),
         (r'\[small\](.+?)\[/small\]', r'<small>\1</small>'),
         (r'\[br\]', r'<br />') ]
 
 BBCODE_RULES += getattr(settings, 'BBMARKUP_EXTRA_RULES', [])
 
+
 BBCODE_RULES_COMPILED = []
 for bbset in (getattr(settings, 'BBMARKUP_CUSTOM_RULES', []) or BBCODE_RULES):
     p = re.compile(bbset[0], re.DOTALL)
     BBCODE_RULES_COMPILED.append((p, bbset[1]))
 
 
-def bbcode(value):
+def code_parser(matchobj):
+    """
+    Escaping bbcode and html tags between [code] tags.
+    """
 
+    value = matchobj.group(1)
+    value = value.replace('[', '&#91;')
+    value = value.replace(']', '&#93;')
+    return "<pre><code>%s</code></pre>" % value
+
+
+def bbcode(value, linebr=True, code_parser=code_parser):
+    """
+    >>> data = '[code]print "Lorem [b]imsum[b]"[/code]'
+    >>> bbcode(data)
+    u'<pre><code>print &quot;Lorem &#91;b&#93;imsum&#91;b&#93;&quot;</code></pre>'
+    >>> bbcode('[i]Lorem[/i] \n [s]imsum[/s]')
+    u'<em>Lorem</em> <br /> <strike>imsum</strike>'
+    """
+
+    value = escape(value)
+    value = re.sub(r'\[code\](.+?)\[/code\]', code_parser, value)
     for bbset in BBCODE_RULES_COMPILED:
         value = bbset[0].sub(bbset[1], value)
+    if linebr:
+        value = value.replace('\n', '<br />')
 
     return value