Skip to content
Open
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
23 changes: 19 additions & 4 deletions markdown_it/rules_core/linkify.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re
from typing import Protocol

from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpen
from ..common.utils import isLinkClose, isLinkOpen
from ..token import Token
from .state_core import StateCore

Expand All @@ -28,6 +28,12 @@ def linkify(state: StateCore) -> None:

tokens = inline_token.children

# Text tokens to replace, as `(index, nodes)` pairs. They are applied
# in a single pass below: splicing each match into the child list as it
# is found rebuilds that list every time, which is quadratic in the
# number of links.
replacements: list[tuple[int, list[Token]]] = []

htmlLinkLevel = 0

# We scan from the end, to keep position when new tags added.
Expand All @@ -36,7 +42,6 @@ def linkify(state: StateCore) -> None:
i = len(tokens)
while i >= 1:
i -= 1
assert isinstance(tokens, list)
currentToken = tokens[i]

# Skip content of markdown links
Expand Down Expand Up @@ -65,7 +70,7 @@ def linkify(state: StateCore) -> None:
links: list[_LinkType] = state.md.linkify.match(text) or []

# Now split string to nodes
nodes = []
nodes: list[Token] = []
level = currentToken.level
lastPos = 0

Expand Down Expand Up @@ -138,7 +143,17 @@ def linkify(state: StateCore) -> None:
token.level = level
nodes.append(token)

inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes)
replacements.append((i, nodes))

if replacements:
new_tokens: list[Token] = []
last = 0
for index, new_nodes in reversed(replacements):
new_tokens.extend(tokens[last:index])
new_tokens.extend(new_nodes)
last = index + 1
new_tokens.extend(tokens[last:])
inline_token.children = new_tokens


class _LinkType(Protocol):
Expand Down
46 changes: 38 additions & 8 deletions markdown_it/rules_inline/linkify.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
"""Process links like https://example.org/"""

import re

from .state_inline import StateInline

# RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE)
#
# The backscan for the scheme is bounded, so that a long run of scheme
# characters before each `://` cannot make it quadratic. No schema linkify-it
# recognises is this long.
MAX_SCHEME_LENGTH = 10


def isAsciiAlpha(ch: str) -> bool:
return ("a" <= ch <= "z") or ("A" <= ch <= "Z")


def isSchemeChar(ch: str) -> bool:
return (
("a" <= ch <= "z")
or ("A" <= ch <= "Z")
or ("0" <= ch <= "9")
or ch in ("+", "-", ".")
)


def linkify(state: StateInline, silent: bool) -> bool:
Expand All @@ -28,14 +43,29 @@ def linkify(state: StateInline, silent: bool) -> bool:
):
return False

if not (match := SCHEME_RE.search(state.pending)):
# Search backwards for the scheme, but no further than MAX_SCHEME_LENGTH
# characters, the start of the pending string, or the start of the source.
# `state.src` is scanned rather than `state.pending` because it is cheaper
# to index.
protoMin = pos - min(MAX_SCHEME_LENGTH, len(state.pending), pos)
protoStart = pos
while protoStart > protoMin and isSchemeChar(state.src[protoStart - 1]):
protoStart -= 1

if protoStart == pos or not isAsciiAlpha(state.src[protoStart]):
return False

proto = match.group(1)
if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])):
protoLength = pos - protoStart

if not (link := state.md.linkify.match_at_start(state.src[protoStart:])):
return False
url: str = link.url

# invalid link, but still detected by linkify somehow;
# need to check to prevent the position from moving backwards below
if len(url) <= protoLength:
return False

# disallow '*' at the end of the link (conflicts with emphasis)
url = url.rstrip("*")

Expand All @@ -44,7 +74,7 @@ def linkify(state: StateInline, silent: bool) -> bool:
return False

if not silent:
state.pending = state.pending[: -len(proto)]
state.pending = state.pending[:-protoLength]

token = state.push("link_open", "a", 1)
token.attrs = {"href": full_url}
Expand All @@ -58,5 +88,5 @@ def linkify(state: StateInline, silent: bool) -> bool:
token.markup = "linkify"
token.info = "auto"

state.pos += len(url) - len(proto)
state.pos += len(url) - protoLength
return True
79 changes: 79 additions & 0 deletions tests/test_linkify.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,82 @@ def test_token_levels():
assert link_open.level == 0
assert link_text.level == 1
assert link_close.level == 0


@pytest.mark.parametrize(
"src,expected",
[
# the scheme is read backwards from `://`, and must still be found
("http://a.com", '<a href="http://a.com">http://a.com</a>'),
("x http://a.com", 'x <a href="http://a.com">http://a.com</a>'),
("(http://a.com", '(<a href="http://a.com">http://a.com</a>'),
# not a scheme: starts with a digit, or there is nothing before `://`
("0http://a.com", "0http://a.com"),
("://a.com", "://a.com"),
# a run of scheme characters longer than any schema linkify-it knows
("abcdefghijkl://a.com", "abcdefghijkl://a.com"),
("a" * 50 + "://a.com", "a" * 50 + "://a.com"),
# the scheme may not reach back past the start of the pending text
("`c`http://a.com", '<code>c</code><a href="http://a.com">http://a.com</a>'),
],
)
def test_scheme_backscan(src, expected):
"""The scheme before `://` is found (or rejected) as before."""
md = MarkdownIt(options_update={"linkify": True}).enable("linkify")
assert md.renderInline(src) == expected


def test_long_scheme_backscan_runs_are_linear():
"""A long run of `://` preceded by scheme characters must stay linear.

The scheme used to be matched with a `$`-anchored regex over the whole of
`state.pending`, which is O(len) per `://` and so quadratic over a run of
them. The backscan is now bounded by `MAX_SCHEME_LENGTH`. This input
exceeds the suite's 10 s timeout without that bound.
"""
md = MarkdownIt(options_update={"linkify": True}).enable("linkify")
assert md.renderInline("a://" * 20_000) == "a://" * 20_000


def test_many_linkified_text_tokens_are_linear():
"""Many separate text tokens with links in one block must stay linear.

The core rule used to splice each match into the inline token's children
with `arrayReplaceAt`, rebuilding the whole list every time, which is
quadratic in the number of matches. This input exceeds the suite's 10 s
timeout without the single-pass rebuild.
"""
md = MarkdownIt(options_update={"linkify": True}).enable("linkify")
html = md.renderInline("*x* a.com " * 20_000)
assert html.count('<a href="http://a.com">') == 20_000
assert html.count("<em>x</em>") == 20_000


def test_linkify_keeps_token_order_across_several_text_tokens():
"""The single-pass rebuild must keep the children in source order, and
leave the tokens it skips (markdown and html links) untouched."""
md = MarkdownIt(options_update={"linkify": True}).enable("linkify")
src = "a.com *e* [t](b.com) <a href='c.com'>c.com</a> d.com"
children = md.parseInline(src)[0].children
assert children is not None
assert [(t.type, t.markup, t.level) for t in children] == [
("link_open", "linkify", 0),
("text", "", 1),
("link_close", "linkify", 0),
("text", "", 0),
("em_open", "*", 0),
("text", "", 1),
("em_close", "*", 0),
("text", "", 0),
("link_open", "", 0),
("text", "", 1),
("link_close", "", 0),
("text", "", 0),
("html_inline", "", 0),
("text", "", 0),
("html_inline", "", 0),
("text", "", 0),
("link_open", "linkify", 0),
("text", "", 1),
("link_close", "linkify", 0),
]