linkify.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Process links like https://example.org/
  2. 'use strict';
  3. // RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
  4. var SCHEME_RE = /(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;
  5. module.exports = function linkify(state, silent) {
  6. var pos, max, match, proto, link, url, fullUrl, token;
  7. if (!state.md.options.linkify) return false;
  8. if (state.linkLevel > 0) return false;
  9. pos = state.pos;
  10. max = state.posMax;
  11. if (pos + 3 > max) return false;
  12. if (state.src.charCodeAt(pos) !== 0x3A/* : */) return false;
  13. if (state.src.charCodeAt(pos + 1) !== 0x2F/* / */) return false;
  14. if (state.src.charCodeAt(pos + 2) !== 0x2F/* / */) return false;
  15. match = state.pending.match(SCHEME_RE);
  16. if (!match) return false;
  17. proto = match[1];
  18. link = state.md.linkify.matchAtStart(state.src.slice(pos - proto.length));
  19. if (!link) return false;
  20. url = link.url;
  21. // disallow '*' at the end of the link (conflicts with emphasis)
  22. url = url.replace(/\*+$/, '');
  23. fullUrl = state.md.normalizeLink(url);
  24. if (!state.md.validateLink(fullUrl)) return false;
  25. if (!silent) {
  26. state.pending = state.pending.slice(0, -proto.length);
  27. token = state.push('link_open', 'a', 1);
  28. token.attrs = [ [ 'href', fullUrl ] ];
  29. token.markup = 'linkify';
  30. token.info = 'auto';
  31. token = state.push('text', '', 0);
  32. token.content = state.md.normalizeLinkText(url);
  33. token = state.push('link_close', 'a', -1);
  34. token.markup = 'linkify';
  35. token.info = 'auto';
  36. }
  37. state.pos += url.length - proto.length;
  38. return true;
  39. };