-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighlight.js
3678 lines (3337 loc) · 108 KB
/
highlight.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
Highlight.js v11.0.0 (git: bb0e02ce46)
(c) 2006-2021 Ivan Sagalaev and other contributors
License: BSD-3-Clause
*/
var hljs = (function () {
'use strict';
var deepFreezeEs6 = {exports: {}};
function deepFreeze(obj) {
if (obj instanceof Map) {
obj.clear = obj.delete = obj.set = function () {
throw new Error('map is read-only');
};
} else if (obj instanceof Set) {
obj.add = obj.clear = obj.delete = function () {
throw new Error('set is read-only');
};
}
// Freeze self
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach(function (name) {
var prop = obj[name];
// Freeze prop if it is an object
if (typeof prop == 'object' && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
});
return obj;
}
deepFreezeEs6.exports = deepFreeze;
deepFreezeEs6.exports.default = deepFreeze;
var deepFreeze$1 = deepFreezeEs6.exports;
/** @typedef {import('highlight.js').CompiledMode} CompiledMode */
/** @implements CallbackResponse */
class Response {
/**
* @param {CompiledMode} mode
*/
constructor(mode) {
// eslint-disable-next-line no-undefined
if (mode.data === undefined) mode.data = {};
this.data = mode.data;
this.isMatchIgnored = false;
}
ignoreMatch() {
this.isMatchIgnored = true;
}
}
/**
* @param {string} value
* @returns {string}
*/
function escapeHTML(value) {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/**
* performs a shallow merge of multiple objects into one
*
* @template T
* @param {T} original
* @param {Record<string,any>[]} objects
* @returns {T} a single new object
*/
function inherit$1(original, ...objects) {
/** @type Record<string,any> */
const result = Object.create(null);
for (const key in original) {
result[key] = original[key];
}
objects.forEach(function(obj) {
for (const key in obj) {
result[key] = obj[key];
}
});
return /** @type {T} */ (result);
}
/**
* @typedef {object} Renderer
* @property {(text: string) => void} addText
* @property {(node: Node) => void} openNode
* @property {(node: Node) => void} closeNode
* @property {() => string} value
*/
/** @typedef {{kind?: string, sublanguage?: boolean}} Node */
/** @typedef {{walk: (r: Renderer) => void}} Tree */
/** */
const SPAN_CLOSE = '</span>';
/**
* Determines if a node needs to be wrapped in <span>
*
* @param {Node} node */
const emitsWrappingTags = (node) => {
return !!node.kind;
};
/**
*
* @param {string} name
* @param {{prefix:string}} options
*/
const expandScopeName = (name, { prefix }) => {
if (name.includes(".")) {
const pieces = name.split(".");
return [
`${prefix}${pieces.shift()}`,
...(pieces.map((x, i) => `${x}${"_".repeat(i + 1)}`))
].join(" ");
}
return `${prefix}${name}`;
};
/** @type {Renderer} */
class HTMLRenderer {
/**
* Creates a new HTMLRenderer
*
* @param {Tree} parseTree - the parse tree (must support `walk` API)
* @param {{classPrefix: string}} options
*/
constructor(parseTree, options) {
this.buffer = "";
this.classPrefix = options.classPrefix;
parseTree.walk(this);
}
/**
* Adds texts to the output stream
*
* @param {string} text */
addText(text) {
this.buffer += escapeHTML(text);
}
/**
* Adds a node open to the output stream (if needed)
*
* @param {Node} node */
openNode(node) {
if (!emitsWrappingTags(node)) return;
let scope = node.kind;
if (node.sublanguage) {
scope = `language-${scope}`;
} else {
scope = expandScopeName(scope, { prefix: this.classPrefix });
}
this.span(scope);
}
/**
* Adds a node close to the output stream (if needed)
*
* @param {Node} node */
closeNode(node) {
if (!emitsWrappingTags(node)) return;
this.buffer += SPAN_CLOSE;
}
/**
* returns the accumulated buffer
*/
value() {
return this.buffer;
}
// helpers
/**
* Builds a span element
*
* @param {string} className */
span(className) {
this.buffer += `<span class="${className}">`;
}
}
/** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} | string} Node */
/** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} } DataNode */
/** @typedef {import('highlight.js').Emitter} Emitter */
/** */
class TokenTree {
constructor() {
/** @type DataNode */
this.rootNode = { children: [] };
this.stack = [this.rootNode];
}
get top() {
return this.stack[this.stack.length - 1];
}
get root() { return this.rootNode; }
/** @param {Node} node */
add(node) {
this.top.children.push(node);
}
/** @param {string} kind */
openNode(kind) {
/** @type Node */
const node = { kind, children: [] };
this.add(node);
this.stack.push(node);
}
closeNode() {
if (this.stack.length > 1) {
return this.stack.pop();
}
// eslint-disable-next-line no-undefined
return undefined;
}
closeAllNodes() {
while (this.closeNode());
}
toJSON() {
return JSON.stringify(this.rootNode, null, 4);
}
/**
* @typedef { import("./html_renderer").Renderer } Renderer
* @param {Renderer} builder
*/
walk(builder) {
// this does not
return this.constructor._walk(builder, this.rootNode);
// this works
// return TokenTree._walk(builder, this.rootNode);
}
/**
* @param {Renderer} builder
* @param {Node} node
*/
static _walk(builder, node) {
if (typeof node === "string") {
builder.addText(node);
} else if (node.children) {
builder.openNode(node);
node.children.forEach((child) => this._walk(builder, child));
builder.closeNode(node);
}
return builder;
}
/**
* @param {Node} node
*/
static _collapse(node) {
if (typeof node === "string") return;
if (!node.children) return;
if (node.children.every(el => typeof el === "string")) {
// node.text = node.children.join("");
// delete node.children;
node.children = [node.children.join("")];
} else {
node.children.forEach((child) => {
TokenTree._collapse(child);
});
}
}
}
/**
Currently this is all private API, but this is the minimal API necessary
that an Emitter must implement to fully support the parser.
Minimal interface:
- addKeyword(text, kind)
- addText(text)
- addSublanguage(emitter, subLanguageName)
- finalize()
- openNode(kind)
- closeNode()
- closeAllNodes()
- toHTML()
*/
/**
* @implements {Emitter}
*/
class TokenTreeEmitter extends TokenTree {
/**
* @param {*} options
*/
constructor(options) {
super();
this.options = options;
}
/**
* @param {string} text
* @param {string} kind
*/
addKeyword(text, kind) {
if (text === "") { return; }
this.openNode(kind);
this.addText(text);
this.closeNode();
}
/**
* @param {string} text
*/
addText(text) {
if (text === "") { return; }
this.add(text);
}
/**
* @param {Emitter & {root: DataNode}} emitter
* @param {string} name
*/
addSublanguage(emitter, name) {
/** @type DataNode */
const node = emitter.root;
node.kind = name;
node.sublanguage = true;
this.add(node);
}
toHTML() {
const renderer = new HTMLRenderer(this, this.options);
return renderer.value();
}
finalize() {
return true;
}
}
/**
* @param {string} value
* @returns {RegExp}
* */
/**
* @param {RegExp | string } re
* @returns {string}
*/
function source(re) {
if (!re) return null;
if (typeof re === "string") return re;
return re.source;
}
/**
* @param {RegExp | string } re
* @returns {string}
*/
function lookahead(re) {
return concat('(?=', re, ')');
}
/**
* @param {RegExp | string } re
* @returns {string}
*/
function optional(re) {
return concat('(?:', re, ')?');
}
/**
* @param {...(RegExp | string) } args
* @returns {string}
*/
function concat(...args) {
const joined = args.map((x) => source(x)).join("");
return joined;
}
function stripOptionsFromArgs(args) {
const opts = args[args.length - 1];
if (typeof opts === 'object' && opts.constructor === Object) {
args.splice(args.length - 1, 1);
return opts;
} else {
return {};
}
}
/**
* Any of the passed expresssions may match
*
* Creates a huge this | this | that | that match
* @param {(RegExp | string)[] } args
* @returns {string}
*/
function either(...args) {
const opts = stripOptionsFromArgs(args);
const joined = '(' +
(opts.capture ? "" : "?:") +
args.map((x) => source(x)).join("|") + ")";
return joined;
}
/**
* @param {RegExp} re
* @returns {number}
*/
function countMatchGroups(re) {
return (new RegExp(re.toString() + '|')).exec('').length - 1;
}
/**
* Does lexeme start with a regular expression match at the beginning
* @param {RegExp} re
* @param {string} lexeme
*/
function startsWith(re, lexeme) {
const match = re && re.exec(lexeme);
return match && match.index === 0;
}
// BACKREF_RE matches an open parenthesis or backreference. To avoid
// an incorrect parse, it additionally matches the following:
// - [...] elements, where the meaning of parentheses and escapes change
// - other escape sequences, so we do not misparse escape sequences as
// interesting elements
// - non-matching or lookahead parentheses, which do not capture. These
// follow the '(' with a '?'.
const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;
// **INTERNAL** Not intended for outside usage
// join logically computes regexps.join(separator), but fixes the
// backreferences so they continue to match.
// it also places each individual regular expression into it's own
// match group, keeping track of the sequencing of those match groups
// is currently an exercise for the caller. :-)
/**
* @param {(string | RegExp)[]} regexps
* @param {{joinWith: string}} opts
* @returns {string}
*/
function _rewriteBackreferences(regexps, { joinWith }) {
let numCaptures = 0;
return regexps.map((regex) => {
numCaptures += 1;
const offset = numCaptures;
let re = source(regex);
let out = '';
while (re.length > 0) {
const match = BACKREF_RE.exec(re);
if (!match) {
out += re;
break;
}
out += re.substring(0, match.index);
re = re.substring(match.index + match[0].length);
if (match[0][0] === '\\' && match[1]) {
// Adjust the backreference.
out += '\\' + String(Number(match[1]) + offset);
} else {
out += match[0];
if (match[0] === '(') {
numCaptures++;
}
}
}
return out;
}).map(re => `(${re})`).join(joinWith);
}
/** @typedef {import('highlight.js').Mode} Mode */
/** @typedef {import('highlight.js').ModeCallback} ModeCallback */
// Common regexps
const MATCH_NOTHING_RE = /\b\B/;
const IDENT_RE = '[a-zA-Z]\\w*';
const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*';
const NUMBER_RE = '\\b\\d+(\\.\\d+)?';
const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float
const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b...
const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~';
/**
* @param { Partial<Mode> & {binary?: string | RegExp} } opts
*/
const SHEBANG = (opts = {}) => {
const beginShebang = /^#![ ]*\//;
if (opts.binary) {
opts.begin = concat(
beginShebang,
/.*\b/,
opts.binary,
/\b.*/);
}
return inherit$1({
scope: 'meta',
begin: beginShebang,
end: /$/,
relevance: 0,
/** @type {ModeCallback} */
"on:begin": (m, resp) => {
if (m.index !== 0) resp.ignoreMatch();
}
}, opts);
};
// Common modes
const BACKSLASH_ESCAPE = {
begin: '\\\\[\\s\\S]', relevance: 0
};
const APOS_STRING_MODE = {
scope: 'string',
begin: '\'',
end: '\'',
illegal: '\\n',
contains: [BACKSLASH_ESCAPE]
};
const QUOTE_STRING_MODE = {
scope: 'string',
begin: '"',
end: '"',
illegal: '\\n',
contains: [BACKSLASH_ESCAPE]
};
const PHRASAL_WORDS_MODE = {
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/
};
/**
* Creates a comment mode
*
* @param {string | RegExp} begin
* @param {string | RegExp} end
* @param {Mode | {}} [modeOptions]
* @returns {Partial<Mode>}
*/
const COMMENT = function(begin, end, modeOptions = {}) {
const mode = inherit$1(
{
scope: 'comment',
begin,
end,
contains: []
},
modeOptions
);
mode.contains.push({
scope: 'doctag',
// hack to avoid the space from being included. the space is necessary to
// match here to prevent the plain text rule below from gobbling up doctags
begin: '[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)',
end: /(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,
excludeBegin: true,
relevance: 0
});
const ENGLISH_WORD = either(
// list of common 1 and 2 letter words in English
"I",
"a",
"is",
"so",
"us",
"to",
"at",
"if",
"in",
"it",
"on",
// note: this is not an exhaustive list of contractions, just popular ones
/[A-Za-z]+['](d|ve|re|ll|t|s|n)/, // contractions - can't we'd they're let's, etc
/[A-Za-z]+[-][a-z]+/, // `no-way`, etc.
/[A-Za-z][a-z]{2,}/ // allow capitalized words at beginning of sentences
);
// looking like plain text, more likely to be a comment
mode.contains.push(
{
// TODO: how to include ", (, ) without breaking grammars that use these for
// comment delimiters?
// begin: /[ ]+([()"]?([A-Za-z'-]{3,}|is|a|I|so|us|[tT][oO]|at|if|in|it|on)[.]?[()":]?([.][ ]|[ ]|\))){3}/
// ---
// this tries to find sequences of 3 english words in a row (without any
// "programming" type syntax) this gives us a strong signal that we've
// TRULY found a comment - vs perhaps scanning with the wrong language.
// It's possible to find something that LOOKS like the start of the
// comment - but then if there is no readable text - good chance it is a
// false match and not a comment.
//
// for a visual example please see:
// https://github.com/highlightjs/highlight.js/issues/2827
begin: concat(
/[ ]+/, // necessary to prevent us gobbling up doctags like /* @author Bob Mcgill */
'(',
ENGLISH_WORD,
/[.]?[:]?([.][ ]|[ ])/,
'){3}') // look for 3 words in a row
}
);
return mode;
};
const C_LINE_COMMENT_MODE = COMMENT('//', '$');
const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/');
const HASH_COMMENT_MODE = COMMENT('#', '$');
const NUMBER_MODE = {
scope: 'number',
begin: NUMBER_RE,
relevance: 0
};
const C_NUMBER_MODE = {
scope: 'number',
begin: C_NUMBER_RE,
relevance: 0
};
const BINARY_NUMBER_MODE = {
scope: 'number',
begin: BINARY_NUMBER_RE,
relevance: 0
};
const REGEXP_MODE = {
// this outer rule makes sure we actually have a WHOLE regex and not simply
// an expression such as:
//
// 3 / something
//
// (which will then blow up when regex's `illegal` sees the newline)
begin: /(?=\/[^/\n]*\/)/,
contains: [{
scope: 'regexp',
begin: /\//,
end: /\/[gimuy]*/,
illegal: /\n/,
contains: [
BACKSLASH_ESCAPE,
{
begin: /\[/,
end: /\]/,
relevance: 0,
contains: [BACKSLASH_ESCAPE]
}
]
}]
};
const TITLE_MODE = {
scope: 'title',
begin: IDENT_RE,
relevance: 0
};
const UNDERSCORE_TITLE_MODE = {
scope: 'title',
begin: UNDERSCORE_IDENT_RE,
relevance: 0
};
const METHOD_GUARD = {
// excludes method names from keyword processing
begin: '\\.\\s*' + UNDERSCORE_IDENT_RE,
relevance: 0
};
/**
* Adds end same as begin mechanics to a mode
*
* Your mode must include at least a single () match group as that first match
* group is what is used for comparison
* @param {Partial<Mode>} mode
*/
const END_SAME_AS_BEGIN = function(mode) {
return Object.assign(mode,
{
/** @type {ModeCallback} */
'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; },
/** @type {ModeCallback} */
'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); }
});
};
var MODES = /*#__PURE__*/Object.freeze({
__proto__: null,
MATCH_NOTHING_RE: MATCH_NOTHING_RE,
IDENT_RE: IDENT_RE,
UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE,
NUMBER_RE: NUMBER_RE,
C_NUMBER_RE: C_NUMBER_RE,
BINARY_NUMBER_RE: BINARY_NUMBER_RE,
RE_STARTERS_RE: RE_STARTERS_RE,
SHEBANG: SHEBANG,
BACKSLASH_ESCAPE: BACKSLASH_ESCAPE,
APOS_STRING_MODE: APOS_STRING_MODE,
QUOTE_STRING_MODE: QUOTE_STRING_MODE,
PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE,
COMMENT: COMMENT,
C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE,
C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE,
HASH_COMMENT_MODE: HASH_COMMENT_MODE,
NUMBER_MODE: NUMBER_MODE,
C_NUMBER_MODE: C_NUMBER_MODE,
BINARY_NUMBER_MODE: BINARY_NUMBER_MODE,
REGEXP_MODE: REGEXP_MODE,
TITLE_MODE: TITLE_MODE,
UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE,
METHOD_GUARD: METHOD_GUARD,
END_SAME_AS_BEGIN: END_SAME_AS_BEGIN
});
/**
@typedef {import('highlight.js').CallbackResponse} CallbackResponse
@typedef {import('highlight.js').CompilerExt} CompilerExt
*/
// Grammar extensions / plugins
// See: https://github.com/highlightjs/highlight.js/issues/2833
// Grammar extensions allow "syntactic sugar" to be added to the grammar modes
// without requiring any underlying changes to the compiler internals.
// `compileMatch` being the perfect small example of now allowing a grammar
// author to write `match` when they desire to match a single expression rather
// than being forced to use `begin`. The extension then just moves `match` into
// `begin` when it runs. Ie, no features have been added, but we've just made
// the experience of writing (and reading grammars) a little bit nicer.
// ------
// TODO: We need negative look-behind support to do this properly
/**
* Skip a match if it has a preceding dot
*
* This is used for `beginKeywords` to prevent matching expressions such as
* `bob.keyword.do()`. The mode compiler automatically wires this up as a
* special _internal_ 'on:begin' callback for modes with `beginKeywords`
* @param {RegExpMatchArray} match
* @param {CallbackResponse} response
*/
function skipIfHasPrecedingDot(match, response) {
const before = match.input[match.index - 1];
if (before === ".") {
response.ignoreMatch();
}
}
/**
*
* @type {CompilerExt}
*/
function scopeClassName(mode, _parent) {
// eslint-disable-next-line no-undefined
if (mode.className !== undefined) {
mode.scope = mode.className;
delete mode.className;
}
}
/**
* `beginKeywords` syntactic sugar
* @type {CompilerExt}
*/
function beginKeywords(mode, parent) {
if (!parent) return;
if (!mode.beginKeywords) return;
// for languages with keywords that include non-word characters checking for
// a word boundary is not sufficient, so instead we check for a word boundary
// or whitespace - this does no harm in any case since our keyword engine
// doesn't allow spaces in keywords anyways and we still check for the boundary
// first
mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)';
mode.__beforeBegin = skipIfHasPrecedingDot;
mode.keywords = mode.keywords || mode.beginKeywords;
delete mode.beginKeywords;
// prevents double relevance, the keywords themselves provide
// relevance, the mode doesn't need to double it
// eslint-disable-next-line no-undefined
if (mode.relevance === undefined) mode.relevance = 0;
}
/**
* Allow `illegal` to contain an array of illegal values
* @type {CompilerExt}
*/
function compileIllegal(mode, _parent) {
if (!Array.isArray(mode.illegal)) return;
mode.illegal = either(...mode.illegal);
}
/**
* `match` to match a single expression for readability
* @type {CompilerExt}
*/
function compileMatch(mode, _parent) {
if (!mode.match) return;
if (mode.begin || mode.end) throw new Error("begin & end are not supported with match");
mode.begin = mode.match;
delete mode.match;
}
/**
* provides the default 1 relevance to all modes
* @type {CompilerExt}
*/
function compileRelevance(mode, _parent) {
// eslint-disable-next-line no-undefined
if (mode.relevance === undefined) mode.relevance = 1;
}
// allow beforeMatch to act as a "qualifier" for the match
// the full match begin must be [beforeMatch][begin]
const beforeMatchExt = (mode, parent) => {
if (!mode.beforeMatch) return;
// starts conflicts with endsParent which we need to make sure the child
// rule is not matched multiple times
if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
const originalMode = Object.assign({}, mode);
Object.keys(mode).forEach((key) => { delete mode[key]; });
mode.keywords = originalMode.keywords;
mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
mode.starts = {
relevance: 0,
contains: [
Object.assign(originalMode, { endsParent: true })
]
};
mode.relevance = 0;
delete originalMode.beforeMatch;
};
// keywords that should have no default relevance value
const COMMON_KEYWORDS = [
'of',
'and',
'for',
'in',
'not',
'or',
'if',
'then',
'parent', // common variable name
'list', // common variable name
'value' // common variable name
];
const DEFAULT_KEYWORD_SCOPE = "keyword";
/**
* Given raw keywords from a language definition, compile them.
*
* @param {string | Record<string,string|string[]> | Array<string>} rawKeywords
* @param {boolean} caseInsensitive
*/
function compileKeywords(rawKeywords, caseInsensitive, scopeName = DEFAULT_KEYWORD_SCOPE) {
/** @type KeywordDict */
const compiledKeywords = Object.create(null);
// input can be a string of keywords, an array of keywords, or a object with
// named keys representing scopeName (which can then point to a string or array)
if (typeof rawKeywords === 'string') {
compileList(scopeName, rawKeywords.split(" "));
} else if (Array.isArray(rawKeywords)) {
compileList(scopeName, rawKeywords);
} else {
Object.keys(rawKeywords).forEach(function(scopeName) {
// collapse all our objects back into the parent object
Object.assign(
compiledKeywords,
compileKeywords(rawKeywords[scopeName], caseInsensitive, scopeName)
);
});
}
return compiledKeywords;
// ---
/**
* Compiles an individual list of keywords
*
* Ex: "for if when while|5"
*
* @param {string} scopeName
* @param {Array<string>} keywordList
*/
function compileList(scopeName, keywordList) {
if (caseInsensitive) {
keywordList = keywordList.map(x => x.toLowerCase());
}
keywordList.forEach(function(keyword) {
const pair = keyword.split('|');
compiledKeywords[pair[0]] = [scopeName, scoreForKeyword(pair[0], pair[1])];
});
}
}
/**
* Returns the proper score for a given keyword
*
* Also takes into account comment keywords, which will be scored 0 UNLESS
* another score has been manually assigned.
* @param {string} keyword
* @param {string} [providedScore]
*/
function scoreForKeyword(keyword, providedScore) {
// manual scores always win over common keywords
// so you can force a score of 1 if you really insist
if (providedScore) {
return Number(providedScore);
}
return commonKeyword(keyword) ? 0 : 1;
}
/**
* Determines if a given keyword is common or not
*
* @param {string} keyword */
function commonKeyword(keyword) {
return COMMON_KEYWORDS.includes(keyword.toLowerCase());
}
/*
For the reasoning behind this please see:
https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419
*/
/**
* @type {Record<string, boolean>}
*/
const seenDeprecations = {};
/**
* @param {string} message
*/
const error = (message) => {
console.error(message);
};
/**
* @param {string} message
* @param {any} args
*/
const warn = (message, ...args) => {
console.log(`WARN: ${message}`, ...args);
};
/**
* @param {string} version
* @param {string} message
*/
const deprecated = (version, message) => {
if (seenDeprecations[`${version}/${message}`]) return;
console.log(`Deprecated as of ${version}. ${message}`);
seenDeprecations[`${version}/${message}`] = true;
};
/* eslint-disable no-throw-literal */
/**
@typedef {import('highlight.js').CompiledMode} CompiledMode
*/
const MultiClassError = new Error();
/**