prism-autolinker.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. (function(){
  2. if (
  3. typeof self !== 'undefined' && !self.Prism ||
  4. typeof global !== 'undefined' && !global.Prism
  5. ) {
  6. return;
  7. }
  8. var url = /\b([a-z]{3,7}:\/\/|tel:)[\w\-+%~/.:=&@]+(?:\?[\w\-+%~/.:=?&!$'()*,;@]*)?(?:#[\w\-+%~/.:#=?&!$'()*,;@]*)?/,
  9. email = /\b\S+@[\w.]+[a-z]{2}/,
  10. linkMd = /\[([^\]]+)]\(([^)]+)\)/,
  11. // Tokens that may contain URLs and emails
  12. candidates = ['comment', 'url', 'attr-value', 'string'];
  13. Prism.plugins.autolinker = {
  14. processGrammar: function (grammar) {
  15. // Abort if grammar has already been processed
  16. if (!grammar || grammar['url-link']) {
  17. return;
  18. }
  19. Prism.languages.DFS(grammar, function (key, def, type) {
  20. if (candidates.indexOf(type) > -1 && !Array.isArray(def)) {
  21. if (!def.pattern) {
  22. def = this[key] = {
  23. pattern: def
  24. };
  25. }
  26. def.inside = def.inside || {};
  27. if (type == 'comment') {
  28. def.inside['md-link'] = linkMd;
  29. }
  30. if (type == 'attr-value') {
  31. Prism.languages.insertBefore('inside', 'punctuation', { 'url-link': url }, def);
  32. }
  33. else {
  34. def.inside['url-link'] = url;
  35. }
  36. def.inside['email-link'] = email;
  37. }
  38. });
  39. grammar['url-link'] = url;
  40. grammar['email-link'] = email;
  41. }
  42. };
  43. Prism.hooks.add('before-highlight', function(env) {
  44. Prism.plugins.autolinker.processGrammar(env.grammar);
  45. });
  46. Prism.hooks.add('wrap', function(env) {
  47. if (/-link$/.test(env.type)) {
  48. env.tag = 'a';
  49. var href = env.content;
  50. if (env.type == 'email-link' && href.indexOf('mailto:') != 0) {
  51. href = 'mailto:' + href;
  52. }
  53. else if (env.type == 'md-link') {
  54. // Markdown
  55. var match = env.content.match(linkMd);
  56. href = match[2];
  57. env.content = match[1];
  58. }
  59. env.attributes.href = href;
  60. // Silently catch any error thrown by decodeURIComponent (#1186)
  61. try {
  62. env.content = decodeURIComponent(env.content);
  63. } catch(e) {}
  64. }
  65. });
  66. })();