UNPKG

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