aboutsummaryrefslogtreecommitdiffstats
path: root/prototype/src/formatting.py
blob: 56614c35dbe173a3ef955e61361478ee4cea7b44 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from markdown import markdown
from html import escape
import re


COLORS = ["red", "green", "yellow", "blue", "magenta", "cyan"]
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)


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


def parse(text, doquotes=True):
    text = TOKENS.sub(map_html, escape(text))
    if doquotes:
        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)
    )
Un proyecto texto-plano.xyz