summaryrefslogtreecommitdiffstats
path: root/data/resources/prism/plugins/data-uri-highlight/prism-data-uri-highlight.jsin
blob: 7ff8d1fd5fca72f112fe75bc00d8b66d63928df6 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
(function () {

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

	var autoLinkerProcess = function (grammar) {
		if (Prism.plugins.autolinker) {
			Prism.plugins.autolinker.processGrammar(grammar);
		}
		return grammar;
	};
	var dataURI = {
		pattern: /(.)\bdata:[^\/]+\/[^,]+,(?:(?!\1)[\s\S]|\\\1)+(?=\1)/,
		lookbehind: true,
		inside: {
			'language-css': {
				pattern: /(data:[^\/]+\/(?:[^+,]+\+)?css,)[\s\S]+/,
				lookbehind: true
			},
			'language-javascript': {
				pattern: /(data:[^\/]+\/(?:[^+,]+\+)?javascript,)[\s\S]+/,
				lookbehind: true
			},
			'language-json': {
				pattern: /(data:[^\/]+\/(?:[^+,]+\+)?json,)[\s\S]+/,
				lookbehind: true
			},
			'language-markup': {
				pattern: /(data:[^\/]+\/(?:[^+,]+\+)?(?:html|xml),)[\s\S]+/,
				lookbehind: true
			}
		}
	};

	// Tokens that may contain URLs
	var candidates = ['url', 'attr-value', 'string'];

	Prism.plugins.dataURIHighlight = {
		processGrammar: function (grammar) {
			// Abort if grammar has already been processed
			if (!grammar || grammar['data-uri']) {
				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 == 'attr-value') {
						Prism.languages.insertBefore('inside', def.inside['url-link'] ? 'url-link' : 'punctuation', {
							'data-uri': dataURI
						}, def);
					}
					else {
						if (def.inside['url-link']) {
							Prism.languages.insertBefore('inside', 'url-link', {
								'data-uri': dataURI
							}, def);
						} else {
							def.inside['data-uri'] = dataURI;
						}
					}
				}
			});
			grammar['data-uri'] = dataURI;
		}
	};

	Prism.hooks.add('before-highlight', function (env) {
		// Prepare the needed grammars for this code block
		if (dataURI.pattern.test(env.code)) {
			for (var p in dataURI.inside) {
				if (dataURI.inside.hasOwnProperty(p)) {
					if (!dataURI.inside[p].inside && dataURI.inside[p].pattern.test(env.code)) {
						var lang = p.match(/^language-(.+)/)[1];
						if (Prism.languages[lang]) {
							dataURI.inside[p].inside = {
								rest: autoLinkerProcess(Prism.languages[lang])
							};
						}
					}
				}
			}
		}

		Prism.plugins.dataURIHighlight.processGrammar(env.grammar);
	});
}());