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