prism-autolinker.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. (function(){
  2. if (!self.Prism) {
  3. return;
  4. }
  5. var url = /\b([a-z]{3,7}:\/\/|tel:)[\w\-+%~/.:#=?&]+/,
  6. email = /\b\S+@[\w.]+[a-z]{2}/,
  7. linkMd = /\[([^\]]+)]\(([^)]+)\)/,
  8. // Tokens that may contain URLs and emails
  9. candidates = ['comment', 'url', 'attr-value', 'string'];
  10. for (var language in Prism.languages) {
  11. var tokens = Prism.languages[language];
  12. Prism.languages.DFS(tokens, function (key, def, type) {
  13. if (candidates.indexOf(type) > -1 && Prism.util.type(def) !== 'Array') {
  14. if (!def.pattern) {
  15. def = this[key] = {
  16. pattern: def
  17. };
  18. }
  19. def.inside = def.inside || {};
  20. if (type == 'comment') {
  21. def.inside['md-link'] = linkMd;
  22. }
  23. if (type == 'attr-value') {
  24. Prism.languages.insertBefore('inside', 'punctuation', { 'url-link': url }, def);
  25. }
  26. else {
  27. def.inside['url-link'] = url;
  28. }
  29. def.inside['email-link'] = email;
  30. }
  31. });
  32. tokens['url-link'] = url;
  33. tokens['email-link'] = email;
  34. }
  35. Prism.hooks.add('wrap', function(env) {
  36. if (/-link$/.test(env.type)) {
  37. env.tag = 'a';
  38. var href = env.content;
  39. if (env.type == 'email-link' && href.indexOf('mailto:') != 0) {
  40. href = 'mailto:' + href;
  41. }
  42. else if (env.type == 'md-link') {
  43. // Markdown
  44. var match = env.content.match(linkMd);
  45. href = match[2];
  46. env.content = match[1];
  47. }
  48. env.attributes.href = href;
  49. }
  50. });
  51. })();