core.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080
  1. // https://github.com/substack/deep-freeze/blob/master/index.js
  2. /** @param {any} obj */
  3. function deepFreeze(obj) {
  4. Object.freeze(obj);
  5. var objIsFunction = typeof obj === 'function';
  6. Object.getOwnPropertyNames(obj).forEach(function(prop) {
  7. if (Object.hasOwnProperty.call(obj, prop)
  8. && obj[prop] !== null
  9. && (typeof obj[prop] === "object" || typeof obj[prop] === "function")
  10. // IE11 fix: https://github.com/highlightjs/highlight.js/issues/2318
  11. // TODO: remove in the future
  12. && (objIsFunction ? prop !== 'caller' && prop !== 'callee' && prop !== 'arguments' : true)
  13. && !Object.isFrozen(obj[prop])) {
  14. deepFreeze(obj[prop]);
  15. }
  16. });
  17. return obj;
  18. }
  19. class Response {
  20. /**
  21. * @param {CompiledMode} mode
  22. */
  23. constructor(mode) {
  24. // eslint-disable-next-line no-undefined
  25. if (mode.data === undefined) mode.data = {};
  26. this.data = mode.data;
  27. }
  28. ignoreMatch() {
  29. this.ignore = true;
  30. }
  31. }
  32. /**
  33. * @param {string} value
  34. * @returns {string}
  35. */
  36. function escapeHTML(value) {
  37. return value
  38. .replace(/&/g, '&')
  39. .replace(/</g, '&lt;')
  40. .replace(/>/g, '&gt;')
  41. .replace(/"/g, '&quot;')
  42. .replace(/'/g, '&#x27;');
  43. }
  44. /**
  45. * performs a shallow merge of multiple objects into one
  46. *
  47. * @template T
  48. * @param {T} original
  49. * @param {Record<string,any>[]} objects
  50. * @returns {T} a single new object
  51. */
  52. function inherit(original, ...objects) {
  53. /** @type Record<string,any> */
  54. var result = {};
  55. for (const key in original) {
  56. result[key] = original[key];
  57. }
  58. objects.forEach(function(obj) {
  59. for (const key in obj) {
  60. result[key] = obj[key];
  61. }
  62. });
  63. return /** @type {T} */ (result);
  64. }
  65. /* Stream merging */
  66. /**
  67. * @typedef Event
  68. * @property {'start'|'stop'} event
  69. * @property {number} offset
  70. * @property {Node} node
  71. */
  72. /**
  73. * @param {Node} node
  74. */
  75. function tag(node) {
  76. return node.nodeName.toLowerCase();
  77. }
  78. /**
  79. * @param {Node} node
  80. */
  81. function nodeStream(node) {
  82. /** @type Event[] */
  83. var result = [];
  84. (function _nodeStream(node, offset) {
  85. for (var child = node.firstChild; child; child = child.nextSibling) {
  86. if (child.nodeType === 3) {
  87. offset += child.nodeValue.length;
  88. } else if (child.nodeType === 1) {
  89. result.push({
  90. event: 'start',
  91. offset: offset,
  92. node: child
  93. });
  94. offset = _nodeStream(child, offset);
  95. // Prevent void elements from having an end tag that would actually
  96. // double them in the output. There are more void elements in HTML
  97. // but we list only those realistically expected in code display.
  98. if (!tag(child).match(/br|hr|img|input/)) {
  99. result.push({
  100. event: 'stop',
  101. offset: offset,
  102. node: child
  103. });
  104. }
  105. }
  106. }
  107. return offset;
  108. })(node, 0);
  109. return result;
  110. }
  111. /**
  112. * @param {any} original - the original stream
  113. * @param {any} highlighted - stream of the highlighted source
  114. * @param {string} value - the original source itself
  115. */
  116. function mergeStreams(original, highlighted, value) {
  117. var processed = 0;
  118. var result = '';
  119. var nodeStack = [];
  120. function selectStream() {
  121. if (!original.length || !highlighted.length) {
  122. return original.length ? original : highlighted;
  123. }
  124. if (original[0].offset !== highlighted[0].offset) {
  125. return (original[0].offset < highlighted[0].offset) ? original : highlighted;
  126. }
  127. /*
  128. To avoid starting the stream just before it should stop the order is
  129. ensured that original always starts first and closes last:
  130. if (event1 == 'start' && event2 == 'start')
  131. return original;
  132. if (event1 == 'start' && event2 == 'stop')
  133. return highlighted;
  134. if (event1 == 'stop' && event2 == 'start')
  135. return original;
  136. if (event1 == 'stop' && event2 == 'stop')
  137. return highlighted;
  138. ... which is collapsed to:
  139. */
  140. return highlighted[0].event === 'start' ? original : highlighted;
  141. }
  142. /**
  143. * @param {Node} node
  144. */
  145. function open(node) {
  146. /** @param {Attr} attr */
  147. function attr_str(attr) {
  148. return ' ' + attr.nodeName + '="' + escapeHTML(attr.value) + '"';
  149. }
  150. // @ts-ignore
  151. result += '<' + tag(node) + [].map.call(node.attributes, attr_str).join('') + '>';
  152. }
  153. /**
  154. * @param {Node} node
  155. */
  156. function close(node) {
  157. result += '</' + tag(node) + '>';
  158. }
  159. /**
  160. * @param {Event} event
  161. */
  162. function render(event) {
  163. (event.event === 'start' ? open : close)(event.node);
  164. }
  165. while (original.length || highlighted.length) {
  166. var stream = selectStream();
  167. result += escapeHTML(value.substring(processed, stream[0].offset));
  168. processed = stream[0].offset;
  169. if (stream === original) {
  170. /*
  171. On any opening or closing tag of the original markup we first close
  172. the entire highlighted node stack, then render the original tag along
  173. with all the following original tags at the same offset and then
  174. reopen all the tags on the highlighted stack.
  175. */
  176. nodeStack.reverse().forEach(close);
  177. do {
  178. render(stream.splice(0, 1)[0]);
  179. stream = selectStream();
  180. } while (stream === original && stream.length && stream[0].offset === processed);
  181. nodeStack.reverse().forEach(open);
  182. } else {
  183. if (stream[0].event === 'start') {
  184. nodeStack.push(stream[0].node);
  185. } else {
  186. nodeStack.pop();
  187. }
  188. render(stream.splice(0, 1)[0]);
  189. }
  190. }
  191. return result + escapeHTML(value.substr(processed));
  192. }
  193. var utils = /*#__PURE__*/Object.freeze({
  194. __proto__: null,
  195. escapeHTML: escapeHTML,
  196. inherit: inherit,
  197. nodeStream: nodeStream,
  198. mergeStreams: mergeStreams
  199. });
  200. /**
  201. * @typedef {object} Renderer
  202. * @property {(text: string) => void} addText
  203. * @property {(node: Node) => void} openNode
  204. * @property {(node: Node) => void} closeNode
  205. * @property {() => string} value
  206. */
  207. /** @typedef {{kind?: string, sublanguage?: boolean}} Node */
  208. /** @typedef {{walk: (r: Renderer) => void}} Tree */
  209. /** */
  210. const SPAN_CLOSE = '</span>';
  211. /**
  212. * Determines if a node needs to be wrapped in <span>
  213. *
  214. * @param {Node} node */
  215. const emitsWrappingTags = (node) => {
  216. return !!node.kind;
  217. };
  218. /** @type {Renderer} */
  219. class HTMLRenderer {
  220. /**
  221. * Creates a new HTMLRenderer
  222. *
  223. * @param {Tree} parseTree - the parse tree (must support `walk` API)
  224. * @param {{classPrefix: string}} options
  225. */
  226. constructor(parseTree, options) {
  227. this.buffer = "";
  228. this.classPrefix = options.classPrefix;
  229. parseTree.walk(this);
  230. }
  231. /**
  232. * Adds texts to the output stream
  233. *
  234. * @param {string} text */
  235. addText(text) {
  236. this.buffer += escapeHTML(text);
  237. }
  238. /**
  239. * Adds a node open to the output stream (if needed)
  240. *
  241. * @param {Node} node */
  242. openNode(node) {
  243. if (!emitsWrappingTags(node)) return;
  244. let className = node.kind;
  245. if (!node.sublanguage) {
  246. className = `${this.classPrefix}${className}`;
  247. }
  248. this.span(className);
  249. }
  250. /**
  251. * Adds a node close to the output stream (if needed)
  252. *
  253. * @param {Node} node */
  254. closeNode(node) {
  255. if (!emitsWrappingTags(node)) return;
  256. this.buffer += SPAN_CLOSE;
  257. }
  258. /**
  259. * returns the accumulated buffer
  260. */
  261. value() {
  262. return this.buffer;
  263. }
  264. // helpers
  265. /**
  266. * Builds a span element
  267. *
  268. * @param {string} className */
  269. span(className) {
  270. this.buffer += `<span class="${className}">`;
  271. }
  272. }
  273. /** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} | string} Node */
  274. /** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} } DataNode */
  275. /** */
  276. class TokenTree {
  277. constructor() {
  278. /** @type DataNode */
  279. this.rootNode = { children: [] };
  280. this.stack = [this.rootNode];
  281. }
  282. get top() {
  283. return this.stack[this.stack.length - 1];
  284. }
  285. get root() { return this.rootNode; }
  286. /** @param {Node} node */
  287. add(node) {
  288. this.top.children.push(node);
  289. }
  290. /** @param {string} kind */
  291. openNode(kind) {
  292. /** @type Node */
  293. const node = { kind, children: [] };
  294. this.add(node);
  295. this.stack.push(node);
  296. }
  297. closeNode() {
  298. if (this.stack.length > 1) {
  299. return this.stack.pop();
  300. }
  301. // eslint-disable-next-line no-undefined
  302. return undefined;
  303. }
  304. closeAllNodes() {
  305. while (this.closeNode());
  306. }
  307. toJSON() {
  308. return JSON.stringify(this.rootNode, null, 4);
  309. }
  310. /**
  311. * @typedef { import("./html_renderer").Renderer } Renderer
  312. * @param {Renderer} builder
  313. */
  314. walk(builder) {
  315. // this does not
  316. return this.constructor._walk(builder, this.rootNode);
  317. // this works
  318. // return TokenTree._walk(builder, this.rootNode);
  319. }
  320. /**
  321. * @param {Renderer} builder
  322. * @param {Node} node
  323. */
  324. static _walk(builder, node) {
  325. if (typeof node === "string") {
  326. builder.addText(node);
  327. } else if (node.children) {
  328. builder.openNode(node);
  329. node.children.forEach((child) => this._walk(builder, child));
  330. builder.closeNode(node);
  331. }
  332. return builder;
  333. }
  334. /**
  335. * @param {Node} node
  336. */
  337. static _collapse(node) {
  338. if (typeof node === "string") return;
  339. if (!node.children) return;
  340. if (node.children.every(el => typeof el === "string")) {
  341. // node.text = node.children.join("");
  342. // delete node.children;
  343. node.children = [node.children.join("")];
  344. } else {
  345. node.children.forEach((child) => {
  346. TokenTree._collapse(child);
  347. });
  348. }
  349. }
  350. }
  351. /**
  352. Currently this is all private API, but this is the minimal API necessary
  353. that an Emitter must implement to fully support the parser.
  354. Minimal interface:
  355. - addKeyword(text, kind)
  356. - addText(text)
  357. - addSublanguage(emitter, subLanguageName)
  358. - finalize()
  359. - openNode(kind)
  360. - closeNode()
  361. - closeAllNodes()
  362. - toHTML()
  363. */
  364. /**
  365. * @implements {Emitter}
  366. */
  367. class TokenTreeEmitter extends TokenTree {
  368. /**
  369. * @param {*} options
  370. */
  371. constructor(options) {
  372. super();
  373. this.options = options;
  374. }
  375. /**
  376. * @param {string} text
  377. * @param {string} kind
  378. */
  379. addKeyword(text, kind) {
  380. if (text === "") { return; }
  381. this.openNode(kind);
  382. this.addText(text);
  383. this.closeNode();
  384. }
  385. /**
  386. * @param {string} text
  387. */
  388. addText(text) {
  389. if (text === "") { return; }
  390. this.add(text);
  391. }
  392. /**
  393. * @param {Emitter & {root: DataNode}} emitter
  394. * @param {string} name
  395. */
  396. addSublanguage(emitter, name) {
  397. /** @type DataNode */
  398. const node = emitter.root;
  399. node.kind = name;
  400. node.sublanguage = true;
  401. this.add(node);
  402. }
  403. toHTML() {
  404. const renderer = new HTMLRenderer(this, this.options);
  405. return renderer.value();
  406. }
  407. finalize() {
  408. return true;
  409. }
  410. }
  411. /**
  412. * @param {string} value
  413. * @returns {RegExp}
  414. * */
  415. function escape(value) {
  416. return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm');
  417. }
  418. /**
  419. * @param {RegExp | string } re
  420. * @returns {string}
  421. */
  422. function source(re) {
  423. if (!re) return null;
  424. if (typeof re === "string") return re;
  425. return re.source;
  426. }
  427. /**
  428. * @param {...(RegExp | string) } args
  429. * @returns {string}
  430. */
  431. function concat(...args) {
  432. const joined = args.map((x) => source(x)).join("");
  433. return joined;
  434. }
  435. /**
  436. * @param {RegExp} re
  437. * @returns {number}
  438. */
  439. function countMatchGroups(re) {
  440. return (new RegExp(re.toString() + '|')).exec('').length - 1;
  441. }
  442. /**
  443. * Does lexeme start with a regular expression match at the beginning
  444. * @param {RegExp} re
  445. * @param {string} lexeme
  446. */
  447. function startsWith(re, lexeme) {
  448. var match = re && re.exec(lexeme);
  449. return match && match.index === 0;
  450. }
  451. // join logically computes regexps.join(separator), but fixes the
  452. // backreferences so they continue to match.
  453. // it also places each individual regular expression into it's own
  454. // match group, keeping track of the sequencing of those match groups
  455. // is currently an exercise for the caller. :-)
  456. /**
  457. * @param {(string | RegExp)[]} regexps
  458. * @param {string} separator
  459. * @returns {string}
  460. */
  461. function join(regexps, separator = "|") {
  462. // backreferenceRe matches an open parenthesis or backreference. To avoid
  463. // an incorrect parse, it additionally matches the following:
  464. // - [...] elements, where the meaning of parentheses and escapes change
  465. // - other escape sequences, so we do not misparse escape sequences as
  466. // interesting elements
  467. // - non-matching or lookahead parentheses, which do not capture. These
  468. // follow the '(' with a '?'.
  469. var backreferenceRe = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
  470. var numCaptures = 0;
  471. var ret = '';
  472. for (var i = 0; i < regexps.length; i++) {
  473. numCaptures += 1;
  474. var offset = numCaptures;
  475. var re = source(regexps[i]);
  476. if (i > 0) {
  477. ret += separator;
  478. }
  479. ret += "(";
  480. while (re.length > 0) {
  481. var match = backreferenceRe.exec(re);
  482. if (match == null) {
  483. ret += re;
  484. break;
  485. }
  486. ret += re.substring(0, match.index);
  487. re = re.substring(match.index + match[0].length);
  488. if (match[0][0] === '\\' && match[1]) {
  489. // Adjust the backreference.
  490. ret += '\\' + String(Number(match[1]) + offset);
  491. } else {
  492. ret += match[0];
  493. if (match[0] === '(') {
  494. numCaptures++;
  495. }
  496. }
  497. }
  498. ret += ")";
  499. }
  500. return ret;
  501. }
  502. // Common regexps
  503. const IDENT_RE = '[a-zA-Z]\\w*';
  504. const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
  505. const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
  506. const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
  507. const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
  508. const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
  509. /**
  510. * @param { Partial<Mode> & {binary?: string | RegExp} } opts
  511. */
  512. const SHEBANG = (opts = {}) => {
  513. const beginShebang = /^#![ ]*\//;
  514. if (opts.binary) {
  515. opts.begin = concat(
  516. beginShebang,
  517. /.*\b/,
  518. opts.binary,
  519. /\b.*/);
  520. }
  521. return inherit({
  522. className: 'meta',
  523. begin: beginShebang,
  524. end: /$/,
  525. relevance: 0,
  526. /** @type {ModeCallback} */
  527. "on:begin": (m, resp) => {
  528. if (m.index !== 0) resp.ignoreMatch();
  529. }
  530. }, opts);
  531. };
  532. // Common modes
  533. const BACKSLASH_ESCAPE = {
  534. begin: '\\\\[\\s\\S]', relevance: 0
  535. };
  536. const APOS_STRING_MODE = {
  537. className: 'string',
  538. begin: '\'',
  539. end: '\'',
  540. illegal: '\\n',
  541. contains: [BACKSLASH_ESCAPE]
  542. };
  543. const QUOTE_STRING_MODE = {
  544. className: 'string',
  545. begin: '"',
  546. end: '"',
  547. illegal: '\\n',
  548. contains: [BACKSLASH_ESCAPE]
  549. };
  550. const PHRASAL_WORDS_MODE = {
  551. 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/
  552. };
  553. /**
  554. * Creates a comment mode
  555. *
  556. * @param {string | RegExp} begin
  557. * @param {string | RegExp} end
  558. * @param {Mode | {}} [modeOptions]
  559. * @returns {Partial<Mode>}
  560. */
  561. const COMMENT = function(begin, end, modeOptions = {}) {
  562. var mode = inherit(
  563. {
  564. className: 'comment',
  565. begin,
  566. end,
  567. contains: []
  568. },
  569. modeOptions
  570. );
  571. mode.contains.push(PHRASAL_WORDS_MODE);
  572. mode.contains.push({
  573. className: 'doctag',
  574. begin: '(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):',
  575. relevance: 0
  576. });
  577. return mode;
  578. };
  579. const C_LINE_COMMENT_MODE = COMMENT('//', '$');
  580. const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
  581. const HASH_COMMENT_MODE = COMMENT('#', '$');
  582. const NUMBER_MODE = {
  583. className: 'number',
  584. begin: NUMBER_RE,
  585. relevance: 0
  586. };
  587. const C_NUMBER_MODE = {
  588. className: 'number',
  589. begin: C_NUMBER_RE,
  590. relevance: 0
  591. };
  592. const BINARY_NUMBER_MODE = {
  593. className: 'number',
  594. begin: BINARY_NUMBER_RE,
  595. relevance: 0
  596. };
  597. const CSS_NUMBER_MODE = {
  598. className: 'number',
  599. begin: NUMBER_RE + '(' +
  600. '%|em|ex|ch|rem' +
  601. '|vw|vh|vmin|vmax' +
  602. '|cm|mm|in|pt|pc|px' +
  603. '|deg|grad|rad|turn' +
  604. '|s|ms' +
  605. '|Hz|kHz' +
  606. '|dpi|dpcm|dppx' +
  607. ')?',
  608. relevance: 0
  609. };
  610. const REGEXP_MODE = {
  611. // this outer rule makes sure we actually have a WHOLE regex and not simply
  612. // an expression such as:
  613. //
  614. // 3 / something
  615. //
  616. // (which will then blow up when regex's `illegal` sees the newline)
  617. begin: /(?=\/[^/\n]*\/)/,
  618. contains: [{
  619. className: 'regexp',
  620. begin: /\//,
  621. end: /\/[gimuy]*/,
  622. illegal: /\n/,
  623. contains: [
  624. BACKSLASH_ESCAPE,
  625. {
  626. begin: /\[/,
  627. end: /\]/,
  628. relevance: 0,
  629. contains: [BACKSLASH_ESCAPE]
  630. }
  631. ]
  632. }]
  633. };
  634. const TITLE_MODE = {
  635. className: 'title',
  636. begin: IDENT_RE,
  637. relevance: 0
  638. };
  639. const UNDERSCORE_TITLE_MODE = {
  640. className: 'title',
  641. begin: UNDERSCORE_IDENT_RE,
  642. relevance: 0
  643. };
  644. const METHOD_GUARD = {
  645. // excludes method names from keyword processing
  646. begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
  647. relevance: 0
  648. };
  649. /**
  650. * Adds end same as begin mechanics to a mode
  651. *
  652. * Your mode must include at least a single () match group as that first match
  653. * group is what is used for comparison
  654. * @param {Partial<Mode>} mode
  655. */
  656. const END_SAME_AS_BEGIN = function(mode) {
  657. return Object.assign(mode,
  658. {
  659. /** @type {ModeCallback} */
  660. 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
  661. /** @type {ModeCallback} */
  662. 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
  663. });
  664. };
  665. var MODES = /*#__PURE__*/Object.freeze({
  666. __proto__: null,
  667. IDENT_RE: IDENT_RE,
  668. UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
  669. NUMBER_RE: NUMBER_RE,
  670. C_NUMBER_RE: C_NUMBER_RE,
  671. BINARY_NUMBER_RE: BINARY_NUMBER_RE,
  672. RE_STARTERS_RE: RE_STARTERS_RE,
  673. SHEBANG: SHEBANG,
  674. BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
  675. APOS_STRING_MODE: APOS_STRING_MODE,
  676. QUOTE_STRING_MODE: QUOTE_STRING_MODE,
  677. PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
  678. COMMENT: COMMENT,
  679. C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
  680. C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
  681. HASH_COMMENT_MODE: HASH_COMMENT_MODE,
  682. NUMBER_MODE: NUMBER_MODE,
  683. C_NUMBER_MODE: C_NUMBER_MODE,
  684. BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
  685. CSS_NUMBER_MODE: CSS_NUMBER_MODE,
  686. REGEXP_MODE: REGEXP_MODE,
  687. TITLE_MODE: TITLE_MODE,
  688. UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE,
  689. METHOD_GUARD: METHOD_GUARD,
  690. END_SAME_AS_BEGIN: END_SAME_AS_BEGIN
  691. });
  692. // keywords that should have no default relevance value
  693. var COMMON_KEYWORDS = 'of and for in not or if then'.split(' ');
  694. // compilation
  695. /**
  696. * Compiles a language definition result
  697. *
  698. * Given the raw result of a language definition (Language), compiles this so
  699. * that it is ready for highlighting code.
  700. * @param {Language} language
  701. * @returns {CompiledLanguage}
  702. */
  703. function compileLanguage(language) {
  704. /**
  705. * Builds a regex with the case sensativility of the current language
  706. *
  707. * @param {RegExp | string} value
  708. * @param {boolean} [global]
  709. */
  710. function langRe(value, global) {
  711. return new RegExp(
  712. source(value),
  713. 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')
  714. );
  715. }
  716. /**
  717. Stores multiple regular expressions and allows you to quickly search for
  718. them all in a string simultaneously - returning the first match. It does
  719. this by creating a huge (a|b|c) regex - each individual item wrapped with ()
  720. and joined by `|` - using match groups to track position. When a match is
  721. found checking which position in the array has content allows us to figure
  722. out which of the original regexes / match groups triggered the match.
  723. The match object itself (the result of `Regex.exec`) is returned but also
  724. enhanced by merging in any meta-data that was registered with the regex.
  725. This is how we keep track of which mode matched, and what type of rule
  726. (`illegal`, `begin`, end, etc).
  727. */
  728. class MultiRegex {
  729. constructor() {
  730. this.matchIndexes = {};
  731. // @ts-ignore
  732. this.regexes = [];
  733. this.matchAt = 1;
  734. this.position = 0;
  735. }
  736. // @ts-ignore
  737. addRule(re, opts) {
  738. opts.position = this.position++;
  739. // @ts-ignore
  740. this.matchIndexes[this.matchAt] = opts;
  741. this.regexes.push([opts, re]);
  742. this.matchAt += countMatchGroups(re) + 1;
  743. }
  744. compile() {
  745. if (this.regexes.length === 0) {
  746. // avoids the need to check length every time exec is called
  747. // @ts-ignore
  748. this.exec = () => null;
  749. }
  750. const terminators = this.regexes.map(el => el[1]);
  751. this.matcherRe = langRe(join(terminators), true);
  752. this.lastIndex = 0;
  753. }
  754. /** @param {string} s */
  755. exec(s) {
  756. this.matcherRe.lastIndex = this.lastIndex;
  757. const match = this.matcherRe.exec(s);
  758. if (!match) { return null; }
  759. // eslint-disable-next-line no-undefined
  760. const i = match.findIndex((el, i) => i > 0 && el !== undefined);
  761. // @ts-ignore
  762. const matchData = this.matchIndexes[i];
  763. // trim off any earlier non-relevant match groups (ie, the other regex
  764. // match groups that make up the multi-matcher)
  765. match.splice(0, i);
  766. return Object.assign(match, matchData);
  767. }
  768. }
  769. /*
  770. Created to solve the key deficiently with MultiRegex - there is no way to
  771. test for multiple matches at a single location. Why would we need to do
  772. that? In the future a more dynamic engine will allow certain matches to be
  773. ignored. An example: if we matched say the 3rd regex in a large group but
  774. decided to ignore it - we'd need to started testing again at the 4th
  775. regex... but MultiRegex itself gives us no real way to do that.
  776. So what this class creates MultiRegexs on the fly for whatever search
  777. position they are needed.
  778. NOTE: These additional MultiRegex objects are created dynamically. For most
  779. grammars most of the time we will never actually need anything more than the
  780. first MultiRegex - so this shouldn't have too much overhead.
  781. Say this is our search group, and we match regex3, but wish to ignore it.
  782. regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0
  783. What we need is a new MultiRegex that only includes the remaining
  784. possibilities:
  785. regex4 | regex5 ' ie, startAt = 3
  786. This class wraps all that complexity up in a simple API... `startAt` decides
  787. where in the array of expressions to start doing the matching. It
  788. auto-increments, so if a match is found at position 2, then startAt will be
  789. set to 3. If the end is reached startAt will return to 0.
  790. MOST of the time the parser will be setting startAt manually to 0.
  791. */
  792. class ResumableMultiRegex {
  793. constructor() {
  794. // @ts-ignore
  795. this.rules = [];
  796. // @ts-ignore
  797. this.multiRegexes = [];
  798. this.count = 0;
  799. this.lastIndex = 0;
  800. this.regexIndex = 0;
  801. }
  802. // @ts-ignore
  803. getMatcher(index) {
  804. if (this.multiRegexes[index]) return this.multiRegexes[index];
  805. const matcher = new MultiRegex();
  806. this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
  807. matcher.compile();
  808. this.multiRegexes[index] = matcher;
  809. return matcher;
  810. }
  811. considerAll() {
  812. this.regexIndex = 0;
  813. }
  814. // @ts-ignore
  815. addRule(re, opts) {
  816. this.rules.push([re, opts]);
  817. if (opts.type === "begin") this.count++;
  818. }
  819. /** @param {string} s */
  820. exec(s) {
  821. const m = this.getMatcher(this.regexIndex);
  822. m.lastIndex = this.lastIndex;
  823. const result = m.exec(s);
  824. if (result) {
  825. this.regexIndex += result.position + 1;
  826. if (this.regexIndex === this.count) { // wrap-around
  827. this.regexIndex = 0;
  828. }
  829. }
  830. // this.regexIndex = 0;
  831. return result;
  832. }
  833. }
  834. /**
  835. * Given a mode, builds a huge ResumableMultiRegex that can be used to walk
  836. * the content and find matches.
  837. *
  838. * @param {CompiledMode} mode
  839. * @returns {ResumableMultiRegex}
  840. */
  841. function buildModeRegex(mode) {
  842. const mm = new ResumableMultiRegex();
  843. mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));
  844. if (mode.terminator_end) {
  845. mm.addRule(mode.terminator_end, { type: "end" });
  846. }
  847. if (mode.illegal) {
  848. mm.addRule(mode.illegal, { type: "illegal" });
  849. }
  850. return mm;
  851. }
  852. // TODO: We need negative look-behind support to do this properly
  853. /**
  854. * Skip a match if it has a preceding or trailing dot
  855. *
  856. * This is used for `beginKeywords` to prevent matching expressions such as
  857. * `bob.keyword.do()`. The mode compiler automatically wires this up as a
  858. * special _internal_ 'on:begin' callback for modes with `beginKeywords`
  859. * @param {RegExpMatchArray} match
  860. * @param {CallbackResponse} response
  861. */
  862. function skipIfhasPrecedingOrTrailingDot(match, response) {
  863. const before = match.input[match.index - 1];
  864. const after = match.input[match.index + match[0].length];
  865. if (before === "." || after === ".") {
  866. response.ignoreMatch();
  867. }
  868. }
  869. /** skip vs abort vs ignore
  870. *
  871. * @skip - The mode is still entered and exited normally (and contains rules apply),
  872. * but all content is held and added to the parent buffer rather than being
  873. * output when the mode ends. Mostly used with `sublanguage` to build up
  874. * a single large buffer than can be parsed by sublanguage.
  875. *
  876. * - The mode begin ands ends normally.
  877. * - Content matched is added to the parent mode buffer.
  878. * - The parser cursor is moved forward normally.
  879. *
  880. * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it
  881. * never matched) but DOES NOT continue to match subsequent `contains`
  882. * modes. Abort is bad/suboptimal because it can result in modes
  883. * farther down not getting applied because an earlier rule eats the
  884. * content but then aborts.
  885. *
  886. * - The mode does not begin.
  887. * - Content matched by `begin` is added to the mode buffer.
  888. * - The parser cursor is moved forward accordingly.
  889. *
  890. * @ignore - Ignores the mode (as if it never matched) and continues to match any
  891. * subsequent `contains` modes. Ignore isn't technically possible with
  892. * the current parser implementation.
  893. *
  894. * - The mode does not begin.
  895. * - Content matched by `begin` is ignored.
  896. * - The parser cursor is not moved forward.
  897. */
  898. /**
  899. * Compiles an individual mode
  900. *
  901. * This can raise an error if the mode contains certain detectable known logic
  902. * issues.
  903. * @param {Mode} mode
  904. * @param {CompiledMode | null} [parent]
  905. * @returns {CompiledMode | never}
  906. */
  907. function compileMode(mode, parent) {
  908. const cmode = /** @type CompiledMode */ (mode);
  909. if (mode.compiled) return cmode;
  910. mode.compiled = true;
  911. // __beforeBegin is considered private API, internal use only
  912. mode.__beforeBegin = null;
  913. mode.keywords = mode.keywords || mode.beginKeywords;
  914. let kw_pattern = null;
  915. if (typeof mode.keywords === "object") {
  916. kw_pattern = mode.keywords.$pattern;
  917. delete mode.keywords.$pattern;
  918. }
  919. if (mode.keywords) {
  920. mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
  921. }
  922. // both are not allowed
  923. if (mode.lexemes && kw_pattern) {
  924. throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");
  925. }
  926. // `mode.lexemes` was the old standard before we added and now recommend
  927. // using `keywords.$pattern` to pass the keyword pattern
  928. cmode.keywordPatternRe = langRe(mode.lexemes || kw_pattern || /\w+/, true);
  929. if (parent) {
  930. if (mode.beginKeywords) {
  931. // for languages with keywords that include non-word characters checking for
  932. // a word boundary is not sufficient, so instead we check for a word boundary
  933. // or whitespace - this does no harm in any case since our keyword engine
  934. // doesn't allow spaces in keywords anyways and we still check for the boundary
  935. // first
  936. mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?=\\b|\\s)';
  937. mode.__beforeBegin = skipIfhasPrecedingOrTrailingDot;
  938. }
  939. if (!mode.begin) mode.begin = /\B|\b/;
  940. cmode.beginRe = langRe(mode.begin);
  941. if (mode.endSameAsBegin) mode.end = mode.begin;
  942. if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
  943. if (mode.end) cmode.endRe = langRe(mode.end);
  944. cmode.terminator_end = source(mode.end) || '';
  945. if (mode.endsWithParent && parent.terminator_end) {
  946. cmode.terminator_end += (mode.end ? '|' : '') + parent.terminator_end;
  947. }
  948. }
  949. if (mode.illegal) cmode.illegalRe = langRe(mode.illegal);
  950. // eslint-disable-next-line no-undefined
  951. if (mode.relevance === undefined) mode.relevance = 1;
  952. if (!mode.contains) mode.contains = [];
  953. mode.contains = [].concat(...mode.contains.map(function(c) {
  954. return expand_or_clone_mode(c === 'self' ? mode : c);
  955. }));
  956. mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });
  957. if (mode.starts) {
  958. compileMode(mode.starts, parent);
  959. }
  960. cmode.matcher = buildModeRegex(cmode);
  961. return cmode;
  962. }
  963. // self is not valid at the top-level
  964. if (language.contains && language.contains.includes('self')) {
  965. throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
  966. }
  967. return compileMode(/** @type Mode */ (language));
  968. }
  969. /**
  970. * Determines if a mode has a dependency on it's parent or not
  971. *
  972. * If a mode does have a parent dependency then often we need to clone it if
  973. * it's used in multiple places so that each copy points to the correct parent,
  974. * where-as modes without a parent can often safely be re-used at the bottom of
  975. * a mode chain.
  976. *
  977. * @param {Mode | null} mode
  978. * @returns {boolean} - is there a dependency on the parent?
  979. * */
  980. function dependencyOnParent(mode) {
  981. if (!mode) return false;
  982. return mode.endsWithParent || dependencyOnParent(mode.starts);
  983. }
  984. /**
  985. * Expands a mode or clones it if necessary
  986. *
  987. * This is necessary for modes with parental dependenceis (see notes on
  988. * `dependencyOnParent`) and for nodes that have `variants` - which must then be
  989. * exploded into their own individual modes at compile time.
  990. *
  991. * @param {Mode} mode
  992. * @returns {Mode | Mode[]}
  993. * */
  994. function expand_or_clone_mode(mode) {
  995. if (mode.variants && !mode.cached_variants) {
  996. mode.cached_variants = mode.variants.map(function(variant) {
  997. return inherit(mode, { variants: null }, variant);
  998. });
  999. }
  1000. // EXPAND
  1001. // if we have variants then essentially "replace" the mode with the variants
  1002. // this happens in compileMode, where this function is called from
  1003. if (mode.cached_variants) {
  1004. return mode.cached_variants;
  1005. }
  1006. // CLONE
  1007. // if we have dependencies on parents then we need a unique
  1008. // instance of ourselves, so we can be reused with many
  1009. // different parents without issue
  1010. if (dependencyOnParent(mode)) {
  1011. return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });
  1012. }
  1013. if (Object.isFrozen(mode)) {
  1014. return inherit(mode);
  1015. }
  1016. // no special dependency issues, just return ourselves
  1017. return mode;
  1018. }
  1019. /***********************************************
  1020. Keywords
  1021. ***********************************************/
  1022. /**
  1023. * Given raw keywords from a language definition, compile them.
  1024. *
  1025. * @param {string | Record<string,string>} rawKeywords
  1026. * @param {boolean} case_insensitive
  1027. */
  1028. function compileKeywords(rawKeywords, case_insensitive) {
  1029. /** @type KeywordDict */
  1030. var compiled_keywords = {};
  1031. if (typeof rawKeywords === 'string') { // string
  1032. splitAndCompile('keyword', rawKeywords);
  1033. } else {
  1034. Object.keys(rawKeywords).forEach(function(className) {
  1035. splitAndCompile(className, rawKeywords[className]);
  1036. });
  1037. }
  1038. return compiled_keywords;
  1039. // ---
  1040. /**
  1041. * Compiles an individual list of keywords
  1042. *
  1043. * Ex: "for if when while|5"
  1044. *
  1045. * @param {string} className
  1046. * @param {string} keywordList
  1047. */
  1048. function splitAndCompile(className, keywordList) {
  1049. if (case_insensitive) {
  1050. keywordList = keywordList.toLowerCase();
  1051. }
  1052. keywordList.split(' ').forEach(function(keyword) {
  1053. var pair = keyword.split('|');
  1054. compiled_keywords[pair[0]] = [className, scoreForKeyword(pair[0], pair[1])];
  1055. });
  1056. }
  1057. }
  1058. /**
  1059. * Returns the proper score for a given keyword
  1060. *
  1061. * Also takes into account comment keywords, which will be scored 0 UNLESS
  1062. * another score has been manually assigned.
  1063. * @param {string} keyword
  1064. * @param {string} [providedScore]
  1065. */
  1066. function scoreForKeyword(keyword, providedScore) {
  1067. // manual scores always win over common keywords
  1068. // so you can force a score of 1 if you really insist
  1069. if (providedScore) {
  1070. return Number(providedScore);
  1071. }
  1072. return commonKeyword(keyword) ? 0 : 1;
  1073. }
  1074. /**
  1075. * Determines if a given keyword is common or not
  1076. *
  1077. * @param {string} keyword */
  1078. function commonKeyword(keyword) {
  1079. return COMMON_KEYWORDS.includes(keyword.toLowerCase());
  1080. }
  1081. var version = "10.1.1";
  1082. /*
  1083. Syntax highlighting with language autodetection.
  1084. https://highlightjs.org/
  1085. */
  1086. const escape$1 = escapeHTML;
  1087. const inherit$1 = inherit;
  1088. const { nodeStream: nodeStream$1, mergeStreams: mergeStreams$1 } = utils;
  1089. const NO_MATCH = Symbol("nomatch");
  1090. /**
  1091. * @param {any} hljs - object that is extended (legacy)
  1092. * @returns {HLJSApi}
  1093. */
  1094. const HLJS = function(hljs) {
  1095. // Convenience variables for build-in objects
  1096. /** @type {unknown[]} */
  1097. var ArrayProto = [];
  1098. // Global internal variables used within the highlight.js library.
  1099. /** @type {Record<string, Language>} */
  1100. var languages = {};
  1101. /** @type {Record<string, string>} */
  1102. var aliases = {};
  1103. /** @type {HLJSPlugin[]} */
  1104. var plugins = [];
  1105. // safe/production mode - swallows more errors, tries to keep running
  1106. // even if a single syntax or parse hits a fatal error
  1107. var SAFE_MODE = true;
  1108. var fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm;
  1109. var LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
  1110. /** @type {Language} */
  1111. const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };
  1112. // Global options used when within external APIs. This is modified when
  1113. // calling the `hljs.configure` function.
  1114. /** @type HLJSOptions */
  1115. var options = {
  1116. noHighlightRe: /^(no-?highlight)$/i,
  1117. languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
  1118. classPrefix: 'hljs-',
  1119. tabReplace: null,
  1120. useBR: false,
  1121. languages: null,
  1122. // beta configuration options, subject to change, welcome to discuss
  1123. // https://github.com/highlightjs/highlight.js/issues/1086
  1124. __emitter: TokenTreeEmitter
  1125. };
  1126. /* Utility functions */
  1127. /**
  1128. * Tests a language name to see if highlighting should be skipped
  1129. * @param {string} languageName
  1130. */
  1131. function shouldNotHighlight(languageName) {
  1132. return options.noHighlightRe.test(languageName);
  1133. }
  1134. /**
  1135. * @param {HighlightedHTMLElement} block - the HTML element to determine language for
  1136. */
  1137. function blockLanguage(block) {
  1138. var classes = block.className + ' ';
  1139. classes += block.parentNode ? block.parentNode.className : '';
  1140. // language-* takes precedence over non-prefixed class names.
  1141. const match = options.languageDetectRe.exec(classes);
  1142. if (match) {
  1143. var language = getLanguage(match[1]);
  1144. if (!language) {
  1145. console.warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
  1146. console.warn("Falling back to no-highlight mode for this block.", block);
  1147. }
  1148. return language ? match[1] : 'no-highlight';
  1149. }
  1150. return classes
  1151. .split(/\s+/)
  1152. .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
  1153. }
  1154. /**
  1155. * Core highlighting function.
  1156. *
  1157. * @param {string} languageName - the language to use for highlighting
  1158. * @param {string} code - the code to highlight
  1159. * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
  1160. * @param {Mode} [continuation] - current continuation mode, if any
  1161. *
  1162. * @returns {HighlightResult} Result - an object that represents the result
  1163. * @property {string} language - the language name
  1164. * @property {number} relevance - the relevance score
  1165. * @property {string} value - the highlighted HTML code
  1166. * @property {string} code - the original raw code
  1167. * @property {Mode} top - top of the current mode stack
  1168. * @property {boolean} illegal - indicates whether any illegal matches were found
  1169. */
  1170. function highlight(languageName, code, ignoreIllegals, continuation) {
  1171. /** @type {{ code: string, language: string, result?: any }} */
  1172. var context = {
  1173. code,
  1174. language: languageName
  1175. };
  1176. // the plugin can change the desired language or the code to be highlighted
  1177. // just be changing the object it was passed
  1178. fire("before:highlight", context);
  1179. // a before plugin can usurp the result completely by providing it's own
  1180. // in which case we don't even need to call highlight
  1181. var result = context.result ?
  1182. context.result :
  1183. _highlight(context.language, context.code, ignoreIllegals, continuation);
  1184. result.code = context.code;
  1185. // the plugin can change anything in result to suite it
  1186. fire("after:highlight", result);
  1187. return result;
  1188. }
  1189. /**
  1190. * private highlight that's used internally and does not fire callbacks
  1191. *
  1192. * @param {string} languageName - the language to use for highlighting
  1193. * @param {string} code - the code to highlight
  1194. * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
  1195. * @param {Mode} [continuation] - current continuation mode, if any
  1196. */
  1197. function _highlight(languageName, code, ignoreIllegals, continuation) {
  1198. var codeToHighlight = code;
  1199. /**
  1200. * Return keyword data if a match is a keyword
  1201. * @param {CompiledMode} mode - current mode
  1202. * @param {RegExpMatchArray} match - regexp match data
  1203. * @returns {KeywordData | false}
  1204. */
  1205. function keywordData(mode, match) {
  1206. var matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];
  1207. return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];
  1208. }
  1209. function processKeywords() {
  1210. if (!top.keywords) {
  1211. emitter.addText(mode_buffer);
  1212. return;
  1213. }
  1214. let last_index = 0;
  1215. top.keywordPatternRe.lastIndex = 0;
  1216. let match = top.keywordPatternRe.exec(mode_buffer);
  1217. let buf = "";
  1218. while (match) {
  1219. buf += mode_buffer.substring(last_index, match.index);
  1220. const data = keywordData(top, match);
  1221. if (data) {
  1222. const [kind, keywordRelevance] = data;
  1223. emitter.addText(buf);
  1224. buf = "";
  1225. relevance += keywordRelevance;
  1226. emitter.addKeyword(match[0], kind);
  1227. } else {
  1228. buf += match[0];
  1229. }
  1230. last_index = top.keywordPatternRe.lastIndex;
  1231. match = top.keywordPatternRe.exec(mode_buffer);
  1232. }
  1233. buf += mode_buffer.substr(last_index);
  1234. emitter.addText(buf);
  1235. }
  1236. function processSubLanguage() {
  1237. if (mode_buffer === "") return;
  1238. /** @type HighlightResult */
  1239. var result = null;
  1240. if (typeof top.subLanguage === 'string') {
  1241. if (!languages[top.subLanguage]) {
  1242. emitter.addText(mode_buffer);
  1243. return;
  1244. }
  1245. result = _highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]);
  1246. continuations[top.subLanguage] = result.top;
  1247. } else {
  1248. result = highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : null);
  1249. }
  1250. // Counting embedded language score towards the host language may be disabled
  1251. // with zeroing the containing mode relevance. Use case in point is Markdown that
  1252. // allows XML everywhere and makes every XML snippet to have a much larger Markdown
  1253. // score.
  1254. if (top.relevance > 0) {
  1255. relevance += result.relevance;
  1256. }
  1257. emitter.addSublanguage(result.emitter, result.language);
  1258. }
  1259. function processBuffer() {
  1260. if (top.subLanguage != null) {
  1261. processSubLanguage();
  1262. } else {
  1263. processKeywords();
  1264. }
  1265. mode_buffer = '';
  1266. }
  1267. /**
  1268. * @param {Mode} mode - new mode to start
  1269. */
  1270. function startNewMode(mode) {
  1271. if (mode.className) {
  1272. emitter.openNode(mode.className);
  1273. }
  1274. top = Object.create(mode, { parent: { value: top } });
  1275. return top;
  1276. }
  1277. /**
  1278. * @param {CompiledMode } mode - the mode to potentially end
  1279. * @param {RegExpMatchArray} match - the latest match
  1280. * @param {string} matchPlusRemainder - match plus remainder of content
  1281. * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode
  1282. */
  1283. function endOfMode(mode, match, matchPlusRemainder) {
  1284. let matched = startsWith(mode.endRe, matchPlusRemainder);
  1285. if (matched) {
  1286. if (mode["on:end"]) {
  1287. const resp = new Response(mode);
  1288. mode["on:end"](match, resp);
  1289. if (resp.ignore) matched = false;
  1290. }
  1291. if (matched) {
  1292. while (mode.endsParent && mode.parent) {
  1293. mode = mode.parent;
  1294. }
  1295. return mode;
  1296. }
  1297. }
  1298. // even if on:end fires an `ignore` it's still possible
  1299. // that we might trigger the end node because of a parent mode
  1300. if (mode.endsWithParent) {
  1301. return endOfMode(mode.parent, match, matchPlusRemainder);
  1302. }
  1303. }
  1304. /**
  1305. * Handle matching but then ignoring a sequence of text
  1306. *
  1307. * @param {string} lexeme - string containing full match text
  1308. */
  1309. function doIgnore(lexeme) {
  1310. if (top.matcher.regexIndex === 0) {
  1311. // no more regexs to potentially match here, so we move the cursor forward one
  1312. // space
  1313. mode_buffer += lexeme[0];
  1314. return 1;
  1315. } else {
  1316. // no need to move the cursor, we still have additional regexes to try and
  1317. // match at this very spot
  1318. continueScanAtSamePosition = true;
  1319. return 0;
  1320. }
  1321. }
  1322. /**
  1323. * Handle the start of a new potential mode match
  1324. *
  1325. * @param {EnhancedMatch} match - the current match
  1326. * @returns {number} how far to advance the parse cursor
  1327. */
  1328. function doBeginMatch(match) {
  1329. var lexeme = match[0];
  1330. var new_mode = match.rule;
  1331. const resp = new Response(new_mode);
  1332. // first internal before callbacks, then the public ones
  1333. const beforeCallbacks = [new_mode.__beforeBegin, new_mode["on:begin"]];
  1334. for (const cb of beforeCallbacks) {
  1335. if (!cb) continue;
  1336. cb(match, resp);
  1337. if (resp.ignore) return doIgnore(lexeme);
  1338. }
  1339. if (new_mode && new_mode.endSameAsBegin) {
  1340. new_mode.endRe = escape(lexeme);
  1341. }
  1342. if (new_mode.skip) {
  1343. mode_buffer += lexeme;
  1344. } else {
  1345. if (new_mode.excludeBegin) {
  1346. mode_buffer += lexeme;
  1347. }
  1348. processBuffer();
  1349. if (!new_mode.returnBegin && !new_mode.excludeBegin) {
  1350. mode_buffer = lexeme;
  1351. }
  1352. }
  1353. startNewMode(new_mode);
  1354. // if (mode["after:begin"]) {
  1355. // let resp = new Response(mode);
  1356. // mode["after:begin"](match, resp);
  1357. // }
  1358. return new_mode.returnBegin ? 0 : lexeme.length;
  1359. }
  1360. /**
  1361. * Handle the potential end of mode
  1362. *
  1363. * @param {RegExpMatchArray} match - the current match
  1364. */
  1365. function doEndMatch(match) {
  1366. var lexeme = match[0];
  1367. var matchPlusRemainder = codeToHighlight.substr(match.index);
  1368. var end_mode = endOfMode(top, match, matchPlusRemainder);
  1369. if (!end_mode) { return NO_MATCH; }
  1370. var origin = top;
  1371. if (origin.skip) {
  1372. mode_buffer += lexeme;
  1373. } else {
  1374. if (!(origin.returnEnd || origin.excludeEnd)) {
  1375. mode_buffer += lexeme;
  1376. }
  1377. processBuffer();
  1378. if (origin.excludeEnd) {
  1379. mode_buffer = lexeme;
  1380. }
  1381. }
  1382. do {
  1383. if (top.className) {
  1384. emitter.closeNode();
  1385. }
  1386. if (!top.skip && !top.subLanguage) {
  1387. relevance += top.relevance;
  1388. }
  1389. top = top.parent;
  1390. } while (top !== end_mode.parent);
  1391. if (end_mode.starts) {
  1392. if (end_mode.endSameAsBegin) {
  1393. end_mode.starts.endRe = end_mode.endRe;
  1394. }
  1395. startNewMode(end_mode.starts);
  1396. }
  1397. return origin.returnEnd ? 0 : lexeme.length;
  1398. }
  1399. function processContinuations() {
  1400. var list = [];
  1401. for (var current = top; current !== language; current = current.parent) {
  1402. if (current.className) {
  1403. list.unshift(current.className);
  1404. }
  1405. }
  1406. list.forEach(item => emitter.openNode(item));
  1407. }
  1408. /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */
  1409. var lastMatch = {};
  1410. /**
  1411. * Process an individual match
  1412. *
  1413. * @param {string} textBeforeMatch - text preceeding the match (since the last match)
  1414. * @param {EnhancedMatch} [match] - the match itself
  1415. */
  1416. function processLexeme(textBeforeMatch, match) {
  1417. var lexeme = match && match[0];
  1418. // add non-matched text to the current mode buffer
  1419. mode_buffer += textBeforeMatch;
  1420. if (lexeme == null) {
  1421. processBuffer();
  1422. return 0;
  1423. }
  1424. // we've found a 0 width match and we're stuck, so we need to advance
  1425. // this happens when we have badly behaved rules that have optional matchers to the degree that
  1426. // sometimes they can end up matching nothing at all
  1427. // Ref: https://github.com/highlightjs/highlight.js/issues/2140
  1428. if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
  1429. // spit the "skipped" character that our regex choked on back into the output sequence
  1430. mode_buffer += codeToHighlight.slice(match.index, match.index + 1);
  1431. if (!SAFE_MODE) {
  1432. /** @type {AnnotatedError} */
  1433. const err = new Error('0 width match regex');
  1434. err.languageName = languageName;
  1435. err.badRule = lastMatch.rule;
  1436. throw err;
  1437. }
  1438. return 1;
  1439. }
  1440. lastMatch = match;
  1441. if (match.type === "begin") {
  1442. return doBeginMatch(match);
  1443. } else if (match.type === "illegal" && !ignoreIllegals) {
  1444. // illegal match, we do not continue processing
  1445. /** @type {AnnotatedError} */
  1446. const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');
  1447. err.mode = top;
  1448. throw err;
  1449. } else if (match.type === "end") {
  1450. var processed = doEndMatch(match);
  1451. if (processed !== NO_MATCH) {
  1452. return processed;
  1453. }
  1454. }
  1455. // edge case for when illegal matches $ (end of line) which is technically
  1456. // a 0 width match but not a begin/end match so it's not caught by the
  1457. // first handler (when ignoreIllegals is true)
  1458. if (match.type === "illegal" && lexeme === "") {
  1459. // advance so we aren't stuck in an infinite loop
  1460. return 1;
  1461. }
  1462. // infinite loops are BAD, this is a last ditch catch all. if we have a
  1463. // decent number of iterations yet our index (cursor position in our
  1464. // parsing) still 3x behind our index then something is very wrong
  1465. // so we bail
  1466. if (iterations > 100000 && iterations > match.index * 3) {
  1467. const err = new Error('potential infinite loop, way more iterations than matches');
  1468. throw err;
  1469. }
  1470. /*
  1471. Why might be find ourselves here? Only one occasion now. An end match that was
  1472. triggered but could not be completed. When might this happen? When an `endSameasBegin`
  1473. rule sets the end rule to a specific match. Since the overall mode termination rule that's
  1474. being used to scan the text isn't recompiled that means that any match that LOOKS like
  1475. the end (but is not, because it is not an exact match to the beginning) will
  1476. end up here. A definite end match, but when `doEndMatch` tries to "reapply"
  1477. the end rule and fails to match, we wind up here, and just silently ignore the end.
  1478. This causes no real harm other than stopping a few times too many.
  1479. */
  1480. mode_buffer += lexeme;
  1481. return lexeme.length;
  1482. }
  1483. var language = getLanguage(languageName);
  1484. if (!language) {
  1485. console.error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
  1486. throw new Error('Unknown language: "' + languageName + '"');
  1487. }
  1488. var md = compileLanguage(language);
  1489. var result = '';
  1490. /** @type {CompiledMode} */
  1491. var top = continuation || md;
  1492. /** @type Record<string,Mode> */
  1493. var continuations = {}; // keep continuations for sub-languages
  1494. var emitter = new options.__emitter(options);
  1495. processContinuations();
  1496. var mode_buffer = '';
  1497. var relevance = 0;
  1498. var index = 0;
  1499. var iterations = 0;
  1500. var continueScanAtSamePosition = false;
  1501. try {
  1502. top.matcher.considerAll();
  1503. for (;;) {
  1504. iterations++;
  1505. if (continueScanAtSamePosition) {
  1506. // only regexes not matched previously will now be
  1507. // considered for a potential match
  1508. continueScanAtSamePosition = false;
  1509. } else {
  1510. top.matcher.lastIndex = index;
  1511. top.matcher.considerAll();
  1512. }
  1513. const match = top.matcher.exec(codeToHighlight);
  1514. // console.log("match", match[0], match.rule && match.rule.begin)
  1515. if (!match) break;
  1516. const beforeMatch = codeToHighlight.substring(index, match.index);
  1517. const processedCount = processLexeme(beforeMatch, match);
  1518. index = match.index + processedCount;
  1519. }
  1520. processLexeme(codeToHighlight.substr(index));
  1521. emitter.closeAllNodes();
  1522. emitter.finalize();
  1523. result = emitter.toHTML();
  1524. return {
  1525. relevance: relevance,
  1526. value: result,
  1527. language: languageName,
  1528. illegal: false,
  1529. emitter: emitter,
  1530. top: top
  1531. };
  1532. } catch (err) {
  1533. if (err.message && err.message.includes('Illegal')) {
  1534. return {
  1535. illegal: true,
  1536. illegalBy: {
  1537. msg: err.message,
  1538. context: codeToHighlight.slice(index - 100, index + 100),
  1539. mode: err.mode
  1540. },
  1541. sofar: result,
  1542. relevance: 0,
  1543. value: escape$1(codeToHighlight),
  1544. emitter: emitter
  1545. };
  1546. } else if (SAFE_MODE) {
  1547. return {
  1548. illegal: false,
  1549. relevance: 0,
  1550. value: escape$1(codeToHighlight),
  1551. emitter: emitter,
  1552. language: languageName,
  1553. top: top,
  1554. errorRaised: err
  1555. };
  1556. } else {
  1557. throw err;
  1558. }
  1559. }
  1560. }
  1561. /**
  1562. * returns a valid highlight result, without actually doing any actual work,
  1563. * auto highlight starts with this and it's possible for small snippets that
  1564. * auto-detection may not find a better match
  1565. * @param {string} code
  1566. * @returns {HighlightResult}
  1567. */
  1568. function justTextHighlightResult(code) {
  1569. const result = {
  1570. relevance: 0,
  1571. emitter: new options.__emitter(options),
  1572. value: escape$1(code),
  1573. illegal: false,
  1574. top: PLAINTEXT_LANGUAGE
  1575. };
  1576. result.emitter.addText(code);
  1577. return result;
  1578. }
  1579. /**
  1580. Highlighting with language detection. Accepts a string with the code to
  1581. highlight. Returns an object with the following properties:
  1582. - language (detected language)
  1583. - relevance (int)
  1584. - value (an HTML string with highlighting markup)
  1585. - second_best (object with the same structure for second-best heuristically
  1586. detected language, may be absent)
  1587. @param {string} code
  1588. @param {Array<string>} [languageSubset]
  1589. @returns {AutoHighlightResult}
  1590. */
  1591. function highlightAuto(code, languageSubset) {
  1592. languageSubset = languageSubset || options.languages || Object.keys(languages);
  1593. var result = justTextHighlightResult(code);
  1594. var secondBest = result;
  1595. languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {
  1596. var current = _highlight(name, code, false);
  1597. current.language = name;
  1598. if (current.relevance > secondBest.relevance) {
  1599. secondBest = current;
  1600. }
  1601. if (current.relevance > result.relevance) {
  1602. secondBest = result;
  1603. result = current;
  1604. }
  1605. });
  1606. if (secondBest.language) {
  1607. // second_best (with underscore) is the expected API
  1608. result.second_best = secondBest;
  1609. }
  1610. return result;
  1611. }
  1612. /**
  1613. Post-processing of the highlighted markup:
  1614. - replace TABs with something more useful
  1615. - replace real line-breaks with '<br>' for non-pre containers
  1616. @param {string} html
  1617. @returns {string}
  1618. */
  1619. function fixMarkup(html) {
  1620. if (!(options.tabReplace || options.useBR)) {
  1621. return html;
  1622. }
  1623. return html.replace(fixMarkupRe, match => {
  1624. if (match === '\n') {
  1625. return options.useBR ? '<br>' : match;
  1626. } else if (options.tabReplace) {
  1627. return match.replace(/\t/g, options.tabReplace);
  1628. }
  1629. return match;
  1630. });
  1631. }
  1632. /**
  1633. * Builds new class name for block given the language name
  1634. *
  1635. * @param {string} prevClassName
  1636. * @param {string} [currentLang]
  1637. * @param {string} [resultLang]
  1638. */
  1639. function buildClassName(prevClassName, currentLang, resultLang) {
  1640. var language = currentLang ? aliases[currentLang] : resultLang;
  1641. var result = [prevClassName.trim()];
  1642. if (!prevClassName.match(/\bhljs\b/)) {
  1643. result.push('hljs');
  1644. }
  1645. if (!prevClassName.includes(language)) {
  1646. result.push(language);
  1647. }
  1648. return result.join(' ').trim();
  1649. }
  1650. /**
  1651. * Applies highlighting to a DOM node containing code. Accepts a DOM node and
  1652. * two optional parameters for fixMarkup.
  1653. *
  1654. * @param {HighlightedHTMLElement} element - the HTML element to highlight
  1655. */
  1656. function highlightBlock(element) {
  1657. /** @type HTMLElement */
  1658. let node = null;
  1659. const language = blockLanguage(element);
  1660. if (shouldNotHighlight(language)) return;
  1661. fire("before:highlightBlock",
  1662. { block: element, language: language });
  1663. if (options.useBR) {
  1664. node = document.createElement('div');
  1665. node.innerHTML = element.innerHTML.replace(/\n/g, '').replace(/<br[ /]*>/g, '\n');
  1666. } else {
  1667. node = element;
  1668. }
  1669. const text = node.textContent;
  1670. const result = language ? highlight(language, text, true) : highlightAuto(text);
  1671. const originalStream = nodeStream$1(node);
  1672. if (originalStream.length) {
  1673. const resultNode = document.createElement('div');
  1674. resultNode.innerHTML = result.value;
  1675. result.value = mergeStreams$1(originalStream, nodeStream$1(resultNode), text);
  1676. }
  1677. result.value = fixMarkup(result.value);
  1678. fire("after:highlightBlock", { block: element, result: result });
  1679. element.innerHTML = result.value;
  1680. element.className = buildClassName(element.className, language, result.language);
  1681. element.result = {
  1682. language: result.language,
  1683. // TODO: remove with version 11.0
  1684. re: result.relevance,
  1685. relavance: result.relevance
  1686. };
  1687. if (result.second_best) {
  1688. element.second_best = {
  1689. language: result.second_best.language,
  1690. // TODO: remove with version 11.0
  1691. re: result.second_best.relevance,
  1692. relavance: result.second_best.relevance
  1693. };
  1694. }
  1695. }
  1696. /**
  1697. * Updates highlight.js global options with the passed options
  1698. *
  1699. * @param {{}} userOptions
  1700. */
  1701. function configure(userOptions) {
  1702. options = inherit$1(options, userOptions);
  1703. }
  1704. /**
  1705. * Highlights to all <pre><code> blocks on a page
  1706. *
  1707. * @type {Function & {called?: boolean}}
  1708. */
  1709. const initHighlighting = () => {
  1710. if (initHighlighting.called) return;
  1711. initHighlighting.called = true;
  1712. var blocks = document.querySelectorAll('pre code');
  1713. ArrayProto.forEach.call(blocks, highlightBlock);
  1714. };
  1715. // Higlights all when DOMContentLoaded fires
  1716. function initHighlightingOnLoad() {
  1717. // @ts-ignore
  1718. window.addEventListener('DOMContentLoaded', initHighlighting, false);
  1719. }
  1720. /**
  1721. * Register a language grammar module
  1722. *
  1723. * @param {string} languageName
  1724. * @param {LanguageFn} languageDefinition
  1725. */
  1726. function registerLanguage(languageName, languageDefinition) {
  1727. var lang = null;
  1728. try {
  1729. lang = languageDefinition(hljs);
  1730. } catch (error) {
  1731. console.error("Language definition for '{}' could not be registered.".replace("{}", languageName));
  1732. // hard or soft error
  1733. if (!SAFE_MODE) { throw error; } else { console.error(error); }
  1734. // languages that have serious errors are replaced with essentially a
  1735. // "plaintext" stand-in so that the code blocks will still get normal
  1736. // css classes applied to them - and one bad language won't break the
  1737. // entire highlighter
  1738. lang = PLAINTEXT_LANGUAGE;
  1739. }
  1740. // give it a temporary name if it doesn't have one in the meta-data
  1741. if (!lang.name) lang.name = languageName;
  1742. languages[languageName] = lang;
  1743. lang.rawDefinition = languageDefinition.bind(null, hljs);
  1744. if (lang.aliases) {
  1745. registerAliases(lang.aliases, { languageName });
  1746. }
  1747. }
  1748. /**
  1749. * @returns {string[]} List of language internal names
  1750. */
  1751. function listLanguages() {
  1752. return Object.keys(languages);
  1753. }
  1754. /**
  1755. intended usage: When one language truly requires another
  1756. Unlike `getLanguage`, this will throw when the requested language
  1757. is not available.
  1758. @param {string} name - name of the language to fetch/require
  1759. @returns {Language | never}
  1760. */
  1761. function requireLanguage(name) {
  1762. var lang = getLanguage(name);
  1763. if (lang) { return lang; }
  1764. var err = new Error('The \'{}\' language is required, but not loaded.'.replace('{}', name));
  1765. throw err;
  1766. }
  1767. /**
  1768. * @param {string} name - name of the language to retrieve
  1769. * @returns {Language | undefined}
  1770. */
  1771. function getLanguage(name) {
  1772. name = (name || '').toLowerCase();
  1773. return languages[name] || languages[aliases[name]];
  1774. }
  1775. /**
  1776. *
  1777. * @param {string|string[]} aliasList - single alias or list of aliases
  1778. * @param {{languageName: string}} opts
  1779. */
  1780. function registerAliases(aliasList, { languageName }) {
  1781. if (typeof aliasList === 'string') {
  1782. aliasList = [aliasList];
  1783. }
  1784. aliasList.forEach(alias => { aliases[alias] = languageName; });
  1785. }
  1786. /**
  1787. * Determines if a given language has auto-detection enabled
  1788. * @param {string} name - name of the language
  1789. */
  1790. function autoDetection(name) {
  1791. var lang = getLanguage(name);
  1792. return lang && !lang.disableAutodetect;
  1793. }
  1794. /**
  1795. * @param {HLJSPlugin} plugin
  1796. */
  1797. function addPlugin(plugin) {
  1798. plugins.push(plugin);
  1799. }
  1800. /**
  1801. *
  1802. * @param {PluginEvent} event
  1803. * @param {any} args
  1804. */
  1805. function fire(event, args) {
  1806. var cb = event;
  1807. plugins.forEach(function(plugin) {
  1808. if (plugin[cb]) {
  1809. plugin[cb](args);
  1810. }
  1811. });
  1812. }
  1813. /* Interface definition */
  1814. Object.assign(hljs, {
  1815. highlight,
  1816. highlightAuto,
  1817. fixMarkup,
  1818. highlightBlock,
  1819. configure,
  1820. initHighlighting,
  1821. initHighlightingOnLoad,
  1822. registerLanguage,
  1823. listLanguages,
  1824. getLanguage,
  1825. registerAliases,
  1826. requireLanguage,
  1827. autoDetection,
  1828. inherit: inherit$1,
  1829. addPlugin
  1830. });
  1831. hljs.debugMode = function() { SAFE_MODE = false; };
  1832. hljs.safeMode = function() { SAFE_MODE = true; };
  1833. hljs.versionString = version;
  1834. for (const key in MODES) {
  1835. // @ts-ignore
  1836. if (typeof MODES[key] === "object") {
  1837. // @ts-ignore
  1838. deepFreeze(MODES[key]);
  1839. }
  1840. }
  1841. // merge all the modes/regexs into our main object
  1842. Object.assign(hljs, MODES);
  1843. return hljs;
  1844. };
  1845. // export an "instance" of the highlighter
  1846. var highlight = HLJS({});
  1847. module.exports = highlight;