forked from irinazheltisheva/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.ts
More file actions
1064 lines (910 loc) · 55.2 KB
/
Copy pathstrings.ts
File metadata and controls
1064 lines (910 loc) · 55.2 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CharCode } from 'vs/base/common/charCode';
import { Constants } from 'vs/base/common/uint';
export function isFalsyOrWhitespace(str: string | undefined): boolean {
if (!str || typeof str !== 'string') {
return true;
}
return str.trim().length === 0;
}
/**
* @deprecated ES6: use `String.padStart`
*/
export function pad(n: number, l: number, char: string = '0'): string {
const str = '' + n;
const r = [str];
for (let i = str.length; i < l; i++) {
r.push(char);
}
return r.reverse().join('');
}
const _formatRegexp = /{(\d+)}/g;
/**
* Helper to produce a string with a variable number of arguments. Insert variable segments
* into the string using the {n} notation where N is the index of the argument following the string.
* @param value string to which formatting is applied
* @param args replacements for {n}-entries
*/
export function format(value: string, ...args: any[]): string {
if (args.length === 0) {
return value;
}
return value.replace(_formatRegexp, function (match, group) {
const idx = parseInt(group, 10);
return isNaN(idx) || idx < 0 || idx >= args.length ?
match :
args[idx];
});
}
/**
* Converts HTML characters inside the string to use entities instead. Makes the string safe from
* being used e.g. in HTMLElement.innerHTML.
*/
export function escape(html: string): string {
return html.replace(/[<>&]/g, function (match) {
switch (match) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
default: return match;
}
});
}
/**
* Escapes regular expression characters in a given string
*/
export function escapeRegExpCharacters(value: string): string {
return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, '\\$&');
}
/**
* Removes all occurrences of needle from the beginning and end of haystack.
* @param haystack string to trim
* @param needle the thing to trim (default is a blank)
*/
export function trim(haystack: string, needle: string = ' '): string {
const trimmed = ltrim(haystack, needle);
return rtrim(trimmed, needle);
}
/**
* Removes all occurrences of needle from the beginning of haystack.
* @param haystack string to trim
* @param needle the thing to trim
*/
export function ltrim(haystack: string, needle: string): string {
if (!haystack || !needle) {
return haystack;
}
const needleLen = needle.length;
if (needleLen === 0 || haystack.length === 0) {
return haystack;
}
let offset = 0;
while (haystack.indexOf(needle, offset) === offset) {
offset = offset + needleLen;
}
return haystack.substring(offset);
}
/**
* Removes all occurrences of needle from the end of haystack.
* @param haystack string to trim
* @param needle the thing to trim
*/
export function rtrim(haystack: string, needle: string): string {
if (!haystack || !needle) {
return haystack;
}
const needleLen = needle.length,
haystackLen = haystack.length;
if (needleLen === 0 || haystackLen === 0) {
return haystack;
}
let offset = haystackLen,
idx = -1;
while (true) {
idx = haystack.lastIndexOf(needle, offset - 1);
if (idx === -1 || idx + needleLen !== offset) {
break;
}
if (idx === 0) {
return '';
}
offset = idx;
}
return haystack.substring(0, offset);
}
export function convertSimple2RegExpPattern(pattern: string): string {
return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&').replace(/[\*]/g, '.*');
}
export function stripWildcards(pattern: string): string {
return pattern.replace(/\*/g, '');
}
export interface RegExpOptions {
matchCase?: boolean;
wholeWord?: boolean;
multiline?: boolean;
global?: boolean;
unicode?: boolean;
}
export function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp {
if (!searchString) {
throw new Error('Cannot create regex from empty string');
}
if (!isRegex) {
searchString = escapeRegExpCharacters(searchString);
}
if (options.wholeWord) {
if (!/\B/.test(searchString.charAt(0))) {
searchString = '\\b' + searchString;
}
if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
searchString = searchString + '\\b';
}
}
let modifiers = '';
if (options.global) {
modifiers += 'g';
}
if (!options.matchCase) {
modifiers += 'i';
}
if (options.multiline) {
modifiers += 'm';
}
if (options.unicode) {
modifiers += 'u';
}
return new RegExp(searchString, modifiers);
}
export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {
// Exit early if it's one of these special cases which are meant to match
// against an empty string
if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') {
return false;
}
// We check against an empty string. If the regular expression doesn't advance
// (e.g. ends in an endless loop) it will match an empty string.
const match = regexp.exec('');
return !!(match && regexp.lastIndex === 0);
}
export function regExpContainsBackreference(regexpValue: string): boolean {
return !!regexpValue.match(/([^\\]|^)(\\\\)*\\\d+/);
}
export function regExpFlags(regexp: RegExp): string {
return (regexp.global ? 'g' : '')
+ (regexp.ignoreCase ? 'i' : '')
+ (regexp.multiline ? 'm' : '')
+ ((regexp as any /* standalone editor compilation */).unicode ? 'u' : '');
}
/**
* Returns first index of the string that is not whitespace.
* If string is empty or contains only whitespaces, returns -1
*/
export function firstNonWhitespaceIndex(str: string): number {
for (let i = 0, len = str.length; i < len; i++) {
const chCode = str.charCodeAt(i);
if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
return i;
}
}
return -1;
}
/**
* Returns the leading whitespace of the string.
* If the string contains only whitespaces, returns entire string
*/
export function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string {
for (let i = start; i < end; i++) {
const chCode = str.charCodeAt(i);
if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
return str.substring(start, i);
}
}
return str.substring(start, end);
}
/**
* Returns last index of the string that is not whitespace.
* If string is empty or contains only whitespaces, returns -1
*/
export function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number {
for (let i = startIndex; i >= 0; i--) {
const chCode = str.charCodeAt(i);
if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
return i;
}
}
return -1;
}
export function compare(a: string, b: string): number {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
export function compareSubstring(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number {
for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
let codeA = a.charCodeAt(aStart);
let codeB = b.charCodeAt(bStart);
if (codeA < codeB) {
return -1;
} else if (codeA > codeB) {
return 1;
}
}
const aLen = aEnd - aStart;
const bLen = bEnd - bStart;
if (aLen < bLen) {
return -1;
} else if (aLen > bLen) {
return 1;
}
return 0;
}
export function compareIgnoreCase(a: string, b: string): number {
return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);
}
export function compareSubstringIgnoreCase(a: string, b: string, aStart: number = 0, aEnd: number = a.length, bStart: number = 0, bEnd: number = b.length): number {
for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
let codeA = a.charCodeAt(aStart);
let codeB = b.charCodeAt(bStart);
if (codeA === codeB) {
// equal
continue;
}
const diff = codeA - codeB;
if (diff === 32 && isUpperAsciiLetter(codeB)) { //codeB =[65-90] && codeA =[97-122]
continue;
} else if (diff === -32 && isUpperAsciiLetter(codeA)) { //codeB =[97-122] && codeA =[65-90]
continue;
}
if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) {
//
return diff;
} else {
return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
}
}
const aLen = aEnd - aStart;
const bLen = bEnd - bStart;
if (aLen < bLen) {
return -1;
} else if (aLen > bLen) {
return 1;
}
return 0;
}
export function isLowerAsciiLetter(code: number): boolean {
return code >= CharCode.a && code <= CharCode.z;
}
export function isUpperAsciiLetter(code: number): boolean {
return code >= CharCode.A && code <= CharCode.Z;
}
function isAsciiLetter(code: number): boolean {
return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
}
export function equalsIgnoreCase(a: string, b: string): boolean {
return a.length === b.length && doEqualsIgnoreCase(a, b);
}
function doEqualsIgnoreCase(a: string, b: string, stopAt = a.length): boolean {
for (let i = 0; i < stopAt; i++) {
const codeA = a.charCodeAt(i);
const codeB = b.charCodeAt(i);
if (codeA === codeB) {
continue;
}
// a-z A-Z
if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) {
const diff = Math.abs(codeA - codeB);
if (diff !== 0 && diff !== 32) {
return false;
}
}
// Any other charcode
else {
if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) {
return false;
}
}
}
return true;
}
export function startsWithIgnoreCase(str: string, candidate: string): boolean {
const candidateLength = candidate.length;
if (candidate.length > str.length) {
return false;
}
return doEqualsIgnoreCase(str, candidate, candidateLength);
}
/**
* @returns the length of the common prefix of the two strings.
*/
export function commonPrefixLength(a: string, b: string): number {
let i: number,
len = Math.min(a.length, b.length);
for (i = 0; i < len; i++) {
if (a.charCodeAt(i) !== b.charCodeAt(i)) {
return i;
}
}
return len;
}
/**
* @returns the length of the common suffix of the two strings.
*/
export function commonSuffixLength(a: string, b: string): number {
let i: number,
len = Math.min(a.length, b.length);
const aLastIndex = a.length - 1;
const bLastIndex = b.length - 1;
for (i = 0; i < len; i++) {
if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {
return i;
}
}
return len;
}
/**
* See http://en.wikipedia.org/wiki/Surrogate_pair
*/
export function isHighSurrogate(charCode: number): boolean {
return (0xD800 <= charCode && charCode <= 0xDBFF);
}
/**
* See http://en.wikipedia.org/wiki/Surrogate_pair
*/
export function isLowSurrogate(charCode: number): boolean {
return (0xDC00 <= charCode && charCode <= 0xDFFF);
}
/**
* See http://en.wikipedia.org/wiki/Surrogate_pair
*/
export function computeCodePoint(highSurrogate: number, lowSurrogate: number): number {
return ((highSurrogate - 0xD800) << 10) + (lowSurrogate - 0xDC00) + 0x10000;
}
/**
* get the code point that begins at offset `offset`
*/
export function getNextCodePoint(str: string, len: number, offset: number): number {
const charCode = str.charCodeAt(offset);
if (isHighSurrogate(charCode) && offset + 1 < len) {
const nextCharCode = str.charCodeAt(offset + 1);
if (isLowSurrogate(nextCharCode)) {
return computeCodePoint(charCode, nextCharCode);
}
}
return charCode;
}
/**
* get the code point that ends right before offset `offset`
*/
function getPrevCodePoint(str: string, offset: number): number {
const charCode = str.charCodeAt(offset - 1);
if (isLowSurrogate(charCode) && offset > 1) {
const prevCharCode = str.charCodeAt(offset - 2);
if (isHighSurrogate(prevCharCode)) {
return computeCodePoint(prevCharCode, charCode);
}
}
return charCode;
}
export function nextCharLength(str: string, offset: number): number {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
const initialOffset = offset;
const len = str.length;
const initialCodePoint = getNextCodePoint(str, len, offset);
offset += (initialCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
while (offset < len) {
const nextCodePoint = getNextCodePoint(str, len, offset);
const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(nextCodePoint);
if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
offset += (nextCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
return (offset - initialOffset);
}
export function prevCharLength(str: string, offset: number): number {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
const initialOffset = offset;
const initialCodePoint = getPrevCodePoint(str, offset);
offset -= (initialCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
while (offset > 0) {
const prevCodePoint = getPrevCodePoint(str, offset);
const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(prevCodePoint);
if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
break;
}
offset -= (prevCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
graphemeBreakType = prevGraphemeBreakType;
}
return (initialOffset - offset);
}
function _getCharContainingOffset(str: string, offset: number): [number, number] {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
const len = str.length;
const initialOffset = offset;
const initialCodePoint = getNextCodePoint(str, len, offset);
const initialGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(initialCodePoint);
offset += (initialCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
// extend to the right
let graphemeBreakType = initialGraphemeBreakType;
while (offset < len) {
const nextCodePoint = getNextCodePoint(str, len, offset);
const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(nextCodePoint);
if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
break;
}
offset += (nextCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
graphemeBreakType = nextGraphemeBreakType;
}
const endOffset = offset;
// extend to the left
offset = initialOffset;
graphemeBreakType = initialGraphemeBreakType;
while (offset > 0) {
const prevCodePoint = getPrevCodePoint(str, offset);
const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(prevCodePoint);
if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
break;
}
offset -= (prevCodePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
graphemeBreakType = prevGraphemeBreakType;
}
return [offset, endOffset];
}
export function getCharContainingOffset(str: string, offset: number): [number, number] {
if (offset > 0 && isLowSurrogate(str.charCodeAt(offset))) {
return _getCharContainingOffset(str, offset - 1);
}
return _getCharContainingOffset(str, offset);
}
/**
* A manual encoding of `str` to UTF8.
* Use only in environments which do not offer native conversion methods!
*/
export function encodeUTF8(str: string): Uint8Array {
const strLen = str.length;
// See https://en.wikipedia.org/wiki/UTF-8
// first loop to establish needed buffer size
let neededSize = 0;
let strOffset = 0;
while (strOffset < strLen) {
const codePoint = getNextCodePoint(str, strLen, strOffset);
strOffset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
if (codePoint < 0x0080) {
neededSize += 1;
} else if (codePoint < 0x0800) {
neededSize += 2;
} else if (codePoint < 0x10000) {
neededSize += 3;
} else {
neededSize += 4;
}
}
// second loop to actually encode
const arr = new Uint8Array(neededSize);
strOffset = 0;
let arrOffset = 0;
while (strOffset < strLen) {
const codePoint = getNextCodePoint(str, strLen, strOffset);
strOffset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
if (codePoint < 0x0080) {
arr[arrOffset++] = codePoint;
} else if (codePoint < 0x0800) {
arr[arrOffset++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);
arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
} else if (codePoint < 0x10000) {
arr[arrOffset++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);
arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
} else {
arr[arrOffset++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);
arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);
arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
}
}
return arr;
}
/**
* A manual decoding of a UTF8 string.
* Use only in environments which do not offer native conversion methods!
*/
export function decodeUTF8(buffer: Uint8Array): string {
// https://en.wikipedia.org/wiki/UTF-8
const len = buffer.byteLength;
const result: string[] = [];
let offset = 0;
while (offset < len) {
const v0 = buffer[offset];
let codePoint: number;
if (v0 >= 0b11110000 && offset + 3 < len) {
// 4 bytes
codePoint = (
(((buffer[offset++] & 0b00000111) << 18) >>> 0)
| (((buffer[offset++] & 0b00111111) << 12) >>> 0)
| (((buffer[offset++] & 0b00111111) << 6) >>> 0)
| (((buffer[offset++] & 0b00111111) << 0) >>> 0)
);
} else if (v0 >= 0b11100000 && offset + 2 < len) {
// 3 bytes
codePoint = (
(((buffer[offset++] & 0b00001111) << 12) >>> 0)
| (((buffer[offset++] & 0b00111111) << 6) >>> 0)
| (((buffer[offset++] & 0b00111111) << 0) >>> 0)
);
} else if (v0 >= 0b11000000 && offset + 1 < len) {
// 2 bytes
codePoint = (
(((buffer[offset++] & 0b00011111) << 6) >>> 0)
| (((buffer[offset++] & 0b00111111) << 0) >>> 0)
);
} else {
// 1 byte
codePoint = buffer[offset++];
}
if ((codePoint >= 0 && codePoint <= 0xD7FF) || (codePoint >= 0xE000 && codePoint <= 0xFFFF)) {
// Basic Multilingual Plane
result.push(String.fromCharCode(codePoint));
} else if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
// Supplementary Planes
const uPrime = codePoint - 0x10000;
const w1 = 0xD800 + ((uPrime & 0b11111111110000000000) >>> 10);
const w2 = 0xDC00 + ((uPrime & 0b00000000001111111111) >>> 0);
result.push(String.fromCharCode(w1));
result.push(String.fromCharCode(w2));
} else {
// illegal code point
result.push(String.fromCharCode(0xFFFD));
}
}
return result.join('');
}
/**
* Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-rtl-test.js
*/
const CONTAINS_RTL = /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE33\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDCFF]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD50-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
/**
* Returns true if `str` contains any Unicode character that is classified as "R" or "AL".
*/
export function containsRTL(str: string): boolean {
return CONTAINS_RTL.test(str);
}
/**
* Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-emoji-test.js
*/
const CONTAINS_EMOJI = /(?:[\u231A\u231B\u23F0\u23F3\u2600-\u27BF\u2B50\u2B55]|\uD83C[\uDDE6-\uDDFF\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F\uDE80-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD00-\uDDFF\uDE70-\uDE73\uDE78-\uDE82\uDE90-\uDE95])/;
export function containsEmoji(str: string): boolean {
return CONTAINS_EMOJI.test(str);
}
const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
/**
* Returns true if `str` contains only basic ASCII characters in the range 32 - 126 (including 32 and 126) or \n, \r, \t
*/
export function isBasicASCII(str: string): boolean {
return IS_BASIC_ASCII.test(str);
}
export const UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/; // LINE SEPARATOR (LS) or PARAGRAPH SEPARATOR (PS)
/**
* Returns true if `str` contains unusual line terminators, like LS or PS
*/
export function containsUnusualLineTerminators(str: string): boolean {
return UNUSUAL_LINE_TERMINATORS.test(str);
}
export function containsFullWidthCharacter(str: string): boolean {
for (let i = 0, len = str.length; i < len; i++) {
if (isFullWidthCharacter(str.charCodeAt(i))) {
return true;
}
}
return false;
}
export function isFullWidthCharacter(charCode: number): boolean {
// Do a cheap trick to better support wrapping of wide characters, treat them as 2 columns
// http://jrgraphix.net/research/unicode_blocks.php
// 2E80 — 2EFF CJK Radicals Supplement
// 2F00 — 2FDF Kangxi Radicals
// 2FF0 — 2FFF Ideographic Description Characters
// 3000 — 303F CJK Symbols and Punctuation
// 3040 — 309F Hiragana
// 30A0 — 30FF Katakana
// 3100 — 312F Bopomofo
// 3130 — 318F Hangul Compatibility Jamo
// 3190 — 319F Kanbun
// 31A0 — 31BF Bopomofo Extended
// 31F0 — 31FF Katakana Phonetic Extensions
// 3200 — 32FF Enclosed CJK Letters and Months
// 3300 — 33FF CJK Compatibility
// 3400 — 4DBF CJK Unified Ideographs Extension A
// 4DC0 — 4DFF Yijing Hexagram Symbols
// 4E00 — 9FFF CJK Unified Ideographs
// A000 — A48F Yi Syllables
// A490 — A4CF Yi Radicals
// AC00 — D7AF Hangul Syllables
// [IGNORE] D800 — DB7F High Surrogates
// [IGNORE] DB80 — DBFF High Private Use Surrogates
// [IGNORE] DC00 — DFFF Low Surrogates
// [IGNORE] E000 — F8FF Private Use Area
// F900 — FAFF CJK Compatibility Ideographs
// [IGNORE] FB00 — FB4F Alphabetic Presentation Forms
// [IGNORE] FB50 — FDFF Arabic Presentation Forms-A
// [IGNORE] FE00 — FE0F Variation Selectors
// [IGNORE] FE20 — FE2F Combining Half Marks
// [IGNORE] FE30 — FE4F CJK Compatibility Forms
// [IGNORE] FE50 — FE6F Small Form Variants
// [IGNORE] FE70 — FEFF Arabic Presentation Forms-B
// FF00 — FFEF Halfwidth and Fullwidth Forms
// [https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms]
// of which FF01 - FF5E fullwidth ASCII of 21 to 7E
// [IGNORE] and FF65 - FFDC halfwidth of Katakana and Hangul
// [IGNORE] FFF0 — FFFF Specials
charCode = +charCode; // @perf
return (
(charCode >= 0x2E80 && charCode <= 0xD7AF)
|| (charCode >= 0xF900 && charCode <= 0xFAFF)
|| (charCode >= 0xFF01 && charCode <= 0xFF5E)
);
}
/**
* A fast function (therefore imprecise) to check if code points are emojis.
* Generated using https://github.com/alexandrudima/unicode-utils/blob/master/generate-emoji-test.js
*/
export function isEmojiImprecise(x: number): boolean {
return (
(x >= 0x1F1E6 && x <= 0x1F1FF) || (x >= 9728 && x <= 10175) || (x >= 127744 && x <= 128591)
|| (x >= 128640 && x <= 128764) || (x >= 128992 && x <= 129003) || (x >= 129280 && x <= 129535)
|| (x >= 129648 && x <= 129651) || (x >= 129656 && x <= 129666) || (x >= 129680 && x <= 129685)
);
}
/**
* Given a string and a max length returns a shorted version. Shorting
* happens at favorable positions - such as whitespace or punctuation characters.
*/
export function lcut(text: string, n: number) {
if (text.length < n) {
return text;
}
const re = /\b/g;
let i = 0;
while (re.test(text)) {
if (text.length - re.lastIndex < n) {
break;
}
i = re.lastIndex;
re.lastIndex += 1;
}
return text.substring(i).replace(/^\s/, '');
}
// Escape codes
// http://en.wikipedia.org/wiki/ANSI_escape_code
const EL = /\x1B\x5B[12]?K/g; // Erase in line
const COLOR_START = /\x1b\[\d+m/g; // Color
const COLOR_END = /\x1b\[0?m/g; // Color
export function removeAnsiEscapeCodes(str: string): string {
if (str) {
str = str.replace(EL, '');
str = str.replace(COLOR_START, '');
str = str.replace(COLOR_END, '');
}
return str;
}
// -- UTF-8 BOM
export const UTF8_BOM_CHARACTER = String.fromCharCode(CharCode.UTF8_BOM);
export function startsWithUTF8BOM(str: string): boolean {
return !!(str && str.length > 0 && str.charCodeAt(0) === CharCode.UTF8_BOM);
}
export function stripUTF8BOM(str: string): string {
return startsWithUTF8BOM(str) ? str.substr(1) : str;
}
/**
* Checks if the characters of the provided query string are included in the
* target string. The characters do not have to be contiguous within the string.
*/
export function fuzzyContains(target: string, query: string): boolean {
if (!target || !query) {
return false; // return early if target or query are undefined
}
if (target.length < query.length) {
return false; // impossible for query to be contained in target
}
const queryLen = query.length;
const targetLower = target.toLowerCase();
let index = 0;
let lastIndexOf = -1;
while (index < queryLen) {
const indexOf = targetLower.indexOf(query[index], lastIndexOf + 1);
if (indexOf < 0) {
return false;
}
lastIndexOf = indexOf;
index++;
}
return true;
}
export function containsUppercaseCharacter(target: string, ignoreEscapedChars = false): boolean {
if (!target) {
return false;
}
if (ignoreEscapedChars) {
target = target.replace(/\\./g, '');
}
return target.toLowerCase() !== target;
}
export function uppercaseFirstLetter(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function getNLines(str: string, n = 1): string {
if (n === 0) {
return '';
}
let idx = -1;
do {
idx = str.indexOf('\n', idx + 1);
n--;
} while (n > 0 && idx >= 0);
return idx >= 0 ?
str.substr(0, idx) :
str;
}
/**
* Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
*/
export function singleLetterHash(n: number): string {
const LETTERS_CNT = (CharCode.Z - CharCode.A + 1);
n = n % (2 * LETTERS_CNT);
if (n < LETTERS_CNT) {
return String.fromCharCode(CharCode.a + n);
}
return String.fromCharCode(CharCode.A + n - LETTERS_CNT);
}
//#region Unicode Grapheme Break
export function getGraphemeBreakType(codePoint: number): GraphemeBreakType {
const graphemeBreakTree = GraphemeBreakTree.getInstance();
return graphemeBreakTree.getGraphemeBreakType(codePoint);
}
export function breakBetweenGraphemeBreakType(breakTypeA: GraphemeBreakType, breakTypeB: GraphemeBreakType): boolean {
// http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
// !!! Let's make the common case a bit faster
if (breakTypeA === GraphemeBreakType.Other) {
// see https://www.unicode.org/Public/13.0.0/ucd/auxiliary/GraphemeBreakTest-13.0.0d10.html#table
return (breakTypeB !== GraphemeBreakType.Extend && breakTypeB !== GraphemeBreakType.SpacingMark);
}
// Do not break between a CR and LF. Otherwise, break before and after controls.
// GB3 CR × LF
// GB4 (Control | CR | LF) ÷
// GB5 ÷ (Control | CR | LF)
if (breakTypeA === GraphemeBreakType.CR) {
if (breakTypeB === GraphemeBreakType.LF) {
return false; // GB3
}
}
if (breakTypeA === GraphemeBreakType.Control || breakTypeA === GraphemeBreakType.CR || breakTypeA === GraphemeBreakType.LF) {
return true; // GB4
}
if (breakTypeB === GraphemeBreakType.Control || breakTypeB === GraphemeBreakType.CR || breakTypeB === GraphemeBreakType.LF) {
return true; // GB5
}
// Do not break Hangul syllable sequences.
// GB6 L × (L | V | LV | LVT)
// GB7 (LV | V) × (V | T)
// GB8 (LVT | T) × T
if (breakTypeA === GraphemeBreakType.L) {
if (breakTypeB === GraphemeBreakType.L || breakTypeB === GraphemeBreakType.V || breakTypeB === GraphemeBreakType.LV || breakTypeB === GraphemeBreakType.LVT) {
return false; // GB6
}
}
if (breakTypeA === GraphemeBreakType.LV || breakTypeA === GraphemeBreakType.V) {
if (breakTypeB === GraphemeBreakType.V || breakTypeB === GraphemeBreakType.T) {
return false; // GB7
}
}
if (breakTypeA === GraphemeBreakType.LVT || breakTypeA === GraphemeBreakType.T) {
if (breakTypeB === GraphemeBreakType.T) {
return false; // GB8
}
}
// Do not break before extending characters or ZWJ.
// GB9 × (Extend | ZWJ)
if (breakTypeB === GraphemeBreakType.Extend || breakTypeB === GraphemeBreakType.ZWJ) {
return false; // GB9
}
// The GB9a and GB9b rules only apply to extended grapheme clusters:
// Do not break before SpacingMarks, or after Prepend characters.
// GB9a × SpacingMark
// GB9b Prepend ×
if (breakTypeB === GraphemeBreakType.SpacingMark) {
return false; // GB9a
}
if (breakTypeA === GraphemeBreakType.Prepend) {
return false; // GB9b
}
// Do not break within emoji modifier sequences or emoji zwj sequences.
// GB11 \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic}
if (breakTypeA === GraphemeBreakType.ZWJ && breakTypeB === GraphemeBreakType.Extended_Pictographic) {
// Note: we are not implementing the rule entirely here to avoid introducing states
return false; // GB11
}
// GB12 sot (RI RI)* RI × RI
// GB13 [^RI] (RI RI)* RI × RI
if (breakTypeA === GraphemeBreakType.Regional_Indicator && breakTypeB === GraphemeBreakType.Regional_Indicator) {
// Note: we are not implementing the rule entirely here to avoid introducing states
return false; // GB12 & GB13
}
// GB999 Any ÷ Any
return true;
}
export const enum GraphemeBreakType {
Other = 0,
Prepend = 1,
CR = 2,
LF = 3,
Control = 4,
Extend = 5,
Regional_Indicator = 6,
SpacingMark = 7,
L = 8,
V = 9,
T = 10,