blob: cec690fce482efeecc30eaaf9679efe3f6e70fca (
plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
"""
Like the standard ![alt text](src.img title_text) image format in Markdown, but with two extra parameters.
Usage:
![alt text](src.img title_text href figcapture)
href: if not empty, encapsulates image in <a> with the specified url
figcapture: if not empty, encapsulates image in a <figure> with the specified figcapture
ALL PARAMETERS ARE MANDATORY!
Parameters can be encapsulated in double-quotes. Use "" for empty parameter.
"""
from marko import inline
from marko.helpers import MarkoExtension
from . import utils
class ExtendedImageElement(inline.InlineElement):
pattern = r'!\[(.*)\]\(((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\s((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\s((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\s((?:[^"\s\\]|\\.)+|"(?:[^"\\]|\\.)*")\)'
parse_children = True
def __init__(self, match):
self.alt = self.__strip_quotes(match.group(1))
self.src = self.__strip_quotes(match.group(2))
self.title = self.__strip_quotes(match.group(3))
self.href = self.__strip_quotes(match.group(4))
self.figcaption = self.__strip_quotes(match.group(5))
@staticmethod
def __strip_quotes(text: str) -> str:
if text.startswith('"'):
return text[1:-1]
return text
def __create_image_renderer(filters: list[str]):
class ExtendedImageRenderer:
FILTERS = filters
def render_extended_image_element(self, element):
img = f'<img src="{element.src}" title="{element.title}" alt="{element.alt}" />'
if element.href != "":
img = f'<a href="{element.href}" {"target=\"_blank\"" if utils.is_foreign_url(element.href, ExtendedImageRenderer.FILTERS) else ""}>{img}</a>'
if element.figcaption != "":
img = f"<figure>{img}<figcaption>{element.figcaption}</figcaption></figure>"
return img
return ExtendedImageRenderer
def get_image_renderer(filters: list[str] = None):
if filters is None:
filters = []
return MarkoExtension(
elements=[ExtendedImageElement],
renderer_mixins=[__create_image_renderer(filters)]
)
|