refactor urlize function
Before adoption: this commit came in with the history the project adopted, so no landing records it.
don't try other url types if one already matched no-op function if trim is not enabled avoid backtracking when matching trailing punctuation match head and tail punctuation separately don't scan for unbalanced parentheses more than necessary ensure email domain starts and ends with a word character
authored by David Lord · committed by David Lord · parent be83e7e · Browse files · 2 files·+68 added−59 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+68 added−59 removed
- other:+68 added−59 removed
Provenance
- Commit
1aa979c- Tree
ecab86b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
be83e7e
2 files changed+68 added−59 removed
modified:src/jinja2/utils.py+63 added-55 removed
166 unmodified lines167 168 return pformat(obj)169 170 171-_word_split_re = re.compile(r"(\s+)")172-_lead_pattern = "|".join(map(re.escape, ("(", "<", "<")))173-_trail_pattern = "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">")))174-_punctuation_re = re.compile(175- fr"^(?P<lead>(?:{_lead_pattern})*)(?P<middle>.*?)(?P<trail>(?:{_trail_pattern})*)$"176-)171 _http_re = re.compile(172 r"""173 ^174 (20 unmodified lines195 $196 """,197 re.IGNORECASE | re.VERBOSE,198 )205-_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")199+_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")200 201 202 def urlize(text, trim_url_limit=None, rel=None, target=None, extra_schemes=None):203 """Convert URLs in text into clickable links.26 unmodified lines230 The parsing rules were updated. Recognize email addresses with231 or without the ``mailto:`` scheme. Validate IP addresses. Ignore232 parentheses and brackets in more cases.233 """234+ if trim_url_limit is not None:235 241- def trim_url(x, limit=trim_url_limit):242- if limit is not None:243- return x[:limit] + ("..." if len(x) >= limit else "")236+ def trim_url(x):237+ if len(x) > trim_url_limit:238+ return f"{x[:trim_url_limit]}..."239 245- return x240+ return x241 242+ else:243+244+ def trim_url(x):245+ return x246+247- words = _word_split_re.split(str(escape(text)))247+ words = re.split(r"(\s+)", str(escape(text)))248 rel_attr = f' rel="{escape(rel)}"' if rel else ""249 target_attr = f' target="{escape(target)}"' if target else ""250 251 for i, word in enumerate(words):252- match = _punctuation_re.match(word)252+ head, middle, tail = "", word, ""253+ match = re.match(r"^([(<]|<)+", middle)254 255 if match:255- lead, middle, trail = match.groups()256- # fix for mismatched opening and closing parentheses257- pairs = [("(", ")"), ("<", ">"), ("<", ">")]256+ head = match.group()257+ middle = middle[match.end() :]258 259- for start_char in re.findall(_lead_pattern, middle):260- end_char = next(c for o, c in pairs if o == start_char)259+ # Unlike lead, which is anchored to the start of the string,260+ # need to check that the string ends with any of the characters261+ # before trying to match all of them, to avoid backtracking.262+ if middle.endswith((")", ">", ".", ",", "\n", ">")):263+ match = re.search(r"([)>.,\n]|>)+$", middle)264 262- while (263- middle.count(start_char) > middle.count(end_char)264- and end_char in trail265- ):266- end_char_index = trail.index(end_char)267- middle = middle + trail[: end_char_index + len(end_char)]268- trail = trail[end_char_index + len(end_char) :]265+ if match:266+ tail = match.group()267+ middle = middle[: match.start()]268 270- if _http_re.match(middle):271- if middle.startswith("https://") or middle.startswith("http://"):272- middle = (273- f'<a href="{middle}"{rel_attr}{target_attr}>'274- f"{trim_url(middle)}</a>"275- )276- else:277- middle = (278- f'<a href="https://{middle}"{rel_attr}{target_attr}>'279- f"{trim_url(middle)}</a>"280- )269+ # Prefer balancing parentheses in URLs instead of ignoring a270+ # trailing character.271+ for start_char, end_char in ("(", ")"), ("<", ">"), ("<", ">"):272+ start_count = middle.count(start_char)273 282- if (283- "@" in middle284- and not middle.startswith("www.")285- and ":" not in middle286- and _simple_email_re.match(middle)287- ):288- middle = f'<a href="mailto:{middle}">{middle}</a>'274+ if start_count <= middle.count(end_char):275+ # Balanced, or lighter on the left276+ continue277 290- if middle.startswith("mailto:") and _simple_email_re.match(middle[7:]):291- middle = f'<a href="{middle}">{middle[7:]}</a>'278+ # Move as many as possible from the tail to balance279+ for _ in range(min(start_count, tail.count(end_char))):280+ end_index = tail.index(end_char) + len(end_char)281+ # Move anything in the tail before the end char too282+ middle += tail[:end_index]283+ tail = tail[end_index:]284 293- if extra_schemes is not None:294- schemes = {x for x in extra_schemes if middle.startswith(x)}285+ if _http_re.match(middle):286+ if middle.startswith("https://") or middle.startswith("http://"):287+ middle = (288+ f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'289+ )290+ else:291+ middle = (292+ f'<a href="https://{middle}"{rel_attr}{target_attr}>'293+ f"{trim_url(middle)}</a>"294+ )295 296- for uri_scheme in schemes:297- if len(middle) > len(uri_scheme):298- middle = (299- f'<a href="{middle}"{rel_attr}{target_attr}>'300- f"{middle}</a>"301- )296+ elif middle.startswith("mailto:") and _email_re.match(middle[7:]):297+ middle = f'<a href="{middle}">{middle[7:]}</a>'298 303- if lead + middle + trail != word:304- words[i] = lead + middle + trail299+ elif (300+ "@" in middle301+ and not middle.startswith("www.")302+ and ":" not in middle303+ and _email_re.match(middle)304+ ):305+ middle = f'<a href="mailto:{middle}">{middle}</a>'306 307+ elif extra_schemes is not None:308+ for scheme in extra_schemes:309+ if middle != scheme and middle.startswith(scheme):310+ middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>'311+312+ words[i] = f"{head}{middle}{tail}"313+314 return "".join(words)315 316 317 def generate_lorem_ipsum(n=5, html=True, min=20, max=100):427 unmodified linesmodified:CHANGES.rst+5 added-4 removed
23 unmodified lines24 - Deprecate the ``autoescape`` and ``with`` extensions, they are25 built-in to the compiler. :issue:`1203`26 - The ``urlize`` filter recognizes ``mailto:`` links and takes27 ``extra_schemes`` (or ``env.policies["urlize.extra_schemes"]``) to28- recognize other schemes such as ``ftp://`` or ``tel:``. It ignores29- parentheses around URLs. The URL parsing in general has been30- updated. URLs without a scheme are linked as ``https://`` instead of31- ``http://``. :issue:`522, 827, 1172`, :pr:`1195`28+ recognize other schemes. It tries to balance parentheses within a29+ URL instead of ignoring trailing characters. The parsing in general30+ has been updated to be more efficient and match more cases. URLs31+ without a scheme are linked as ``https://`` instead of ``http://``.32+ :issue:`522, 827, 1172`, :pr:`1195`33 34 35 Version 2.11.236 --------------770 unmodified lines