Convert URLs in text into clickable links. This may not recognize links in some situations. Usually, a more comprehensive formatter, such as a Markdown library, is a better choice. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email addresses. Links with traili
(
text: str,
trim_url_limit: t.Optional[int] = None,
rel: t.Optional[str] = None,
target: t.Optional[str] = None,
extra_schemes: t.Optional[t.Iterable[str]] = None,
)
| 219 | |
| 220 | |
| 221 | def urlize( |
| 222 | text: str, |
| 223 | trim_url_limit: t.Optional[int] = None, |
| 224 | rel: t.Optional[str] = None, |
| 225 | target: t.Optional[str] = None, |
| 226 | extra_schemes: t.Optional[t.Iterable[str]] = None, |
| 227 | ) -> str: |
| 228 | """Convert URLs in text into clickable links. |
| 229 | |
| 230 | This may not recognize links in some situations. Usually, a more |
| 231 | comprehensive formatter, such as a Markdown library, is a better |
| 232 | choice. |
| 233 | |
| 234 | Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email |
| 235 | addresses. Links with trailing punctuation (periods, commas, closing |
| 236 | parentheses) and leading punctuation (opening parentheses) are |
| 237 | recognized excluding the punctuation. Email addresses that include |
| 238 | header fields are not recognized (for example, |
| 239 | ``mailto:address@example.com?cc=copy@example.com``). |
| 240 | |
| 241 | :param text: Original text containing URLs to link. |
| 242 | :param trim_url_limit: Shorten displayed URL values to this length. |
| 243 | :param target: Add the ``target`` attribute to links. |
| 244 | :param rel: Add the ``rel`` attribute to links. |
| 245 | :param extra_schemes: Recognize URLs that start with these schemes |
| 246 | in addition to the default behavior. |
| 247 | |
| 248 | .. versionchanged:: 3.0 |
| 249 | The ``extra_schemes`` parameter was added. |
| 250 | |
| 251 | .. versionchanged:: 3.0 |
| 252 | Generate ``https://`` links for URLs without a scheme. |
| 253 | |
| 254 | .. versionchanged:: 3.0 |
| 255 | The parsing rules were updated. Recognize email addresses with |
| 256 | or without the ``mailto:`` scheme. Validate IP addresses. Ignore |
| 257 | parentheses and brackets in more cases. |
| 258 | """ |
| 259 | if trim_url_limit is not None: |
| 260 | |
| 261 | def trim_url(x: str) -> str: |
| 262 | if len(x) > trim_url_limit: # type: ignore |
| 263 | return f"{x[:trim_url_limit]}..." |
| 264 | |
| 265 | return x |
| 266 | |
| 267 | else: |
| 268 | |
| 269 | def trim_url(x: str) -> str: |
| 270 | return x |
| 271 | |
| 272 | words = re.split(r"(\s+)", str(markupsafe.escape(text))) |
| 273 | rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else "" |
| 274 | target_attr = f' target="{markupsafe.escape(target)}"' if target else "" |
| 275 | |
| 276 | for i, word in enumerate(words): |
| 277 | head, middle, tail = "", word, "" |
| 278 | match = re.match(r"^([(<]|<)+", middle) |
no test coverage detected