Merge pull request #1195 from bebleo/add_mailto_link_support
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Improve and extend urlize
authored by David Lord · committed by GitHub · parents 2f41690, 1aa979c · Browse files · 7 files·+232 added−66 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+232 added−66 removed
- tests:+32 added−0 removed
- other:+200 added−66 removed
Provenance
- Commit
f1b1caf- Tree
2e2f459- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
2f41690- Parent 2
1aa979c
7 files changed+232 added−66 removed
modified:docs/api.rst+4 added
548 unmodified lines549 ``urlize.target``:550 The default target that is issued for links from the `urlize` filter551 if no other target is defined by the call explicitly.552 553+``urlize.extra_schemes``:554+ Recognize URLs that start with these schemes in addition to the555+ default ``http://``, ``https://``, and ``mailto:``.556+557 ``json.dumps_function``:558 If this is set to a value other than `None` then the `tojson` filter559 will dump with this function instead of the default one. Note that560 this function should accept arbitrary extra arguments which might be325 unmodified linesmodified:src/jinja2/defaults.py+1 added
33 unmodified lines34 DEFAULT_POLICIES = {35 "compiler.ascii_str": True,36 "urlize.rel": "noopener",37 "urlize.target": None,38+ "urlize.extra_schemes": None,39 "truncate.leeway": 5,40 "json.dumps_function": None,41 "json.dumps_kwargs": {"sort_keys": True},42 "ext.i18n.trimmed": False,1 unmodified linemodified:src/jinja2/filters.py+61 added-17 removed
565 unmodified lines566 """Pretty print a variable. Useful for debugging."""567 return pformat(value)568 569 570+_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")571+572+573 @evalcontextfilter574 def do_urlize(572- eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None575+ eval_ctx,576+ value,577+ trim_url_limit=None,578+ nofollow=False,579+ target=None,580+ rel=None,581+ extra_schemes=None,582 ):574- """Converts URLs in plain text into clickable links.583+ """Convert URLs in text into clickable links.584 576- If you pass the filter an additional integer it will shorten the urls577- to that number. Also a third argument exists that makes the urls578- "nofollow":585+ This may not recognize links in some situations. Usually, a more586+ comprehensive formatter, such as a Markdown library, is a better587+ choice.588 580- .. sourcecode:: jinja589+ Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email590+ addresses. Links with trailing punctuation (periods, commas, closing591+ parentheses) and leading punctuation (opening parentheses) are592+ recognized excluding the punctuation. Email addresses that include593+ header fields are not recognized (for example,594+ ``mailto:address@example.com?cc=copy@example.com``).595 582- {{ mytext|urlize(40, true) }}583- links are shortened to 40 chars and defined with rel="nofollow"596+ :param value: Original text containing URLs to link.597+ :param trim_url_limit: Shorten displayed URL values to this length.598+ :param nofollow: Add the ``rel=nofollow`` attribute to links.599+ :param target: Add the ``target`` attribute to links.600+ :param rel: Add the ``rel`` attribute to links.601+ :param extra_schemes: Recognize URLs that start with these schemes602+ in addition to the default behavior. Defaults to603+ ``env.policies["urlize.extra_schemes"]``, which defaults to no604+ extra schemes.605 585- If *target* is specified, the ``target`` attribute will be added to the586- ``<a>`` tag:606+ .. versionchanged:: 3.0607+ The ``extra_schemes`` parameter was added.608 588- .. sourcecode:: jinja609+ .. versionchanged:: 3.0610+ Generate ``https://`` links for URLs without a scheme.611 590- {{ mytext|urlize(40, target='_blank') }}612+ .. versionchanged:: 3.0613+ The parsing rules were updated. Recognize email addresses with614+ or without the ``mailto:`` scheme. Validate IP addresses. Ignore615+ parentheses and brackets in more cases.616 617 .. versionchanged:: 2.8618 The ``target`` parameter was added.619 """620 policies = eval_ctx.environment.policies596- rel = set((rel or "").split() or [])621+ rel_parts = set((rel or "").split())622+623 if nofollow:598- rel.add("nofollow")599- rel.update((policies["urlize.rel"] or "").split())624+ rel_parts.add("nofollow")625+626+ rel_parts.update((policies["urlize.rel"] or "").split())627+ rel = " ".join(sorted(rel_parts)) or None628+629 if target is None:630 target = policies["urlize.target"]602- rel = " ".join(sorted(rel)) or None603- rv = urlize(value, trim_url_limit, rel=rel, target=target)631+632+ if extra_schemes is None:633+ extra_schemes = policies["urlize.extra_schemes"] or ()634+635+ for scheme in extra_schemes:636+ if _uri_scheme_re.fullmatch(scheme) is None:637+ raise FilterArgumentError(f"{scheme!r} is not a valid URI scheme prefix.")638+639+ rv = urlize(640+ value,641+ trim_url_limit=trim_url_limit,642+ rel=rel,643+ target=target,644+ extra_schemes=extra_schemes,645+ )646+647 if eval_ctx.autoescape:648 rv = Markup(rv)649+650 return rv651 652 653 def do_indent(s, width=4, first=False, blank=False):752 unmodified linesmodified:src/jinja2/utils.py+127 added-49 removed
9 unmodified lines10 11 from markupsafe import escape12 from markupsafe import Markup13 14-_word_split_re = re.compile(r"(\s+)")15-_lead_pattern = "|".join(map(re.escape, ("(", "<", "<")))16-_trail_pattern = "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">")))17-_punctuation_re = re.compile(18- fr"^(?P<lead>(?:{_lead_pattern})*)(?P<middle>.*?)(?P<trail>(?:{_trail_pattern})*)$"19-)20-_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")14 _striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")15 _entity_re = re.compile(r"&([^;]+);")16 _letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"17 _digits = "0123456789"149 unmodified lines167 168 return pformat(obj)169 170 178-def urlize(text, trim_url_limit=None, rel=None, target=None):179- """Converts any URLs in text into clickable links. Works on http://,180- https:// and www. links. Links can have trailing punctuation (periods,181- commas, close-parens) and leading punctuation (opening parens) and182- it'll still do the right thing.171+_http_re = re.compile(172+ r"""173+ ^174+ (175+ (https?://|www\.) # scheme or www176+ (([\w%-]+\.)+)? # subdomain177+ (178+ [a-z]{2,63} # basic tld179+ |180+ xn--[\w%]{2,59} # idna tld181+ )182+ |183+ ([\w%-]{2,63}\.)+ # basic domain184+ (com|net|int|edu|gov|org|info|mil) # basic tld185+ |186+ (https?://) # scheme187+ (188+ (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4189+ |190+ (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6191+ )192+ )193+ (?::[\d]{1,5})? # port194+ (?:[/?#]\S*)? # path, query, and fragment195+ $196+ """,197+ re.IGNORECASE | re.VERBOSE,198+)199+_email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$")200 184- If trim_url_limit is not None, the URLs in link text will be limited185- to trim_url_limit characters.201 187- If nofollow is True, the URLs in link text will get a rel="nofollow"188- attribute.202+def urlize(text, trim_url_limit=None, rel=None, target=None, extra_schemes=None):203+ """Convert URLs in text into clickable links.204 190- If target is not None, a target attribute will be added to the link.205+ This may not recognize links in some situations. Usually, a more206+ comprehensive formatter, such as a Markdown library, is a better207+ choice.208+209+ Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email210+ addresses. Links with trailing punctuation (periods, commas, closing211+ parentheses) and leading punctuation (opening parentheses) are212+ recognized excluding the punctuation. Email addresses that include213+ header fields are not recognized (for example,214+ ``mailto:address@example.com?cc=copy@example.com``).215+216+ :param text: Original text containing URLs to link.217+ :param trim_url_limit: Shorten displayed URL values to this length.218+ :param target: Add the ``target`` attribute to links.219+ :param rel: Add the ``rel`` attribute to links.220+ :param extra_schemes: Recognize URLs that start with these schemes221+ in addition to the default behavior.222+223+ .. versionchanged:: 3.0224+ The ``extra_schemes`` parameter was added.225+226+ .. versionchanged:: 3.0227+ Generate ``https://`` links for URLs without a scheme.228+229+ .. versionchanged:: 3.0230+ 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 193- def trim_url(x, limit=trim_url_limit):194- if limit is not None:195- 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 197- return x240+ return x241 242+ else:243+244+ def trim_url(x):245+ return x246+199- 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):204- match = _punctuation_re.match(word)252+ head, middle, tail = "", word, ""253+ match = re.match(r"^([(<]|<)+", middle)254+255 if match:206- lead, middle, trail = match.groups()207- if middle.startswith("www.") or (208- "@" not in middle209- and not middle.startswith("http://")210- and not middle.startswith("https://")211- and len(middle) > 0212- and middle[0] in _letters + _digits213- and (214- middle.endswith(".org")215- or middle.endswith(".net")216- or middle.endswith(".com")256+ head = match.group()257+ middle = middle[match.end() :]258+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+265+ if match:266+ tail = match.group()267+ middle = middle[: match.start()]268+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+274+ if start_count <= middle.count(end_char):275+ # Balanced, or lighter on the left276+ continue277+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+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 )218- ):290+ else:291 middle = (220- f'<a href="http://{middle}"{rel_attr}{target_attr}>'292+ f'<a href="https://{middle}"{rel_attr}{target_attr}>'293 f"{trim_url(middle)}</a>"294 )223- if middle.startswith("http://") or middle.startswith("https://"):224- middle = (225- f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'226- )227- if (228- "@" in middle229- and not middle.startswith("www.")230- and ":" not in middle231- and _simple_email_re.match(middle)232- ):233- middle = f'<a href="mailto:{middle}">{middle}</a>'234- if lead + middle + trail != word:235- words[i] = lead + middle + trail295+296+ elif middle.startswith("mailto:") and _email_re.match(middle[7:]):297+ middle = f'<a href="{middle}">{middle[7:]}</a>'298+299+ 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:tests/test_filters.py+23 added
335 unmodified lines336 tmpl = env.from_string('{{ "foo"|upper }}')337 assert tmpl.render() == "FOO"338 339 def test_urlize(self, env):340+ tmpl = env.from_string('{{ "foo example.org bar"|urlize }}')341+ assert tmpl.render() == (342+ 'foo <a href="https://example.org" rel="noopener">' "example.org</a> bar"343+ )344 tmpl = env.from_string('{{ "foo http://www.example.com/ bar"|urlize }}')345 assert tmpl.render() == (346 'foo <a href="http://www.example.com/" rel="noopener">'347 "http://www.example.com/</a> bar"348 )349+ tmpl = env.from_string('{{ "foo mailto:email@example.com bar"|urlize }}')350+ assert tmpl.render() == (351+ 'foo <a href="mailto:email@example.com">email@example.com</a> bar'352+ )353+ tmpl = env.from_string('{{ "foo email@example.com bar"|urlize }}')354+ assert tmpl.render() == (355+ 'foo <a href="mailto:email@example.com">email@example.com</a> bar'356+ )357 358 def test_urlize_rel_policy(self):359 env = Environment()360 env.policies["urlize.rel"] = None11 unmodified lines372 == 'foo <a href="http://www.example.com/" rel="noopener" target="_blank">'373 "http://www.example.com/</a> bar"374 )375 376+ def test_urlize_extra_schemes_parameter(self, env):377+ tmpl = env.from_string(378+ '{{ "foo tel:+1-514-555-1234 ftp://localhost bar"|'379+ 'urlize(extra_schemes=["tel:", "ftp:"]) }}'380+ )381+ assert tmpl.render() == (382+ 'foo <a href="tel:+1-514-555-1234" rel="noopener">'383+ 'tel:+1-514-555-1234</a> <a href="ftp://localhost" rel="noopener">'384+ "ftp://localhost</a> bar"385+ )386+387 def test_wordcount(self, env):388 tmpl = env.from_string('{{ "foo bar baz"|wordcount }}')389 assert tmpl.render() == "3"390 378 unmodified linesmodified:tests/test_regression.py+9 added
107 unmodified lines108 tmpl.render() == '<a href="http://www.example.org/<foo" rel="noopener">'109 "http://www.example.org/<foo</a>"110 )111 112+ def test_urlize_filter_closing_punctuation(self, env):113+ tmpl = env.from_string(114+ '{{ "(see http://www.example.org/?page=subj_<desc.h>)"|urlize }}'115+ )116+ assert tmpl.render() == (117+ '(see <a href="http://www.example.org/?page=subj_<desc.h>" '118+ 'rel="noopener">http://www.example.org/?page=subj_<desc.h></a>)'119+ )120+121 def test_loop_call_loop(self, env):122 tmpl = env.from_string(123 """124 496 unmodified linesmodified:CHANGES.rst+7 added
21 unmodified lines22 - Blocks can be marked as ``required``. They must be overridden at23 some point, but not necessarily by the direct child. :issue:`1147`24 - 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. 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