bbj/src/formatting.py

82 lines
2.1 KiB
Python
Raw Normal View History

2017-04-03 04:51:44 +00:00
"""
This module is not complete and none of its functions are currently
used elsewhere. Subject to major refactoring.
"""
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-04-05 21:33:25 +00:00
#0, 1 2 3 4 5 6
2017-04-02 07:35:58 +00:00
colors = [
2017-04-05 21:33:25 +00:00
"red", "yellow", "green", "blue", "cyan", "magenta"
2017-04-02 07:35:58 +00:00
]
2017-03-04 01:56:08 +00:00
2017-04-02 07:35:58 +00:00
markup = [
"bold", "italic", "underline", "strike"
]
2017-03-01 21:54:34 +00:00
2017-04-10 14:02:08 +00:00
tokens = re.compile(r"\[(%s): (.+?)]" % "|".join(colors + markup),
flags=re.DOTALL)
2017-03-01 21:54:34 +00:00
2017-04-10 14:02:08 +00:00
quotes = re.compile(">>([0-9]+)")
linequotes = re.compile("^(>.+)$",
2017-04-02 07:35:58 +00:00
flags=re.MULTILINE)
def apply_formatting(msg_obj, formatter):
"""
Receives a messages object from a thread and returns it with
all the message bodies passed through FORMATTER.
"""
2017-04-10 14:02:08 +00:00
for x in range(len(msg_obj)):
msg_obj[x]["body"] = formatter(msg_obj[x]["body"])
2017-04-02 07:35:58 +00:00
return msg_obj
def raw(text):
"""
Just return the message in the same state that it was submitted.
"""
return text
2017-04-10 14:02:08 +00:00
def strip(text):
"""
Returns the text with all formatting directives removed.
Not to be confused with `raw`.
"""
def entities(text):
"""
Returns a tuple where [0] is raw text
"""
2017-04-02 07:35:58 +00:00
def html(text):
"""
Returns messages in html format, after being sent through markdown.
Color directives are given as:
<span color="{COLOR}" style="color: {COLOR};">content</span>
Directives may be nested. If you don't have access to a fully featured
and compliant html renderer in your client, you should use one of the
simpler directives like strip, indice, or raw.
"""
text = TOKENS.sub(map_html, escape(text))
text = QUOTES.sub(r'<span post="\1" class="quote">\g<0></span>', text)
return markdown(
LINEQUOTES.sub(r'<span class="linequote">\1</span><br>', text))
# and this is the callback used by the sub statement
2017-03-03 01:10:16 +00:00
def map_html(match):
directive, body = match.group(1).lower(), match.group(2)
2017-04-02 07:35:58 +00:00
if directive in colors:
2017-03-03 01:10:16 +00:00
return '<span color="{0}" style="color: {0};">{1}</span>'.format(directive, body)
2017-04-02 07:35:58 +00:00
elif directive in markup:
2017-03-03 01:10:16 +00:00
return '<{0}>{1}</{0}>'.format(directive[0], body)
return body