bbj/src/formatting.py

29 lines
989 B
Python
Raw Normal View History

2017-03-03 01:10:16 +00:00
from markdown import markdown
from html import escape
2017-03-01 21:54:34 +00:00
import re
2017-03-03 01:10:16 +00:00
# these parameters are utter nonsense...
2017-03-01 21:54:34 +00:00
COLORS = ["red", "green", "yellow", "blue", "magenta", "cyan"]
2017-03-03 01:10:16 +00:00
MARKUP = ["bold", "italic", "underline", "strike"]
TOKENS = re.compile(r"\[({}): (.+?)]".format("|".join(COLORS + MARKUP)), flags=re.DOTALL)
QUOTES = re.compile(">>([0-9]+)")
LINEQUOTES = re.compile("^(>.+)$", flags=re.MULTILINE)
2017-03-01 21:54:34 +00:00
2017-03-03 01:10:16 +00:00
def map_html(match):
directive, body = match.group(1).lower(), match.group(2)
if directive in COLORS:
return '<span color="{0}" style="color: {0};">{1}</span>'.format(directive, body)
elif directive in MARKUP:
return '<{0}>{1}</{0}>'.format(directive[0], body)
return body
2017-03-01 21:54:34 +00:00
def parse(text, doquotes=True):
2017-03-03 01:10:16 +00:00
text = TOKENS.sub(map_html, escape(text))
2017-03-01 21:54:34 +00:00
if doquotes:
2017-03-03 01:10:16 +00:00
text = QUOTES.sub(r'<span post="\1" class="quote">\g<0></span>', text)
return markdown(
2017-03-04 01:38:20 +00:00
LINEQUOTES.sub(r'<span class="linequote">\1</span><br>', text)
2017-03-03 01:10:16 +00:00
)