strings.ts 18.4 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Johannes Rieken 已提交
6
import { CharCode } from 'vs/base/common/charCode';
7

E
Erich Gamma 已提交
8 9 10
/**
 * The empty string.
 */
B
Benjamin Pasero 已提交
11
export const empty = '';
E
Erich Gamma 已提交
12

M
Matt Bierner 已提交
13
export function isFalsyOrWhitespace(str: string | undefined): boolean {
14 15 16 17 18 19
	if (!str || typeof str !== 'string') {
		return true;
	}
	return str.trim().length === 0;
}

E
Erich Gamma 已提交
20
/**
21
 * @returns the provided number with the given number of preceding zeros.
E
Erich Gamma 已提交
22 23
 */
export function pad(n: number, l: number, char: string = '0'): string {
B
Benjamin Pasero 已提交
24 25
	let str = '' + n;
	let r = [str];
E
Erich Gamma 已提交
26

B
Benjamin Pasero 已提交
27
	for (let i = str.length; i < l; i++) {
E
Erich Gamma 已提交
28 29 30 31 32 33
		r.push(char);
	}

	return r.reverse().join('');
}

B
Benjamin Pasero 已提交
34
const _formatRegexp = /{(\d+)}/g;
E
Erich Gamma 已提交
35 36 37 38 39 40 41 42 43 44 45

/**
 * 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;
	}
J
Johannes Rieken 已提交
46
	return value.replace(_formatRegexp, function (match, group) {
B
Benjamin Pasero 已提交
47
		let idx = parseInt(group, 10);
E
Erich Gamma 已提交
48 49 50 51 52 53 54 55 56 57 58
		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 {
J
Johannes Rieken 已提交
59
	return html.replace(/[<|>|&]/g, function (match) {
E
Erich Gamma 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72
		switch (match) {
			case '<': return '&lt;';
			case '>': return '&gt;';
			case '&': return '&amp;';
			default: return match;
		}
	});
}

/**
 * Escapes regular expression characters in a given string
 */
export function escapeRegExpCharacters(value: string): string {
73
	return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\[\]\(\)\#]/g, '\\$&');
E
Erich Gamma 已提交
74 75 76
}

/**
P
Pascal Borreli 已提交
77
 * Removes all occurrences of needle from the beginning and end of haystack.
E
Erich Gamma 已提交
78 79 80
 * @param haystack string to trim
 * @param needle the thing to trim (default is a blank)
 */
R
Rob Lourens 已提交
81
export function trim(haystack: string, needle: string = ' '): string {
B
Benjamin Pasero 已提交
82
	let trimmed = ltrim(haystack, needle);
E
Erich Gamma 已提交
83 84 85 86
	return rtrim(trimmed, needle);
}

/**
P
Pascal Borreli 已提交
87
 * Removes all occurrences of needle from the beginning of haystack.
E
Erich Gamma 已提交
88 89 90
 * @param haystack string to trim
 * @param needle the thing to trim
 */
91
export function ltrim(haystack: string, needle: string): string {
E
Erich Gamma 已提交
92 93 94 95
	if (!haystack || !needle) {
		return haystack;
	}

B
Benjamin Pasero 已提交
96
	let needleLen = needle.length;
E
Erich Gamma 已提交
97 98 99 100
	if (needleLen === 0 || haystack.length === 0) {
		return haystack;
	}

101
	let offset = 0;
E
Erich Gamma 已提交
102

103
	while (haystack.indexOf(needle, offset) === offset) {
E
Erich Gamma 已提交
104 105 106 107 108 109
		offset = offset + needleLen;
	}
	return haystack.substring(offset);
}

/**
P
Pascal Borreli 已提交
110
 * Removes all occurrences of needle from the end of haystack.
E
Erich Gamma 已提交
111 112 113
 * @param haystack string to trim
 * @param needle the thing to trim
 */
