-
Notifications
You must be signed in to change notification settings - Fork 111
/
span_token.py
331 lines (254 loc) · 10 KB
/
span_token.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
"""
Built-in span-level token classes.
"""
import html
import re
import mistletoe.span_tokenizer as tokenizer
from mistletoe import core_tokens, token
"""
Tokens to be included in the parsing process, in the order specified.
"""
__all__ = ['EscapeSequence', 'Strikethrough', 'AutoLink', 'CoreTokens',
'InlineCode', 'LineBreak', 'RawText']
def tokenize_inner(content):
"""
A wrapper around span_tokenizer.tokenize. Pass in all span-level token
constructors as arguments to span_tokenizer.tokenize.
Doing so (instead of importing span_token module in span_tokenizer)
avoids cyclic dependency issues, and allows for future injections of
custom token classes.
_token_types variable is at the bottom of this module.
See also: span_tokenizer.tokenize, block_token.tokenize.
"""
return tokenizer.tokenize(content, _token_types)
def add_token(token_cls, position=1):
"""
Allows external manipulation of the parsing process.
This function is called in BaseRenderer.__enter__.
Arguments:
token_cls (SpanToken): token to be included in the parsing process.
"""
_token_types.insert(position, token_cls)
def remove_token(token_cls):
"""
Allows external manipulation of the parsing process.
This function is called in BaseRenderer.__exit__.
Arguments:
token_cls (SpanToken): token to be removed from the parsing process.
"""
_token_types.remove(token_cls)
def reset_tokens():
"""
Resets global _token_types to all token classes in __all__.
"""
global _token_types
_token_types = [globals()[cls_name] for cls_name in __all__]
class SpanToken(token.Token):
parse_inner = True
parse_group = 1
precedence = 5
def __init__(self, match):
if not self.parse_inner:
self.content = match.group(self.parse_group)
def __contains__(self, text):
if self.children is not None:
return any(text in child for child in self.children)
return text in self.content
@classmethod
def find(cls, string):
return cls.pattern.finditer(string)
class CoreTokens(SpanToken):
"""
Represents core tokens (Strong, Emphasis, Image, Link) during the early stage of parsing.
Replaced with objects of the proper classes in the final stage of parsing.
"""
precedence = 3
def __new__(self, match):
return globals()[match.type](match)
@classmethod
def find(cls, string):
return core_tokens.find_core_tokens(string, token._root_node)
class Strong(SpanToken):
"""
Strong token. ("**some text**")
This is an inline token. Its children are inline (span) tokens.
One of the core tokens.
"""
def __init__(self, match):
self.delimiter = match.delimiter
class Emphasis(SpanToken):
"""
Emphasis token. ("*some text*")
This is an inline token. Its children are inline (span) tokens.
One of the core tokens.
"""
def __init__(self, match):
self.delimiter = match.delimiter
class InlineCode(SpanToken):
"""
Inline code token. ("`some code`")
This is an inline token with a single child of type RawText.
"""
pattern = re.compile(r"(?<!\\|`)(?:\\\\)*(`+)(?!`)(.+?)(?<!`)\1(?!`)", re.DOTALL)
parse_inner = False
parse_group = 2
def __init__(self, match):
content = match.group(self.parse_group)
self.delimiter = match.group(1)
content = content.replace('\n', ' ')
self.padding = " " if not content.isspace() and content.startswith(" ") and content.endswith(" ") else ""
if self.padding:
content = content[1:-1]
self.children = (RawText(content),)
@classmethod
def find(cls, string):
matches = core_tokens._code_matches
core_tokens._code_matches = []
return matches
class Strikethrough(SpanToken):
"""
Strikethrough token. ("~~some text~~")
This is an inline token. Its children are inline (span) tokens.
"""
pattern = re.compile(r"(?<!\\)(?:\\\\)*~~(.+?)~~", re.DOTALL)
class Image(SpanToken):
"""
Image token. ("![alt](src "title")")
This is an inline token. Its children are inline (span) tokens holding the image description.
One of the core tokens.
Attributes:
src (str): image source.
title (str): image title (default to empty).
label (str): link label, for reference links.
"""
repr_attributes = ("src", "title")
def __init__(self, match):
self.src = EscapeSequence.strip(match.group(2).strip())
self.title = EscapeSequence.strip(match.group(3))
self.dest_type = getattr(match, "dest_type", None)
self.label = getattr(match, "label", None)
self.title_delimiter = getattr(match, "title_delimiter", None)
class Link(SpanToken):
"""
Link token. ("[name](target "title")")
This is an inline token. Its children are inline (span) tokens holding the link text.
One of the core tokens.
Attributes:
target (str): link target.
title (str): link title (default to empty).
label (str): link label, for reference links.
"""
repr_attributes = ("target", "title")
def __init__(self, match):
self.target = EscapeSequence.strip(match.group(2).strip())
self.title = EscapeSequence.strip(match.group(3))
self.dest_type = getattr(match, "dest_type", None)
self.label = getattr(match, "label", None)
self.title_delimiter = getattr(match, "title_delimiter", None)
class AutoLink(SpanToken):
"""
Autolink token. ("<http://www.google.com>")
This is an inline token with a single child of type RawText.
Attributes:
children (list): a single RawText node for the link target.
target (str): link target.
mailto (bool): true iff the target looks like an email address, but does not have the "mailto:" prefix.
"""
repr_attributes = ("target", "mailto")
pattern = re.compile(r"(?<!\\)(?:\\\\)*<([A-Za-z][A-Za-z0-9+.-]{1,31}:[^ <>]*?|[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*)>")
parse_inner = False
def __init__(self, match):
content = match.group(self.parse_group)
self.children = (RawText(content),)
self.target = content
self.mailto = '@' in self.target and 'mailto' not in self.target.casefold()
class EscapeSequence(SpanToken):
"""
Escape sequence token. ("\\\\*")
This is an inline token with a single child of type RawText.
Attributes:
children (iterator): a single RawText node containing the escaped character.
"""
pattern = re.compile(r"\\([!\"#$%&'()*+,-./:;<=>?@\[\\\]^_`{|}~])")
parse_inner = False
precedence = 2
def __init__(self, match):
self.children = (RawText(match.group(self.parse_group)),)
@classmethod
def strip(cls, string):
return html.unescape(cls.pattern.sub(r'\1', string))
class LineBreak(SpanToken):
"""
Line break token: hard or soft.
This is an inline token without children.
Attributes:
soft (bool): true if this is a soft line break.
"""
repr_attributes = ("soft",)
pattern = re.compile(r'( *|\\)\n')
parse_inner = False
parse_group = 0
def __init__(self, match):
self.content = match.group(1)
self.soft = not self.content.startswith((' ', '\\'))
class RawText(SpanToken):
"""
Raw text token.
This is an inline token without children.
RawText is the only token that accepts a string for its constructor,
instead of a match object. Also, all recursions should bottom out here.
"""
def __init__(self, content):
self.content = content
_tags = {'address', 'article', 'aside', 'base', 'basefont', 'blockquote',
'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details',
'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure',
'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5',
'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link',
'main', 'menu', 'menuitem', 'meta', 'nav', 'noframes', 'ol',
'optgroup', 'option', 'p', 'param', 'section', 'source', 'summary',
'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track',
'ul'}
_tag = r'[A-Za-z][A-Za-z0-9-]*' # noqa: E221
_attrs = r'(?:\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\s*=\s*(?:[^\s"\'=<>`]+|\'[^\']*?\'|"[^\"]*?"))?)*'
_open_tag = r'(?<!\\)<' + _tag + _attrs + r'\s*/?>' # noqa: E221
_closing_tag = r'(?<!\\)</' + _tag + r'\s*>'
_comment = r'(?<!\\)<!--(?!>|->)(?:(?!--).)+?(?<!-)-->' # noqa: E221
_instruction = r'(?<!\\)<\?.+?\?>'
_declaration = r'(?<!\\)<![A-Z].+?>'
_cdata = r'(?<!\\)<!\[CDATA.+?\]\]>' # noqa: E221
class HtmlSpan(SpanToken):
"""
Span-level HTML token.
This is an inline token without children.
Attributes:
content (str): the raw HTML content.
"""
pattern = re.compile('|'.join([_open_tag, _closing_tag, _comment,
_instruction, _declaration, _cdata]),
re.DOTALL)
parse_inner = False
parse_group = 0
HTMLSpan = HtmlSpan
"""
Deprecated name of the `HtmlSpan` class.
"""
# Note: The following XWiki tokens are based on the XWiki Syntax 2.0 (or above; 1.0 was deprecated years ago already).
class XWikiBlockMacroStart(SpanToken):
"""
A "block" macro opening tag. ("{{macroName<optionalParams>}}<newLine>")
We want to keep it on a separate line instead of "soft" merging it with the *following* line.
"""
pattern = re.compile(r'(?<!\\)(\{\{\w+.*?(?<![\\/])\}\})\s*\n')
parse_inner = False
parse_group = 1
class XWikiBlockMacroEnd(SpanToken):
"""
A "block" macro closing tag. ("<onlySpacesAllowed>{{/macroName}}")
We want to keep it on a separate line instead of "soft" merging it with the *preceding* line.
"""
pattern = re.compile(r'^(?:\s*)(\{\{/\w+\}\})', re.MULTILINE)
parse_inner = False
parse_group = 1
_token_types = []
reset_tokens()