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

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