highlight.js 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575
  1. /*!
  2. Highlight.js v11.7.0 (git: 82688fad18)
  3. (c) 2006-2022 undefined and other contributors
  4. License: BSD-3-Clause
  5. */
  6. var hljs = (function () {
  7. 'use strict';
  8. var deepFreezeEs6 = {exports: {}};
  9. function deepFreeze(obj) {
  10. if (obj instanceof Map) {
  11. obj.clear = obj.delete = obj.set = function () {
  12. throw new Error('map is read-only');
  13. };
  14. } else if (obj instanceof Set) {
  15. obj.add = obj.clear = obj.delete = function () {
  16. throw new Error('set is read-only');
  17. };
  18. }
  19. // Freeze self
  20. Object.freeze(obj);
  21. Object.getOwnPropertyNames(obj).forEach(function (name) {
  22. var prop = obj[name];
  23. // Freeze prop if it is an object
  24. if (typeof prop == 'object' && !Object.isFrozen(prop)) {
  25. deepFreeze(prop);
  26. }
  27. });
  28. return obj;
  29. }
  30. deepFreezeEs6.exports = deepFreeze;
  31. deepFreezeEs6.exports.default = deepFreeze;
  32. /** @typedef {import('highlight.js').CallbackResponse} CallbackResponse */
  33. /** @typedef {import('highlight.js').CompiledMode} CompiledMode */
  34. /** @implements CallbackResponse */
  35. class Response {
  36. /**
  37. * @param {CompiledMode} mode
  38. */
  39. constructor(mode) {
  40. // eslint-disable-next-line no-undefined
  41. if (mode.data === undefined) mode.data = {};
  42. this.data = mode.data;
  43. this.isMatchIgnored = false;
  44. }
  45. ignoreMatch() {
  46. this.isMatchIgnored = true;
  47. }
  48. }
  49. /**
  50. * @param {string} value
  51. * @returns {string}
  52. */
  53. function escapeHTML(value) {
  54. return value
  55. .replace(/&/g, '&')
  56. .replace(/</g, '&lt;')
  57. .replace(/>/g, '&gt;')
  58. .replace(/"/g, '&quot;')
  59. .replace(/'/g, '&#x27;');
  60. }
  61. /**
  62. * performs a shallow merge of multiple objects into one
  63. *
  64. * @template T
  65. * @param {T} original
  66. * @param {Record<string,any>[]} objects
  67. * @returns {T} a single new object
  68. */
  69. function inherit$1(original, ...objects) {
  70. /** @type Record<string,any> */
  71. const result = Object.create(null);
  72. for (const key in original) {
  73. result[key] = original[key];
  74. }
  75. objects.forEach(function(obj) {
  76. for (const key in obj) {
  77. result[key] = obj[key];
  78. }
  79. });
  80. return /** @type {T} */ (result);
  81. }
  82. /**
  83. * @typedef {object} Renderer
  84. * @property {(text: string) => void} addText
  85. * @property {(node: Node) => void} openNode
  86. * @property {(node: Node) => void} closeNode
  87. * @property {() => string} value
  88. */
  89. /** @typedef {{scope?: string, language?: string, sublanguage?: boolean}} Node */
  90. /** @typedef {{walk: (r: Renderer) => void}} Tree */
  91. /** */
  92. const SPAN_CLOSE = '</span>';
  93. /**
  94. * Determines if a node needs to be wrapped in <span>
  95. *
  96. * @param {Node} node */
  97. const emitsWrappingTags = (node) => {
  98. // rarely we can have a sublanguage where language is undefined
  99. // TODO: track down why
  100. return !!node.scope || (node.sublanguage && node.language);
  101. };
  102. /**
  103. *
  104. * @param {string} name
  105. * @param {{prefix:string}} options
  106. */
  107. const scopeToCSSClass = (name, { prefix }) => {
  108. if (name.includes(".")) {
  109. const pieces = name.split(".");
  110. return [
  111. `${prefix}${pieces.shift()}`,
  112. ...(pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`))
  113. ].join(" ");
  114. }
  115. return `${prefix}${name}`;
  116. };
  117. /** @type {Renderer} */
  118. class HTMLRenderer {
  119. /**
  120. * Creates a new HTMLRenderer
  121. *
  122. * @param {Tree} parseTree - the parse tree (must support `walk` API)
  123. * @param {{classPrefix: string}} options
  124. */
  125. constructor(parseTree, options) {
  126. this.buffer = "";
  127. this.classPrefix = options.classPrefix;
  128. parseTree.walk(this);
  129. }
  130. /**
  131. * Adds texts to the output stream
  132. *
  133. * @param {string} text */
  134. addText(text) {
  135. this.buffer += escapeHTML(text);
  136. }
  137. /**
  138. * Adds a node open to the output stream (if needed)
  139. *
  140. * @param {Node} node */
  141. openNode(node) {
  142. if (!emitsWrappingTags(node)) return;
  143. let className = "";
  144. if (node.sublanguage) {
  145. className = `language-${node.language}`;
  146. } else {
  147. className = scopeToCSSClass(node.scope, { prefix: this.classPrefix });
  148. }
  149. this.span(className);
  150. }
  151. /**
  152. * Adds a node close to the output stream (if needed)
  153. *
  154. * @param {Node} node */
  155. closeNode(node) {
  156. if (!emitsWrappingTags(node)) return;
  157. this.buffer += SPAN_CLOSE;
  158. }
  159. /**
  160. * returns the accumulated buffer
  161. */
  162. value() {
  163. return this.buffer;
  164. }
  165. // helpers
  166. /**
  167. * Builds a span element
  168. *
  169. * @param {string} className */
  170. span(className) {
  171. this.buffer += `<span class="${className}">`;
  172. }
  173. }
  174. /** @typedef {{scope?: string, language?: string, sublanguage?: boolean, children: Node[]} | string} Node */
  175. /** @typedef {{scope?: string, language?: string, sublanguage?: boolean, children: Node[]} } DataNode */
  176. /** @typedef {import('highlight.js').Emitter} Emitter */
  177. /** */
  178. /** @returns {DataNode} */
  179. const newNode = (opts = {}) => {
  180. /** @type DataNode */
  181. const result = { children: [] };
  182. Object.assign(result, opts);
  183. return result;
  184. };
  185. class TokenTree {
  186. constructor() {
  187. /** @type DataNode */
  188. this.rootNode = newNode();
  189. this.stack = [this.rootNode];
  190. }
  191. get top() {
  192. return this.stack[this.stack.length - 1];
  193. }
  194. get root() { return this.rootNode; }
  195. /** @param {Node} node */
  196. add(node) {
  197. this.top.children.push(node);
  198. }
  199. /** @param {string} scope */
  200. openNode(scope) {
  201. /** @type Node */
  202. const node = newNode({ scope });
  203. this.add(node);
  204. this.stack.push(node);
  205. }
  206. closeNode() {
  207. if (this.stack.length > 1) {
  208. return this.stack.pop();
  209. }
  210. // eslint-disable-next-line no-undefined
  211. return undefined;
  212. }
  213. closeAllNodes() {
  214. while (this.closeNode());
  215. }
  216. toJSON() {
  217. return JSON.stringify(this.rootNode, null, 4);
  218. }
  219. /**
  220. * @typedef { import("./html_renderer").Renderer } Renderer
  221. * @param {Renderer} builder
  222. */
  223. walk(builder) {
  224. // this does not
  225. return this.constructor._walk(builder, this.rootNode);
  226. // this works
  227. // return TokenTree._walk(builder, this.rootNode);
  228. }
  229. /**
  230. * @param {Renderer} builder
  231. * @param {Node} node
  232. */
  233. static _walk(builder, node) {
  234. if (typeof node === "string") {
  235. builder.addText(node);
  236. } else if (node.children) {
  237. builder.openNode(node);
  238. node.children.forEach((child) => this._walk(builder, child));
  239. builder.closeNode(node);
  240. }
  241. return builder;
  242. }
  243. /**
  244. * @param {Node} node
  245. */
  246. static _collapse(node) {
  247. if (typeof node === "string") return;
  248. if (!node.children) return;
  249. if (node.children.every(el => typeof el === "string")) {
  250. // node.text = node.children.join("");
  251. // delete node.children;
  252. node.children = [node.children.join("")];
  253. } else {
  254. node.children.forEach((child) => {
  255. TokenTree._collapse(child);
  256. });
  257. }
  258. }
  259. }
  260. /**
  261. Currently this is all private API, but this is the minimal API necessary
  262. that an Emitter must implement to fully support the parser.
  263. Minimal interface:
  264. - addKeyword(text, scope)
  265. - addText(text)
  266. - addSublanguage(emitter, subLanguageName)
  267. - finalize()
  268. - openNode(scope)
  269. - closeNode()
  270. - closeAllNodes()
  271. - toHTML()
  272. */
  273. /**
  274. * @implements {Emitter}
  275. */
  276. class TokenTreeEmitter extends TokenTree {
  277. /**
  278. * @param {*} options
  279. */
  280. constructor(options) {
  281. super();
  282. this.options = options;
  283. }
  284. /**
  285. * @param {string} text
  286. * @param {string} scope
  287. */
  288. addKeyword(text, scope) {
  289. if (text === "") { return; }
  290. this.openNode(scope);
  291. this.addText(text);
  292. this.closeNode();
  293. }
  294. /**
  295. * @param {string} text
  296. */
  297. addText(text) {
  298. if (text === "") { return; }
  299. this.add(text);
  300. }
  301. /**
  302. * @param {Emitter & {root: DataNode}} emitter
  303. * @param {string} name
  304. */
  305. addSublanguage(emitter, name) {
  306. /** @type DataNode */
  307. const node = emitter.root;
  308. node.sublanguage = true;
  309. node.language = name;
  310. this.add(node);
  311. }
  312. toHTML() {
  313. const renderer = new HTMLRenderer(this, this.options);
  314. return renderer.value();
  315. }
  316. finalize() {
  317. return true;
  318. }
  319. }
  320. /**
  321. * @param {string} value
  322. * @returns {RegExp}
  323. * */
  324. /**
  325. * @param {RegExp | string } re
  326. * @returns {string}
  327. */
  328. function source(re) {
  329. if (!re) return null;
  330. if (typeof re === "string") return re;
  331. return re.source;
  332. }
  333. /**
  334. * @param {RegExp | string } re
  335. * @returns {string}
  336. */
  337. function lookahead(re) {
  338. return concat('(?=', re, ')');
  339. }
  340. /**
  341. * @param {RegExp | string } re
  342. * @returns {string}
  343. */
  344. function anyNumberOfTimes(re) {
  345. return concat('(?:', re, ')*');
  346. }
  347. /**
  348. * @param {RegExp | string } re
  349. * @returns {string}
  350. */
  351. function optional(re) {
  352. return concat('(?:', re, ')?');
  353. }
  354. /**
  355. * @param {...(RegExp | string) } args
  356. * @returns {string}
  357. */
  358. function concat(...args) {
  359. const joined = args.map((x) => source(x)).join("");
  360. return joined;
  361. }
  362. /**
  363. * @param { Array<string | RegExp | Object> } args
  364. * @returns {object}
  365. */
  366. function stripOptionsFromArgs(args) {
  367. const opts = args[args.length - 1];
  368. if (typeof opts === 'object' && opts.constructor === Object) {
  369. args.splice(args.length - 1, 1);
  370. return opts;
  371. } else {
  372. return {};
  373. }
  374. }
  375. /** @typedef { {capture?: boolean} } RegexEitherOptions */
  376. /**
  377. * Any of the passed expresssions may match
  378. *
  379. * Creates a huge this | this | that | that match
  380. * @param {(RegExp | string)[] | [...(RegExp | string)[], RegexEitherOptions]} args
  381. * @returns {string}
  382. */
  383. function either(...args) {
  384. /** @type { object & {capture?: boolean} } */
  385. const opts = stripOptionsFromArgs(args);
  386. const joined = '('
  387. + (opts.capture ? "" : "?:")
  388. + args.map((x) => source(x)).join("|") + ")";
  389. return joined;
  390. }
  391. /**
  392. * @param {RegExp | string} re
  393. * @returns {number}
  394. */
  395. function countMatchGroups(re) {
  396. return (new RegExp(re.toString() + '|')).exec('').length - 1;
  397. }
  398. /**
  399. * Does lexeme start with a regular expression match at the beginning
  400. * @param {RegExp} re
  401. * @param {string} lexeme
  402. */
  403. function startsWith(re, lexeme) {
  404. const match = re && re.exec(lexeme);
  405. return match && match.index === 0;
  406. }
  407. // BACKREF_RE matches an open parenthesis or backreference. To avoid
  408. // an incorrect parse, it additionally matches the following:
  409. // - [...] elements, where the meaning of parentheses and escapes change
  410. // - other escape sequences, so we do not misparse escape sequences as
  411. // interesting elements
  412. // - non-matching or lookahead parentheses, which do not capture. These
  413. // follow the '(' with a '?'.
  414. const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
  415. // **INTERNAL** Not intended for outside usage
  416. // join logically computes regexps.join(separator), but fixes the
  417. // backreferences so they continue to match.
  418. // it also places each individual regular expression into it's own
  419. // match group, keeping track of the sequencing of those match groups
  420. // is currently an exercise for the caller. :-)
  421. /**
  422. * @param {(string | RegExp)[]} regexps
  423. * @param {{joinWith: string}} opts
  424. * @returns {string}
  425. */
  426. function _rewriteBackreferences(regexps, { joinWith }) {
  427. let numCaptures = 0;
  428. return regexps.map((regex) => {
  429. numCaptures += 1;
  430. const offset = numCaptures;
  431. let re = source(regex);
  432. let out = '';
  433. while (re.length > 0) {
  434. const match = BACKREF_RE.exec(re);
  435. if (!match) {
  436. out += re;
  437. break;
  438. }
  439. out += re.substring(0, match.index);
  440. re = re.substring(match.index + match[0].length);
  441. if (match[0][0] === '\\' && match[1]) {
  442. // Adjust the backreference.
  443. out += '\\' + String(Number(match[1]) + offset);
  444. } else {
  445. out += match[0];
  446. if (match[0] === '(') {
  447. numCaptures++;
  448. }
  449. }
  450. }
  451. return out;
  452. }).map(re => `(${re})`).join(joinWith);
  453. }
  454. /** @typedef {import('highlight.js').Mode} Mode */
  455. /** @typedef {import('highlight.js').ModeCallback} ModeCallback */
  456. // Common regexps
  457. const MATCH_NOTHING_RE = /\b\B/;
  458. const IDENT_RE = '[a-zA-Z]\\w*';
  459. const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
  460. const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
  461. const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
  462. const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
  463. const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
  464. /**
  465. * @param { Partial<Mode> & {binary?: string | RegExp} } opts
  466. */
  467. const SHEBANG = (opts = {}) => {
  468. const beginShebang = /^#![ ]*\//;
  469. if (opts.binary) {
  470. opts.begin = concat(
  471. beginShebang,
  472. /.*\b/,
  473. opts.binary,
  474. /\b.*/);
  475. }
  476. return inherit$1({
  477. scope: 'meta',
  478. begin: beginShebang,
  479. end: /$/,
  480. relevance: 0,
  481. /** @type {ModeCallback} */
  482. "on:begin": (m, resp) => {
  483. if (m.index !== 0) resp.ignoreMatch();
  484. }
  485. }, opts);
  486. };
  487. // Common modes
  488. const BACKSLASH_ESCAPE = {
  489. begin: '\\\\[\\s\\S]', relevance: 0
  490. };
  491. const APOS_STRING_MODE = {
  492. scope: 'string',
  493. begin: '\'',
  494. end: '\'',
  495. illegal: '\\n',
  496. contains: [BACKSLASH_ESCAPE]
  497. };
  498. const QUOTE_STRING_MODE = {
  499. scope: 'string',
  500. begin: '"',
  501. end: '"',
  502. illegal: '\\n',
  503. contains: [BACKSLASH_ESCAPE]
  504. };
  505. const PHRASAL_WORDS_MODE = {
  506. begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
  507. };
  508. /**
  509. * Creates a comment mode
  510. *
  511. * @param {string | RegExp} begin
  512. * @param {string | RegExp} end
  513. * @param {Mode | {}} [modeOptions]
  514. * @returns {Partial<Mode>}
  515. */
  516. const COMMENT = function(begin, end, modeOptions = {}) {
  517. const mode = inherit$1(
  518. {
  519. scope: 'comment',
  520. begin,
  521. end,
  522. contains: []
  523. },
  524. modeOptions
  525. );
  526. mode.contains.push({
  527. scope: 'doctag',
  528. // hack to avoid the space from being included. the space is necessary to
  529. // match here to prevent the plain text rule below from gobbling up doctags
  530. begin: '[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)',
  531. end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
  532. excludeBegin: true,
  533. relevance: 0
  534. });
  535. const ENGLISH_WORD = either(
  536. // list of common 1 and 2 letter words in English
  537. "I",
  538. "a",
  539. "is",
  540. "so",
  541. "us",
  542. "to",
  543. "at",
  544. "if",
  545. "in",
  546. "it",
  547. "on",
  548. // note: this is not an exhaustive list of contractions, just popular ones
  549. /[A-Za-z]+['](d|ve|re|ll|t|s|n)/, // contractions - can't we'd they're let's, etc
  550. /[A-Za-z]+[-][a-z]+/, // `no-way`, etc.
  551. /[A-Za-z][a-z]{2,}/ // allow capitalized words at beginning of sentences
  552. );
  553. // looking like plain text, more likely to be a comment
  554. mode.contains.push(
  555. {
  556. // TODO: how to include ", (, ) without breaking grammars that use these for
  557. // comment delimiters?
  558. // begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
  559. // ---
  560. // this tries to find sequences of 3 english words in a row (without any
  561. // "programming" type syntax) this gives us a strong signal that we've
  562. // TRULY found a comment - vs perhaps scanning with the wrong language.
  563. // It's possible to find something that LOOKS like the start of the
  564. // comment - but then if there is no readable text - good chance it is a
  565. // false match and not a comment.
  566. //
  567. // for a visual example please see:
  568. // https://github.com/highlightjs/highlight.js/issues/2827
  569. begin: concat(
  570. /[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
  571. '(',
  572. ENGLISH_WORD,
  573. /[.]?[:]?([.][ ]|[ ])/,
  574. '){3}') // look for 3 words in a row
  575. }
  576. );
  577. return mode;
  578. };
  579. const C_LINE_COMMENT_MODE = COMMENT('//', '$');
  580. const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
  581. const HASH_COMMENT_MODE = COMMENT('#', '$');
  582. const NUMBER_MODE = {
  583. scope: 'number',
  584. begin: NUMBER_RE,
  585. relevance: 0
  586. };
  587. const C_NUMBER_MODE = {
  588. scope: 'number',
  589. begin: C_NUMBER_RE,
  590. relevance: 0
  591. };
  592. const BINARY_NUMBER_MODE = {
  593. scope: 'number',
  594. begin: BINARY_NUMBER_RE,
  595. relevance: 0
  596. };
  597. const REGEXP_MODE = {
  598. // this outer rule makes sure we actually have a WHOLE regex and not simply
  599. // an expression such as:
  600. //
  601. // 3 / something
  602. //
  603. // (which will then blow up when regex's `illegal` sees the newline)
  604. begin: /(?=\/[^/\n]*\/)/,
  605. contains: [{
  606. scope: 'regexp',
  607. begin: /\//,
  608. end: /\/[gimuy]*/,
  609. illegal: /\n/,
  610. contains: [
  611. BACKSLASH_ESCAPE,
  612. {
  613. begin: /\[/,
  614. end: /\]/,
  615. relevance: 0,
  616. contains: [BACKSLASH_ESCAPE]
  617. }
  618. ]
  619. }]
  620. };
  621. const TITLE_MODE = {
  622. scope: 'title',
  623. begin: IDENT_RE,
  624. relevance: 0
  625. };
  626. const UNDERSCORE_TITLE_MODE = {
  627. scope: 'title',
  628. begin: UNDERSCORE_IDENT_RE,
  629. relevance: 0
  630. };
  631. const METHOD_GUARD = {
  632. // excludes method names from keyword processing
  633. begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
  634. relevance: 0
  635. };
  636. /**
  637. * Adds end same as begin mechanics to a mode
  638. *
  639. * Your mode must include at least a single () match group as that first match
  640. * group is what is used for comparison
  641. * @param {Partial<Mode>} mode
  642. */
  643. const END_SAME_AS_BEGIN = function(mode) {
  644. return Object.assign(mode,
  645. {
  646. /** @type {ModeCallback} */
  647. 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
  648. /** @type {ModeCallback} */
  649. 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
  650. });
  651. };
  652. var MODES = /*#__PURE__*/Object.freeze({
  653. __proto__: null,
  654. MATCH_NOTHING_RE: MATCH_NOTHING_RE,
  655. IDENT_RE: IDENT_RE,
  656. UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
  657. NUMBER_RE: NUMBER_RE,
  658. C_NUMBER_RE: C_NUMBER_RE,
  659. BINARY_NUMBER_RE: BINARY_NUMBER_RE,
  660. RE_STARTERS_RE: RE_STARTERS_RE,
  661. SHEBANG: SHEBANG,
  662. BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
  663. APOS_STRING_MODE: APOS_STRING_MODE,
  664. QUOTE_STRING_MODE: QUOTE_STRING_MODE,
  665. PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
  666. COMMENT: COMMENT,
  667. C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
  668. C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
  669. HASH_COMMENT_MODE: HASH_COMMENT_MODE,
  670. NUMBER_MODE: NUMBER_MODE,
  671. C_NUMBER_MODE: C_NUMBER_MODE,
  672. BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
  673. REGEXP_MODE: REGEXP_MODE,
  674. TITLE_MODE: TITLE_MODE,
  675. UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE,
  676. METHOD_GUARD: METHOD_GUARD,
  677. END_SAME_AS_BEGIN: END_SAME_AS_BEGIN
  678. });
  679. /**
  680. @typedef {import('highlight.js').CallbackResponse} CallbackResponse
  681. @typedef {import('highlight.js').CompilerExt} CompilerExt
  682. */
  683. // Grammar extensions / plugins
  684. // See: https://github.com/highlightjs/highlight.js/issues/2833
  685. // Grammar extensions allow "syntactic sugar" to be added to the grammar modes
  686. // without requiring any underlying changes to the compiler internals.
  687. // `compileMatch` being the perfect small example of now allowing a grammar
  688. // author to write `match` when they desire to match a single expression rather
  689. // than being forced to use `begin`. The extension then just moves `match` into
  690. // `begin` when it runs. Ie, no features have been added, but we've just made
  691. // the experience of writing (and reading grammars) a little bit nicer.
  692. // ------
  693. // TODO: We need negative look-behind support to do this properly
  694. /**
  695. * Skip a match if it has a preceding dot
  696. *
  697. * This is used for `beginKeywords` to prevent matching expressions such as
  698. * `bob.keyword.do()`. The mode compiler automatically wires this up as a
  699. * special _internal_ 'on:begin' callback for modes with `beginKeywords`
  700. * @param {RegExpMatchArray} match
  701. * @param {CallbackResponse} response
  702. */
  703. function skipIfHasPrecedingDot(match, response) {
  704. const before = match.input[match.index - 1];
  705. if (before === ".") {
  706. response.ignoreMatch();
  707. }
  708. }
  709. /**
  710. *
  711. * @type {CompilerExt}
  712. */
  713. function scopeClassName(mode, _parent) {
  714. // eslint-disable-next-line no-undefined
  715. if (mode.className !== undefined) {
  716. mode.scope = mode.className;
  717. delete mode.className;
  718. }
  719. }
  720. /**
  721. * `beginKeywords` syntactic sugar
  722. * @type {CompilerExt}
  723. */
  724. function beginKeywords(mode, parent) {
  725. if (!parent) return;
  726. if (!mode.beginKeywords) return;
  727. // for languages with keywords that include non-word characters checking for
  728. // a word boundary is not sufficient, so instead we check for a word boundary
  729. // or whitespace - this does no harm in any case since our keyword engine
  730. // doesn't allow spaces in keywords anyways and we still check for the boundary
  731. // first
  732. mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)';
  733. mode.__beforeBegin = skipIfHasPrecedingDot;
  734. mode.keywords = mode.keywords || mode.beginKeywords;
  735. delete mode.beginKeywords;
  736. // prevents double relevance, the keywords themselves provide
  737. // relevance, the mode doesn't need to double it
  738. // eslint-disable-next-line no-undefined
  739. if (mode.relevance === undefined) mode.relevance = 0;
  740. }
  741. /**
  742. * Allow `illegal` to contain an array of illegal values
  743. * @type {CompilerExt}
  744. */
  745. function compileIllegal(mode, _parent) {
  746. if (!Array.isArray(mode.illegal)) return;
  747. mode.illegal = either(...mode.illegal);
  748. }
  749. /**
  750. * `match` to match a single expression for readability
  751. * @type {CompilerExt}
  752. */
  753. function compileMatch(mode, _parent) {
  754. if (!mode.match) return;
  755. if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
  756. mode.begin = mode.match;
  757. delete mode.match;
  758. }
  759. /**
  760. * provides the default 1 relevance to all modes
  761. * @type {CompilerExt}
  762. */
  763. function compileRelevance(mode, _parent) {
  764. // eslint-disable-next-line no-undefined
  765. if (mode.relevance === undefined) mode.relevance = 1;
  766. }
  767. // allow beforeMatch to act as a "qualifier" for the match
  768. // the full match begin must be [beforeMatch][begin]
  769. const beforeMatchExt = (mode, parent) => {
  770. if (!mode.beforeMatch) return;
  771. // starts conflicts with endsParent which we need to make sure the child
  772. // rule is not matched multiple times
  773. if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
  774. const originalMode = Object.assign({}, mode);
  775. Object.keys(mode).forEach((key) => { delete mode[key]; });
  776. mode.keywords = originalMode.keywords;
  777. mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
  778. mode.starts = {
  779. relevance: 0,
  780. contains: [
  781. Object.assign(originalMode, { endsParent: true })
  782. ]
  783. };
  784. mode.relevance = 0;
  785. delete originalMode.beforeMatch;
  786. };
  787. // keywords that should have no default relevance value
  788. const COMMON_KEYWORDS = [
  789. 'of',
  790. 'and',
  791. 'for',
  792. 'in',
  793. 'not',
  794. 'or',
  795. 'if',
  796. 'then',
  797. 'parent', // common variable name
  798. 'list', // common variable name
  799. 'value' // common variable name
  800. ];
  801. const DEFAULT_KEYWORD_SCOPE = "keyword";
  802. /**
  803. * Given raw keywords from a language definition, compile them.
  804. *
  805. * @param {string | Record<string,string|string[]> | Array<string>} rawKeywords
  806. * @param {boolean} caseInsensitive
  807. */
  808. function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
  809. /** @type {import("highlight.js/private").KeywordDict} */
  810. const compiledKeywords = Object.create(null);
  811. // input can be a string of keywords, an array of keywords, or a object with
  812. // named keys representing scopeName (which can then point to a string or array)
  813. if (typeof rawKeywords === 'string') {
  814. compileList(scopeName, rawKeywords.split(" "));
  815. } else if (Array.isArray(rawKeywords)) {
  816. compileList(scopeName, rawKeywords);
  817. } else {
  818. Object.keys(rawKeywords).forEach(function(scopeName) {
  819. // collapse all our objects back into the parent object
  820. Object.assign(
  821. compiledKeywords,
  822. compileKeywords(rawKeywords[scopeName], caseInsensitive, scopeName)
  823. );
  824. });
  825. }
  826. return compiledKeywords;
  827. // ---
  828. /**
  829. * Compiles an individual list of keywords
  830. *
  831. * Ex: "for if when while|5"
  832. *
  833. * @param {string} scopeName
  834. * @param {Array<string>} keywordList
  835. */
  836. function compileList(scopeName, keywordList) {
  837. if (caseInsensitive) {
  838. keywordList = keywordList.map(x => x.toLowerCase());
  839. }
  840. keywordList.forEach(function(keyword) {
  841. const pair = keyword.split('|');
  842. compiledKeywords[pair[0]] = [scopeName, scoreForKeyword(pair[0], pair[1])];
  843. });
  844. }
  845. }
  846. /**
  847. * Returns the proper score for a given keyword
  848. *
  849. * Also takes into account comment keywords, which will be scored 0 UNLESS
  850. * another score has been manually assigned.
  851. * @param {string} keyword
  852. * @param {string} [providedScore]
  853. */
  854. function scoreForKeyword(keyword, providedScore) {
  855. // manual scores always win over common keywords
  856. // so you can force a score of 1 if you really insist
  857. if (providedScore) {
  858. return Number(providedScore);
  859. }
  860. return commonKeyword(keyword) ? 0 : 1;
  861. }
  862. /**
  863. * Determines if a given keyword is common or not
  864. *
  865. * @param {string} keyword */
  866. function commonKeyword(keyword) {
  867. return COMMON_KEYWORDS.includes(keyword.toLowerCase());
  868. }
  869. /*
  870. For the reasoning behind this please see:
  871. https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419
  872. */
  873. /**
  874. * @type {Record<string, boolean>}
  875. */
  876. const seenDeprecations = {};
  877. /**
  878. * @param {string} message
  879. */
  880. const error = (message) => {
  881. console.error(message);
  882. };
  883. /**
  884. * @param {string} message
  885. * @param {any} args
  886. */
  887. const warn = (message, ...args) => {
  888. console.log(`WARN: ${message}`, ...args);
  889. };
  890. /**
  891. * @param {string} version
  892. * @param {string} message
  893. */
  894. const deprecated = (version, message) => {
  895. if (seenDeprecations[`${version}/${message}`]) return;
  896. console.log(`Deprecated as of ${version}. ${message}`);
  897. seenDeprecations[`${version}/${message}`] = true;
  898. };
  899. /* eslint-disable no-throw-literal */
  900. /**
  901. @typedef {import('highlight.js').CompiledMode} CompiledMode
  902. */
  903. const MultiClassError = new Error();
  904. /**
  905. * Renumbers labeled scope names to account for additional inner match
  906. * groups that otherwise would break everything.
  907. *
  908. * Lets say we 3 match scopes:
  909. *
  910. * { 1 => ..., 2 => ..., 3 => ... }
  911. *
  912. * So what we need is a clean match like this:
  913. *
  914. * (a)(b)(c) => [ "a", "b", "c" ]
  915. *
  916. * But this falls apart with inner match groups:
  917. *
  918. * (a)(((b)))(c) => ["a", "b", "b", "b", "c" ]
  919. *
  920. * Our scopes are now "out of alignment" and we're repeating `b` 3 times.
  921. * What needs to happen is the numbers are remapped:
  922. *
  923. * { 1 => ..., 2 => ..., 5 => ... }
  924. *
  925. * We also need to know that the ONLY groups that should be output
  926. * are 1, 2, and 5. This function handles this behavior.
  927. *
  928. * @param {CompiledMode} mode
  929. * @param {Array<RegExp | string>} regexes
  930. * @param {{key: "beginScope"|"endScope"}} opts
  931. */
  932. function remapScopeNames(mode, regexes, { key }) {
  933. let offset = 0;
  934. const scopeNames = mode[key];
  935. /** @type Record<number,boolean> */
  936. const emit = {};
  937. /** @type Record<number,string> */
  938. const positions = {};
  939. for (let i = 1; i <= regexes.length; i++) {
  940. positions[i + offset] = scopeNames[i];
  941. emit[i + offset] = true;
  942. offset += countMatchGroups(regexes[i - 1]);
  943. }
  944. // we use _emit to keep track of which match groups are "top-level" to avoid double
  945. // output from inside match groups
  946. mode[key] = positions;
  947. mode[key]._emit = emit;
  948. mode[key]._multi = true;
  949. }
  950. /**
  951. * @param {CompiledMode} mode
  952. */
  953. function beginMultiClass(mode) {
  954. if (!Array.isArray(mode.begin)) return;
  955. if (mode.skip || mode.excludeBegin || mode.returnBegin) {
  956. error("skip, excludeBegin, returnBegin not compatible with beginScope: {}");
  957. throw MultiClassError;
  958. }
  959. if (typeof mode.beginScope !== "object" || mode.beginScope === null) {
  960. error("beginScope must be object");
  961. throw MultiClassError;
  962. }
  963. remapScopeNames(mode, mode.begin, { key: "beginScope" });
  964. mode.begin = _rewriteBackreferences(mode.begin, { joinWith: "" });
  965. }
  966. /**
  967. * @param {CompiledMode} mode
  968. */
  969. function endMultiClass(mode) {
  970. if (!Array.isArray(mode.end)) return;
  971. if (mode.skip || mode.excludeEnd || mode.returnEnd) {
  972. error("skip, excludeEnd, returnEnd not compatible with endScope: {}");
  973. throw MultiClassError;
  974. }
  975. if (typeof mode.endScope !== "object" || mode.endScope === null) {
  976. error("endScope must be object");
  977. throw MultiClassError;
  978. }
  979. remapScopeNames(mode, mode.end, { key: "endScope" });
  980. mode.end = _rewriteBackreferences(mode.end, { joinWith: "" });
  981. }
  982. /**
  983. * this exists only to allow `scope: {}` to be used beside `match:`
  984. * Otherwise `beginScope` would necessary and that would look weird
  985. {
  986. match: [ /def/, /\w+/ ]
  987. scope: { 1: "keyword" , 2: "title" }
  988. }
  989. * @param {CompiledMode} mode
  990. */
  991. function scopeSugar(mode) {
  992. if (mode.scope && typeof mode.scope === "object" && mode.scope !== null) {
  993. mode.beginScope = mode.scope;
  994. delete mode.scope;
  995. }
  996. }
  997. /**
  998. * @param {CompiledMode} mode
  999. */
  1000. function MultiClass(mode) {
  1001. scopeSugar(mode);
  1002. if (typeof mode.beginScope === "string") {
  1003. mode.beginScope = { _wrap: mode.beginScope };
  1004. }
  1005. if (typeof mode.endScope === "string") {
  1006. mode.endScope = { _wrap: mode.endScope };
  1007. }
  1008. beginMultiClass(mode);
  1009. endMultiClass(mode);
  1010. }
  1011. /**
  1012. @typedef {import('highlight.js').Mode} Mode
  1013. @typedef {import('highlight.js').CompiledMode} CompiledMode
  1014. @typedef {import('highlight.js').Language} Language
  1015. @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin
  1016. @typedef {import('highlight.js').CompiledLanguage} CompiledLanguage
  1017. */
  1018. // compilation
  1019. /**
  1020. * Compiles a language definition result
  1021. *
  1022. * Given the raw result of a language definition (Language), compiles this so
  1023. * that it is ready for highlighting code.
  1024. * @param {Language} language
  1025. * @returns {CompiledLanguage}
  1026. */
  1027. function compileLanguage(language) {
  1028. /**
  1029. * Builds a regex with the case sensitivity of the current language
  1030. *
  1031. * @param {RegExp | string} value
  1032. * @param {boolean} [global]
  1033. */
  1034. function langRe(value, global) {
  1035. return new RegExp(
  1036. source(value),
  1037. 'm'
  1038. + (language.case_insensitive ? 'i' : '')
  1039. + (language.unicodeRegex ? 'u' : '')
  1040. + (global ? 'g' : '')
  1041. );
  1042. }
  1043. /**
  1044. Stores multiple regular expressions and allows you to quickly search for
  1045. them all in a string simultaneously - returning the first match. It does
  1046. this by creating a huge (a|b|c) regex - each individual item wrapped with ()
  1047. and joined by `|` - using match groups to track position. When a match is
  1048. found checking which position in the array has content allows us to figure
  1049. out which of the original regexes / match groups triggered the match.
  1050. The match object itself (the result of `Regex.exec`) is returned but also
  1051. enhanced by merging in any meta-data that was registered with the regex.
  1052. This is how we keep track of which mode matched, and what type of rule
  1053. (`illegal`, `begin`, end, etc).
  1054. */
  1055. class MultiRegex {
  1056. constructor() {
  1057. this.matchIndexes = {};
  1058. // @ts-ignore
  1059. this.regexes = [];
  1060. this.matchAt = 1;
  1061. this.position = 0;
  1062. }
  1063. // @ts-ignore
  1064. addRule(re, opts) {
  1065. opts.position = this.position++;
  1066. // @ts-ignore
  1067. this.matchIndexes[this.matchAt] = opts;
  1068. this.regexes.push([opts, re]);
  1069. this.matchAt += countMatchGroups(re) + 1;
  1070. }
  1071. compile() {
  1072. if (this.regexes.length === 0) {
  1073. // avoids the need to check length every time exec is called
  1074. // @ts-ignore
  1075. this.exec = () => null;
  1076. }
  1077. const terminators = this.regexes.map(el => el[1]);
  1078. this.matcherRe = langRe(_rewriteBackreferences(terminators, { joinWith: '|' }), true);
  1079. this.lastIndex = 0;
  1080. }
  1081. /** @param {string} s */
  1082. exec(s) {
  1083. this.matcherRe.lastIndex = this.lastIndex;
  1084. const match = this.matcherRe.exec(s);
  1085. if (!match) { return null; }
  1086. // eslint-disable-next-line no-undefined
  1087. const i = match.findIndex((el, i) => i > 0 && el !== undefined);
  1088. // @ts-ignore
  1089. const matchData = this.matchIndexes[i];
  1090. // trim off any earlier non-relevant match groups (ie, the other regex
  1091. // match groups that make up the multi-matcher)
  1092. match.splice(0, i);
  1093. return Object.assign(match, matchData);
  1094. }
  1095. }
  1096. /*
  1097. Created to solve the key deficiently with MultiRegex - there is no way to
  1098. test for multiple matches at a single location. Why would we need to do
  1099. that? In the future a more dynamic engine will allow certain matches to be
  1100. ignored. An example: if we matched say the 3rd regex in a large group but
  1101. decided to ignore it - we'd need to started testing again at the 4th
  1102. regex... but MultiRegex itself gives us no real way to do that.
  1103. So what this class creates MultiRegexs on the fly for whatever search
  1104. position they are needed.
  1105. NOTE: These additional MultiRegex objects are created dynamically. For most
  1106. grammars most of the time we will never actually need anything more than the
  1107. first MultiRegex - so this shouldn't have too much overhead.
  1108. Say this is our search group, and we match regex3, but wish to ignore it.
  1109. regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0
  1110. What we need is a new MultiRegex that only includes the remaining
  1111. possibilities:
  1112. regex4 | regex5 ' ie, startAt = 3
  1113. This class wraps all that complexity up in a simple API... `startAt` decides
  1114. where in the array of expressions to start doing the matching. It
  1115. auto-increments, so if a match is found at position 2, then startAt will be
  1116. set to 3. If the end is reached startAt will return to 0.
  1117. MOST of the time the parser will be setting startAt manually to 0.
  1118. */
  1119. class ResumableMultiRegex {
  1120. constructor() {
  1121. // @ts-ignore
  1122. this.rules = [];
  1123. // @ts-ignore
  1124. this.multiRegexes = [];
  1125. this.count = 0;
  1126. this.lastIndex = 0;
  1127. this.regexIndex = 0;
  1128. }
  1129. // @ts-ignore
  1130. getMatcher(index) {
  1131. if (this.multiRegexes[index]) return this.multiRegexes[index];
  1132. const matcher = new MultiRegex();
  1133. this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
  1134. matcher.compile();
  1135. this.multiRegexes[index] = matcher;
  1136. return matcher;
  1137. }
  1138. resumingScanAtSamePosition() {
  1139. return this.regexIndex !== 0;
  1140. }
  1141. considerAll() {
  1142. this.regexIndex = 0;
  1143. }
  1144. // @ts-ignore
  1145. addRule(re, opts) {
  1146. this.rules.push([re, opts]);
  1147. if (opts.type === "begin") this.count++;
  1148. }
  1149. /** @param {string} s */
  1150. exec(s) {
  1151. const m = this.getMatcher(this.regexIndex);
  1152. m.lastIndex = this.lastIndex;
  1153. let result = m.exec(s);
  1154. // The following is because we have no easy way to say "resume scanning at the
  1155. // existing position but also skip the current rule ONLY". What happens is
  1156. // all prior rules are also skipped which can result in matching the wrong
  1157. // thing. Example of matching "booger":
  1158. // our matcher is [string, "booger", number]
  1159. //
  1160. // ....booger....
  1161. // if "booger" is ignored then we'd really need a regex to scan from the
  1162. // SAME position for only: [string, number] but ignoring "booger" (if it
  1163. // was the first match), a simple resume would scan ahead who knows how
  1164. // far looking only for "number", ignoring potential string matches (or
  1165. // future "booger" matches that might be valid.)
  1166. // So what we do: We execute two matchers, one resuming at the same
  1167. // position, but the second full matcher starting at the position after:
  1168. // /--- resume first regex match here (for [number])
  1169. // |/---- full match here for [string, "booger", number]
  1170. // vv
  1171. // ....booger....
  1172. // Which ever results in a match first is then used. So this 3-4 step
  1173. // process essentially allows us to say "match at this position, excluding
  1174. // a prior rule that was ignored".
  1175. //
  1176. // 1. Match "booger" first, ignore. Also proves that [string] does non match.
  1177. // 2. Resume matching for [number]
  1178. // 3. Match at index + 1 for [string, "booger", number]
  1179. // 4. If #2 and #3 result in matches, which came first?
  1180. if (this.resumingScanAtSamePosition()) {
  1181. if (result && result.index === this.lastIndex) ; else { // use the second matcher result
  1182. const m2 = this.getMatcher(0);
  1183. m2.lastIndex = this.lastIndex + 1;
  1184. result = m2.exec(s);
  1185. }
  1186. }
  1187. if (result) {
  1188. this.regexIndex += result.position + 1;
  1189. if (this.regexIndex === this.count) {
  1190. // wrap-around to considering all matches again
  1191. this.considerAll();
  1192. }
  1193. }
  1194. return result;
  1195. }
  1196. }
  1197. /**
  1198. * Given a mode, builds a huge ResumableMultiRegex that can be used to walk
  1199. * the content and find matches.
  1200. *
  1201. * @param {CompiledMode} mode
  1202. * @returns {ResumableMultiRegex}
  1203. */
  1204. function buildModeRegex(mode) {
  1205. const mm = new ResumableMultiRegex();
  1206. mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));
  1207. if (mode.terminatorEnd) {
  1208. mm.addRule(mode.terminatorEnd, { type: "end" });
  1209. }
  1210. if (mode.illegal) {
  1211. mm.addRule(mode.illegal, { type: "illegal" });
  1212. }
  1213. return mm;
  1214. }
  1215. /** skip vs abort vs ignore
  1216. *
  1217. * @skip - The mode is still entered and exited normally (and contains rules apply),
  1218. * but all content is held and added to the parent buffer rather than being
  1219. * output when the mode ends. Mostly used with `sublanguage` to build up
  1220. * a single large buffer than can be parsed by sublanguage.
  1221. *
  1222. * - The mode begin ands ends normally.
  1223. * - Content matched is added to the parent mode buffer.
  1224. * - The parser cursor is moved forward normally.
  1225. *
  1226. * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it
  1227. * never matched) but DOES NOT continue to match subsequent `contains`
  1228. * modes. Abort is bad/suboptimal because it can result in modes
  1229. * farther down not getting applied because an earlier rule eats the
  1230. * content but then aborts.
  1231. *
  1232. * - The mode does not begin.
  1233. * - Content matched by `begin` is added to the mode buffer.
  1234. * - The parser cursor is moved forward accordingly.
  1235. *
  1236. * @ignore - Ignores the mode (as if it never matched) and continues to match any
  1237. * subsequent `contains` modes. Ignore isn't technically possible with
  1238. * the current parser implementation.
  1239. *
  1240. * - The mode does not begin.
  1241. * - Content matched by `begin` is ignored.
  1242. * - The parser cursor is not moved forward.
  1243. */
  1244. /**
  1245. * Compiles an individual mode
  1246. *
  1247. * This can raise an error if the mode contains certain detectable known logic
  1248. * issues.
  1249. * @param {Mode} mode
  1250. * @param {CompiledMode | null} [parent]
  1251. * @returns {CompiledMode | never}
  1252. */
  1253. function compileMode(mode, parent) {
  1254. const cmode = /** @type CompiledMode */ (mode);
  1255. if (mode.isCompiled) return cmode;
  1256. [
  1257. scopeClassName,
  1258. // do this early so compiler extensions generally don't have to worry about
  1259. // the distinction between match/begin
  1260. compileMatch,
  1261. MultiClass,
  1262. beforeMatchExt
  1263. ].forEach(ext => ext(mode, parent));
  1264. language.compilerExtensions.forEach(ext => ext(mode, parent));
  1265. // __beforeBegin is considered private API, internal use only
  1266. mode.__beforeBegin = null;
  1267. [
  1268. beginKeywords,
  1269. // do this later so compiler extensions that come earlier have access to the
  1270. // raw array if they wanted to perhaps manipulate it, etc.
  1271. compileIllegal,
  1272. // default to 1 relevance if not specified
  1273. compileRelevance
  1274. ].forEach(ext => ext(mode, parent));
  1275. mode.isCompiled = true;
  1276. let keywordPattern = null;
  1277. if (typeof mode.keywords === "object" && mode.keywords.$pattern) {
  1278. // we need a copy because keywords might be compiled multiple times
  1279. // so we can't go deleting $pattern from the original on the first
  1280. // pass
  1281. mode.keywords = Object.assign({}, mode.keywords);
  1282. keywordPattern = mode.keywords.$pattern;
  1283. delete mode.keywords.$pattern;
  1284. }
  1285. keywordPattern = keywordPattern || /\w+/;
  1286. if (mode.keywords) {
  1287. mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
  1288. }
  1289. cmode.keywordPatternRe = langRe(keywordPattern, true);
  1290. if (parent) {
  1291. if (!mode.begin) mode.begin = /\B|\b/;
  1292. cmode.beginRe = langRe(cmode.begin);
  1293. if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
  1294. if (mode.end) cmode.endRe = langRe(cmode.end);
  1295. cmode.terminatorEnd = source(cmode.end) || '';
  1296. if (mode.endsWithParent && parent.terminatorEnd) {
  1297. cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd;
  1298. }
  1299. }
  1300. if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal));
  1301. if (!mode.contains) mode.contains = [];
  1302. mode.contains = [].concat(...mode.contains.map(function(c) {
  1303. return expandOrCloneMode(c === 'self' ? mode : c);
  1304. }));
  1305. mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });
  1306. if (mode.starts) {
  1307. compileMode(mode.starts, parent);
  1308. }
  1309. cmode.matcher = buildModeRegex(cmode);
  1310. return cmode;
  1311. }
  1312. if (!language.compilerExtensions) language.compilerExtensions = [];
  1313. // self is not valid at the top-level
  1314. if (language.contains && language.contains.includes('self')) {
  1315. throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
  1316. }
  1317. // we need a null object, which inherit will guarantee
  1318. language.classNameAliases = inherit$1(language.classNameAliases || {});
  1319. return compileMode(/** @type Mode */ (language));
  1320. }
  1321. /**
  1322. * Determines if a mode has a dependency on it's parent or not
  1323. *
  1324. * If a mode does have a parent dependency then often we need to clone it if
  1325. * it's used in multiple places so that each copy points to the correct parent,
  1326. * where-as modes without a parent can often safely be re-used at the bottom of
  1327. * a mode chain.
  1328. *
  1329. * @param {Mode | null} mode
  1330. * @returns {boolean} - is there a dependency on the parent?
  1331. * */
  1332. function dependencyOnParent(mode) {
  1333. if (!mode) return false;
  1334. return mode.endsWithParent || dependencyOnParent(mode.starts);
  1335. }
  1336. /**
  1337. * Expands a mode or clones it if necessary
  1338. *
  1339. * This is necessary for modes with parental dependenceis (see notes on
  1340. * `dependencyOnParent`) and for nodes that have `variants` - which must then be
  1341. * exploded into their own individual modes at compile time.
  1342. *
  1343. * @param {Mode} mode
  1344. * @returns {Mode | Mode[]}
  1345. * */
  1346. function expandOrCloneMode(mode) {
  1347. if (mode.variants && !mode.cachedVariants) {
  1348. mode.cachedVariants = mode.variants.map(function(variant) {
  1349. return inherit$1(mode, { variants: null }, variant);
  1350. });
  1351. }
  1352. // EXPAND
  1353. // if we have variants then essentially "replace" the mode with the variants
  1354. // this happens in compileMode, where this function is called from
  1355. if (mode.cachedVariants) {
  1356. return mode.cachedVariants;
  1357. }
  1358. // CLONE
  1359. // if we have dependencies on parents then we need a unique
  1360. // instance of ourselves, so we can be reused with many
  1361. // different parents without issue
  1362. if (dependencyOnParent(mode)) {
  1363. return inherit$1(mode, { starts: mode.starts ? inherit$1(mode.starts) : null });
  1364. }
  1365. if (Object.isFrozen(mode)) {
  1366. return inherit$1(mode);
  1367. }
  1368. // no special dependency issues, just return ourselves
  1369. return mode;
  1370. }
  1371. var version = "11.7.0";
  1372. class HTMLInjectionError extends Error {
  1373. constructor(reason, html) {
  1374. super(reason);
  1375. this.name = "HTMLInjectionError";
  1376. this.html = html;
  1377. }
  1378. }
  1379. /*
  1380. Syntax highlighting with language autodetection.
  1381. https://highlightjs.org/
  1382. */
  1383. /**
  1384. @typedef {import('highlight.js').Mode} Mode
  1385. @typedef {import('highlight.js').CompiledMode} CompiledMode
  1386. @typedef {import('highlight.js').CompiledScope} CompiledScope
  1387. @typedef {import('highlight.js').Language} Language
  1388. @typedef {import('highlight.js').HLJSApi} HLJSApi
  1389. @typedef {import('highlight.js').HLJSPlugin} HLJSPlugin
  1390. @typedef {import('highlight.js').PluginEvent} PluginEvent
  1391. @typedef {import('highlight.js').HLJSOptions} HLJSOptions
  1392. @typedef {import('highlight.js').LanguageFn} LanguageFn
  1393. @typedef {import('highlight.js').HighlightedHTMLElement} HighlightedHTMLElement
  1394. @typedef {import('highlight.js').BeforeHighlightContext} BeforeHighlightContext
  1395. @typedef {import('highlight.js/private').MatchType} MatchType
  1396. @typedef {import('highlight.js/private').KeywordData} KeywordData
  1397. @typedef {import('highlight.js/private').EnhancedMatch} EnhancedMatch
  1398. @typedef {import('highlight.js/private').AnnotatedError} AnnotatedError
  1399. @typedef {import('highlight.js').AutoHighlightResult} AutoHighlightResult
  1400. @typedef {import('highlight.js').HighlightOptions} HighlightOptions
  1401. @typedef {import('highlight.js').HighlightResult} HighlightResult
  1402. */
  1403. const escape = escapeHTML;
  1404. const inherit = inherit$1;
  1405. const NO_MATCH = Symbol("nomatch");
  1406. const MAX_KEYWORD_HITS = 7;
  1407. /**
  1408. * @param {any} hljs - object that is extended (legacy)
  1409. * @returns {HLJSApi}
  1410. */
  1411. const HLJS = function(hljs) {
  1412. // Global internal variables used within the highlight.js library.
  1413. /** @type {Record<string, Language>} */
  1414. const languages = Object.create(null);
  1415. /** @type {Record<string, string>} */
  1416. const aliases = Object.create(null);
  1417. /** @type {HLJSPlugin[]} */
  1418. const plugins = [];
  1419. // safe/production mode - swallows more errors, tries to keep running
  1420. // even if a single syntax or parse hits a fatal error
  1421. let SAFE_MODE = true;
  1422. const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
  1423. /** @type {Language} */
  1424. const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };
  1425. // Global options used when within external APIs. This is modified when
  1426. // calling the `hljs.configure` function.
  1427. /** @type HLJSOptions */
  1428. let options = {
  1429. ignoreUnescapedHTML: false,
  1430. throwUnescapedHTML: false,
  1431. noHighlightRe: /^(no-?highlight)$/i,
  1432. languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
  1433. classPrefix: 'hljs-',
  1434. cssSelector: 'pre code',
  1435. languages: null,
  1436. // beta configuration options, subject to change, welcome to discuss
  1437. // https://github.com/highlightjs/highlight.js/issues/1086
  1438. __emitter: TokenTreeEmitter
  1439. };
  1440. /* Utility functions */
  1441. /**
  1442. * Tests a language name to see if highlighting should be skipped
  1443. * @param {string} languageName
  1444. */
  1445. function shouldNotHighlight(languageName) {
  1446. return options.noHighlightRe.test(languageName);
  1447. }
  1448. /**
  1449. * @param {HighlightedHTMLElement} block - the HTML element to determine language for
  1450. */
  1451. function blockLanguage(block) {
  1452. let classes = block.className + ' ';
  1453. classes += block.parentNode ? block.parentNode.className : '';
  1454. // language-* takes precedence over non-prefixed class names.
  1455. const match = options.languageDetectRe.exec(classes);
  1456. if (match) {
  1457. const language = getLanguage(match[1]);
  1458. if (!language) {
  1459. warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
  1460. warn("Falling back to no-highlight mode for this block.", block);
  1461. }
  1462. return language ? match[1] : 'no-highlight';
  1463. }
  1464. return classes
  1465. .split(/\s+/)
  1466. .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
  1467. }
  1468. /**
  1469. * Core highlighting function.
  1470. *
  1471. * OLD API
  1472. * highlight(lang, code, ignoreIllegals, continuation)
  1473. *
  1474. * NEW API
  1475. * highlight(code, {lang, ignoreIllegals})
  1476. *
  1477. * @param {string} codeOrLanguageName - the language to use for highlighting
  1478. * @param {string | HighlightOptions} optionsOrCode - the code to highlight
  1479. * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
  1480. *
  1481. * @returns {HighlightResult} Result - an object that represents the result
  1482. * @property {string} language - the language name
  1483. * @property {number} relevance - the relevance score
  1484. * @property {string} value - the highlighted HTML code
  1485. * @property {string} code - the original raw code
  1486. * @property {CompiledMode} top - top of the current mode stack
  1487. * @property {boolean} illegal - indicates whether any illegal matches were found
  1488. */
  1489. function highlight(codeOrLanguageName, optionsOrCode, ignoreIllegals) {
  1490. let code = "";
  1491. let languageName = "";
  1492. if (typeof optionsOrCode === "object") {
  1493. code = codeOrLanguageName;
  1494. ignoreIllegals = optionsOrCode.ignoreIllegals;
  1495. languageName = optionsOrCode.language;
  1496. } else {
  1497. // old API
  1498. deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
  1499. deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
  1500. languageName = codeOrLanguageName;
  1501. code = optionsOrCode;
  1502. }
  1503. // https://github.com/highlightjs/highlight.js/issues/3149
  1504. // eslint-disable-next-line no-undefined
  1505. if (ignoreIllegals === undefined) { ignoreIllegals = true; }
  1506. /** @type {BeforeHighlightContext} */
  1507. const context = {
  1508. code,
  1509. language: languageName
  1510. };
  1511. // the plugin can change the desired language or the code to be highlighted
  1512. // just be changing the object it was passed
  1513. fire("before:highlight", context);
  1514. // a before plugin can usurp the result completely by providing it's own
  1515. // in which case we don't even need to call highlight
  1516. const result = context.result
  1517. ? context.result
  1518. : _highlight(context.language, context.code, ignoreIllegals);
  1519. result.code = context.code;
  1520. // the plugin can change anything in result to suite it
  1521. fire("after:highlight", result);
  1522. return result;
  1523. }
  1524. /**
  1525. * private highlight that's used internally and does not fire callbacks
  1526. *
  1527. * @param {string} languageName - the language to use for highlighting
  1528. * @param {string} codeToHighlight - the code to highlight
  1529. * @param {boolean?} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
  1530. * @param {CompiledMode?} [continuation] - current continuation mode, if any
  1531. * @returns {HighlightResult} - result of the highlight operation
  1532. */
  1533. function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
  1534. const keywordHits = Object.create(null);
  1535. /**
  1536. * Return keyword data if a match is a keyword
  1537. * @param {CompiledMode} mode - current mode
  1538. * @param {string} matchText - the textual match
  1539. * @returns {KeywordData | false}
  1540. */
  1541. function keywordData(mode, matchText) {
  1542. return mode.keywords[matchText];
  1543. }
  1544. function processKeywords() {
  1545. if (!top.keywords) {
  1546. emitter.addText(modeBuffer);
  1547. return;
  1548. }
  1549. let lastIndex = 0;
  1550. top.keywordPatternRe.lastIndex = 0;
  1551. let match = top.keywordPatternRe.exec(modeBuffer);
  1552. let buf = "";
  1553. while (match) {
  1554. buf += modeBuffer.substring(lastIndex, match.index);
  1555. const word = language.case_insensitive ? match[0].toLowerCase() : match[0];
  1556. const data = keywordData(top, word);
  1557. if (data) {
  1558. const [kind, keywordRelevance] = data;
  1559. emitter.addText(buf);
  1560. buf = "";
  1561. keywordHits[word] = (keywordHits[word] || 0) + 1;
  1562. if (keywordHits[word] <= MAX_KEYWORD_HITS) relevance += keywordRelevance;
  1563. if (kind.startsWith("_")) {
  1564. // _ implied for relevance only, do not highlight
  1565. // by applying a class name
  1566. buf += match[0];
  1567. } else {
  1568. const cssClass = language.classNameAliases[kind] || kind;
  1569. emitter.addKeyword(match[0], cssClass);
  1570. }
  1571. } else {
  1572. buf += match[0];
  1573. }
  1574. lastIndex = top.keywordPatternRe.lastIndex;
  1575. match = top.keywordPatternRe.exec(modeBuffer);
  1576. }
  1577. buf += modeBuffer.substring(lastIndex);
  1578. emitter.addText(buf);
  1579. }
  1580. function processSubLanguage() {
  1581. if (modeBuffer === "") return;
  1582. /** @type HighlightResult */
  1583. let result = null;
  1584. if (typeof top.subLanguage === 'string') {
  1585. if (!languages[top.subLanguage]) {
  1586. emitter.addText(modeBuffer);
  1587. return;
  1588. }
  1589. result = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
  1590. continuations[top.subLanguage] = /** @type {CompiledMode} */ (result._top);
  1591. } else {
  1592. result = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
  1593. }
  1594. // Counting embedded language score towards the host language may be disabled
  1595. // with zeroing the containing mode relevance. Use case in point is Markdown that
  1596. // allows XML everywhere and makes every XML snippet to have a much larger Markdown
  1597. // score.
  1598. if (top.relevance > 0) {
  1599. relevance += result.relevance;
  1600. }
  1601. emitter.addSublanguage(result._emitter, result.language);
  1602. }
  1603. function processBuffer() {
  1604. if (top.subLanguage != null) {
  1605. processSubLanguage();
  1606. } else {
  1607. processKeywords();
  1608. }
  1609. modeBuffer = '';
  1610. }
  1611. /**
  1612. * @param {CompiledScope} scope
  1613. * @param {RegExpMatchArray} match
  1614. */
  1615. function emitMultiClass(scope, match) {
  1616. let i = 1;
  1617. const max = match.length - 1;
  1618. while (i <= max) {
  1619. if (!scope._emit[i]) { i++; continue; }
  1620. const klass = language.classNameAliases[scope[i]] || scope[i];
  1621. const text = match[i];
  1622. if (klass) {
  1623. emitter.addKeyword(text, klass);
  1624. } else {
  1625. modeBuffer = text;
  1626. processKeywords();
  1627. modeBuffer = "";
  1628. }
  1629. i++;
  1630. }
  1631. }
  1632. /**
  1633. * @param {CompiledMode} mode - new mode to start
  1634. * @param {RegExpMatchArray} match
  1635. */
  1636. function startNewMode(mode, match) {
  1637. if (mode.scope && typeof mode.scope === "string") {
  1638. emitter.openNode(language.classNameAliases[mode.scope] || mode.scope);
  1639. }
  1640. if (mode.beginScope) {
  1641. // beginScope just wraps the begin match itself in a scope
  1642. if (mode.beginScope._wrap) {
  1643. emitter.addKeyword(modeBuffer, language.classNameAliases[mode.beginScope._wrap] || mode.beginScope._wrap);
  1644. modeBuffer = "";
  1645. } else if (mode.beginScope._multi) {
  1646. // at this point modeBuffer should just be the match
  1647. emitMultiClass(mode.beginScope, match);
  1648. modeBuffer = "";
  1649. }
  1650. }
  1651. top = Object.create(mode, { parent: { value: top } });
  1652. return top;
  1653. }
  1654. /**
  1655. * @param {CompiledMode } mode - the mode to potentially end
  1656. * @param {RegExpMatchArray} match - the latest match
  1657. * @param {string} matchPlusRemainder - match plus remainder of content
  1658. * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode
  1659. */
  1660. function endOfMode(mode, match, matchPlusRemainder) {
  1661. let matched = startsWith(mode.endRe, matchPlusRemainder);
  1662. if (matched) {
  1663. if (mode["on:end"]) {
  1664. const resp = new Response(mode);
  1665. mode["on:end"](match, resp);
  1666. if (resp.isMatchIgnored) matched = false;
  1667. }
  1668. if (matched) {
  1669. while (mode.endsParent && mode.parent) {
  1670. mode = mode.parent;
  1671. }
  1672. return mode;
  1673. }
  1674. }
  1675. // even if on:end fires an `ignore` it's still possible
  1676. // that we might trigger the end node because of a parent mode
  1677. if (mode.endsWithParent) {
  1678. return endOfMode(mode.parent, match, matchPlusRemainder);
  1679. }
  1680. }
  1681. /**
  1682. * Handle matching but then ignoring a sequence of text
  1683. *
  1684. * @param {string} lexeme - string containing full match text
  1685. */
  1686. function doIgnore(lexeme) {
  1687. if (top.matcher.regexIndex === 0) {
  1688. // no more regexes to potentially match here, so we move the cursor forward one
  1689. // space
  1690. modeBuffer += lexeme[0];
  1691. return 1;
  1692. } else {
  1693. // no need to move the cursor, we still have additional regexes to try and
  1694. // match at this very spot
  1695. resumeScanAtSamePosition = true;
  1696. return 0;
  1697. }
  1698. }
  1699. /**
  1700. * Handle the start of a new potential mode match
  1701. *
  1702. * @param {EnhancedMatch} match - the current match
  1703. * @returns {number} how far to advance the parse cursor
  1704. */
  1705. function doBeginMatch(match) {
  1706. const lexeme = match[0];
  1707. const newMode = match.rule;
  1708. const resp = new Response(newMode);
  1709. // first internal before callbacks, then the public ones
  1710. const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
  1711. for (const cb of beforeCallbacks) {
  1712. if (!cb) continue;
  1713. cb(match, resp);
  1714. if (resp.isMatchIgnored) return doIgnore(lexeme);
  1715. }
  1716. if (newMode.skip) {
  1717. modeBuffer += lexeme;
  1718. } else {
  1719. if (newMode.excludeBegin) {
  1720. modeBuffer += lexeme;
  1721. }
  1722. processBuffer();
  1723. if (!newMode.returnBegin && !newMode.excludeBegin) {
  1724. modeBuffer = lexeme;
  1725. }
  1726. }
  1727. startNewMode(newMode, match);
  1728. return newMode.returnBegin ? 0 : lexeme.length;
  1729. }
  1730. /**
  1731. * Handle the potential end of mode
  1732. *
  1733. * @param {RegExpMatchArray} match - the current match
  1734. */
  1735. function doEndMatch(match) {
  1736. const lexeme = match[0];
  1737. const matchPlusRemainder = codeToHighlight.substring(match.index);
  1738. const endMode = endOfMode(top, match, matchPlusRemainder);
  1739. if (!endMode) { return NO_MATCH; }
  1740. const origin = top;
  1741. if (top.endScope && top.endScope._wrap) {
  1742. processBuffer();
  1743. emitter.addKeyword(lexeme, top.endScope._wrap);
  1744. } else if (top.endScope && top.endScope._multi) {
  1745. processBuffer();
  1746. emitMultiClass(top.endScope, match);
  1747. } else if (origin.skip) {
  1748. modeBuffer += lexeme;
  1749. } else {
  1750. if (!(origin.returnEnd || origin.excludeEnd)) {
  1751. modeBuffer += lexeme;
  1752. }
  1753. processBuffer();
  1754. if (origin.excludeEnd) {
  1755. modeBuffer = lexeme;
  1756. }
  1757. }
  1758. do {
  1759. if (top.scope) {
  1760. emitter.closeNode();
  1761. }
  1762. if (!top.skip && !top.subLanguage) {
  1763. relevance += top.relevance;
  1764. }
  1765. top = top.parent;
  1766. } while (top !== endMode.parent);
  1767. if (endMode.starts) {
  1768. startNewMode(endMode.starts, match);
  1769. }
  1770. return origin.returnEnd ? 0 : lexeme.length;
  1771. }
  1772. function processContinuations() {
  1773. const list = [];
  1774. for (let current = top; current !== language; current = current.parent) {
  1775. if (current.scope) {
  1776. list.unshift(current.scope);
  1777. }
  1778. }
  1779. list.forEach(item => emitter.openNode(item));
  1780. }
  1781. /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */
  1782. let lastMatch = {};
  1783. /**
  1784. * Process an individual match
  1785. *
  1786. * @param {string} textBeforeMatch - text preceding the match (since the last match)
  1787. * @param {EnhancedMatch} [match] - the match itself
  1788. */
  1789. function processLexeme(textBeforeMatch, match) {
  1790. const lexeme = match && match[0];
  1791. // add non-matched text to the current mode buffer
  1792. modeBuffer += textBeforeMatch;
  1793. if (lexeme == null) {
  1794. processBuffer();
  1795. return 0;
  1796. }
  1797. // we've found a 0 width match and we're stuck, so we need to advance
  1798. // this happens when we have badly behaved rules that have optional matchers to the degree that
  1799. // sometimes they can end up matching nothing at all
  1800. // Ref: https://github.com/highlightjs/highlight.js/issues/2140
  1801. if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
  1802. // spit the "skipped" character that our regex choked on back into the output sequence
  1803. modeBuffer += codeToHighlight.slice(match.index, match.index + 1);
  1804. if (!SAFE_MODE) {
  1805. /** @type {AnnotatedError} */
  1806. const err = new Error(`0 width match regex (${languageName})`);
  1807. err.languageName = languageName;
  1808. err.badRule = lastMatch.rule;
  1809. throw err;
  1810. }
  1811. return 1;
  1812. }
  1813. lastMatch = match;
  1814. if (match.type === "begin") {
  1815. return doBeginMatch(match);
  1816. } else if (match.type === "illegal" && !ignoreIllegals) {
  1817. // illegal match, we do not continue processing
  1818. /** @type {AnnotatedError} */
  1819. const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.scope || '<unnamed>') + '"');
  1820. err.mode = top;
  1821. throw err;
  1822. } else if (match.type === "end") {
  1823. const processed = doEndMatch(match);
  1824. if (processed !== NO_MATCH) {
  1825. return processed;
  1826. }
  1827. }
  1828. // edge case for when illegal matches $ (end of line) which is technically
  1829. // a 0 width match but not a begin/end match so it's not caught by the
  1830. // first handler (when ignoreIllegals is true)
  1831. if (match.type === "illegal" && lexeme === "") {
  1832. // advance so we aren't stuck in an infinite loop
  1833. return 1;
  1834. }
  1835. // infinite loops are BAD, this is a last ditch catch all. if we have a
  1836. // decent number of iterations yet our index (cursor position in our
  1837. // parsing) still 3x behind our index then something is very wrong
  1838. // so we bail
  1839. if (iterations > 100000 && iterations > match.index * 3) {
  1840. const err = new Error('potential infinite loop, way more iterations than matches');
  1841. throw err;
  1842. }
  1843. /*
  1844. Why might be find ourselves here? An potential end match that was
  1845. triggered but could not be completed. IE, `doEndMatch` returned NO_MATCH.
  1846. (this could be because a callback requests the match be ignored, etc)
  1847. This causes no real harm other than stopping a few times too many.
  1848. */
  1849. modeBuffer += lexeme;
  1850. return lexeme.length;
  1851. }
  1852. const language = getLanguage(languageName);
  1853. if (!language) {
  1854. error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
  1855. throw new Error('Unknown language: "' + languageName + '"');
  1856. }
  1857. const md = compileLanguage(language);
  1858. let result = '';
  1859. /** @type {CompiledMode} */
  1860. let top = continuation || md;
  1861. /** @type Record<string,CompiledMode> */
  1862. const continuations = {}; // keep continuations for sub-languages
  1863. const emitter = new options.__emitter(options);
  1864. processContinuations();
  1865. let modeBuffer = '';
  1866. let relevance = 0;
  1867. let index = 0;
  1868. let iterations = 0;
  1869. let resumeScanAtSamePosition = false;
  1870. try {
  1871. top.matcher.considerAll();
  1872. for (;;) {
  1873. iterations++;
  1874. if (resumeScanAtSamePosition) {
  1875. // only regexes not matched previously will now be
  1876. // considered for a potential match
  1877. resumeScanAtSamePosition = false;
  1878. } else {
  1879. top.matcher.considerAll();
  1880. }
  1881. top.matcher.lastIndex = index;
  1882. const match = top.matcher.exec(codeToHighlight);
  1883. // console.log("match", match[0], match.rule && match.rule.begin)
  1884. if (!match) break;
  1885. const beforeMatch = codeToHighlight.substring(index, match.index);
  1886. const processedCount = processLexeme(beforeMatch, match);
  1887. index = match.index + processedCount;
  1888. }
  1889. processLexeme(codeToHighlight.substring(index));
  1890. emitter.closeAllNodes();
  1891. emitter.finalize();
  1892. result = emitter.toHTML();
  1893. return {
  1894. language: languageName,
  1895. value: result,
  1896. relevance: relevance,
  1897. illegal: false,
  1898. _emitter: emitter,
  1899. _top: top
  1900. };
  1901. } catch (err) {
  1902. if (err.message && err.message.includes('Illegal')) {
  1903. return {
  1904. language: languageName,
  1905. value: escape(codeToHighlight),
  1906. illegal: true,
  1907. relevance: 0,
  1908. _illegalBy: {
  1909. message: err.message,
  1910. index: index,
  1911. context: codeToHighlight.slice(index - 100, index + 100),
  1912. mode: err.mode,
  1913. resultSoFar: result
  1914. },
  1915. _emitter: emitter
  1916. };
  1917. } else if (SAFE_MODE) {
  1918. return {
  1919. language: languageName,
  1920. value: escape(codeToHighlight),
  1921. illegal: false,
  1922. relevance: 0,
  1923. errorRaised: err,
  1924. _emitter: emitter,
  1925. _top: top
  1926. };
  1927. } else {
  1928. throw err;
  1929. }
  1930. }
  1931. }
  1932. /**
  1933. * returns a valid highlight result, without actually doing any actual work,
  1934. * auto highlight starts with this and it's possible for small snippets that
  1935. * auto-detection may not find a better match
  1936. * @param {string} code
  1937. * @returns {HighlightResult}
  1938. */
  1939. function justTextHighlightResult(code) {
  1940. const result = {
  1941. value: escape(code),
  1942. illegal: false,
  1943. relevance: 0,
  1944. _top: PLAINTEXT_LANGUAGE,
  1945. _emitter: new options.__emitter(options)
  1946. };
  1947. result._emitter.addText(code);
  1948. return result;
  1949. }
  1950. /**
  1951. Highlighting with language detection. Accepts a string with the code to
  1952. highlight. Returns an object with the following properties:
  1953. - language (detected language)
  1954. - relevance (int)
  1955. - value (an HTML string with highlighting markup)
  1956. - secondBest (object with the same structure for second-best heuristically
  1957. detected language, may be absent)
  1958. @param {string} code
  1959. @param {Array<string>} [languageSubset]
  1960. @returns {AutoHighlightResult}
  1961. */
  1962. function highlightAuto(code, languageSubset) {
  1963. languageSubset = languageSubset || options.languages || Object.keys(languages);
  1964. const plaintext = justTextHighlightResult(code);
  1965. const results = languageSubset.filter(getLanguage).filter(autoDetection).map(name =>
  1966. _highlight(name, code, false)
  1967. );
  1968. results.unshift(plaintext); // plaintext is always an option
  1969. const sorted = results.sort((a, b) => {
  1970. // sort base on relevance
  1971. if (a.relevance !== b.relevance) return b.relevance - a.relevance;
  1972. // always award the tie to the base language
  1973. // ie if C++ and Arduino are tied, it's more likely to be C++
  1974. if (a.language && b.language) {
  1975. if (getLanguage(a.language).supersetOf === b.language) {
  1976. return 1;
  1977. } else if (getLanguage(b.language).supersetOf === a.language) {
  1978. return -1;
  1979. }
  1980. }
  1981. // otherwise say they are equal, which has the effect of sorting on
  1982. // relevance while preserving the original ordering - which is how ties
  1983. // have historically been settled, ie the language that comes first always
  1984. // wins in the case of a tie
  1985. return 0;
  1986. });
  1987. const [best, secondBest] = sorted;
  1988. /** @type {AutoHighlightResult} */
  1989. const result = best;
  1990. result.secondBest = secondBest;
  1991. return result;
  1992. }
  1993. /**
  1994. * Builds new class name for block given the language name
  1995. *
  1996. * @param {HTMLElement} element
  1997. * @param {string} [currentLang]
  1998. * @param {string} [resultLang]
  1999. */
  2000. function updateClassName(element, currentLang, resultLang) {
  2001. const language = (currentLang && aliases[currentLang]) || resultLang;
  2002. element.classList.add("hljs");
  2003. element.classList.add(`language-${language}`);
  2004. }
  2005. /**
  2006. * Applies highlighting to a DOM node containing code.
  2007. *
  2008. * @param {HighlightedHTMLElement} element - the HTML element to highlight
  2009. */
  2010. function highlightElement(element) {
  2011. /** @type HTMLElement */
  2012. let node = null;
  2013. const language = blockLanguage(element);
  2014. if (shouldNotHighlight(language)) return;
  2015. fire("before:highlightElement",
  2016. { el: element, language: language });
  2017. // we should be all text, no child nodes (unescaped HTML) - this is possibly
  2018. // an HTML injection attack - it's likely too late if this is already in
  2019. // production (the code has likely already done its damage by the time
  2020. // we're seeing it)... but we yell loudly about this so that hopefully it's
  2021. // more likely to be caught in development before making it to production
  2022. if (element.children.length > 0) {
  2023. if (!options.ignoreUnescapedHTML) {
  2024. console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk.");
  2025. console.warn("https://github.com/highlightjs/highlight.js/wiki/security");
  2026. console.warn("The element with unescaped HTML:");
  2027. console.warn(element);
  2028. }
  2029. if (options.throwUnescapedHTML) {
  2030. const err = new HTMLInjectionError(
  2031. "One of your code blocks includes unescaped HTML.",
  2032. element.innerHTML
  2033. );
  2034. throw err;
  2035. }
  2036. }
  2037. node = element;
  2038. const text = node.textContent;
  2039. const result = language ? highlight(text, { language, ignoreIllegals: true }) : highlightAuto(text);
  2040. element.innerHTML = result.value;
  2041. updateClassName(element, language, result.language);
  2042. element.result = {
  2043. language: result.language,
  2044. // TODO: remove with version 11.0
  2045. re: result.relevance,
  2046. relevance: result.relevance
  2047. };
  2048. if (result.secondBest) {
  2049. element.secondBest = {
  2050. language: result.secondBest.language,
  2051. relevance: result.secondBest.relevance
  2052. };
  2053. }
  2054. fire("after:highlightElement", { el: element, result, text });
  2055. }
  2056. /**
  2057. * Updates highlight.js global options with the passed options
  2058. *
  2059. * @param {Partial<HLJSOptions>} userOptions
  2060. */
  2061. function configure(userOptions) {
  2062. options = inherit(options, userOptions);
  2063. }
  2064. // TODO: remove v12, deprecated
  2065. const initHighlighting = () => {
  2066. highlightAll();
  2067. deprecated("10.6.0", "initHighlighting() deprecated. Use highlightAll() now.");
  2068. };
  2069. // TODO: remove v12, deprecated
  2070. function initHighlightingOnLoad() {
  2071. highlightAll();
  2072. deprecated("10.6.0", "initHighlightingOnLoad() deprecated. Use highlightAll() now.");
  2073. }
  2074. let wantsHighlight = false;
  2075. /**
  2076. * auto-highlights all pre>code elements on the page
  2077. */
  2078. function highlightAll() {
  2079. // if we are called too early in the loading process
  2080. if (document.readyState === "loading") {
  2081. wantsHighlight = true;
  2082. return;
  2083. }
  2084. const blocks = document.querySelectorAll(options.cssSelector);
  2085. blocks.forEach(highlightElement);
  2086. }
  2087. function boot() {
  2088. // if a highlight was requested before DOM was loaded, do now
  2089. if (wantsHighlight) highlightAll();
  2090. }
  2091. // make sure we are in the browser environment
  2092. if (typeof window !== 'undefined' && window.addEventListener) {
  2093. window.addEventListener('DOMContentLoaded', boot, false);
  2094. }
  2095. /**
  2096. * Register a language grammar module
  2097. *
  2098. * @param {string} languageName
  2099. * @param {LanguageFn} languageDefinition
  2100. */
  2101. function registerLanguage(languageName, languageDefinition) {
  2102. let lang = null;
  2103. try {
  2104. lang = languageDefinition(hljs);
  2105. } catch (error$1) {
  2106. error("Language definition for '{}' could not be registered.".replace("{}", languageName));
  2107. // hard or soft error
  2108. if (!SAFE_MODE) { throw error$1; } else { error(error$1); }
  2109. // languages that have serious errors are replaced with essentially a
  2110. // "plaintext" stand-in so that the code blocks will still get normal
  2111. // css classes applied to them - and one bad language won't break the
  2112. // entire highlighter
  2113. lang = PLAINTEXT_LANGUAGE;
  2114. }
  2115. // give it a temporary name if it doesn't have one in the meta-data
  2116. if (!lang.name) lang.name = languageName;
  2117. languages[languageName] = lang;
  2118. lang.rawDefinition = languageDefinition.bind(null, hljs);
  2119. if (lang.aliases) {
  2120. registerAliases(lang.aliases, { languageName });
  2121. }
  2122. }
  2123. /**
  2124. * Remove a language grammar module
  2125. *
  2126. * @param {string} languageName
  2127. */
  2128. function unregisterLanguage(languageName) {
  2129. delete languages[languageName];
  2130. for (const alias of Object.keys(aliases)) {
  2131. if (aliases[alias] === languageName) {
  2132. delete aliases[alias];
  2133. }
  2134. }
  2135. }
  2136. /**
  2137. * @returns {string[]} List of language internal names
  2138. */
  2139. function listLanguages() {
  2140. return Object.keys(languages);
  2141. }
  2142. /**
  2143. * @param {string} name - name of the language to retrieve
  2144. * @returns {Language | undefined}
  2145. */
  2146. function getLanguage(name) {
  2147. name = (name || '').toLowerCase();
  2148. return languages[name] || languages[aliases[name]];
  2149. }
  2150. /**
  2151. *
  2152. * @param {string|string[]} aliasList - single alias or list of aliases
  2153. * @param {{languageName: string}} opts
  2154. */
  2155. function registerAliases(aliasList, { languageName }) {
  2156. if (typeof aliasList === 'string') {
  2157. aliasList = [aliasList];
  2158. }
  2159. aliasList.forEach(alias => { aliases[alias.toLowerCase()] = languageName; });
  2160. }
  2161. /**
  2162. * Determines if a given language has auto-detection enabled
  2163. * @param {string} name - name of the language
  2164. */
  2165. function autoDetection(name) {
  2166. const lang = getLanguage(name);
  2167. return lang && !lang.disableAutodetect;
  2168. }
  2169. /**
  2170. * Upgrades the old highlightBlock plugins to the new
  2171. * highlightElement API
  2172. * @param {HLJSPlugin} plugin
  2173. */
  2174. function upgradePluginAPI(plugin) {
  2175. // TODO: remove with v12
  2176. if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
  2177. plugin["before:highlightElement"] = (data) => {
  2178. plugin["before:highlightBlock"](
  2179. Object.assign({ block: data.el }, data)
  2180. );
  2181. };
  2182. }
  2183. if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
  2184. plugin["after:highlightElement"] = (data) => {
  2185. plugin["after:highlightBlock"](
  2186. Object.assign({ block: data.el }, data)
  2187. );
  2188. };
  2189. }
  2190. }
  2191. /**
  2192. * @param {HLJSPlugin} plugin
  2193. */
  2194. function addPlugin(plugin) {
  2195. upgradePluginAPI(plugin);
  2196. plugins.push(plugin);
  2197. }
  2198. /**
  2199. *
  2200. * @param {PluginEvent} event
  2201. * @param {any} args
  2202. */
  2203. function fire(event, args) {
  2204. const cb = event;
  2205. plugins.forEach(function(plugin) {
  2206. if (plugin[cb]) {
  2207. plugin[cb](args);
  2208. }
  2209. });
  2210. }
  2211. /**
  2212. * DEPRECATED
  2213. * @param {HighlightedHTMLElement} el
  2214. */
  2215. function deprecateHighlightBlock(el) {
  2216. deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
  2217. deprecated("10.7.0", "Please use highlightElement now.");
  2218. return highlightElement(el);
  2219. }
  2220. /* Interface definition */
  2221. Object.assign(hljs, {
  2222. highlight,
  2223. highlightAuto,
  2224. highlightAll,
  2225. highlightElement,
  2226. // TODO: Remove with v12 API
  2227. highlightBlock: deprecateHighlightBlock,
  2228. configure,
  2229. initHighlighting,
  2230. initHighlightingOnLoad,
  2231. registerLanguage,
  2232. unregisterLanguage,
  2233. listLanguages,
  2234. getLanguage,
  2235. registerAliases,
  2236. autoDetection,
  2237. inherit,
  2238. addPlugin
  2239. });
  2240. hljs.debugMode = function() { SAFE_MODE = false; };
  2241. hljs.safeMode = function() { SAFE_MODE = true; };
  2242. hljs.versionString = version;
  2243. hljs.regex = {
  2244. concat: concat,
  2245. lookahead: lookahead,
  2246. either: either,
  2247. optional: optional,
  2248. anyNumberOfTimes: anyNumberOfTimes
  2249. };
  2250. for (const key in MODES) {
  2251. // @ts-ignore
  2252. if (typeof MODES[key] === "object") {
  2253. // @ts-ignore
  2254. deepFreezeEs6.exports(MODES[key]);
  2255. }
  2256. }
  2257. // merge all the modes/regexes into our main object
  2258. Object.assign(hljs, MODES);
  2259. return hljs;
  2260. };
  2261. // export an "instance" of the highlighter
  2262. var highlight = HLJS({});
  2263. return highlight;
  2264. })();
  2265. if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = hljs; }