UNPKG

2.53 kBJavaScriptView Raw
1(function () {
2
3 if (typeof Prism === 'undefined' || !Prism.languages['diff']) {
4 return;
5 }
6
7
8 var LANGUAGE_REGEX = /diff-([\w-]+)/i;
9 var HTML_TAG = /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/gi;
10 //this will match a line plus the line break while ignoring the line breaks HTML tags may contain.
11 var HTML_LINE = RegExp(/(?:__|[^\r\n<])*(?:\r\n?|\n|(?:__|[^\r\n<])(?![^\r\n]))/.source.replace(/__/g, function () { return HTML_TAG.source; }), 'gi');
12
13 var PREFIXES = Prism.languages.diff.PREFIXES;
14
15
16 Prism.hooks.add('before-sanity-check', function (env) {
17 var lang = env.language;
18 if (LANGUAGE_REGEX.test(lang) && !env.grammar) {
19 env.grammar = Prism.languages[lang] = Prism.languages['diff'];
20 }
21 });
22 Prism.hooks.add('before-tokenize', function (env) {
23 var lang = env.language;
24 if (LANGUAGE_REGEX.test(lang) && !Prism.languages[lang]) {
25 Prism.languages[lang] = Prism.languages['diff'];
26 }
27 });
28
29 Prism.hooks.add('wrap', function (env) {
30 var diffLanguage, diffGrammar;
31
32 if (env.language !== 'diff') {
33 var langMatch = LANGUAGE_REGEX.exec(env.language);
34 if (!langMatch) {
35 return; // not a language specific diff
36 }
37
38 diffLanguage = langMatch[1];
39 diffGrammar = Prism.languages[diffLanguage];
40 }
41
42 // one of the diff tokens without any nested tokens
43 if (env.type in PREFIXES) {
44 /** @type {string} */
45 var content = env.content.replace(HTML_TAG, ''); // remove all HTML tags
46
47 /** @type {string} */
48 var decoded = content.replace(/&lt;/g, '<').replace(/&amp;/g, '&');
49
50 // remove any one-character prefix
51 var code = decoded.replace(/(^|[\r\n])./g, '$1');
52
53 // highlight, if possible
54 var highlighted;
55 if (diffGrammar) {
56 highlighted = Prism.highlight(code, diffGrammar, diffLanguage);
57 } else {
58 highlighted = Prism.util.encode(code);
59 }
60
61 // get the HTML source of the prefix token
62 var prefixToken = new Prism.Token('prefix', PREFIXES[env.type], [/\w+/.exec(env.type)[0]]);
63 var prefix = Prism.Token.stringify(prefixToken, env.language);
64
65 // add prefix
66 var lines = [], m;
67 HTML_LINE.lastIndex = 0;
68 while (m = HTML_LINE.exec(highlighted)) {
69 lines.push(prefix + m[0]);
70 }
71 if (/(?:^|[\r\n]).$/.test(decoded)) {
72 // because both "+a\n+" and "+a\n" will map to "a\n" after the line prefixes are removed
73 lines.push(prefix);
74 }
75 env.content = lines.join('');
76
77 if (diffGrammar) {
78 env.classes.push('language-' + diffLanguage);
79 }
80 }
81 });
82
83}());