forked from PrismJS/prism
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prism-diff-highlight.js
83 lines (66 loc) · 2.47 KB
/
prism-diff-highlight.js
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
(function () {
if (typeof Prism === 'undefined' || !Prism.languages['diff']) {
return;
}
var LANGUAGE_REGEX = /diff-([\w-]+)/i;
var HTML_TAG = /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/gi;
//this will match a line plus the line break while ignoring the line breaks HTML tags may contain.
var HTML_LINE = RegExp(/(?:__|[^\r\n<])*(?:\r\n?|\n|(?:__|[^\r\n<])(?![^\r\n]))/.source.replace(/__/g, function () { return HTML_TAG.source; }), 'gi');
var PREFIXES = Prism.languages.diff.PREFIXES;
Prism.hooks.add('before-sanity-check', function (env) {
var lang = env.language;
if (LANGUAGE_REGEX.test(lang) && !env.grammar) {
env.grammar = Prism.languages[lang] = Prism.languages['diff'];
}
});
Prism.hooks.add('before-tokenize', function (env) {
var lang = env.language;
if (LANGUAGE_REGEX.test(lang) && !Prism.languages[lang]) {
Prism.languages[lang] = Prism.languages['diff'];
}
});
Prism.hooks.add('wrap', function (env) {
var diffLanguage, diffGrammar;
if (env.language !== 'diff') {
var langMatch = LANGUAGE_REGEX.exec(env.language);
if (!langMatch) {
return; // not a language specific diff
}
diffLanguage = langMatch[1];
diffGrammar = Prism.languages[diffLanguage];
}
// one of the diff tokens without any nested tokens
if (env.type in PREFIXES) {
/** @type {string} */
var content = env.content.replace(HTML_TAG, ''); // remove all HTML tags
/** @type {string} */
var decoded = content.replace(/</g, '<').replace(/&/g, '&');
// remove any one-character prefix
var code = decoded.replace(/(^|[\r\n])./g, '$1');
// highlight, if possible
var highlighted;
if (diffGrammar) {
highlighted = Prism.highlight(code, diffGrammar, diffLanguage);
} else {
highlighted = Prism.util.encode(code);
}
// get the HTML source of the prefix token
var prefixToken = new Prism.Token('prefix', PREFIXES[env.type], [/\w+/.exec(env.type)[0]]);
var prefix = Prism.Token.stringify(prefixToken, env.language);
// add prefix
var lines = [], m;
HTML_LINE.lastIndex = 0;
while (m = HTML_LINE.exec(highlighted)) {
lines.push(prefix + m[0]);
}
if (/(?:^|[\r\n]).$/.test(decoded)) {
// because both "+a\n+" and "+a\n" will map to "a\n" after the line prefixes are removed
lines.push(prefix);
}
env.content = lines.join('');
if (diffGrammar) {
env.classes.push('language-' + diffLanguage);
}
}
});
}());