autolink.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Process autolinks '<protocol:...>'
  2. import re
  3. from .state_inline import StateInline
  4. EMAIL_RE = re.compile(
  5. r"^([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$" # noqa: E501
  6. )
  7. AUTOLINK_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$")
  8. def autolink(state: StateInline, silent: bool) -> bool:
  9. pos = state.pos
  10. if state.src[pos] != "<":
  11. return False
  12. start = state.pos
  13. maximum = state.posMax
  14. while True:
  15. pos += 1
  16. if pos >= maximum:
  17. return False
  18. ch = state.src[pos]
  19. if ch == "<":
  20. return False
  21. if ch == ">":
  22. break
  23. url = state.src[start + 1 : pos]
  24. if AUTOLINK_RE.search(url) is not None:
  25. fullUrl = state.md.normalizeLink(url)
  26. if not state.md.validateLink(fullUrl):
  27. return False
  28. if not silent:
  29. token = state.push("link_open", "a", 1)
  30. token.attrs = {"href": fullUrl}
  31. token.markup = "autolink"
  32. token.info = "auto"
  33. token = state.push("text", "", 0)
  34. token.content = state.md.normalizeLinkText(url)
  35. token = state.push("link_close", "a", -1)
  36. token.markup = "autolink"
  37. token.info = "auto"
  38. state.pos += len(url) + 2
  39. return True
  40. if EMAIL_RE.search(url) is not None:
  41. fullUrl = state.md.normalizeLink("mailto:" + url)
  42. if not state.md.validateLink(fullUrl):
  43. return False
  44. if not silent:
  45. token = state.push("link_open", "a", 1)
  46. token.attrs = {"href": fullUrl}
  47. token.markup = "autolink"
  48. token.info = "auto"
  49. token = state.push("text", "", 0)
  50. token.content = state.md.normalizeLinkText(url)
  51. token = state.push("link_close", "a", -1)
  52. token.markup = "autolink"
  53. token.info = "auto"
  54. state.pos += len(url) + 2
  55. return True
  56. return False