Improve and extend urlize
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Bebleo · committed by David Lord · parent c3b34a0 · Browse files · 6 files·+129 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+129 added−27 removed
- tests:+32 added−0 removed
- other:+97 added−27 removed
Provenance
- Commit
d504e1d- Tree
7b97d88- Author
Bebleo <james.warne@outlook.com>- Committer
David Lord <davidism@gmail.com>- Parent
c3b34a0
6 files changed+129 added−27 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.additional_uri_schemes``:554+ Additional uri scheme prefixes that will generate links from the555+ `urlize` filter in addition to 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_uri_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+36 added-3 removed
18 unmodified lines19 from .utils import urlize20 21 _word_re = re.compile(r"\w+")22 _word_beginning_split_re = re.compile(r"([-\s({\[<]+)")23+_uri_scheme_re = re.compile(r"^([\w\.\+-]{2,}:(/){0,2})$")24 25 26 def contextfilter(f):27 """Decorator for marking context dependent filters. The current541 unmodified lines569 570 571 @evalcontextfilter572 def do_urlize(572- eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None573+ eval_ctx,574+ value,575+ trim_url_limit=None,576+ nofollow=False,577+ target=None,578+ rel=None,579+ extra_uri_schemes=None,580 ):581 """Converts URLs in plain text into clickable links.582 583 If you pass the filter an additional integer it will shorten the urls11 unmodified lines595 .. sourcecode:: jinja596 597 {{ mytext|urlize(40, target='_blank') }}598 599+ If *extra_uri_schemes* are added then links will be generated for those600+ in addition to http(s): and mailto: schemes.601+602+ .. sourcecode:: jinja603+604+ {{ mytext|urlize(extra_uri_schemes=['tel:', 'ftp://']) }}605+ links are generated for tel and ftp.606+607 .. versionchanged:: 2.8608 The ``target`` parameter was added.609+610+ .. versionchanged:: 3.0611+ The ``extra_uri_schemes`` parameter was added.612 """613 policies = eval_ctx.environment.policies614+615 rel = set((rel or "").split() or [])616 if nofollow:617 rel.add("nofollow")618 rel.update((policies["urlize.rel"] or "").split())619+ rel = " ".join(sorted(rel)) or None620+621 if target is None:622 target = policies["urlize.target"]602- rel = " ".join(sorted(rel)) or None603- rv = urlize(value, trim_url_limit, rel=rel, target=target)623+624+ if extra_uri_schemes is None:625+ extra_uri_schemes = policies["urlize.extra_uri_schemes"] or []626+ for uri_scheme in extra_uri_schemes:627+ if _uri_scheme_re.fullmatch(uri_scheme) is None:628+ raise FilterArgumentError(f"{uri_scheme} is not a valid URI scheme prefix.")629+630+ rv = urlize(631+ value,632+ trim_url_limit,633+ rel=rel,634+ target=target,635+ extra_uri_schemes=extra_uri_schemes,636+ )637 if eval_ctx.autoescape:638 rv = Markup(rv)639 return rv640 754 unmodified linesmodified:src/jinja2/utils.py+56 added-24 removed
15 unmodified lines16 _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_http_https_re = re.compile(21+ r"^((https?://|www\.)(([\w%-]+\.)+)?([a-z]{2,63}|xn--[\w%]{2,59})|"22+ r"([\w%-]{2,63}\.)+(com|net|int|edu|gov|org|info|mil)|"23+ r"(https?://)((([\d]{1,3})(\.[\d]{1,3}){3})|"24+ r"(\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}\])))"25+ r"(?::[\d]{1,5})?(?:[/?#]\S*)?$",26+ re.IGNORECASE,27+)28 _simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")29 _striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")30 _entity_re = re.compile(r"&([^;]+);")31 _letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"150 unmodified lines182 183 return pformat(obj)184 185 178-def urlize(text, trim_url_limit=None, rel=None, target=None):186+def urlize(text, trim_url_limit=None, rel=None, target=None, extra_uri_schemes=None):187 """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.188+ https://, www., mailto:, and email links. Links can have trailing189+ punctuation (periods, commas, close-parens) and leading punctuation190+ (opening parens) and it'll still do the right thing.191 192 If trim_url_limit is not None, the URLs in link text will be limited193 to trim_url_limit characters.194 195 If nofollow is True, the URLs in link text will get a rel="nofollow"196 attribute.197 198 If target is not None, a target attribute will be added to the link.199+200+ Known Limitations:201+ - Will not urlize emails or mailto: links if they include header fields202+ (for example, mailto:address@example.com?cc=copy@example.com).203+204+ .. versionchanged:: 3.0205+ Adds limited support for mailto: links206 """207 208 def trim_url(x, limit=trim_url_limit):209 if limit is not None:8 unmodified lines218 for i, word in enumerate(words):219 match = _punctuation_re.match(word)220 if match:221 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")217- )218- ):219- middle = (220- f'<a href="http://{middle}"{rel_attr}{target_attr}>'221- f"{trim_url(middle)}</a>"222- )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- )222+ # fix for mismatched opening and closing parentheses223+ pairs = [("(", ")"), ("<", ">"), ("<", ">")]224+ for start_char in re.findall(_lead_pattern, middle):225+ end_char = next(c for o, c in pairs if o == start_char)226+ while (227+ middle.count(start_char) > middle.count(end_char)228+ and end_char in trail229+ ):230+ end_char_index = trail.index(end_char)231+ middle = middle + trail[: end_char_index + len(end_char)]232+ trail = trail[end_char_index + len(end_char) :]233+234+ if _simple_http_https_re.match(middle):235+ if middle.startswith("https://") or middle.startswith("http://"):236+ middle = (237+ f'<a href="{middle}"{rel_attr}{target_attr}>'238+ f"{trim_url(middle)}</a>"239+ )240+ else:241+ middle = (242+ f'<a href="https://{middle}"{rel_attr}{target_attr}>'243+ f"{trim_url(middle)}</a>"244+ )245+246 if (247 "@" in middle248 and not middle.startswith("www.")249 and ":" not in middle250 and _simple_email_re.match(middle)251 ):252 middle = f'<a href="mailto:{middle}">{middle}</a>'253+ if middle.startswith("mailto:") and _simple_email_re.match(middle[7:]):254+ middle = f'<a href="{middle}">{middle[7:]}</a>'255+256+ if extra_uri_schemes is not None:257+ schemes = {x for x in extra_uri_schemes if middle.startswith(x)}258+ for uri_scheme in schemes:259+ if len(middle) > len(uri_scheme):260+ middle = (261+ f'<a href="{middle}"{rel_attr}{target_attr}>'262+ f"{middle}</a>"263+ )264+265 if lead + middle + trail != word:266 words[i] = lead + middle + trail267+268 return "".join(words)269 270 271 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_uri_schemes_parameter(self, env):377+ tmpl = env.from_string(378+ '{{ "foo tel:+1-514-555-1234 ftp://localhost bar"|'379+ 'urlize(extra_uri_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 lines