UNPKG

34.8 kBJavaScriptView Raw
1/// <reference lib="WebWorker"/>
2
3var _self = (typeof window !== 'undefined')
4 ? window // if in browser
5 : (
6 (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
7 ? self // if in worker
8 : {} // if in node js
9 );
10
11/**
12 * Prism: Lightweight, robust, elegant syntax highlighting
13 *
14 * @license MIT <https://opensource.org/licenses/MIT>
15 * @author Lea Verou <https://lea.verou.me>
16 * @namespace
17 * @public
18 */
19var Prism = (function (_self){
20
21// Private helper vars
22var lang = /\blang(?:uage)?-([\w-]+)\b/i;
23var uniqueId = 0;
24
25
26var _ = {
27 /**
28 * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
29 * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
30 * additional languages or plugins yourself.
31 *
32 * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
33 *
34 * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
35 * empty Prism object into the global scope before loading the Prism script like this:
36 *
37 * ```js
38 * window.Prism = window.Prism || {};
39 * Prism.manual = true;
40 * // add a new <script> to load Prism's script
41 * ```
42 *
43 * @default false
44 * @type {boolean}
45 * @memberof Prism
46 * @public
47 */
48 manual: _self.Prism && _self.Prism.manual,
49 disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
50
51 /**
52 * A namespace for utility methods.
53 *
54 * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
55 * change or disappear at any time.
56 *
57 * @namespace
58 * @memberof Prism
59 */
60 util: {
61 encode: function encode(tokens) {
62 if (tokens instanceof Token) {
63 return new Token(tokens.type, encode(tokens.content), tokens.alias);
64 } else if (Array.isArray(tokens)) {
65 return tokens.map(encode);
66 } else {
67 return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
68 }
69 },
70
71 /**
72 * Returns the name of the type of the given value.
73 *
74 * @param {any} o
75 * @returns {string}
76 * @example
77 * type(null) === 'Null'
78 * type(undefined) === 'Undefined'
79 * type(123) === 'Number'
80 * type('foo') === 'String'
81 * type(true) === 'Boolean'
82 * type([1, 2]) === 'Array'
83 * type({}) === 'Object'
84 * type(String) === 'Function'
85 * type(/abc+/) === 'RegExp'
86 */
87 type: function (o) {
88 return Object.prototype.toString.call(o).slice(8, -1);
89 },
90
91 /**
92 * Returns a unique number for the given object. Later calls will still return the same number.
93 *
94 * @param {Object} obj
95 * @returns {number}
96 */
97 objId: function (obj) {
98 if (!obj['__id']) {
99 Object.defineProperty(obj, '__id', { value: ++uniqueId });
100 }
101 return obj['__id'];
102 },
103
104 /**
105 * Creates a deep clone of the given object.
106 *
107 * The main intended use of this function is to clone language definitions.
108 *
109 * @param {T} o
110 * @param {Record<number, any>} [visited]
111 * @returns {T}
112 * @template T
113 */
114 clone: function deepClone(o, visited) {
115 visited = visited || {};
116
117 var clone, id;
118 switch (_.util.type(o)) {
119 case 'Object':
120 id = _.util.objId(o);
121 if (visited[id]) {
122 return visited[id];
123 }
124 clone = /** @type {Record<string, any>} */ ({});
125 visited[id] = clone;
126
127 for (var key in o) {
128 if (o.hasOwnProperty(key)) {
129 clone[key] = deepClone(o[key], visited);
130 }
131 }
132
133 return /** @type {any} */ (clone);
134
135 case 'Array':
136 id = _.util.objId(o);
137 if (visited[id]) {
138 return visited[id];
139 }
140 clone = [];
141 visited[id] = clone;
142
143 (/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) {
144 clone[i] = deepClone(v, visited);
145 });
146
147 return /** @type {any} */ (clone);
148
149 default:
150 return o;
151 }
152 },
153
154 /**
155 * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
156 *
157 * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
158 *
159 * @param {Element} element
160 * @returns {string}
161 */
162 getLanguage: function (element) {
163 while (element && !lang.test(element.className)) {
164 element = element.parentElement;
165 }
166 if (element) {
167 return (element.className.match(lang) || [, 'none'])[1].toLowerCase();
168 }
169 return 'none';
170 },
171
172 /**
173 * Returns the script element that is currently executing.
174 *
175 * This does __not__ work for line script element.
176 *
177 * @returns {HTMLScriptElement | null}
178 */
179 currentScript: function () {
180 if (typeof document === 'undefined') {
181 return null;
182 }
183 if ('currentScript' in document && 1 < 2 /* hack to trip TS' flow analysis */) {
184 return /** @type {any} */ (document.currentScript);
185 }
186
187 // IE11 workaround
188 // we'll get the src of the current script by parsing IE11's error stack trace
189 // this will not work for inline scripts
190
191 try {
192 throw new Error();
193 } catch (err) {
194 // Get file src url from stack. Specifically works with the format of stack traces in IE.
195 // A stack will look like this:
196 //
197 // Error
198 // at _.util.currentScript (http://localhost/components/prism-core.js:119:5)
199 // at Global code (http://localhost/components/prism-core.js:606:1)
200
201 var src = (/at [^(\r\n]*\((.*):.+:.+\)$/i.exec(err.stack) || [])[1];
202 if (src) {
203 var scripts = document.getElementsByTagName('script');
204 for (var i in scripts) {
205 if (scripts[i].src == src) {
206 return scripts[i];
207 }
208 }
209 }
210 return null;
211 }
212 },
213
214 /**
215 * Returns whether a given class is active for `element`.
216 *
217 * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
218 * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
219 * given class is just the given class with a `no-` prefix.
220 *
221 * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
222 * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
223 * ancestors have the given class or the negated version of it, then the default activation will be returned.
224 *
225 * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
226 * version of it, the class is considered active.
227 *
228 * @param {Element} element
229 * @param {string} className
230 * @param {boolean} [defaultActivation=false]
231 * @returns {boolean}
232 */
233 isActive: function (element, className, defaultActivation) {
234 var no = 'no-' + className;
235
236 while (element) {
237 var classList = element.classList;
238 if (classList.contains(className)) {
239 return true;
240 }
241 if (classList.contains(no)) {
242 return false;
243 }
244 element = element.parentElement;
245 }
246 return !!defaultActivation;
247 }
248 },
249
250 /**
251 * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
252 *
253 * @namespace
254 * @memberof Prism
255 * @public
256 */
257 languages: {
258 /**
259 * Creates a deep copy of the language with the given id and appends the given tokens.
260 *
261 * If a token in `redef` also appears in the copied language, then the existing token in the copied language
262 * will be overwritten at its original position.
263 *
264 * ## Best practices
265 *
266 * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
267 * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
268 * understand the language definition because, normally, the order of tokens matters in Prism grammars.
269 *
270 * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
271 * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
272 *
273 * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
274 * @param {Grammar} redef The new tokens to append.
275 * @returns {Grammar} The new language created.
276 * @public
277 * @example
278 * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
279 * // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
280 * // at its original position
281 * 'comment': { ... },
282 * // CSS doesn't have a 'color' token, so this token will be appended
283 * 'color': /\b(?:red|green|blue)\b/
284 * });
285 */
286 extend: function (id, redef) {
287 var lang = _.util.clone(_.languages[id]);
288
289 for (var key in redef) {
290 lang[key] = redef[key];
291 }
292
293 return lang;
294 },
295
296 /**
297 * Inserts tokens _before_ another token in a language definition or any other grammar.
298 *
299 * ## Usage
300 *
301 * This helper method makes it easy to modify existing languages. For example, the CSS language definition
302 * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
303 * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
304 * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
305 * this:
306 *
307 * ```js
308 * Prism.languages.markup.style = {
309 * // token
310 * };
311 * ```
312 *
313 * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
314 * before existing tokens. For the CSS example above, you would use it like this:
315 *
316 * ```js
317 * Prism.languages.insertBefore('markup', 'cdata', {
318 * 'style': {
319 * // token
320 * }
321 * });
322 * ```
323 *
324 * ## Special cases
325 *
326 * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
327 * will be ignored.
328 *
329 * This behavior can be used to insert tokens after `before`:
330 *
331 * ```js
332 * Prism.languages.insertBefore('markup', 'comment', {
333 * 'comment': Prism.languages.markup.comment,
334 * // tokens after 'comment'
335 * });
336 * ```
337 *
338 * ## Limitations
339 *
340 * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
341 * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
342 * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
343 * deleting properties which is necessary to insert at arbitrary positions.
344 *
345 * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
346 * Instead, it will create a new object and replace all references to the target object with the new one. This
347 * can be done without temporarily deleting properties, so the iteration order is well-defined.
348 *
349 * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
350 * you hold the target object in a variable, then the value of the variable will not change.
351 *
352 * ```js
353 * var oldMarkup = Prism.languages.markup;
354 * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
355 *
356 * assert(oldMarkup !== Prism.languages.markup);
357 * assert(newMarkup === Prism.languages.markup);
358 * ```
359 *
360 * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
361 * object to be modified.
362 * @param {string} before The key to insert before.
363 * @param {Grammar} insert An object containing the key-value pairs to be inserted.
364 * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
365 * object to be modified.
366 *
367 * Defaults to `Prism.languages`.
368 * @returns {Grammar} The new grammar object.
369 * @public
370 */
371 insertBefore: function (inside, before, insert, root) {
372 root = root || /** @type {any} */ (_.languages);
373 var grammar = root[inside];
374 /** @type {Grammar} */
375 var ret = {};
376
377 for (var token in grammar) {
378 if (grammar.hasOwnProperty(token)) {
379
380 if (token == before) {
381 for (var newToken in insert) {
382 if (insert.hasOwnProperty(newToken)) {
383 ret[newToken] = insert[newToken];
384 }
385 }
386 }
387
388 // Do not insert token which also occur in insert. See #1525
389 if (!insert.hasOwnProperty(token)) {
390 ret[token] = grammar[token];
391 }
392 }
393 }
394
395 var old = root[inside];
396 root[inside] = ret;
397
398 // Update references in other language definitions
399 _.languages.DFS(_.languages, function(key, value) {
400 if (value === old && key != inside) {
401 this[key] = ret;
402 }
403 });
404
405 return ret;
406 },
407
408 // Traverse a language definition with Depth First Search
409 DFS: function DFS(o, callback, type, visited) {
410 visited = visited || {};
411
412 var objId = _.util.objId;
413
414 for (var i in o) {
415 if (o.hasOwnProperty(i)) {
416 callback.call(o, i, o[i], type || i);
417
418 var property = o[i],
419 propertyType = _.util.type(property);
420
421 if (propertyType === 'Object' && !visited[objId(property)]) {
422 visited[objId(property)] = true;
423 DFS(property, callback, null, visited);
424 }
425 else if (propertyType === 'Array' && !visited[objId(property)]) {
426 visited[objId(property)] = true;
427 DFS(property, callback, i, visited);
428 }
429 }
430 }
431 }
432 },
433
434 plugins: {},
435
436 /**
437 * This is the most high-level function in Prism’s API.
438 * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
439 * each one of them.
440 *
441 * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
442 *
443 * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
444 * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
445 * @memberof Prism
446 * @public
447 */
448 highlightAll: function(async, callback) {
449 _.highlightAllUnder(document, async, callback);
450 },
451
452 /**
453 * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
454 * {@link Prism.highlightElement} on each one of them.
455 *
456 * The following hooks will be run:
457 * 1. `before-highlightall`
458 * 2. All hooks of {@link Prism.highlightElement} for each element.
459 *
460 * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
461 * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
462 * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
463 * @memberof Prism
464 * @public
465 */
466 highlightAllUnder: function(container, async, callback) {
467 var env = {
468 callback: callback,
469 container: container,
470 selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
471 };
472
473 _.hooks.run('before-highlightall', env);
474
475 env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
476
477 _.hooks.run('before-all-elements-highlight', env);
478
479 for (var i = 0, element; element = env.elements[i++];) {
480 _.highlightElement(element, async === true, env.callback);
481 }
482 },
483
484 /**
485 * Highlights the code inside a single element.
486 *
487 * The following hooks will be run:
488 * 1. `before-sanity-check`
489 * 2. `before-highlight`
490 * 3. All hooks of {@link Prism.highlight}. These hooks will only be run by the current worker if `async` is `true`.
491 * 4. `before-insert`
492 * 5. `after-highlight`
493 * 6. `complete`
494 *
495 * @param {Element} element The element containing the code.
496 * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
497 * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
498 * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
499 * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
500 *
501 * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
502 * asynchronous highlighting to work. You can build your own bundle on the
503 * [Download page](https://prismjs.com/download.html).
504 * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
505 * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
506 * @memberof Prism
507 * @public
508 */
509 highlightElement: function(element, async, callback) {
510 // Find language
511 var language = _.util.getLanguage(element);
512 var grammar = _.languages[language];
513
514 // Set language on the element, if not present
515 element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
516
517 // Set language on the parent, for styling
518 var parent = element.parentElement;
519 if (parent && parent.nodeName.toLowerCase() === 'pre') {
520 parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
521 }
522
523 var code = element.textContent;
524
525 var env = {
526 element: element,
527 language: language,
528 grammar: grammar,
529 code: code
530 };
531
532 function insertHighlightedCode(highlightedCode) {
533 env.highlightedCode = highlightedCode;
534
535 _.hooks.run('before-insert', env);
536
537 env.element.innerHTML = env.highlightedCode;
538
539 _.hooks.run('after-highlight', env);
540 _.hooks.run('complete', env);
541 callback && callback.call(env.element);
542 }
543
544 _.hooks.run('before-sanity-check', env);
545
546 if (!env.code) {
547 _.hooks.run('complete', env);
548 callback && callback.call(env.element);
549 return;
550 }
551
552 _.hooks.run('before-highlight', env);
553
554 if (!env.grammar) {
555 insertHighlightedCode(_.util.encode(env.code));
556 return;
557 }
558
559 if (async && _self.Worker) {
560 var worker = new Worker(_.filename);
561
562 worker.onmessage = function(evt) {
563 insertHighlightedCode(evt.data);
564 };
565
566 worker.postMessage(JSON.stringify({
567 language: env.language,
568 code: env.code,
569 immediateClose: true
570 }));
571 }
572 else {
573 insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
574 }
575 },
576
577 /**
578 * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
579 * and the language definitions to use, and returns a string with the HTML produced.
580 *
581 * The following hooks will be run:
582 * 1. `before-tokenize`
583 * 2. `after-tokenize`
584 * 3. `wrap`: On each {@link Token}.
585 *
586 * @param {string} text A string with the code to be highlighted.
587 * @param {Grammar} grammar An object containing the tokens to use.
588 *
589 * Usually a language definition like `Prism.languages.markup`.
590 * @param {string} language The name of the language definition passed to `grammar`.
591 * @returns {string} The highlighted HTML.
592 * @memberof Prism
593 * @public
594 * @example
595 * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
596 */
597 highlight: function (text, grammar, language) {
598 var env = {
599 code: text,
600 grammar: grammar,
601 language: language
602 };
603 _.hooks.run('before-tokenize', env);
604 env.tokens = _.tokenize(env.code, env.grammar);
605 _.hooks.run('after-tokenize', env);
606 return Token.stringify(_.util.encode(env.tokens), env.language);
607 },
608
609 /**
610 * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
611 * and the language definitions to use, and returns an array with the tokenized code.
612 *
613 * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
614 *
615 * This method could be useful in other contexts as well, as a very crude parser.
616 *
617 * @param {string} text A string with the code to be highlighted.
618 * @param {Grammar} grammar An object containing the tokens to use.
619 *
620 * Usually a language definition like `Prism.languages.markup`.
621 * @returns {TokenStream} An array of strings and tokens, a token stream.
622 * @memberof Prism
623 * @public
624 * @example
625 * let code = `var foo = 0;`;
626 * let tokens = Prism.tokenize(code, Prism.languages.javascript);
627 * tokens.forEach(token => {
628 * if (token instanceof Prism.Token && token.type === 'number') {
629 * console.log(`Found numeric literal: ${token.content}`);
630 * }
631 * });
632 */
633 tokenize: function(text, grammar) {
634 var rest = grammar.rest;
635 if (rest) {
636 for (var token in rest) {
637 grammar[token] = rest[token];
638 }
639
640 delete grammar.rest;
641 }
642
643 var tokenList = new LinkedList();
644 addAfter(tokenList, tokenList.head, text);
645
646 matchGrammar(text, tokenList, grammar, tokenList.head, 0);
647
648 return toArray(tokenList);
649 },
650
651 /**
652 * @namespace
653 * @memberof Prism
654 * @public
655 */
656 hooks: {
657 all: {},
658
659 /**
660 * Adds the given callback to the list of callbacks for the given hook.
661 *
662 * The callback will be invoked when the hook it is registered for is run.
663 * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
664 *
665 * One callback function can be registered to multiple hooks and the same hook multiple times.
666 *
667 * @param {string} name The name of the hook.
668 * @param {HookCallback} callback The callback function which is given environment variables.
669 * @public
670 */
671 add: function (name, callback) {
672 var hooks = _.hooks.all;
673
674 hooks[name] = hooks[name] || [];
675
676 hooks[name].push(callback);
677 },
678
679 /**
680 * Runs a hook invoking all registered callbacks with the given environment variables.
681 *
682 * Callbacks will be invoked synchronously and in the order in which they were registered.
683 *
684 * @param {string} name The name of the hook.
685 * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
686 * @public
687 */
688 run: function (name, env) {
689 var callbacks = _.hooks.all[name];
690
691 if (!callbacks || !callbacks.length) {
692 return;
693 }
694
695 for (var i=0, callback; callback = callbacks[i++];) {
696 callback(env);
697 }
698 }
699 },
700
701 Token: Token
702};
703_self.Prism = _;
704
705
706// Typescript note:
707// The following can be used to import the Token type in JSDoc:
708//
709// @typedef {InstanceType<import("./prism-core")["Token"]>} Token
710
711/**
712 * Creates a new token.
713 *
714 * @param {string} type See {@link Token#type type}
715 * @param {string | TokenStream} content See {@link Token#content content}
716 * @param {string|string[]} [alias] The alias(es) of the token.
717 * @param {string} [matchedStr=""] A copy of the full string this token was created from.
718 * @class
719 * @global
720 * @public
721 */
722function Token(type, content, alias, matchedStr) {
723 /**
724 * The type of the token.
725 *
726 * This is usually the key of a pattern in a {@link Grammar}.
727 *
728 * @type {string}
729 * @see GrammarToken
730 * @public
731 */
732 this.type = type;
733 /**
734 * The strings or tokens contained by this token.
735 *
736 * This will be a token stream if the pattern matched also defined an `inside` grammar.
737 *
738 * @type {string | TokenStream}
739 * @public
740 */
741 this.content = content;
742 /**
743 * The alias(es) of the token.
744 *
745 * @type {string|string[]}
746 * @see GrammarToken
747 * @public
748 */
749 this.alias = alias;
750 // Copy of the full string this token was created from
751 this.length = (matchedStr || '').length | 0;
752}
753
754/**
755 * A token stream is an array of strings and {@link Token Token} objects.
756 *
757 * Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
758 * them.
759 *
760 * 1. No adjacent strings.
761 * 2. No empty strings.
762 *
763 * The only exception here is the token stream that only contains the empty string and nothing else.
764 *
765 * @typedef {Array<string | Token>} TokenStream
766 * @global
767 * @public
768 */
769
770/**
771 * Converts the given token or token stream to an HTML representation.
772 *
773 * The following hooks will be run:
774 * 1. `wrap`: On each {@link Token}.
775 *
776 * @param {string | Token | TokenStream} o The token or token stream to be converted.
777 * @param {string} language The name of current language.
778 * @returns {string} The HTML representation of the token or token stream.
779 * @memberof Token
780 * @static
781 */
782Token.stringify = function stringify(o, language) {
783 if (typeof o == 'string') {
784 return o;
785 }
786 if (Array.isArray(o)) {
787 var s = '';
788 o.forEach(function (e) {
789 s += stringify(e, language);
790 });
791 return s;
792 }
793
794 var env = {
795 type: o.type,
796 content: stringify(o.content, language),
797 tag: 'span',
798 classes: ['token', o.type],
799 attributes: {},
800 language: language
801 };
802
803 var aliases = o.alias;
804 if (aliases) {
805 if (Array.isArray(aliases)) {
806 Array.prototype.push.apply(env.classes, aliases);
807 } else {
808 env.classes.push(aliases);
809 }
810 }
811
812 _.hooks.run('wrap', env);
813
814 var attributes = '';
815 for (var name in env.attributes) {
816 attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
817 }
818
819 return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
820};
821
822/**
823 * @param {string} text
824 * @param {LinkedList<string | Token>} tokenList
825 * @param {any} grammar
826 * @param {LinkedListNode<string | Token>} startNode
827 * @param {number} startPos
828 * @param {RematchOptions} [rematch]
829 * @returns {void}
830 * @private
831 *
832 * @typedef RematchOptions
833 * @property {string} cause
834 * @property {number} reach
835 */
836function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
837 for (var token in grammar) {
838 if (!grammar.hasOwnProperty(token) || !grammar[token]) {
839 continue;
840 }
841
842 var patterns = grammar[token];
843 patterns = Array.isArray(patterns) ? patterns : [patterns];
844
845 for (var j = 0; j < patterns.length; ++j) {
846 if (rematch && rematch.cause == token + ',' + j) {
847 return;
848 }
849
850 var patternObj = patterns[j],
851 inside = patternObj.inside,
852 lookbehind = !!patternObj.lookbehind,
853 greedy = !!patternObj.greedy,
854 lookbehindLength = 0,
855 alias = patternObj.alias;
856
857 if (greedy && !patternObj.pattern.global) {
858 // Without the global flag, lastIndex won't work
859 var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
860 patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
861 }
862
863 /** @type {RegExp} */
864 var pattern = patternObj.pattern || patternObj;
865
866 for ( // iterate the token list and keep track of the current token/string position
867 var currentNode = startNode.next, pos = startPos;
868 currentNode !== tokenList.tail;
869 pos += currentNode.value.length, currentNode = currentNode.next
870 ) {
871
872 if (rematch && pos >= rematch.reach) {
873 break;
874 }
875
876 var str = currentNode.value;
877
878 if (tokenList.length > text.length) {
879 // Something went terribly wrong, ABORT, ABORT!
880 return;
881 }
882
883 if (str instanceof Token) {
884 continue;
885 }
886
887 var removeCount = 1; // this is the to parameter of removeBetween
888
889 if (greedy && currentNode != tokenList.tail.prev) {
890 pattern.lastIndex = pos;
891 var match = pattern.exec(text);
892 if (!match) {
893 break;
894 }
895
896 var from = match.index + (lookbehind && match[1] ? match[1].length : 0);
897 var to = match.index + match[0].length;
898 var p = pos;
899
900 // find the node that contains the match
901 p += currentNode.value.length;
902 while (from >= p) {
903 currentNode = currentNode.next;
904 p += currentNode.value.length;
905 }
906 // adjust pos (and p)
907 p -= currentNode.value.length;
908 pos = p;
909
910 // the current node is a Token, then the match starts inside another Token, which is invalid
911 if (currentNode.value instanceof Token) {
912 continue;
913 }
914
915 // find the last node which is affected by this match
916 for (
917 var k = currentNode;
918 k !== tokenList.tail && (p < to || typeof k.value === 'string');
919 k = k.next
920 ) {
921 removeCount++;
922 p += k.value.length;
923 }
924 removeCount--;
925
926 // replace with the new match
927 str = text.slice(pos, p);
928 match.index -= pos;
929 } else {
930 pattern.lastIndex = 0;
931
932 var match = pattern.exec(str);
933 }
934
935 if (!match) {
936 continue;
937 }
938
939 if (lookbehind) {
940 lookbehindLength = match[1] ? match[1].length : 0;
941 }
942
943 var from = match.index + lookbehindLength,
944 matchStr = match[0].slice(lookbehindLength),
945 to = from + matchStr.length,
946 before = str.slice(0, from),
947 after = str.slice(to);
948
949 var reach = pos + str.length;
950 if (rematch && reach > rematch.reach) {
951 rematch.reach = reach;
952 }
953
954 var removeFrom = currentNode.prev;
955
956 if (before) {
957 removeFrom = addAfter(tokenList, removeFrom, before);
958 pos += before.length;
959 }
960
961 removeRange(tokenList, removeFrom, removeCount);
962
963 var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
964 currentNode = addAfter(tokenList, removeFrom, wrapped);
965
966 if (after) {
967 addAfter(tokenList, currentNode, after);
968 }
969
970 if (removeCount > 1) {
971 // at least one Token object was removed, so we have to do some rematching
972 // this can only happen if the current pattern is greedy
973 matchGrammar(text, tokenList, grammar, currentNode.prev, pos, {
974 cause: token + ',' + j,
975 reach: reach
976 });
977 }
978 }
979 }
980 }
981}
982
983/**
984 * @typedef LinkedListNode
985 * @property {T} value
986 * @property {LinkedListNode<T> | null} prev The previous node.
987 * @property {LinkedListNode<T> | null} next The next node.
988 * @template T
989 * @private
990 */
991
992/**
993 * @template T
994 * @private
995 */
996function LinkedList() {
997 /** @type {LinkedListNode<T>} */
998 var head = { value: null, prev: null, next: null };
999 /** @type {LinkedListNode<T>} */
1000 var tail = { value: null, prev: head, next: null };
1001 head.next = tail;
1002
1003 /** @type {LinkedListNode<T>} */
1004 this.head = head;
1005 /** @type {LinkedListNode<T>} */
1006 this.tail = tail;
1007 this.length = 0;
1008}
1009
1010/**
1011 * Adds a new node with the given value to the list.
1012 * @param {LinkedList<T>} list
1013 * @param {LinkedListNode<T>} node
1014 * @param {T} value
1015 * @returns {LinkedListNode<T>} The added node.
1016 * @template T
1017 */
1018function addAfter(list, node, value) {
1019 // assumes that node != list.tail && values.length >= 0
1020 var next = node.next;
1021
1022 var newNode = { value: value, prev: node, next: next };
1023 node.next = newNode;
1024 next.prev = newNode;
1025 list.length++;
1026
1027 return newNode;
1028}
1029/**
1030 * Removes `count` nodes after the given node. The given node will not be removed.
1031 * @param {LinkedList<T>} list
1032 * @param {LinkedListNode<T>} node
1033 * @param {number} count
1034 * @template T
1035 */
1036function removeRange(list, node, count) {
1037 var next = node.next;
1038 for (var i = 0; i < count && next !== list.tail; i++) {
1039 next = next.next;
1040 }
1041 node.next = next;
1042 next.prev = node;
1043 list.length -= i;
1044}
1045/**
1046 * @param {LinkedList<T>} list
1047 * @returns {T[]}
1048 * @template T
1049 */
1050function toArray(list) {
1051 var array = [];
1052 var node = list.head.next;
1053 while (node !== list.tail) {
1054 array.push(node.value);
1055 node = node.next;
1056 }
1057 return array;
1058}
1059
1060
1061if (!_self.document) {
1062 if (!_self.addEventListener) {
1063 // in Node.js
1064 return _;
1065 }
1066
1067 if (!_.disableWorkerMessageHandler) {
1068 // In worker
1069 _self.addEventListener('message', function (evt) {
1070 var message = JSON.parse(evt.data),
1071 lang = message.language,
1072 code = message.code,
1073 immediateClose = message.immediateClose;
1074
1075 _self.postMessage(_.highlight(code, _.languages[lang], lang));
1076 if (immediateClose) {
1077 _self.close();
1078 }
1079 }, false);
1080 }
1081
1082 return _;
1083}
1084
1085// Get current script and highlight
1086var script = _.util.currentScript();
1087
1088if (script) {
1089 _.filename = script.src;
1090
1091 if (script.hasAttribute('data-manual')) {
1092 _.manual = true;
1093 }
1094}
1095
1096function highlightAutomaticallyCallback() {
1097 if (!_.manual) {
1098 _.highlightAll();
1099 }
1100}
1101
1102if (!_.manual) {
1103 // If the document state is "loading", then we'll use DOMContentLoaded.
1104 // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
1105 // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
1106 // might take longer one animation frame to execute which can create a race condition where only some plugins have
1107 // been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
1108 // See https://github.com/PrismJS/prism/issues/2102
1109 var readyState = document.readyState;
1110 if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
1111 document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
1112 } else {
1113 if (window.requestAnimationFrame) {
1114 window.requestAnimationFrame(highlightAutomaticallyCallback);
1115 } else {
1116 window.setTimeout(highlightAutomaticallyCallback, 16);
1117 }
1118 }
1119}
1120
1121return _;
1122
1123})(_self);
1124
1125if (typeof module !== 'undefined' && module.exports) {
1126 module.exports = Prism;
1127}
1128
1129// hack for components to work correctly in node.js
1130if (typeof global !== 'undefined') {
1131 global.Prism = Prism;
1132}
1133
1134// some additional documentation/types
1135
1136/**
1137 * The expansion of a simple `RegExp` literal to support additional properties.
1138 *
1139 * @typedef GrammarToken
1140 * @property {RegExp} pattern The regular expression of the token.
1141 * @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
1142 * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
1143 * @property {boolean} [greedy=false] Whether the token is greedy.
1144 * @property {string|string[]} [alias] An optional alias or list of aliases.
1145 * @property {Grammar} [inside] The nested grammar of this token.
1146 *
1147 * The `inside` grammar will be used to tokenize the text value of each token of this kind.
1148 *
1149 * This can be used to make nested and even recursive language definitions.
1150 *
1151 * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
1152 * each another.
1153 * @global
1154 * @public
1155*/
1156
1157/**
1158 * @typedef Grammar
1159 * @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
1160 * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
1161 * @global
1162 * @public
1163 */
1164
1165/**
1166 * A function which will invoked after an element was successfully highlighted.
1167 *
1168 * @callback HighlightCallback
1169 * @param {Element} element The element successfully highlighted.
1170 * @returns {void}
1171 * @global
1172 * @public
1173*/
1174
1175/**
1176 * @callback HookCallback
1177 * @param {Object<string, any>} env The environment variables of the hook.
1178 * @returns {void}
1179 * @global
1180 * @public
1181 */