@tiptap/extension-code-block-lowlight 2.0.0-beta.54 → 2.0.0-beta.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3009 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tiptap/extension-code-block'), require('prosemirror-state'), require('prosemirror-view'), require('@tiptap/core')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tiptap/extension-code-block', 'prosemirror-state', 'prosemirror-view', '@tiptap/core'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@tiptap/extension-code-block-lowlight"] = {}, global.CodeBlock, global.prosemirrorState, global.prosemirrorView, global.core$2));
5
+ })(this, (function (exports, CodeBlock, prosemirrorState, prosemirrorView, core$2) { 'use strict';
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var CodeBlock__default = /*#__PURE__*/_interopDefaultLegacy(CodeBlock);
10
+
11
+ var core$1 = {};
12
+
13
+ function deepFreeze(obj) {
14
+ if (obj instanceof Map) {
15
+ obj.clear = obj.delete = obj.set = function () {
16
+ throw new Error('map is read-only');
17
+ };
18
+ } else if (obj instanceof Set) {
19
+ obj.add = obj.clear = obj.delete = function () {
20
+ throw new Error('set is read-only');
21
+ };
22
+ }
23
+
24
+ // Freeze self
25
+ Object.freeze(obj);
26
+
27
+ Object.getOwnPropertyNames(obj).forEach(function (name) {
28
+ var prop = obj[name];
29
+
30
+ // Freeze prop if it is an object
31
+ if (typeof prop == 'object' && !Object.isFrozen(prop)) {
32
+ deepFreeze(prop);
33
+ }
34
+ });
35
+
36
+ return obj;
37
+ }
38
+
39
+ var deepFreezeEs6 = deepFreeze;
40
+ var _default = deepFreeze;
41
+ deepFreezeEs6.default = _default;
42
+
43
+ /** @implements CallbackResponse */
44
+ class Response {
45
+ /**
46
+ * @param {CompiledMode} mode
47
+ */
48
+ constructor(mode) {
49
+ // eslint-disable-next-line no-undefined
50
+ if (mode.data === undefined) mode.data = {};
51
+
52
+ this.data = mode.data;
53
+ this.isMatchIgnored = false;
54
+ }
55
+
56
+ ignoreMatch() {
57
+ this.isMatchIgnored = true;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * @param {string} value
63
+ * @returns {string}
64
+ */
65
+ function escapeHTML(value) {
66
+ return value
67
+ .replace(/&/g, '&')
68
+ .replace(/</g, '&lt;')
69
+ .replace(/>/g, '&gt;')
70
+ .replace(/"/g, '&quot;')
71
+ .replace(/'/g, '&#x27;');
72
+ }
73
+
74
+ /**
75
+ * performs a shallow merge of multiple objects into one
76
+ *
77
+ * @template T
78
+ * @param {T} original
79
+ * @param {Record<string,any>[]} objects
80
+ * @returns {T} a single new object
81
+ */
82
+ function inherit(original, ...objects) {
83
+ /** @type Record<string,any> */
84
+ const result = Object.create(null);
85
+
86
+ for (const key in original) {
87
+ result[key] = original[key];
88
+ }
89
+ objects.forEach(function(obj) {
90
+ for (const key in obj) {
91
+ result[key] = obj[key];
92
+ }
93
+ });
94
+ return /** @type {T} */ (result);
95
+ }
96
+
97
+ /**
98
+ * @typedef {object} Renderer
99
+ * @property {(text: string) => void} addText
100
+ * @property {(node: Node) => void} openNode
101
+ * @property {(node: Node) => void} closeNode
102
+ * @property {() => string} value
103
+ */
104
+
105
+ /** @typedef {{kind?: string, sublanguage?: boolean}} Node */
106
+ /** @typedef {{walk: (r: Renderer) => void}} Tree */
107
+ /** */
108
+
109
+ const SPAN_CLOSE = '</span>';
110
+
111
+ /**
112
+ * Determines if a node needs to be wrapped in <span>
113
+ *
114
+ * @param {Node} node */
115
+ const emitsWrappingTags = (node) => {
116
+ return !!node.kind;
117
+ };
118
+
119
+ /** @type {Renderer} */
120
+ class HTMLRenderer {
121
+ /**
122
+ * Creates a new HTMLRenderer
123
+ *
124
+ * @param {Tree} parseTree - the parse tree (must support `walk` API)
125
+ * @param {{classPrefix: string}} options
126
+ */
127
+ constructor(parseTree, options) {
128
+ this.buffer = "";
129
+ this.classPrefix = options.classPrefix;
130
+ parseTree.walk(this);
131
+ }
132
+
133
+ /**
134
+ * Adds texts to the output stream
135
+ *
136
+ * @param {string} text */
137
+ addText(text) {
138
+ this.buffer += escapeHTML(text);
139
+ }
140
+
141
+ /**
142
+ * Adds a node open to the output stream (if needed)
143
+ *
144
+ * @param {Node} node */
145
+ openNode(node) {
146
+ if (!emitsWrappingTags(node)) return;
147
+
148
+ let className = node.kind;
149
+ if (!node.sublanguage) {
150
+ className = `${this.classPrefix}${className}`;
151
+ }
152
+ this.span(className);
153
+ }
154
+
155
+ /**
156
+ * Adds a node close to the output stream (if needed)
157
+ *
158
+ * @param {Node} node */
159
+ closeNode(node) {
160
+ if (!emitsWrappingTags(node)) return;
161
+
162
+ this.buffer += SPAN_CLOSE;
163
+ }
164
+
165
+ /**
166
+ * returns the accumulated buffer
167
+ */
168
+ value() {
169
+ return this.buffer;
170
+ }
171
+
172
+ // helpers
173
+
174
+ /**
175
+ * Builds a span element
176
+ *
177
+ * @param {string} className */
178
+ span(className) {
179
+ this.buffer += `<span class="${className}">`;
180
+ }
181
+ }
182
+
183
+ /** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} | string} Node */
184
+ /** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} } DataNode */
185
+ /** */
186
+
187
+ class TokenTree {
188
+ constructor() {
189
+ /** @type DataNode */
190
+ this.rootNode = { children: [] };
191
+ this.stack = [this.rootNode];
192
+ }
193
+
194
+ get top() {
195
+ return this.stack[this.stack.length - 1];
196
+ }
197
+
198
+ get root() { return this.rootNode; }
199
+
200
+ /** @param {Node} node */
201
+ add(node) {
202
+ this.top.children.push(node);
203
+ }
204
+
205
+ /** @param {string} kind */
206
+ openNode(kind) {
207
+ /** @type Node */
208
+ const node = { kind, children: [] };
209
+ this.add(node);
210
+ this.stack.push(node);
211
+ }
212
+
213
+ closeNode() {
214
+ if (this.stack.length > 1) {
215
+ return this.stack.pop();
216
+ }
217
+ // eslint-disable-next-line no-undefined
218
+ return undefined;
219
+ }
220
+
221
+ closeAllNodes() {
222
+ while (this.closeNode());
223
+ }
224
+
225
+ toJSON() {
226
+ return JSON.stringify(this.rootNode, null, 4);
227
+ }
228
+
229
+ /**
230
+ * @typedef { import("./html_renderer").Renderer } Renderer
231
+ * @param {Renderer} builder
232
+ */
233
+ walk(builder) {
234
+ // this does not
235
+ return this.constructor._walk(builder, this.rootNode);
236
+ // this works
237
+ // return TokenTree._walk(builder, this.rootNode);
238
+ }
239
+
240
+ /**
241
+ * @param {Renderer} builder
242
+ * @param {Node} node
243
+ */
244
+ static _walk(builder, node) {
245
+ if (typeof node === "string") {
246
+ builder.addText(node);
247
+ } else if (node.children) {
248
+ builder.openNode(node);
249
+ node.children.forEach((child) => this._walk(builder, child));
250
+ builder.closeNode(node);
251
+ }
252
+ return builder;
253
+ }
254
+
255
+ /**
256
+ * @param {Node} node
257
+ */
258
+ static _collapse(node) {
259
+ if (typeof node === "string") return;
260
+ if (!node.children) return;
261
+
262
+ if (node.children.every(el => typeof el === "string")) {
263
+ // node.text = node.children.join("");
264
+ // delete node.children;
265
+ node.children = [node.children.join("")];
266
+ } else {
267
+ node.children.forEach((child) => {
268
+ TokenTree._collapse(child);
269
+ });
270
+ }
271
+ }
272
+ }
273
+
274
+ /**
275
+ Currently this is all private API, but this is the minimal API necessary
276
+ that an Emitter must implement to fully support the parser.
277
+
278
+ Minimal interface:
279
+
280
+ - addKeyword(text, kind)
281
+ - addText(text)
282
+ - addSublanguage(emitter, subLanguageName)
283
+ - finalize()
284
+ - openNode(kind)
285
+ - closeNode()
286
+ - closeAllNodes()
287
+ - toHTML()
288
+
289
+ */
290
+
291
+ /**
292
+ * @implements {Emitter}
293
+ */
294
+ class TokenTreeEmitter extends TokenTree {
295
+ /**
296
+ * @param {*} options
297
+ */
298
+ constructor(options) {
299
+ super();
300
+ this.options = options;
301
+ }
302
+
303
+ /**
304
+ * @param {string} text
305
+ * @param {string} kind
306
+ */
307
+ addKeyword(text, kind) {
308
+ if (text === "") { return; }
309
+
310
+ this.openNode(kind);
311
+ this.addText(text);
312
+ this.closeNode();
313
+ }
314
+
315
+ /**
316
+ * @param {string} text
317
+ */
318
+ addText(text) {
319
+ if (text === "") { return; }
320
+
321
+ this.add(text);
322
+ }
323
+
324
+ /**
325
+ * @param {Emitter & {root: DataNode}} emitter
326
+ * @param {string} name
327
+ */
328
+ addSublanguage(emitter, name) {
329
+ /** @type DataNode */
330
+ const node = emitter.root;
331
+ node.kind = name;
332
+ node.sublanguage = true;
333
+ this.add(node);
334
+ }
335
+
336
+ toHTML() {
337
+ const renderer = new HTMLRenderer(this, this.options);
338
+ return renderer.value();
339
+ }
340
+
341
+ finalize() {
342
+ return true;
343
+ }
344
+ }
345
+
346
+ /**
347
+ * @param {string} value
348
+ * @returns {RegExp}
349
+ * */
350
+ function escape(value) {
351
+ return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm');
352
+ }
353
+
354
+ /**
355
+ * @param {RegExp | string } re
356
+ * @returns {string}
357
+ */
358
+ function source(re) {
359
+ if (!re) return null;
360
+ if (typeof re === "string") return re;
361
+
362
+ return re.source;
363
+ }
364
+
365
+ /**
366
+ * @param {...(RegExp | string) } args
367
+ * @returns {string}
368
+ */
369
+ function concat(...args) {
370
+ const joined = args.map((x) => source(x)).join("");
371
+ return joined;
372
+ }
373
+
374
+ /**
375
+ * Any of the passed expresssions may match
376
+ *
377
+ * Creates a huge this | this | that | that match
378
+ * @param {(RegExp | string)[] } args
379
+ * @returns {string}
380
+ */
381
+ function either(...args) {
382
+ const joined = '(' + args.map((x) => source(x)).join("|") + ")";
383
+ return joined;
384
+ }
385
+
386
+ /**
387
+ * @param {RegExp} re
388
+ * @returns {number}
389
+ */
390
+ function countMatchGroups(re) {
391
+ return (new RegExp(re.toString() + '|')).exec('').length - 1;
392
+ }
393
+
394
+ /**
395
+ * Does lexeme start with a regular expression match at the beginning
396
+ * @param {RegExp} re
397
+ * @param {string} lexeme
398
+ */
399
+ function startsWith(re, lexeme) {
400
+ const match = re && re.exec(lexeme);
401
+ return match && match.index === 0;
402
+ }
403
+
404
+ // BACKREF_RE matches an open parenthesis or backreference. To avoid
405
+ // an incorrect parse, it additionally matches the following:
406
+ // - [...] elements, where the meaning of parentheses and escapes change
407
+ // - other escape sequences, so we do not misparse escape sequences as
408
+ // interesting elements
409
+ // - non-matching or lookahead parentheses, which do not capture. These
410
+ // follow the '(' with a '?'.
411
+ const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
412
+
413
+ // join logically computes regexps.join(separator), but fixes the
414
+ // backreferences so they continue to match.
415
+ // it also places each individual regular expression into it's own
416
+ // match group, keeping track of the sequencing of those match groups
417
+ // is currently an exercise for the caller. :-)
418
+ /**
419
+ * @param {(string | RegExp)[]} regexps
420
+ * @param {string} separator
421
+ * @returns {string}
422
+ */
423
+ function join(regexps, separator = "|") {
424
+ let numCaptures = 0;
425
+
426
+ return regexps.map((regex) => {
427
+ numCaptures += 1;
428
+ const offset = numCaptures;
429
+ let re = source(regex);
430
+ let out = '';
431
+
432
+ while (re.length > 0) {
433
+ const match = BACKREF_RE.exec(re);
434
+ if (!match) {
435
+ out += re;
436
+ break;
437
+ }
438
+ out += re.substring(0, match.index);
439
+ re = re.substring(match.index + match[0].length);
440
+ if (match[0][0] === '\\' && match[1]) {
441
+ // Adjust the backreference.
442
+ out += '\\' + String(Number(match[1]) + offset);
443
+ } else {
444
+ out += match[0];
445
+ if (match[0] === '(') {
446
+ numCaptures++;
447
+ }
448
+ }
449
+ }
450
+ return out;
451
+ }).map(re => `(${re})`).join(separator);
452
+ }
453
+
454
+ // Common regexps
455
+ const MATCH_NOTHING_RE = /\b\B/;
456
+ const IDENT_RE = '[a-zA-Z]\\w*';
457
+ const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
458
+ const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
459
+ const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
460
+ const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
461
+ const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
462
+
463
+ /**
464
+ * @param { Partial<Mode> & {binary?: string | RegExp} } opts
465
+ */
466
+ const SHEBANG = (opts = {}) => {
467
+ const beginShebang = /^#![ ]*\//;
468
+ if (opts.binary) {
469
+ opts.begin = concat(
470
+ beginShebang,
471
+ /.*\b/,
472
+ opts.binary,
473
+ /\b.*/);
474
+ }
475
+ return inherit({
476
+ className: 'meta',
477
+ begin: beginShebang,
478
+ end: /$/,
479
+ relevance: 0,
480
+ /** @type {ModeCallback} */
481
+ "on:begin": (m, resp) => {
482
+ if (m.index !== 0) resp.ignoreMatch();
483
+ }
484
+ }, opts);
485
+ };
486
+
487
+ // Common modes
488
+ const BACKSLASH_ESCAPE = {
489
+ begin: '\\\\[\\s\\S]', relevance: 0
490
+ };
491
+ const APOS_STRING_MODE = {
492
+ className: 'string',
493
+ begin: '\'',
494
+ end: '\'',
495
+ illegal: '\\n',
496
+ contains: [BACKSLASH_ESCAPE]
497
+ };
498
+ const QUOTE_STRING_MODE = {
499
+ className: 'string',
500
+ begin: '"',
501
+ end: '"',
502
+ illegal: '\\n',
503
+ contains: [BACKSLASH_ESCAPE]
504
+ };
505
+ const PHRASAL_WORDS_MODE = {
506
+ begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/
507
+ };
508
+ /**
509
+ * Creates a comment mode
510
+ *
511
+ * @param {string | RegExp} begin
512
+ * @param {string | RegExp} end
513
+ * @param {Mode | {}} [modeOptions]
514
+ * @returns {Partial<Mode>}
515
+ */
516
+ const COMMENT = function(begin, end, modeOptions = {}) {
517
+ const mode = inherit(
518
+ {
519
+ className: 'comment',
520
+ begin,
521
+ end,
522
+ contains: []
523
+ },
524
+ modeOptions
525
+ );
526
+ mode.contains.push(PHRASAL_WORDS_MODE);
527
+ mode.contains.push({
528
+ className: 'doctag',
529
+ begin: '(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):',
530
+ relevance: 0
531
+ });
532
+ return mode;
533
+ };
534
+ const C_LINE_COMMENT_MODE = COMMENT('//', '$');
535
+ const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
536
+ const HASH_COMMENT_MODE = COMMENT('#', '$');
537
+ const NUMBER_MODE = {
538
+ className: 'number',
539
+ begin: NUMBER_RE,
540
+ relevance: 0
541
+ };
542
+ const C_NUMBER_MODE = {
543
+ className: 'number',
544
+ begin: C_NUMBER_RE,
545
+ relevance: 0
546
+ };
547
+ const BINARY_NUMBER_MODE = {
548
+ className: 'number',
549
+ begin: BINARY_NUMBER_RE,
550
+ relevance: 0
551
+ };
552
+ const CSS_NUMBER_MODE = {
553
+ className: 'number',
554
+ begin: NUMBER_RE + '(' +
555
+ '%|em|ex|ch|rem' +
556
+ '|vw|vh|vmin|vmax' +
557
+ '|cm|mm|in|pt|pc|px' +
558
+ '|deg|grad|rad|turn' +
559
+ '|s|ms' +
560
+ '|Hz|kHz' +
561
+ '|dpi|dpcm|dppx' +
562
+ ')?',
563
+ relevance: 0
564
+ };
565
+ const REGEXP_MODE = {
566
+ // this outer rule makes sure we actually have a WHOLE regex and not simply
567
+ // an expression such as:
568
+ //
569
+ // 3 / something
570
+ //
571
+ // (which will then blow up when regex's `illegal` sees the newline)
572
+ begin: /(?=\/[^/\n]*\/)/,
573
+ contains: [{
574
+ className: 'regexp',
575
+ begin: /\//,
576
+ end: /\/[gimuy]*/,
577
+ illegal: /\n/,
578
+ contains: [
579
+ BACKSLASH_ESCAPE,
580
+ {
581
+ begin: /\[/,
582
+ end: /\]/,
583
+ relevance: 0,
584
+ contains: [BACKSLASH_ESCAPE]
585
+ }
586
+ ]
587
+ }]
588
+ };
589
+ const TITLE_MODE = {
590
+ className: 'title',
591
+ begin: IDENT_RE,
592
+ relevance: 0
593
+ };
594
+ const UNDERSCORE_TITLE_MODE = {
595
+ className: 'title',
596
+ begin: UNDERSCORE_IDENT_RE,
597
+ relevance: 0
598
+ };
599
+ const METHOD_GUARD = {
600
+ // excludes method names from keyword processing
601
+ begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
602
+ relevance: 0
603
+ };
604
+
605
+ /**
606
+ * Adds end same as begin mechanics to a mode
607
+ *
608
+ * Your mode must include at least a single () match group as that first match
609
+ * group is what is used for comparison
610
+ * @param {Partial<Mode>} mode
611
+ */
612
+ const END_SAME_AS_BEGIN = function(mode) {
613
+ return Object.assign(mode,
614
+ {
615
+ /** @type {ModeCallback} */
616
+ 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
617
+ /** @type {ModeCallback} */
618
+ 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
619
+ });
620
+ };
621
+
622
+ var MODES = /*#__PURE__*/Object.freeze({
623
+ __proto__: null,
624
+ MATCH_NOTHING_RE: MATCH_NOTHING_RE,
625
+ IDENT_RE: IDENT_RE,
626
+ UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
627
+ NUMBER_RE: NUMBER_RE,
628
+ C_NUMBER_RE: C_NUMBER_RE,
629
+ BINARY_NUMBER_RE: BINARY_NUMBER_RE,
630
+ RE_STARTERS_RE: RE_STARTERS_RE,
631
+ SHEBANG: SHEBANG,
632
+ BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
633
+ APOS_STRING_MODE: APOS_STRING_MODE,
634
+ QUOTE_STRING_MODE: QUOTE_STRING_MODE,
635
+ PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
636
+ COMMENT: COMMENT,
637
+ C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
638
+ C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
639
+ HASH_COMMENT_MODE: HASH_COMMENT_MODE,
640
+ NUMBER_MODE: NUMBER_MODE,
641
+ C_NUMBER_MODE: C_NUMBER_MODE,
642
+ BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
643
+ CSS_NUMBER_MODE: CSS_NUMBER_MODE,
644
+ REGEXP_MODE: REGEXP_MODE,
645
+ TITLE_MODE: TITLE_MODE,
646
+ UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE,
647
+ METHOD_GUARD: METHOD_GUARD,
648
+ END_SAME_AS_BEGIN: END_SAME_AS_BEGIN
649
+ });
650
+
651
+ // Grammar extensions / plugins
652
+ // See: https://github.com/highlightjs/highlight.js/issues/2833
653
+
654
+ // Grammar extensions allow "syntactic sugar" to be added to the grammar modes
655
+ // without requiring any underlying changes to the compiler internals.
656
+
657
+ // `compileMatch` being the perfect small example of now allowing a grammar
658
+ // author to write `match` when they desire to match a single expression rather
659
+ // than being forced to use `begin`. The extension then just moves `match` into
660
+ // `begin` when it runs. Ie, no features have been added, but we've just made
661
+ // the experience of writing (and reading grammars) a little bit nicer.
662
+
663
+ // ------
664
+
665
+ // TODO: We need negative look-behind support to do this properly
666
+ /**
667
+ * Skip a match if it has a preceding dot
668
+ *
669
+ * This is used for `beginKeywords` to prevent matching expressions such as
670
+ * `bob.keyword.do()`. The mode compiler automatically wires this up as a
671
+ * special _internal_ 'on:begin' callback for modes with `beginKeywords`
672
+ * @param {RegExpMatchArray} match
673
+ * @param {CallbackResponse} response
674
+ */
675
+ function skipIfhasPrecedingDot(match, response) {
676
+ const before = match.input[match.index - 1];
677
+ if (before === ".") {
678
+ response.ignoreMatch();
679
+ }
680
+ }
681
+
682
+
683
+ /**
684
+ * `beginKeywords` syntactic sugar
685
+ * @type {CompilerExt}
686
+ */
687
+ function beginKeywords(mode, parent) {
688
+ if (!parent) return;
689
+ if (!mode.beginKeywords) return;
690
+
691
+ // for languages with keywords that include non-word characters checking for
692
+ // a word boundary is not sufficient, so instead we check for a word boundary
693
+ // or whitespace - this does no harm in any case since our keyword engine
694
+ // doesn't allow spaces in keywords anyways and we still check for the boundary
695
+ // first
696
+ mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)';
697
+ mode.__beforeBegin = skipIfhasPrecedingDot;
698
+ mode.keywords = mode.keywords || mode.beginKeywords;
699
+ delete mode.beginKeywords;
700
+
701
+ // prevents double relevance, the keywords themselves provide
702
+ // relevance, the mode doesn't need to double it
703
+ // eslint-disable-next-line no-undefined
704
+ if (mode.relevance === undefined) mode.relevance = 0;
705
+ }
706
+
707
+ /**
708
+ * Allow `illegal` to contain an array of illegal values
709
+ * @type {CompilerExt}
710
+ */
711
+ function compileIllegal(mode, _parent) {
712
+ if (!Array.isArray(mode.illegal)) return;
713
+
714
+ mode.illegal = either(...mode.illegal);
715
+ }
716
+
717
+ /**
718
+ * `match` to match a single expression for readability
719
+ * @type {CompilerExt}
720
+ */
721
+ function compileMatch(mode, _parent) {
722
+ if (!mode.match) return;
723
+ if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
724
+
725
+ mode.begin = mode.match;
726
+ delete mode.match;
727
+ }
728
+
729
+ /**
730
+ * provides the default 1 relevance to all modes
731
+ * @type {CompilerExt}
732
+ */
733
+ function compileRelevance(mode, _parent) {
734
+ // eslint-disable-next-line no-undefined
735
+ if (mode.relevance === undefined) mode.relevance = 1;
736
+ }
737
+
738
+ // keywords that should have no default relevance value
739
+ const COMMON_KEYWORDS = [
740
+ 'of',
741
+ 'and',
742
+ 'for',
743
+ 'in',
744
+ 'not',
745
+ 'or',
746
+ 'if',
747
+ 'then',
748
+ 'parent', // common variable name
749
+ 'list', // common variable name
750
+ 'value' // common variable name
751
+ ];
752
+
753
+ const DEFAULT_KEYWORD_CLASSNAME = "keyword";
754
+
755
+ /**
756
+ * Given raw keywords from a language definition, compile them.
757
+ *
758
+ * @param {string | Record<string,string|string[]> | Array<string>} rawKeywords
759
+ * @param {boolean} caseInsensitive
760
+ */
761
+ function compileKeywords(rawKeywords, caseInsensitive, className = DEFAULT_KEYWORD_CLASSNAME) {
762
+ /** @type KeywordDict */
763
+ const compiledKeywords = {};
764
+
765
+ // input can be a string of keywords, an array of keywords, or a object with
766
+ // named keys representing className (which can then point to a string or array)
767
+ if (typeof rawKeywords === 'string') {
768
+ compileList(className, rawKeywords.split(" "));
769
+ } else if (Array.isArray(rawKeywords)) {
770
+ compileList(className, rawKeywords);
771
+ } else {
772
+ Object.keys(rawKeywords).forEach(function(className) {
773
+ // collapse all our objects back into the parent object
774
+ Object.assign(
775
+ compiledKeywords,
776
+ compileKeywords(rawKeywords[className], caseInsensitive, className)
777
+ );
778
+ });
779
+ }
780
+ return compiledKeywords;
781
+
782
+ // ---
783
+
784
+ /**
785
+ * Compiles an individual list of keywords
786
+ *
787
+ * Ex: "for if when while|5"
788
+ *
789
+ * @param {string} className
790
+ * @param {Array<string>} keywordList
791
+ */
792
+ function compileList(className, keywordList) {
793
+ if (caseInsensitive) {
794
+ keywordList = keywordList.map(x => x.toLowerCase());
795
+ }
796
+ keywordList.forEach(function(keyword) {
797
+ const pair = keyword.split('|');
798
+ compiledKeywords[pair[0]] = [className, scoreForKeyword(pair[0], pair[1])];
799
+ });
800
+ }
801
+ }
802
+
803
+ /**
804
+ * Returns the proper score for a given keyword
805
+ *
806
+ * Also takes into account comment keywords, which will be scored 0 UNLESS
807
+ * another score has been manually assigned.
808
+ * @param {string} keyword
809
+ * @param {string} [providedScore]
810
+ */
811
+ function scoreForKeyword(keyword, providedScore) {
812
+ // manual scores always win over common keywords
813
+ // so you can force a score of 1 if you really insist
814
+ if (providedScore) {
815
+ return Number(providedScore);
816
+ }
817
+
818
+ return commonKeyword(keyword) ? 0 : 1;
819
+ }
820
+
821
+ /**
822
+ * Determines if a given keyword is common or not
823
+ *
824
+ * @param {string} keyword */
825
+ function commonKeyword(keyword) {
826
+ return COMMON_KEYWORDS.includes(keyword.toLowerCase());
827
+ }
828
+
829
+ // compilation
830
+
831
+ /**
832
+ * Compiles a language definition result
833
+ *
834
+ * Given the raw result of a language definition (Language), compiles this so
835
+ * that it is ready for highlighting code.
836
+ * @param {Language} language
837
+ * @param {{plugins: HLJSPlugin[]}} opts
838
+ * @returns {CompiledLanguage}
839
+ */
840
+ function compileLanguage(language, { plugins }) {
841
+ /**
842
+ * Builds a regex with the case sensativility of the current language
843
+ *
844
+ * @param {RegExp | string} value
845
+ * @param {boolean} [global]
846
+ */
847
+ function langRe(value, global) {
848
+ return new RegExp(
849
+ source(value),
850
+ 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '')
851
+ );
852
+ }
853
+
854
+ /**
855
+ Stores multiple regular expressions and allows you to quickly search for
856
+ them all in a string simultaneously - returning the first match. It does
857
+ this by creating a huge (a|b|c) regex - each individual item wrapped with ()
858
+ and joined by `|` - using match groups to track position. When a match is
859
+ found checking which position in the array has content allows us to figure
860
+ out which of the original regexes / match groups triggered the match.
861
+
862
+ The match object itself (the result of `Regex.exec`) is returned but also
863
+ enhanced by merging in any meta-data that was registered with the regex.
864
+ This is how we keep track of which mode matched, and what type of rule
865
+ (`illegal`, `begin`, end, etc).
866
+ */
867
+ class MultiRegex {
868
+ constructor() {
869
+ this.matchIndexes = {};
870
+ // @ts-ignore
871
+ this.regexes = [];
872
+ this.matchAt = 1;
873
+ this.position = 0;
874
+ }
875
+
876
+ // @ts-ignore
877
+ addRule(re, opts) {
878
+ opts.position = this.position++;
879
+ // @ts-ignore
880
+ this.matchIndexes[this.matchAt] = opts;
881
+ this.regexes.push([opts, re]);
882
+ this.matchAt += countMatchGroups(re) + 1;
883
+ }
884
+
885
+ compile() {
886
+ if (this.regexes.length === 0) {
887
+ // avoids the need to check length every time exec is called
888
+ // @ts-ignore
889
+ this.exec = () => null;
890
+ }
891
+ const terminators = this.regexes.map(el => el[1]);
892
+ this.matcherRe = langRe(join(terminators), true);
893
+ this.lastIndex = 0;
894
+ }
895
+
896
+ /** @param {string} s */
897
+ exec(s) {
898
+ this.matcherRe.lastIndex = this.lastIndex;
899
+ const match = this.matcherRe.exec(s);
900
+ if (!match) { return null; }
901
+
902
+ // eslint-disable-next-line no-undefined
903
+ const i = match.findIndex((el, i) => i > 0 && el !== undefined);
904
+ // @ts-ignore
905
+ const matchData = this.matchIndexes[i];
906
+ // trim off any earlier non-relevant match groups (ie, the other regex
907
+ // match groups that make up the multi-matcher)
908
+ match.splice(0, i);
909
+
910
+ return Object.assign(match, matchData);
911
+ }
912
+ }
913
+
914
+ /*
915
+ Created to solve the key deficiently with MultiRegex - there is no way to
916
+ test for multiple matches at a single location. Why would we need to do
917
+ that? In the future a more dynamic engine will allow certain matches to be
918
+ ignored. An example: if we matched say the 3rd regex in a large group but
919
+ decided to ignore it - we'd need to started testing again at the 4th
920
+ regex... but MultiRegex itself gives us no real way to do that.
921
+
922
+ So what this class creates MultiRegexs on the fly for whatever search
923
+ position they are needed.
924
+
925
+ NOTE: These additional MultiRegex objects are created dynamically. For most
926
+ grammars most of the time we will never actually need anything more than the
927
+ first MultiRegex - so this shouldn't have too much overhead.
928
+
929
+ Say this is our search group, and we match regex3, but wish to ignore it.
930
+
931
+ regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0
932
+
933
+ What we need is a new MultiRegex that only includes the remaining
934
+ possibilities:
935
+
936
+ regex4 | regex5 ' ie, startAt = 3
937
+
938
+ This class wraps all that complexity up in a simple API... `startAt` decides
939
+ where in the array of expressions to start doing the matching. It
940
+ auto-increments, so if a match is found at position 2, then startAt will be
941
+ set to 3. If the end is reached startAt will return to 0.
942
+
943
+ MOST of the time the parser will be setting startAt manually to 0.
944
+ */
945
+ class ResumableMultiRegex {
946
+ constructor() {
947
+ // @ts-ignore
948
+ this.rules = [];
949
+ // @ts-ignore
950
+ this.multiRegexes = [];
951
+ this.count = 0;
952
+
953
+ this.lastIndex = 0;
954
+ this.regexIndex = 0;
955
+ }
956
+
957
+ // @ts-ignore
958
+ getMatcher(index) {
959
+ if (this.multiRegexes[index]) return this.multiRegexes[index];
960
+
961
+ const matcher = new MultiRegex();
962
+ this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts));
963
+ matcher.compile();
964
+ this.multiRegexes[index] = matcher;
965
+ return matcher;
966
+ }
967
+
968
+ resumingScanAtSamePosition() {
969
+ return this.regexIndex !== 0;
970
+ }
971
+
972
+ considerAll() {
973
+ this.regexIndex = 0;
974
+ }
975
+
976
+ // @ts-ignore
977
+ addRule(re, opts) {
978
+ this.rules.push([re, opts]);
979
+ if (opts.type === "begin") this.count++;
980
+ }
981
+
982
+ /** @param {string} s */
983
+ exec(s) {
984
+ const m = this.getMatcher(this.regexIndex);
985
+ m.lastIndex = this.lastIndex;
986
+ let result = m.exec(s);
987
+
988
+ // The following is because we have no easy way to say "resume scanning at the
989
+ // existing position but also skip the current rule ONLY". What happens is
990
+ // all prior rules are also skipped which can result in matching the wrong
991
+ // thing. Example of matching "booger":
992
+
993
+ // our matcher is [string, "booger", number]
994
+ //
995
+ // ....booger....
996
+
997
+ // if "booger" is ignored then we'd really need a regex to scan from the
998
+ // SAME position for only: [string, number] but ignoring "booger" (if it
999
+ // was the first match), a simple resume would scan ahead who knows how
1000
+ // far looking only for "number", ignoring potential string matches (or
1001
+ // future "booger" matches that might be valid.)
1002
+
1003
+ // So what we do: We execute two matchers, one resuming at the same
1004
+ // position, but the second full matcher starting at the position after:
1005
+
1006
+ // /--- resume first regex match here (for [number])
1007
+ // |/---- full match here for [string, "booger", number]
1008
+ // vv
1009
+ // ....booger....
1010
+
1011
+ // Which ever results in a match first is then used. So this 3-4 step
1012
+ // process essentially allows us to say "match at this position, excluding
1013
+ // a prior rule that was ignored".
1014
+ //
1015
+ // 1. Match "booger" first, ignore. Also proves that [string] does non match.
1016
+ // 2. Resume matching for [number]
1017
+ // 3. Match at index + 1 for [string, "booger", number]
1018
+ // 4. If #2 and #3 result in matches, which came first?
1019
+ if (this.resumingScanAtSamePosition()) {
1020
+ if (result && result.index === this.lastIndex) ; else { // use the second matcher result
1021
+ const m2 = this.getMatcher(0);
1022
+ m2.lastIndex = this.lastIndex + 1;
1023
+ result = m2.exec(s);
1024
+ }
1025
+ }
1026
+
1027
+ if (result) {
1028
+ this.regexIndex += result.position + 1;
1029
+ if (this.regexIndex === this.count) {
1030
+ // wrap-around to considering all matches again
1031
+ this.considerAll();
1032
+ }
1033
+ }
1034
+
1035
+ return result;
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * Given a mode, builds a huge ResumableMultiRegex that can be used to walk
1041
+ * the content and find matches.
1042
+ *
1043
+ * @param {CompiledMode} mode
1044
+ * @returns {ResumableMultiRegex}
1045
+ */
1046
+ function buildModeRegex(mode) {
1047
+ const mm = new ResumableMultiRegex();
1048
+
1049
+ mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" }));
1050
+
1051
+ if (mode.terminatorEnd) {
1052
+ mm.addRule(mode.terminatorEnd, { type: "end" });
1053
+ }
1054
+ if (mode.illegal) {
1055
+ mm.addRule(mode.illegal, { type: "illegal" });
1056
+ }
1057
+
1058
+ return mm;
1059
+ }
1060
+
1061
+ /** skip vs abort vs ignore
1062
+ *
1063
+ * @skip - The mode is still entered and exited normally (and contains rules apply),
1064
+ * but all content is held and added to the parent buffer rather than being
1065
+ * output when the mode ends. Mostly used with `sublanguage` to build up
1066
+ * a single large buffer than can be parsed by sublanguage.
1067
+ *
1068
+ * - The mode begin ands ends normally.
1069
+ * - Content matched is added to the parent mode buffer.
1070
+ * - The parser cursor is moved forward normally.
1071
+ *
1072
+ * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it
1073
+ * never matched) but DOES NOT continue to match subsequent `contains`
1074
+ * modes. Abort is bad/suboptimal because it can result in modes
1075
+ * farther down not getting applied because an earlier rule eats the
1076
+ * content but then aborts.
1077
+ *
1078
+ * - The mode does not begin.
1079
+ * - Content matched by `begin` is added to the mode buffer.
1080
+ * - The parser cursor is moved forward accordingly.
1081
+ *
1082
+ * @ignore - Ignores the mode (as if it never matched) and continues to match any
1083
+ * subsequent `contains` modes. Ignore isn't technically possible with
1084
+ * the current parser implementation.
1085
+ *
1086
+ * - The mode does not begin.
1087
+ * - Content matched by `begin` is ignored.
1088
+ * - The parser cursor is not moved forward.
1089
+ */
1090
+
1091
+ /**
1092
+ * Compiles an individual mode
1093
+ *
1094
+ * This can raise an error if the mode contains certain detectable known logic
1095
+ * issues.
1096
+ * @param {Mode} mode
1097
+ * @param {CompiledMode | null} [parent]
1098
+ * @returns {CompiledMode | never}
1099
+ */
1100
+ function compileMode(mode, parent) {
1101
+ const cmode = /** @type CompiledMode */ (mode);
1102
+ if (mode.isCompiled) return cmode;
1103
+
1104
+ [
1105
+ // do this early so compiler extensions generally don't have to worry about
1106
+ // the distinction between match/begin
1107
+ compileMatch
1108
+ ].forEach(ext => ext(mode, parent));
1109
+
1110
+ language.compilerExtensions.forEach(ext => ext(mode, parent));
1111
+
1112
+ // __beforeBegin is considered private API, internal use only
1113
+ mode.__beforeBegin = null;
1114
+
1115
+ [
1116
+ beginKeywords,
1117
+ // do this later so compiler extensions that come earlier have access to the
1118
+ // raw array if they wanted to perhaps manipulate it, etc.
1119
+ compileIllegal,
1120
+ // default to 1 relevance if not specified
1121
+ compileRelevance
1122
+ ].forEach(ext => ext(mode, parent));
1123
+
1124
+ mode.isCompiled = true;
1125
+
1126
+ let keywordPattern = null;
1127
+ if (typeof mode.keywords === "object") {
1128
+ keywordPattern = mode.keywords.$pattern;
1129
+ delete mode.keywords.$pattern;
1130
+ }
1131
+
1132
+ if (mode.keywords) {
1133
+ mode.keywords = compileKeywords(mode.keywords, language.case_insensitive);
1134
+ }
1135
+
1136
+ // both are not allowed
1137
+ if (mode.lexemes && keywordPattern) {
1138
+ throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) ");
1139
+ }
1140
+
1141
+ // `mode.lexemes` was the old standard before we added and now recommend
1142
+ // using `keywords.$pattern` to pass the keyword pattern
1143
+ keywordPattern = keywordPattern || mode.lexemes || /\w+/;
1144
+ cmode.keywordPatternRe = langRe(keywordPattern, true);
1145
+
1146
+ if (parent) {
1147
+ if (!mode.begin) mode.begin = /\B|\b/;
1148
+ cmode.beginRe = langRe(mode.begin);
1149
+ if (mode.endSameAsBegin) mode.end = mode.begin;
1150
+ if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/;
1151
+ if (mode.end) cmode.endRe = langRe(mode.end);
1152
+ cmode.terminatorEnd = source(mode.end) || '';
1153
+ if (mode.endsWithParent && parent.terminatorEnd) {
1154
+ cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd;
1155
+ }
1156
+ }
1157
+ if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal));
1158
+ if (!mode.contains) mode.contains = [];
1159
+
1160
+ mode.contains = [].concat(...mode.contains.map(function(c) {
1161
+ return expandOrCloneMode(c === 'self' ? mode : c);
1162
+ }));
1163
+ mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); });
1164
+
1165
+ if (mode.starts) {
1166
+ compileMode(mode.starts, parent);
1167
+ }
1168
+
1169
+ cmode.matcher = buildModeRegex(cmode);
1170
+ return cmode;
1171
+ }
1172
+
1173
+ if (!language.compilerExtensions) language.compilerExtensions = [];
1174
+
1175
+ // self is not valid at the top-level
1176
+ if (language.contains && language.contains.includes('self')) {
1177
+ throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");
1178
+ }
1179
+
1180
+ // we need a null object, which inherit will guarantee
1181
+ language.classNameAliases = inherit(language.classNameAliases || {});
1182
+
1183
+ return compileMode(/** @type Mode */ (language));
1184
+ }
1185
+
1186
+ /**
1187
+ * Determines if a mode has a dependency on it's parent or not
1188
+ *
1189
+ * If a mode does have a parent dependency then often we need to clone it if
1190
+ * it's used in multiple places so that each copy points to the correct parent,
1191
+ * where-as modes without a parent can often safely be re-used at the bottom of
1192
+ * a mode chain.
1193
+ *
1194
+ * @param {Mode | null} mode
1195
+ * @returns {boolean} - is there a dependency on the parent?
1196
+ * */
1197
+ function dependencyOnParent(mode) {
1198
+ if (!mode) return false;
1199
+
1200
+ return mode.endsWithParent || dependencyOnParent(mode.starts);
1201
+ }
1202
+
1203
+ /**
1204
+ * Expands a mode or clones it if necessary
1205
+ *
1206
+ * This is necessary for modes with parental dependenceis (see notes on
1207
+ * `dependencyOnParent`) and for nodes that have `variants` - which must then be
1208
+ * exploded into their own individual modes at compile time.
1209
+ *
1210
+ * @param {Mode} mode
1211
+ * @returns {Mode | Mode[]}
1212
+ * */
1213
+ function expandOrCloneMode(mode) {
1214
+ if (mode.variants && !mode.cachedVariants) {
1215
+ mode.cachedVariants = mode.variants.map(function(variant) {
1216
+ return inherit(mode, { variants: null }, variant);
1217
+ });
1218
+ }
1219
+
1220
+ // EXPAND
1221
+ // if we have variants then essentially "replace" the mode with the variants
1222
+ // this happens in compileMode, where this function is called from
1223
+ if (mode.cachedVariants) {
1224
+ return mode.cachedVariants;
1225
+ }
1226
+
1227
+ // CLONE
1228
+ // if we have dependencies on parents then we need a unique
1229
+ // instance of ourselves, so we can be reused with many
1230
+ // different parents without issue
1231
+ if (dependencyOnParent(mode)) {
1232
+ return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null });
1233
+ }
1234
+
1235
+ if (Object.isFrozen(mode)) {
1236
+ return inherit(mode);
1237
+ }
1238
+
1239
+ // no special dependency issues, just return ourselves
1240
+ return mode;
1241
+ }
1242
+
1243
+ var version = "10.7.3";
1244
+
1245
+ // @ts-nocheck
1246
+
1247
+ function hasValueOrEmptyAttribute(value) {
1248
+ return Boolean(value || value === "");
1249
+ }
1250
+
1251
+ function BuildVuePlugin(hljs) {
1252
+ const Component = {
1253
+ props: ["language", "code", "autodetect"],
1254
+ data: function() {
1255
+ return {
1256
+ detectedLanguage: "",
1257
+ unknownLanguage: false
1258
+ };
1259
+ },
1260
+ computed: {
1261
+ className() {
1262
+ if (this.unknownLanguage) return "";
1263
+
1264
+ return "hljs " + this.detectedLanguage;
1265
+ },
1266
+ highlighted() {
1267
+ // no idea what language to use, return raw code
1268
+ if (!this.autoDetect && !hljs.getLanguage(this.language)) {
1269
+ console.warn(`The language "${this.language}" you specified could not be found.`);
1270
+ this.unknownLanguage = true;
1271
+ return escapeHTML(this.code);
1272
+ }
1273
+
1274
+ let result = {};
1275
+ if (this.autoDetect) {
1276
+ result = hljs.highlightAuto(this.code);
1277
+ this.detectedLanguage = result.language;
1278
+ } else {
1279
+ result = hljs.highlight(this.language, this.code, this.ignoreIllegals);
1280
+ this.detectedLanguage = this.language;
1281
+ }
1282
+ return result.value;
1283
+ },
1284
+ autoDetect() {
1285
+ return !this.language || hasValueOrEmptyAttribute(this.autodetect);
1286
+ },
1287
+ ignoreIllegals() {
1288
+ return true;
1289
+ }
1290
+ },
1291
+ // this avoids needing to use a whole Vue compilation pipeline just
1292
+ // to build Highlight.js
1293
+ render(createElement) {
1294
+ return createElement("pre", {}, [
1295
+ createElement("code", {
1296
+ class: this.className,
1297
+ domProps: { innerHTML: this.highlighted }
1298
+ })
1299
+ ]);
1300
+ }
1301
+ // template: `<pre><code :class="className" v-html="highlighted"></code></pre>`
1302
+ };
1303
+
1304
+ const VuePlugin = {
1305
+ install(Vue) {
1306
+ Vue.component('highlightjs', Component);
1307
+ }
1308
+ };
1309
+
1310
+ return { Component, VuePlugin };
1311
+ }
1312
+
1313
+ /* plugin itself */
1314
+
1315
+ /** @type {HLJSPlugin} */
1316
+ const mergeHTMLPlugin = {
1317
+ "after:highlightElement": ({ el, result, text }) => {
1318
+ const originalStream = nodeStream(el);
1319
+ if (!originalStream.length) return;
1320
+
1321
+ const resultNode = document.createElement('div');
1322
+ resultNode.innerHTML = result.value;
1323
+ result.value = mergeStreams(originalStream, nodeStream(resultNode), text);
1324
+ }
1325
+ };
1326
+
1327
+ /* Stream merging support functions */
1328
+
1329
+ /**
1330
+ * @typedef Event
1331
+ * @property {'start'|'stop'} event
1332
+ * @property {number} offset
1333
+ * @property {Node} node
1334
+ */
1335
+
1336
+ /**
1337
+ * @param {Node} node
1338
+ */
1339
+ function tag(node) {
1340
+ return node.nodeName.toLowerCase();
1341
+ }
1342
+
1343
+ /**
1344
+ * @param {Node} node
1345
+ */
1346
+ function nodeStream(node) {
1347
+ /** @type Event[] */
1348
+ const result = [];
1349
+ (function _nodeStream(node, offset) {
1350
+ for (let child = node.firstChild; child; child = child.nextSibling) {
1351
+ if (child.nodeType === 3) {
1352
+ offset += child.nodeValue.length;
1353
+ } else if (child.nodeType === 1) {
1354
+ result.push({
1355
+ event: 'start',
1356
+ offset: offset,
1357
+ node: child
1358
+ });
1359
+ offset = _nodeStream(child, offset);
1360
+ // Prevent void elements from having an end tag that would actually
1361
+ // double them in the output. There are more void elements in HTML
1362
+ // but we list only those realistically expected in code display.
1363
+ if (!tag(child).match(/br|hr|img|input/)) {
1364
+ result.push({
1365
+ event: 'stop',
1366
+ offset: offset,
1367
+ node: child
1368
+ });
1369
+ }
1370
+ }
1371
+ }
1372
+ return offset;
1373
+ })(node, 0);
1374
+ return result;
1375
+ }
1376
+
1377
+ /**
1378
+ * @param {any} original - the original stream
1379
+ * @param {any} highlighted - stream of the highlighted source
1380
+ * @param {string} value - the original source itself
1381
+ */
1382
+ function mergeStreams(original, highlighted, value) {
1383
+ let processed = 0;
1384
+ let result = '';
1385
+ const nodeStack = [];
1386
+
1387
+ function selectStream() {
1388
+ if (!original.length || !highlighted.length) {
1389
+ return original.length ? original : highlighted;
1390
+ }
1391
+ if (original[0].offset !== highlighted[0].offset) {
1392
+ return (original[0].offset < highlighted[0].offset) ? original : highlighted;
1393
+ }
1394
+
1395
+ /*
1396
+ To avoid starting the stream just before it should stop the order is
1397
+ ensured that original always starts first and closes last:
1398
+
1399
+ if (event1 == 'start' && event2 == 'start')
1400
+ return original;
1401
+ if (event1 == 'start' && event2 == 'stop')
1402
+ return highlighted;
1403
+ if (event1 == 'stop' && event2 == 'start')
1404
+ return original;
1405
+ if (event1 == 'stop' && event2 == 'stop')
1406
+ return highlighted;
1407
+
1408
+ ... which is collapsed to:
1409
+ */
1410
+ return highlighted[0].event === 'start' ? original : highlighted;
1411
+ }
1412
+
1413
+ /**
1414
+ * @param {Node} node
1415
+ */
1416
+ function open(node) {
1417
+ /** @param {Attr} attr */
1418
+ function attributeString(attr) {
1419
+ return ' ' + attr.nodeName + '="' + escapeHTML(attr.value) + '"';
1420
+ }
1421
+ // @ts-ignore
1422
+ result += '<' + tag(node) + [].map.call(node.attributes, attributeString).join('') + '>';
1423
+ }
1424
+
1425
+ /**
1426
+ * @param {Node} node
1427
+ */
1428
+ function close(node) {
1429
+ result += '</' + tag(node) + '>';
1430
+ }
1431
+
1432
+ /**
1433
+ * @param {Event} event
1434
+ */
1435
+ function render(event) {
1436
+ (event.event === 'start' ? open : close)(event.node);
1437
+ }
1438
+
1439
+ while (original.length || highlighted.length) {
1440
+ let stream = selectStream();
1441
+ result += escapeHTML(value.substring(processed, stream[0].offset));
1442
+ processed = stream[0].offset;
1443
+ if (stream === original) {
1444
+ /*
1445
+ On any opening or closing tag of the original markup we first close
1446
+ the entire highlighted node stack, then render the original tag along
1447
+ with all the following original tags at the same offset and then
1448
+ reopen all the tags on the highlighted stack.
1449
+ */
1450
+ nodeStack.reverse().forEach(close);
1451
+ do {
1452
+ render(stream.splice(0, 1)[0]);
1453
+ stream = selectStream();
1454
+ } while (stream === original && stream.length && stream[0].offset === processed);
1455
+ nodeStack.reverse().forEach(open);
1456
+ } else {
1457
+ if (stream[0].event === 'start') {
1458
+ nodeStack.push(stream[0].node);
1459
+ } else {
1460
+ nodeStack.pop();
1461
+ }
1462
+ render(stream.splice(0, 1)[0]);
1463
+ }
1464
+ }
1465
+ return result + escapeHTML(value.substr(processed));
1466
+ }
1467
+
1468
+ /*
1469
+
1470
+ For the reasoning behind this please see:
1471
+ https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419
1472
+
1473
+ */
1474
+
1475
+ /**
1476
+ * @type {Record<string, boolean>}
1477
+ */
1478
+ const seenDeprecations = {};
1479
+
1480
+ /**
1481
+ * @param {string} message
1482
+ */
1483
+ const error = (message) => {
1484
+ console.error(message);
1485
+ };
1486
+
1487
+ /**
1488
+ * @param {string} message
1489
+ * @param {any} args
1490
+ */
1491
+ const warn = (message, ...args) => {
1492
+ console.log(`WARN: ${message}`, ...args);
1493
+ };
1494
+
1495
+ /**
1496
+ * @param {string} version
1497
+ * @param {string} message
1498
+ */
1499
+ const deprecated = (version, message) => {
1500
+ if (seenDeprecations[`${version}/${message}`]) return;
1501
+
1502
+ console.log(`Deprecated as of ${version}. ${message}`);
1503
+ seenDeprecations[`${version}/${message}`] = true;
1504
+ };
1505
+
1506
+ /*
1507
+ Syntax highlighting with language autodetection.
1508
+ https://highlightjs.org/
1509
+ */
1510
+
1511
+ const escape$1 = escapeHTML;
1512
+ const inherit$1 = inherit;
1513
+ const NO_MATCH = Symbol("nomatch");
1514
+
1515
+ /**
1516
+ * @param {any} hljs - object that is extended (legacy)
1517
+ * @returns {HLJSApi}
1518
+ */
1519
+ const HLJS = function(hljs) {
1520
+ // Global internal variables used within the highlight.js library.
1521
+ /** @type {Record<string, Language>} */
1522
+ const languages = Object.create(null);
1523
+ /** @type {Record<string, string>} */
1524
+ const aliases = Object.create(null);
1525
+ /** @type {HLJSPlugin[]} */
1526
+ const plugins = [];
1527
+
1528
+ // safe/production mode - swallows more errors, tries to keep running
1529
+ // even if a single syntax or parse hits a fatal error
1530
+ let SAFE_MODE = true;
1531
+ const fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm;
1532
+ const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?";
1533
+ /** @type {Language} */
1534
+ const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] };
1535
+
1536
+ // Global options used when within external APIs. This is modified when
1537
+ // calling the `hljs.configure` function.
1538
+ /** @type HLJSOptions */
1539
+ let options = {
1540
+ noHighlightRe: /^(no-?highlight)$/i,
1541
+ languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i,
1542
+ classPrefix: 'hljs-',
1543
+ tabReplace: null,
1544
+ useBR: false,
1545
+ languages: null,
1546
+ // beta configuration options, subject to change, welcome to discuss
1547
+ // https://github.com/highlightjs/highlight.js/issues/1086
1548
+ __emitter: TokenTreeEmitter
1549
+ };
1550
+
1551
+ /* Utility functions */
1552
+
1553
+ /**
1554
+ * Tests a language name to see if highlighting should be skipped
1555
+ * @param {string} languageName
1556
+ */
1557
+ function shouldNotHighlight(languageName) {
1558
+ return options.noHighlightRe.test(languageName);
1559
+ }
1560
+
1561
+ /**
1562
+ * @param {HighlightedHTMLElement} block - the HTML element to determine language for
1563
+ */
1564
+ function blockLanguage(block) {
1565
+ let classes = block.className + ' ';
1566
+
1567
+ classes += block.parentNode ? block.parentNode.className : '';
1568
+
1569
+ // language-* takes precedence over non-prefixed class names.
1570
+ const match = options.languageDetectRe.exec(classes);
1571
+ if (match) {
1572
+ const language = getLanguage(match[1]);
1573
+ if (!language) {
1574
+ warn(LANGUAGE_NOT_FOUND.replace("{}", match[1]));
1575
+ warn("Falling back to no-highlight mode for this block.", block);
1576
+ }
1577
+ return language ? match[1] : 'no-highlight';
1578
+ }
1579
+
1580
+ return classes
1581
+ .split(/\s+/)
1582
+ .find((_class) => shouldNotHighlight(_class) || getLanguage(_class));
1583
+ }
1584
+
1585
+ /**
1586
+ * Core highlighting function.
1587
+ *
1588
+ * OLD API
1589
+ * highlight(lang, code, ignoreIllegals, continuation)
1590
+ *
1591
+ * NEW API
1592
+ * highlight(code, {lang, ignoreIllegals})
1593
+ *
1594
+ * @param {string} codeOrlanguageName - the language to use for highlighting
1595
+ * @param {string | HighlightOptions} optionsOrCode - the code to highlight
1596
+ * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
1597
+ * @param {CompiledMode} [continuation] - current continuation mode, if any
1598
+ *
1599
+ * @returns {HighlightResult} Result - an object that represents the result
1600
+ * @property {string} language - the language name
1601
+ * @property {number} relevance - the relevance score
1602
+ * @property {string} value - the highlighted HTML code
1603
+ * @property {string} code - the original raw code
1604
+ * @property {CompiledMode} top - top of the current mode stack
1605
+ * @property {boolean} illegal - indicates whether any illegal matches were found
1606
+ */
1607
+ function highlight(codeOrlanguageName, optionsOrCode, ignoreIllegals, continuation) {
1608
+ let code = "";
1609
+ let languageName = "";
1610
+ if (typeof optionsOrCode === "object") {
1611
+ code = codeOrlanguageName;
1612
+ ignoreIllegals = optionsOrCode.ignoreIllegals;
1613
+ languageName = optionsOrCode.language;
1614
+ // continuation not supported at all via the new API
1615
+ // eslint-disable-next-line no-undefined
1616
+ continuation = undefined;
1617
+ } else {
1618
+ // old API
1619
+ deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated.");
1620
+ deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277");
1621
+ languageName = codeOrlanguageName;
1622
+ code = optionsOrCode;
1623
+ }
1624
+
1625
+ /** @type {BeforeHighlightContext} */
1626
+ const context = {
1627
+ code,
1628
+ language: languageName
1629
+ };
1630
+ // the plugin can change the desired language or the code to be highlighted
1631
+ // just be changing the object it was passed
1632
+ fire("before:highlight", context);
1633
+
1634
+ // a before plugin can usurp the result completely by providing it's own
1635
+ // in which case we don't even need to call highlight
1636
+ const result = context.result
1637
+ ? context.result
1638
+ : _highlight(context.language, context.code, ignoreIllegals, continuation);
1639
+
1640
+ result.code = context.code;
1641
+ // the plugin can change anything in result to suite it
1642
+ fire("after:highlight", result);
1643
+
1644
+ return result;
1645
+ }
1646
+
1647
+ /**
1648
+ * private highlight that's used internally and does not fire callbacks
1649
+ *
1650
+ * @param {string} languageName - the language to use for highlighting
1651
+ * @param {string} codeToHighlight - the code to highlight
1652
+ * @param {boolean?} [ignoreIllegals] - whether to ignore illegal matches, default is to bail
1653
+ * @param {CompiledMode?} [continuation] - current continuation mode, if any
1654
+ * @returns {HighlightResult} - result of the highlight operation
1655
+ */
1656
+ function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) {
1657
+ /**
1658
+ * Return keyword data if a match is a keyword
1659
+ * @param {CompiledMode} mode - current mode
1660
+ * @param {RegExpMatchArray} match - regexp match data
1661
+ * @returns {KeywordData | false}
1662
+ */
1663
+ function keywordData(mode, match) {
1664
+ const matchText = language.case_insensitive ? match[0].toLowerCase() : match[0];
1665
+ return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText];
1666
+ }
1667
+
1668
+ function processKeywords() {
1669
+ if (!top.keywords) {
1670
+ emitter.addText(modeBuffer);
1671
+ return;
1672
+ }
1673
+
1674
+ let lastIndex = 0;
1675
+ top.keywordPatternRe.lastIndex = 0;
1676
+ let match = top.keywordPatternRe.exec(modeBuffer);
1677
+ let buf = "";
1678
+
1679
+ while (match) {
1680
+ buf += modeBuffer.substring(lastIndex, match.index);
1681
+ const data = keywordData(top, match);
1682
+ if (data) {
1683
+ const [kind, keywordRelevance] = data;
1684
+ emitter.addText(buf);
1685
+ buf = "";
1686
+
1687
+ relevance += keywordRelevance;
1688
+ if (kind.startsWith("_")) {
1689
+ // _ implied for relevance only, do not highlight
1690
+ // by applying a class name
1691
+ buf += match[0];
1692
+ } else {
1693
+ const cssClass = language.classNameAliases[kind] || kind;
1694
+ emitter.addKeyword(match[0], cssClass);
1695
+ }
1696
+ } else {
1697
+ buf += match[0];
1698
+ }
1699
+ lastIndex = top.keywordPatternRe.lastIndex;
1700
+ match = top.keywordPatternRe.exec(modeBuffer);
1701
+ }
1702
+ buf += modeBuffer.substr(lastIndex);
1703
+ emitter.addText(buf);
1704
+ }
1705
+
1706
+ function processSubLanguage() {
1707
+ if (modeBuffer === "") return;
1708
+ /** @type HighlightResult */
1709
+ let result = null;
1710
+
1711
+ if (typeof top.subLanguage === 'string') {
1712
+ if (!languages[top.subLanguage]) {
1713
+ emitter.addText(modeBuffer);
1714
+ return;
1715
+ }
1716
+ result = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]);
1717
+ continuations[top.subLanguage] = /** @type {CompiledMode} */ (result.top);
1718
+ } else {
1719
+ result = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null);
1720
+ }
1721
+
1722
+ // Counting embedded language score towards the host language may be disabled
1723
+ // with zeroing the containing mode relevance. Use case in point is Markdown that
1724
+ // allows XML everywhere and makes every XML snippet to have a much larger Markdown
1725
+ // score.
1726
+ if (top.relevance > 0) {
1727
+ relevance += result.relevance;
1728
+ }
1729
+ emitter.addSublanguage(result.emitter, result.language);
1730
+ }
1731
+
1732
+ function processBuffer() {
1733
+ if (top.subLanguage != null) {
1734
+ processSubLanguage();
1735
+ } else {
1736
+ processKeywords();
1737
+ }
1738
+ modeBuffer = '';
1739
+ }
1740
+
1741
+ /**
1742
+ * @param {Mode} mode - new mode to start
1743
+ */
1744
+ function startNewMode(mode) {
1745
+ if (mode.className) {
1746
+ emitter.openNode(language.classNameAliases[mode.className] || mode.className);
1747
+ }
1748
+ top = Object.create(mode, { parent: { value: top } });
1749
+ return top;
1750
+ }
1751
+
1752
+ /**
1753
+ * @param {CompiledMode } mode - the mode to potentially end
1754
+ * @param {RegExpMatchArray} match - the latest match
1755
+ * @param {string} matchPlusRemainder - match plus remainder of content
1756
+ * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode
1757
+ */
1758
+ function endOfMode(mode, match, matchPlusRemainder) {
1759
+ let matched = startsWith(mode.endRe, matchPlusRemainder);
1760
+
1761
+ if (matched) {
1762
+ if (mode["on:end"]) {
1763
+ const resp = new Response(mode);
1764
+ mode["on:end"](match, resp);
1765
+ if (resp.isMatchIgnored) matched = false;
1766
+ }
1767
+
1768
+ if (matched) {
1769
+ while (mode.endsParent && mode.parent) {
1770
+ mode = mode.parent;
1771
+ }
1772
+ return mode;
1773
+ }
1774
+ }
1775
+ // even if on:end fires an `ignore` it's still possible
1776
+ // that we might trigger the end node because of a parent mode
1777
+ if (mode.endsWithParent) {
1778
+ return endOfMode(mode.parent, match, matchPlusRemainder);
1779
+ }
1780
+ }
1781
+
1782
+ /**
1783
+ * Handle matching but then ignoring a sequence of text
1784
+ *
1785
+ * @param {string} lexeme - string containing full match text
1786
+ */
1787
+ function doIgnore(lexeme) {
1788
+ if (top.matcher.regexIndex === 0) {
1789
+ // no more regexs to potentially match here, so we move the cursor forward one
1790
+ // space
1791
+ modeBuffer += lexeme[0];
1792
+ return 1;
1793
+ } else {
1794
+ // no need to move the cursor, we still have additional regexes to try and
1795
+ // match at this very spot
1796
+ resumeScanAtSamePosition = true;
1797
+ return 0;
1798
+ }
1799
+ }
1800
+
1801
+ /**
1802
+ * Handle the start of a new potential mode match
1803
+ *
1804
+ * @param {EnhancedMatch} match - the current match
1805
+ * @returns {number} how far to advance the parse cursor
1806
+ */
1807
+ function doBeginMatch(match) {
1808
+ const lexeme = match[0];
1809
+ const newMode = match.rule;
1810
+
1811
+ const resp = new Response(newMode);
1812
+ // first internal before callbacks, then the public ones
1813
+ const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]];
1814
+ for (const cb of beforeCallbacks) {
1815
+ if (!cb) continue;
1816
+ cb(match, resp);
1817
+ if (resp.isMatchIgnored) return doIgnore(lexeme);
1818
+ }
1819
+
1820
+ if (newMode && newMode.endSameAsBegin) {
1821
+ newMode.endRe = escape(lexeme);
1822
+ }
1823
+
1824
+ if (newMode.skip) {
1825
+ modeBuffer += lexeme;
1826
+ } else {
1827
+ if (newMode.excludeBegin) {
1828
+ modeBuffer += lexeme;
1829
+ }
1830
+ processBuffer();
1831
+ if (!newMode.returnBegin && !newMode.excludeBegin) {
1832
+ modeBuffer = lexeme;
1833
+ }
1834
+ }
1835
+ startNewMode(newMode);
1836
+ // if (mode["after:begin"]) {
1837
+ // let resp = new Response(mode);
1838
+ // mode["after:begin"](match, resp);
1839
+ // }
1840
+ return newMode.returnBegin ? 0 : lexeme.length;
1841
+ }
1842
+
1843
+ /**
1844
+ * Handle the potential end of mode
1845
+ *
1846
+ * @param {RegExpMatchArray} match - the current match
1847
+ */
1848
+ function doEndMatch(match) {
1849
+ const lexeme = match[0];
1850
+ const matchPlusRemainder = codeToHighlight.substr(match.index);
1851
+
1852
+ const endMode = endOfMode(top, match, matchPlusRemainder);
1853
+ if (!endMode) { return NO_MATCH; }
1854
+
1855
+ const origin = top;
1856
+ if (origin.skip) {
1857
+ modeBuffer += lexeme;
1858
+ } else {
1859
+ if (!(origin.returnEnd || origin.excludeEnd)) {
1860
+ modeBuffer += lexeme;
1861
+ }
1862
+ processBuffer();
1863
+ if (origin.excludeEnd) {
1864
+ modeBuffer = lexeme;
1865
+ }
1866
+ }
1867
+ do {
1868
+ if (top.className) {
1869
+ emitter.closeNode();
1870
+ }
1871
+ if (!top.skip && !top.subLanguage) {
1872
+ relevance += top.relevance;
1873
+ }
1874
+ top = top.parent;
1875
+ } while (top !== endMode.parent);
1876
+ if (endMode.starts) {
1877
+ if (endMode.endSameAsBegin) {
1878
+ endMode.starts.endRe = endMode.endRe;
1879
+ }
1880
+ startNewMode(endMode.starts);
1881
+ }
1882
+ return origin.returnEnd ? 0 : lexeme.length;
1883
+ }
1884
+
1885
+ function processContinuations() {
1886
+ const list = [];
1887
+ for (let current = top; current !== language; current = current.parent) {
1888
+ if (current.className) {
1889
+ list.unshift(current.className);
1890
+ }
1891
+ }
1892
+ list.forEach(item => emitter.openNode(item));
1893
+ }
1894
+
1895
+ /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */
1896
+ let lastMatch = {};
1897
+
1898
+ /**
1899
+ * Process an individual match
1900
+ *
1901
+ * @param {string} textBeforeMatch - text preceeding the match (since the last match)
1902
+ * @param {EnhancedMatch} [match] - the match itself
1903
+ */
1904
+ function processLexeme(textBeforeMatch, match) {
1905
+ const lexeme = match && match[0];
1906
+
1907
+ // add non-matched text to the current mode buffer
1908
+ modeBuffer += textBeforeMatch;
1909
+
1910
+ if (lexeme == null) {
1911
+ processBuffer();
1912
+ return 0;
1913
+ }
1914
+
1915
+ // we've found a 0 width match and we're stuck, so we need to advance
1916
+ // this happens when we have badly behaved rules that have optional matchers to the degree that
1917
+ // sometimes they can end up matching nothing at all
1918
+ // Ref: https://github.com/highlightjs/highlight.js/issues/2140
1919
+ if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") {
1920
+ // spit the "skipped" character that our regex choked on back into the output sequence
1921
+ modeBuffer += codeToHighlight.slice(match.index, match.index + 1);
1922
+ if (!SAFE_MODE) {
1923
+ /** @type {AnnotatedError} */
1924
+ const err = new Error('0 width match regex');
1925
+ err.languageName = languageName;
1926
+ err.badRule = lastMatch.rule;
1927
+ throw err;
1928
+ }
1929
+ return 1;
1930
+ }
1931
+ lastMatch = match;
1932
+
1933
+ if (match.type === "begin") {
1934
+ return doBeginMatch(match);
1935
+ } else if (match.type === "illegal" && !ignoreIllegals) {
1936
+ // illegal match, we do not continue processing
1937
+ /** @type {AnnotatedError} */
1938
+ const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '<unnamed>') + '"');
1939
+ err.mode = top;
1940
+ throw err;
1941
+ } else if (match.type === "end") {
1942
+ const processed = doEndMatch(match);
1943
+ if (processed !== NO_MATCH) {
1944
+ return processed;
1945
+ }
1946
+ }
1947
+
1948
+ // edge case for when illegal matches $ (end of line) which is technically
1949
+ // a 0 width match but not a begin/end match so it's not caught by the
1950
+ // first handler (when ignoreIllegals is true)
1951
+ if (match.type === "illegal" && lexeme === "") {
1952
+ // advance so we aren't stuck in an infinite loop
1953
+ return 1;
1954
+ }
1955
+
1956
+ // infinite loops are BAD, this is a last ditch catch all. if we have a
1957
+ // decent number of iterations yet our index (cursor position in our
1958
+ // parsing) still 3x behind our index then something is very wrong
1959
+ // so we bail
1960
+ if (iterations > 100000 && iterations > match.index * 3) {
1961
+ const err = new Error('potential infinite loop, way more iterations than matches');
1962
+ throw err;
1963
+ }
1964
+
1965
+ /*
1966
+ Why might be find ourselves here? Only one occasion now. An end match that was
1967
+ triggered but could not be completed. When might this happen? When an `endSameasBegin`
1968
+ rule sets the end rule to a specific match. Since the overall mode termination rule that's
1969
+ being used to scan the text isn't recompiled that means that any match that LOOKS like
1970
+ the end (but is not, because it is not an exact match to the beginning) will
1971
+ end up here. A definite end match, but when `doEndMatch` tries to "reapply"
1972
+ the end rule and fails to match, we wind up here, and just silently ignore the end.
1973
+
1974
+ This causes no real harm other than stopping a few times too many.
1975
+ */
1976
+
1977
+ modeBuffer += lexeme;
1978
+ return lexeme.length;
1979
+ }
1980
+
1981
+ const language = getLanguage(languageName);
1982
+ if (!language) {
1983
+ error(LANGUAGE_NOT_FOUND.replace("{}", languageName));
1984
+ throw new Error('Unknown language: "' + languageName + '"');
1985
+ }
1986
+
1987
+ const md = compileLanguage(language, { plugins });
1988
+ let result = '';
1989
+ /** @type {CompiledMode} */
1990
+ let top = continuation || md;
1991
+ /** @type Record<string,CompiledMode> */
1992
+ const continuations = {}; // keep continuations for sub-languages
1993
+ const emitter = new options.__emitter(options);
1994
+ processContinuations();
1995
+ let modeBuffer = '';
1996
+ let relevance = 0;
1997
+ let index = 0;
1998
+ let iterations = 0;
1999
+ let resumeScanAtSamePosition = false;
2000
+
2001
+ try {
2002
+ top.matcher.considerAll();
2003
+
2004
+ for (;;) {
2005
+ iterations++;
2006
+ if (resumeScanAtSamePosition) {
2007
+ // only regexes not matched previously will now be
2008
+ // considered for a potential match
2009
+ resumeScanAtSamePosition = false;
2010
+ } else {
2011
+ top.matcher.considerAll();
2012
+ }
2013
+ top.matcher.lastIndex = index;
2014
+
2015
+ const match = top.matcher.exec(codeToHighlight);
2016
+ // console.log("match", match[0], match.rule && match.rule.begin)
2017
+
2018
+ if (!match) break;
2019
+
2020
+ const beforeMatch = codeToHighlight.substring(index, match.index);
2021
+ const processedCount = processLexeme(beforeMatch, match);
2022
+ index = match.index + processedCount;
2023
+ }
2024
+ processLexeme(codeToHighlight.substr(index));
2025
+ emitter.closeAllNodes();
2026
+ emitter.finalize();
2027
+ result = emitter.toHTML();
2028
+
2029
+ return {
2030
+ // avoid possible breakage with v10 clients expecting
2031
+ // this to always be an integer
2032
+ relevance: Math.floor(relevance),
2033
+ value: result,
2034
+ language: languageName,
2035
+ illegal: false,
2036
+ emitter: emitter,
2037
+ top: top
2038
+ };
2039
+ } catch (err) {
2040
+ if (err.message && err.message.includes('Illegal')) {
2041
+ return {
2042
+ illegal: true,
2043
+ illegalBy: {
2044
+ msg: err.message,
2045
+ context: codeToHighlight.slice(index - 100, index + 100),
2046
+ mode: err.mode
2047
+ },
2048
+ sofar: result,
2049
+ relevance: 0,
2050
+ value: escape$1(codeToHighlight),
2051
+ emitter: emitter
2052
+ };
2053
+ } else if (SAFE_MODE) {
2054
+ return {
2055
+ illegal: false,
2056
+ relevance: 0,
2057
+ value: escape$1(codeToHighlight),
2058
+ emitter: emitter,
2059
+ language: languageName,
2060
+ top: top,
2061
+ errorRaised: err
2062
+ };
2063
+ } else {
2064
+ throw err;
2065
+ }
2066
+ }
2067
+ }
2068
+
2069
+ /**
2070
+ * returns a valid highlight result, without actually doing any actual work,
2071
+ * auto highlight starts with this and it's possible for small snippets that
2072
+ * auto-detection may not find a better match
2073
+ * @param {string} code
2074
+ * @returns {HighlightResult}
2075
+ */
2076
+ function justTextHighlightResult(code) {
2077
+ const result = {
2078
+ relevance: 0,
2079
+ emitter: new options.__emitter(options),
2080
+ value: escape$1(code),
2081
+ illegal: false,
2082
+ top: PLAINTEXT_LANGUAGE
2083
+ };
2084
+ result.emitter.addText(code);
2085
+ return result;
2086
+ }
2087
+
2088
+ /**
2089
+ Highlighting with language detection. Accepts a string with the code to
2090
+ highlight. Returns an object with the following properties:
2091
+
2092
+ - language (detected language)
2093
+ - relevance (int)
2094
+ - value (an HTML string with highlighting markup)
2095
+ - second_best (object with the same structure for second-best heuristically
2096
+ detected language, may be absent)
2097
+
2098
+ @param {string} code
2099
+ @param {Array<string>} [languageSubset]
2100
+ @returns {AutoHighlightResult}
2101
+ */
2102
+ function highlightAuto(code, languageSubset) {
2103
+ languageSubset = languageSubset || options.languages || Object.keys(languages);
2104
+ const plaintext = justTextHighlightResult(code);
2105
+
2106
+ const results = languageSubset.filter(getLanguage).filter(autoDetection).map(name =>
2107
+ _highlight(name, code, false)
2108
+ );
2109
+ results.unshift(plaintext); // plaintext is always an option
2110
+
2111
+ const sorted = results.sort((a, b) => {
2112
+ // sort base on relevance
2113
+ if (a.relevance !== b.relevance) return b.relevance - a.relevance;
2114
+
2115
+ // always award the tie to the base language
2116
+ // ie if C++ and Arduino are tied, it's more likely to be C++
2117
+ if (a.language && b.language) {
2118
+ if (getLanguage(a.language).supersetOf === b.language) {
2119
+ return 1;
2120
+ } else if (getLanguage(b.language).supersetOf === a.language) {
2121
+ return -1;
2122
+ }
2123
+ }
2124
+
2125
+ // otherwise say they are equal, which has the effect of sorting on
2126
+ // relevance while preserving the original ordering - which is how ties
2127
+ // have historically been settled, ie the language that comes first always
2128
+ // wins in the case of a tie
2129
+ return 0;
2130
+ });
2131
+
2132
+ const [best, secondBest] = sorted;
2133
+
2134
+ /** @type {AutoHighlightResult} */
2135
+ const result = best;
2136
+ result.second_best = secondBest;
2137
+
2138
+ return result;
2139
+ }
2140
+
2141
+ /**
2142
+ Post-processing of the highlighted markup:
2143
+
2144
+ - replace TABs with something more useful
2145
+ - replace real line-breaks with '<br>' for non-pre containers
2146
+
2147
+ @param {string} html
2148
+ @returns {string}
2149
+ */
2150
+ function fixMarkup(html) {
2151
+ if (!(options.tabReplace || options.useBR)) {
2152
+ return html;
2153
+ }
2154
+
2155
+ return html.replace(fixMarkupRe, match => {
2156
+ if (match === '\n') {
2157
+ return options.useBR ? '<br>' : match;
2158
+ } else if (options.tabReplace) {
2159
+ return match.replace(/\t/g, options.tabReplace);
2160
+ }
2161
+ return match;
2162
+ });
2163
+ }
2164
+
2165
+ /**
2166
+ * Builds new class name for block given the language name
2167
+ *
2168
+ * @param {HTMLElement} element
2169
+ * @param {string} [currentLang]
2170
+ * @param {string} [resultLang]
2171
+ */
2172
+ function updateClassName(element, currentLang, resultLang) {
2173
+ const language = currentLang ? aliases[currentLang] : resultLang;
2174
+
2175
+ element.classList.add("hljs");
2176
+ if (language) element.classList.add(language);
2177
+ }
2178
+
2179
+ /** @type {HLJSPlugin} */
2180
+ const brPlugin = {
2181
+ "before:highlightElement": ({ el }) => {
2182
+ if (options.useBR) {
2183
+ el.innerHTML = el.innerHTML.replace(/\n/g, '').replace(/<br[ /]*>/g, '\n');
2184
+ }
2185
+ },
2186
+ "after:highlightElement": ({ result }) => {
2187
+ if (options.useBR) {
2188
+ result.value = result.value.replace(/\n/g, "<br>");
2189
+ }
2190
+ }
2191
+ };
2192
+
2193
+ const TAB_REPLACE_RE = /^(<[^>]+>|\t)+/gm;
2194
+ /** @type {HLJSPlugin} */
2195
+ const tabReplacePlugin = {
2196
+ "after:highlightElement": ({ result }) => {
2197
+ if (options.tabReplace) {
2198
+ result.value = result.value.replace(TAB_REPLACE_RE, (m) =>
2199
+ m.replace(/\t/g, options.tabReplace)
2200
+ );
2201
+ }
2202
+ }
2203
+ };
2204
+
2205
+ /**
2206
+ * Applies highlighting to a DOM node containing code. Accepts a DOM node and
2207
+ * two optional parameters for fixMarkup.
2208
+ *
2209
+ * @param {HighlightedHTMLElement} element - the HTML element to highlight
2210
+ */
2211
+ function highlightElement(element) {
2212
+ /** @type HTMLElement */
2213
+ let node = null;
2214
+ const language = blockLanguage(element);
2215
+
2216
+ if (shouldNotHighlight(language)) return;
2217
+
2218
+ // support for v10 API
2219
+ fire("before:highlightElement",
2220
+ { el: element, language: language });
2221
+
2222
+ node = element;
2223
+ const text = node.textContent;
2224
+ const result = language ? highlight(text, { language, ignoreIllegals: true }) : highlightAuto(text);
2225
+
2226
+ // support for v10 API
2227
+ fire("after:highlightElement", { el: element, result, text });
2228
+
2229
+ element.innerHTML = result.value;
2230
+ updateClassName(element, language, result.language);
2231
+ element.result = {
2232
+ language: result.language,
2233
+ // TODO: remove with version 11.0
2234
+ re: result.relevance,
2235
+ relavance: result.relevance
2236
+ };
2237
+ if (result.second_best) {
2238
+ element.second_best = {
2239
+ language: result.second_best.language,
2240
+ // TODO: remove with version 11.0
2241
+ re: result.second_best.relevance,
2242
+ relavance: result.second_best.relevance
2243
+ };
2244
+ }
2245
+ }
2246
+
2247
+ /**
2248
+ * Updates highlight.js global options with the passed options
2249
+ *
2250
+ * @param {Partial<HLJSOptions>} userOptions
2251
+ */
2252
+ function configure(userOptions) {
2253
+ if (userOptions.useBR) {
2254
+ deprecated("10.3.0", "'useBR' will be removed entirely in v11.0");
2255
+ deprecated("10.3.0", "Please see https://github.com/highlightjs/highlight.js/issues/2559");
2256
+ }
2257
+ options = inherit$1(options, userOptions);
2258
+ }
2259
+
2260
+ /**
2261
+ * Highlights to all <pre><code> blocks on a page
2262
+ *
2263
+ * @type {Function & {called?: boolean}}
2264
+ */
2265
+ // TODO: remove v12, deprecated
2266
+ const initHighlighting = () => {
2267
+ if (initHighlighting.called) return;
2268
+ initHighlighting.called = true;
2269
+
2270
+ deprecated("10.6.0", "initHighlighting() is deprecated. Use highlightAll() instead.");
2271
+
2272
+ const blocks = document.querySelectorAll('pre code');
2273
+ blocks.forEach(highlightElement);
2274
+ };
2275
+
2276
+ // Higlights all when DOMContentLoaded fires
2277
+ // TODO: remove v12, deprecated
2278
+ function initHighlightingOnLoad() {
2279
+ deprecated("10.6.0", "initHighlightingOnLoad() is deprecated. Use highlightAll() instead.");
2280
+ wantsHighlight = true;
2281
+ }
2282
+
2283
+ let wantsHighlight = false;
2284
+
2285
+ /**
2286
+ * auto-highlights all pre>code elements on the page
2287
+ */
2288
+ function highlightAll() {
2289
+ // if we are called too early in the loading process
2290
+ if (document.readyState === "loading") {
2291
+ wantsHighlight = true;
2292
+ return;
2293
+ }
2294
+
2295
+ const blocks = document.querySelectorAll('pre code');
2296
+ blocks.forEach(highlightElement);
2297
+ }
2298
+
2299
+ function boot() {
2300
+ // if a highlight was requested before DOM was loaded, do now
2301
+ if (wantsHighlight) highlightAll();
2302
+ }
2303
+
2304
+ // make sure we are in the browser environment
2305
+ if (typeof window !== 'undefined' && window.addEventListener) {
2306
+ window.addEventListener('DOMContentLoaded', boot, false);
2307
+ }
2308
+
2309
+ /**
2310
+ * Register a language grammar module
2311
+ *
2312
+ * @param {string} languageName
2313
+ * @param {LanguageFn} languageDefinition
2314
+ */
2315
+ function registerLanguage(languageName, languageDefinition) {
2316
+ let lang = null;
2317
+ try {
2318
+ lang = languageDefinition(hljs);
2319
+ } catch (error$1) {
2320
+ error("Language definition for '{}' could not be registered.".replace("{}", languageName));
2321
+ // hard or soft error
2322
+ if (!SAFE_MODE) { throw error$1; } else { error(error$1); }
2323
+ // languages that have serious errors are replaced with essentially a
2324
+ // "plaintext" stand-in so that the code blocks will still get normal
2325
+ // css classes applied to them - and one bad language won't break the
2326
+ // entire highlighter
2327
+ lang = PLAINTEXT_LANGUAGE;
2328
+ }
2329
+ // give it a temporary name if it doesn't have one in the meta-data
2330
+ if (!lang.name) lang.name = languageName;
2331
+ languages[languageName] = lang;
2332
+ lang.rawDefinition = languageDefinition.bind(null, hljs);
2333
+
2334
+ if (lang.aliases) {
2335
+ registerAliases(lang.aliases, { languageName });
2336
+ }
2337
+ }
2338
+
2339
+ /**
2340
+ * Remove a language grammar module
2341
+ *
2342
+ * @param {string} languageName
2343
+ */
2344
+ function unregisterLanguage(languageName) {
2345
+ delete languages[languageName];
2346
+ for (const alias of Object.keys(aliases)) {
2347
+ if (aliases[alias] === languageName) {
2348
+ delete aliases[alias];
2349
+ }
2350
+ }
2351
+ }
2352
+
2353
+ /**
2354
+ * @returns {string[]} List of language internal names
2355
+ */
2356
+ function listLanguages() {
2357
+ return Object.keys(languages);
2358
+ }
2359
+
2360
+ /**
2361
+ intended usage: When one language truly requires another
2362
+
2363
+ Unlike `getLanguage`, this will throw when the requested language
2364
+ is not available.
2365
+
2366
+ @param {string} name - name of the language to fetch/require
2367
+ @returns {Language | never}
2368
+ */
2369
+ function requireLanguage(name) {
2370
+ deprecated("10.4.0", "requireLanguage will be removed entirely in v11.");
2371
+ deprecated("10.4.0", "Please see https://github.com/highlightjs/highlight.js/pull/2844");
2372
+
2373
+ const lang = getLanguage(name);
2374
+ if (lang) { return lang; }
2375
+
2376
+ const err = new Error('The \'{}\' language is required, but not loaded.'.replace('{}', name));
2377
+ throw err;
2378
+ }
2379
+
2380
+ /**
2381
+ * @param {string} name - name of the language to retrieve
2382
+ * @returns {Language | undefined}
2383
+ */
2384
+ function getLanguage(name) {
2385
+ name = (name || '').toLowerCase();
2386
+ return languages[name] || languages[aliases[name]];
2387
+ }
2388
+
2389
+ /**
2390
+ *
2391
+ * @param {string|string[]} aliasList - single alias or list of aliases
2392
+ * @param {{languageName: string}} opts
2393
+ */
2394
+ function registerAliases(aliasList, { languageName }) {
2395
+ if (typeof aliasList === 'string') {
2396
+ aliasList = [aliasList];
2397
+ }
2398
+ aliasList.forEach(alias => { aliases[alias.toLowerCase()] = languageName; });
2399
+ }
2400
+
2401
+ /**
2402
+ * Determines if a given language has auto-detection enabled
2403
+ * @param {string} name - name of the language
2404
+ */
2405
+ function autoDetection(name) {
2406
+ const lang = getLanguage(name);
2407
+ return lang && !lang.disableAutodetect;
2408
+ }
2409
+
2410
+ /**
2411
+ * Upgrades the old highlightBlock plugins to the new
2412
+ * highlightElement API
2413
+ * @param {HLJSPlugin} plugin
2414
+ */
2415
+ function upgradePluginAPI(plugin) {
2416
+ // TODO: remove with v12
2417
+ if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
2418
+ plugin["before:highlightElement"] = (data) => {
2419
+ plugin["before:highlightBlock"](
2420
+ Object.assign({ block: data.el }, data)
2421
+ );
2422
+ };
2423
+ }
2424
+ if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
2425
+ plugin["after:highlightElement"] = (data) => {
2426
+ plugin["after:highlightBlock"](
2427
+ Object.assign({ block: data.el }, data)
2428
+ );
2429
+ };
2430
+ }
2431
+ }
2432
+
2433
+ /**
2434
+ * @param {HLJSPlugin} plugin
2435
+ */
2436
+ function addPlugin(plugin) {
2437
+ upgradePluginAPI(plugin);
2438
+ plugins.push(plugin);
2439
+ }
2440
+
2441
+ /**
2442
+ *
2443
+ * @param {PluginEvent} event
2444
+ * @param {any} args
2445
+ */
2446
+ function fire(event, args) {
2447
+ const cb = event;
2448
+ plugins.forEach(function(plugin) {
2449
+ if (plugin[cb]) {
2450
+ plugin[cb](args);
2451
+ }
2452
+ });
2453
+ }
2454
+
2455
+ /**
2456
+ Note: fixMarkup is deprecated and will be removed entirely in v11
2457
+
2458
+ @param {string} arg
2459
+ @returns {string}
2460
+ */
2461
+ function deprecateFixMarkup(arg) {
2462
+ deprecated("10.2.0", "fixMarkup will be removed entirely in v11.0");
2463
+ deprecated("10.2.0", "Please see https://github.com/highlightjs/highlight.js/issues/2534");
2464
+
2465
+ return fixMarkup(arg);
2466
+ }
2467
+
2468
+ /**
2469
+ *
2470
+ * @param {HighlightedHTMLElement} el
2471
+ */
2472
+ function deprecateHighlightBlock(el) {
2473
+ deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
2474
+ deprecated("10.7.0", "Please use highlightElement now.");
2475
+
2476
+ return highlightElement(el);
2477
+ }
2478
+
2479
+ /* Interface definition */
2480
+ Object.assign(hljs, {
2481
+ highlight,
2482
+ highlightAuto,
2483
+ highlightAll,
2484
+ fixMarkup: deprecateFixMarkup,
2485
+ highlightElement,
2486
+ // TODO: Remove with v12 API
2487
+ highlightBlock: deprecateHighlightBlock,
2488
+ configure,
2489
+ initHighlighting,
2490
+ initHighlightingOnLoad,
2491
+ registerLanguage,
2492
+ unregisterLanguage,
2493
+ listLanguages,
2494
+ getLanguage,
2495
+ registerAliases,
2496
+ requireLanguage,
2497
+ autoDetection,
2498
+ inherit: inherit$1,
2499
+ addPlugin,
2500
+ // plugins for frameworks
2501
+ vuePlugin: BuildVuePlugin(hljs).VuePlugin
2502
+ });
2503
+
2504
+ hljs.debugMode = function() { SAFE_MODE = false; };
2505
+ hljs.safeMode = function() { SAFE_MODE = true; };
2506
+ hljs.versionString = version;
2507
+
2508
+ for (const key in MODES) {
2509
+ // @ts-ignore
2510
+ if (typeof MODES[key] === "object") {
2511
+ // @ts-ignore
2512
+ deepFreezeEs6(MODES[key]);
2513
+ }
2514
+ }
2515
+
2516
+ // merge all the modes/regexs into our main object
2517
+ Object.assign(hljs, MODES);
2518
+
2519
+ // built-in plugins, likely to be moved out of core in the future
2520
+ hljs.addPlugin(brPlugin); // slated to be removed in v11
2521
+ hljs.addPlugin(mergeHTMLPlugin);
2522
+ hljs.addPlugin(tabReplacePlugin);
2523
+ return hljs;
2524
+ };
2525
+
2526
+ // export an "instance" of the highlighter
2527
+ var highlight$1 = HLJS({});
2528
+
2529
+ var core = highlight$1;
2530
+
2531
+ var format = {exports: {}};
2532
+
2533
+ (function (module) {
2534
+ (function() {
2535
+
2536
+ //// Export the API
2537
+ var namespace;
2538
+
2539
+ // CommonJS / Node module
2540
+ {
2541
+ namespace = module.exports = format;
2542
+ }
2543
+
2544
+ namespace.format = format;
2545
+ namespace.vsprintf = vsprintf;
2546
+
2547
+ if (typeof console !== 'undefined' && typeof console.log === 'function') {
2548
+ namespace.printf = printf;
2549
+ }
2550
+
2551
+ function printf(/* ... */) {
2552
+ console.log(format.apply(null, arguments));
2553
+ }
2554
+
2555
+ function vsprintf(fmt, replacements) {
2556
+ return format.apply(null, [fmt].concat(replacements));
2557
+ }
2558
+
2559
+ function format(fmt) {
2560
+ var argIndex = 1 // skip initial format argument
2561
+ , args = [].slice.call(arguments)
2562
+ , i = 0
2563
+ , n = fmt.length
2564
+ , result = ''
2565
+ , c
2566
+ , escaped = false
2567
+ , arg
2568
+ , tmp
2569
+ , leadingZero = false
2570
+ , precision
2571
+ , nextArg = function() { return args[argIndex++]; }
2572
+ , slurpNumber = function() {
2573
+ var digits = '';
2574
+ while (/\d/.test(fmt[i])) {
2575
+ digits += fmt[i++];
2576
+ c = fmt[i];
2577
+ }
2578
+ return digits.length > 0 ? parseInt(digits) : null;
2579
+ }
2580
+ ;
2581
+ for (; i < n; ++i) {
2582
+ c = fmt[i];
2583
+ if (escaped) {
2584
+ escaped = false;
2585
+ if (c == '.') {
2586
+ leadingZero = false;
2587
+ c = fmt[++i];
2588
+ }
2589
+ else if (c == '0' && fmt[i + 1] == '.') {
2590
+ leadingZero = true;
2591
+ i += 2;
2592
+ c = fmt[i];
2593
+ }
2594
+ else {
2595
+ leadingZero = true;
2596
+ }
2597
+ precision = slurpNumber();
2598
+ switch (c) {
2599
+ case 'b': // number in binary
2600
+ result += parseInt(nextArg(), 10).toString(2);
2601
+ break;
2602
+ case 'c': // character
2603
+ arg = nextArg();
2604
+ if (typeof arg === 'string' || arg instanceof String)
2605
+ result += arg;
2606
+ else
2607
+ result += String.fromCharCode(parseInt(arg, 10));
2608
+ break;
2609
+ case 'd': // number in decimal
2610
+ result += parseInt(nextArg(), 10);
2611
+ break;
2612
+ case 'f': // floating point number
2613
+ tmp = String(parseFloat(nextArg()).toFixed(precision || 6));
2614
+ result += leadingZero ? tmp : tmp.replace(/^0/, '');
2615
+ break;
2616
+ case 'j': // JSON
2617
+ result += JSON.stringify(nextArg());
2618
+ break;
2619
+ case 'o': // number in octal
2620
+ result += '0' + parseInt(nextArg(), 10).toString(8);
2621
+ break;
2622
+ case 's': // string
2623
+ result += nextArg();
2624
+ break;
2625
+ case 'x': // lowercase hexadecimal
2626
+ result += '0x' + parseInt(nextArg(), 10).toString(16);
2627
+ break;
2628
+ case 'X': // uppercase hexadecimal
2629
+ result += '0x' + parseInt(nextArg(), 10).toString(16).toUpperCase();
2630
+ break;
2631
+ default:
2632
+ result += c;
2633
+ break;
2634
+ }
2635
+ } else if (c === '%') {
2636
+ escaped = true;
2637
+ } else {
2638
+ result += c;
2639
+ }
2640
+ }
2641
+ return result;
2642
+ }
2643
+
2644
+ }());
2645
+ }(format));
2646
+
2647
+ var formatter = format.exports;
2648
+
2649
+ var fault$1 = create(Error);
2650
+
2651
+ var fault_1 = fault$1;
2652
+
2653
+ fault$1.eval = create(EvalError);
2654
+ fault$1.range = create(RangeError);
2655
+ fault$1.reference = create(ReferenceError);
2656
+ fault$1.syntax = create(SyntaxError);
2657
+ fault$1.type = create(TypeError);
2658
+ fault$1.uri = create(URIError);
2659
+
2660
+ fault$1.create = create;
2661
+
2662
+ // Create a new `EConstructor`, with the formatted `format` as a first argument.
2663
+ function create(EConstructor) {
2664
+ FormattedError.displayName = EConstructor.displayName || EConstructor.name;
2665
+
2666
+ return FormattedError
2667
+
2668
+ function FormattedError(format) {
2669
+ if (format) {
2670
+ format = formatter.apply(null, arguments);
2671
+ }
2672
+
2673
+ return new EConstructor(format)
2674
+ }
2675
+ }
2676
+
2677
+ var high = core;
2678
+ var fault = fault_1;
2679
+
2680
+ core$1.highlight = highlight;
2681
+ core$1.highlightAuto = highlightAuto;
2682
+ core$1.registerLanguage = registerLanguage;
2683
+ core$1.listLanguages = listLanguages;
2684
+ core$1.registerAlias = registerAlias;
2685
+
2686
+ Emitter.prototype.addText = text;
2687
+ Emitter.prototype.addKeyword = addKeyword;
2688
+ Emitter.prototype.addSublanguage = addSublanguage;
2689
+ Emitter.prototype.openNode = open;
2690
+ Emitter.prototype.closeNode = close;
2691
+ Emitter.prototype.closeAllNodes = noop;
2692
+ Emitter.prototype.finalize = noop;
2693
+ Emitter.prototype.toHTML = toHtmlNoop;
2694
+
2695
+ var defaultPrefix = 'hljs-';
2696
+
2697
+ // Highlighting `value` in the language `name`.
2698
+ function highlight(name, value, options) {
2699
+ var before = high.configure({});
2700
+ var settings = options || {};
2701
+ var prefix = settings.prefix;
2702
+ var result;
2703
+
2704
+ if (typeof name !== 'string') {
2705
+ throw fault('Expected `string` for name, got `%s`', name)
2706
+ }
2707
+
2708
+ if (!high.getLanguage(name)) {
2709
+ throw fault('Unknown language: `%s` is not registered', name)
2710
+ }
2711
+
2712
+ if (typeof value !== 'string') {
2713
+ throw fault('Expected `string` for value, got `%s`', value)
2714
+ }
2715
+
2716
+ if (prefix === null || prefix === undefined) {
2717
+ prefix = defaultPrefix;
2718
+ }
2719
+
2720
+ high.configure({__emitter: Emitter, classPrefix: prefix});
2721
+
2722
+ result = high.highlight(value, {language: name, ignoreIllegals: true});
2723
+
2724
+ high.configure(before || {});
2725
+
2726
+ /* istanbul ignore if - Highlight.js seems to use this (currently) for broken
2727
+ * grammars, so let’s keep it in there just to be sure. */
2728
+ if (result.errorRaised) {
2729
+ throw result.errorRaised
2730
+ }
2731
+
2732
+ return {
2733
+ relevance: result.relevance,
2734
+ language: result.language,
2735
+ value: result.emitter.rootNode.children
2736
+ }
2737
+ }
2738
+
2739
+ function highlightAuto(value, options) {
2740
+ var settings = options || {};
2741
+ var subset = settings.subset || high.listLanguages();
2742
+ settings.prefix;
2743
+ var length = subset.length;
2744
+ var index = -1;
2745
+ var result;
2746
+ var secondBest;
2747
+ var current;
2748
+ var name;
2749
+
2750
+ if (typeof value !== 'string') {
2751
+ throw fault('Expected `string` for value, got `%s`', value)
2752
+ }
2753
+
2754
+ secondBest = {relevance: 0, language: null, value: []};
2755
+ result = {relevance: 0, language: null, value: []};
2756
+
2757
+ while (++index < length) {
2758
+ name = subset[index];
2759
+
2760
+ if (!high.getLanguage(name)) {
2761
+ continue
2762
+ }
2763
+
2764
+ current = highlight(name, value, options);
2765
+ current.language = name;
2766
+
2767
+ if (current.relevance > secondBest.relevance) {
2768
+ secondBest = current;
2769
+ }
2770
+
2771
+ if (current.relevance > result.relevance) {
2772
+ secondBest = result;
2773
+ result = current;
2774
+ }
2775
+ }
2776
+
2777
+ if (secondBest.language) {
2778
+ result.secondBest = secondBest;
2779
+ }
2780
+
2781
+ return result
2782
+ }
2783
+
2784
+ // Register a language.
2785
+ function registerLanguage(name, syntax) {
2786
+ high.registerLanguage(name, syntax);
2787
+ }
2788
+
2789
+ // Get a list of all registered languages.
2790
+ function listLanguages() {
2791
+ return high.listLanguages()
2792
+ }
2793
+
2794
+ // Register more aliases for an already registered language.
2795
+ function registerAlias(name, alias) {
2796
+ var map = name;
2797
+ var key;
2798
+
2799
+ if (alias) {
2800
+ map = {};
2801
+ map[name] = alias;
2802
+ }
2803
+
2804
+ for (key in map) {
2805
+ high.registerAliases(map[key], {languageName: key});
2806
+ }
2807
+ }
2808
+
2809
+ function Emitter(options) {
2810
+ this.options = options;
2811
+ this.rootNode = {children: []};
2812
+ this.stack = [this.rootNode];
2813
+ }
2814
+
2815
+ function addKeyword(value, name) {
2816
+ this.openNode(name);
2817
+ this.addText(value);
2818
+ this.closeNode();
2819
+ }
2820
+
2821
+ function addSublanguage(other, name) {
2822
+ var stack = this.stack;
2823
+ var current = stack[stack.length - 1];
2824
+ var results = other.rootNode.children;
2825
+ var node = name
2826
+ ? {
2827
+ type: 'element',
2828
+ tagName: 'span',
2829
+ properties: {className: [name]},
2830
+ children: results
2831
+ }
2832
+ : results;
2833
+
2834
+ current.children = current.children.concat(node);
2835
+ }
2836
+
2837
+ function text(value) {
2838
+ var stack = this.stack;
2839
+ var current;
2840
+ var tail;
2841
+
2842
+ if (value === '') return
2843
+
2844
+ current = stack[stack.length - 1];
2845
+ tail = current.children[current.children.length - 1];
2846
+
2847
+ if (tail && tail.type === 'text') {
2848
+ tail.value += value;
2849
+ } else {
2850
+ current.children.push({type: 'text', value: value});
2851
+ }
2852
+ }
2853
+
2854
+ function open(name) {
2855
+ var stack = this.stack;
2856
+ var className = this.options.classPrefix + name;
2857
+ var current = stack[stack.length - 1];
2858
+ var child = {
2859
+ type: 'element',
2860
+ tagName: 'span',
2861
+ properties: {className: [className]},
2862
+ children: []
2863
+ };
2864
+
2865
+ current.children.push(child);
2866
+ stack.push(child);
2867
+ }
2868
+
2869
+ function close() {
2870
+ this.stack.pop();
2871
+ }
2872
+
2873
+ function toHtmlNoop() {
2874
+ return ''
2875
+ }
2876
+
2877
+ function noop() {}
2878
+
2879
+ function parseNodes(nodes, className = []) {
2880
+ return nodes
2881
+ .map(node => {
2882
+ const classes = [
2883
+ ...className,
2884
+ ...node.properties
2885
+ ? node.properties.className
2886
+ : [],
2887
+ ];
2888
+ if (node.children) {
2889
+ return parseNodes(node.children, classes);
2890
+ }
2891
+ return {
2892
+ text: node.value,
2893
+ classes,
2894
+ };
2895
+ })
2896
+ .flat();
2897
+ }
2898
+ function getHighlightNodes(result) {
2899
+ // `.value` for lowlight v1, `.children` for lowlight v2
2900
+ return result.value || result.children || [];
2901
+ }
2902
+ function getDecorations({ doc, name, lowlight, defaultLanguage, }) {
2903
+ const decorations = [];
2904
+ core$2.findChildren(doc, node => node.type.name === name)
2905
+ .forEach(block => {
2906
+ let from = block.pos + 1;
2907
+ const language = block.node.attrs.language || defaultLanguage;
2908
+ console.log({ language, defaultLanguage });
2909
+ const languages = lowlight.listLanguages();
2910
+ const nodes = language && languages.includes(language)
2911
+ ? getHighlightNodes(lowlight.highlight(language, block.node.textContent))
2912
+ : getHighlightNodes(lowlight.highlightAuto(block.node.textContent));
2913
+ parseNodes(nodes).forEach(node => {
2914
+ const to = from + node.text.length;
2915
+ if (node.classes.length) {
2916
+ const decoration = prosemirrorView.Decoration.inline(from, to, {
2917
+ class: node.classes.join(' '),
2918
+ });
2919
+ decorations.push(decoration);
2920
+ }
2921
+ from = to;
2922
+ });
2923
+ });
2924
+ return prosemirrorView.DecorationSet.create(doc, decorations);
2925
+ }
2926
+ function LowlightPlugin({ name, lowlight, defaultLanguage }) {
2927
+ return new prosemirrorState.Plugin({
2928
+ key: new prosemirrorState.PluginKey('lowlight'),
2929
+ state: {
2930
+ init: (_, { doc }) => getDecorations({
2931
+ doc,
2932
+ name,
2933
+ lowlight,
2934
+ defaultLanguage,
2935
+ }),
2936
+ apply: (transaction, decorationSet, oldState, newState) => {
2937
+ const oldNodeName = oldState.selection.$head.parent.type.name;
2938
+ const newNodeName = newState.selection.$head.parent.type.name;
2939
+ const oldNodes = core$2.findChildren(oldState.doc, node => node.type.name === name);
2940
+ const newNodes = core$2.findChildren(newState.doc, node => node.type.name === name);
2941
+ if (transaction.docChanged
2942
+ // Apply decorations if:
2943
+ && (
2944
+ // selection includes named node,
2945
+ [oldNodeName, newNodeName].includes(name)
2946
+ // OR transaction adds/removes named node,
2947
+ || newNodes.length !== oldNodes.length
2948
+ // OR transaction has changes that completely encapsulte a node
2949
+ // (for example, a transaction that affects the entire document).
2950
+ // Such transactions can happen during collab syncing via y-prosemirror, for example.
2951
+ || transaction.steps.some(step => {
2952
+ // @ts-ignore
2953
+ return step.from !== undefined
2954
+ // @ts-ignore
2955
+ && step.to !== undefined
2956
+ && oldNodes.some(node => {
2957
+ // @ts-ignore
2958
+ return node.pos >= step.from
2959
+ // @ts-ignore
2960
+ && node.pos + node.node.nodeSize <= step.to;
2961
+ });
2962
+ }))) {
2963
+ return getDecorations({
2964
+ doc: transaction.doc,
2965
+ name,
2966
+ lowlight,
2967
+ defaultLanguage,
2968
+ });
2969
+ }
2970
+ return decorationSet.map(transaction.mapping, transaction.doc);
2971
+ },
2972
+ },
2973
+ props: {
2974
+ decorations(state) {
2975
+ return this.getState(state);
2976
+ },
2977
+ },
2978
+ });
2979
+ }
2980
+
2981
+ const CodeBlockLowlight = CodeBlock__default["default"].extend({
2982
+ addOptions() {
2983
+ var _a;
2984
+ return {
2985
+ ...(_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this),
2986
+ lowlight: core$1,
2987
+ defaultLanguage: null,
2988
+ };
2989
+ },
2990
+ addProseMirrorPlugins() {
2991
+ var _a;
2992
+ return [
2993
+ ...((_a = this.parent) === null || _a === void 0 ? void 0 : _a.call(this)) || [],
2994
+ LowlightPlugin({
2995
+ name: this.name,
2996
+ lowlight: this.options.lowlight,
2997
+ defaultLanguage: this.options.defaultLanguage,
2998
+ }),
2999
+ ];
3000
+ },
3001
+ });
3002
+
3003
+ exports.CodeBlockLowlight = CodeBlockLowlight;
3004
+ exports["default"] = CodeBlockLowlight;
3005
+
3006
+ Object.defineProperty(exports, '__esModule', { value: true });
3007
+
3008
+ }));
3009
+ //# sourceMappingURL=tiptap-extension-code-block-lowlight.umd.js.map