UNPKG

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