{{ message }}
Repository navigation
Expand file tree
/
Copy pathinlinepatterns.py
More file actions
1319 lines (1041 loc) · 47.9 KB
/
Copy pathinlinepatterns.py
File metadata and controls
1319 lines (1041 loc) · 47.9 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Python Markdown
# A Python implementation of John Gruber's Markdown.
# Documentation: https://python-markdown.github.io/
# GitHub: https://github.com/Python-Markdown/markdown/
# PyPI: https://pypi.org/project/Markdown/
# Started by Manfred Stienstra (http://www.dwerg.net/).
# Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
# Currently maintained by Waylan Limberg (https://github.com/waylan),
# Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
# Copyright 2007-2023 The Python Markdown Project (v. 1.7 and later)
# Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
# Copyright 2004 Manfred Stienstra (the original version)
# License: BSD (see LICENSE.md for details).
"""
In version 3.0, a new, more flexible inline processor was added, [`markdown.inlinepatterns.InlineProcessor`][]. The
original inline patterns, which inherit from [`markdown.inlinepatterns.Pattern`][] or one of its children are still
supported, though users are encouraged to migrate.
The new `InlineProcessor` provides two major enhancements to `Patterns`:
1. Inline Processors no longer need to match the entire block, so regular expressions no longer need to start with
`r'^(.*?)'` and end with `r'(.*?)%'`. This runs faster. The returned [`Match`][re.Match] object will only contain
what is explicitly matched in the pattern, and extension pattern groups now start with `m.group(1)`.
2. The `handleMatch` method now takes an additional input called `data`, which is the entire block under analysis,
not just what is matched with the specified pattern. The method now returns the element *and* the indexes relative
to `data` that the return element is replacing (usually `m.start(0)` and `m.end(0)`). If the boundaries are
returned as `None`, it is assumed that the match did not take place, and nothing will be altered in `data`.
This allows handling of more complex constructs than regular expressions can handle, e.g., matching nested
brackets, and explicit control of the span "consumed" by the processor.
"""
from __future__ import annotations
from . import util
from typing import TYPE_CHECKING, Any, Collection, NamedTuple, cast
from collections import deque
import re
import xml.etree.ElementTree as etree
from html import entities
if TYPE_CHECKING: # pragma: no cover
from markdown import Markdown
def build_inlinepatterns(md: Markdown, **kwargs: Any) -> util.Registry[InlineProcessor]:
"""
Build the default set of inline patterns for Markdown.
The order in which processors and/or patterns are applied is very important - e.g. if we first replace
`http://.../` links with `<a>` tags and _then_ try to replace inline HTML, we would end up with a mess. So, we
apply the expressions in the following order:
* backticks and escaped characters have to be handled before everything else so that we can preempt any markdown
patterns by escaping them;
* then we handle the various types of links (auto-links must be handled before inline HTML);
* then we handle inline HTML. At this point we will simply replace all inline HTML strings with a placeholder
and add the actual HTML to a stash;
* finally we apply strong, emphasis, etc.
"""
inlinePatterns = util.Registry()
inlinePatterns.register(BacktickInlineProcessor(BACKTICK_RE), 'backtick', 190)
inlinePatterns.register(EscapeInlineProcessor(ESCAPE_RE, md), 'escape', 180)
inlinePatterns.register(ReferenceInlineProcessor(REFERENCE_RE, md), 'reference', 170)
inlinePatterns.register(LinkInlineProcessor(LINK_RE, md), 'link', 160)
inlinePatterns.register(ImageInlineProcessor(IMAGE_LINK_RE, md), 'image_link', 150)
inlinePatterns.register(
ImageReferenceInlineProcessor(IMAGE_REFERENCE_RE, md), 'image_reference', 140
)
inlinePatterns.register(
ShortReferenceInlineProcessor(REFERENCE_RE, md), 'short_reference', 130
)
inlinePatterns.register(
ShortImageReferenceInlineProcessor(IMAGE_REFERENCE_RE, md), 'short_image_ref', 125
)
inlinePatterns.register(AutolinkInlineProcessor(AUTOLINK_RE, md), 'autolink', 120)
inlinePatterns.register(AutomailInlineProcessor(AUTOMAIL_RE, md), 'automail', 110)
inlinePatterns.register(SubstituteTagInlineProcessor(LINE_BREAK_RE, 'br'), 'linebreak', 100)
inlinePatterns.register(HtmlInlineProcessor(HTML_RE, md), 'html', 90)
inlinePatterns.register(HtmlInlineProcessor(ENTITY_RE, md), 'entity', 80)
inlinePatterns.register(DelimiterProcessor('*', 'strong,em', md), 'em_strong', 60)
md.delimiters.add('_', 'strong,em', smart=True)
return inlinePatterns
# The actual regular expressions for patterns
# -----------------------------------------------------------------------------
NOIMG = r'(?<!\!)'
""" Match not an image. Partial regular expression which matches if not preceded by `!`. """
BACKTICK_RE = r'(?:(?<!\\)((?:\\{2})+)(?=`+)|(?<!\\)`)'
""" Match backtick quoted string (`` `e=f()` `` or ``` ``e=f("`")`` ```). """
ESCAPE_RE = r'\\(.)'
""" Match a backslash escaped character (`\\<` or `\\*`). """
LINK_RE = NOIMG + r'\['
""" Match start of in-line link (`[text](url)` or `[text](<url>)` or `[text](url "title")`). """
IMAGE_LINK_RE = r'\!\['
""" Match start of in-line image link (`` or ``). """
REFERENCE_RE = LINK_RE
""" Match start of reference link (`[Label][3]`). """
IMAGE_REFERENCE_RE = IMAGE_LINK_RE
""" Match start of image reference (`![alt text][2]`). """
AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^<>]*)>'
""" Match an automatic link (`<http://www.example.com>`). """
AUTOMAIL_RE = r'<([^<> !]+@[^@<> ]+)>'
""" Match an automatic email link (`<me@example.com>`). """
HTML_RE = (
# Tag
r'''(<(\/?+[a-zA-Z][^\s"'<>@]*+(?:\s+[^\s"'=<>]++(?:\s*+=\s*+(?:"[^"]*+"|'[^']*+'|[^\s"'=<>]++))?+)*+\s*+/?|'''
# Comment
r'!--(?:(?!<!--|-->).)*--|'
# Processing instruction
r'[?](?:(?!<[?]|[?]>).)*[?]|'
# `CDATA`
r'!\[CDATA\[(?:(?!<!\[CDATA\[|\]\]>).)*\]\]'
')>)'
)
""" Match an HTML tag (`<...>`). """
ENTITY_RE = r'(&(?:\#[0-9]+|\#x[0-9a-fA-F]+|[a-zA-Z0-9]+);)'
""" Match an HTML entity (`&` (decimal) or `&` (hex) or `&` (named)). """
LINE_BREAK_RE = r' \n'
""" Match two spaces at end of line. """
def dequote(string: str) -> str:
"""Remove quotes from around a string."""
if ((string.startswith('"') and string.endswith('"')) or
(string.startswith("'") and string.endswith("'"))):
return string[1:-1]
else:
return string
class EmStrongItem(NamedTuple):
"""Emphasis/strong pattern item."""
pattern: re.Pattern[str]
builder: str
tags: str
# The pattern classes
# -----------------------------------------------------------------------------
class Pattern: # pragma: no cover
"""
Base class that inline patterns subclass.
Inline patterns are handled by means of `Pattern` subclasses, one per regular expression.
Each pattern object uses a single regular expression and must support the following methods:
[`getCompiledRegExp`][markdown.inlinepatterns.Pattern.getCompiledRegExp] and
[`handleMatch`][markdown.inlinepatterns.Pattern.handleMatch].
All the regular expressions used by `Pattern` subclasses must capture the whole block. For this
reason, they all start with `^(.*)` and end with `(.*)!`. When passing a regular expression on
class initialization, the `^(.*)` and `(.*)!` are added automatically and the regular expression
is pre-compiled.
It is strongly suggested that the newer style [`markdown.inlinepatterns.InlineProcessor`][] that
use a more efficient and flexible search approach be used instead. However, the older style
`Pattern` remains for backward compatibility with many existing third-party extensions.
"""
ANCESTOR_EXCLUDES: Collection[str] = tuple()
"""
A collection of elements which are undesirable ancestors. The processor will be skipped if it
would cause the content to be a descendant of one of the listed tag names.
"""
compiled_re: re.Pattern[str]
md: Markdown | None
def __init__(self, pattern: str, md: Markdown | None = None):
"""
Create an instant of an inline pattern.
Arguments:
pattern: A regular expression that matches a pattern.
md: An optional pointer to the instance of `markdown.Markdown` and is available as
`self.md` on the class instance.
"""
self.pattern = pattern
self.compiled_re = re.compile(r"^(.*?)%s(.*)$" % pattern,
re.DOTALL | re.UNICODE)
self.md = md
def getCompiledRegExp(self) -> re.Pattern:
""" Return a compiled regular expression. """
return self.compiled_re
def handleMatch(self, m: re.Match[str]) -> etree.Element | str:
"""Return a ElementTree element from the given match.
Subclasses should override this method.
Arguments:
m: A match object containing a match of the pattern.
Returns: An ElementTree Element object.
"""
pass # pragma: no cover
def type(self) -> str:
""" Return class name, to define pattern type """
return self.__class__.__name__
def unescape(self, text: str) -> str:
""" Return unescaped text given text with an inline placeholder. """
try:
stash = self.md.treeprocessors['inline'].stashed_nodes
except KeyError: # pragma: no cover
return text
def get_stash(m):
id = m.group(1)
if id in stash:
value = stash.get(id)
if isinstance(value, str):
return value
else:
# An `etree` Element - return text content only
return ''.join(value.itertext())
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
class InlineProcessor(Pattern):
"""
Base class that inline processors subclass.
This is the newer style inline processor that uses a more
efficient and flexible search approach.
"""
def __init__(self, pattern: str, md: Markdown | None = None):
"""
Create an instant of an inline processor.
Arguments:
pattern: A regular expression that matches a pattern.
md: An optional pointer to the instance of `markdown.Markdown` and is available as
`self.md` on the class instance.
"""
self.pattern = pattern
self.compiled_re = re.compile(pattern, re.DOTALL | re.UNICODE)
# API for Markdown to pass `safe_mode` into instance
self.safe_mode = False
self.md = md
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | str | None, int | None, int | None]:
"""Return a ElementTree element from the given match and the
start and end index of the matched text.
If `start` and/or `end` are returned as `None`, it will be
assumed that the processor did not find a valid region of text.
Subclasses should override this method.
Arguments:
m: A re match object containing a match of the pattern.
data: The buffer currently under analysis.
Returns:
el: The ElementTree element, text or None.
start: The start of the region that has been matched or None.
end: The end of the region that has been matched or None.
"""
pass # pragma: no cover
class SimpleTextPattern(Pattern): # pragma: no cover
""" Return a simple text of `group(2)` of a Pattern. """
def handleMatch(self, m: re.Match[str]) -> str:
""" Return string content of `group(2)` of a matching pattern. """
return m.group(2)
class SimpleTextInlineProcessor(InlineProcessor):
""" Return a simple text of `group(1)` of a Pattern. """
def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]:
""" Return string content of `group(1)` of a matching pattern. """
return m.group(1), m.start(0), m.end(0)
class EscapeInlineProcessor(InlineProcessor):
""" Return an escaped character. """
def handleMatch(self, m: re.Match[str], data: str) -> tuple[str | None, int, int]:
"""
If the character matched by `group(1)` of a pattern is in [`ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS]
then return the integer representing the character's Unicode code point (as returned by [`ord`][]) wrapped
in [`util.STX`][markdown.util.STX] and [`util.ETX`][markdown.util.ETX].
If the matched character is not in [`ESCAPED_CHARS`][markdown.Markdown.ESCAPED_CHARS], then return `None`.
"""
char = m.group(1)
if char in self.md.ESCAPED_CHARS:
return '{}{}{}'.format(util.STX, ord(char), util.ETX), m.start(0), m.end(0)
else:
return None, m.start(0), m.end(0)
class SimpleTagPattern(Pattern): # pragma: no cover
"""
Return element of type `tag` with a text attribute of `group(3)`
of a Pattern.
"""
def __init__(self, pattern: str, tag: str):
"""
Create an instant of an simple tag pattern.
Arguments:
pattern: A regular expression that matches a pattern.
tag: Tag of element.
"""
Pattern.__init__(self, pattern)
self.tag = tag
""" The tag of the rendered element. """
def handleMatch(self, m: re.Match[str]) -> etree.Element:
"""
Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(3)` of a
matching pattern as the Element's text.
"""
el = etree.Element(self.tag)
el.text = m.group(3)
return el
class SimpleTagInlineProcessor(InlineProcessor):
"""
Return element of type `tag` with a text attribute of `group(2)`
of a Pattern.
"""
def __init__(self, pattern: str, tag: str):
"""
Create an instant of an simple tag processor.
Arguments:
pattern: A regular expression that matches a pattern.
tag: Tag of element.
"""
InlineProcessor.__init__(self, pattern)
self.tag = tag
""" The tag of the rendered element. """
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: # pragma: no cover
"""
Return [`Element`][xml.etree.ElementTree.Element] of type `tag` with the string in `group(2)` of a
matching pattern as the Element's text.
"""
el = etree.Element(self.tag)
el.text = m.group(2)
return el, m.start(0), m.end(0)
class SubstituteTagPattern(SimpleTagPattern): # pragma: no cover
""" Return an element of type `tag` with no children. """
def handleMatch(self, m: re.Match[str]) -> etree.Element:
""" Return empty [`Element`][xml.etree.ElementTree.Element] of type `tag`. """
return etree.Element(self.tag)
class SubstituteTagInlineProcessor(SimpleTagInlineProcessor):
""" Return an element of type `tag` with no children. """
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]:
""" Return empty [`Element`][xml.etree.ElementTree.Element] of type `tag`. """
return etree.Element(self.tag), m.start(0), m.end(0)
class BacktickInlineProcessor(InlineProcessor):
""" Return a `<code>` element containing the escaped matching text. """
def __init__(self, pattern: str):
InlineProcessor.__init__(self, pattern)
self.ESCAPED_BSLASH = '{}{}{}'.format(util.STX, ord('\\'), util.ETX)
self.tag = 'code'
""" The tag of the rendered element. """
def find_code_spans(self, start: int, text: str) -> tuple[int, int] | None:
"""Find code spans."""
last = len(text)
# Get the maximum starting ticks
max_ticks = 0
while start < last and text[start] == '`':
max_ticks += 1
start += 1
if not max_ticks: # pragma: no cover
# This is not ever expected to happen.
return None
longest_span = 0
end = 0
# Find an ending span of backticks that matches our opening
i = start
while i < last:
span_length = 0
while i < last and text[i] == '`':
span_length += 1
i += 1
if not span_length:
i += 1
continue
# Did we find the end?
if max_ticks == span_length:
return start, i - span_length
# Track the longest span of backticks we find as a fallback.
if span_length > longest_span:
longest_span = span_length
end = i
# Since we didn't find an exact matching start and end,
# adjust start to match the largest end we could calculate.
if longest_span:
return start - (max_ticks - longest_span), end - longest_span
# We could not find a suitable pairing
return None
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | str | None, int | None, int | None]:
"""
If the match contains `group(3)` of a pattern, then return a `code`
[`Element`][xml.etree.ElementTree.Element] which contains HTML escaped text (with
[`code_escape`][markdown.util.code_escape]) as an [`AtomicString`][markdown.util.AtomicString].
If the match contains `group(1)` then return the text of `group(1)` as backslash escaped.
"""
if m.group(1):
return m.group(1).replace('\\\\', self.ESCAPED_BSLASH), m.start(0), m.end(0)
begin = m.start(0)
result = self.find_code_spans(begin, data)
if result is not None:
start, end = result
el = etree.Element(self.tag)
el.text = util.AtomicString(util.code_escape(data[start:end].strip()))
return el, begin, result[1] + (start - begin)
return None, None, None
class DoubleTagPattern(SimpleTagPattern): # pragma: no cover
"""Return a ElementTree element nested in tag2 nested in tag1.
Useful for strong emphasis etc.
"""
def handleMatch(self, m: re.Match[str]) -> etree.Element:
"""
Return [`Element`][xml.etree.ElementTree.Element] in following format:
`<tag1><tag2>group(3)</tag2>group(4)</tag2>` where `group(4)` is optional.
"""
tag1, tag2 = self.tag.split(",")
el1 = etree.Element(tag1)
el2 = etree.SubElement(el1, tag2)
el2.text = m.group(3)
if len(m.groups()) == 5:
el2.tail = m.group(4)
return el1
class DoubleTagInlineProcessor(SimpleTagInlineProcessor):
"""Return a ElementTree element nested in tag2 nested in tag1.
Useful for strong emphasis etc.
"""
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element, int, int]: # pragma: no cover
"""
Return [`Element`][xml.etree.ElementTree.Element] in following format:
`<tag1><tag2>group(2)</tag2>group(3)</tag2>` where `group(3)` is optional.
"""
tag1, tag2 = self.tag.split(",")
el1 = etree.Element(tag1)
el2 = etree.SubElement(el1, tag2)
el2.text = m.group(2)
if len(m.groups()) == 3:
el2.tail = m.group(3)
return el1, m.start(0), m.end(0)
class HtmlInlineProcessor(InlineProcessor):
""" Store raw inline html and return a placeholder. """
def handleMatch(self, m: re.Match[str], data: str) -> tuple[str, int, int]:
""" Store the text of `group(1)` of a pattern and return a placeholder string. """
rawhtml = self.backslash_unescape(self.unescape(m.group(1)))
place_holder = self.md.htmlStash.store(rawhtml)
return place_holder, m.start(0), m.end(0)
def unescape(self, text: str) -> str:
""" Return unescaped text given text with an inline placeholder. """
try:
stash = self.md.treeprocessors['inline'].stashed_nodes
except KeyError: # pragma: no cover
return text
def get_stash(m: re.Match[str]) -> str:
id = m.group(1)
value = stash.get(id)
if value is not None:
if isinstance(value, etree.Element):
# Ensure we don't have a placeholder inside a placeholder
return self.unescape(self.md.serializer(value))
else:
return r'\%s' % value
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
def backslash_unescape(self, text: str) -> str:
""" Return text with backslash escapes undone (backslashes are restored). """
try:
RE = self.md.treeprocessors['unescape'].RE
except KeyError: # pragma: no cover
return text
def _unescape(m: re.Match[str]) -> str:
return chr(int(m.group(1)))
return RE.sub(_unescape, text)
class Delimiter:
"""Delimiter."""
def __init__(self, token: str, tags: str, smart: bool, double: bool):
"""Initialize."""
self.stack: deque[tuple[int, int, bool, int]] = deque()
temp = tags.split(',')
self.tag_count = len(temp)
self.tags: tuple[str, str] = (temp[0], temp[1]) if self.tag_count == 2 else (temp[0], temp[0])
self.double = len(temp) != 2 and double
self.single = len(temp) != 2 and not double
self.smart = smart
self._build_patterns(token)
def _build_patterns(self, token: str) -> str:
"""Build regular expression patterns."""
# Build up patterns
self.token = token
etoken = re.escape(token)
# Avoid at start and end
xstart = fr'(?:(?<=_)|(?<![\w{etoken}]))' if token != '_' else fr'(?<![\w{etoken}])'
xend = fr'(?:(?=_)|(?![\w{etoken}]))' if token != '_' else fr'(?![\w{etoken}])'
self.max_size = 2
if self.tag_count != 2 and not self.double:
self.max_size = 1
# Patterns for "smart" cases.
if self.smart:
self.boundary = re.compile(
fr'''(?x)
(?P<ambiguous>(?<!^)(?<![\s{etoken}]){xstart}{etoken}{{1,}}{xend}(?![\s{etoken}])(?!$))|
(?P<end>(?<!^)(?<![\s{etoken}]){etoken}{{1,}}{xend})|
(?P<start>{xstart}{etoken}{{1,}}(?![\s{etoken}])(?!$))
''',
flags=re.UNICODE
)
# Patterns for "dumb" cases.
else:
self.boundary = re.compile(
fr'''(?x)
(?P<ambiguous>(?<!^)(?<![\s{etoken}]){etoken}{{1,}}(?![\s{etoken}])(?!$))|
(?P<end>(?<!^)(?<![\s{etoken}]){etoken}{{1,}})|
(?P<start>{etoken}{{1,}}(?![\s{etoken}])(?!$))
''',
flags=re.UNICODE
)
self.bad = re.compile(fr'{etoken}+')
return fr'{etoken}'
def reset(self) -> None:
"""Reset."""
# Cache info
self.stack.clear()
class DelimiterProcessor(InlineProcessor):
"""Processor for handling complex nested patterns such as strong and em matches."""
SPACE = re.compile(r'\s')
def __init__(
self,
token: str,
tags: str,
md: Markdown,
smart: bool = False,
double: bool = False
) -> None:
"""Initialize."""
md.delimiters = self
self.regions: list[tuple[int, int, int, int, tuple[str, str], int]] = []
self.stack: list[tuple[int, int, bool, int]] = []
self.tokens: list[str] = []
self.delimiters: dict[str, Delimiter] = {}
self.cache_index = 0
self.cache_pos = 0
self.md = md
# API for Markdown to pass `safe_mode` into instance
self.safe_mode = False
self.add(token, tags, smart, double)
def add(
self,
token: str,
tags: str,
smart: bool = False,
double: bool = False
) -> None:
"""Add a delimiter."""
if token not in self.tokens:
self.tokens.append(token)
self.delimiters[token] = Delimiter(token, tags, smart, double)
self.pattern = '|'.join([re.escape(t) for t in self.tokens])
self.compiled_re = re.compile(self.pattern, re.DOTALL | re.UNICODE)
def remove(self, token: str) -> None:
"""Remove a token."""
try:
i = self.tokens.index(token)
del self.tokens[i]
del self.delimiters[token]
except Exception:
pass
self.pattern = '|'.join([re.escape(t) for t in self.tokens])
self.compiled_re = re.compile(self.pattern, re.DOTALL | re.UNICODE) if self.pattern else re.compile(r'(?!)')
def reset(self) -> None:
"""Reset."""
# Cache info
for v in self.delimiters.values():
v.reset()
self.regions.clear()
self.stack.clear()
self.cache_index = 0
self.cache_pos = 0
def _build_element(
self,
data: str,
start: int = 0,
offset: int = 0
) -> tuple[etree.Element, int]:
"""Element builder."""
regions = self.regions
el: etree.Element | None = None
last: Any = None
previous: Any = None
outer: list[etree.Element] = []
outer_r: list[tuple[int, int, int, int, tuple[str, str], int]] = []
# Iterate regions creating the elements they represent
end = len(regions)
idx = 0
for idx, i in enumerate(range(start, end), 1):
r = regions[i]
# Not contained within region
if idx and r[0] >= regions[start][3]:
idx -= 1
break
# Get the appropriate element(s)
if r[-1] == 2:
el1 = etree.Element(r[4][0])
else:
el1 = etree.Element(r[4][1])
# Populate the elements with their text
if idx > 1:
if last.text is None:
if previous[2] < r[0]:
last.text = data[previous[1]+offset:previous[2]+offset]
else:
last.text = data[previous[1]+offset:r[0]+offset]
if last is not outer[-1] and last.tail is None:
if r[0] < outer_r[-1][3]:
last.tail = data[previous[3]+offset:r[0]+offset]
else:
last.tail = data[previous[3]+offset:outer_r[-1][2]+offset]
outer[-1].tail = data[outer_r[-1][3]+offset:r[0]+offset]
# First element
if el is None:
el = el1
last = el
outer.append(el)
outer_r.append(r)
# Subsequent elements
else:
# Is the current outer element no longer wrapping this one?
while len(outer_r) > 1 and r[3] > outer_r[-1][3]:
outer.pop()
outer_r.pop()
# Non-nested
else:
outer[-1].append(el1)
# Is this element wrapping the next?
if i + 1 < end:
if r[3] > regions[i + 1][3]:
outer.append(el1)
outer_r.append(r)
# Track the last element we parsed.
last = el1
# Track the previous region.
previous = r
# Populate remaining elements with their text
while outer:
if last.text is None:
last.text = data[previous[1]+offset:previous[2]+offset]
if last.tail is None and last is not outer[-1]:
last.tail = data[previous[3]+offset:outer_r[-1][2]+offset]
last = outer.pop()
previous = outer_r.pop()
return cast('etree.Element', el), idx
def increment_next_position(self, start: int, count: int) -> None:
"""
Increment cache position to the next location that we can initiate an insertion.
Cache position should be the first match after our current replacement.
This gives us an anchor to calculate the new offset after insertion.
"""
# Determine next offset
self.cache_index += count
if self.cache_index < len(self.regions):
self.cache_pos = self.regions[self.cache_index][0]
while self.stack:
entry = self.stack.pop(0)
if start < entry[0] <= self.cache_pos:
self.cache_pos = entry[0]
break
# Nothing left to process
else:
self.reset()
def get_cached_result(self, pos: int, data: str) -> tuple[etree.Element, int, int]:
"""Get a cached result."""
# Process the next region(s) in the cache
regions = self.regions
offset = pos - self.cache_pos if pos != self.cache_pos else pos - regions[self.cache_index][0]
start, end = regions[self.cache_index][0], regions[self.cache_index][3]
el, count = self._build_element(data, self.cache_index, offset)
self.increment_next_position(start, count)
return el, start + offset, end + offset
def get_match(self, data: str, start: int) -> re.Match[str] | None:
"""Get match."""
for d in self.delimiters.values():
m = d.boundary.match(data, start)
if m is not None:
return m
return None
def search(self, data: str, start: int) -> re.Match[str] | None:
"""Search."""
for i in range(start, len(data)):
if data[i] in self.delimiters:
d = self.delimiters[data[i]]
m = d.boundary.match(data, i)
if m is not None:
if not d.stack and m.lastgroup[0] == 'e': # type: ignore[index]
continue
return m
return None
def add_region(self, delim: Delimiter, a: int, b: int, c: int, d: int, size: int) -> None:
"""Add region."""
self.regions.append((a, b, c, d, delim.tags, size))
for delim in self.delimiters.values():
while delim.stack:
p = delim.stack[-1][0]
if max(p, a) <= min(p, d - 1):
delim.stack.pop()
continue
break
def handleMatch( # type: ignore[override]
self,
m: re.Match[str],
data: str
) -> tuple[etree.Element | None, int | None, int | None]:
"""Parse delimiter pattern."""
# Do we have entries we haven't returned yet?
if self.regions:
return self.get_cached_result(m.start(0), data)
# If token is not an opening, quit
m2 = self.get_match(data, m.start(0))
if m2 is None or m2.lastgroup[0] == 'e': # type: ignore[index]
if m2 is None:
delim = self.delimiters[m.group(0)]
m2 = delim.bad.match(data, m.start(0))
# Advance past the full length of the delimiter found
return None, m2.start(0), m2.end(0)
# Get the stack and regions
token = data[m.start(0)]
delim = self.delimiters[token]
stack = delim.stack
start = m2.start(0)
end = m2.end(0)
length = end - start
# Double needs at least a size of 2
if delim.double and length < 2:
return None, m.start(0), m.end(0)
is_ambiguous = m2.lastgroup[0] != 's' # type: ignore[index]
stack.append((start, start + length, is_ambiguous, length))
# Pair tokens until the stack is empty or we can no longer find tokens.
while any(d.stack for d in self.delimiters.values()):
m2 = self.search(data, end)
if m2 is None:
break
token = data[m2.start(0)]
delim = self.delimiters[token]
stack = delim.stack
start = m2.start(0)
end = m2.end(0)
# Get current and last delimiter size
current = len(m2.group(0))
# Some delimiters may be ambiguous and look like both a start or an end
is_start = m2.lastgroup[0] != 'e' # type: ignore[index]
is_end = not is_start or m2.lastgroup[0] != 's' # type: ignore[index]
is_ambiguous = is_start and is_end
last = stack[-1][-1] if stack else 0
# Find closing tokens
# Looking for:
# - `*em*`
# - `**strong**`
# - `***strong,em***`
# - `*em**`
# - `*em***`
# - `**strong***`
#
# Avoid ambiguous tokens that could be a start or an end.
# Consume starts until the end token is fully consumed.
# If we don't consume the entire end, see if next rule consumes it.
if stack and is_end and ((not is_ambiguous and current > last) or current == last or current >= 3):
is_start = False
# Consume previous points until the delimiter is consumed
original = current
while stack and current and last <= current:
delimiter = stack.pop()
# Build up region for pair and adjust accounting.
size = min(delimiter[-1], 1 if delim.tag_count == 2 and delimiter[-1] == 3 else delim.max_size)
self.add_region(delim, delimiter[1] - size, delimiter[1], start, start + size, size)
start += size
current -= size
new = 0
if size < delimiter[-1] and (not delim.double or (delimiter[-1] - size) != 1):
new = delimiter[-1] - size
stack.append((delimiter[0], delimiter[1] - size, delimiter[2], new))
if not stack:
if any(d.stack for d in self.delimiters.values() if d is not delim):
delim.reset()
continue
is_end = False
break
last = stack[-1][-1]
# Should remainder be treated as a new start?
if original >= 3 and current and is_ambiguous:
delim.stack.append((m2.start(0) + (original - current), end, False, current))
is_end = False
# Do we still have more to consume?
else:
is_end = current and stack and last > current
# Looking for:
# - `***em*`
# - `***strong**`
# - `**em*`
if stack and is_end and (last >= 3 or not is_ambiguous) and last > current:
delimiter = stack.pop()
# Don't pair with an ambiguous opening
while stack and delimiter[-1] != 3 and delimiter[2]:
delimiter = stack.pop()
last = delimiter[-1]
if delimiter[2] and delimiter[-1] != 3:
if any(d.stack for d in self.delimiters.values() if d is not delim):
delim.reset()
continue
break
# Create new regions
is_start = False
ds, de = delimiter[:2]
while current and (not delim.double or current != 1):
size = min(current, 1 if delim.tag_count == 2 and current == 3 else delim.max_size)
new = last - size
self.add_region(delim, ds + new, de, start, start + size, size)
start += size
current -= size
last -= size
de -= size
if last and (not delim.double or last > 1):
stack.append((ds, de, False, last))
# Find opening tokens
# Looking for:
# - `*em ...*`
# - `**strong ...*`
# - `***em ...*`
if is_start and (not delim.double or current != 1):
stack.append((start, end, is_ambiguous, current))
# Combine the stacks and order them
for delim in self.delimiters.values():
self.stack.extend(delim.stack)
self.stack.sort(key=lambda x: x[0])
# Build the HTML elements
if self.regions:
# Regions may be out of order.
self.regions.sort(key=lambda x: x[0])
You can’t perform that action at this time.
