UNPKG

1.74 kBJavaScriptView Raw
1(function () {
2
3 if (
4 typeof self !== 'undefined' && !self.Prism ||
5 typeof global !== 'undefined' && !global.Prism
6 ) {
7 return;
8 }
9
10
11 var invisibles = {
12 'tab': /\t/,
13 'crlf': /\r\n/,
14 'lf': /\n/,
15 'cr': /\r/,
16 'space': / /
17 };
18
19
20 /**
21 * Handles the recursive calling of `addInvisibles` for one token.
22 *
23 * @param {Object|Array} tokens The grammar or array which contains the token.
24 * @param {string|number} name The name or index of the token in `tokens`.
25 */
26 function handleToken(tokens, name) {
27 var value = tokens[name];
28
29 var type = Prism.util.type(value);
30 switch (type) {
31 case 'RegExp':
32 var inside = {};
33 tokens[name] = {
34 pattern: value,
35 inside: inside
36 };
37 addInvisibles(inside);
38 break;
39
40 case 'Array':
41 for (var i = 0, l = value.length; i < l; i++) {
42 handleToken(value, i);
43 }
44 break;
45
46 default: // 'Object'
47 var inside = value.inside || (value.inside = {});
48 addInvisibles(inside);
49 break;
50 }
51 }
52
53 /**
54 * Recursively adds patterns to match invisible characters to the given grammar (if not added already).
55 *
56 * @param {Object} grammar
57 */
58 function addInvisibles(grammar) {
59 if (!grammar || grammar['tab']) {
60 return;
61 }
62
63 // assign invisibles here to "mark" the grammar in case of self references
64 for (var name in invisibles) {
65 if (invisibles.hasOwnProperty(name)) {
66 grammar[name] = invisibles[name];
67 }
68 }
69
70 for (var name in grammar) {
71 if (grammar.hasOwnProperty(name) && !invisibles[name]) {
72 if (name === 'rest') {
73 addInvisibles(grammar['rest']);
74 } else {
75 handleToken(grammar, name);
76 }
77 }
78 }
79 }
80
81 Prism.hooks.add('before-highlight', function (env) {
82 addInvisibles(env.grammar);
83 });
84})();