prism.js 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304
  1. /* PrismJS 1.28.0
  2. https://prismjs.com/download.html#themes=prism-coy&languages=markup+css+clike+javascript+python+sql+visual-basic&plugins=line-numbers+normalize-whitespace */
  3. /// <reference lib="WebWorker"/>
  4. var _self = (typeof window !== 'undefined')
  5. ? window // if in browser
  6. : (
  7. (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
  8. ? self // if in worker
  9. : {} // if in node js
  10. );
  11. /**
  12. * Prism: Lightweight, robust, elegant syntax highlighting
  13. *
  14. * @license MIT <https://opensource.org/licenses/MIT>
  15. * @author Lea Verou <https://lea.verou.me>
  16. * @namespace
  17. * @public
  18. */
  19. var Prism = (function (_self) {
  20. // Private helper vars
  21. var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
  22. var uniqueId = 0;
  23. // The grammar object for plaintext
  24. var plainTextGrammar = {};
  25. var _ = {
  26. /**
  27. * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
  28. * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
  29. * additional languages or plugins yourself.
  30. *
  31. * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
  32. *
  33. * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
  34. * empty Prism object into the global scope before loading the Prism script like this:
  35. *
  36. * ```js
  37. * window.Prism = window.Prism || {};
  38. * Prism.manual = true;
  39. * // add a new <script> to load Prism's script
  40. * ```
  41. *
  42. * @default false
  43. * @type {boolean}
  44. * @memberof Prism
  45. * @public
  46. */
  47. manual: _self.Prism && _self.Prism.manual,
  48. /**
  49. * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
  50. * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
  51. * own worker, you don't want it to do this.
  52. *
  53. * By setting this value to `true`, Prism will not add its own listeners to the worker.
  54. *
  55. * You obviously have to change this value before Prism executes. To do this, you can add an
  56. * empty Prism object into the global scope before loading the Prism script like this:
  57. *
  58. * ```js
  59. * window.Prism = window.Prism || {};
  60. * Prism.disableWorkerMessageHandler = true;
  61. * // Load Prism's script
  62. * ```
  63. *
  64. * @default false
  65. * @type {boolean}
  66. * @memberof Prism
  67. * @public
  68. */
  69. disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler,
  70. /**
  71. * A namespace for utility methods.
  72. *
  73. * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
  74. * change or disappear at any time.
  75. *
  76. * @namespace
  77. * @memberof Prism
  78. */
  79. util: {
  80. encode: function encode(tokens) {
  81. if (tokens instanceof Token) {
  82. return new Token(tokens.type, encode(tokens.content), tokens.alias);
  83. } else if (Array.isArray(tokens)) {
  84. return tokens.map(encode);
  85. } else {
  86. return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
  87. }
  88. },
  89. /**
  90. * Returns the name of the type of the given value.
  91. *
  92. * @param {any} o
  93. * @returns {string}
  94. * @example
  95. * type(null) === 'Null'
  96. * type(undefined) === 'Undefined'
  97. * type(123) === 'Number'
  98. * type('foo') === 'String'
  99. * type(true) === 'Boolean'
  100. * type([1, 2]) === 'Array'
  101. * type({}) === 'Object'
  102. * type(String) === 'Function'
  103. * type(/abc+/) === 'RegExp'
  104. */
  105. type: function (o) {
  106. return Object.prototype.toString.call(o).slice(8, -1);
  107. },
  108. /**
  109. * Returns a unique number for the given object. Later calls will still return the same number.
  110. *
  111. * @param {Object} obj
  112. * @returns {number}
  113. */
  114. objId: function (obj) {
  115. if (!obj['__id']) {
  116. Object.defineProperty(obj, '__id', { value: ++uniqueId });
  117. }
  118. return obj['__id'];
  119. },
  120. /**
  121. * Creates a deep clone of the given object.
  122. *
  123. * The main intended use of this function is to clone language definitions.
  124. *
  125. * @param {T} o
  126. * @param {Record<number, any>} [visited]
  127. * @returns {T}
  128. * @template T
  129. */
  130. clone: function deepClone(o, visited) {
  131. visited = visited || {};
  132. var clone; var id;
  133. switch (_.util.type(o)) {
  134. case 'Object':
  135. id = _.util.objId(o);
  136. if (visited[id]) {
  137. return visited[id];
  138. }
  139. clone = /** @type {Record<string, any>} */ ({});
  140. visited[id] = clone;
  141. for (var key in o) {
  142. if (o.hasOwnProperty(key)) {
  143. clone[key] = deepClone(o[key], visited);
  144. }
  145. }
  146. return /** @type {any} */ (clone);
  147. case 'Array':
  148. id = _.util.objId(o);
  149. if (visited[id]) {
  150. return visited[id];
  151. }
  152. clone = [];
  153. visited[id] = clone;
  154. (/** @type {Array} */(/** @type {any} */(o))).forEach(function (v, i) {
  155. clone[i] = deepClone(v, visited);
  156. });
  157. return /** @type {any} */ (clone);
  158. default:
  159. return o;
  160. }
  161. },
  162. /**
  163. * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
  164. *
  165. * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
  166. *
  167. * @param {Element} element
  168. * @returns {string}
  169. */
  170. getLanguage: function (element) {
  171. while (element) {
  172. var m = lang.exec(element.className);
  173. if (m) {
  174. return m[1].toLowerCase();
  175. }
  176. element = element.parentElement;
  177. }
  178. return 'none';
  179. },
  180. /**
  181. * Sets the Prism `language-xxxx` class of the given element.
  182. *
  183. * @param {Element} element
  184. * @param {string} language
  185. * @returns {void}
  186. */
  187. setLanguage: function (element, language) {
  188. // remove all `language-xxxx` classes
  189. // (this might leave behind a leading space)
  190. element.className = element.className.replace(RegExp(lang, 'gi'), '');
  191. // add the new `language-xxxx` class
  192. // (using `classList` will automatically clean up spaces for us)
  193. element.classList.add('language-' + language);
  194. },
  195. /**
  196. * Returns the script element that is currently executing.
  197. *
  198. * This does __not__ work for line script element.
  199. *
  200. * @returns {HTMLScriptElement | null}
  201. */
  202. currentScript: function () {
  203. if (typeof document === 'undefined') {
  204. return null;
  205. }
  206. if ('currentScript' in document && 1 < 2 /* hack to trip TS' flow analysis */) {
  207. return /** @type {any} */ (document.currentScript);
  208. }
  209. // IE11 workaround
  210. // we'll get the src of the current script by parsing IE11's error stack trace
  211. // this will not work for inline scripts
  212. try {
  213. throw new Error();
  214. } catch (err) {
  215. // Get file src url from stack. Specifically works with the format of stack traces in IE.
  216. // A stack will look like this:
  217. //
  218. // Error
  219. // at _.util.currentScript (http://localhost/components/prism-core.js:119:5)
  220. // at Global code (http://localhost/components/prism-core.js:606:1)
  221. var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
  222. if (src) {
  223. var scripts = document.getElementsByTagName('script');
  224. for (var i in scripts) {
  225. if (scripts[i].src == src) {
  226. return scripts[i];
  227. }
  228. }
  229. }
  230. return null;
  231. }
  232. },
  233. /**
  234. * Returns whether a given class is active for `element`.
  235. *
  236. * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
  237. * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
  238. * given class is just the given class with a `no-` prefix.
  239. *
  240. * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
  241. * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
  242. * ancestors have the given class or the negated version of it, then the default activation will be returned.
  243. *
  244. * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
  245. * version of it, the class is considered active.
  246. *
  247. * @param {Element} element
  248. * @param {string} className
  249. * @param {boolean} [defaultActivation=false]
  250. * @returns {boolean}
  251. */
  252. isActive: function (element, className, defaultActivation) {
  253. var no = 'no-' + className;
  254. while (element) {
  255. var classList = element.classList;
  256. if (classList.contains(className)) {
  257. return true;
  258. }
  259. if (classList.contains(no)) {
  260. return false;
  261. }
  262. element = element.parentElement;
  263. }
  264. return !!defaultActivation;
  265. }
  266. },
  267. /**
  268. * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
  269. *
  270. * @namespace
  271. * @memberof Prism
  272. * @public
  273. */
  274. languages: {
  275. /**
  276. * The grammar for plain, unformatted text.
  277. */
  278. plain: plainTextGrammar,
  279. plaintext: plainTextGrammar,
  280. text: plainTextGrammar,
  281. txt: plainTextGrammar,
  282. /**
  283. * Creates a deep copy of the language with the given id and appends the given tokens.
  284. *
  285. * If a token in `redef` also appears in the copied language, then the existing token in the copied language
  286. * will be overwritten at its original position.
  287. *
  288. * ## Best practices
  289. *
  290. * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
  291. * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
  292. * understand the language definition because, normally, the order of tokens matters in Prism grammars.
  293. *
  294. * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
  295. * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
  296. *
  297. * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
  298. * @param {Grammar} redef The new tokens to append.
  299. * @returns {Grammar} The new language created.
  300. * @public
  301. * @example
  302. * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
  303. * // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
  304. * // at its original position
  305. * 'comment': { ... },
  306. * // CSS doesn't have a 'color' token, so this token will be appended
  307. * 'color': /\b(?:red|green|blue)\b/
  308. * });
  309. */
  310. extend: function (id, redef) {
  311. var lang = _.util.clone(_.languages[id]);
  312. for (var key in redef) {
  313. lang[key] = redef[key];
  314. }
  315. return lang;
  316. },
  317. /**
  318. * Inserts tokens _before_ another token in a language definition or any other grammar.
  319. *
  320. * ## Usage
  321. *
  322. * This helper method makes it easy to modify existing languages. For example, the CSS language definition
  323. * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
  324. * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
  325. * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
  326. * this:
  327. *
  328. * ```js
  329. * Prism.languages.markup.style = {
  330. * // token
  331. * };
  332. * ```
  333. *
  334. * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
  335. * before existing tokens. For the CSS example above, you would use it like this:
  336. *
  337. * ```js
  338. * Prism.languages.insertBefore('markup', 'cdata', {
  339. * 'style': {
  340. * // token
  341. * }
  342. * });
  343. * ```
  344. *
  345. * ## Special cases
  346. *
  347. * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
  348. * will be ignored.
  349. *
  350. * This behavior can be used to insert tokens after `before`:
  351. *
  352. * ```js
  353. * Prism.languages.insertBefore('markup', 'comment', {
  354. * 'comment': Prism.languages.markup.comment,
  355. * // tokens after 'comment'
  356. * });
  357. * ```
  358. *
  359. * ## Limitations
  360. *
  361. * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
  362. * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
  363. * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
  364. * deleting properties which is necessary to insert at arbitrary positions.
  365. *
  366. * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
  367. * Instead, it will create a new object and replace all references to the target object with the new one. This
  368. * can be done without temporarily deleting properties, so the iteration order is well-defined.
  369. *
  370. * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
  371. * you hold the target object in a variable, then the value of the variable will not change.
  372. *
  373. * ```js
  374. * var oldMarkup = Prism.languages.markup;
  375. * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
  376. *
  377. * assert(oldMarkup !== Prism.languages.markup);
  378. * assert(newMarkup === Prism.languages.markup);
  379. * ```
  380. *
  381. * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
  382. * object to be modified.
  383. * @param {string} before The key to insert before.
  384. * @param {Grammar} insert An object containing the key-value pairs to be inserted.
  385. * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
  386. * object to be modified.
  387. *
  388. * Defaults to `Prism.languages`.
  389. * @returns {Grammar} The new grammar object.
  390. * @public
  391. */
  392. insertBefore: function (inside, before, insert, root) {
  393. root = root || /** @type {any} */ (_.languages);
  394. var grammar = root[inside];
  395. /** @type {Grammar} */
  396. var ret = {};
  397. for (var token in grammar) {
  398. if (grammar.hasOwnProperty(token)) {
  399. if (token == before) {
  400. for (var newToken in insert) {
  401. if (insert.hasOwnProperty(newToken)) {
  402. ret[newToken] = insert[newToken];
  403. }
  404. }
  405. }
  406. // Do not insert token which also occur in insert. See #1525
  407. if (!insert.hasOwnProperty(token)) {
  408. ret[token] = grammar[token];
  409. }
  410. }
  411. }
  412. var old = root[inside];
  413. root[inside] = ret;
  414. // Update references in other language definitions
  415. _.languages.DFS(_.languages, function (key, value) {
  416. if (value === old && key != inside) {
  417. this[key] = ret;
  418. }
  419. });
  420. return ret;
  421. },
  422. // Traverse a language definition with Depth First Search
  423. DFS: function DFS(o, callback, type, visited) {
  424. visited = visited || {};
  425. var objId = _.util.objId;
  426. for (var i in o) {
  427. if (o.hasOwnProperty(i)) {
  428. callback.call(o, i, o[i], type || i);
  429. var property = o[i];
  430. var propertyType = _.util.type(property);
  431. if (propertyType === 'Object' && !visited[objId(property)]) {
  432. visited[objId(property)] = true;
  433. DFS(property, callback, null, visited);
  434. } else if (propertyType === 'Array' && !visited[objId(property)]) {
  435. visited[objId(property)] = true;
  436. DFS(property, callback, i, visited);
  437. }
  438. }
  439. }
  440. }
  441. },
  442. plugins: {},
  443. /**
  444. * This is the most high-level function in Prism’s API.
  445. * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
  446. * each one of them.
  447. *
  448. * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
  449. *
  450. * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
  451. * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
  452. * @memberof Prism
  453. * @public
  454. */
  455. highlightAll: function (async, callback) {
  456. _.highlightAllUnder(document, async, callback);
  457. },
  458. /**
  459. * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
  460. * {@link Prism.highlightElement} on each one of them.
  461. *
  462. * The following hooks will be run:
  463. * 1. `before-highlightall`
  464. * 2. `before-all-elements-highlight`
  465. * 3. All hooks of {@link Prism.highlightElement} for each element.
  466. *
  467. * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
  468. * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
  469. * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
  470. * @memberof Prism
  471. * @public
  472. */
  473. highlightAllUnder: function (container, async, callback) {
  474. var env = {
  475. callback: callback,
  476. container: container,
  477. selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
  478. };
  479. _.hooks.run('before-highlightall', env);
  480. env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
  481. _.hooks.run('before-all-elements-highlight', env);
  482. for (var i = 0, element; (element = env.elements[i++]);) {
  483. _.highlightElement(element, async === true, env.callback);
  484. }
  485. },
  486. /**
  487. * Highlights the code inside a single element.
  488. *
  489. * The following hooks will be run:
  490. * 1. `before-sanity-check`
  491. * 2. `before-highlight`
  492. * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
  493. * 4. `before-insert`
  494. * 5. `after-highlight`
  495. * 6. `complete`
  496. *
  497. * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
  498. * the element's language.
  499. *
  500. * @param {Element} element The element containing the code.
  501. * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
  502. * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
  503. * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
  504. * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
  505. *
  506. * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
  507. * asynchronous highlighting to work. You can build your own bundle on the
  508. * [Download page](https://prismjs.com/download.html).
  509. * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
  510. * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
  511. * @memberof Prism
  512. * @public
  513. */
  514. highlightElement: function (element, async, callback) {
  515. // Find language
  516. var language = _.util.getLanguage(element);
  517. var grammar = _.languages[language];
  518. // Set language on the element, if not present
  519. _.util.setLanguage(element, language);
  520. // Set language on the parent, for styling
  521. var parent = element.parentElement;
  522. if (parent && parent.nodeName.toLowerCase() === 'pre') {
  523. _.util.setLanguage(parent, language);
  524. }
  525. var code = element.textContent;
  526. var env = {
  527. element: element,
  528. language: language,
  529. grammar: grammar,
  530. code: code
  531. };
  532. function insertHighlightedCode(highlightedCode) {
  533. env.highlightedCode = highlightedCode;
  534. _.hooks.run('before-insert', env);
  535. env.element.innerHTML = env.highlightedCode;
  536. _.hooks.run('after-highlight', env);
  537. _.hooks.run('complete', env);
  538. callback && callback.call(env.element);
  539. }
  540. _.hooks.run('before-sanity-check', env);
  541. // plugins may change/add the parent/element
  542. parent = env.element.parentElement;
  543. if (parent && parent.nodeName.toLowerCase() === 'pre' && !parent.hasAttribute('tabindex')) {
  544. parent.setAttribute('tabindex', '0');
  545. }
  546. if (!env.code) {
  547. _.hooks.run('complete', env);
  548. callback && callback.call(env.element);
  549. return;
  550. }
  551. _.hooks.run('before-highlight', env);
  552. if (!env.grammar) {
  553. insertHighlightedCode(_.util.encode(env.code));
  554. return;
  555. }
  556. if (async && _self.Worker) {
  557. var worker = new Worker(_.filename);
  558. worker.onmessage = function (evt) {
  559. insertHighlightedCode(evt.data);
  560. };
  561. worker.postMessage(JSON.stringify({
  562. language: env.language,
  563. code: env.code,
  564. immediateClose: true
  565. }));
  566. } else {
  567. insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
  568. }
  569. },
  570. /**
  571. * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
  572. * and the language definitions to use, and returns a string with the HTML produced.
  573. *
  574. * The following hooks will be run:
  575. * 1. `before-tokenize`
  576. * 2. `after-tokenize`
  577. * 3. `wrap`: On each {@link Token}.
  578. *
  579. * @param {string} text A string with the code to be highlighted.
  580. * @param {Grammar} grammar An object containing the tokens to use.
  581. *
  582. * Usually a language definition like `Prism.languages.markup`.
  583. * @param {string} language The name of the language definition passed to `grammar`.
  584. * @returns {string} The highlighted HTML.
  585. * @memberof Prism
  586. * @public
  587. * @example
  588. * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
  589. */
  590. highlight: function (text, grammar, language) {
  591. var env = {
  592. code: text,
  593. grammar: grammar,
  594. language: language
  595. };
  596. _.hooks.run('before-tokenize', env);
  597. if (!env.grammar) {
  598. throw new Error('The language "' + env.language + '" has no grammar.');
  599. }
  600. env.tokens = _.tokenize(env.code, env.grammar);
  601. _.hooks.run('after-tokenize', env);
  602. return Token.stringify(_.util.encode(env.tokens), env.language);
  603. },
  604. /**
  605. * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
  606. * and the language definitions to use, and returns an array with the tokenized code.
  607. *
  608. * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
  609. *
  610. * This method could be useful in other contexts as well, as a very crude parser.
  611. *
  612. * @param {string} text A string with the code to be highlighted.
  613. * @param {Grammar} grammar An object containing the tokens to use.
  614. *
  615. * Usually a language definition like `Prism.languages.markup`.
  616. * @returns {TokenStream} An array of strings and tokens, a token stream.
  617. * @memberof Prism
  618. * @public
  619. * @example
  620. * let code = `var foo = 0;`;
  621. * let tokens = Prism.tokenize(code, Prism.languages.javascript);
  622. * tokens.forEach(token => {
  623. * if (token instanceof Prism.Token && token.type === 'number') {
  624. * console.log(`Found numeric literal: ${token.content}`);
  625. * }
  626. * });
  627. */
  628. tokenize: function (text, grammar) {
  629. var rest = grammar.rest;
  630. if (rest) {
  631. for (var token in rest) {
  632. grammar[token] = rest[token];
  633. }
  634. delete grammar.rest;
  635. }
  636. var tokenList = new LinkedList();
  637. addAfter(tokenList, tokenList.head, text);
  638. matchGrammar(text, tokenList, grammar, tokenList.head, 0);
  639. return toArray(tokenList);
  640. },
  641. /**
  642. * @namespace
  643. * @memberof Prism
  644. * @public
  645. */
  646. hooks: {
  647. all: {},
  648. /**
  649. * Adds the given callback to the list of callbacks for the given hook.
  650. *
  651. * The callback will be invoked when the hook it is registered for is run.
  652. * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
  653. *
  654. * One callback function can be registered to multiple hooks and the same hook multiple times.
  655. *
  656. * @param {string} name The name of the hook.
  657. * @param {HookCallback} callback The callback function which is given environment variables.
  658. * @public
  659. */
  660. add: function (name, callback) {
  661. var hooks = _.hooks.all;
  662. hooks[name] = hooks[name] || [];
  663. hooks[name].push(callback);
  664. },
  665. /**
  666. * Runs a hook invoking all registered callbacks with the given environment variables.
  667. *
  668. * Callbacks will be invoked synchronously and in the order in which they were registered.
  669. *
  670. * @param {string} name The name of the hook.
  671. * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
  672. * @public
  673. */
  674. run: function (name, env) {
  675. var callbacks = _.hooks.all[name];
  676. if (!callbacks || !callbacks.length) {
  677. return;
  678. }
  679. for (var i = 0, callback; (callback = callbacks[i++]);) {
  680. callback(env);
  681. }
  682. }
  683. },
  684. Token: Token
  685. };
  686. _self.Prism = _;
  687. // Typescript note:
  688. // The following can be used to import the Token type in JSDoc:
  689. //
  690. // @typedef {InstanceType<import("./prism-core")["Token"]>} Token
  691. /**
  692. * Creates a new token.
  693. *
  694. * @param {string} type See {@link Token#type type}
  695. * @param {string | TokenStream} content See {@link Token#content content}
  696. * @param {string|string[]} [alias] The alias(es) of the token.
  697. * @param {string} [matchedStr=""] A copy of the full string this token was created from.
  698. * @class
  699. * @global
  700. * @public
  701. */
  702. function Token(type, content, alias, matchedStr) {
  703. /**
  704. * The type of the token.
  705. *
  706. * This is usually the key of a pattern in a {@link Grammar}.
  707. *
  708. * @type {string}
  709. * @see GrammarToken
  710. * @public
  711. */
  712. this.type = type;
  713. /**
  714. * The strings or tokens contained by this token.
  715. *
  716. * This will be a token stream if the pattern matched also defined an `inside` grammar.
  717. *
  718. * @type {string | TokenStream}
  719. * @public
  720. */
  721. this.content = content;
  722. /**
  723. * The alias(es) of the token.
  724. *
  725. * @type {string|string[]}
  726. * @see GrammarToken
  727. * @public
  728. */
  729. this.alias = alias;
  730. // Copy of the full string this token was created from
  731. this.length = (matchedStr || '').length | 0;
  732. }
  733. /**
  734. * A token stream is an array of strings and {@link Token Token} objects.
  735. *
  736. * Token streams have to fulfill a few properties that are assumed by most functions (mostly internal ones) that process
  737. * them.
  738. *
  739. * 1. No adjacent strings.
  740. * 2. No empty strings.
  741. *
  742. * The only exception here is the token stream that only contains the empty string and nothing else.
  743. *
  744. * @typedef {Array<string | Token>} TokenStream
  745. * @global
  746. * @public
  747. */
  748. /**
  749. * Converts the given token or token stream to an HTML representation.
  750. *
  751. * The following hooks will be run:
  752. * 1. `wrap`: On each {@link Token}.
  753. *
  754. * @param {string | Token | TokenStream} o The token or token stream to be converted.
  755. * @param {string} language The name of current language.
  756. * @returns {string} The HTML representation of the token or token stream.
  757. * @memberof Token
  758. * @static
  759. */
  760. Token.stringify = function stringify(o, language) {
  761. if (typeof o == 'string') {
  762. return o;
  763. }
  764. if (Array.isArray(o)) {
  765. var s = '';
  766. o.forEach(function (e) {
  767. s += stringify(e, language);
  768. });
  769. return s;
  770. }
  771. var env = {
  772. type: o.type,
  773. content: stringify(o.content, language),
  774. tag: 'span',
  775. classes: ['token', o.type],
  776. attributes: {},
  777. language: language
  778. };
  779. var aliases = o.alias;
  780. if (aliases) {
  781. if (Array.isArray(aliases)) {
  782. Array.prototype.push.apply(env.classes, aliases);
  783. } else {
  784. env.classes.push(aliases);
  785. }
  786. }
  787. _.hooks.run('wrap', env);
  788. var attributes = '';
  789. for (var name in env.attributes) {
  790. attributes += ' ' + name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"';
  791. }
  792. return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + attributes + '>' + env.content + '</' + env.tag + '>';
  793. };
  794. /**
  795. * @param {RegExp} pattern
  796. * @param {number} pos
  797. * @param {string} text
  798. * @param {boolean} lookbehind
  799. * @returns {RegExpExecArray | null}
  800. */
  801. function matchPattern(pattern, pos, text, lookbehind) {
  802. pattern.lastIndex = pos;
  803. var match = pattern.exec(text);
  804. if (match && lookbehind && match[1]) {
  805. // change the match to remove the text matched by the Prism lookbehind group
  806. var lookbehindLength = match[1].length;
  807. match.index += lookbehindLength;
  808. match[0] = match[0].slice(lookbehindLength);
  809. }
  810. return match;
  811. }
  812. /**
  813. * @param {string} text
  814. * @param {LinkedList<string | Token>} tokenList
  815. * @param {any} grammar
  816. * @param {LinkedListNode<string | Token>} startNode
  817. * @param {number} startPos
  818. * @param {RematchOptions} [rematch]
  819. * @returns {void}
  820. * @private
  821. *
  822. * @typedef RematchOptions
  823. * @property {string} cause
  824. * @property {number} reach
  825. */
  826. function matchGrammar(text, tokenList, grammar, startNode, startPos, rematch) {
  827. for (var token in grammar) {
  828. if (!grammar.hasOwnProperty(token) || !grammar[token]) {
  829. continue;
  830. }
  831. var patterns = grammar[token];
  832. patterns = Array.isArray(patterns) ? patterns : [patterns];
  833. for (var j = 0; j < patterns.length; ++j) {
  834. if (rematch && rematch.cause == token + ',' + j) {
  835. return;
  836. }
  837. var patternObj = patterns[j];
  838. var inside = patternObj.inside;
  839. var lookbehind = !!patternObj.lookbehind;
  840. var greedy = !!patternObj.greedy;
  841. var alias = patternObj.alias;
  842. if (greedy && !patternObj.pattern.global) {
  843. // Without the global flag, lastIndex won't work
  844. var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
  845. patternObj.pattern = RegExp(patternObj.pattern.source, flags + 'g');
  846. }
  847. /** @type {RegExp} */
  848. var pattern = patternObj.pattern || patternObj;
  849. for ( // iterate the token list and keep track of the current token/string position
  850. var currentNode = startNode.next, pos = startPos;
  851. currentNode !== tokenList.tail;
  852. pos += currentNode.value.length, currentNode = currentNode.next
  853. ) {
  854. if (rematch && pos >= rematch.reach) {
  855. break;
  856. }
  857. var str = currentNode.value;
  858. if (tokenList.length > text.length) {
  859. // Something went terribly wrong, ABORT, ABORT!
  860. return;
  861. }
  862. if (str instanceof Token) {
  863. continue;
  864. }
  865. var removeCount = 1; // this is the to parameter of removeBetween
  866. var match;
  867. if (greedy) {
  868. match = matchPattern(pattern, pos, text, lookbehind);
  869. if (!match || match.index >= text.length) {
  870. break;
  871. }
  872. var from = match.index;
  873. var to = match.index + match[0].length;
  874. var p = pos;
  875. // find the node that contains the match
  876. p += currentNode.value.length;
  877. while (from >= p) {
  878. currentNode = currentNode.next;
  879. p += currentNode.value.length;
  880. }
  881. // adjust pos (and p)
  882. p -= currentNode.value.length;
  883. pos = p;
  884. // the current node is a Token, then the match starts inside another Token, which is invalid
  885. if (currentNode.value instanceof Token) {
  886. continue;
  887. }
  888. // find the last node which is affected by this match
  889. for (
  890. var k = currentNode;
  891. k !== tokenList.tail && (p < to || typeof k.value === 'string');
  892. k = k.next
  893. ) {
  894. removeCount++;
  895. p += k.value.length;
  896. }
  897. removeCount--;
  898. // replace with the new match
  899. str = text.slice(pos, p);
  900. match.index -= pos;
  901. } else {
  902. match = matchPattern(pattern, 0, str, lookbehind);
  903. if (!match) {
  904. continue;
  905. }
  906. }
  907. // eslint-disable-next-line no-redeclare
  908. var from = match.index;
  909. var matchStr = match[0];
  910. var before = str.slice(0, from);
  911. var after = str.slice(from + matchStr.length);
  912. var reach = pos + str.length;
  913. if (rematch && reach > rematch.reach) {
  914. rematch.reach = reach;
  915. }
  916. var removeFrom = currentNode.prev;
  917. if (before) {
  918. removeFrom = addAfter(tokenList, removeFrom, before);
  919. pos += before.length;
  920. }
  921. removeRange(tokenList, removeFrom, removeCount);
  922. var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
  923. currentNode = addAfter(tokenList, removeFrom, wrapped);
  924. if (after) {
  925. addAfter(tokenList, currentNode, after);
  926. }
  927. if (removeCount > 1) {
  928. // at least one Token object was removed, so we have to do some rematching
  929. // this can only happen if the current pattern is greedy
  930. /** @type {RematchOptions} */
  931. var nestedRematch = {
  932. cause: token + ',' + j,
  933. reach: reach
  934. };
  935. matchGrammar(text, tokenList, grammar, currentNode.prev, pos, nestedRematch);
  936. // the reach might have been extended because of the rematching
  937. if (rematch && nestedRematch.reach > rematch.reach) {
  938. rematch.reach = nestedRematch.reach;
  939. }
  940. }
  941. }
  942. }
  943. }
  944. }
  945. /**
  946. * @typedef LinkedListNode
  947. * @property {T} value
  948. * @property {LinkedListNode<T> | null} prev The previous node.
  949. * @property {LinkedListNode<T> | null} next The next node.
  950. * @template T
  951. * @private
  952. */
  953. /**
  954. * @template T
  955. * @private
  956. */
  957. function LinkedList() {
  958. /** @type {LinkedListNode<T>} */
  959. var head = { value: null, prev: null, next: null };
  960. /** @type {LinkedListNode<T>} */
  961. var tail = { value: null, prev: head, next: null };
  962. head.next = tail;
  963. /** @type {LinkedListNode<T>} */
  964. this.head = head;
  965. /** @type {LinkedListNode<T>} */
  966. this.tail = tail;
  967. this.length = 0;
  968. }
  969. /**
  970. * Adds a new node with the given value to the list.
  971. *
  972. * @param {LinkedList<T>} list
  973. * @param {LinkedListNode<T>} node
  974. * @param {T} value
  975. * @returns {LinkedListNode<T>} The added node.
  976. * @template T
  977. */
  978. function addAfter(list, node, value) {
  979. // assumes that node != list.tail && values.length >= 0
  980. var next = node.next;
  981. var newNode = { value: value, prev: node, next: next };
  982. node.next = newNode;
  983. next.prev = newNode;
  984. list.length++;
  985. return newNode;
  986. }
  987. /**
  988. * Removes `count` nodes after the given node. The given node will not be removed.
  989. *
  990. * @param {LinkedList<T>} list
  991. * @param {LinkedListNode<T>} node
  992. * @param {number} count
  993. * @template T
  994. */
  995. function removeRange(list, node, count) {
  996. var next = node.next;
  997. for (var i = 0; i < count && next !== list.tail; i++) {
  998. next = next.next;
  999. }
  1000. node.next = next;
  1001. next.prev = node;
  1002. list.length -= i;
  1003. }
  1004. /**
  1005. * @param {LinkedList<T>} list
  1006. * @returns {T[]}
  1007. * @template T
  1008. */
  1009. function toArray(list) {
  1010. var array = [];
  1011. var node = list.head.next;
  1012. while (node !== list.tail) {
  1013. array.push(node.value);
  1014. node = node.next;
  1015. }
  1016. return array;
  1017. }
  1018. if (!_self.document) {
  1019. if (!_self.addEventListener) {
  1020. // in Node.js
  1021. return _;
  1022. }
  1023. if (!_.disableWorkerMessageHandler) {
  1024. // In worker
  1025. _self.addEventListener('message', function (evt) {
  1026. var message = JSON.parse(evt.data);
  1027. var lang = message.language;
  1028. var code = message.code;
  1029. var immediateClose = message.immediateClose;
  1030. _self.postMessage(_.highlight(code, _.languages[lang], lang));
  1031. if (immediateClose) {
  1032. _self.close();
  1033. }
  1034. }, false);
  1035. }
  1036. return _;
  1037. }
  1038. // Get current script and highlight
  1039. var script = _.util.currentScript();
  1040. if (script) {
  1041. _.filename = script.src;
  1042. if (script.hasAttribute('data-manual')) {
  1043. _.manual = true;
  1044. }
  1045. }
  1046. function highlightAutomaticallyCallback() {
  1047. if (!_.manual) {
  1048. _.highlightAll();
  1049. }
  1050. }
  1051. if (!_.manual) {
  1052. // If the document state is "loading", then we'll use DOMContentLoaded.
  1053. // If the document state is "interactive" and the prism.js script is deferred, then we'll also use the
  1054. // DOMContentLoaded event because there might be some plugins or languages which have also been deferred and they
  1055. // might take longer one animation frame to execute which can create a race condition where only some plugins have
  1056. // been loaded when Prism.highlightAll() is executed, depending on how fast resources are loaded.
  1057. // See https://github.com/PrismJS/prism/issues/2102
  1058. var readyState = document.readyState;
  1059. if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) {
  1060. document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback);
  1061. } else {
  1062. if (window.requestAnimationFrame) {
  1063. window.requestAnimationFrame(highlightAutomaticallyCallback);
  1064. } else {
  1065. window.setTimeout(highlightAutomaticallyCallback, 16);
  1066. }
  1067. }
  1068. }
  1069. return _;
  1070. }(_self));
  1071. if (typeof module !== 'undefined' && module.exports) {
  1072. module.exports = Prism;
  1073. }
  1074. // hack for components to work correctly in node.js
  1075. if (typeof global !== 'undefined') {
  1076. global.Prism = Prism;
  1077. }
  1078. // some additional documentation/types
  1079. /**
  1080. * The expansion of a simple `RegExp` literal to support additional properties.
  1081. *
  1082. * @typedef GrammarToken
  1083. * @property {RegExp} pattern The regular expression of the token.
  1084. * @property {boolean} [lookbehind=false] If `true`, then the first capturing group of `pattern` will (effectively)
  1085. * behave as a lookbehind group meaning that the captured text will not be part of the matched text of the new token.
  1086. * @property {boolean} [greedy=false] Whether the token is greedy.
  1087. * @property {string|string[]} [alias] An optional alias or list of aliases.
  1088. * @property {Grammar} [inside] The nested grammar of this token.
  1089. *
  1090. * The `inside` grammar will be used to tokenize the text value of each token of this kind.
  1091. *
  1092. * This can be used to make nested and even recursive language definitions.
  1093. *
  1094. * Note: This can cause infinite recursion. Be careful when you embed different languages or even the same language into
  1095. * each another.
  1096. * @global
  1097. * @public
  1098. */
  1099. /**
  1100. * @typedef Grammar
  1101. * @type {Object<string, RegExp | GrammarToken | Array<RegExp | GrammarToken>>}
  1102. * @property {Grammar} [rest] An optional grammar object that will be appended to this grammar.
  1103. * @global
  1104. * @public
  1105. */
  1106. /**
  1107. * A function which will invoked after an element was successfully highlighted.
  1108. *
  1109. * @callback HighlightCallback
  1110. * @param {Element} element The element successfully highlighted.
  1111. * @returns {void}
  1112. * @global
  1113. * @public
  1114. */
  1115. /**
  1116. * @callback HookCallback
  1117. * @param {Object<string, any>} env The environment variables of the hook.
  1118. * @returns {void}
  1119. * @global
  1120. * @public
  1121. */
  1122. ;
  1123. Prism.languages.markup = {
  1124. 'comment': {
  1125. pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
  1126. greedy: true
  1127. },
  1128. 'prolog': {
  1129. pattern: /<\?[\s\S]+?\?>/,
  1130. greedy: true
  1131. },
  1132. 'doctype': {
  1133. // https://www.w3.org/TR/xml/#NT-doctypedecl
  1134. pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
  1135. greedy: true,
  1136. inside: {
  1137. 'internal-subset': {
  1138. pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
  1139. lookbehind: true,
  1140. greedy: true,
  1141. inside: null // see below
  1142. },
  1143. 'string': {
  1144. pattern: /"[^"]*"|'[^']*'/,
  1145. greedy: true
  1146. },
  1147. 'punctuation': /^<!|>$|[[\]]/,
  1148. 'doctype-tag': /^DOCTYPE/i,
  1149. 'name': /[^\s<>'"]+/
  1150. }
  1151. },
  1152. 'cdata': {
  1153. pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
  1154. greedy: true
  1155. },
  1156. 'tag': {
  1157. pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
  1158. greedy: true,
  1159. inside: {
  1160. 'tag': {
  1161. pattern: /^<\/?[^\s>\/]+/,
  1162. inside: {
  1163. 'punctuation': /^<\/?/,
  1164. 'namespace': /^[^\s>\/:]+:/
  1165. }
  1166. },
  1167. 'special-attr': [],
  1168. 'attr-value': {
  1169. pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
  1170. inside: {
  1171. 'punctuation': [
  1172. {
  1173. pattern: /^=/,
  1174. alias: 'attr-equals'
  1175. },
  1176. {
  1177. pattern: /^(\s*)["']|["']$/,
  1178. lookbehind: true
  1179. }
  1180. ]
  1181. }
  1182. },
  1183. 'punctuation': /\/?>/,
  1184. 'attr-name': {
  1185. pattern: /[^\s>\/]+/,
  1186. inside: {
  1187. 'namespace': /^[^\s>\/:]+:/
  1188. }
  1189. }
  1190. }
  1191. },
  1192. 'entity': [
  1193. {
  1194. pattern: /&[\da-z]{1,8};/i,
  1195. alias: 'named-entity'
  1196. },
  1197. /&#x?[\da-f]{1,8};/i
  1198. ]
  1199. };
  1200. Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] =
  1201. Prism.languages.markup['entity'];
  1202. Prism.languages.markup['doctype'].inside['internal-subset'].inside = Prism.languages.markup;
  1203. // Plugin to make entity title show the real entity, idea by Roman Komarov
  1204. Prism.hooks.add('wrap', function (env) {
  1205. if (env.type === 'entity') {
  1206. env.attributes['title'] = env.content.replace(/&amp;/, '&');
  1207. }
  1208. });
  1209. Object.defineProperty(Prism.languages.markup.tag, 'addInlined', {
  1210. /**
  1211. * Adds an inlined language to markup.
  1212. *
  1213. * An example of an inlined language is CSS with `<style>` tags.
  1214. *
  1215. * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
  1216. * case insensitive.
  1217. * @param {string} lang The language key.
  1218. * @example
  1219. * addInlined('style', 'css');
  1220. */
  1221. value: function addInlined(tagName, lang) {
  1222. var includedCdataInside = {};
  1223. includedCdataInside['language-' + lang] = {
  1224. pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
  1225. lookbehind: true,
  1226. inside: Prism.languages[lang]
  1227. };
  1228. includedCdataInside['cdata'] = /^<!\[CDATA\[|\]\]>$/i;
  1229. var inside = {
  1230. 'included-cdata': {
  1231. pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
  1232. inside: includedCdataInside
  1233. }
  1234. };
  1235. inside['language-' + lang] = {
  1236. pattern: /[\s\S]+/,
  1237. inside: Prism.languages[lang]
  1238. };
  1239. var def = {};
  1240. def[tagName] = {
  1241. pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function () { return tagName; }), 'i'),
  1242. lookbehind: true,
  1243. greedy: true,
  1244. inside: inside
  1245. };
  1246. Prism.languages.insertBefore('markup', 'cdata', def);
  1247. }
  1248. });
  1249. Object.defineProperty(Prism.languages.markup.tag, 'addAttribute', {
  1250. /**
  1251. * Adds an pattern to highlight languages embedded in HTML attributes.
  1252. *
  1253. * An example of an inlined language is CSS with `style` attributes.
  1254. *
  1255. * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
  1256. * case insensitive.
  1257. * @param {string} lang The language key.
  1258. * @example
  1259. * addAttribute('style', 'css');
  1260. */
  1261. value: function (attrName, lang) {
  1262. Prism.languages.markup.tag.inside['special-attr'].push({
  1263. pattern: RegExp(
  1264. /(^|["'\s])/.source + '(?:' + attrName + ')' + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
  1265. 'i'
  1266. ),
  1267. lookbehind: true,
  1268. inside: {
  1269. 'attr-name': /^[^\s=]+/,
  1270. 'attr-value': {
  1271. pattern: /=[\s\S]+/,
  1272. inside: {
  1273. 'value': {
  1274. pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
  1275. lookbehind: true,
  1276. alias: [lang, 'language-' + lang],
  1277. inside: Prism.languages[lang]
  1278. },
  1279. 'punctuation': [
  1280. {
  1281. pattern: /^=/,
  1282. alias: 'attr-equals'
  1283. },
  1284. /"|'/
  1285. ]
  1286. }
  1287. }
  1288. }
  1289. });
  1290. }
  1291. });
  1292. Prism.languages.html = Prism.languages.markup;
  1293. Prism.languages.mathml = Prism.languages.markup;
  1294. Prism.languages.svg = Prism.languages.markup;
  1295. Prism.languages.xml = Prism.languages.extend('markup', {});
  1296. Prism.languages.ssml = Prism.languages.xml;
  1297. Prism.languages.atom = Prism.languages.xml;
  1298. Prism.languages.rss = Prism.languages.xml;
  1299. (function (Prism) {
  1300. var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
  1301. Prism.languages.css = {
  1302. 'comment': /\/\*[\s\S]*?\*\//,
  1303. 'atrule': {
  1304. pattern: RegExp('@[\\w-](?:' + /[^;{\s"']|\s+(?!\s)/.source + '|' + string.source + ')*?' + /(?:;|(?=\s*\{))/.source),
  1305. inside: {
  1306. 'rule': /^@[\w-]+/,
  1307. 'selector-function-argument': {
  1308. pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
  1309. lookbehind: true,
  1310. alias: 'selector'
  1311. },
  1312. 'keyword': {
  1313. pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
  1314. lookbehind: true
  1315. }
  1316. // See rest below
  1317. }
  1318. },
  1319. 'url': {
  1320. // https://drafts.csswg.org/css-values-3/#urls
  1321. pattern: RegExp('\\burl\\((?:' + string.source + '|' + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ')\\)', 'i'),
  1322. greedy: true,
  1323. inside: {
  1324. 'function': /^url/i,
  1325. 'punctuation': /^\(|\)$/,
  1326. 'string': {
  1327. pattern: RegExp('^' + string.source + '$'),
  1328. alias: 'url'
  1329. }
  1330. }
  1331. },
  1332. 'selector': {
  1333. pattern: RegExp('(^|[{}\\s])[^{}\\s](?:[^{};"\'\\s]|\\s+(?![\\s{])|' + string.source + ')*(?=\\s*\\{)'),
  1334. lookbehind: true
  1335. },
  1336. 'string': {
  1337. pattern: string,
  1338. greedy: true
  1339. },
  1340. 'property': {
  1341. pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
  1342. lookbehind: true
  1343. },
  1344. 'important': /!important\b/i,
  1345. 'function': {
  1346. pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
  1347. lookbehind: true
  1348. },
  1349. 'punctuation': /[(){};:,]/
  1350. };
  1351. Prism.languages.css['atrule'].inside.rest = Prism.languages.css;
  1352. var markup = Prism.languages.markup;
  1353. if (markup) {
  1354. markup.tag.addInlined('style', 'css');
  1355. markup.tag.addAttribute('style', 'css');
  1356. }
  1357. }(Prism));
  1358. Prism.languages.clike = {
  1359. 'comment': [
  1360. {
  1361. pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
  1362. lookbehind: true,
  1363. greedy: true
  1364. },
  1365. {
  1366. pattern: /(^|[^\\:])\/\/.*/,
  1367. lookbehind: true,
  1368. greedy: true
  1369. }
  1370. ],
  1371. 'string': {
  1372. pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
  1373. greedy: true
  1374. },
  1375. 'class-name': {
  1376. pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
  1377. lookbehind: true,
  1378. inside: {
  1379. 'punctuation': /[.\\]/
  1380. }
  1381. },
  1382. 'keyword': /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
  1383. 'boolean': /\b(?:false|true)\b/,
  1384. 'function': /\b\w+(?=\()/,
  1385. 'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
  1386. 'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
  1387. 'punctuation': /[{}[\];(),.:]/
  1388. };
  1389. Prism.languages.javascript = Prism.languages.extend('clike', {
  1390. 'class-name': [
  1391. Prism.languages.clike['class-name'],
  1392. {
  1393. pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
  1394. lookbehind: true
  1395. }
  1396. ],
  1397. 'keyword': [
  1398. {
  1399. pattern: /((?:^|\})\s*)catch\b/,
  1400. lookbehind: true
  1401. },
  1402. {
  1403. 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/,
  1404. lookbehind: true
  1405. },
  1406. ],
  1407. // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
  1408. 'function': /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
  1409. 'number': {
  1410. pattern: RegExp(
  1411. /(^|[^\w$])/.source +
  1412. '(?:' +
  1413. (
  1414. // constant
  1415. /NaN|Infinity/.source +
  1416. '|' +
  1417. // binary integer
  1418. /0[bB][01]+(?:_[01]+)*n?/.source +
  1419. '|' +
  1420. // octal integer
  1421. /0[oO][0-7]+(?:_[0-7]+)*n?/.source +
  1422. '|' +
  1423. // hexadecimal integer
  1424. /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source +
  1425. '|' +
  1426. // decimal bigint
  1427. /\d+(?:_\d+)*n/.source +
  1428. '|' +
  1429. // decimal number (integer or float) but no bigint
  1430. /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source
  1431. ) +
  1432. ')' +
  1433. /(?![\w$])/.source
  1434. ),
  1435. lookbehind: true
  1436. },
  1437. 'operator': /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
  1438. });
  1439. Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
  1440. Prism.languages.insertBefore('javascript', 'keyword', {
  1441. 'regex': {
  1442. pattern: RegExp(
  1443. // lookbehind
  1444. // eslint-disable-next-line regexp/no-dupe-characters-character-class
  1445. /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source +
  1446. // Regex pattern:
  1447. // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
  1448. // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
  1449. // with the only syntax, so we have to define 2 different regex patterns.
  1450. /\//.source +
  1451. '(?:' +
  1452. /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source +
  1453. '|' +
  1454. // `v` flag syntax. This supports 3 levels of nested character classes.
  1455. /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source +
  1456. ')' +
  1457. // lookahead
  1458. /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
  1459. ),
  1460. lookbehind: true,
  1461. greedy: true,
  1462. inside: {
  1463. 'regex-source': {
  1464. pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
  1465. lookbehind: true,
  1466. alias: 'language-regex',
  1467. inside: Prism.languages.regex
  1468. },
  1469. 'regex-delimiter': /^\/|\/$/,
  1470. 'regex-flags': /^[a-z]+$/,
  1471. }
  1472. },
  1473. // This must be declared before keyword because we use "function" inside the look-forward
  1474. 'function-variable': {
  1475. 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*=>))/,
  1476. alias: 'function'
  1477. },
  1478. 'parameter': [
  1479. {
  1480. pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
  1481. lookbehind: true,
  1482. inside: Prism.languages.javascript
  1483. },
  1484. {
  1485. pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
  1486. lookbehind: true,
  1487. inside: Prism.languages.javascript
  1488. },
  1489. {
  1490. pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
  1491. lookbehind: true,
  1492. inside: Prism.languages.javascript
  1493. },
  1494. {
  1495. 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*\{)/,
  1496. lookbehind: true,
  1497. inside: Prism.languages.javascript
  1498. }
  1499. ],
  1500. 'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/
  1501. });
  1502. Prism.languages.insertBefore('javascript', 'string', {
  1503. 'hashbang': {
  1504. pattern: /^#!.*/,
  1505. greedy: true,
  1506. alias: 'comment'
  1507. },
  1508. 'template-string': {
  1509. pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
  1510. greedy: true,
  1511. inside: {
  1512. 'template-punctuation': {
  1513. pattern: /^`|`$/,
  1514. alias: 'string'
  1515. },
  1516. 'interpolation': {
  1517. pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
  1518. lookbehind: true,
  1519. inside: {
  1520. 'interpolation-punctuation': {
  1521. pattern: /^\$\{|\}$/,
  1522. alias: 'punctuation'
  1523. },
  1524. rest: Prism.languages.javascript
  1525. }
  1526. },
  1527. 'string': /[\s\S]+/
  1528. }
  1529. },
  1530. 'string-property': {
  1531. pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
  1532. lookbehind: true,
  1533. greedy: true,
  1534. alias: 'property'
  1535. }
  1536. });
  1537. Prism.languages.insertBefore('javascript', 'operator', {
  1538. 'literal-property': {
  1539. pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
  1540. lookbehind: true,
  1541. alias: 'property'
  1542. },
  1543. });
  1544. if (Prism.languages.markup) {
  1545. Prism.languages.markup.tag.addInlined('script', 'javascript');
  1546. // add attribute support for all DOM events.
  1547. // https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events
  1548. Prism.languages.markup.tag.addAttribute(
  1549. /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,
  1550. 'javascript'
  1551. );
  1552. }
  1553. Prism.languages.js = Prism.languages.javascript;
  1554. Prism.languages.python = {
  1555. 'comment': {
  1556. pattern: /(^|[^\\])#.*/,
  1557. lookbehind: true,
  1558. greedy: true
  1559. },
  1560. 'string-interpolation': {
  1561. pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
  1562. greedy: true,
  1563. inside: {
  1564. 'interpolation': {
  1565. // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
  1566. pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
  1567. lookbehind: true,
  1568. inside: {
  1569. 'format-spec': {
  1570. pattern: /(:)[^:(){}]+(?=\}$)/,
  1571. lookbehind: true
  1572. },
  1573. 'conversion-option': {
  1574. pattern: /![sra](?=[:}]$)/,
  1575. alias: 'punctuation'
  1576. },
  1577. rest: null
  1578. }
  1579. },
  1580. 'string': /[\s\S]+/
  1581. }
  1582. },
  1583. 'triple-quoted-string': {
  1584. pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
  1585. greedy: true,
  1586. alias: 'string'
  1587. },
  1588. 'string': {
  1589. pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
  1590. greedy: true
  1591. },
  1592. 'function': {
  1593. pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
  1594. lookbehind: true
  1595. },
  1596. 'class-name': {
  1597. pattern: /(\bclass\s+)\w+/i,
  1598. lookbehind: true
  1599. },
  1600. 'decorator': {
  1601. pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
  1602. lookbehind: true,
  1603. alias: ['annotation', 'punctuation'],
  1604. inside: {
  1605. 'punctuation': /\./
  1606. }
  1607. },
  1608. 'keyword': /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
  1609. 'builtin': /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
  1610. 'boolean': /\b(?:False|None|True)\b/,
  1611. 'number': /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
  1612. 'operator': /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
  1613. 'punctuation': /[{}[\];(),.:]/
  1614. };
  1615. Prism.languages.python['string-interpolation'].inside['interpolation'].inside.rest = Prism.languages.python;
  1616. Prism.languages.py = Prism.languages.python;
  1617. Prism.languages.sql = {
  1618. 'comment': {
  1619. pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,
  1620. lookbehind: true
  1621. },
  1622. 'variable': [
  1623. {
  1624. pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,
  1625. greedy: true
  1626. },
  1627. /@[\w.$]+/
  1628. ],
  1629. 'string': {
  1630. pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,
  1631. greedy: true,
  1632. lookbehind: true
  1633. },
  1634. 'identifier': {
  1635. pattern: /(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,
  1636. greedy: true,
  1637. lookbehind: true,
  1638. inside: {
  1639. 'punctuation': /^`|`$/
  1640. }
  1641. },
  1642. 'function': /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i, // Should we highlight user defined functions too?
  1643. 'keyword': /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,
  1644. 'boolean': /\b(?:FALSE|NULL|TRUE)\b/i,
  1645. 'number': /\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,
  1646. 'operator': /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,
  1647. 'punctuation': /[;[\]()`,.]/
  1648. };
  1649. Prism.languages['visual-basic'] = {
  1650. 'comment': {
  1651. pattern: /(?:['‘’]|REM\b)(?:[^\r\n_]|_(?:\r\n?|\n)?)*/i,
  1652. inside: {
  1653. 'keyword': /^REM/i
  1654. }
  1655. },
  1656. 'directive': {
  1657. pattern: /#(?:Const|Else|ElseIf|End|ExternalChecksum|ExternalSource|If|Region)(?:\b_[ \t]*(?:\r\n?|\n)|.)+/i,
  1658. alias: 'property',
  1659. greedy: true
  1660. },
  1661. 'string': {
  1662. pattern: /\$?["“”](?:["“”]{2}|[^"“”])*["“”]C?/i,
  1663. greedy: true
  1664. },
  1665. 'date': {
  1666. pattern: /#[ \t]*(?:\d+([/-])\d+\1\d+(?:[ \t]+(?:\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?))?|\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?)[ \t]*#/i,
  1667. alias: 'number'
  1668. },
  1669. 'number': /(?:(?:\b\d+(?:\.\d+)?|\.\d+)(?:E[+-]?\d+)?|&[HO][\dA-F]+)(?:[FRD]|U?[ILS])?/i,
  1670. 'boolean': /\b(?:False|Nothing|True)\b/i,
  1671. 'keyword': /\b(?:AddHandler|AddressOf|Alias|And(?:Also)?|As|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|C(?:Bool|Byte|Char|Date|Dbl|Dec|Int|Lng|Obj|SByte|Short|Sng|Str|Type|UInt|ULng|UShort)|Char|Class|Const|Continue|Currency|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else(?:If)?|End(?:If)?|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get(?:Type|XMLNamespace)?|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mod|Module|Must(?:Inherit|Override)|My(?:Base|Class)|Namespace|Narrowing|New|Next|Not(?:Inheritable|Overridable)?|Object|Of|On|Operator|Option(?:al)?|Or(?:Else)?|Out|Overloads|Overridable|Overrides|ParamArray|Partial|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|SByte|Select|Set|Shadows|Shared|short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TryCast|Type|TypeOf|U(?:Integer|Long|Short)|Until|Using|Variant|Wend|When|While|Widening|With(?:Events)?|WriteOnly|Xor)\b/i,
  1672. 'operator': /[+\-*/\\^<=>&#@$%!]|\b_(?=[ \t]*[\r\n])/,
  1673. 'punctuation': /[{}().,:?]/
  1674. };
  1675. Prism.languages.vb = Prism.languages['visual-basic'];
  1676. Prism.languages.vba = Prism.languages['visual-basic'];
  1677. (function () {
  1678. if (typeof Prism === 'undefined' || typeof document === 'undefined') {
  1679. return;
  1680. }
  1681. /**
  1682. * Plugin name which is used as a class name for <pre> which is activating the plugin
  1683. *
  1684. * @type {string}
  1685. */
  1686. var PLUGIN_NAME = 'line-numbers';
  1687. /**
  1688. * Regular expression used for determining line breaks
  1689. *
  1690. * @type {RegExp}
  1691. */
  1692. var NEW_LINE_EXP = /\n(?!$)/g;
  1693. /**
  1694. * Global exports
  1695. */
  1696. var config = Prism.plugins.lineNumbers = {
  1697. /**
  1698. * Get node for provided line number
  1699. *
  1700. * @param {Element} element pre element
  1701. * @param {number} number line number
  1702. * @returns {Element|undefined}
  1703. */
  1704. getLine: function (element, number) {
  1705. if (element.tagName !== 'PRE' || !element.classList.contains(PLUGIN_NAME)) {
  1706. return;
  1707. }
  1708. var lineNumberRows = element.querySelector('.line-numbers-rows');
  1709. if (!lineNumberRows) {
  1710. return;
  1711. }
  1712. var lineNumberStart = parseInt(element.getAttribute('data-start'), 10) || 1;
  1713. var lineNumberEnd = lineNumberStart + (lineNumberRows.children.length - 1);
  1714. if (number < lineNumberStart) {
  1715. number = lineNumberStart;
  1716. }
  1717. if (number > lineNumberEnd) {
  1718. number = lineNumberEnd;
  1719. }
  1720. var lineIndex = number - lineNumberStart;
  1721. return lineNumberRows.children[lineIndex];
  1722. },
  1723. /**
  1724. * Resizes the line numbers of the given element.
  1725. *
  1726. * This function will not add line numbers. It will only resize existing ones.
  1727. *
  1728. * @param {HTMLElement} element A `<pre>` element with line numbers.
  1729. * @returns {void}
  1730. */
  1731. resize: function (element) {
  1732. resizeElements([element]);
  1733. },
  1734. /**
  1735. * Whether the plugin can assume that the units font sizes and margins are not depended on the size of
  1736. * the current viewport.
  1737. *
  1738. * Setting this to `true` will allow the plugin to do certain optimizations for better performance.
  1739. *
  1740. * Set this to `false` if you use any of the following CSS units: `vh`, `vw`, `vmin`, `vmax`.
  1741. *
  1742. * @type {boolean}
  1743. */
  1744. assumeViewportIndependence: true
  1745. };
  1746. /**
  1747. * Resizes the given elements.
  1748. *
  1749. * @param {HTMLElement[]} elements
  1750. */
  1751. function resizeElements(elements) {
  1752. elements = elements.filter(function (e) {
  1753. var codeStyles = getStyles(e);
  1754. var whiteSpace = codeStyles['white-space'];
  1755. return whiteSpace === 'pre-wrap' || whiteSpace === 'pre-line';
  1756. });
  1757. if (elements.length == 0) {
  1758. return;
  1759. }
  1760. var infos = elements.map(function (element) {
  1761. var codeElement = element.querySelector('code');
  1762. var lineNumbersWrapper = element.querySelector('.line-numbers-rows');
  1763. if (!codeElement || !lineNumbersWrapper) {
  1764. return undefined;
  1765. }
  1766. /** @type {HTMLElement} */
  1767. var lineNumberSizer = element.querySelector('.line-numbers-sizer');
  1768. var codeLines = codeElement.textContent.split(NEW_LINE_EXP);
  1769. if (!lineNumberSizer) {
  1770. lineNumberSizer = document.createElement('span');
  1771. lineNumberSizer.className = 'line-numbers-sizer';
  1772. codeElement.appendChild(lineNumberSizer);
  1773. }
  1774. lineNumberSizer.innerHTML = '0';
  1775. lineNumberSizer.style.display = 'block';
  1776. var oneLinerHeight = lineNumberSizer.getBoundingClientRect().height;
  1777. lineNumberSizer.innerHTML = '';
  1778. return {
  1779. element: element,
  1780. lines: codeLines,
  1781. lineHeights: [],
  1782. oneLinerHeight: oneLinerHeight,
  1783. sizer: lineNumberSizer,
  1784. };
  1785. }).filter(Boolean);
  1786. infos.forEach(function (info) {
  1787. var lineNumberSizer = info.sizer;
  1788. var lines = info.lines;
  1789. var lineHeights = info.lineHeights;
  1790. var oneLinerHeight = info.oneLinerHeight;
  1791. lineHeights[lines.length - 1] = undefined;
  1792. lines.forEach(function (line, index) {
  1793. if (line && line.length > 1) {
  1794. var e = lineNumberSizer.appendChild(document.createElement('span'));
  1795. e.style.display = 'block';
  1796. e.textContent = line;
  1797. } else {
  1798. lineHeights[index] = oneLinerHeight;
  1799. }
  1800. });
  1801. });
  1802. infos.forEach(function (info) {
  1803. var lineNumberSizer = info.sizer;
  1804. var lineHeights = info.lineHeights;
  1805. var childIndex = 0;
  1806. for (var i = 0; i < lineHeights.length; i++) {
  1807. if (lineHeights[i] === undefined) {
  1808. lineHeights[i] = lineNumberSizer.children[childIndex++].getBoundingClientRect().height;
  1809. }
  1810. }
  1811. });
  1812. infos.forEach(function (info) {
  1813. var lineNumberSizer = info.sizer;
  1814. var wrapper = info.element.querySelector('.line-numbers-rows');
  1815. lineNumberSizer.style.display = 'none';
  1816. lineNumberSizer.innerHTML = '';
  1817. info.lineHeights.forEach(function (height, lineNumber) {
  1818. wrapper.children[lineNumber].style.height = height + 'px';
  1819. });
  1820. });
  1821. }
  1822. /**
  1823. * Returns style declarations for the element
  1824. *
  1825. * @param {Element} element
  1826. */
  1827. function getStyles(element) {
  1828. if (!element) {
  1829. return null;
  1830. }
  1831. return window.getComputedStyle ? getComputedStyle(element) : (element.currentStyle || null);
  1832. }
  1833. var lastWidth = undefined;
  1834. window.addEventListener('resize', function () {
  1835. if (config.assumeViewportIndependence && lastWidth === window.innerWidth) {
  1836. return;
  1837. }
  1838. lastWidth = window.innerWidth;
  1839. resizeElements(Array.prototype.slice.call(document.querySelectorAll('pre.' + PLUGIN_NAME)));
  1840. });
  1841. Prism.hooks.add('complete', function (env) {
  1842. if (!env.code) {
  1843. return;
  1844. }
  1845. var code = /** @type {Element} */ (env.element);
  1846. var pre = /** @type {HTMLElement} */ (code.parentNode);
  1847. // works only for <code> wrapped inside <pre> (not inline)
  1848. if (!pre || !/pre/i.test(pre.nodeName)) {
  1849. return;
  1850. }
  1851. // Abort if line numbers already exists
  1852. if (code.querySelector('.line-numbers-rows')) {
  1853. return;
  1854. }
  1855. // only add line numbers if <code> or one of its ancestors has the `line-numbers` class
  1856. if (!Prism.util.isActive(code, PLUGIN_NAME)) {
  1857. return;
  1858. }
  1859. // Remove the class 'line-numbers' from the <code>
  1860. code.classList.remove(PLUGIN_NAME);
  1861. // Add the class 'line-numbers' to the <pre>
  1862. pre.classList.add(PLUGIN_NAME);
  1863. var match = env.code.match(NEW_LINE_EXP);
  1864. var linesNum = match ? match.length + 1 : 1;
  1865. var lineNumbersWrapper;
  1866. var lines = new Array(linesNum + 1).join('<span></span>');
  1867. lineNumbersWrapper = document.createElement('span');
  1868. lineNumbersWrapper.setAttribute('aria-hidden', 'true');
  1869. lineNumbersWrapper.className = 'line-numbers-rows';
  1870. lineNumbersWrapper.innerHTML = lines;
  1871. if (pre.hasAttribute('data-start')) {
  1872. pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1);
  1873. }
  1874. env.element.appendChild(lineNumbersWrapper);
  1875. resizeElements([pre]);
  1876. Prism.hooks.run('line-numbers', env);
  1877. });
  1878. Prism.hooks.add('line-numbers', function (env) {
  1879. env.plugins = env.plugins || {};
  1880. env.plugins.lineNumbers = true;
  1881. });
  1882. }());
  1883. (function () {
  1884. if (typeof Prism === 'undefined') {
  1885. return;
  1886. }
  1887. var assign = Object.assign || function (obj1, obj2) {
  1888. for (var name in obj2) {
  1889. if (obj2.hasOwnProperty(name)) {
  1890. obj1[name] = obj2[name];
  1891. }
  1892. }
  1893. return obj1;
  1894. };
  1895. function NormalizeWhitespace(defaults) {
  1896. this.defaults = assign({}, defaults);
  1897. }
  1898. function toCamelCase(value) {
  1899. return value.replace(/-(\w)/g, function (match, firstChar) {
  1900. return firstChar.toUpperCase();
  1901. });
  1902. }
  1903. function tabLen(str) {
  1904. var res = 0;
  1905. for (var i = 0; i < str.length; ++i) {
  1906. if (str.charCodeAt(i) == '\t'.charCodeAt(0)) {
  1907. res += 3;
  1908. }
  1909. }
  1910. return str.length + res;
  1911. }
  1912. NormalizeWhitespace.prototype = {
  1913. setDefaults: function (defaults) {
  1914. this.defaults = assign(this.defaults, defaults);
  1915. },
  1916. normalize: function (input, settings) {
  1917. settings = assign(this.defaults, settings);
  1918. for (var name in settings) {
  1919. var methodName = toCamelCase(name);
  1920. if (name !== 'normalize' && methodName !== 'setDefaults' &&
  1921. settings[name] && this[methodName]) {
  1922. input = this[methodName].call(this, input, settings[name]);
  1923. }
  1924. }
  1925. return input;
  1926. },
  1927. /*
  1928. * Normalization methods
  1929. */
  1930. leftTrim: function (input) {
  1931. return input.replace(/^\s+/, '');
  1932. },
  1933. rightTrim: function (input) {
  1934. return input.replace(/\s+$/, '');
  1935. },
  1936. tabsToSpaces: function (input, spaces) {
  1937. spaces = spaces|0 || 4;
  1938. return input.replace(/\t/g, new Array(++spaces).join(' '));
  1939. },
  1940. spacesToTabs: function (input, spaces) {
  1941. spaces = spaces|0 || 4;
  1942. return input.replace(RegExp(' {' + spaces + '}', 'g'), '\t');
  1943. },
  1944. removeTrailing: function (input) {
  1945. return input.replace(/\s*?$/gm, '');
  1946. },
  1947. // Support for deprecated plugin remove-initial-line-feed
  1948. removeInitialLineFeed: function (input) {
  1949. return input.replace(/^(?:\r?\n|\r)/, '');
  1950. },
  1951. removeIndent: function (input) {
  1952. var indents = input.match(/^[^\S\n\r]*(?=\S)/gm);
  1953. if (!indents || !indents[0].length) {
  1954. return input;
  1955. }
  1956. indents.sort(function (a, b) { return a.length - b.length; });
  1957. if (!indents[0].length) {
  1958. return input;
  1959. }
  1960. return input.replace(RegExp('^' + indents[0], 'gm'), '');
  1961. },
  1962. indent: function (input, tabs) {
  1963. return input.replace(/^[^\S\n\r]*(?=\S)/gm, new Array(++tabs).join('\t') + '$&');
  1964. },
  1965. breakLines: function (input, characters) {
  1966. characters = (characters === true) ? 80 : characters|0 || 80;
  1967. var lines = input.split('\n');
  1968. for (var i = 0; i < lines.length; ++i) {
  1969. if (tabLen(lines[i]) <= characters) {
  1970. continue;
  1971. }
  1972. var line = lines[i].split(/(\s+)/g);
  1973. var len = 0;
  1974. for (var j = 0; j < line.length; ++j) {
  1975. var tl = tabLen(line[j]);
  1976. len += tl;
  1977. if (len > characters) {
  1978. line[j] = '\n' + line[j];
  1979. len = tl;
  1980. }
  1981. }
  1982. lines[i] = line.join('');
  1983. }
  1984. return lines.join('\n');
  1985. }
  1986. };
  1987. // Support node modules
  1988. if (typeof module !== 'undefined' && module.exports) {
  1989. module.exports = NormalizeWhitespace;
  1990. }
  1991. Prism.plugins.NormalizeWhitespace = new NormalizeWhitespace({
  1992. 'remove-trailing': true,
  1993. 'remove-indent': true,
  1994. 'left-trim': true,
  1995. 'right-trim': true,
  1996. /*'break-lines': 80,
  1997. 'indent': 2,
  1998. 'remove-initial-line-feed': false,
  1999. 'tabs-to-spaces': 4,
  2000. 'spaces-to-tabs': 4*/
  2001. });
  2002. Prism.hooks.add('before-sanity-check', function (env) {
  2003. var Normalizer = Prism.plugins.NormalizeWhitespace;
  2004. // Check settings
  2005. if (env.settings && env.settings['whitespace-normalization'] === false) {
  2006. return;
  2007. }
  2008. // Check classes
  2009. if (!Prism.util.isActive(env.element, 'whitespace-normalization', true)) {
  2010. return;
  2011. }
  2012. // Simple mode if there is no env.element
  2013. if ((!env.element || !env.element.parentNode) && env.code) {
  2014. env.code = Normalizer.normalize(env.code, env.settings);
  2015. return;
  2016. }
  2017. // Normal mode
  2018. var pre = env.element.parentNode;
  2019. if (!env.code || !pre || pre.nodeName.toLowerCase() !== 'pre') {
  2020. return;
  2021. }
  2022. var children = pre.childNodes;
  2023. var before = '';
  2024. var after = '';
  2025. var codeFound = false;
  2026. // Move surrounding whitespace from the <pre> tag into the <code> tag
  2027. for (var i = 0; i < children.length; ++i) {
  2028. var node = children[i];
  2029. if (node == env.element) {
  2030. codeFound = true;
  2031. } else if (node.nodeName === '#text') {
  2032. if (codeFound) {
  2033. after += node.nodeValue;
  2034. } else {
  2035. before += node.nodeValue;
  2036. }
  2037. pre.removeChild(node);
  2038. --i;
  2039. }
  2040. }
  2041. if (!env.element.children.length || !Prism.plugins.KeepMarkup) {
  2042. env.code = before + env.code + after;
  2043. env.code = Normalizer.normalize(env.code, env.settings);
  2044. } else {
  2045. // Preserve markup for keep-markup plugin
  2046. var html = before + env.element.innerHTML + after;
  2047. env.element.innerHTML = Normalizer.normalize(html, env.settings);
  2048. env.code = env.element.textContent;
  2049. }
  2050. });
  2051. }());