114
export function rtrim(haystack: string, needle: string): string {
E
Erich Gamma 已提交
115 116 117 118
	if (!haystack || !needle) {
		return haystack;
	}

B
Benjamin Pasero 已提交
119
	let needleLen = needle.length,
E
Erich Gamma 已提交
120 121 122 123 124 125
		haystackLen = haystack.length;

	if (needleLen === 0 || haystackLen === 0) {
		return haystack;
	}

B
Benjamin Pasero 已提交
126
	let offset = haystackLen,
E
Erich Gamma 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
		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 {
B
Benjamin Pasero 已提交
148
	return pattern.replace(/\*/g, '');
E
Erich Gamma 已提交
149 150 151 152 153 154 155 156 157 158
}

/**
 * Determines if haystack starts with needle.
 */
export function startsWith(haystack: string, needle: string): boolean {
	if (haystack.length < needle.length) {
		return false;
	}

159 160 161 162
	if (haystack === needle) {
		return true;
	}

B
Benjamin Pasero 已提交
163
	for (let i = 0; i < needle.length; i++) {
E
Erich Gamma 已提交
164 165 166 167 168 169 170 171 172 173 174 175
		if (haystack[i] !== needle[i]) {
			return false;
		}
	}

	return true;
}

/**
 * Determines if haystack ends with needle.
 */
export function endsWith(haystack: string, needle: string): boolean {
B
Benjamin Pasero 已提交
176
	let diff = haystack.length - needle.length;
E
Erich Gamma 已提交
177
	if (diff > 0) {
C
Christof Marti 已提交
178
		return haystack.indexOf(needle, diff) === diff;
E
Erich Gamma 已提交
179 180 181 182 183 184 185
	} else if (diff === 0) {
		return haystack === needle;
	} else {
		return false;
	}
}

S
Sandeep Somavarapu 已提交
186 187 188 189 190 191 192 193
export interface RegExpOptions {
	matchCase?: boolean;
	wholeWord?: boolean;
	multiline?: boolean;
	global?: boolean;
}

export function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp {
194
	if (!searchString) {
E
Erich Gamma 已提交
195 196 197
		throw new Error('Cannot create regex from empty string');
	}
	if (!isRegex) {
198
		searchString = escapeRegExpCharacters(searchString);
E
Erich Gamma 已提交
199
	}
S
Sandeep Somavarapu 已提交
200
	if (options.wholeWord) {
E
Erich Gamma 已提交
201 202 203 204 205 206 207
		if (!/\B/.test(searchString.charAt(0))) {
			searchString = '\\b' + searchString;
		}
		if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
			searchString = searchString + '\\b';
		}
	}
208
	let modifiers = '';
S
Sandeep Somavarapu 已提交
209
	if (options.global) {
210 211
		modifiers += 'g';
	}
S
Sandeep Somavarapu 已提交
212
	if (!options.matchCase) {
E
Erich Gamma 已提交
213 214
		modifiers += 'i';
	}
S
Sandeep Somavarapu 已提交
215 216 217
	if (options.multiline) {
		modifiers += 'm';
	}
E
Erich Gamma 已提交
218 219 220 221 222

	return new RegExp(searchString, modifiers);
}

export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {
223 224
	// Exit early if it's one of these special cases which are meant to match
	// against an empty string
225
	if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$' || regexp.source === '^\\s*$') {
226 227 228
		return false;
	}

E
Erich Gamma 已提交
229 230
	// 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.
B
Benjamin Pasero 已提交
231
	let match = regexp.exec('');
M
Matt Bierner 已提交
232
	return !!(match && <any>regexp.lastIndex === 0);
E
Erich Gamma 已提交
233 234
}

235 236 237 238
export function regExpContainsBackreference(regexpValue: string): boolean {
	return !!regexpValue.match(/([^\\]|^)(\\\\)*\\\d+/);
}

E
Erich Gamma 已提交
239 240 241 242 243
/**
 * 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 {
B
Benjamin Pasero 已提交
244
	for (let i = 0, len = str.length; i < len; i++) {
245 246
		let chCode = str.charCodeAt(i);
		if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
E
Erich Gamma 已提交
247 248 249 250 251 252 253 254 255 256
			return i;
		}
	}
	return -1;
}

/**
 * Returns the leading whitespace of the string.
 * If the string contains only whitespaces, returns entire string
 */
