UNPKG

49.8 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. `before-all-elements-highlight`
464 * 3. All hooks of {@link Prism.highlightElement} for each element.
465 *
466 * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
467 * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
468 * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
469 * @memberof Prism
470 * @public
471 */
472 highlightAllUnder: function(container, async, callback) {
473 var env = {
474 callback: callback,
475 container: container,
476 selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
477 };
478
479 _.hooks.run('before-highlightall', env);
480
481 env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
482
483 _.hooks.run('before-all-elements-highlight', env);
484
485 for (var i = 0, element; element = env.elements[i++];) {
486 _.highlightElement(element, async === true, env.callback);
487 }
488 },
489
490 /**
491 * Highlights the code inside a single element.
492 *
493 * The following hooks will be run:
494 * 1. `before-sanity-check`
495 * 2. `before-highlight`
496 * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
497 * 4. `before-insert`
498 * 5. `after-highlight`
499 * 6. `complete`
500 *
501 * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
502 * the element's language.
503 *
504 * @param {Element} element The element containing the code.
505 * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
506 * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
507 * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
508 * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
509 *
510 * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
511 * asynchronous highlighting to work. You can build your own bundle on the
512 * [Download page](https://prismjs.com/download.html).
513 * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
514 * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
515 * @memberof Prism
516 * @public
517 */
518 highlightElement: function(element, async, callback) {
519 // Find language
520 var language = _.util.getLanguage(element);
521 var grammar = _.languages[language];
522
523 // Set language on the element, if not present
524 element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
525
526 // Set language on the parent, for styling
527 var parent = element.parentElement;
528 if (parent && parent.nodeName.toLowerCase() === 'pre') {
529 parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
530 }
531
532 var code = element.textContent;
533
534 var env = {
535 element: element,
536 language: language,
537 grammar: grammar,
538 code: code
539 };
540
541 function insertHighlightedCode(highlightedCode) {
542 env.highlightedCode = highlightedCode;
543
544 _.hooks.run('before-insert', env);
545
546 env.element.innerHTML = env.highlightedCode;
547
548 _.hooks.run('after-highlight', env);
549 _.hooks.run('complete', env);
550 callback && callback.call(env.element);
551 }
552
553 _.hooks.run('before-sanity-check', env);
554
555 if (!env.code) {
556 _.hooks.run('complete', env);
557 callback && callback.call(env.element);
558 return;
559 }
560
561 _.hooks.run('before-highlight', env);
562
563 if (!env.grammar) {
564 insertHighlightedCode(_.util.encode(env.code));
565 return;
566 }
567
568 if (async && _self.Worker) {
569 var worker = new Worker(_.filename);
570
571 worker.onmessage = function(evt) {
572 insertHighlightedCode(evt.data);
573 };
574
575 worker.postMessage(JSON.stringify({
576 language: env.language,
577 code: env.code,
578 immediateClose: true
579 }));
580 }
581 else {
582 insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
583 }
584 },
585
586 /**
587 * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
588 * and the language definitions to use, and returns a string with the HTML produced.
589 *
590 * The following hooks will be run:
591 * 1. `before-tokenize`
592 * 2. `after-tokenize`
593 * 3. `wrap`: On each {@link Token}.
594 *
595 * @param {string} text A string with the code to be highlighted.
596 * @param {Grammar} grammar An object containing the tokens to use.
597 *
598 * Usually a language definition like `Prism.languages.markup`.
599 * @param {string} language The name of the language definition passed to `grammar`.
600 * @returns {string} The highlighted HTML.
601 * @memberof Prism
602 * @public
603 * @example
604 * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
605 */
606 highlight: function (text, grammar, language) {
607 var env = {
608 code: text,
609 grammar: grammar,
610 language: language
611 };
612 _.hooks.run('before-tokenize', env);
613 env.tokens = _.tokenize(env.code, env.grammar);
614 _.hooks.run('after-tokenize', env);
615 return Token.stringify(_.util.encode(env.tokens), env.language);
616 },
617
618 /**
619 * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
620 * and the language definitions to use, and returns an array with the tokenized code.
621 *
622 * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
623 *
624 * This method could be useful in other contexts as well, as a very crude parser.
625 *
626 * @param {string} text A string with the code to be highlighted.
627 * @param {Grammar} grammar An object containing the tokens to use.
628 *
629 * Usually a language definition like `Prism.languages.markup`.
630 * @returns {TokenStream} An array of strings and tokens, a token stream.
631 * @memberof Prism
632 * @public
633 * @example
634 * let code = `var foo = 0;`;
635 * let tokens = Prism.tokenize(code, Prism.languages.javascript);
636 * tokens.forEach(token => {
637 * if (token instanceof Prism.Token && token.type === 'number') {
638 * console.log(`Found numeric literal: ${token.content}`);
639 * }
640 * });
641 */
642 tokenize: function(text, grammar) {
643 var rest = grammar.rest;
644 if (rest) {
645 for (var token in rest) {
646 grammar[token] = rest[token];
647 }
648
649 delete grammar.rest;
650 }
651
652 var tokenList = new LinkedList();
653 addAfter(tokenList, tokenList.head, text);
654
655 matchGrammar(text, tokenList, grammar, tokenList.head, 0);
656
657 return toArray(tokenList);
658 },
659
660 /**
661 * @namespace
662 * @memberof Prism
663 * @public
664 */
665 hooks: {
666 all: {},
667
668 /**
669 * Adds the given callback to the list of callbacks for the given hook.
670 *
671 * The callback will be invoked when the hook it is registered for is run.
672 * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
673 *
674 * One callback function can be registered to multiple hooks and the same hook multiple times.
675 *
676 * @param {string} name The name of the hook.
677 * @param {HookCallback} callback The callback function which is given environment variables.
678 * @public
679 */
680 add: function (name, callback) {
681 var hooks = _.hooks.all;
682
683 hooks[name] = hooks[name] || [];
684
685 hooks[name].push(callback);
686 },
687
688 /**
689 * Runs a hook invoking all registered callbacks with the given environment variables.
690 *
691 * Callbacks will be invoked synchronously and in the order in which they were registered.
692 *
693 * @param {string} name The name of the hook.
694 * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
695 * @public
696 */
697 run: function (name, env) {
698 var callbacks = _.hooks.all[name];
699
700 if (!callbacks || !callbacks.length) {
701 return;
702 }
703
704 for (var i=0, callback; callback = callbacks[i++];) {
705 callback(env);
706 }
707 }
708 },
709
710 Token: Token
711};
712_self.Prism = _;
713
714
715// Typescript note:
716// The following can be used to import the Token type in JSDoc:
717//
718// @typedef {InstanceType<import("./prism-core")["Token"]>} Token
719
720/**
721 * Creates a new token.
722 *
723 * @param {string} type See {@link Token#type type}
724 * @param {string | TokenStream} content See {@link Token#content content}
725 * @param {string|string[]} [alias] The alias(es) of the token.
726 * @param {string} [matchedStr=""] A copy of the full string this token was created from.
727 * @class
728 * @global
729 * @public
730 */
731function Token(type, content, alias, matchedStr) {
732 /**
733 * The type of the token.
734 *
735 * This is usually the key of a pattern in a {@link Grammar}.
736 *
737 * @type {string}
738 * @see GrammarToken
739 * @public
740 */
741 this.type = type;
742 /**
743 * The strings or tokens contained by this token.
744 *
745 * This will be a token stream if the pattern matched also defined an `inside` grammar.
746 *
747 * @type {string | TokenStream}
748 * @public
749 */
750 this.content = content;
751 /**
752 * The alias(es) of the token.
753 *
754 * @type {string|string[]}
755 * @see GrammarToken
756 * @public
757 */
758 this.alias = alias;
759 // Copy of the full string this token was created from
760 this.length = (matchedStr || '').length | 0;
761}
762
763/**
764 * A token stream is an array of strings and {@link Token Token} objects.
765 *
766 * Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
767 * them.
768 *
769 * 1. No adjacent strings.
770 * 2. No empty strings.
771 *
772 * The only exception here is the token stream that only contains the empty string and nothing else.
773 *
774 * @typedef {Array<string | Token>} TokenStream
775 * @global
776 * @public
777 */
778
779/**
780 * Converts the given token or token stream to an HTML representation.
781 *
782 * The following hooks will be run:
783 * 1. `wrap`: On each {@link Token}.
784 *
785 * @param {string | Token | TokenStream} o The token or token stream to be converted.
786 * @param {string} language The name of current language.
787 * @returns {string} The HTML representation of the token or token stream.
788 * @memberof Token
789 * @static
790 */
791Token.stringify = function stringify(o, language) {
792 if (typeof o == 'string') {
793 return o;
794 }
795 if (Array.isArray(o)) {
796 var s = '';
797 o.forEach(function (e) {
798 s += stringify(e, language);
799 });
800 return s;
801 }
802
803 var env = {
804 type: o.type,
805 content: stringify(o.content, language),
806 tag: 'span',
807 classes: ['token', o.type],
808 attributes: {},
809 language: language
810 };
811
812 var aliases = o.alias;
813 if (aliases) {
814 if (Array.isArray(aliases)) {
815 Array.prototype.push.apply(env.classes, aliases);
816 } else {
817 env.classes.push(aliases);
818 }
819 }
820
821 _.hooks.run('wrap', env);
822
823 var attributes = '';
824 for (var name in env.attributes) {
825 attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
826 }
827
828 return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
829};
830
831/**
832 * @param {string} text
833 * @param {LinkedList<string | Token>} tokenList
834 * @param {any} grammar
835 * @param {LinkedListNode<string | Token>} startNode
836 * @param {number} startPos
837 * @param {RematchOptions} [rematch]
838 * @returns {void}
839 * @private
840 *
841 * @typedef RematchOptions
842 * @property {string} cause
843 * @property {number} reach
844 */
845function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
846 for (var token in grammar) {
847 if (!grammar.hasOwnProperty(token) || !grammar[token]) {
848 continue;
849 }
850
851 var patterns = grammar[token];
852 patterns = Array.isArray(patterns) ? patterns : [patterns];
853
854 for (var j = 0; j < patterns.length; ++j) {
855 if (rematch && rematch.cause == token + ',' + j) {
856 return;
857 }
858
859 var patternObj = patterns[j],
860 inside = patternObj.inside,
861 lookbehind = !!patternObj.lookbehind,
862 greedy = !!patternObj.greedy,
863 lookbehindLength = 0,
864 alias = patternObj.alias;
865
866 if (greedy && !patternObj.pattern.global) {
867 // Without the global flag, lastIndex won't work
868 var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
869 patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
870 }
871
872 /** @type {RegExp} */
873 var pattern = patternObj.pattern || patternObj;
874
875 for ( // iterate the token list and keep track of the current token/string position
876 var currentNode = startNode.next, pos = startPos;
877 currentNode !== tokenList.tail;
878 pos += currentNode.value.length, currentNode = currentNode.next
879 ) {
880
881 if (rematch && pos >= rematch.reach) {
882 break;
883 }
884
885 var str = currentNode.value;
886
887 if (tokenList.length > text.length) {
888 // Something went terribly wrong, ABORT, ABORT!
889 return;
890 }
891
892 if (str instanceof Token) {
893 continue;
894 }
895
896 var removeCount = 1; // this is the to parameter of removeBetween
897
898 if (greedy && currentNode != tokenList.tail.prev) {
899 pattern.lastIndex = pos;
900 var match = pattern.exec(text);
901 if (!match) {
902 break;
903 }
904
905 var from = match.index + (lookbehind && match[1] ? match[1].length : 0);
906 var to = match.index + match[0].length;
907 var p = pos;
908
909 // find the node that contains the match
910 p += currentNode.value.length;
911 while (from >= p) {
912 currentNode = currentNode.next;
913 p += currentNode.value.length;
914 }
915 // adjust pos (and p)
916 p -= currentNode.value.length;
917 pos = p;
918
919 // the current node is a Token, then the match starts inside another Token, which is invalid
920 if (currentNode.value instanceof Token) {
921 continue;
922 }
923
924 // find the last node which is affected by this match
925 for (
926 var k = currentNode;
927 k !== tokenList.tail && (p < to || typeof k.value === 'string');
928 k = k.next
929 ) {
930 removeCount++;
931 p += k.value.length;
932 }
933 removeCount--;
934
935 // replace with the new match
936 str = text.slice(pos, p);
937 match.index -= pos;
938 } else {
939 pattern.lastIndex = 0;
940
941 var match = pattern.exec(str);
942 }
943
944 if (!match) {
945 continue;
946 }
947
948 if (lookbehind) {
949 lookbehindLength = match[1] ? match[1].length : 0;
950 }
951
952 var from = match.index + lookbehindLength,
953 matchStr = match[0].slice(lookbehindLength),
954 to = from + matchStr.length,
955 before = str.slice(0, from),
956 after = str.slice(to);
957
958 var reach = pos + str.length;
959 if (rematch && reach > rematch.reach) {
960 rematch.reach = reach;
961 }
962
963 var removeFrom = currentNode.prev;
964
965 if (before) {
966 removeFrom = addAfter(tokenList, removeFrom, before);
967 pos += before.length;
968 }
969
970 removeRange(tokenList, removeFrom, removeCount);
971
972 var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
973 currentNode = addAfter(tokenList, removeFrom, wrapped);
974
975 if (after) {
976 addAfter(tokenList, currentNode, after);
977 }
978
979 if (removeCount > 1) {
980 // at least one Token object was removed, so we have to do some rematching
981 // this can only happen if the current pattern is greedy
982 matchGrammar(text, tokenList, grammar, currentNode.prev, pos, {
983 cause: token + ',' + j,
984 reach: reach
985 });
986 }
987 }
988 }
989 }
990}
991
992/**
993 * @typedef LinkedListNode
994 * @property {T} value
995 * @property {LinkedListNode<T> | null} prev The previous node.
996 * @property {LinkedListNode<T> | null} next The next node.
997 * @template T
998 * @private
999 */
1000
1001/**
1002 * @template T
1003 * @private
1004 */
1005function LinkedList() {
1006 /** @type {LinkedListNode<T>} */
1007 var head = { value: null, prev: null, next: null };
1008 /** @type {LinkedListNode<T>} */
1009 var tail = { value: null, prev: head, next: null };
1010 head.next = tail;
1011
1012 /** @type {LinkedListNode<T>} */
1013 this.head = head;
1014 /** @type {LinkedListNode<T>} */
1015 this.tail = tail;
1016 this.length = 0;
1017}
1018
1019/**
1020 * Adds a new node with the given value to the list.
1021 * @param {LinkedList<T>} list
1022 * @param {LinkedListNode<T>} node
1023 * @param {T} value
1024 * @returns {LinkedListNode<T>} The added node.
1025 * @template T
1026 */
1027function addAfter(list, node, value) {
1028 // assumes that node != list.tail && values.length >= 0
1029 var next = node.next;
1030
1031 var newNode = { value: value, prev: node, next: next };
1032 node.next = newNode;
1033 next.prev = newNode;
1034 list.length++;
1035
1036 return newNode;
1037}
1038/**
1039 * Removes `count` nodes after the given node. The given node will not be removed.
1040 * @param {LinkedList<T>} list
1041 * @param {LinkedListNode<T>} node
1042 * @param {number} count
1043 * @template T
1044 */
1045function removeRange(list, node, count) {
1046 var next = node.next;
1047 for (var i = 0; i < count && next !== list.tail; i++) {
1048 next = next.next;
1049 }
1050 node.next = next;
1051 next.prev = node;
1052 list.length -= i;
1053}
1054/**
1055 * @param {LinkedList<T>} list
1056 * @returns {T[]}
1057 * @template T
1058 */
1059function toArray(list) {
1060 var array = [];
1061 var node = list.head.next;
1062 while (node !== list.tail) {
1063 array.push(node.value);
1064 node = node.next;
1065 }
1066 return array;
1067}
1068
1069
1070if (!_self.document) {
1071 if (!_self.addEventListener) {
1072 // in Node.js
1073 return _;
1074 }
1075
1076 if (!_.disableWorkerMessageHandler) {
1077 // In worker
1078 _self.addEventListener('message', function (evt) {
1079 var message = JSON.parse(evt.data),
1080 lang = message.language,
1081 code = message.code,
1082 immediateClose = message.immediateClose;
1083
1084 _self.postMessage(_.highlight(code, _.languages[lang], lang));
1085 if (immediateClose) {
1086 _self.close();
1087 }
1088 }, false);
1089 }
1090
1091 return _;
1092}
1093
1094// Get current script and highlight
1095var script = _.util.currentScript();
1096
1097if (script) {
1098 _.filename = script.src;
1099
1100 if (script.hasAttribute('data-manual')) {
1101 _.manual = true;
1102 }
1103}
1104
1105function highlightAutomaticallyCallback() {
1106 if (!_.manual) {
1107 _.highlightAll();
1108 }
1109}
1110
1111if (!_.manual) {
1112 // If the document state is "loading", then we'll use DOMContentLoaded.
1113 // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
1114 // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
1115 // might take longer one animation frame to execute which can create a race condition where only some plugins have
1116 // been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
1117 // See https://github.com/PrismJS/prism/issues/2102
1118 var readyState = document.readyState;
1119 if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
1120 document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
1121 } else {
1122 if (window.requestAnimationFrame) {
1123 window.requestAnimationFrame(highlightAutomaticallyCallback);
1124 } else {
1125 window.setTimeout(highlightAutomaticallyCallback, 16);
1126 }
1127 }
1128}
1129
1130return _;
1131
1132})(_self);
1133
1134if (typeof module !== 'undefined' && module.exports) {
1135 module.exports = Prism;
1136}
1137
1138// hack for components to work correctly in node.js
1139if (typeof global !== 'undefined') {
1140 global.Prism = Prism;
1141}
1142
1143// some additional documentation/types
1144
1145/**
1146 * The expansion of a simple `RegExp` literal to support additional properties.
1147 *
1148 * @typedef GrammarToken
1149 * @property {RegExp} pattern The regular expression of the token.
1150 * @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
1151 * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
1152 * @property {boolean} [greedy=false] Whether the token is greedy.
1153 * @property {string|string[]} [alias] An optional alias or list of aliases.
1154 * @property {Grammar} [inside] The nested grammar of this token.
1155 *
1156 * The `inside` grammar will be used to tokenize the text value of each token of this kind.
1157 *
1158 * This can be used to make nested and even recursive language definitions.
1159 *
1160 * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
1161 * each another.
1162 * @global
1163 * @public
1164*/
1165
1166/**
1167 * @typedef Grammar
1168 * @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
1169 * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
1170 * @global
1171 * @public
1172 */
1173
1174/**
1175 * A function which will invoked after an element was successfully highlighted.
1176 *
1177 * @callback HighlightCallback
1178 * @param {Element} element The element successfully highlighted.
1179 * @returns {void}
1180 * @global
1181 * @public
1182*/
1183
1184/**
1185 * @callback HookCallback
1186 * @param {Object<string, any>} env The environment variables of the hook.
1187 * @returns {void}
1188 * @global
1189 * @public
1190 */
1191
1192
1193/* **********************************************
1194 Begin prism-markup.js
1195********************************************** */
1196
1197Prism.languages.markup = {
1198 'comment': /<!--[\s\S]*?-->/,
1199 'prolog': /<\?[\s\S]+?\?>/,
1200 'doctype': {
1201 // https://www.w3.org/TR/xml/#NT-doctypedecl
1202 pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
1203 greedy: true,
1204 inside: {
1205 'internal-subset': {
1206 pattern: /(\[)[\s\S]+(?=\]>$)/,
1207 lookbehind: true,
1208 greedy: true,
1209 inside: null // see below
1210 },
1211 'string': {
1212 pattern: /"[^"]*"|'[^']*'/,
1213 greedy: true
1214 },
1215 'punctuation': /^<!|>$|[[\]]/,
1216 'doctype-tag': /^DOCTYPE/,
1217 'name': /[^\s<>'"]+/
1218 }
1219 },
1220 'cdata': /<!\[CDATA\[[\s\S]*?]]>/i,
1221 'tag': {
1222 pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
1223 greedy: true,
1224 inside: {
1225 'tag': {
1226 pattern: /^<\/?[^\s>\/]+/,
1227 inside: {
1228 'punctuation': /^<\/?/,
1229 'namespace': /^[^\s>\/:]+:/
1230 }
1231 },
1232 'attr-value': {
1233 pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
1234 inside: {
1235 'punctuation': [
1236 {
1237 pattern: /^=/,
1238 alias: 'attr-equals'
1239 },
1240 /"|'/
1241 ]
1242 }
1243 },
1244 'punctuation': /\/?>/,
1245 'attr-name': {
1246 pattern: /[^\s>\/]+/,
1247 inside: {
1248 'namespace': /^[^\s>\/:]+:/
1249 }
1250 }
1251
1252 }
1253 },
1254 'entity': [
1255 {
1256 pattern: /&[\da-z]{1,8};/i,
1257 alias: 'named-entity'
1258 },
1259 /&#x?[\da-f]{1,8};/i
1260 ]
1261};
1262
1263Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
1264 Prism.languages.markup['entity'];
1265Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
1266
1267// Plugin to make entity title show the real entity, idea by Roman Komarov
1268Prism.hooks.add('wrap', function (env) {
1269
1270 if (env.type === 'entity') {
1271 env.attributes['title'] = env.content.replace(/&amp;/, '&');
1272 }
1273});
1274
1275Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
1276 /**
1277 * Adds an inlined language to markup.
1278 *
1279 * An example of an inlined language is CSS with `<style>` tags.
1280 *
1281 * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
1282 * case insensitive.
1283 * @param {string} lang The language key.
1284 * @example
1285 * addInlined('style', 'css');
1286 */
1287 value: function addInlined(tagName, lang) {
1288 var includedCdataInside = {};
1289 includedCdataInside['language-' + lang] = {
1290 pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
1291 lookbehind: true,
1292 inside: Prism.languages[lang]
1293 };
1294 includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
1295
1296 var inside = {
1297 'included-cdata': {
1298 pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
1299 inside: includedCdataInside
1300 }
1301 };
1302 inside['language-' + lang] = {
1303 pattern: /[\s\S]+/,
1304 inside: Prism.languages[lang]
1305 };
1306
1307 var def = {};
1308 def[tagName] = {
1309 pattern: RegExp(/(<__[\s\S]*?>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () { return tagName; }), 'i'),
1310 lookbehind: true,
1311 greedy: true,
1312 inside: inside
1313 };
1314
1315 Prism.languages.insertBefore('markup', 'cdata', def);
1316 }
1317});
1318
1319Prism.languages.html = Prism.languages.markup;
1320Prism.languages.mathml = Prism.languages.markup;
1321Prism.languages.svg = Prism.languages.markup;
1322
1323Prism.languages.xml = Prism.languages.extend('markup', {});
1324Prism.languages.ssml = Prism.languages.xml;
1325Prism.languages.atom = Prism.languages.xml;
1326Prism.languages.rss = Prism.languages.xml;
1327
1328
1329/* **********************************************
1330 Begin prism-css.js
1331********************************************** */
1332
1333(function (Prism) {
1334
1335 var string = /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/;
1336
1337 Prism.languages.css = {
1338 'comment': /\/\*[\s\S]*?\*\//,
1339 'atrule': {
1340 pattern: /@[\w-]+[\s\S]*?(?:;|(?=\s*\{))/,
1341 inside: {
1342 'rule': /^@[\w-]+/,
1343 'selector-function-argument': {
1344 pattern: /(\bselector\s*\((?!\s*\))\s*)(?:[^()]|\((?:[^()]|\([^()]*\))*\))+?(?=\s*\))/,
1345 lookbehind: true,
1346 alias: 'selector'
1347 },
1348 'keyword': {
1349 pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
1350 lookbehind: true
1351 }
1352 // See rest below
1353 }
1354 },
1355 'url': {
1356 // https://drafts.csswg.org/css-values-3/#urls
1357 pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
1358 greedy: true,
1359 inside: {
1360 'function': /^url/i,
1361 'punctuation': /^\(|\)$/,
1362 'string': {
1363 pattern: RegExp('^' + string.source + '$'),
1364 alias: 'url'
1365 }
1366 }
1367 },
1368 'selector': RegExp('[^{}\\s](?:[^{};"\']|' + string.source + ')*?(?=\\s*\\{)'),
1369 'string': {
1370 pattern: string,
1371 greedy: true
1372 },
1373 'property': /[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,
1374 'important': /!important\b/i,
1375 'function': /[-a-z0-9]+(?=\()/i,
1376 'punctuation': /[(){};:,]/
1377 };
1378
1379 Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
1380
1381 var markup = Prism.languages.markup;
1382 if (markup) {
1383 markup.tag.addInlined('style', 'css');
1384
1385 Prism.languages.insertBefore('inside', 'attr-value', {
1386 'style-attr': {
1387 pattern: /\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,
1388 inside: {
1389 'attr-name': {
1390 pattern: /^\s*style/i,
1391 inside: markup.tag.inside
1392 },
1393 'punctuation': /^\s*=\s*['"]|['"]\s*$/,
1394 'attr-value': {
1395 pattern: /.+/i,
1396 inside: Prism.languages.css
1397 }
1398 },
1399 alias: 'language-css'
1400 }
1401 }, markup.tag);
1402 }
1403
1404}(Prism));
1405
1406
1407/* **********************************************
1408 Begin prism-clike.js
1409********************************************** */
1410
1411Prism.languages.clike = {
1412 'comment': [
1413 {
1414 pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
1415 lookbehind: true
1416 },
1417 {
1418 pattern: /(^|[^\\:])\/\/.*/,
1419 lookbehind: true,
1420 greedy: true
1421 }
1422 ],
1423 'string': {
1424 pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
1425 greedy: true
1426 },
1427 'class-name': {
1428 pattern: /(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,
1429 lookbehind: true,
1430 inside: {
1431 'punctuation': /[.\\]/
1432 }
1433 },
1434 'keyword': /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
1435 'boolean': /\b(?:true|false)\b/,
1436 'function': /\w+(?=\()/,
1437 'number': /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,
1438 'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
1439 'punctuation': /[{}[\];(),.:]/
1440};
1441
1442
1443/* **********************************************
1444 Begin prism-javascript.js
1445********************************************** */
1446
1447Prism.languages.javascript = Prism.languages.extend('clike', {
1448 'class-name': [
1449 Prism.languages.clike['class-name'],
1450 {
1451 pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/,
1452 lookbehind: true
1453 }
1454 ],
1455 'keyword': [
1456 {
1457 pattern: /((?:^|})\s*)(?:catch|finally)\b/,
1458 lookbehind: true
1459 },
1460 {
1461 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/,
1462 lookbehind: true
1463 },
1464 ],
1465 '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)?)+)?/,
1466 // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
1467 'function': /#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
1468 'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
1469});
1470
1471Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/;
1472
1473Prism.languages.insertBefore('javascript', 'keyword', {
1474 'regex': {
1475 pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,
1476 lookbehind: true,
1477 greedy: true,
1478 inside: {
1479 'regex-source': {
1480 pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
1481 lookbehind: true,
1482 alias: 'language-regex',
1483 inside: Prism.languages.regex
1484 },
1485 'regex-flags': /[a-z]+$/,
1486 'regex-delimiter': /^\/|\/$/
1487 }
1488 },
1489 // This must be declared before keyword because we use "function" inside the look-forward
1490 'function-variable': {
1491 pattern: /#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/,
1492 alias: 'function'
1493 },
1494 'parameter': [
1495 {
1496 pattern: /(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/,
1497 lookbehind: true,
1498 inside: Prism.languages.javascript
1499 },
1500 {
1501 pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i,
1502 inside: Prism.languages.javascript
1503 },
1504 {
1505 pattern: /(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/,
1506 lookbehind: true,
1507 inside: Prism.languages.javascript
1508 },
1509 {
1510 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*\{)/,
1511 lookbehind: true,
1512 inside: Prism.languages.javascript
1513 }
1514 ],
1515 'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
1516});
1517
1518Prism.languages.insertBefore('javascript', 'string', {
1519 'template-string': {
1520 pattern: /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}|(?!\${)[^\\`])*`/,
1521 greedy: true,
1522 inside: {
1523 'template-punctuation': {
1524 pattern: /^`|`$/,
1525 alias: 'string'
1526 },
1527 'interpolation': {
1528 pattern: /((?:^|[^\\])(?:\\{2})*)\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}/,
1529 lookbehind: true,
1530 inside: {
1531 'interpolation-punctuation': {
1532 pattern: /^\${|}$/,
1533 alias: 'punctuation'
1534 },
1535 rest: Prism.languages.javascript
1536 }
1537 },
1538 'string': /[\s\S]+/
1539 }
1540 }
1541});
1542
1543if (Prism.languages.markup) {
1544 Prism.languages.markup.tag.addInlined('script', 'javascript');
1545}
1546
1547Prism.languages.js = Prism.languages.javascript;
1548
1549
1550/* **********************************************
1551 Begin prism-file-highlight.js
1552********************************************** */
1553
1554(function () {
1555 if (typeof self === 'undefined' || !self.Prism || !self.document) {
1556 return;
1557 }
1558
1559 var Prism = window.Prism;
1560
1561 var LOADING_MESSAGE = 'Loading…';
1562 var FAILURE_MESSAGE = function (status, message) {
1563 return '✖ Error ' + status + ' while fetching file: ' + message;
1564 };
1565 var FAILURE_EMPTY_MESSAGE = '✖ Error: File does not exist or is empty';
1566
1567 var EXTENSIONS = {
1568 'js': 'javascript',
1569 'py': 'python',
1570 'rb': 'ruby',
1571 'ps1': 'powershell',
1572 'psm1': 'powershell',
1573 'sh': 'bash',
1574 'bat': 'batch',
1575 'h': 'c',
1576 'tex': 'latex'
1577 };
1578
1579 var STATUS_ATTR = 'data-src-status';
1580 var STATUS_LOADING = 'loading';
1581 var STATUS_LOADED = 'loaded';
1582 var STATUS_FAILED = 'failed';
1583
1584 var SELECTOR = 'pre[data-src]:not([' + STATUS_ATTR + '="' + STATUS_LOADED + '"])'
1585 + ':not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
1586
1587 var lang = /\blang(?:uage)?-([\w-]+)\b/i;
1588
1589 /**
1590 * Sets the Prism `language-xxxx` or `lang-xxxx` class to the given language.
1591 *
1592 * @param {HTMLElement} element
1593 * @param {string} language
1594 * @returns {void}
1595 */
1596 function setLanguageClass(element, language) {
1597 var className = element.className;
1598 className = className.replace(lang, ' ') + ' language-' + language;
1599 element.className = className.replace(/\s+/g, ' ').trim();
1600 }
1601
1602
1603 Prism.hooks.add('before-highlightall', function (env) {
1604 env.selector += ', ' + SELECTOR;
1605 });
1606
1607 Prism.hooks.add('before-sanity-check', function (env) {
1608 var pre = /** @type {HTMLPreElement} */ (env.element);
1609 if (pre.matches(SELECTOR)) {
1610 env.code = ''; // fast-path the whole thing and go to complete
1611
1612 pre.setAttribute(STATUS_ATTR, STATUS_LOADING); // mark as loading
1613
1614 // add code element with loading message
1615 var code = pre.appendChild(document.createElement('CODE'));
1616 code.textContent = LOADING_MESSAGE;
1617
1618 var src = pre.getAttribute('data-src');
1619
1620 var language = env.language;
1621 if (language === 'none') {
1622 // the language might be 'none' because there is no language set;
1623 // in this case, we want to use the extension as the language
1624 var extension = (/\.(\w+)$/.exec(src) || [, 'none'])[1];
1625 language = EXTENSIONS[extension] || extension;
1626 }
1627
1628 // set language classes
1629 setLanguageClass(code, language);
1630 setLanguageClass(pre, language);
1631
1632 // preload the language
1633 var autoloader = Prism.plugins.autoloader;
1634 if (autoloader) {
1635 autoloader.loadLanguages(language);
1636 }
1637
1638 // load file
1639 var xhr = new XMLHttpRequest();
1640 xhr.open('GET', src, true);
1641 xhr.onreadystatechange = function () {
1642 if (xhr.readyState == 4) {
1643 if (xhr.status < 400 && xhr.responseText) {
1644 // mark as loaded
1645 pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
1646
1647 // highlight code
1648 code.textContent = xhr.responseText;
1649 Prism.highlightElement(code);
1650
1651 } else {
1652 // mark as failed
1653 pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
1654
1655 if (xhr.status >= 400) {
1656 code.textContent = FAILURE_MESSAGE(xhr.status, xhr.statusText);
1657 } else {
1658 code.textContent = FAILURE_EMPTY_MESSAGE;
1659 }
1660 }
1661 }
1662 };
1663 xhr.send(null);
1664 }
1665 });
1666
1667 Prism.plugins.fileHighlight = {
1668 /**
1669 * Executes the File Highlight plugin for all matching `pre` elements under the given container.
1670 *
1671 * Note: Elements which are already loaded or currently loading will not be touched by this method.
1672 *
1673 * @param {ParentNode} [container=document]
1674 */
1675 highlight: function highlight(container) {
1676 var elements = (container || document).querySelectorAll(SELECTOR);
1677
1678 for (var i = 0, element; element = elements[i++];) {
1679 Prism.highlightElement(element);
1680 }
1681 }
1682 };
1683
1684 var logged = false;
1685 /** @deprecated Use `Prism.plugins.fileHighlight.highlight` instead. */
1686 Prism.fileHighlight = function () {
1687 if (!logged) {
1688 console.warn('Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.');
1689 logged = true;
1690 }
1691 Prism.plugins.fileHighlight.highlight.apply(this, arguments);
1692 }
1693
1694})();