update urlize docs, clean up code
Before adoption: this commit came in with the history the project adopted, so no landing records it.
move regexes near implementation commented verbose regex for http pattern renamed extra_uri_schemes to extra_schemes
authored by David Lord · committed by David Lord · parent d504e1d · Browse files · 6 files·+128 added−73 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+128 added−73 removed
- tests:+2 added−2 removed
- other:+126 added−71 removed
Provenance
- Commit
be83e7e- Tree
0f169e1- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
d504e1d
6 files changed+128 added−73 removed
modified:docs/api.rst+3 added-3 removed
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:.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 that326 unmodified linesmodified:src/jinja2/defaults.py+1 added-1 removed
33 unmodified lines34 DEFAULT_POLICIES = {35 "compiler.ascii_str": True,36 "urlize.rel": "noopener",37 "urlize.target": None,38- "urlize.extra_uri_schemes": 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+46 added-35 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})$")23 24 25 def contextfilter(f):26 """Decorator for marking context dependent filters. The current539 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(575 eval_ctx,576 value,577 trim_url_limit=None,578 nofollow=False,579 target=None,580 rel=None,579- extra_uri_schemes=None,581+ extra_schemes=None,582 ):581- """Converts URLs in plain text into clickable links.583+ """Convert URLs in text into clickable links.584 583- If you pass the filter an additional integer it will shorten the urls584- to that number. Also a third argument exists that makes the urls585- "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 587- .. 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 589- {{ mytext|urlize(40, true) }}590- 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 592- If *target* is specified, the ``target`` attribute will be added to the593- ``<a>`` tag:606+ .. versionchanged:: 3.0607+ The ``extra_schemes`` parameter was added.608 595- .. sourcecode:: jinja609+ .. versionchanged:: 3.0610+ Generate ``https://`` links for URLs without a scheme.611 597- {{ 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 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-617 .. versionchanged:: 2.8618 The ``target`` parameter was added.609-610- .. versionchanged:: 3.0611- The ``extra_uri_schemes`` parameter was added.619 """620 policies = eval_ctx.environment.policies621+ rel_parts = set((rel or "").split())622 615- rel = set((rel or "").split() or [])623 if nofollow:617- rel.add("nofollow")618- rel.update((policies["urlize.rel"] or "").split())619- rel = " ".join(sorted(rel)) or None624+ 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"]631 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.")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,632- trim_url_limit,641+ trim_url_limit=trim_url_limit,642 rel=rel,643 target=target,635- extra_uri_schemes=extra_uri_schemes,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+70 added-32 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_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._-]+$")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 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://,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.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+)177+_http_re = re.compile(178+ r"""179+ ^180+ (181+ (https?://|www\.) # scheme or www182+ (([\w%-]+\.)+)? # subdomain183+ (184+ [a-z]{2,63} # basic tld185+ |186+ xn--[\w%]{2,59} # idna tld187+ )188+ |189+ ([\w%-]{2,63}\.)+ # basic domain190+ (com|net|int|edu|gov|org|info|mil) # basic tld191+ |192+ (https?://) # scheme193+ (194+ (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4195+ |196+ (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6197+ )198+ )199+ (?::[\d]{1,5})? # port200+ (?:[/?#]\S*)? # path, query, and fragment201+ $202+ """,203+ re.IGNORECASE | re.VERBOSE,204+)205+_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")206 192- If trim_url_limit is not None, the URLs in link text will be limited193- to trim_url_limit characters.207 195- If nofollow is True, the URLs in link text will get a rel="nofollow"196- attribute.208+def urlize(text, trim_url_limit=None, rel=None, target=None, extra_schemes=None):209+ """Convert URLs in text into clickable links.210 198- If target is not None, a target attribute will be added to the link.211+ This may not recognize links in some situations. Usually, a more212+ comprehensive formatter, such as a Markdown library, is a better213+ choice.214 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).215+ Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email216+ addresses. Links with trailing punctuation (periods, commas, closing217+ parentheses) and leading punctuation (opening parentheses) are218+ recognized excluding the punctuation. Email addresses that include219+ header fields are not recognized (for example,220+ ``mailto:address@example.com?cc=copy@example.com``).221 222+ :param text: Original text containing URLs to link.223+ :param trim_url_limit: Shorten displayed URL values to this length.224+ :param target: Add the ``target`` attribute to links.225+ :param rel: Add the ``rel`` attribute to links.226+ :param extra_schemes: Recognize URLs that start with these schemes227+ in addition to the default behavior.228+229 .. versionchanged:: 3.0205- Adds limited support for mailto: links230+ The ``extra_schemes`` parameter was added.231+232+ .. versionchanged:: 3.0233+ Generate ``https://`` links for URLs without a scheme.234+235+ .. versionchanged:: 3.0236+ The parsing rules were updated. Recognize email addresses with237+ or without the ``mailto:`` scheme. Validate IP addresses. Ignore238+ parentheses and brackets in more cases.239 """240 241 def trim_url(x, limit=trim_url_limit):242 if limit is not None:6 unmodified lines249 target_attr = f' target="{escape(target)}"' if target else ""250 251 for i, word in enumerate(words):252 match = _punctuation_re.match(word)253+254 if match:255 lead, middle, trail = match.groups()256 # fix for mismatched opening and closing parentheses257 pairs = [("(", ")"), ("<", ">"), ("<", ">")]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)261+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) :]269 234- if _simple_http_https_re.match(middle):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>"10 unmodified lines285 and ":" not in middle286 and _simple_email_re.match(middle)287 ):288 middle = f'<a href="mailto:{middle}">{middle}</a>'289+290 if middle.startswith("mailto:") and _simple_email_re.match(middle[7:]):291 middle = f'<a href="{middle}">{middle[7:]}</a>'292 256- if extra_uri_schemes is not None:257- schemes = {x for x in extra_uri_schemes if middle.startswith(x)}293+ if extra_schemes is not None:294+ schemes = {x for x in extra_schemes if middle.startswith(x)}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}>'437 unmodified linesmodified:tests/test_filters.py+2 added-2 removed
371 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):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_uri_schemes=["tel:", "ftp:"]) }}'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">'385 unmodified linesmodified:CHANGES.rst+6 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 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`32 33 34 Version 2.11.235 --------------770 unmodified lines