257 258
export function getLeadingWhitespace(str: string, start: number = 0, end: number = str.length): string {
	for (let i = start; i < end; i++) {
259 260
		let chCode = str.charCodeAt(i);
		if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
261
			return str.substring(start, i);
E
Erich Gamma 已提交
262 263
		}
	}
264
	return str.substring(start, end);
E
Erich Gamma 已提交
265 266 267 268 269 270
}

/**
 * Returns last index of the string that is not whitespace.
 * If string is empty or contains only whitespaces, returns -1
 */
271 272
export function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number {
	for (let i = startIndex; i >= 0; i--) {
273 274
		let chCode = str.charCodeAt(i);
		if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
E
Erich Gamma 已提交
275 276 277 278 279 280
			return i;
		}
	}
	return -1;
}

J
Johannes Rieken 已提交
281
export function compare(a: string, b: string): number {
282 283
	if (a < b) {
		return -1;
J
Johannes Rieken 已提交
284
	} else if (a > b) {
285 286 287 288 289 290
		return 1;
	} else {
		return 0;
	}
}

291 292 293
export function compareIgnoreCase(a: string, b: string): number {
	const len = Math.min(a.length, b.length);
	for (let i = 0; i < len; i++) {
J
Johannes Rieken 已提交
294 295
		let codeA = a.charCodeAt(i);
		let codeB = b.charCodeAt(i);
296 297 298 299 300 301

		if (codeA === codeB) {
			// equal
			continue;
		}

J
Johannes Rieken 已提交
302
		if (isUpperAsciiLetter(codeA)) {
S
Sandeep Somavarapu 已提交
303
			codeA += 32;
J
Johannes Rieken 已提交
304 305 306
		}

		if (isUpperAsciiLetter(codeB)) {
S
Sandeep Somavarapu 已提交
307
			codeB += 32;
J
Johannes Rieken 已提交
308 309 310 311 312 313 314 315 316 317 318 319
		}

		const diff = codeA - codeB;

		if (diff === 0) {
			// equal -> ignoreCase
			continue;

		} else if (isLowerAsciiLetter(codeA) && isLowerAsciiLetter(codeB)) {
			//
			return diff;

J
Johannes Rieken 已提交
320 321
		} else {
			return compare(a.toLowerCase(), b.toLowerCase());
322 323 324 325 326 327 328 329 330 331 332 333
		}
	}

	if (a.length < b.length) {
		return -1;
	} else if (a.length > b.length) {
		return 1;
	} else {
		return 0;
	}
}

A
Alex Dima 已提交
334
export function isLowerAsciiLetter(code: number): boolean {
J
Johannes Rieken 已提交
335 336 337
	return code >= CharCode.a && code <= CharCode.z;
}

A
Alex Dima 已提交
338
export function isUpperAsciiLetter(code: number): boolean {
J
Johannes Rieken 已提交
339 340 341
	return code >= CharCode.A && code <= CharCode.Z;
}

342
function isAsciiLetter(code: number): boolean {
J
Johannes Rieken 已提交
343
	return isLowerAsciiLetter(code) || isUpperAsciiLetter(code);
E
Erich Gamma 已提交
344 345 346
}

export function equalsIgnoreCase(a: string, b: string): boolean {
347 348
	const len1 = a ? a.length : 0;
	const len2 = b ? b.length : 0;
E
Erich Gamma 已提交
349 350 351 352 353

	if (len1 !== len2) {
		return false;
	}

B
Benjamin Pasero 已提交
354 355 356
	return doEqualsIgnoreCase(a, b);
}

