Debian Codegraph @

docs/prism-core.js.html

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