prism.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. /* PrismJS 1.28.0
  2. https://prismjs.com/download.html#themes=prism&languages=clike+csharp */
  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.clike = {
  1124. 'comment': [
  1125. {
  1126. pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
  1127. lookbehind: true,
  1128. greedy: true
  1129. },
  1130. {
  1131. pattern: /(^|[^\\:])\/\/.*/,
  1132. lookbehind: true,
  1133. greedy: true
  1134. }
  1135. ],
  1136. 'string': {
  1137. pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
  1138. greedy: true
  1139. },
  1140. 'class-name': {
  1141. pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
  1142. lookbehind: true,
  1143. inside: {
  1144. 'punctuation': /[.\\]/
  1145. }
  1146. },
  1147. 'keyword': /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
  1148. 'boolean': /\b(?:false|true)\b/,
  1149. 'function': /\b\w+(?=\()/,
  1150. 'number': /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
  1151. 'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
  1152. 'punctuation': /[{}[\];(),.:]/
  1153. };
  1154. (function (Prism) {
  1155. /**
  1156. * Replaces all placeholders "<<n>>" of given pattern with the n-th replacement (zero based).
  1157. *
  1158. * Note: This is a simple text based replacement. Be careful when using backreferences!
  1159. *
  1160. * @param {string} pattern the given pattern.
  1161. * @param {string[]} replacements a list of replacement which can be inserted into the given pattern.
  1162. * @returns {string} the pattern with all placeholders replaced with their corresponding replacements.
  1163. * @example replace(/a<<0>>a/.source, [/b+/.source]) === /a(?:b+)a/.source
  1164. */
  1165. function replace(pattern, replacements) {
  1166. return pattern.replace(/<<(\d+)>>/g, function (m, index) {
  1167. return '(?:' + replacements[+index] + ')';
  1168. });
  1169. }
  1170. /**
  1171. * @param {string} pattern
  1172. * @param {string[]} replacements
  1173. * @param {string} [flags]
  1174. * @returns {RegExp}
  1175. */
  1176. function re(pattern, replacements, flags) {
  1177. return RegExp(replace(pattern, replacements), flags || '');
  1178. }
  1179. /**
  1180. * Creates a nested pattern where all occurrences of the string `<<self>>` are replaced with the pattern itself.
  1181. *
  1182. * @param {string} pattern
  1183. * @param {number} depthLog2
  1184. * @returns {string}
  1185. */
  1186. function nested(pattern, depthLog2) {
  1187. for (var i = 0; i < depthLog2; i++) {
  1188. pattern = pattern.replace(/<<self>>/g, function () { return '(?:' + pattern + ')'; });
  1189. }
  1190. return pattern.replace(/<<self>>/g, '[^\\s\\S]');
  1191. }
  1192. // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/
  1193. var keywordKinds = {
  1194. // keywords which represent a return or variable type
  1195. type: 'bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void',
  1196. // keywords which are used to declare a type
  1197. typeDeclaration: 'class enum interface record struct',
  1198. // contextual keywords
  1199. // ("var" and "dynamic" are missing because they are used like types)
  1200. contextual: 'add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)',
  1201. // all other keywords
  1202. other: 'abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield'
  1203. };
  1204. // keywords
  1205. function keywordsToPattern(words) {
  1206. return '\\b(?:' + words.trim().replace(/ /g, '|') + ')\\b';
  1207. }
  1208. var typeDeclarationKeywords = keywordsToPattern(keywordKinds.typeDeclaration);
  1209. var keywords = RegExp(keywordsToPattern(keywordKinds.type + ' ' + keywordKinds.typeDeclaration + ' ' + keywordKinds.contextual + ' ' + keywordKinds.other));
  1210. var nonTypeKeywords = keywordsToPattern(keywordKinds.typeDeclaration + ' ' + keywordKinds.contextual + ' ' + keywordKinds.other);
  1211. var nonContextualKeywords = keywordsToPattern(keywordKinds.type + ' ' + keywordKinds.typeDeclaration + ' ' + keywordKinds.other);
  1212. // types
  1213. var generic = nested(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source, 2); // the idea behind the other forbidden characters is to prevent false positives. Same for tupleElement.
  1214. var nestedRound = nested(/\((?:[^()]|<<self>>)*\)/.source, 2);
  1215. var name = /@?\b[A-Za-z_]\w*\b/.source;
  1216. var genericName = replace(/<<0>>(?:\s*<<1>>)?/.source, [name, generic]);
  1217. var identifier = replace(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source, [nonTypeKeywords, genericName]);
  1218. var array = /\[\s*(?:,\s*)*\]/.source;
  1219. var typeExpressionWithoutTuple = replace(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source, [identifier, array]);
  1220. var tupleElement = replace(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source, [generic, nestedRound, array]);
  1221. var tuple = replace(/\(<<0>>+(?:,<<0>>+)+\)/.source, [tupleElement]);
  1222. var typeExpression = replace(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source, [tuple, identifier, array]);
  1223. var typeInside = {
  1224. 'keyword': keywords,
  1225. 'punctuation': /[<>()?,.:[\]]/
  1226. };
  1227. // strings & characters
  1228. // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#character-literals
  1229. // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#string-literals
  1230. var character = /'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source; // simplified pattern
  1231. var regularString = /"(?:\\.|[^\\"\r\n])*"/.source;
  1232. var verbatimString = /@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;
  1233. Prism.languages.csharp = Prism.languages.extend('clike', {
  1234. 'string': [
  1235. {
  1236. pattern: re(/(^|[^$\\])<<0>>/.source, [verbatimString]),
  1237. lookbehind: true,
  1238. greedy: true
  1239. },
  1240. {
  1241. pattern: re(/(^|[^@$\\])<<0>>/.source, [regularString]),
  1242. lookbehind: true,
  1243. greedy: true
  1244. }
  1245. ],
  1246. 'class-name': [
  1247. {
  1248. // Using static
  1249. // using static System.Math;
  1250. pattern: re(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source, [identifier]),
  1251. lookbehind: true,
  1252. inside: typeInside
  1253. },
  1254. {
  1255. // Using alias (type)
  1256. // using Project = PC.MyCompany.Project;
  1257. pattern: re(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source, [name, typeExpression]),
  1258. lookbehind: true,
  1259. inside: typeInside
  1260. },
  1261. {
  1262. // Using alias (alias)
  1263. // using Project = PC.MyCompany.Project;
  1264. pattern: re(/(\busing\s+)<<0>>(?=\s*=)/.source, [name]),
  1265. lookbehind: true
  1266. },
  1267. {
  1268. // Type declarations
  1269. // class Foo<A, B>
  1270. // interface Foo<out A, B>
  1271. pattern: re(/(\b<<0>>\s+)<<1>>/.source, [typeDeclarationKeywords, genericName]),
  1272. lookbehind: true,
  1273. inside: typeInside
  1274. },
  1275. {
  1276. // Single catch exception declaration
  1277. // catch(Foo)
  1278. // (things like catch(Foo e) is covered by variable declaration)
  1279. pattern: re(/(\bcatch\s*\(\s*)<<0>>/.source, [identifier]),
  1280. lookbehind: true,
  1281. inside: typeInside
  1282. },
  1283. {
  1284. // Name of the type parameter of generic constraints
  1285. // where Foo : class
  1286. pattern: re(/(\bwhere\s+)<<0>>/.source, [name]),
  1287. lookbehind: true
  1288. },
  1289. {
  1290. // Casts and checks via as and is.
  1291. // as Foo<A>, is Bar<B>
  1292. // (things like if(a is Foo b) is covered by variable declaration)
  1293. pattern: re(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source, [typeExpressionWithoutTuple]),
  1294. lookbehind: true,
  1295. inside: typeInside
  1296. },
  1297. {
  1298. // Variable, field and parameter declaration
  1299. // (Foo bar, Bar baz, Foo[,,] bay, Foo<Bar, FooBar<Bar>> bax)
  1300. pattern: re(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source, [typeExpression, nonContextualKeywords, name]),
  1301. inside: typeInside
  1302. }
  1303. ],
  1304. 'keyword': keywords,
  1305. // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#literals
  1306. 'number': /(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,
  1307. 'operator': />>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,
  1308. 'punctuation': /\?\.?|::|[{}[\];(),.:]/
  1309. });
  1310. Prism.languages.insertBefore('csharp', 'number', {
  1311. 'range': {
  1312. pattern: /\.\./,
  1313. alias: 'operator'
  1314. }
  1315. });
  1316. Prism.languages.insertBefore('csharp', 'punctuation', {
  1317. 'named-parameter': {
  1318. pattern: re(/([(,]\s*)<<0>>(?=\s*:)/.source, [name]),
  1319. lookbehind: true,
  1320. alias: 'punctuation'
  1321. }
  1322. });
  1323. Prism.languages.insertBefore('csharp', 'class-name', {
  1324. 'namespace': {
  1325. // namespace Foo.Bar {}
  1326. // using Foo.Bar;
  1327. pattern: re(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source, [name]),
  1328. lookbehind: true,
  1329. inside: {
  1330. 'punctuation': /\./
  1331. }
  1332. },
  1333. 'type-expression': {
  1334. // default(Foo), typeof(Foo<Bar>), sizeof(int)
  1335. pattern: re(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source, [nestedRound]),
  1336. lookbehind: true,
  1337. alias: 'class-name',
  1338. inside: typeInside
  1339. },
  1340. 'return-type': {
  1341. // Foo<Bar> ForBar(); Foo IFoo.Bar() => 0
  1342. // int this[int index] => 0; T IReadOnlyList<T>.this[int index] => this[index];
  1343. // int Foo => 0; int Foo { get; set } = 0;
  1344. pattern: re(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source, [typeExpression, identifier]),
  1345. inside: typeInside,
  1346. alias: 'class-name'
  1347. },
  1348. 'constructor-invocation': {
  1349. // new List<Foo<Bar[]>> { }
  1350. pattern: re(/(\bnew\s+)<<0>>(?=\s*[[({])/.source, [typeExpression]),
  1351. lookbehind: true,
  1352. inside: typeInside,
  1353. alias: 'class-name'
  1354. },
  1355. /*'explicit-implementation': {
  1356. // int IFoo<Foo>.Bar => 0; void IFoo<Foo<Foo>>.Foo<T>();
  1357. pattern: replace(/\b<<0>>(?=\.<<1>>)/, className, methodOrPropertyDeclaration),
  1358. inside: classNameInside,
  1359. alias: 'class-name'
  1360. },*/
  1361. 'generic-method': {
  1362. // foo<Bar>()
  1363. pattern: re(/<<0>>\s*<<1>>(?=\s*\()/.source, [name, generic]),
  1364. inside: {
  1365. 'function': re(/^<<0>>/.source, [name]),
  1366. 'generic': {
  1367. pattern: RegExp(generic),
  1368. alias: 'class-name',
  1369. inside: typeInside
  1370. }
  1371. }
  1372. },
  1373. 'type-list': {
  1374. // The list of types inherited or of generic constraints
  1375. // class Foo<F> : Bar, IList<FooBar>
  1376. // where F : Bar, IList<int>
  1377. pattern: re(
  1378. /\b((?:<<0>>\s+<<1>>|record\s+<<1>>\s*<<5>>|where\s+<<2>>)\s*:\s*)(?:<<3>>|<<4>>|<<1>>\s*<<5>>|<<6>>)(?:\s*,\s*(?:<<3>>|<<4>>|<<6>>))*(?=\s*(?:where|[{;]|=>|$))/.source,
  1379. [typeDeclarationKeywords, genericName, name, typeExpression, keywords.source, nestedRound, /\bnew\s*\(\s*\)/.source]
  1380. ),
  1381. lookbehind: true,
  1382. inside: {
  1383. 'record-arguments': {
  1384. pattern: re(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source, [genericName, nestedRound]),
  1385. lookbehind: true,
  1386. greedy: true,
  1387. inside: Prism.languages.csharp
  1388. },
  1389. 'keyword': keywords,
  1390. 'class-name': {
  1391. pattern: RegExp(typeExpression),
  1392. greedy: true,
  1393. inside: typeInside
  1394. },
  1395. 'punctuation': /[,()]/
  1396. }
  1397. },
  1398. 'preprocessor': {
  1399. pattern: /(^[\t ]*)#.*/m,
  1400. lookbehind: true,
  1401. alias: 'property',
  1402. inside: {
  1403. // highlight preprocessor directives as keywords
  1404. 'directive': {
  1405. pattern: /(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,
  1406. lookbehind: true,
  1407. alias: 'keyword'
  1408. }
  1409. }
  1410. }
  1411. });
  1412. // attributes
  1413. var regularStringOrCharacter = regularString + '|' + character;
  1414. var regularStringCharacterOrComment = replace(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source, [regularStringOrCharacter]);
  1415. var roundExpression = nested(replace(/[^"'/()]|<<0>>|\(<<self>>*\)/.source, [regularStringCharacterOrComment]), 2);
  1416. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
  1417. var attrTarget = /\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source;
  1418. var attr = replace(/<<0>>(?:\s*\(<<1>>*\))?/.source, [identifier, roundExpression]);
  1419. Prism.languages.insertBefore('csharp', 'class-name', {
  1420. 'attribute': {
  1421. // Attributes
  1422. // [Foo], [Foo(1), Bar(2, Prop = "foo")], [return: Foo(1), Bar(2)], [assembly: Foo(Bar)]
  1423. pattern: re(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source, [attrTarget, attr]),
  1424. lookbehind: true,
  1425. greedy: true,
  1426. inside: {
  1427. 'target': {
  1428. pattern: re(/^<<0>>(?=\s*:)/.source, [attrTarget]),
  1429. alias: 'keyword'
  1430. },
  1431. 'attribute-arguments': {
  1432. pattern: re(/\(<<0>>*\)/.source, [roundExpression]),
  1433. inside: Prism.languages.csharp
  1434. },
  1435. 'class-name': {
  1436. pattern: RegExp(identifier),
  1437. inside: {
  1438. 'punctuation': /\./
  1439. }
  1440. },
  1441. 'punctuation': /[:,]/
  1442. }
  1443. }
  1444. });
  1445. // string interpolation
  1446. var formatString = /:[^}\r\n]+/.source;
  1447. // multi line
  1448. var mInterpolationRound = nested(replace(/[^"'/()]|<<0>>|\(<<self>>*\)/.source, [regularStringCharacterOrComment]), 2);
  1449. var mInterpolation = replace(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source, [mInterpolationRound, formatString]);
  1450. // single line
  1451. var sInterpolationRound = nested(replace(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source, [regularStringOrCharacter]), 2);
  1452. var sInterpolation = replace(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source, [sInterpolationRound, formatString]);
  1453. function createInterpolationInside(interpolation, interpolationRound) {
  1454. return {
  1455. 'interpolation': {
  1456. pattern: re(/((?:^|[^{])(?:\{\{)*)<<0>>/.source, [interpolation]),
  1457. lookbehind: true,
  1458. inside: {
  1459. 'format-string': {
  1460. pattern: re(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source, [interpolationRound, formatString]),
  1461. lookbehind: true,
  1462. inside: {
  1463. 'punctuation': /^:/
  1464. }
  1465. },
  1466. 'punctuation': /^\{|\}$/,
  1467. 'expression': {
  1468. pattern: /[\s\S]+/,
  1469. alias: 'language-csharp',
  1470. inside: Prism.languages.csharp
  1471. }
  1472. }
  1473. },
  1474. 'string': /[\s\S]+/
  1475. };
  1476. }
  1477. Prism.languages.insertBefore('csharp', 'string', {
  1478. 'interpolation-string': [
  1479. {
  1480. pattern: re(/(^|[^\\])(?:\$@|@\$)"(?:""|\\[\s\S]|\{\{|<<0>>|[^\\{"])*"/.source, [mInterpolation]),
  1481. lookbehind: true,
  1482. greedy: true,
  1483. inside: createInterpolationInside(mInterpolation, mInterpolationRound),
  1484. },
  1485. {
  1486. pattern: re(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source, [sInterpolation]),
  1487. lookbehind: true,
  1488. greedy: true,
  1489. inside: createInterpolationInside(sInterpolation, sInterpolationRound),
  1490. }
  1491. ],
  1492. 'char': {
  1493. pattern: RegExp(character),
  1494. greedy: true
  1495. }
  1496. });
  1497. Prism.languages.dotnet = Prism.languages.cs = Prism.languages.csharp;
  1498. }(Prism));