Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ See the [Contributing Guide](contributing.md) for details.

### Fixed

* Fix cases in new emphasis handling that did not handle long chains of tokens
like they should (#1690).
* Fix quadratic-time parsing of many consecutive reference definitions, and of
many consecutive footnote definitions in the `footnotes` extension.
* Support automatic links with URL schemes other than HTTP and FTP, such as
Expand Down
48 changes: 40 additions & 8 deletions markdown/inlinepatterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,14 @@ class Delimiter:
def __init__(self, token: str, tags: str, smart: bool, double: bool):
"""Initialize."""

self.stack: deque[tuple[int, int, bool, int]] = deque()
# An unclosed delimiter.
#
# 0. Start position of the (remaining) run in the text.
# 1. End position of the (remaining) run in the text.
# 2. Whether the run is ambiguous (could be a start or an end).
# 3. Original length of the run.
# 4. Current length of the run.
self.stack: deque[tuple[int, int, bool, int, 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])
Expand Down Expand Up @@ -636,7 +643,8 @@ def __init__(

md.delimiters = self
self.regions: list[tuple[int, int, int, int, tuple[str, str], int]] = []
self.stack: list[tuple[int, int, bool, int]] = []
# Unpaired delimiter. The entries are the same as `Delimiter.stack`.
self.stack: list[tuple[int, int, bool, int, int]] = []
self.tokens: list[str] = []
self.delimiters: dict[str, Delimiter] = {}
self.cache_index = 0
Expand Down Expand Up @@ -804,6 +812,16 @@ def get_cached_result(self, pos: int, data: str) -> tuple[etree.Element, int, in
self.increment_next_position(start, count)
return el, start + offset, end + offset

@staticmethod
def rule_of_3(opener: int, closer: int) -> bool:
"""
Check the "rule of 3" which prevents an open delimiter from pairing with an ambiguous one.

The original lengths of the delimiter must be used, not what is left of them after partial pairing.
"""

return (opener + closer) % 3 == 0 and (opener % 3 != 0 or closer % 3 != 0)

def get_match(self, data: str, start: int) -> re.Match[str] | None:
"""Get match."""

Expand Down Expand Up @@ -872,7 +890,7 @@ def handleMatch( # type: ignore[override]
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))
stack.append((start, start + length, is_ambiguous, length, 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()):
Expand All @@ -897,6 +915,17 @@ def handleMatch( # type: ignore[override]

last = stack[-1][-1] if stack else 0

# Rule of 3: an ambiguous delimiter cannot pair with an open delimiter if the sum of the
# original lengths is a multiple of 3 (unless both are multiples of 3).
if (
stack and is_ambiguous and current != last and
self.rule_of_3(stack[-1][3], current)
):
for i in range(len(stack) - 2, -1, -1):
if stack[i][-1] == current and not self.rule_of_3(stack[i][3], current):
last = current
break

# Find closing tokens
# Looking for:
# - `*em*`
Expand All @@ -909,7 +938,10 @@ def handleMatch( # type: ignore[override]
# 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):
if stack and is_end and (
(current > last and (not is_ambiguous or not self.rule_of_3(stack[-1][3], current))) or
current == last or current >= 3
):
is_start = False

# Consume previous points until the delimiter is consumed
Expand All @@ -925,7 +957,7 @@ def handleMatch( # type: ignore[override]
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))
stack.append((delimiter[0], delimiter[1] - size, delimiter[2], delimiter[3], new))

if not stack:
if any(d.stack for d in self.delimiters.values() if d is not delim):
Expand All @@ -938,7 +970,7 @@ def handleMatch( # type: ignore[override]

# 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))
delim.stack.append((m2.start(0) + (original - current), end, False, original, current))
is_end = False

# Do we still have more to consume?
Expand Down Expand Up @@ -975,15 +1007,15 @@ def handleMatch( # type: ignore[override]
last -= size
de -= size
if last and (not delim.double or last > 1):
stack.append((ds, de, False, last))
stack.append((ds, de, False, delimiter[3], 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))
stack.append((start, end, is_ambiguous, current, current))

# Combine the stacks and order them
for delim in self.delimiters.values():
Expand Down
86 changes: 83 additions & 3 deletions tests/test_syntax/inline/test_emphasis.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,11 +387,11 @@ def test_advanced_nesting(self):
<p><em>a<strong>b</strong>c<strong>d</strong>e**f</em></p>
<p><em><strong>a</strong>b</em>cd<strong>e<em>f</em></strong></p>
<p><em><strong>a</strong>b</em>cd<em>e<strong>f</strong></em></p>
<p><em><strong>a</strong>b</em>cd<em>e<strong>f<em>g</em>h</strong></em></p>
<p><em><strong>a</strong>b</em>cd<em>e<strong>f</strong></em>h***</p>
<p><strong><em>a</em></strong>bc<strong>d<em>e</em></strong></p>
<p><em>a<strong>b</strong>c<strong>d</strong>e**f</em></p>
<p><em>a<strong>b</strong></em>c<strong>d</strong><em>e**f</em></p>
<p><em>a<strong>b</strong></em>c<strong>d</strong>*e<strong>f</strong></p>
<p><em>a<strong>b</strong></em>c<strong>d</strong><em>e</em><em>f</em></p>
<p><em>a<strong>b</strong></em>c<strong>d</strong><em>e</em><em>f</em>*</p>
<p>_<em>a <em>b c</em></em></p>
<p>_a __b __c __d __e _<em>f</em></p>
<p><strong><em>a <em><em>b <em>c d</em></em> e</em> f</em></strong></p>
Expand Down Expand Up @@ -831,6 +831,86 @@ def test_commonmark(self):
)
)

def test_ambiguous_closer_skips_rejected_opener(self):
"""Test that an ambiguous closer can skip an opener rejected by the rule of 3."""

self.assertMarkdownRenders(
'__a "_b"__: x',
'<p><strong>a "_b"</strong>: x</p>'
)

def test_ambiguous_closer_skips_rejected_opener_asterisk(self):
"""Test the rule of 3 with asterisks."""

self.assertMarkdownRenders(
'**a "*b"**: x',
'<p><strong>a "*b"</strong>: x</p>'
)

def test_attribute_list_like_content(self):
"""Test the rule of 3 with a link followed by attribute list like content."""

self.assertMarkdownRenders(
'__[A](u){target="_blank"}__: x',
'<p><strong><a href="u">A</a>{target="_blank"}</strong>: x</p>'
)

def test_rejected_opener_is_original_run_length(self):
"""Test that the original length of a partially consumed run is used for the rule of 3."""

self.assertMarkdownRenders(
'__a_ __"_: x',
'<p>_<em>a</em> __"_: x</p>'
)

def test_unambiguous_closer_unaffected(self):
"""Test that an unambiguous closer is not subject to the rule of 3."""

self.assertMarkdownRenders(
'__a "_b" c__ x',
'<p>_<em>a "<em>b" c</em></em> x</p>'
)

def test_remainder_classified_by_original_context(self):
"""Test that the unused part of a closing run is classified by what preceded the run."""

self.check_markdown(
'_a__"__"_: x',
'<p><em>a</em>_"__"_: x</p>'
)

def test_remainder_classified_by_original_context_three(self):
"""Test the unused part of a longer closing run."""

self.check_markdown(
'_a___"_"__: x',
'<p><em>a</em>__"_"__: x</p>'
)

def test_placeholder_treated_as_punctuation(self):
"""Test that a placeholder from a different delimiter is still treated as punctuation."""

self.check_markdown(
'*test*_"test"_',
'<p><em>test</em><em>"test"</em></p>'
)

def test_ambiguous_closer_pairs_with_partially_consumed_opener(self):
"""Test that the rule of 3 uses the original run length of a partially consumed opener."""

self.check_markdown(
'**a*_**: x',
'<p><em><em>a</em>_</em>*: x</p>'
)

def test_ambiguous_closer_rejected_by_original_run_length(self):
"""Test that the rule of 3 still rejects a pairing based on the original run lengths."""

self.check_markdown(
'**a*b**: x',
'<p>*<em>a<em>b</em></em>: x</p>'
)


class TestProcessorRemoval(TestCase):

Expand Down
Loading