@tiptap/extension-code-block-lowlight 2.0.0-beta.208 → 2.0.0-beta.210

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