core.js 74 KB

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