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