5621 lines · 178.2 KB · JavaScript
RawDownload
/* PrismJS 1.30.0https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript+bash+c+cpp+cmake+coffeescript+crystal+d+dart+diff+django+elixir+erlang+go+groovy+java+json+julia+kotlin+latex+lua+markdown+markup-templating+matlab+nginx+nim+nix+ocaml+perl+php+python+qml+r+jsx+ruby+rust+scss+scala+shell-session+sql+tcl+typescript+yaml+zig *//// <reference lib="WebWorker"/> var _self = (typeof window !== 'undefined')	? window   // if in browser	: (		(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)			? self // if in worker			: {}   // if in node js	); /** * Prism: Lightweight, robust, elegant syntax highlighting * * @license MIT <https://opensource.org/licenses/MIT> * @author Lea Verou <https://lea.verou.me> * @namespace * @public */var Prism = (function (_self) { 	// Private helper vars	var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;	var uniqueId = 0; 	// The grammar object for plaintext	var plainTextGrammar = {};  	var _ = {		/**		 * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the		 * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load		 * additional languages or plugins yourself.		 *		 * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.		 *		 * You obviously have to change this value before the automatic highlighting started. To do this, you can add an		 * empty Prism object into the global scope before loading the Prism script like this:		 *		 * ```js		 * window.Prism = window.Prism || {};		 * Prism.manual = true;		 * // add a new <script> to load Prism's script		 * ```		 *		 * @default false		 * @type {boolean}		 * @memberof Prism		 * @public		 */		manual: _self.Prism && _self.Prism.manual,		/**		 * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses		 * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your		 * own worker, you don't want it to do this.		 *		 * By setting this value to `true`, Prism will not add its own listeners to the worker.		 *		 * You obviously have to change this value before Prism executes. To do this, you can add an		 * empty Prism object into the global scope before loading the Prism script like this:		 *		 * ```js		 * window.Prism = window.Prism || {};		 * Prism.disableWorkerMessageHandler = true;		 * // Load Prism's script		 * ```		 *		 * @default false		 * @type {boolean}		 * @memberof Prism		 * @public		 */		disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler, 		/**		 * A namespace for utility methods.		 *		 * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may		 * change or disappear at any time.		 *		 * @namespace		 * @memberof Prism		 */		util: {			encode: function encode(tokens) {				if (tokens instanceof Token) {					return new Token(tokens.type, encode(tokens.content), tokens.alias);				} else if (Array.isArray(tokens)) {					return tokens.map(encode);				} else {					return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');				}			}, 			/**			 * Returns the name of the type of the given value.			 *			 * @param {any} o			 * @returns {string}			 * @example			 * type(null)      === 'Null'			 * type(undefined) === 'Undefined'			 * type(123)       === 'Number'			 * type('foo')     === 'String'			 * type(true)      === 'Boolean'			 * type([1, 2])    === 'Array'			 * type({})        === 'Object'			 * type(String)    === 'Function'			 * type(/abc+/)    === 'RegExp'			 */			type: function (o) {				return Object.prototype.toString.call(o).slice(8, -1);			}, 			/**			 * Returns a unique number for the given object. Later calls will still return the same number.			 *			 * @param {Object} obj			 * @returns {number}			 */			objId: function (obj) {				if (!obj['__id']) {					Object.defineProperty(obj, '__id', { value: ++uniqueId });				}				return obj['__id'];			}, 			/**			 * Creates a deep clone of the given object.			 *			 * The main intended use of this function is to clone language definitions.			 *			 * @param {T} o			 * @param {Record<number, any>} [visited]			 * @returns {T}			 * @template T			 */			clone: function deepClone(o, visited) {				visited = visited || {}; 				var clone; var id;				switch (_.util.type(o)) {					case 'Object':						id = _.util.objId(o);						if (visited[id]) {							return visited[id];						}						clone = /** @type {Record<string, any>} */ ({});						visited[id] = clone; 						for (var key in o) {							if (o.hasOwnProperty(key)) {								clone[key] = deepClone(o[key], visited);							}						} 						return /** @type {any} */ (clone); 					case 'Array':						id = _.util.objId(o);						if (visited[id]) {							return visited[id];						}						clone = [];						visited[id] = clone; 						(/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) {							clone[i] = deepClone(v, visited);						}); 						return /** @type {any} */ (clone); 					default:						return o;				}			}, 			/**			 * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.			 *			 * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.			 *			 * @param {Element} element			 * @returns {string}			 */			getLanguage: function (element) {				while (element) {					var m = lang.exec(element.className);					if (m) {						return m[1].toLowerCase();					}					element = element.parentElement;				}				return 'none';			}, 			/**			 * Sets the Prism `language-xxxx` class of the given element.			 *			 * @param {Element} element			 * @param {string} language			 * @returns {void}			 */			setLanguage: function (element, language) {				// remove all `language-xxxx` classes				// (this might leave behind a leading space)				element.className = element.className.replace(RegExp(lang, 'gi'), ''); 				// add the new `language-xxxx` class				// (using `classList` will automatically clean up spaces for us)				element.classList.add('language-' + language);			}, 			/**			 * Returns the script element that is currently executing.			 *			 * This does __not__ work for line script element.			 *			 * @returns {HTMLScriptElement | null}			 */			currentScript: function () {				if (typeof document === 'undefined') {					return null;				}				if (document.currentScript && document.currentScript.tagName === 'SCRIPT' && 1 < 2 /* hack to trip TS' flow analysis */) {					return /** @type {any} */ (document.currentScript);				} 				// IE11 workaround				// we'll get the src of the current script by parsing IE11's error stack trace				// this will not work for inline scripts 				try {					throw new Error();				} catch (err) {					// Get file src url from stack. Specifically works with the format of stack traces in IE.					// A stack will look like this:					//					// Error					//    at _.util.currentScript (http://localhost/components/prism-core.js:119:5)					//    at Global code (http://localhost/components/prism-core.js:606:1) 					var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];					if (src) {						var scripts = document.getElementsByTagName('script');						for (var i in scripts) {							if (scripts[i].src == src) {								return scripts[i];							}						}					}					return null;				}			}, 			/**			 * Returns whether a given class is active for `element`.			 *			 * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated			 * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the			 * given class is just the given class with a `no-` prefix.			 *			 * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is			 * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its			 * ancestors have the given class or the negated version of it, then the default activation will be returned.			 *			 * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated			 * version of it, the class is considered active.			 *			 * @param {Element} element			 * @param {string} className			 * @param {boolean} [defaultActivation=false]			 * @returns {boolean}			 */			isActive: function (element, className, defaultActivation) {				var no = 'no-' + className; 				while (element) {					var classList = element.classList;					if (classList.contains(className)) {						return true;					}					if (classList.contains(no)) {						return false;					}					element = element.parentElement;				}				return !!defaultActivation;			}		}, 		/**		 * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.		 *		 * @namespace		 * @memberof Prism		 * @public		 */		languages: {			/**			 * The grammar for plain, unformatted text.			 */			plain: plainTextGrammar,			plaintext: plainTextGrammar,			text: plainTextGrammar,			txt: plainTextGrammar, 			/**			 * Creates a deep copy of the language with the given id and appends the given tokens.			 *			 * If a token in `redef` also appears in the copied language, then the existing token in the copied language			 * will be overwritten at its original position.			 *			 * ## Best practices			 *			 * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)			 * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to			 * understand the language definition because, normally, the order of tokens matters in Prism grammars.			 *			 * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.			 * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.			 *			 * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.			 * @param {Grammar} redef The new tokens to append.			 * @returns {Grammar} The new language created.			 * @public			 * @example			 * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {			 *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token			 *     // at its original position			 *     'comment': { ... },			 *     // CSS doesn't have a 'color' token, so this token will be appended			 *     'color': /\b(?:red|green|blue)\b/			 * });			 */			extend: function (id, redef) {				var lang = _.util.clone(_.languages[id]); 				for (var key in redef) {					lang[key] = redef[key];				} 				return lang;			}, 			/**			 * Inserts tokens _before_ another token in a language definition or any other grammar.			 *			 * ## Usage			 *			 * This helper method makes it easy to modify existing languages. For example, the CSS language definition			 * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded			 * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the			 * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do			 * this:			 *			 * ```js			 * Prism.languages.markup.style = {			 *     // token			 * };			 * ```			 *			 * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens			 * before existing tokens. For the CSS example above, you would use it like this:			 *			 * ```js			 * Prism.languages.insertBefore('markup', 'cdata', {			 *     'style': {			 *         // token			 *     }			 * });			 * ```			 *			 * ## Special cases			 *			 * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar			 * will be ignored.			 *			 * This behavior can be used to insert tokens after `before`:			 *			 * ```js			 * Prism.languages.insertBefore('markup', 'comment', {			 *     'comment': Prism.languages.markup.comment,			 *     // tokens after 'comment'			 * });			 * ```			 *			 * ## Limitations			 *			 * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object			 * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave			 * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily			 * deleting properties which is necessary to insert at arbitrary positions.			 *			 * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.			 * Instead, it will create a new object and replace all references to the target object with the new one. This			 * can be done without temporarily deleting properties, so the iteration order is well-defined.			 *			 * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if			 * you hold the target object in a variable, then the value of the variable will not change.			 *			 * ```js			 * var oldMarkup = Prism.languages.markup;			 * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });			 *			 * assert(oldMarkup !== Prism.languages.markup);			 * assert(newMarkup === Prism.languages.markup);			 * ```			 *			 * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the			 * object to be modified.			 * @param {string} before The key to insert before.			 * @param {Grammar} insert An object containing the key-value pairs to be inserted.			 * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the			 * object to be modified.			 *			 * Defaults to `Prism.languages`.			 * @returns {Grammar} The new grammar object.			 * @public			 */			insertBefore: function (inside, before, insert, root) {				root = root || /** @type {any} */ (_.languages);				var grammar = root[inside];				/** @type {Grammar} */				var ret = {}; 				for (var token in grammar) {					if (grammar.hasOwnProperty(token)) { 						if (token == before) {							for (var newToken in insert) {								if (insert.hasOwnProperty(newToken)) {									ret[newToken] = insert[newToken];								}							}						} 						// Do not insert token which also occur in insert. See #1525						if (!insert.hasOwnProperty(token)) {							ret[token] = grammar[token];						}					}				} 				var old = root[inside];				root[inside] = ret; 				// Update references in other language definitions				_.languages.DFS(_.languages, function (key, value) {					if (value === old && key != inside) {						this[key] = ret;					}				}); 				return ret;			}, 			// Traverse a language definition with Depth First Search			DFS: function DFS(o, callback, type, visited) {				visited = visited || {}; 				var objId = _.util.objId; 				for (var i in o) {					if (o.hasOwnProperty(i)) {						callback.call(o, i, o[i], type || i); 						var property = o[i];						var propertyType = _.util.type(property); 						if (propertyType === 'Object' && !visited[objId(property)]) {							visited[objId(property)] = true;							DFS(property, callback, null, visited);						} else if (propertyType === 'Array' && !visited[objId(property)]) {							visited[objId(property)] = true;							DFS(property, callback, i, visited);						}					}				}			}		}, 		plugins: {}, 		/**		 * This is the most high-level function in Prism’s API.		 * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on		 * each one of them.		 *		 * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.		 *		 * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.		 * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.		 * @memberof Prism		 * @public		 */		highlightAll: function (async, callback) {			_.highlightAllUnder(document, async, callback);

Lines 1–500 of 5621.