@tiptap/extension-code-block-lowlight 2.0.0-beta.7 → 2.0.0-beta.73

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