prism.js 49 KB

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