aboutsummaryrefslogtreecommitdiff
path: root/node_modules/prismjs/plugins/autolinker/prism-autolinker.js
blob: 3913c98adb375739698b7c23b06cd930a6359139 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
(function(){

if (
	typeof self !== 'undefined' && !self.Prism ||
	typeof global !== 'undefined' && !global.Prism
) {
	return;
}

var url = /\b([a-z]{3,7}:\/\/|tel:)[\w\-+%~/.:=&]+(?:\?[\w\-+%~/.:#=?&!$'()*,;]*)?(?:#[\w\-+%~/.:#=?&!$'()*,;]*)?/,
    email = /\b\S+@[\w.]+[a-z]{2}/,
    linkMd = /\[([^\]]+)]\(([^)]+)\)/,
    
	// Tokens that may contain URLs and emails
    candidates = ['comment', 'url', 'attr-value', 'string'];

Prism.plugins.autolinker = {
	processGrammar: function (grammar) {
		// Abort if grammar has already been processed
		if (!grammar || grammar['url-link']) {
			return;
		}
		Prism.languages.DFS(grammar, function (key, def, type) {
			if (candidates.indexOf(type) > -1 && Prism.util.type(def) !== 'Array') {
				if (!def.pattern) {
					def = this[key] = {
						pattern: def
					};
				}

				def.inside = def.inside || {};

				if (type == 'comment') {
					def.inside['md-link'] = linkMd;
				}
				if (type == 'attr-value') {
					Prism.languages.insertBefore('inside', 'punctuation', { 'url-link': url }, def);
				}
				else {
					def.inside['url-link'] = url;
				}

				def.inside['email-link'] = email;
			}
		});
		grammar['url-link'] = url;
		grammar['email-link'] = email;
	}
};

Prism.hooks.add('before-highlight', function(env) {
	Prism.plugins.autolinker.processGrammar(env.grammar);
});

Prism.hooks.add('wrap', function(env) {
	if (/-link$/.test(env.type)) {
		env.tag = 'a';
		
		var href = env.content;
		
		if (env.type == 'email-link' && href.indexOf('mailto:') != 0) {
			href = 'mailto:' + href;
		}
		else if (env.type == 'md-link') {
			// Markdown
			var match = env.content.match(linkMd);
			
			href = match[2];
			env.content = match[1];
		}
		
		env.attributes.href = href;
	}

	// Silently catch any error thrown by decodeURIComponent (#1186)
	try {
		env.content = decodeURIComponent(env.content);
	} catch(e) {}
});

})();