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