UNPKG

54.1 kBJavaScriptView Raw
1
2/* **********************************************
3 Begin prism-core.js
4********************************************** */
5
6/// <reference lib="WebWorker"/>
7
8var _self = (typeof window !== 'undefined')
9 ? window // if in browser
10 : (
11 (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
12 ? self // if in worker
13 : {} // if in node js
14 );
15
16/**
17 * Prism: Lightweight, robust, elegant syntax highlighting
18 *
19 * @license MIT <https://opensource.org/licenses/MIT>
20 * @author Lea Verou <https://lea.verou.me>
21 * @namespace
22 * @public
23 */
24var Prism = (function (_self) {
25
26 // Private helper vars
27 var lang = /\blang(?:uage)?-([\w-]+)\b/i;
28 var uniqueId = 0;
29
30 // The grammar object for plaintext
31 var plainTextGrammar = {};
32
33
34 var _ = {
35 /**
36 * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
37 * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
38 * additional languages or plugins yourself.
39 *
40 * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
41 *
42 * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
43 * empty Prism object into the global scope before loading the Prism script like this:
44 *
45 * ```js
46 * window.Prism = window.Prism || {};
47 * Prism.manual = true;
48 * // add a new <script> to load Prism's script
49 * ```
50 *
51 * @default false
52 * @type {boolean}
53 * @memberof Prism
54 * @public
55 */
56 manual: _self.Prism && _self.Prism.manual,
57 disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
58
59 /**
60 * A namespace for utility methods.
61 *
62 * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
63 * change or disappear at any time.
64 *
65 * @namespace
66 * @memberof Prism
67 */
68 util: {
69 encode: function encode(tokens) {
70 if (tokens instanceof Token) {
71 return new Token(tokens.type, encode(tokens.content), tokens.alias);
72 } else if (Array.isArray(tokens)) {
73 return tokens.map(encode);
74 } else {
75 return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
76 }
77 },
78
79 /**
80 * Returns the name of the type of the given value.
81 *
82 * @param {any} o
83 * @returns {string}
84 * @example
85 * type(null) === 'Null'
86 * type(undefined) === 'Undefined'
87 * type(123) === 'Number'
88 * type('foo') === 'String'
89 * type(true) === 'Boolean'
90 * type([1, 2]) === 'Array'
91 * type({}) === 'Object'
92 * type(String) === 'Function'
93 * type(/abc+/) === 'RegExp'
94 */
95 type: function (o) {
96 return Object.prototype.toString.call(o).slice(8, -1);
97 },
98
99 /**
100 * Returns a unique number for the given object. Later calls will still return the same number.
101 *
102 * @param {Object} obj
103 * @returns {number}
104 */
105 objId: function (obj) {
106 if (!obj['__id']) {
107 Object.defineProperty(obj, '__id', { value: ++uniqueId });
108 }
109 return obj['__id'];
110 },
111
112 /**
113 * Creates a deep clone of the given object.
114 *
115 * The main intended use of this function is to clone language definitions.
116 *
117 * @param {T} o
118 * @param {Record<number, any>} [visited]
119 * @returns {T}
120 * @template T
121 */
122 clone: function deepClone(o, visited) {
123 visited = visited || {};
124
125 var clone; var id;
126 switch (_.util.type(o)) {
127 case 'Object':
128 id = _.util.objId(o);
129 if (visited[id]) {
130 return visited[id];
131 }
132 clone = /** @type {Record<string, any>} */ ({});
133 visited[id] = clone;
134
135 for (var key in o) {
136 if (o.hasOwnProperty(key)) {
137 clone[key] = deepClone(o[key], visited);
138 }
139 }
140
141 return /** @type {any} */ (clone);
142
143 case 'Array':
144 id = _.util.objId(o);
145 if (visited[id]) {
146 return visited[id];
147 }
148 clone = [];
149 visited[id] = clone;
150
151 (/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) {
152 clone[i] = deepClone(v, visited);
153 });
154
155 return /** @type {any} */ (clone);
156
157 default:
158 return o;
159 }
160 },
161
162 /**
163 * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
164 *
165 * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
166 *
167 * @param {Element} element
168 * @returns {string}
169 */
170 getLanguage: function (element) {
171 while (element && !lang.test(element.className)) {
172 element = element.parentElement;
173 }
174 if (element) {
175 return (element.className.match(lang) || [, 'none'])[1].toLowerCase();
176 }
177 return 'none';
178 },
179
180 /**
181 * Returns the script element that is currently executing.
182 *
183 * This does __not__ work for line script element.
184 *
185 * @returns {HTMLScriptElement | null}
186 */
187 currentScript: function () {
188 if (typeof document === 'undefined') {
189 return null;
190 }
191 if ('currentScript' in document && 1 < 2 /* hack to trip TS' flow analysis */) {
192 return /** @type {any} */ (document.currentScript);
193 }
194
195 // IE11 workaround
196 // we'll get the src of the current script by parsing IE11's error stack trace
197 // this will not work for inline scripts
198
199 try {
200 throw new Error();
201 } catch (err) {
202 // Get file src url from stack. Specifically works with the format of stack traces in IE.
203 // A stack will look like this:
204 //
205 // Error
206 // at _.util.currentScript (http://localhost/components/prism-core.js:119:5)
207 // at Global code (http://localhost/components/prism-core.js:606:1)
208
209 var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
210 if (src) {
211 var scripts = document.getElementsByTagName('script');
212 for (var i in scripts) {
213 if (scripts[i].src == src) {
214 return scripts[i];
215 }
216 }
217 }
218 return null;
219 }
220 },
221
222 /**
223 * Returns whether a given class is active for `element`.
224 *
225 * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
226 * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
227 * given class is just the given class with a `no-` prefix.
228 *
229 * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
230 * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
231 * ancestors have the given class or the negated version of it, then the default activation will be returned.
232 *
233 * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
234 * version of it, the class is considered active.
235 *
236 * @param {Element} element
237 * @param {string} className
238 * @param {boolean} [defaultActivation=false]
239 * @returns {boolean}
240 */
241 isActive: function (element, className, defaultActivation) {
242 var no = 'no-' + className;
243
244 while (element) {
245 var classList = element.classList;
246 if (classList.contains(className)) {
247 return true;
248 }
249 if (classList.contains(no)) {
250 return false;
251 }
252 element = element.parentElement;
253 }
254 return !!defaultActivation;
255 }
256 },
257
258 /**
259 * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
260 *
261 * @namespace
262 * @memberof Prism
263 * @public
264 */
265 languages: {
266 /**
267 * The grammar for plain, unformatted text.
268 */
269 plain: plainTextGrammar,
270 plaintext: plainTextGrammar,
271 text: plainTextGrammar,
272 txt: plainTextGrammar,
273
274 /**
275 * Creates a deep copy of the language with the given id and appends the given tokens.
276 *
277 * If a token in `redef` also appears in the copied language, then the existing token in the copied language
278 * will be overwritten at its original position.
279 *
280 * ## Best practices
281 *
282 * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
283 * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
284 * understand the language definition because, normally, the order of tokens matters in Prism grammars.
285 *
286 * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
287 * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
288 *
289 * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
290 * @param {Grammar} redef The new tokens to append.
291 * @returns {Grammar} The new language created.
292 * @public
293 * @example
294 * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
295 * // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
296 * // at its original position
297 * 'comment': { ... },
298 * // CSS doesn't have a 'color' token, so this token will be appended
299 * 'color': /\b(?:red|green|blue)\b/
300 * });
301 */
302 extend: function (id, redef) {
303 var lang = _.util.clone(_.languages[id]);
304
305 for (var key in redef) {
306 lang[key] = redef[key];
307 }
308
309 return lang;
310 },
311
312 /**
313 * Inserts tokens _before_ another token in a language definition or any other grammar.
314 *
315 * ## Usage
316 *
317 * This helper method makes it easy to modify existing languages. For example, the CSS language definition
318 * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
319 * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
320 * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
321 * this:
322 *
323 * ```js
324 * Prism.languages.markup.style = {
325 * // token
326 * };
327 * ```
328 *
329 * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
330 * before existing tokens. For the CSS example above, you would use it like this:
331 *
332 * ```js
333 * Prism.languages.insertBefore('markup', 'cdata', {
334 * 'style': {
335 * // token
336 * }
337 * });
338 * ```
339 *
340 * ## Special cases
341 *
342 * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
343 * will be ignored.
344 *
345 * This behavior can be used to insert tokens after `before`:
346 *
347 * ```js
348 * Prism.languages.insertBefore('markup', 'comment', {
349 * 'comment': Prism.languages.markup.comment,
350 * // tokens after 'comment'
351 * });
352 * ```
353 *
354 * ## Limitations
355 *
356 * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
357 * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
358 * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
359 * deleting properties which is necessary to insert at arbitrary positions.
360 *
361 * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
362 * Instead, it will create a new object and replace all references to the target object with the new one. This
363 * can be done without temporarily deleting properties, so the iteration order is well-defined.
364 *
365 * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
366 * you hold the target object in a variable, then the value of the variable will not change.
367 *
368 * ```js
369 * var oldMarkup = Prism.languages.markup;
370 * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
371 *
372 * assert(oldMarkup !== Prism.languages.markup);
373 * assert(newMarkup === Prism.languages.markup);
374 * ```
375 *
376 * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
377 * object to be modified.
378 * @param {string} before The key to insert before.
379 * @param {Grammar} insert An object containing the key-value pairs to be inserted.
380 * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
381 * object to be modified.
382 *
383 * Defaults to `Prism.languages`.
384 * @returns {Grammar} The new grammar object.
385 * @public
386 */
387 insertBefore: function (inside, before, insert, root) {
388 root = root || /** @type {any} */ (_.languages);
389 var grammar = root[inside];
390 /** @type {Grammar} */
391 var ret = {};
392
393 for (var token in grammar) {
394 if (grammar.hasOwnProperty(token)) {
395
396 if (token == before) {
397 for (var newToken in insert) {
398 if (insert.hasOwnProperty(newToken)) {
399 ret[newToken] = insert[newToken];
400 }
401 }
402 }
403
404 // Do not insert token which also occur in insert. See #1525
405 if (!insert.hasOwnProperty(token)) {
406 ret[token] = grammar[token];
407 }
408 }
409 }
410
411 var old = root[inside];
412 root[inside] = ret;
413
414 // Update references in other language definitions
415 _.languages.DFS(_.languages, function (key, value) {
416 if (value === old && key != inside) {
417 this[key] = ret;
418 }
419 });
420
421 return ret;
422 },
423
424 // Traverse a language definition with Depth First Search
425 DFS: function DFS(o, callback, type, visited) {
426 visited = visited || {};
427
428 var objId = _.util.objId;
429
430 for (var i in o) {
431 if (o.hasOwnProperty(i)) {
432 callback.call(o, i, o[i], type || i);
433
434 var property = o[i];
435 var propertyType = _.util.type(property);
436
437 if (propertyType === 'Object' && !visited[objId(property)]) {
438 visited[objId(property)] = true;
439 DFS(property, callback, null, visited);
440 } else if (propertyType === 'Array' && !visited[objId(property)]) {
441 visited[objId(property)] = true;
442 DFS(property, callback, i, visited);
443 }
444 }
445 }
446 }
447 },
448
449 plugins: {},
450
451 /**
452 * This is the most high-level function in Prism’s API.
453 * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
454 * each one of them.
455 *
456 * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
457 *
458 * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
459 * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
460 * @memberof Prism
461 * @public
462 */
463 highlightAll: function (async, callback) {
464 _.highlightAllUnder(document, async, callback);
465 },
466
467 /**
468 * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
469 * {@link Prism.highlightElement} on each one of them.
470 *
471 * The following hooks will be run:
472 * 1. `before-highlightall`
473 * 2. `before-all-elements-highlight`
474 * 3. All hooks of {@link Prism.highlightElement} for each element.
475 *
476 * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
477 * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
478 * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
479 * @memberof Prism
480 * @public
481 */
482 highlightAllUnder: function (container, async, callback) {
483 var env = {
484 callback: callback,
485 container: container,
486 selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
487 };
488
489 _.hooks.run('before-highlightall', env);
490
491 env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
492
493 _.hooks.run('before-all-elements-highlight', env);
494
495 for (var i = 0, element; (element = env.elements[i++]);) {
496 _.highlightElement(element, async === true, env.callback);
497 }
498 },
499
500 /**
501 * Highlights the code inside a single element.
502 *
503 * The following hooks will be run:
504 * 1. `before-sanity-check`
505 * 2. `before-highlight`
506 * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
507 * 4. `before-insert`
508 * 5. `after-highlight`
509 * 6. `complete`
510 *
511 * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
512 * the element's language.
513 *
514 * @param {Element} element The element containing the code.
515 * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
516 * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
517 * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
518 * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
519 *
520 * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
521 * asynchronous highlighting to work. You can build your own bundle on the
522 * [Download page](https://prismjs.com/download.html).
523 * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
524 * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
525 * @memberof Prism
526 * @public
527 */
528 highlightElement: function (element, async, callback) {
529 // Find language
530 var language = _.util.getLanguage(element);
531 var grammar = _.languages[language];
532
533 // Set language on the element, if not present
534 element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
535
536 // Set language on the parent, for styling
537 var parent = element.parentElement;
538 if (parent && parent.nodeName.toLowerCase() === 'pre') {
539 parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
540 }
541
542 var code = element.textContent;
543
544 var env = {
545 element: element,
546 language: language,
547 grammar: grammar,
548 code: code
549 };
550
551 function insertHighlightedCode(highlightedCode) {
552 env.highlightedCode = highlightedCode;
553
554 _.hooks.run('before-insert', env);
555
556 env.element.innerHTML = env.highlightedCode;
557
558 _.hooks.run('after-highlight', env);
559 _.hooks.run('complete', env);
560 callback && callback.call(env.element);
561 }
562
563 _.hooks.run('before-sanity-check', env);
564
565 // plugins may change/add the parent/element
566 parent = env.element.parentElement;
567 if (parent && parent.nodeName.toLowerCase() === 'pre' && !parent.hasAttribute('tabindex')) {
568 parent.setAttribute('tabindex', '0');
569 }
570
571 if (!env.code) {
572 _.hooks.run('complete', env);
573 callback && callback.call(env.element);
574 return;
575 }
576
577 _.hooks.run('before-highlight', env);
578
579 if (!env.grammar) {
580 insertHighlightedCode(_.util.encode(env.code));
581 return;
582 }
583
584 if (async && _self.Worker) {
585 var worker = new Worker(_.filename);
586
587 worker.onmessage = function (evt) {
588 insertHighlightedCode(evt.data);
589 };
590
591 worker.postMessage(JSON.stringify({
592 language: env.language,
593 code: env.code,
594 immediateClose: true
595 }));
596 } else {
597 insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
598 }
599 },
600
601 /**
602 * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
603 * and the language definitions to use, and returns a string with the HTML produced.
604 *
605 * The following hooks will be run:
606 * 1. `before-tokenize`
607 * 2. `after-tokenize`
608 * 3. `wrap`: On each {@link Token}.
609 *
610 * @param {string} text A string with the code to be highlighted.
611 * @param {Grammar} grammar An object containing the tokens to use.
612 *
613 * Usually a language definition like `Prism.languages.markup`.
614 * @param {string} language The name of the language definition passed to `grammar`.
615 * @returns {string} The highlighted HTML.
616 * @memberof Prism
617 * @public
618 * @example
619 * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
620 */
621 highlight: function (text, grammar, language) {
622 var env = {
623 code: text,
624 grammar: grammar,
625 language: language
626 };
627 _.hooks.run('before-tokenize', env);
628 env.tokens = _.tokenize(env.code, env.grammar);
629 _.hooks.run('after-tokenize', env);
630 return Token.stringify(_.util.encode(env.tokens), env.language);
631 },
632
633 /**
634 * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
635 * and the language definitions to use, and returns an array with the tokenized code.
636 *
637 * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
638 *
639 * This method could be useful in other contexts as well, as a very crude parser.
640 *
641 * @param {string} text A string with the code to be highlighted.
642 * @param {Grammar} grammar An object containing the tokens to use.
643 *
644 * Usually a language definition like `Prism.languages.markup`.
645 * @returns {TokenStream} An array of strings and tokens, a token stream.
646 * @memberof Prism
647 * @public
648 * @example
649 * let code = `var foo = 0;`;
650 * let tokens = Prism.tokenize(code, Prism.languages.javascript);
651 * tokens.forEach(token => {
652 * if (token instanceof Prism.Token && token.type === 'number') {
653 * console.log(`Found numeric literal: ${token.content}`);
654 * }
655 * });
656 */
657 tokenize: function (text, grammar) {
658 var rest = grammar.rest;
659 if (rest) {
660 for (var token in rest) {
661 grammar[token] = rest[token];
662 }
663
664 delete grammar.rest;
665 }
666
667 var tokenList = new LinkedList();
668 addAfter(tokenList, tokenList.head, text);
669
670 matchGrammar(text, tokenList, grammar, tokenList.head, 0);
671
672 return toArray(tokenList);
673 },
674
675 /**
676 * @namespace
677 * @memberof Prism
678 * @public
679 */
680 hooks: {
681 all: {},
682
683 /**
684 * Adds the given callback to the list of callbacks for the given hook.
685 *
686 * The callback will be invoked when the hook it is registered for is run.
687 * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
688 *
689 * One callback function can be registered to multiple hooks and the same hook multiple times.
690 *
691 * @param {string} name The name of the hook.
692 * @param {HookCallback} callback The callback function which is given environment variables.
693 * @public
694 */
695 add: function (name, callback) {
696 var hooks = _.hooks.all;
697
698 hooks[name] = hooks[name] || [];
699
700 hooks[name].push(callback);
701 },
702
703 /**
704 * Runs a hook invoking all registered callbacks with the given environment variables.
705 *
706 * Callbacks will be invoked synchronously and in the order in which they were registered.
707 *
708 * @param {string} name The name of the hook.
709 * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
710 * @public
711 */
712 run: function (name, env) {
713 var callbacks = _.hooks.all[name];
714
715 if (!callbacks || !callbacks.length) {
716 return;
717 }
718
719 for (var i = 0, callback; (callback = callbacks[i++]);) {
720 callback(env);
721 }
722 }
723 },
724
725 Token: Token
726 };
727 _self.Prism = _;
728
729
730 // Typescript note:
731 // The following can be used to import the Token type in JSDoc:
732 //
733 // @typedef {InstanceType<import("./prism-core")["Token"]>} Token
734
735 /**
736 * Creates a new token.
737 *
738 * @param {string} type See {@link Token#type type}
739 * @param {string | TokenStream} content See {@link Token#content content}
740 * @param {string|string[]} [alias] The alias(es) of the token.
741 * @param {string} [matchedStr=""] A copy of the full string this token was created from.
742 * @class
743 * @global
744 * @public
745 */
746 function Token(type, content, alias, matchedStr) {
747 /**
748 * The type of the token.
749 *
750 * This is usually the key of a pattern in a {@link Grammar}.
751 *
752 * @type {string}
753 * @see GrammarToken
754 * @public
755 */
756 this.type = type;
757 /**
758 * The strings or tokens contained by this token.
759 *
760 * This will be a token stream if the pattern matched also defined an `inside` grammar.
761 *
762 * @type {string | TokenStream}
763 * @public
764 */
765 this.content = content;
766 /**
767 * The alias(es) of the token.
768 *
769 * @type {string|string[]}
770 * @see GrammarToken
771 * @public
772 */
773 this.alias = alias;
774 // Copy of the full string this token was created from
775 this.length = (matchedStr || '').length | 0;
776 }
777
778 /**
779 * A token stream is an array of strings and {@link Token Token} objects.
780 *
781 * Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
782 * them.
783 *
784 * 1. No adjacent strings.
785 * 2. No empty strings.
786 *
787 * The only exception here is the token stream that only contains the empty string and nothing else.
788 *
789 * @typedef {Array<string | Token>} TokenStream
790 * @global
791 * @public
792 */
793
794 /**
795 * Converts the given token or token stream to an HTML representation.
796 *
797 * The following hooks will be run:
798 * 1. `wrap`: On each {@link Token}.
799 *
800 * @param {string | Token | TokenStream} o The token or token stream to be converted.
801 * @param {string} language The name of current language.
802 * @returns {string} The HTML representation of the token or token stream.
803 * @memberof Token
804 * @static
805 */
806 Token.stringify = function stringify(o, language) {
807 if (typeof o == 'string') {
808 return o;
809 }
810 if (Array.isArray(o)) {
811 var s = '';
812 o.forEach(function (e) {
813 s += stringify(e, language);
814 });
815 return s;
816 }
817
818 var env = {
819 type: o.type,
820 content: stringify(o.content, language),
821 tag: 'span',
822 classes: ['token', o.type],
823 attributes: {},
824 language: language
825 };
826
827 var aliases = o.alias;
828 if (aliases) {
829 if (Array.isArray(aliases)) {
830 Array.prototype.push.apply(env.classes, aliases);
831 } else {
832 env.classes.push(aliases);
833 }
834 }
835
836 _.hooks.run('wrap', env);
837
838 var attributes = '';
839 for (var name in env.attributes) {
840 attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
841 }
842
843 return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
844 };
845
846 /**
847 * @param {RegExp} pattern
848 * @param {number} pos
849 * @param {string} text
850 * @param {boolean} lookbehind
851 * @returns {RegExpExecArray | null}
852 */
853 function matchPattern(pattern, pos, text, lookbehind) {
854 pattern.lastIndex = pos;
855 var match = pattern.exec(text);
856 if (match && lookbehind && match[1]) {
857 // change the match to remove the text matched by the Prism lookbehind group
858 var lookbehindLength = match[1].length;
859 match.index += lookbehindLength;
860 match[0] = match[0].slice(lookbehindLength);
861 }
862 return match;
863 }
864
865 /**
866 * @param {string} text
867 * @param {LinkedList<string | Token>} tokenList
868 * @param {any} grammar
869 * @param {LinkedListNode<string | Token>} startNode
870 * @param {number} startPos
871 * @param {RematchOptions} [rematch]
872 * @returns {void}
873 * @private
874 *
875 * @typedef RematchOptions
876 * @property {string} cause
877 * @property {number} reach
878 */
879 function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
880 for (var token in grammar) {
881 if (!grammar.hasOwnProperty(token) || !grammar[token]) {
882 continue;
883 }
884
885 var patterns = grammar[token];
886 patterns = Array.isArray(patterns) ? patterns : [patterns];
887
888 for (var j = 0; j < patterns.length; ++j) {
889 if (rematch && rematch.cause == token + ',' + j) {
890 return;
891 }
892
893 var patternObj = patterns[j];
894 var inside = patternObj.inside;
895 var lookbehind = !!patternObj.lookbehind;
896 var greedy = !!patternObj.greedy;
897 var alias = patternObj.alias;
898
899 if (greedy && !patternObj.pattern.global) {
900 // Without the global flag, lastIndex won't work
901 var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
902 patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
903 }
904
905 /** @type {RegExp} */
906 var pattern = patternObj.pattern || patternObj;
907
908 for ( // iterate the token list and keep track of the current token/string position
909 var currentNode = startNode.next, pos = startPos;
910 currentNode !== tokenList.tail;
911 pos += currentNode.value.length, currentNode = currentNode.next
912 ) {
913
914 if (rematch && pos >= rematch.reach) {
915 break;
916 }
917
918 var str = currentNode.value;
919
920 if (tokenList.length > text.length) {
921 // Something went terribly wrong, ABORT, ABORT!
922 return;
923 }
924
925 if (str instanceof Token) {
926 continue;
927 }
928
929 var removeCount = 1; // this is the to parameter of removeBetween
930 var match;
931
932 if (greedy) {
933 match = matchPattern(pattern, pos, text, lookbehind);
934 if (!match) {
935 break;
936 }
937
938 var from = match.index;
939 var to = match.index + match[0].length;
940 var p = pos;
941
942 // find the node that contains the match
943 p += currentNode.value.length;
944 while (from >= p) {
945 currentNode = currentNode.next;
946 p += currentNode.value.length;
947 }
948 // adjust pos (and p)
949 p -= currentNode.value.length;
950 pos = p;
951
952 // the current node is a Token, then the match starts inside another Token, which is invalid
953 if (currentNode.value instanceof Token) {
954 continue;
955 }
956
957 // find the last node which is affected by this match
958 for (
959 var k = currentNode;
960 k !== tokenList.tail && (p < to || typeof k.value === 'string');
961 k = k.next
962 ) {
963 removeCount++;
964 p += k.value.length;
965 }
966 removeCount--;
967
968 // replace with the new match
969 str = text.slice(pos, p);
970 match.index -= pos;
971 } else {
972 match = matchPattern(pattern, 0, str, lookbehind);
973 if (!match) {
974 continue;
975 }
976 }
977
978 // eslint-disable-next-line no-redeclare
979 var from = match.index;
980 var matchStr = match[0];
981 var before = str.slice(0, from);
982 var after = str.slice(from + matchStr.length);
983
984 var reach = pos + str.length;
985 if (rematch && reach > rematch.reach) {
986 rematch.reach = reach;
987 }
988
989 var removeFrom = currentNode.prev;
990
991 if (before) {
992 removeFrom = addAfter(tokenList, removeFrom, before);
993 pos += before.length;
994 }
995
996 removeRange(tokenList, removeFrom, removeCount);
997
998 var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
999 currentNode = addAfter(tokenList, removeFrom, wrapped);
1000
1001 if (after) {
1002 addAfter(tokenList, currentNode, after);
1003 }
1004
1005 if (removeCount > 1) {
1006 // at least one Token object was removed, so we have to do some rematching
1007 // this can only happen if the current pattern is greedy
1008
1009 /** @type {RematchOptions} */
1010 var nestedRematch = {
1011 cause: token + ',' + j,
1012 reach: reach
1013 };
1014 matchGrammar(text, tokenList, grammar, currentNode.prev, pos, nestedRematch);
1015
1016 // the reach might have been extended because of the rematching
1017 if (rematch && nestedRematch.reach > rematch.reach) {
1018 rematch.reach = nestedRematch.reach;
1019 }
1020 }
1021 }
1022 }
1023 }
1024 }
1025
1026 /**
1027 * @typedef LinkedListNode
1028 * @property {T} value
1029 * @property {LinkedListNode<T> | null} prev The previous node.
1030 * @property {LinkedListNode<T> | null} next The next node.
1031 * @template T
1032 * @private
1033 */
1034
1035 /**
1036 * @template T
1037 * @private
1038 */
1039 function LinkedList() {
1040 /** @type {LinkedListNode<T>} */
1041 var head = { value: null, prev: null, next: null };
1042 /** @type {LinkedListNode<T>} */
1043 var tail = { value: null, prev: head, next: null };
1044 head.next = tail;
1045
1046 /** @type {LinkedListNode<T>} */
1047 this.head = head;
1048 /** @type {LinkedListNode<T>} */
1049 this.tail = tail;
1050 this.length = 0;
1051 }
1052
1053 /**
1054 * Adds a new node with the given value to the list.
1055 *
1056 * @param {LinkedList<T>} list
1057 * @param {LinkedListNode<T>} node
1058 * @param {T} value
1059 * @returns {LinkedListNode<T>} The added node.
1060 * @template T
1061 */
1062 function addAfter(list, node, value) {
1063 // assumes that node != list.tail && values.length >= 0
1064 var next = node.next;
1065
1066 var newNode = { value: value, prev: node, next: next };
1067 node.next = newNode;
1068 next.prev = newNode;
1069 list.length++;
1070
1071 return newNode;
1072 }
1073 /**
1074 * Removes `count` nodes after the given node. The given node will not be removed.
1075 *
1076 * @param {LinkedList<T>} list
1077 * @param {LinkedListNode<T>} node
1078 * @param {number} count
1079 * @template T
1080 */
1081 function removeRange(list, node, count) {
1082 var next = node.next;
1083 for (var i = 0; i < count && next !== list.tail; i++) {
1084 next = next.next;
1085 }
1086 node.next = next;
1087 next.prev = node;
1088 list.length -= i;
1089 }
1090 /**
1091 * @param {LinkedList<T>} list
1092 * @returns {T[]}
1093 * @template T
1094 */
1095 function toArray(list) {
1096 var array = [];
1097 var node = list.head.next;
1098 while (node !== list.tail) {
1099 array.push(node.value);
1100 node = node.next;
1101 }
1102 return array;
1103 }
1104
1105
1106 if (!_self.document) {
1107 if (!_self.addEventListener) {
1108 // in Node.js
1109 return _;
1110 }
1111
1112 if (!_.disableWorkerMessageHandler) {
1113 // In worker
1114 _self.addEventListener('message', function (evt) {
1115 var message = JSON.parse(evt.data);
1116 var lang = message.language;
1117 var code = message.code;
1118 var immediateClose = message.immediateClose;
1119
1120 _self.postMessage(_.highlight(code, _.languages[lang], lang));
1121 if (immediateClose) {
1122 _self.close();
1123 }
1124 }, false);
1125 }
1126
1127 return _;
1128 }
1129
1130 // Get current script and highlight
1131 var script = _.util.currentScript();
1132
1133 if (script) {
1134 _.filename = script.src;
1135
1136 if (script.hasAttribute('data-manual')) {
1137 _.manual = true;
1138 }
1139 }
1140
1141 function highlightAutomaticallyCallback() {
1142 if (!_.manual) {
1143 _.highlightAll();
1144 }
1145 }
1146
1147 if (!_.manual) {
1148 // If the document state is "loading", then we'll use DOMContentLoaded.
1149 // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
1150 // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
1151 // might take longer one animation frame to execute which can create a race condition where only some plugins have
1152 // been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
1153 // See https://github.com/PrismJS/prism/issues/2102
1154 var readyState = document.readyState;
1155 if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
1156 document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
1157 } else {
1158 if (window.requestAnimationFrame) {
1159 window.requestAnimationFrame(highlightAutomaticallyCallback);
1160 } else {
1161 window.setTimeout(highlightAutomaticallyCallback, 16);
1162 }
1163 }
1164 }
1165
1166 return _;
1167
1168}(_self));
1169
1170if (typeof module !== 'undefined' && module.exports) {
1171 module.exports = Prism;
1172}
1173
1174// hack for components to work correctly in node.js
1175if (typeof global !== 'undefined') {
1176 global.Prism = Prism;
1177}
1178
1179// some additional documentation/types
1180
1181/**
1182 * The expansion of a simple `RegExp` literal to support additional properties.
1183 *
1184 * @typedef GrammarToken
1185 * @property {RegExp} pattern The regular expression of the token.
1186 * @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
1187 * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
1188 * @property {boolean} [greedy=false] Whether the token is greedy.
1189 * @property {string|string[]} [alias] An optional alias or list of aliases.
1190 * @property {Grammar} [inside] The nested grammar of this token.
1191 *
1192 * The `inside` grammar will be used to tokenize the text value of each token of this kind.
1193 *
1194 * This can be used to make nested and even recursive language definitions.
1195 *
1196 * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
1197 * each another.
1198 * @global
1199 * @public
1200 */
1201
1202/**
1203 * @typedef Grammar
1204 * @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
1205 * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
1206 * @global
1207 * @public
1208 */
1209
1210/**
1211 * A function which will invoked after an element was successfully highlighted.
1212 *
1213 * @callback HighlightCallback
1214 * @param {Element} element The element successfully highlighted.
1215 * @returns {void}
1216 * @global
1217 * @public
1218 */
1219
1220/**
1221 * @callback HookCallback
1222 * @param {Object<string, any>} env The environment variables of the hook.
1223 * @returns {void}
1224 * @global
1225 * @public
1226 */
1227
1228
1229/* **********************************************
1230 Begin prism-markup.js
1231********************************************** */
1232
1233Prism.languages.markup = {
1234 'comment': {
1235 pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
1236 greedy: true
1237 },
1238 'prolog': {
1239 pattern: /<\?[\s\S]+?\?>/,
1240 greedy: true
1241 },
1242 'doctype': {
1243 // https://www.w3.org/TR/xml/#NT-doctypedecl
1244 pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
1245 greedy: true,
1246 inside: {
1247 'internal-subset': {
1248 pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
1249 lookbehind: true,
1250 greedy: true,
1251 inside: null // see below
1252 },
1253 'string': {
1254 pattern: /"[^"]*"|'[^']*'/,
1255 greedy: true
1256 },
1257 'punctuation': /^<!|>$|[[\]]/,
1258 'doctype-tag': /^DOCTYPE/i,
1259 'name': /[^\s<>'"]+/
1260 }
1261 },
1262 'cdata': {
1263 pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
1264 greedy: true
1265 },
1266 'tag': {
1267 pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
1268 greedy: true,
1269 inside: {
1270 'tag': {
1271 pattern: /^<\/?[^\s>\/]+/,
1272 inside: {
1273 'punctuation': /^<\/?/,
1274 'namespace': /^[^\s>\/:]+:/
1275 }
1276 },
1277 'special-attr': [],
1278 'attr-value': {
1279 pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
1280 inside: {
1281 'punctuation': [
1282 {
1283 pattern: /^=/,
1284 alias: 'attr-equals'
1285 },
1286 /"|'/
1287 ]
1288 }
1289 },
1290 'punctuation': /\/?>/,
1291 'attr-name': {
1292 pattern: /[^\s>\/]+/,
1293 inside: {
1294 'namespace': /^[^\s>\/:]+:/
1295 }
1296 }
1297
1298 }
1299 },
1300 'entity': [
1301 {
1302 pattern: /&[\da-z]{1,8};/i,
1303 alias: 'named-entity'
1304 },
1305 /&#x?[\da-f]{1,8};/i
1306 ]
1307};
1308
1309Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
1310 Prism.languages.markup['entity'];
1311Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
1312
1313// Plugin to make entity title show the real entity, idea by Roman Komarov
1314Prism.hooks.add('wrap', function (env) {
1315
1316 if (env.type === 'entity') {
1317 env.attributes['title'] = env.content.replace(/&amp;/, '&');
1318 }
1319});
1320
1321Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
1322 /**
1323 * Adds an inlined language to markup.
1324 *
1325 * An example of an inlined language is CSS with `<style>` tags.
1326 *
1327 * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
1328 * case insensitive.
1329 * @param {string} lang The language key.
1330 * @example
1331 * addInlined('style', 'css');
1332 */
1333 value: function addInlined(tagName, lang) {
1334 var includedCdataInside = {};
1335 includedCdataInside['language-' + lang] = {
1336 pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
1337 lookbehind: true,
1338 inside: Prism.languages[lang]
1339 };
1340 includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
1341
1342 var inside = {
1343 'included-cdata': {
1344 pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
1345 inside: includedCdataInside
1346 }
1347 };
1348 inside['language-' + lang] = {
1349 pattern: /[\s\S]+/,
1350 inside: Prism.languages[lang]
1351 };
1352
1353 var def = {};
1354 def[tagName] = {
1355 pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () { return tagName; }), 'i'),
1356 lookbehind: true,
1357 greedy: true,
1358 inside: inside
1359 };
1360
1361 Prism.languages.insertBefore('markup', 'cdata', def);
1362 }
1363});
1364Object.defineProperty(Prism.languages.markup.tag, 'addAttribute', {
1365 /**
1366 * Adds an pattern to highlight languages embedded in HTML attributes.
1367 *
1368 * An example of an inlined language is CSS with `style` attributes.
1369 *
1370 * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
1371 * case insensitive.
1372 * @param {string} lang The language key.
1373 * @example
1374 * addAttribute('style', 'css');
1375 */
1376 value: function (attrName, lang) {
1377 Prism.languages.markup.tag.inside['special-attr'].push({
1378 pattern: RegExp(
1379 /(^|["'\s])/.source + '(?:' + attrName + ')' + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
1380 'i'
1381 ),
1382 lookbehind: true,
1383 inside: {
1384 'attr-name': /^[^\s=]+/,
1385 'attr-value': {
1386 pattern: /=[\s\S]+/,
1387 inside: {
1388 'value': {
1389 pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
1390 lookbehind: true,
1391 alias: [lang, 'language-' + lang],
1392 inside: Prism.languages[lang]
1393 },
1394 'punctuation': [
1395 {
1396 pattern: /^=/,
1397 alias: 'attr-equals'
1398 },
1399 /"|'/
1400 ]
1401 }
1402 }
1403 }
1404 });
1405 }
1406});
1407
1408Prism.languages.html = Prism.languages.markup;
1409Prism.languages.mathml = Prism.languages.markup;
1410Prism.languages.svg = Prism.languages.markup;
1411
1412Prism.languages.xml = Prism.languages.extend('markup', {});
1413Prism.languages.ssml = Prism.languages.xml;
1414Prism.languages.atom = Prism.languages.xml;
1415Prism.languages.rss = Prism.languages.xml;
1416
1417
1418/* **********************************************
1419 Begin prism-css.js
1420********************************************** */
1421
1422(function (Prism) {
1423
1424 var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
1425
1426 Prism.languages.css = {
1427 'comment': /\/\*[\s\S]*?\*\//,
1428 'atrule': {
1429 pattern: /@[\w-](?:[^;{\s]|\s+(?![\s{]))*(?:;|(?=\s*\{))/,
1430 inside: {
1431 'rule': /^@[\w-]+/,
1432 'selector-function-argument': {
1433 pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
1434 lookbehind: true,
1435 alias: 'selector'
1436 },
1437 'keyword': {
1438 pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
1439 lookbehind: true
1440 }
1441 // See rest below
1442 }
1443 },
1444 'url': {
1445 // https://drafts.csswg.org/css-values-3/#urls
1446 pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
1447 greedy: true,
1448 inside: {
1449 'function': /^url/i,
1450 'punctuation': /^\(|\)$/,
1451 'string': {
1452 pattern: RegExp('^' + string.source + '$'),
1453 alias: 'url'
1454 }
1455 }
1456 },
1457 'selector': {
1458 pattern: RegExp('(^|[{}\\s])[^{}\\s](?:[^{};"\'\\s]|\\s+(?![\\s{])|' + string.source + ')*(?=\\s*\\{)'),
1459 lookbehind: true
1460 },
1461 'string': {
1462 pattern: string,
1463 greedy: true
1464 },
1465 'property': {
1466 pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
1467 lookbehind: true
1468 },
1469 'important': /!important\b/i,
1470 'function': {
1471 pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
1472 lookbehind: true
1473 },
1474 'punctuation': /[(){};:,]/
1475 };
1476
1477 Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
1478
1479 var markup = Prism.languages.markup;
1480 if (markup) {
1481 markup.tag.addInlined('style', 'css');
1482 markup.tag.addAttribute('style', 'css');
1483 }
1484
1485}(Prism));
1486
1487
1488/* **********************************************
1489 Begin prism-clike.js
1490********************************************** */
1491
1492Prism.languages.clike = {
1493 'comment': [
1494 {
1495 pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
1496 lookbehind: true,
1497 greedy: true
1498 },
1499 {
1500 pattern: /(^|[^\\:])\/\/.*/,
1501 lookbehind: true,
1502 greedy: true
1503 }
1504 ],
1505 'string': {
1506 pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
1507 greedy: true
1508 },
1509 'class-name': {
1510 pattern: /(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,
1511 lookbehind: true,
1512 inside: {
1513 'punctuation': /[.\\]/
1514 }
1515 },
1516 'keyword': /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
1517 'boolean': /\b(?:true|false)\b/,
1518 'function': /\b\w+(?=\()/,
1519 'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
1520 'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
1521 'punctuation': /[{}[\];(),.:]/
1522};
1523
1524
1525/* **********************************************
1526 Begin prism-javascript.js
1527********************************************** */
1528
1529Prism.languages.javascript = Prism.languages.extend('clike', {
1530 'class-name': [
1531 Prism.languages.clike['class-name'],
1532 {
1533 pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:prototype|constructor))/,
1534 lookbehind: true
1535 }
1536 ],
1537 'keyword': [
1538 {
1539 pattern: /((?:^|\})\s*)catch\b/,
1540 lookbehind: true
1541 },
1542 {
1543 pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
1544 lookbehind: true
1545 },
1546 ],
1547 // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
1548 'function': /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
1549 'number': /\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,
1550 'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
1551});
1552
1553Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/;
1554
1555Prism.languages.insertBefore('javascript', 'keyword', {
1556 'regex': {
1557 // eslint-disable-next-line regexp/no-dupe-characters-character-class
1558 pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,
1559 lookbehind: true,
1560 greedy: true,
1561 inside: {
1562 'regex-source': {
1563 pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
1564 lookbehind: true,
1565 alias: 'language-regex',
1566 inside: Prism.languages.regex
1567 },
1568 'regex-delimiter': /^\/|\/$/,
1569 'regex-flags': /^[a-z]+$/,
1570 }
1571 },
1572 // This must be declared before keyword because we use "function" inside the look-forward
1573 'function-variable': {
1574 pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
1575 alias: 'function'
1576 },
1577 'parameter': [
1578 {
1579 pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
1580 lookbehind: true,
1581 inside: Prism.languages.javascript
1582 },
1583 {
1584 pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
1585 lookbehind: true,
1586 inside: Prism.languages.javascript
1587 },
1588 {
1589 pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
1590 lookbehind: true,
1591 inside: Prism.languages.javascript
1592 },
1593 {
1594 pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
1595 lookbehind: true,
1596 inside: Prism.languages.javascript
1597 }
1598 ],
1599 'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
1600});
1601
1602Prism.languages.insertBefore('javascript', 'string', {
1603 'hashbang': {
1604 pattern: /^#!.*/,
1605 greedy: true,
1606 alias: 'comment'
1607 },
1608 'template-string': {
1609 pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
1610 greedy: true,
1611 inside: {
1612 'template-punctuation': {
1613 pattern: /^`|`$/,
1614 alias: 'string'
1615 },
1616 'interpolation': {
1617 pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
1618 lookbehind: true,
1619 inside: {
1620 'interpolation-punctuation': {
1621 pattern: /^\$\{|\}$/,
1622 alias: 'punctuation'
1623 },
1624 rest: Prism.languages.javascript
1625 }
1626 },
1627 'string': /[\s\S]+/
1628 }
1629 }
1630});
1631
1632if (Prism.languages.markup) {
1633 Prism.languages.markup.tag.addInlined('script', 'javascript');
1634
1635 // add attribute support for all DOM events.
1636 // https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events
1637 Prism.languages.markup.tag.addAttribute(
1638 /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
1639 'javascript'
1640 );
1641}
1642
1643Prism.languages.js = Prism.languages.javascript;
1644
1645
1646/* **********************************************
1647 Begin prism-file-highlight.js
1648********************************************** */
1649
1650(function () {
1651
1652 if (typeof Prism === 'undefined' || typeof document === 'undefined') {
1653 return;
1654 }
1655
1656 // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
1657 if (!Element.prototype.matches) {
1658 Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
1659 }
1660
1661 var LOADING_MESSAGE = 'Loading…';
1662 var FAILURE_MESSAGE = function (status, message) {
1663 return '✖ Error ' + status + ' while fetching file: ' + message;
1664 };
1665 var FAILURE_EMPTY_MESSAGE = '✖ Error: File does not exist or is empty';
1666
1667 var EXTENSIONS = {
1668 'js': 'javascript',
1669 'py': 'python',
1670 'rb': 'ruby',
1671 'ps1': 'powershell',
1672 'psm1': 'powershell',
1673 'sh': 'bash',
1674 'bat': 'batch',
1675 'h': 'c',
1676 'tex': 'latex'
1677 };
1678
1679 var STATUS_ATTR = 'data-src-status';
1680 var STATUS_LOADING = 'loading';
1681 var STATUS_LOADED = 'loaded';
1682 var STATUS_FAILED = 'failed';
1683
1684 var SELECTOR = 'pre[data-src]:not([' + STATUS_ATTR + '="' + STATUS_LOADED + '"])'
1685 + ':not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
1686
1687 var lang = /\blang(?:uage)?-([\w-]+)\b/i;
1688
1689 /**
1690 * Sets the Prism `language-xxxx` or `lang-xxxx` class to the given language.
1691 *
1692 * @param {HTMLElement} element
1693 * @param {string} language
1694 * @returns {void}
1695 */
1696 function setLanguageClass(element, language) {
1697 var className = element.className;
1698 className = className.replace(lang, ' ') + ' language-' + language;
1699 element.className = className.replace(/\s+/g, ' ').trim();
1700 }
1701
1702
1703 Prism.hooks.add('before-highlightall', function (env) {
1704 env.selector += ', ' + SELECTOR;
1705 });
1706
1707 Prism.hooks.add('before-sanity-check', function (env) {
1708 var pre = /** @type {HTMLPreElement} */ (env.element);
1709 if (pre.matches(SELECTOR)) {
1710 env.code = ''; // fast-path the whole thing and go to complete
1711
1712 pre.setAttribute(STATUS_ATTR, STATUS_LOADING); // mark as loading
1713
1714 // add code element with loading message
1715 var code = pre.appendChild(document.createElement('CODE'));
1716 code.textContent = LOADING_MESSAGE;
1717
1718 var src = pre.getAttribute('data-src');
1719
1720 var language = env.language;
1721 if (language === 'none') {
1722 // the language might be 'none' because there is no language set;
1723 // in this case, we want to use the extension as the language
1724 var extension = (/\.(\w+)$/.exec(src) || [, 'none'])[1];
1725 language = EXTENSIONS[extension] || extension;
1726 }
1727
1728 // set language classes
1729 setLanguageClass(code, language);
1730 setLanguageClass(pre, language);
1731
1732 // preload the language
1733 var autoloader = Prism.plugins.autoloader;
1734 if (autoloader) {
1735 autoloader.loadLanguages(language);
1736 }
1737
1738 // load file
1739 var xhr = new XMLHttpRequest();
1740 xhr.open('GET', src, true);
1741 xhr.onreadystatechange = function () {
1742 if (xhr.readyState == 4) {
1743 if (xhr.status < 400 && xhr.responseText) {
1744 // mark as loaded
1745 pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
1746
1747 // highlight code
1748 code.textContent = xhr.responseText;
1749 Prism.highlightElement(code);
1750
1751 } else {
1752 // mark as failed
1753 pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
1754
1755 if (xhr.status >= 400) {
1756 code.textContent = FAILURE_MESSAGE(xhr.status, xhr.statusText);
1757 } else {
1758 code.textContent = FAILURE_EMPTY_MESSAGE;
1759 }
1760 }
1761 }
1762 };
1763 xhr.send(null);
1764 }
1765 });
1766
1767 Prism.plugins.fileHighlight = {
1768 /**
1769 * Executes the File Highlight plugin for all matching `pre` elements under the given container.
1770 *
1771 * Note: Elements which are already loaded or currently loading will not be touched by this method.
1772 *
1773 * @param {ParentNode} [container=document]
1774 */
1775 highlight: function highlight(container) {
1776 var elements = (container || document).querySelectorAll(SELECTOR);
1777
1778 for (var i = 0, element; (element = elements[i++]);) {
1779 Prism.highlightElement(element);
1780 }
1781 }
1782 };
1783
1784 var logged = false;
1785 /** @deprecated Use `Prism.plugins.fileHighlight.highlight` instead. */
1786 Prism.fileHighlight = function () {
1787 if (!logged) {
1788 console.warn('Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.');
1789 logged = true;
1790 }
1791 Prism.plugins.fileHighlight.highlight.apply(this, arguments);
1792 };
1793
1794}());