autolink.mjs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Process autolinks '<protocol:...>'
  2. /* eslint max-len:0 */
  3. const EMAIL_RE = /^([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])?)*)$/
  4. /* eslint-disable-next-line no-control-regex */
  5. const AUTOLINK_RE = /^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/
  6. export default function autolink (state, silent) {
  7. let pos = state.pos
  8. if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false }
  9. const start = state.pos
  10. const max = state.posMax
  11. for (;;) {
  12. if (++pos >= max) return false
  13. const ch = state.src.charCodeAt(pos)
  14. if (ch === 0x3C /* < */) return false
  15. if (ch === 0x3E /* > */) break
  16. }
  17. const url = state.src.slice(start + 1, pos)
  18. if (AUTOLINK_RE.test(url)) {
  19. const fullUrl = state.md.normalizeLink(url)
  20. if (!state.md.validateLink(fullUrl)) { return false }
  21. if (!silent) {
  22. const token_o = state.push('link_open', 'a', 1)
  23. token_o.attrs = [['href', fullUrl]]
  24. token_o.markup = 'autolink'
  25. token_o.info = 'auto'
  26. const token_t = state.push('text', '', 0)
  27. token_t.content = state.md.normalizeLinkText(url)
  28. const token_c = state.push('link_close', 'a', -1)
  29. token_c.markup = 'autolink'
  30. token_c.info = 'auto'
  31. }
  32. state.pos += url.length + 2
  33. return true
  34. }
  35. if (EMAIL_RE.test(url)) {
  36. const fullUrl = state.md.normalizeLink('mailto:' + url)
  37. if (!state.md.validateLink(fullUrl)) { return false }
  38. if (!silent) {
  39. const token_o = state.push('link_open', 'a', 1)
  40. token_o.attrs = [['href', fullUrl]]
  41. token_o.markup = 'autolink'
  42. token_o.info = 'auto'
  43. const token_t = state.push('text', '', 0)
  44. token_t.content = state.md.normalizeLinkText(url)
  45. const token_c = state.push('link_close', 'a', -1)
  46. token_c.markup = 'autolink'
  47. token_c.info = 'auto'
  48. }
  49. state.pos += url.length + 2
  50. return true
  51. }
  52. return false
  53. }