357 358 359 360 361
function doEqualsIgnoreCase(a: string, b: string, stopAt = a.length): boolean {
	if (typeof a !== 'string' || typeof b !== 'string') {
		return false;
	}

B
Benjamin Pasero 已提交
362
	for (let i = 0; i < stopAt; i++) {
363 364
		const codeA = a.charCodeAt(i);
		const codeB = b.charCodeAt(i);
E
Erich Gamma 已提交
365 366 367

		if (codeA === codeB) {
			continue;
368
		}
E
Erich Gamma 已提交
369

370 371
		// a-z A-Z
		if (isAsciiLetter(codeA) && isAsciiLetter(codeB)) {
B
Benjamin Pasero 已提交
372
			let diff = Math.abs(codeA - codeB);
E
Erich Gamma 已提交
373 374 375
			if (diff !== 0 && diff !== 32) {
				return false;
			}
376 377 378 379 380
		}

		// Any other charcode
		else {
			if (String.fromCharCode(codeA).toLowerCase() !== String.fromCharCode(codeB).toLowerCase()) {
E
Erich Gamma 已提交
381 382 383 384 385 386 387 388
				return false;
			}
		}
	}

	return true;
}

389
export function startsWithIgnoreCase(str: string, candidate: string): boolean {
B
Benjamin Pasero 已提交
390 391 392 393 394 395 396 397
	const candidateLength = candidate.length;
	if (candidate.length > str.length) {
		return false;
	}

	return doEqualsIgnoreCase(str, candidate, candidateLength);
}

E
Erich Gamma 已提交
398
/**
399
 * @returns the length of the common prefix of the two strings.
E
Erich Gamma 已提交
400 401 402
 */
export function commonPrefixLength(a: string, b: string): number {

B
Benjamin Pasero 已提交
403
	let i: number,
E
Erich Gamma 已提交
404 405 406 407 408 409 410 411 412 413 414 415
		len = Math.min(a.length, b.length);

	for (i = 0; i < len; i++) {
		if (a.charCodeAt(i) !== b.charCodeAt(i)) {
			return i;
		}
	}

	return len;
}

/**
416
 * @returns the length of the common suffix of the two strings.
E
Erich Gamma 已提交
417 418 419
 */
export function commonSuffixLength(a: string, b: string): number {

B
Benjamin Pasero 已提交
420
	let i: number,
E
Erich Gamma 已提交
421 422
		len = Math.min(a.length, b.length);

B
Benjamin Pasero 已提交
423 424
	let aLastIndex = a.length - 1;
	let bLastIndex = b.length - 1;
E
Erich Gamma 已提交
425 426 427 428 429 430 431 432 433 434

	for (i = 0; i < len; i++) {
		if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {
			return i;
		}
	}

	return len;
}

J
Johannes Rieken 已提交
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
function substrEquals(a: string, aStart: number, aEnd: number, b: string, bStart: number, bEnd: number): boolean {
	while (aStart < aEnd && bStart < bEnd) {
		if (a[aStart] !== b[bStart]) {
			return false;
		}
		aStart += 1;
		bStart += 1;
	}
	return true;
}

/**
 * Return the overlap between the suffix of `a` and the prefix of `b`.
 * For instance `overlap("foobar", "arr, I'm a pirate") === 2`.
 */
export function overlap(a: string, b: string): number {
	let aEnd = a.length;
	let bEnd = b.length;
	let aStart = aEnd - bEnd;

	if (aStart === 0) {
		return a === b ? aEnd : 0;
	} else if (aStart < 0) {
		bEnd += aStart;
		aStart = 0;
	}

	while (aStart < aEnd && bEnd > 0) {
		if (substrEquals(a, aStart, aEnd, b, 0, bEnd)) {
			return bEnd;
		}
		bEnd -= 1;
		aStart += 1;
	}
	return 0;
}

E
Erich Gamma 已提交
472 473 474 475 476 477
// --- unicode
// http://en.wikipedia.org/wiki/Surrogate_pair
// Returns the code point starting at a specified index in a string
// Code points U+0000 to U+D7FF and U+E000 to U+FFFF are represented on a single character
// Code points U+10000 to U+10FFFF are represented on two consecutive characters
//export function getUnicodePoint(str:string, index:number, len:number):number {
B
Benjamin Pasero 已提交
478
//	let chrCode = str.charCodeAt(index);
E
Erich Gamma 已提交
479
//	if (0xD800 <= chrCode && chrCode <= 0xDBFF && index + 1 < len) {
B
Benjamin Pasero 已提交
480
//		let nextChrCode = str.charCodeAt(index + 1);
E
Erich Gamma 已提交
481 482 483 484 485 486
//		if (0xDC00 <= nextChrCode && nextChrCode <= 0xDFFF) {
//			return (chrCode - 0xD800) << 10 + (nextChrCode - 0xDC00) + 0x10000;
//		}
//	}
//	return chrCode;
//}
J
Johannes Rieken 已提交
487
export function isHighSurrogate(charCode: number): boolean {
488 489 490
	return (0xD800 <= charCode && charCode <= 0xDBFF);
}

