core.js 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  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. resumingScanAtSamePosition() {
  812. return this.regexIndex !== 0;
  813. }
  814. considerAll() {
  815. this.regexIndex = 0;
  816. }
  817. // @ts-ignore
  818. addRule(re, opts) {
  819. this.rules.push([re, opts]);
  820. if (opts.type === "begin") this.count++;
  821. }
  822. /** @param {string} s */
  823. exec(s) {
  824. const m = this.getMatcher(this.regexIndex);
  825. m.lastIndex = this.lastIndex;
  826. let result = m.exec(s);
  827. // The following is because we have no easy way to say "resume scanning at the
  828. // existing position but also skip the current rule ONLY". What happens is
  829. // all prior rules are also skipped which can result in matching the wrong
  830. // thing. Example of matching "booger":
  831. // our matcher is [string, "booger", number]
  832. //
  833. // ....booger....
  834. // if "booger" is ignored then we'd really need a regex to scan from the
  835. // SAME position for only: [string, number] but ignoring "booger" (if it
  836. // was the first match), a simple resume would scan ahead who knows how
  837. // far looking only for "number", ignoring potential string matches (or
  838. // future "booger" matches that might be valid.)
  839. // So what we do: We execute two matchers, one resuming at the same
  840. // position, but the second full matcher starting at the position after:
  841. // /--- resume first regex match here (for [number])
  842. // |/---- full match here for [string, "booger", number]
  843. // vv
  844. // ....booger....
  845. // Which ever results in a match first is then used. So this 3-4 step
  846. // process essentially allows us to say "match at this position, excluding
  847. // a prior rule that was ignored".
  848. //
  849. // 1. Match "booger" first, ignore. Also proves that [string] does non match.
  850. // 2. Resume matching for [number]
  851. // 3. Match at index + 1 for [string, "booger", number]
  852. // 4. If #2 and #3 result in matches, which came first?
  853. if (this.resumingScanAtSamePosition()) {
  854. if (result && result.index === this.lastIndex) ; else { // use the second matcher result
  855. const m2 = this.getMatcher(0);
  856. m2.lastIndex = this.lastIndex + 1;
  857. result = m2.exec(s);
  858. }
  859. }
  860. if (result) {
  861. this.regexIndex += result.position + 1;
  862. if (this.regexIndex === this.count) {
  863. // wrap-around to considering all matches again
  864. this.considerAll();
  865. }
  866. }
  867. return result;
  868. }
  869. }
  870. /**
  871. * Given a mode, builds a huge ResumableMultiRegex that can be used to walk
  872. * the content and find matches.
  873. *
  874. * @param {CompiledMode} mode
  875. * @returns {ResumableMultiRegex}
  876. */
  877. function buildModeRegex(mode) {
  878. const mm = new ResumableMultiRegex();
  879. mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));
  880. if (mode.terminator_end) {
  881. mm.addRule(mode.terminator_end, { type: "end" });
  882. }
  883. if (mode.illegal) {
  884. mm.addRule(mode.illegal, { type: "illegal" });
  885. }
  886. return mm;
  887. }
  888. // TODO: We need negative look-behind support to do this properly
  889. /**
  890. * Skip a match if it has a preceding or trailing dot
  891. *
  892. * This is used for `beginKeywords` to prevent matching expressions such as
  893. * `bob.keyword.do()`. The mode compiler automatically wires this up as a
  894. * special _internal_ 'on:begin' callback for modes with `beginKeywords`
  895. * @param {RegExpMatchArray} match
  896. * @param {CallbackResponse} response
  897. */
  898. function skipIfhasPrecedingOrTrailingDot(match, response) {
  899. const before = match.input[match.index - 1];
  900. const after = match.input[match.index + match[0].length];
  901. if (before === "." || after === ".") {
  902. response.ignoreMatch();
  903. }
  904. }
  905. /** skip vs abort vs ignore
  906. *
  907. * @skip - The mode is still entered and exited normally (and contains rules apply),
  908. * but all content is held and added to the parent buffer rather than being
  909. * output when the mode ends. Mostly used with `sublanguage` to build up
  910. * a single large buffer than can be parsed by sublanguage.
  911. *
  912. * - The mode begin ands ends normally.
  913. * - Content matched is added to the parent mode buffer.
  914. * - The parser cursor is moved forward normally.
  915. *
  916. * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it
  917. * never matched) but DOES NOT continue to match subsequent `contains`
  918. * modes. Abort is bad/suboptimal because it can result in modes
  919. * farther down not getting applied because an earlier rule eats the
  920. * content but then aborts.
  921. *
  922. * - The mode does not begin.
  923. * - Content matched by `begin` is added to the mode buffer.
  924. * - The parser cursor is moved forward accordingly.
  925. *
  926. * @ignore - Ignores the mode (as if it never matched) and continues to match any
  927. * subsequent `contains` modes. Ignore isn't technically possible with
  928. * the current parser implementation.
  929. *
  930. * - The mode does not begin.
  931. * - Content matched by `begin` is ignored.
  932. * - The parser cursor is not moved forward.
  933. */
  934. /**
  935. * Compiles an individual mode
  936. *
  937. * This can raise an error if the mode contains certain detectable known logic
  938. * issues.
  939. * @param {Mode} mode
  940. * @param {CompiledMode | null} [parent]
  941. * @returns {CompiledMode | never}
  942. */
  943. function compileMode(mode, parent) {
  944. const cmode = /** @type CompiledMode */ (mode);
  945. if (mode.compiled) return cmode;
  946. mode.compiled = true;
  947. // __beforeBegin is considered private API, internal use only
  948. mode.__beforeBegin = null;
  949. mode.keywords = mode.keywords || mode.beginKeywords;
  950. let kw_pattern = null;
  951. if (typeof mode.keywords === "object") {
  952. kw_pattern = mode.keywords.$pattern;
  953. delete mode.keywords.$pattern;
  954. }
  955. if (mode.keywords) {
  956. mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
  957. }
  958. // both are not allowed
  959. if (mode.lexemes && kw_pattern) {
  960. throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");
  961. }
  962. // `mode.lexemes` was the old standard before we added and now recommend
  963. // using `keywords.$pattern` to pass the keyword pattern
  964. cmode.keywordPatternRe = langRe(mode.lexemes || kw_pattern || /\w+/, true);
  965. if (parent) {
  966. if (mode.beginKeywords) {
  967. // for languages with keywords that include non-word characters checking for
  968. // a word boundary is not sufficient, so instead we check for a word boundary
  969. // or whitespace - this does no harm in any case since our keyword engine
  970. // doesn't allow spaces in keywords anyways and we still check for the boundary
  971. // first
  972. mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?=\\b|\\s)';
  973. mode.__beforeBegin = skipIfhasPrecedingOrTrailingDot;
  974. }
  975. if (!mode.begin) mode.begin = /\B|\b/;
  976. cmode.beginRe = langRe(mode.begin);
  977. if (mode.endSameAsBegin) mode.end = mode.begin;
  978. if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
  979. if (mode.end) cmode.endRe = langRe(mode.end);
  980. cmode.terminator_end = source(mode.end) || '';
  981. if (mode.endsWithParent && parent.terminator_end) {
  982. cmode.terminator_end += (mode.end ? '|' : '') + parent.terminator_end;
  983. }
  984. }
  985. if (mode.illegal) cmode.illegalRe = langRe(mode.illegal);
  986. // eslint-disable-next-line no-undefined
  987. if (mode.relevance === undefined) mode.relevance = 1;
  988. if (!mode.contains) mode.contains = [];
  989. mode.contains = [].concat(...mode.contains.map(function(c) {
  990. return expand_or_clone_mode(c === 'self' ? mode : c);
  991. }));
  992. mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });
  993. if (mode.starts) {
  994. compileMode(mode.starts, parent);
  995. }
  996. cmode.matcher = buildModeRegex(cmode);
  997. return cmode;
  998. }
  999. // self is not valid at the top-level
  1000. if (language.contains && language.contains.includes('self')) {
  1001. throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
  1002. }
  1003. return compileMode(/** @type Mode */ (language));
  1004. }
  1005. /**
  1006. * Determines if a mode has a dependency on it's parent or not
  1007. *
  1008. * If a mode does have a parent dependency then often we need to clone it if
  1009. * it's used in multiple places so that each copy points to the correct parent,
  1010. * where-as modes without a parent can often safely be re-used at the bottom of
  1011. * a mode chain.
  1012. *
  1013. * @param {Mode | null} mode
  1014. * @returns {boolean} - is there a dependency on the parent?
  1015. * */
  1016. function dependencyOnParent(mode) {
  1017. if (!mode) return false;
  1018. return mode.endsWithParent || dependencyOnParent(mode.starts);
  1019. }
  1020. /**
  1021. * Expands a mode or clones it if necessary
  1022. *
  1023. * This is necessary for modes with parental dependenceis (see notes on
  1024. * `dependencyOnParent`) and for nodes that have `variants` - which must then be
  1025. * exploded into their own individual modes at compile time.
  1026. *
  1027. * @param {Mode} mode
  1028. * @returns {Mode | Mode[]}
  1029. * */
  1030. function expand_or_clone_mode(mode) {
  1031. if (mode.variants && !mode.cached_variants) {
  1032. mode.cached_variants = mode.variants.map(function(variant) {
  1033. return inherit(mode, { variants: null }, variant);
  1034. });
  1035. }
  1036. // EXPAND
  1037. // if we have variants then essentially "replace" the mode with the variants
  1038. // this happens in compileMode, where this function is called from
  1039. if (mode.cached_variants) {
  1040. return mode.cached_variants;
  1041. }
  1042. // CLONE
  1043. // if we have dependencies on parents then we need a unique
  1044. // instance of ourselves, so we can be reused with many
  1045. // different parents without issue
  1046. if (dependencyOnParent(mode)) {
  1047. return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });
  1048. }
  1049. if (Object.isFrozen(mode)) {
  1050. return inherit(mode);
  1051. }
  1052. // no special dependency issues, just return ourselves
  1053. return mode;
  1054. }
  1055. /***********************************************
  1056. Keywords
  1057. ***********************************************/
  1058. /**
  1059. * Given raw keywords from a language definition, compile them.
  1060. *
  1061. * @param {string | Record<string,string>} rawKeywords
  1062. * @param {boolean} case_insensitive
  1063. */
  1064. function compileKeywords(rawKeywords, case_insensitive) {
  1065. /** @type KeywordDict */
  1066. var compiled_keywords = {};
  1067. if (typeof rawKeywords === 'string') { // string
  1068. splitAndCompile('keyword', rawKeywords);
  1069. } else {
  1070. Object.keys(rawKeywords).forEach(function(className) {
  1071. splitAndCompile(className, rawKeywords[className]);
  1072. });
  1073. }
  1074. return compiled_keywords;
  1075. // ---
  1076. /**
  1077. * Compiles an individual list of keywords
  1078. *
  1079. * Ex: "for if when while|5"
  1080. *
  1081. * @param {string} className
  1082. * @param {string} keywordList
  1083. */
  1084. function splitAndCompile(className, keywordList) {
  1085. if (case_insensitive) {
  1086. keywordList = keywordList.toLowerCase();
  1087. }
  1088. keywordList.split(' ').forEach(function(keyword) {
  1089. var pair = keyword.split('|');
  1090. compiled_keywords[pair[0]] = [className, scoreForKeyword(pair[0], pair[1])];
  1091. });
  1092. }
  1093. }
  1094. /**
  1095. * Returns the proper score for a given keyword
  1096. *
  1097. * Also takes into account comment keywords, which will be scored 0 UNLESS
  1098. * another score has been manually assigned.
  1099. * @param {string} keyword
  1100. * @param {string} [providedScore]
  1101. */
  1102. function scoreForKeyword(keyword, providedScore) {
  1103. // manual scores always win over common keywords
  1104. // so you can force a score of 1 if you really insist
  1105. if (providedScore) {
  1106. return Number(providedScore);
  1107. }
  1108. return commonKeyword(keyword) ? 0 : 1;
  1109. }
  1110. /**
  1111. * Determines if a given keyword is common or not
  1112. *
  1113. * @param {string} keyword */
  1114. function commonKeyword(keyword) {
  1115. return COMMON_KEYWORDS.includes(keyword.toLowerCase());
  1116. }
  1117. var version = "10.2.1";
  1118. // @ts-nocheck
  1119. function hasValueOrEmptyAttribute(value) {
  1120. return Boolean(value || value === "");
  1121. }
  1122. const Component = {
  1123. props: ["language", "code", "autodetect"],
  1124. data: function() {
  1125. return {
  1126. detectedLanguage: "",
  1127. unknownLanguage: false
  1128. };
  1129. },
  1130. computed: {
  1131. className() {
  1132. if (this.unknownLanguage) return "";
  1133. return "hljs " + this.detectedLanguage;
  1134. },
  1135. highlighted() {
  1136. // no idea what language to use, return raw code
  1137. if (!this.autoDetect && !hljs.getLanguage(this.language)) {
  1138. console.warn(`The language "${this.language}" you specified could not be found.`);
  1139. this.unknownLanguage = true;
  1140. return escapeHTML(this.code);
  1141. }
  1142. let result;
  1143. if (this.autoDetect) {
  1144. result = hljs.highlightAuto(this.code);
  1145. this.detectedLanguage = result.language;
  1146. } else {
  1147. result = hljs.highlight(this.language, this.code, this.ignoreIllegals);
  1148. this.detectectLanguage = this.language;
  1149. }
  1150. return result.value;
  1151. },
  1152. autoDetect() {
  1153. return !this.language || hasValueOrEmptyAttribute(this.autodetect);
  1154. },
  1155. ignoreIllegals() {
  1156. return true;
  1157. }
  1158. },
  1159. // this avoids needing to use a whole Vue compilation pipeline just
  1160. // to build Highlight.js
  1161. render(createElement) {
  1162. return createElement("pre", {}, [
  1163. createElement("code", {
  1164. class: this.className,
  1165. domProps: { innerHTML: this.highlighted }})
  1166. ]);
  1167. }
  1168. // template: `<pre><code :class="className" v-html="highlighted"></code></pre>`
  1169. };
  1170. const VuePlugin = {
  1171. install(Vue) {
  1172. Vue.component('highlightjs', Component);
  1173. }
  1174. };
  1175. /*
  1176. Syntax highlighting with language autodetection.
  1177. https://highlightjs.org/
  1178. */
  1179. const escape$1 = escapeHTML;
  1180. const inherit$1 = inherit;
  1181. const { nodeStream: nodeStream$1, mergeStreams: mergeStreams$1 } = utils;
  1182. const NO_MATCH = Symbol("nomatch");
  1183. /**
  1184. * @param {any} hljs - object that is extended (legacy)
  1185. * @returns {HLJSApi}
  1186. */
  1187. const HLJS = function(hljs) {
  1188. // Convenience variables for build-in objects
  1189. /** @type {unknown[]} */
  1190. var ArrayProto = [];
  1191. // Global internal variables used within the highlight.js library.
  1192. /** @type {Record<string, Language>} */
  1193. var languages = Object.create(null);
  1194. /** @type {Record<string, string>} */
  1195. var aliases = Object.create(null);
  1196. /** @type {HLJSPlugin[]} */
  1197. var plugins = [];
  1198. // safe/production mode - swallows more errors, tries to keep running
  1199. // even if a single syntax or parse hits a fatal error
  1200. var SAFE_MODE = true;
  1201. var fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm;
  1202. var LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
  1203. /** @type {Language} */
  1204. const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };
  1205. // Global options used when within external APIs. This is modified when
  1206. // calling the `hljs.configure` function.
  1207. /** @type HLJSOptions */
  1208. var options = {
  1209. noHighlightRe: /^(no-?highlight)$/i,
  1210. languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
  1211. classPrefix: 'hljs-',
  1212. tabReplace: null,
  1213. useBR: false,
  1214. languages: null,
  1215. // beta configuration options, subject to change, welcome to discuss
  1216. // https://github.com/highlightjs/highlight.js/issues/1086
  1217. __emitter: TokenTreeEmitter
  1218. };
  1219. /* Utility functions */
  1220. /**
  1221. * Tests a language name to see if highlighting should be skipped
  1222. * @param {string} languageName
  1223. */
  1224. function shouldNotHighlight(languageName) {
  1225. return options.noHighlightRe.test(languageName);
  1226. }
  1227. /**
  1228. * @param {HighlightedHTMLElement} block - the HTML element to determine language for
  1229. */
  1230. function blockLanguage(block) {
  1231. var classes = block.className + ' ';
  1232. classes += block.parentNode ? block.parentNode.className : '';
  1233. // language-* takes precedence over non-prefixed class names.
  1234. const match = options.languageDetectRe.exec(classes);
  1235. if (match) {
  1236. var language = getLanguage(match[1]);
  1237. if (!language) {
  1238. console.warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
  1239. console.warn("Falling back to no-highlight mode for this block.", block);
  1240. }
  1241. return language ? match[1] : 'no-highlight';
  1242. }
  1243. return classes
  1244. .split(/\s+/)
  1245. .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
  1246. }
  1247. /**
  1248. * Core highlighting function.
  1249. *
  1250. * @param {string} languageName - the language to use for highlighting
  1251. * @param {string} code - the code to highlight
  1252. * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
  1253. * @param {Mode} [continuation] - current continuation mode, if any
  1254. *
  1255. * @returns {HighlightResult} Result - an object that represents the result
  1256. * @property {string} language - the language name
  1257. * @property {number} relevance - the relevance score
  1258. * @property {string} value - the highlighted HTML code
  1259. * @property {string} code - the original raw code
  1260. * @property {Mode} top - top of the current mode stack
  1261. * @property {boolean} illegal - indicates whether any illegal matches were found
  1262. */
  1263. function highlight(languageName, code, ignoreIllegals, continuation) {
  1264. /** @type {{ code: string, language: string, result?: any }} */
  1265. var context = {
  1266. code,
  1267. language: languageName
  1268. };
  1269. // the plugin can change the desired language or the code to be highlighted
  1270. // just be changing the object it was passed
  1271. fire("before:highlight", context);
  1272. // a before plugin can usurp the result completely by providing it's own
  1273. // in which case we don't even need to call highlight
  1274. var result = context.result ?
  1275. context.result :
  1276. _highlight(context.language, context.code, ignoreIllegals, continuation);
  1277. result.code = context.code;
  1278. // the plugin can change anything in result to suite it
  1279. fire("after:highlight", result);
  1280. return result;
  1281. }
  1282. /**
  1283. * private highlight that's used internally and does not fire callbacks
  1284. *
  1285. * @param {string} languageName - the language to use for highlighting
  1286. * @param {string} code - the code to highlight
  1287. * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
  1288. * @param {Mode} [continuation] - current continuation mode, if any
  1289. */
  1290. function _highlight(languageName, code, ignoreIllegals, continuation) {
  1291. var codeToHighlight = code;
  1292. /**
  1293. * Return keyword data if a match is a keyword
  1294. * @param {CompiledMode} mode - current mode
  1295. * @param {RegExpMatchArray} match - regexp match data
  1296. * @returns {KeywordData | false}
  1297. */
  1298. function keywordData(mode, match) {
  1299. var matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];
  1300. return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];
  1301. }
  1302. function processKeywords() {
  1303. if (!top.keywords) {
  1304. emitter.addText(mode_buffer);
  1305. return;
  1306. }
  1307. let last_index = 0;
  1308. top.keywordPatternRe.lastIndex = 0;
  1309. let match = top.keywordPatternRe.exec(mode_buffer);
  1310. let buf = "";
  1311. while (match) {
  1312. buf += mode_buffer.substring(last_index, match.index);
  1313. const data = keywordData(top, match);
  1314. if (data) {
  1315. const [kind, keywordRelevance] = data;
  1316. emitter.addText(buf);
  1317. buf = "";
  1318. relevance += keywordRelevance;
  1319. emitter.addKeyword(match[0], kind);
  1320. } else {
  1321. buf += match[0];
  1322. }
  1323. last_index = top.keywordPatternRe.lastIndex;
  1324. match = top.keywordPatternRe.exec(mode_buffer);
  1325. }
  1326. buf += mode_buffer.substr(last_index);
  1327. emitter.addText(buf);
  1328. }
  1329. function processSubLanguage() {
  1330. if (mode_buffer === "") return;
  1331. /** @type HighlightResult */
  1332. var result = null;
  1333. if (typeof top.subLanguage === 'string') {
  1334. if (!languages[top.subLanguage]) {
  1335. emitter.addText(mode_buffer);
  1336. return;
  1337. }
  1338. result = _highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]);
  1339. continuations[top.subLanguage] = result.top;
  1340. } else {
  1341. result = highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : null);
  1342. }
  1343. // Counting embedded language score towards the host language may be disabled
  1344. // with zeroing the containing mode relevance. Use case in point is Markdown that
  1345. // allows XML everywhere and makes every XML snippet to have a much larger Markdown
  1346. // score.
  1347. if (top.relevance > 0) {
  1348. relevance += result.relevance;
  1349. }
  1350. emitter.addSublanguage(result.emitter, result.language);
  1351. }
  1352. function processBuffer() {
  1353. if (top.subLanguage != null) {
  1354. processSubLanguage();
  1355. } else {
  1356. processKeywords();
  1357. }
  1358. mode_buffer = '';
  1359. }
  1360. /**
  1361. * @param {Mode} mode - new mode to start
  1362. */
  1363. function startNewMode(mode) {
  1364. if (mode.className) {
  1365. emitter.openNode(mode.className);
  1366. }
  1367. top = Object.create(mode, { parent: { value: top } });
  1368. return top;
  1369. }
  1370. /**
  1371. * @param {CompiledMode } mode - the mode to potentially end
  1372. * @param {RegExpMatchArray} match - the latest match
  1373. * @param {string} matchPlusRemainder - match plus remainder of content
  1374. * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode
  1375. */
  1376. function endOfMode(mode, match, matchPlusRemainder) {
  1377. let matched = startsWith(mode.endRe, matchPlusRemainder);
  1378. if (matched) {
  1379. if (mode["on:end"]) {
  1380. const resp = new Response(mode);
  1381. mode["on:end"](match, resp);
  1382. if (resp.ignore) matched = false;
  1383. }
  1384. if (matched) {
  1385. while (mode.endsParent && mode.parent) {
  1386. mode = mode.parent;
  1387. }
  1388. return mode;
  1389. }
  1390. }
  1391. // even if on:end fires an `ignore` it's still possible
  1392. // that we might trigger the end node because of a parent mode
  1393. if (mode.endsWithParent) {
  1394. return endOfMode(mode.parent, match, matchPlusRemainder);
  1395. }
  1396. }
  1397. /**
  1398. * Handle matching but then ignoring a sequence of text
  1399. *
  1400. * @param {string} lexeme - string containing full match text
  1401. */
  1402. function doIgnore(lexeme) {
  1403. if (top.matcher.regexIndex === 0) {
  1404. // no more regexs to potentially match here, so we move the cursor forward one
  1405. // space
  1406. mode_buffer += lexeme[0];
  1407. return 1;
  1408. } else {
  1409. // no need to move the cursor, we still have additional regexes to try and
  1410. // match at this very spot
  1411. resumeScanAtSamePosition = true;
  1412. return 0;
  1413. }
  1414. }
  1415. /**
  1416. * Handle the start of a new potential mode match
  1417. *
  1418. * @param {EnhancedMatch} match - the current match
  1419. * @returns {number} how far to advance the parse cursor
  1420. */
  1421. function doBeginMatch(match) {
  1422. var lexeme = match[0];
  1423. var new_mode = match.rule;
  1424. const resp = new Response(new_mode);
  1425. // first internal before callbacks, then the public ones
  1426. const beforeCallbacks = [new_mode.__beforeBegin, new_mode["on:begin"]];
  1427. for (const cb of beforeCallbacks) {
  1428. if (!cb) continue;
  1429. cb(match, resp);
  1430. if (resp.ignore) return doIgnore(lexeme);
  1431. }
  1432. if (new_mode && new_mode.endSameAsBegin) {
  1433. new_mode.endRe = escape(lexeme);
  1434. }
  1435. if (new_mode.skip) {
  1436. mode_buffer += lexeme;
  1437. } else {
  1438. if (new_mode.excludeBegin) {
  1439. mode_buffer += lexeme;
  1440. }
  1441. processBuffer();
  1442. if (!new_mode.returnBegin && !new_mode.excludeBegin) {
  1443. mode_buffer = lexeme;
  1444. }
  1445. }
  1446. startNewMode(new_mode);
  1447. // if (mode["after:begin"]) {
  1448. // let resp = new Response(mode);
  1449. // mode["after:begin"](match, resp);
  1450. // }
  1451. return new_mode.returnBegin ? 0 : lexeme.length;
  1452. }
  1453. /**
  1454. * Handle the potential end of mode
  1455. *
  1456. * @param {RegExpMatchArray} match - the current match
  1457. */
  1458. function doEndMatch(match) {
  1459. var lexeme = match[0];
  1460. var matchPlusRemainder = codeToHighlight.substr(match.index);
  1461. var end_mode = endOfMode(top, match, matchPlusRemainder);
  1462. if (!end_mode) { return NO_MATCH; }
  1463. var origin = top;
  1464. if (origin.skip) {
  1465. mode_buffer += lexeme;
  1466. } else {
  1467. if (!(origin.returnEnd || origin.excludeEnd)) {
  1468. mode_buffer += lexeme;
  1469. }
  1470. processBuffer();
  1471. if (origin.excludeEnd) {
  1472. mode_buffer = lexeme;
  1473. }
  1474. }
  1475. do {
  1476. if (top.className) {
  1477. emitter.closeNode();
  1478. }
  1479. if (!top.skip && !top.subLanguage) {
  1480. relevance += top.relevance;
  1481. }
  1482. top = top.parent;
  1483. } while (top !== end_mode.parent);
  1484. if (end_mode.starts) {
  1485. if (end_mode.endSameAsBegin) {
  1486. end_mode.starts.endRe = end_mode.endRe;
  1487. }
  1488. startNewMode(end_mode.starts);
  1489. }
  1490. return origin.returnEnd ? 0 : lexeme.length;
  1491. }
  1492. function processContinuations() {
  1493. var list = [];
  1494. for (var current = top; current !== language; current = current.parent) {
  1495. if (current.className) {
  1496. list.unshift(current.className);
  1497. }
  1498. }
  1499. list.forEach(item => emitter.openNode(item));
  1500. }
  1501. /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */
  1502. var lastMatch = {};
  1503. /**
  1504. * Process an individual match
  1505. *
  1506. * @param {string} textBeforeMatch - text preceeding the match (since the last match)
  1507. * @param {EnhancedMatch} [match] - the match itself
  1508. */
  1509. function processLexeme(textBeforeMatch, match) {
  1510. var lexeme = match && match[0];
  1511. // add non-matched text to the current mode buffer
  1512. mode_buffer += textBeforeMatch;
  1513. if (lexeme == null) {
  1514. processBuffer();
  1515. return 0;
  1516. }
  1517. // we've found a 0 width match and we're stuck, so we need to advance
  1518. // this happens when we have badly behaved rules that have optional matchers to the degree that
  1519. // sometimes they can end up matching nothing at all
  1520. // Ref: https://github.com/highlightjs/highlight.js/issues/2140
  1521. if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
  1522. // spit the "skipped" character that our regex choked on back into the output sequence
  1523. mode_buffer += codeToHighlight.slice(match.index, match.index + 1);
  1524. if (!SAFE_MODE) {
  1525. /** @type {AnnotatedError} */
  1526. const err = new Error('0 width match regex');
  1527. err.languageName = languageName;
  1528. err.badRule = lastMatch.rule;
  1529. throw err;
  1530. }
  1531. return 1;
  1532. }
  1533. lastMatch = match;
  1534. if (match.type === "begin") {
  1535. return doBeginMatch(match);
  1536. } else if (match.type === "illegal" && !ignoreIllegals) {
  1537. // illegal match, we do not continue processing
  1538. /** @type {AnnotatedError} */
  1539. const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');
  1540. err.mode = top;
  1541. throw err;
  1542. } else if (match.type === "end") {
  1543. var processed = doEndMatch(match);
  1544. if (processed !== NO_MATCH) {
  1545. return processed;
  1546. }
  1547. }
  1548. // edge case for when illegal matches $ (end of line) which is technically
  1549. // a 0 width match but not a begin/end match so it's not caught by the
  1550. // first handler (when ignoreIllegals is true)
  1551. if (match.type === "illegal" && lexeme === "") {
  1552. // advance so we aren't stuck in an infinite loop
  1553. return 1;
  1554. }
  1555. // infinite loops are BAD, this is a last ditch catch all. if we have a
  1556. // decent number of iterations yet our index (cursor position in our
  1557. // parsing) still 3x behind our index then something is very wrong
  1558. // so we bail
  1559. if (iterations > 100000 && iterations > match.index * 3) {
  1560. const err = new Error('potential infinite loop, way more iterations than matches');
  1561. throw err;
  1562. }
  1563. /*
  1564. Why might be find ourselves here? Only one occasion now. An end match that was
  1565. triggered but could not be completed. When might this happen? When an `endSameasBegin`
  1566. rule sets the end rule to a specific match. Since the overall mode termination rule that's
  1567. being used to scan the text isn't recompiled that means that any match that LOOKS like
  1568. the end (but is not, because it is not an exact match to the beginning) will
  1569. end up here. A definite end match, but when `doEndMatch` tries to "reapply"
  1570. the end rule and fails to match, we wind up here, and just silently ignore the end.
  1571. This causes no real harm other than stopping a few times too many.
  1572. */
  1573. mode_buffer += lexeme;
  1574. return lexeme.length;
  1575. }
  1576. var language = getLanguage(languageName);
  1577. if (!language) {
  1578. console.error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
  1579. throw new Error('Unknown language: "' + languageName + '"');
  1580. }
  1581. var md = compileLanguage(language);
  1582. var result = '';
  1583. /** @type {CompiledMode} */
  1584. var top = continuation || md;
  1585. /** @type Record<string,Mode> */
  1586. var continuations = {}; // keep continuations for sub-languages
  1587. var emitter = new options.__emitter(options);
  1588. processContinuations();
  1589. var mode_buffer = '';
  1590. var relevance = 0;
  1591. var index = 0;
  1592. var iterations = 0;
  1593. var resumeScanAtSamePosition = false;
  1594. try {
  1595. top.matcher.considerAll();
  1596. for (;;) {
  1597. iterations++;
  1598. if (resumeScanAtSamePosition) {
  1599. // only regexes not matched previously will now be
  1600. // considered for a potential match
  1601. resumeScanAtSamePosition = false;
  1602. } else {
  1603. top.matcher.considerAll();
  1604. }
  1605. top.matcher.lastIndex = index;
  1606. const match = top.matcher.exec(codeToHighlight);
  1607. // console.log("match", match[0], match.rule && match.rule.begin)
  1608. if (!match) break;
  1609. const beforeMatch = codeToHighlight.substring(index, match.index);
  1610. const processedCount = processLexeme(beforeMatch, match);
  1611. index = match.index + processedCount;
  1612. }
  1613. processLexeme(codeToHighlight.substr(index));
  1614. emitter.closeAllNodes();
  1615. emitter.finalize();
  1616. result = emitter.toHTML();
  1617. return {
  1618. relevance: relevance,
  1619. value: result,
  1620. language: languageName,
  1621. illegal: false,
  1622. emitter: emitter,
  1623. top: top
  1624. };
  1625. } catch (err) {
  1626. if (err.message && err.message.includes('Illegal')) {
  1627. return {
  1628. illegal: true,
  1629. illegalBy: {
  1630. msg: err.message,
  1631. context: codeToHighlight.slice(index - 100, index + 100),
  1632. mode: err.mode
  1633. },
  1634. sofar: result,
  1635. relevance: 0,
  1636. value: escape$1(codeToHighlight),
  1637. emitter: emitter
  1638. };
  1639. } else if (SAFE_MODE) {
  1640. return {
  1641. illegal: false,
  1642. relevance: 0,
  1643. value: escape$1(codeToHighlight),
  1644. emitter: emitter,
  1645. language: languageName,
  1646. top: top,
  1647. errorRaised: err
  1648. };
  1649. } else {
  1650. throw err;
  1651. }
  1652. }
  1653. }
  1654. /**
  1655. * returns a valid highlight result, without actually doing any actual work,
  1656. * auto highlight starts with this and it's possible for small snippets that
  1657. * auto-detection may not find a better match
  1658. * @param {string} code
  1659. * @returns {HighlightResult}
  1660. */
  1661. function justTextHighlightResult(code) {
  1662. const result = {
  1663. relevance: 0,
  1664. emitter: new options.__emitter(options),
  1665. value: escape$1(code),
  1666. illegal: false,
  1667. top: PLAINTEXT_LANGUAGE
  1668. };
  1669. result.emitter.addText(code);
  1670. return result;
  1671. }
  1672. /**
  1673. Highlighting with language detection. Accepts a string with the code to
  1674. highlight. Returns an object with the following properties:
  1675. - language (detected language)
  1676. - relevance (int)
  1677. - value (an HTML string with highlighting markup)
  1678. - second_best (object with the same structure for second-best heuristically
  1679. detected language, may be absent)
  1680. @param {string} code
  1681. @param {Array<string>} [languageSubset]
  1682. @returns {AutoHighlightResult}
  1683. */
  1684. function highlightAuto(code, languageSubset) {
  1685. languageSubset = languageSubset || options.languages || Object.keys(languages);
  1686. var result = justTextHighlightResult(code);
  1687. var secondBest = result;
  1688. languageSubset.filter(getLanguage).filter(autoDetection).forEach(function(name) {
  1689. var current = _highlight(name, code, false);
  1690. current.language = name;
  1691. if (current.relevance > secondBest.relevance) {
  1692. secondBest = current;
  1693. }
  1694. if (current.relevance > result.relevance) {
  1695. secondBest = result;
  1696. result = current;
  1697. }
  1698. });
  1699. if (secondBest.language) {
  1700. // second_best (with underscore) is the expected API
  1701. result.second_best = secondBest;
  1702. }
  1703. return result;
  1704. }
  1705. /**
  1706. Post-processing of the highlighted markup:
  1707. - replace TABs with something more useful
  1708. - replace real line-breaks with '<br>' for non-pre containers
  1709. @param {string} html
  1710. @returns {string}
  1711. */
  1712. function fixMarkup(html) {
  1713. if (!(options.tabReplace || options.useBR)) {
  1714. return html;
  1715. }
  1716. return html.replace(fixMarkupRe, match => {
  1717. if (match === '\n') {
  1718. return options.useBR ? '<br>' : match;
  1719. } else if (options.tabReplace) {
  1720. return match.replace(/\t/g, options.tabReplace);
  1721. }
  1722. return match;
  1723. });
  1724. }
  1725. /**
  1726. * Builds new class name for block given the language name
  1727. *
  1728. * @param {string} prevClassName
  1729. * @param {string} [currentLang]
  1730. * @param {string} [resultLang]
  1731. */
  1732. function buildClassName(prevClassName, currentLang, resultLang) {
  1733. var language = currentLang ? aliases[currentLang] : resultLang;
  1734. var result = [prevClassName.trim()];
  1735. if (!prevClassName.match(/\bhljs\b/)) {
  1736. result.push('hljs');
  1737. }
  1738. if (!prevClassName.includes(language)) {
  1739. result.push(language);
  1740. }
  1741. return result.join(' ').trim();
  1742. }
  1743. /**
  1744. * Applies highlighting to a DOM node containing code. Accepts a DOM node and
  1745. * two optional parameters for fixMarkup.
  1746. *
  1747. * @param {HighlightedHTMLElement} element - the HTML element to highlight
  1748. */
  1749. function highlightBlock(element) {
  1750. /** @type HTMLElement */
  1751. let node = null;
  1752. const language = blockLanguage(element);
  1753. if (shouldNotHighlight(language)) return;
  1754. fire("before:highlightBlock",
  1755. { block: element, language: language });
  1756. if (options.useBR) {
  1757. // node = document.createElement('div');
  1758. node = document.createElement('view');
  1759. node.innerHTML = element.innerHTML.replace(/\n/g, '').replace(/<br[ /]*>/g, '\n');
  1760. } else {
  1761. node = element;
  1762. }
  1763. const text = node.textContent;
  1764. const result = language ? highlight(language, text, true) : highlightAuto(text);
  1765. const originalStream = nodeStream$1(node);
  1766. if (originalStream.length) {
  1767. // const resultNode = document.createElement('div');
  1768. const resultNode = document.createElement('view');
  1769. resultNode.innerHTML = result.value;
  1770. result.value = mergeStreams$1(originalStream, nodeStream$1(resultNode), text);
  1771. }
  1772. result.value = fixMarkup(result.value);
  1773. fire("after:highlightBlock", { block: element, result: result });
  1774. element.innerHTML = result.value;
  1775. element.className = buildClassName(element.className, language, result.language);
  1776. element.result = {
  1777. language: result.language,
  1778. // TODO: remove with version 11.0
  1779. re: result.relevance,
  1780. relavance: result.relevance
  1781. };
  1782. if (result.second_best) {
  1783. element.second_best = {
  1784. language: result.second_best.language,
  1785. // TODO: remove with version 11.0
  1786. re: result.second_best.relevance,
  1787. relavance: result.second_best.relevance
  1788. };
  1789. }
  1790. }
  1791. /**
  1792. * Updates highlight.js global options with the passed options
  1793. *
  1794. * @param {{}} userOptions
  1795. */
  1796. function configure(userOptions) {
  1797. options = inherit$1(options, userOptions);
  1798. }
  1799. /**
  1800. * Highlights to all <pre><code> blocks on a page
  1801. *
  1802. * @type {Function & {called?: boolean}}
  1803. */
  1804. const initHighlighting = () => {
  1805. if (initHighlighting.called) return;
  1806. initHighlighting.called = true;
  1807. var blocks = document.querySelectorAll('pre code')
  1808. };
  1809. // Higlights all when DOMContentLoaded fires
  1810. function initHighlightingOnLoad() {
  1811. // @ts-ignore
  1812. window.addEventListener('DOMContentLoaded', initHighlighting, false);
  1813. }
  1814. /**
  1815. * Register a language grammar module
  1816. *
  1817. * @param {string} languageName
  1818. * @param {LanguageFn} languageDefinition
  1819. */
  1820. function registerLanguage(languageName, languageDefinition) {
  1821. var lang = null;
  1822. try {
  1823. lang = languageDefinition(hljs);
  1824. } catch (error) {
  1825. console.error("Language definition for '{}' could not be registered.".replace("{}", languageName));
  1826. // hard or soft error
  1827. if (!SAFE_MODE) { throw error; } else { console.error(error); }
  1828. // languages that have serious errors are replaced with essentially a
  1829. // "plaintext" stand-in so that the code blocks will still get normal
  1830. // css classes applied to them - and one bad language won't break the
  1831. // entire highlighter
  1832. lang = PLAINTEXT_LANGUAGE;
  1833. }
  1834. // give it a temporary name if it doesn't have one in the meta-data
  1835. if (!lang.name) lang.name = languageName;
  1836. languages[languageName] = lang;
  1837. lang.rawDefinition = languageDefinition.bind(null, hljs);
  1838. if (lang.aliases) {
  1839. registerAliases(lang.aliases, { languageName });
  1840. }
  1841. }
  1842. /**
  1843. * @returns {string[]} List of language internal names
  1844. */
  1845. function listLanguages() {
  1846. return Object.keys(languages);
  1847. }
  1848. /**
  1849. intended usage: When one language truly requires another
  1850. Unlike `getLanguage`, this will throw when the requested language
  1851. is not available.
  1852. @param {string} name - name of the language to fetch/require
  1853. @returns {Language | never}
  1854. */
  1855. function requireLanguage(name) {
  1856. var lang = getLanguage(name);
  1857. if (lang) { return lang; }
  1858. var err = new Error('The \'{}\' language is required, but not loaded.'.replace('{}', name));
  1859. throw err;
  1860. }
  1861. /**
  1862. * @param {string} name - name of the language to retrieve
  1863. * @returns {Language | undefined}
  1864. */
  1865. function getLanguage(name) {
  1866. name = (name || '').toLowerCase();
  1867. return languages[name] || languages[aliases[name]];
  1868. }
  1869. /**
  1870. *
  1871. * @param {string|string[]} aliasList - single alias or list of aliases
  1872. * @param {{languageName: string}} opts
  1873. */
  1874. function registerAliases(aliasList, { languageName }) {
  1875. if (typeof aliasList === 'string') {
  1876. aliasList = [aliasList];
  1877. }
  1878. aliasList.forEach(alias => { aliases[alias] = languageName; });
  1879. }
  1880. /**
  1881. * Determines if a given language has auto-detection enabled
  1882. * @param {string} name - name of the language
  1883. */
  1884. function autoDetection(name) {
  1885. var lang = getLanguage(name);
  1886. return lang && !lang.disableAutodetect;
  1887. }
  1888. /**
  1889. * @param {HLJSPlugin} plugin
  1890. */
  1891. function addPlugin(plugin) {
  1892. plugins.push(plugin);
  1893. }
  1894. /**
  1895. *
  1896. * @param {PluginEvent} event
  1897. * @param {any} args
  1898. */
  1899. function fire(event, args) {
  1900. var cb = event;
  1901. plugins.forEach(function(plugin) {
  1902. if (plugin[cb]) {
  1903. plugin[cb](args);
  1904. }
  1905. });
  1906. }
  1907. /* fixMarkup is deprecated and will be removed entirely in v11 */
  1908. function deprecate_fixMarkup(arg) {
  1909. console.warn("fixMarkup is deprecated and will be removed entirely in v11.0");
  1910. console.warn("Please see https://github.com/highlightjs/highlight.js/issues/2534");
  1911. return fixMarkup(arg)
  1912. }
  1913. /* Interface definition */
  1914. Object.assign(hljs, {
  1915. highlight,
  1916. highlightAuto,
  1917. fixMarkup: deprecate_fixMarkup,
  1918. highlightBlock,
  1919. configure,
  1920. initHighlighting,
  1921. initHighlightingOnLoad,
  1922. registerLanguage,
  1923. listLanguages,
  1924. getLanguage,
  1925. registerAliases,
  1926. requireLanguage,
  1927. autoDetection,
  1928. inherit: inherit$1,
  1929. addPlugin,
  1930. // plugins for frameworks
  1931. vuePlugin: VuePlugin
  1932. });
  1933. hljs.debugMode = function() { SAFE_MODE = false; };
  1934. hljs.safeMode = function() { SAFE_MODE = true; };
  1935. hljs.versionString = version;
  1936. for (const key in MODES) {
  1937. // @ts-ignore
  1938. if (typeof MODES[key] === "object") {
  1939. // @ts-ignore
  1940. deepFreeze(MODES[key]);
  1941. }
  1942. }
  1943. // merge all the modes/regexs into our main object
  1944. Object.assign(hljs, MODES);
  1945. return hljs;
  1946. };
  1947. // export an "instance" of the highlighter
  1948. var highlight = HLJS({});
  1949. module.exports = highlight;