autoLinks.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // url allowed chars [a-z\d_.~:/?#[]@!$&'()*+,;=-]
  2. var simpleURLRegex = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+)()(?=\s|$)(?!["<>])/gi,
  3. simpleURLRegex2 = /\b(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?()]?)(?=\s|$)(?!["<>])/gi,
  4. //simpleURLRegex3 = /\b(((https?|ftp):\/\/|www\.)[a-z\d.-]+\.[a-z\d_.~:/?#\[\]@!$&'()*+,;=-]+?)([.!?()]?)(?=\s|$)(?!["<>])/gi,
  5. delimUrlRegex = /<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)>/gi,
  6. simpleMailRegex = /(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gmi,
  7. delimMailRegex = /<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
  8. replaceLink = function (options) {
  9. 'use strict';
  10. return function (wm, link, m2, m3, trailingPunctuation) {
  11. var lnkTxt = link,
  12. append = '';
  13. if (/^www\./i.test(link)) {
  14. link = link.replace(/^www\./i, 'http://www.');
  15. }
  16. if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {
  17. append = trailingPunctuation;
  18. }
  19. return '<a href="' + link + '">' + lnkTxt + '</a>' + append;
  20. };
  21. },
  22. replaceMail = function (options, globals) {
  23. 'use strict';
  24. return function (wholeMatch, b, mail) {
  25. var href = 'mailto:';
  26. b = b || '';
  27. mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);
  28. if (options.encodeEmails) {
  29. href = showdown.helper.encodeEmailAddress(href + mail);
  30. mail = showdown.helper.encodeEmailAddress(mail);
  31. } else {
  32. href = href + mail;
  33. }
  34. return b + '<a href="' + href + '">' + mail + '</a>';
  35. };
  36. };
  37. showdown.subParser('autoLinks', function (text, options, globals) {
  38. 'use strict';
  39. text = globals.converter._dispatch('autoLinks.before', text, options, globals);
  40. text = text.replace(delimUrlRegex, replaceLink(options));
  41. text = text.replace(delimMailRegex, replaceMail(options, globals));
  42. text = globals.converter._dispatch('autoLinks.after', text, options, globals);
  43. return text;
  44. });
  45. showdown.subParser('simplifiedAutoLinks', function (text, options, globals) {
  46. 'use strict';
  47. if (!options.simplifiedAutoLink) {
  48. return text;
  49. }
  50. text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);
  51. if (options.excludeTrailingPunctuationFromURLs) {
  52. text = text.replace(simpleURLRegex2, replaceLink(options));
  53. } else {
  54. text = text.replace(simpleURLRegex, replaceLink(options));
  55. }
  56. text = text.replace(simpleMailRegex, replaceMail(options, globals));
  57. text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);
  58. return text;
  59. });