autolink.js 1.9 KB

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