1
|
|
|
""" |
2
|
|
|
byceps.services.text_markup.service |
3
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
4
|
|
|
|
5
|
|
|
:Copyright: 2006-2021 Jochen Kupperschmidt |
6
|
|
|
:License: Revised BSD (see `LICENSE` file for details) |
7
|
|
|
""" |
8
|
|
|
|
9
|
1 |
|
from html import escape |
10
|
|
|
|
11
|
1 |
|
from bbcode import Parser |
12
|
1 |
|
from flask_babel import gettext |
13
|
|
|
|
14
|
1 |
|
try: |
15
|
1 |
|
from .smileys import get_smileys |
16
|
1 |
|
except ModuleNotFoundError: |
17
|
1 |
|
def get_smileys(): |
18
|
1 |
|
return [] |
19
|
|
|
|
20
|
|
|
|
21
|
1 |
|
try: |
22
|
1 |
|
from .smileys import replace_smileys as _replace_smileys |
23
|
1 |
|
except ModuleNotFoundError: |
24
|
1 |
|
def _replace_smileys(text): |
25
|
1 |
|
return text |
26
|
|
|
|
27
|
|
|
|
28
|
1 |
|
def _create_parser() -> Parser: |
29
|
|
|
"""Create a customized BBcode parser.""" |
30
|
1 |
|
parser = Parser(replace_cosmetic=False) |
31
|
|
|
|
32
|
1 |
|
_add_code_formatter(parser) |
33
|
1 |
|
_add_image_formatter(parser) |
34
|
1 |
|
_add_quote_formatter(parser) |
35
|
|
|
|
36
|
1 |
|
return parser |
37
|
|
|
|
38
|
|
|
|
39
|
1 |
|
def _add_code_formatter(parser: Parser) -> None: |
40
|
|
|
"""Replace code tags.""" |
41
|
|
|
|
42
|
1 |
|
def render_code(name, value, options, parent, context): |
43
|
1 |
|
return f'<pre><code class="block">{value}</code></pre>' |
44
|
|
|
|
45
|
1 |
|
parser.add_formatter( |
46
|
|
|
'code', render_code, replace_cosmetic=False, replace_links=False |
47
|
|
|
) |
48
|
|
|
|
49
|
|
|
|
50
|
1 |
|
def _add_image_formatter(parser: Parser) -> None: |
51
|
|
|
"""Replace image tags.""" |
52
|
|
|
|
53
|
1 |
|
def render_image(name, value, options, parent, context): |
54
|
1 |
|
return f'<img src="{value}">' |
55
|
|
|
|
56
|
1 |
|
parser.add_formatter( |
57
|
|
|
'img', render_image, replace_cosmetic=False, replace_links=False |
58
|
|
|
) |
59
|
|
|
|
60
|
|
|
|
61
|
1 |
|
def _add_quote_formatter(parser: Parser) -> None: |
62
|
|
|
"""Render quotes with optional author.""" |
63
|
|
|
|
64
|
1 |
|
def render_quote(name, value, options, parent, context): |
65
|
1 |
|
intro = '' |
66
|
1 |
|
if 'author' in options: |
67
|
1 |
|
author = escape(options['author']) |
68
|
1 |
|
verb = gettext('wrote') |
69
|
1 |
|
intro = ( |
70
|
|
|
f'<p class="quote-intro"><cite>{author}</cite> {verb}:</p>\n' |
71
|
|
|
) |
72
|
1 |
|
return f'{intro}<blockquote>{value}</blockquote>' |
73
|
|
|
|
74
|
1 |
|
parser.add_formatter('quote', render_quote, strip=True) |
75
|
|
|
|
76
|
|
|
|
77
|
1 |
|
_PARSER = _create_parser() |
78
|
|
|
|
79
|
|
|
|
80
|
1 |
|
def render_html(value: str) -> str: |
81
|
|
|
"""Render text as HTML, interpreting BBcode.""" |
82
|
1 |
|
html = _PARSER.format(value) |
83
|
1 |
|
html = _replace_smileys(html) |
84
|
|
|
return html |
85
|
|
|
|