J
Johannes Rieken 已提交
491
export function isLowSurrogate(charCode: number): boolean {
492 493
	return (0xDC00 <= charCode && charCode <= 0xDFFF);
}
E
Erich Gamma 已提交
494

A
Alex Dima 已提交
495 496 497 498 499 500 501 502 503 504 505 506
/**
 * 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);
}

507 508 509 510 511 512 513 514 515
/**
 * 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-\uDEF8]|\uD83E[\uDD00-\uDDE6])/;

export function containsEmoji(str: string): boolean {
	return CONTAINS_EMOJI.test(str);
}

516 517 518 519 520 521 522 523
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);
}

A
Alex Dima 已提交
524 525 526 527 528 529 530 531 532
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;
}

J
Johannes Rieken 已提交
533
export function isFullWidthCharacter(charCode: number): boolean {
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
	// 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
A
Alex Dima 已提交
572
	charCode = +charCode; // @perf
573 574 575 576 577 578 579
	return (
		(charCode >= 0x2E80 && charCode <= 0xD7AF)
		|| (charCode >= 0xF900 && charCode <= 0xFAFF)
		|| (charCode >= 0xFF01 && charCode <= 0xFF5E)
	);
}

E
Erich Gamma 已提交
580 581 582 583
/**
 * Given a string and a max length returns a shorted version. Shorting
 * happens at favorable positions - such as whitespace or punctuation characters.
 */
R
Rob Lourens 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
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/, empty);
}

E
Erich Gamma 已提交
603 604
// Escape codes
// http://en.wikipedia.org/wiki/ANSI_escape_code
B
Benjamin Pasero 已提交
605 606 607
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
E
Erich Gamma 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620

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

A
Alex Dima 已提交
621
export const UTF8_BOM_CHARACTER = String.fromCharCode(CharCode.UTF8_BOM);
E
Erich Gamma 已提交
622 623

export function startsWithUTF8BOM(str: string): boolean {
M
Matt Bierner 已提交
624
	return !!(str && str.length > 0 && str.charCodeAt(0) === CharCode.UTF8_BOM);
I
isidor 已提交
625 626
}

627 628 629 630
export function stripUTF8BOM(str: string): string {
	return startsWithUTF8BOM(str) ? str.substr(1) : str;
}

631 632
export function safeBtoa(str: string): string {
	return btoa(encodeURIComponent(str)); // we use encodeURIComponent because btoa fails for non Latin 1 values
633 634
}

J
Johannes Rieken 已提交
635
export function repeat(s: string, count: number): string {
B
Benjamin Pasero 已提交
636 637
	let result = '';
	for (let i = 0; i < count; i++) {
638 639 640
		result += s;
	}
	return result;
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

/**
 * 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) {
		let indexOf = targetLower.indexOf(query[index], lastIndexOf + 1);
		if (indexOf < 0) {
			return false;
		}

		lastIndexOf = indexOf;

		index++;
	}

	return true;
J
Johannes Rieken 已提交
673
}
674 675 676 677 678 679 680 681 682 683 684 685

export function containsUppercaseCharacter(target: string, ignoreEscapedChars = false): boolean {
	if (!target) {
		return false;
	}

	if (ignoreEscapedChars) {
		target = target.replace(/\\./g, '');
	}

	return target.toLowerCase() !== target;
}
686 687 688

export function uppercaseFirstLetter(str: string): string {
	return str.charAt(0).toUpperCase() + str.slice(1);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
}

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;
}