@tiptap/extension-code-block-lowlight 2.0.0-beta.67 → 2.0.0-beta.71

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