url.py 800 B

1234567891011121314151617181920212223242526272829303132
  1. from typing import TYPE_CHECKING, Match
  2. from ..util import escape_url
  3. if TYPE_CHECKING:
  4. from ..core import InlineState
  5. from ..inline_parser import InlineParser
  6. from ..markdown import Markdown
  7. __all__ = ["url"]
  8. URL_LINK_PATTERN = r"""https?:\/\/[^\s<]+[^<.,:;"')\]\s]"""
  9. def parse_url_link(inline: "InlineParser", m: Match[str], state: "InlineState") -> int:
  10. text = m.group(0)
  11. pos = m.end()
  12. if state.in_link:
  13. inline.process_text(text, state)
  14. return pos
  15. state.append_token(
  16. {
  17. "type": "link",
  18. "children": [{"type": "text", "raw": text}],
  19. "attrs": {"url": escape_url(text)},
  20. }
  21. )
  22. return pos
  23. def url(md: "Markdown") -> None:
  24. md.inline.register("url_link", URL_LINK_PATTERN, parse_url_link)