-
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathblock_parser.py
More file actions
615 lines (501 loc) · 20 KB
/
Copy pathblock_parser.py
File metadata and controls
615 lines (501 loc) · 20 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
import re
import string
from bisect import bisect_left
from typing import List, Match, Optional, Pattern, Set, Tuple
from .core import BlockState, Parser
from .helpers import (
BLOCK_TAGS,
HTML_ATTRIBUTES,
HTML_TAGNAME,
LINK_LABEL,
PRE_TAGS,
parse_link_href,
parse_link_title,
unescape_char,
)
from .list_parser import LIST_PATTERN, parse_list
from .util import escape_url, expand_leading_tab, expand_tab, unikey
DEFAULT_MAX_NESTED_LEVEL = 20
_INDENT_CODE_TRIM = re.compile(r"^ {1,4}", flags=re.M)
_ATX_HEADING_TRIM = re.compile(r"(\s+|^)#+\s*$")
_BLOCK_QUOTE_TRIM = re.compile(r"^ ?", flags=re.M)
_BLANK_TO_LINE = re.compile(r"[ \t]*\n")
_BLOCK_TAGS_PATTERN = "(" + "|".join(BLOCK_TAGS) + "|" + "|".join(PRE_TAGS) + ")"
_OPEN_TAG_END = re.compile(HTML_ATTRIBUTES + r"[ \t]*>[ \t]*(?:\n|$)")
_CLOSE_TAG_END = re.compile(r"[ \t]*>[ \t]*(?:\n|$)")
_BLOCK_QUOTE_LINE = re.compile(r"^ {0,3}>([^\n]*(?:\n|$))")
class BlockParser(Parser[BlockState]):
state_cls = BlockState
BLANK_LINE = re.compile(r"(^[ \t\v\f]*\n)+", re.M)
RAW_HTML = (
r"^ {0,3}("
r"</?" + HTML_TAGNAME + r"|"
r"<!--|" # comment
r"<\?|" # script
r"<![A-Z]|"
r"<!\[CDATA\[)"
)
BLOCK_HTML = (
r"^ {0,3}(?:"
r"(?:</?" + _BLOCK_TAGS_PATTERN + r"(?:[ \t]+|\n|$))"
r"|<!--" # comment
r"|<\?" # script
r"|<![A-Z]"
r"|<!\[CDATA\[)"
)
SPECIFICATION = {
"blank_line": r"(^[ \t\v\f]*\n)+",
"atx_heading": r"^ {0,3}(?P<atx_1>#{1,6})(?!#+)(?P<atx_2>[ \t]*|[ \t]+.*?)$",
"setex_heading": r"^ {0,3}(?P<setext_1>=|-){1,}[ \t]*$",
"fenced_code": (
r"^(?P<fenced_1> {0,3})(?P<fenced_2>`{3,}|~{3,})"
r"[ \t]*(?P<fenced_3>.*?)$"
),
"indent_code": (
r"^(?: {4}| *\t)[^\n]+(?:\n+|$)"
r"((?:(?: {4}| *\t)[^\n]+(?:\n+|$))|\s)*"
),
"thematic_break": r"^ {0,3}((?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$",
"ref_link": r"^ {0,3}\[(?P<reflink_1>" + LINK_LABEL + r")\]:",
"block_quote": r"^ {0,3}>(?P<quote_1>.*?)$",
"list": LIST_PATTERN,
"block_html": BLOCK_HTML,
"raw_html": RAW_HTML,
}
DEFAULT_RULES = (
"fenced_code",
"indent_code",
"atx_heading",
"setex_heading",
"thematic_break",
"block_quote",
"list",
"ref_link",
"raw_html",
"blank_line",
)
def __init__(
self,
block_quote_rules: Optional[List[str]] = None,
list_rules: Optional[List[str]] = None,
max_nested_level: int = DEFAULT_MAX_NESTED_LEVEL,
):
super(BlockParser, self).__init__()
if block_quote_rules is None:
block_quote_rules = list(self.DEFAULT_RULES)
if list_rules is None:
list_rules = list(self.DEFAULT_RULES)
self.block_quote_rules = block_quote_rules
self.list_rules = list_rules
self.max_nested_level = max_nested_level
# register default parse methods
self._methods = {name: getattr(self, "parse_" + name) for name in self.SPECIFICATION}
def parse_blank_line(self, m: Match[str], state: BlockState) -> int:
"""Parse token for blank lines."""
if state.cursor == 0:
state.append_token({"type": "blank_line", "newlines": m.group(0).count("\n")})
else:
state.append_token({"type": "blank_line"})
return m.end()
def parse_thematic_break(self, m: Match[str], state: BlockState) -> int:
"""Parse token for thematic break, e.g. ``<hr>`` tag in HTML."""
state.append_token({"type": "thematic_break"})
# $ does not count '\n'
return m.end() + 1
def parse_indent_code(self, m: Match[str], state: BlockState) -> int:
"""Parse token for code block which is indented by 4 spaces."""
# it is a part of the paragraph
end_pos = state.append_paragraph()
if end_pos:
return end_pos
code = m.group(0)
end_pos = _trim_partial_next_line_indent(code, m.end())
if end_pos != m.end():
code = state.get_text(end_pos)
code = expand_leading_tab(code)
code = _INDENT_CODE_TRIM.sub("", code)
code = code.strip("\n")
state.append_token({"type": "block_code", "raw": code, "style": "indent"})
return end_pos
def parse_fenced_code(self, m: Match[str], state: BlockState) -> Optional[int]:
"""Parse token for fenced code block. A fenced code block is started with
3 or more backtick(`) or tilde(~).
An example of a fenced code block:
.. code-block:: markdown
```python
def markdown(text):
return mistune.html(text)
```
"""
spaces = m.group("fenced_1")
marker = m.group("fenced_2")
info = m.group("fenced_3")
c = marker[0]
if info and c == "`":
# CommonMark Example 145
# Info strings for backtick code blocks cannot contain backticks
if info.find(c) != -1:
return None
_end = re.compile(r"^ {0,3}" + c + "{" + str(len(marker)) + r",}[ \t]*(?:\n|$)", re.M)
cursor_start = m.end() + 1
m2 = _end.search(state.src, cursor_start)
if m2:
code = state.src[cursor_start : m2.start()]
end_pos = m2.end()
else:
code = state.src[cursor_start:]
end_pos = state.cursor_max
if spaces and code:
_trim_pattern = re.compile("^ {0," + str(len(spaces)) + "}", re.M)
code = _trim_pattern.sub("", code)
token = {"type": "block_code", "raw": code, "style": "fenced", "marker": marker}
if info:
info = unescape_char(info)
token["attrs"] = {"info": info.strip()}
state.append_token(token)
return end_pos
def parse_atx_heading(self, m: Match[str], state: BlockState) -> int:
"""Parse token for ATX heading. An ATX heading is started with 1 to 6
symbol of ``#``."""
level = len(m.group("atx_1"))
text = m.group("atx_2").strip(string.whitespace)
# remove last #
if text:
text = _ATX_HEADING_TRIM.sub("", text)
token = {"type": "heading", "text": text, "attrs": {"level": level}, "style": "atx"}
state.append_token(token)
return m.end() + 1
def parse_setex_heading(self, m: Match[str], state: BlockState) -> Optional[int]:
"""Parse token for setex style heading. A setex heading syntax looks like:
.. code-block:: markdown
H1 title
========
"""
if state.cursor in state.lazy_line_starts:
return None
last_token = state.last_token()
if last_token and last_token["type"] == "paragraph":
level = 1 if m.group("setext_1") == "=" else 2
last_token["type"] = "heading"
last_token["style"] = "setext"
last_token["attrs"] = {"level": level}
return m.end() + 1
sc = self.compile_sc(["thematic_break", "list"])
m2 = sc.match(state.src, state.cursor)
if m2:
return self.parse_method(m2, state)
return None
def parse_ref_link(self, m: Match[str], state: BlockState) -> Optional[int]:
"""Parse link references and save the link information into ``state.env``.
Here is an example of a link reference:
.. code-block:: markdown
a [link][example]
[example]: https://example.com "Optional title"
This method will save the link reference into ``state.env`` as::
state.env['ref_links']['example'] = {
'url': 'https://example.com',
'title': "Optional title",
}
"""
end_pos = state.append_paragraph()
if end_pos:
return end_pos
label = m.group("reflink_1")
key = unikey(label)
if not key:
return None
href, href_pos = parse_link_href(state.src, m.end(), block=True)
if href is None:
return None
assert href_pos is not None
blank_pos = _find_next_blank_line(state, href_pos, self.BLANK_LINE)
if blank_pos is None:
max_pos = state.cursor_max
else:
max_pos = blank_pos
title, title_pos = parse_link_title(state.src, href_pos, max_pos)
if title_pos:
m2 = _BLANK_TO_LINE.match(state.src, title_pos)
if m2:
title_pos = m2.end()
else:
title_pos = None
title = None
if title_pos is None:
m3 = _BLANK_TO_LINE.match(state.src, href_pos)
if m3:
href_pos = m3.end()
else:
href_pos = None
href = None
end_pos = title_pos or href_pos
if not end_pos:
return None
if key not in state.env["ref_links"]:
assert href is not None
href = unescape_char(href)
data = {"url": escape_url(href), "label": label}
if title:
data["title"] = title
state.env["ref_links"][key] = data
return end_pos
def extract_block_quote(self, m: Match[str], state: BlockState) -> Tuple[str, Optional[int], Set[int]]:
"""Extract text and cursor end position of a block quote."""
text = _parse_block_quote_line(state.get_line(state.cursor))
assert text is not None
lazy_line_starts: Set[int] = set()
sc = self.compile_sc(["blank_line", "indent_code", "fenced_code"])
require_marker = bool(sc.match(text))
state.cursor += len(state.get_line(state.cursor))
end_pos: Optional[int] = None
if require_marker:
while state.cursor < state.cursor_max:
quote = _parse_block_quote_line(state.get_line(state.cursor))
if quote is None:
break
text += quote
state.cursor += len(state.get_line(state.cursor))
else:
prev_blank_line = False
break_sc = self.compile_sc(
[
"blank_line",
"thematic_break",
"fenced_code",
"list",
"block_html",
]
)
while state.cursor < state.cursor_max:
quote = _parse_block_quote_line(state.get_line(state.cursor))
if quote is not None:
text += quote
state.cursor += len(state.get_line(state.cursor))
if not quote.strip():
prev_blank_line = True
else:
prev_blank_line = False
continue
if prev_blank_line:
# CommonMark Example 249
# because of laziness, a blank line is needed between
# a block quote and a following paragraph
break
m4 = break_sc.match(state.src, state.cursor)
if m4:
end_pos = self.parse_method(m4, state)
if end_pos:
break
# lazy continuation line
line = state.get_line(state.cursor)
lazy_line_starts.add(len(text))
text += expand_leading_tab(line, 3)
state.cursor += len(line)
# according to CommonMark Example 6, the second tab should be
# treated as 4 spaces
return expand_tab(text), end_pos, lazy_line_starts
def parse_block_quote(self, m: Match[str], state: BlockState) -> int:
"""Parse token for block quote. Here is an example of the syntax:
.. code-block:: markdown
> a block quote starts
> with right arrows
"""
text, end_pos, lazy_line_starts = self.extract_block_quote(m, state)
# scan children state
child = state.child_state(text, lazy_line_starts=lazy_line_starts)
if state.depth() >= self.max_nested_level - 1:
# At the nesting limit, stop descending into any further container
# blocks. Trimming only "block_quote" still allowed block quotes and
# lists to recurse into each other without bound (RecursionError).
rules = [rule for rule in self.block_quote_rules if rule not in ("block_quote", "list")]
else:
rules = self.block_quote_rules
self.parse(child, rules)
token = {"type": "block_quote", "children": child.tokens}
if end_pos:
state.prepend_token(token)
return end_pos
state.append_token(token)
return state.cursor
def parse_list(self, m: Match[str], state: BlockState) -> int:
"""Parse tokens for ordered and unordered list."""
return parse_list(self, m, state)
def parse_block_html(self, m: Match[str], state: BlockState) -> Optional[int]:
return self.parse_raw_html(m, state)
def parse_raw_html(self, m: Match[str], state: BlockState) -> Optional[int]:
marker = m.group(0).strip()
# rule 2
if marker == "<!--":
return _parse_html_to_end(state, "-->", m.end())
# rule 3
if marker == "<?":
return _parse_html_to_end(state, "?>", m.end())
# rule 5
if marker == "<![CDATA[":
return _parse_html_to_end(state, "]]>", m.end())
# rule 4
if marker.startswith("<!"):
return _parse_html_to_end(state, ">", m.end())
close_tag = None
open_tag = None
if marker.startswith("</"):
close_tag = marker[2:].lower()
# rule 6
if close_tag in BLOCK_TAGS:
return _parse_html_to_newline(state, self.BLANK_LINE)
else:
open_tag = marker[1:].lower()
# rule 1
if open_tag in PRE_TAGS:
end_tag = "</" + open_tag + ">"
return _parse_html_to_end(state, end_tag, m.end())
# rule 6
if open_tag in BLOCK_TAGS:
return _parse_html_to_newline(state, self.BLANK_LINE)
# Blocks of type 7 may not interrupt a paragraph.
end_pos = state.append_paragraph()
if end_pos:
return end_pos
# rule 7
start_pos = m.end()
end_pos = state.find_line_end()
if (open_tag and _OPEN_TAG_END.match(state.src, start_pos, end_pos)) or (
close_tag and _CLOSE_TAG_END.match(state.src, start_pos, end_pos)
):
return _parse_html_to_newline(state, self.BLANK_LINE)
return None
def parse(self, state: BlockState, rules: Optional[List[str]] = None) -> None:
if rules is None:
rules = self.rules
sc = self.compile_sc(rules)
while state.cursor < state.cursor_max:
if "indent_code" in rules:
end_pos = self._parse_indent_code_fast(state)
if end_pos is not None:
state.cursor = end_pos
continue
m = sc.match(state.src, state.cursor)
if not m and self._parse_plain_paragraph(state, sc):
continue
if not m:
m = sc.search(state.src, state.cursor)
if not m:
break
end_pos = m.start()
if end_pos > state.cursor:
text = state.get_text(end_pos)
state.add_paragraph(text)
state.cursor = end_pos
end_pos2 = self.parse_method(m, state)
if end_pos2:
state.cursor = end_pos2
else:
end_pos3 = state.find_line_end()
text = state.get_text(end_pos3)
state.add_paragraph(text)
state.cursor = end_pos3
if state.cursor < state.cursor_max:
text = state.src[state.cursor :]
state.add_paragraph(text)
state.cursor = state.cursor_max
def _parse_indent_code_fast(self, state: BlockState) -> Optional[int]:
line_end = state.find_line_end()
line = state.get_text(line_end)
if not _is_indent_code_line(line):
return None
if state.last_token() and state.last_token()["type"] == "paragraph":
return state.append_paragraph()
end_pos = _find_indent_code_end(state.src, line_end, state.cursor_max)
code = state.get_text(end_pos)
code = expand_leading_tab(code)
code = _INDENT_CODE_TRIM.sub("", code)
code = code.strip("\n")
state.append_token({"type": "block_code", "raw": code, "style": "indent"})
return end_pos
def _parse_plain_paragraph(self, state: BlockState, sc: Pattern[str]) -> bool:
if not _is_plain_paragraph_start(state.src, state.cursor):
return False
pos = state.cursor
while pos < state.cursor_max:
if pos > state.cursor and sc.match(state.src, pos):
break
line = state.get_line(pos)
if not line.strip():
break
pos += len(line)
if pos <= state.cursor:
return False
state.add_paragraph(state.get_text(pos))
state.cursor = pos
return True
def _parse_html_to_end(state: BlockState, end_marker: str, start_pos: int) -> int:
marker_pos = state.src.find(end_marker, start_pos)
if marker_pos == -1:
text = state.src[state.cursor :]
end_pos = state.cursor_max
else:
text = state.get_text(marker_pos)
state.cursor = marker_pos
end_pos = state.find_line_end()
text += state.get_text(end_pos)
state.append_token({"type": "block_html", "raw": text})
return end_pos
def _parse_html_to_newline(state: BlockState, newline: Pattern[str]) -> int:
m = newline.search(state.src, state.cursor)
if m:
end_pos = m.start()
text = state.get_text(end_pos)
else:
text = state.src[state.cursor :]
end_pos = state.cursor_max
state.append_token({"type": "block_html", "raw": text})
return end_pos
def _parse_block_quote_line(line: str) -> Optional[str]:
m = _BLOCK_QUOTE_LINE.match(line)
if not m:
return None
text = expand_leading_tab(m.group(1), 3)
return _BLOCK_QUOTE_TRIM.sub("", text)
def _find_next_blank_line(state: BlockState, pos: int, pattern: Pattern[str]) -> Optional[int]:
cache = state.env.get("__blank_line_starts__")
if cache is None or cache[0] is not state.src:
cache = (state.src, [m.start() for m in pattern.finditer(state.src)])
state.env["__blank_line_starts__"] = cache
positions = cache[1]
index = bisect_left(positions, pos)
if index < len(positions):
return positions[index]
return None
def _trim_partial_next_line_indent(text: str, end_pos: int) -> int:
line_start = text.rfind("\n") + 1
if line_start == 0:
return end_pos
suffix = text[line_start:]
if suffix and suffix.strip(" \t") == "" and len(suffix.expandtabs(4)) < 4:
return end_pos - len(suffix)
return end_pos
def _is_indent_code_line(line: str) -> bool:
if line.endswith("\n"):
line = line[:-1]
if len(line) > 4 and line.startswith(" "):
return True
index = 0
while index < len(line) and line[index] == " ":
index += 1
return index + 1 < len(line) and line[index] == "\t"
def _find_indent_code_end(src: str, start: int, end: int) -> int:
pos = start
while pos < end:
newline = src.find("\n", pos, end)
line_end = end if newline < 0 else newline + 1
line = src[pos:line_end]
if _is_indent_code_line(line) or not line.strip():
pos = line_end
continue
break
return pos
def _is_plain_paragraph_start(src: str, pos: int) -> bool:
if pos >= len(src):
return False
c = src[pos]
return not c.isspace() and not c.isdigit() and c not in string.punctuation