UNPKG

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