prism.js 57 KB

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