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

B
Benjamin Pasero 已提交
7
import {BoundedLinkedMap} from 'vs/base/common/map';
8
import {CharCode} from 'vs/base/common/charCode';
9

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

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

B
Benjamin Pasero 已提交
22
	for (let i = str.length; i < l; i++) {
E
Erich Gamma 已提交
23 24 25 26 27 28
		r.push(char);
	}

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

B
Benjamin Pasero 已提交
29
const _formatRegexp = /{(\d+)}/g;
E
Erich Gamma 已提交
30 31 32 33 34 35 36 37 38 39 40

/**
 * 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;
	}
41
	return value.replace(_formatRegexp, function(match, group) {
B
Benjamin Pasero 已提交
42
		let idx = parseInt(group, 10);
E
Erich Gamma 已提交
43 44 45 46 47 48 49 50 51 52 53
		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 {
54
	return html.replace(/[<|>|&]/g, function(match) {
E
Erich Gamma 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
		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 {
	return value.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
}

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

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

B
Benjamin Pasero 已提交
91
	let needleLen = needle.length;
E
Erich Gamma 已提交
92 93 94 95
	if (needleLen === 0 || haystack.length === 0) {
		return haystack;
	}

B
Benjamin Pasero 已提交
96
	let offset = 0,
E
Erich Gamma 已提交
97 98 99 100 101 102 103 104 105
		idx = -1;

	while ((idx = haystack.indexOf(needle, offset)) === offset) {
		offset = offset + needleLen;
	}
	return haystack.substring(offset);
}

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

B
Benjamin Pasero 已提交
115
	let needleLen = needle.length,
E
Erich Gamma 已提交
116 117 118 119 120 121
		haystackLen = haystack.length;

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

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

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

B
Benjamin Pasero 已提交
155
	for (let i = 0; i < needle.length; i++) {
E
Erich Gamma 已提交
156 157 158 159 160 161 162 163 164 165 166 167
		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 已提交
168
	let diff = haystack.length - needle.length;
E
Erich Gamma 已提交
169
	if (diff > 0) {
C
Christof Marti 已提交
170
		return haystack.indexOf(needle, diff) === diff;
E
Erich Gamma 已提交
171 172 173 174 175 176 177
	} else if (diff === 0) {
		return haystack === needle;
	} else {
		return false;
	}
}

S
Sandeep Somavarapu 已提交
178 179 180 181 182 183 184 185
export interface RegExpOptions {
	matchCase?: boolean;
	wholeWord?: boolean;
	multiline?: boolean;
	global?: boolean;
}

export function createRegExp(searchString: string, isRegex: boolean, options: RegExpOptions = {}): RegExp {
E
Erich Gamma 已提交
186 187 188 189 190 191
	if (searchString === '') {
		throw new Error('Cannot create regex from empty string');
	}
	if (!isRegex) {
		searchString = searchString.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
	}
S
Sandeep Somavarapu 已提交
192
	if (options.wholeWord) {
E
Erich Gamma 已提交
193 194 195 196 197 198 199
		if (!/\B/.test(searchString.charAt(0))) {
			searchString = '\\b' + searchString;
		}
		if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
			searchString = searchString + '\\b';
		}
	}
200
	let modifiers = '';
S
Sandeep Somavarapu 已提交
201
	if (options.global) {
202 203
		modifiers += 'g';
	}
S
Sandeep Somavarapu 已提交
204
	if (!options.matchCase) {
E
Erich Gamma 已提交
205 206
		modifiers += 'i';
	}
S
Sandeep Somavarapu 已提交
207 208 209
	if (options.multiline) {
		modifiers += 'm';
	}
E
Erich Gamma 已提交
210 211 212 213 214

	return new RegExp(searchString, modifiers);
}

export function regExpLeadsToEndlessLoop(regexp: RegExp): boolean {
215 216
	// Exit early if it's one of these special cases which are meant to match
	// against an empty string
J
Joao Moreno 已提交
217
	if (regexp.source === '^' || regexp.source === '^$' || regexp.source === '$') {
218 219 220
		return false;
	}

E
Erich Gamma 已提交
221 222
	// 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 已提交
223
	let match = regexp.exec('');
E
Erich Gamma 已提交
224 225 226 227 228 229 230
	return (match && <any>regexp.lastIndex === 0);
}

/**
 * The normalize() method returns the Unicode Normalization Form of a given string. The form will be
 * the Normalization Form Canonical Composition.
 *
231
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize}
E
Erich Gamma 已提交
232
 */
B
Benjamin Pasero 已提交
233
export let canNormalize = typeof ((<any>'').normalize) === 'function';
234
const nonAsciiCharactersPattern = /[^\u0000-\u0080]/;
B
Benjamin Pasero 已提交
235
const normalizedCache = new BoundedLinkedMap<string>(10000); // bounded to 10000 elements
236
export function normalizeNFC(str: string): string {
E
Erich Gamma 已提交
237 238 239 240
	if (!canNormalize || !str) {
		return str;
	}

241
	const cached = normalizedCache.get(str);
242 243
	if (cached) {
		return cached;
E
Erich Gamma 已提交
244 245
	}

246 247 248 249 250 251
	let res: string;
	if (nonAsciiCharactersPattern.test(str)) {
		res = (<any>str).normalize('NFC');
	} else {
		res = str;
	}
E
Erich Gamma 已提交
252

B
Benjamin Pasero 已提交
253 254
	// Use the cache for fast lookup
	normalizedCache.set(str, res);
E
Erich Gamma 已提交
255 256 257 258 259 260 261 262 263

	return res;
}

/**
 * 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 已提交
264
	for (let i = 0, len = str.length; i < len; i++) {
265 266
		let chCode = str.charCodeAt(i);
		if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
E
Erich Gamma 已提交
267 268 269 270 271 272 273 274 275 276 277
			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): string {
B
Benjamin Pasero 已提交
278
	for (let i = 0, len = str.length; i < len; i++) {
279 280
		let chCode = str.charCodeAt(i);
		if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289 290
			return str.substring(0, i);
		}
	}
	return str;
}

/**
 * Returns last index of the string that is not whitespace.
 * If string is empty or contains only whitespaces, returns -1
 */
291 292
export function lastNonWhitespaceIndex(str: string, startIndex: number = str.length - 1): number {
	for (let i = startIndex; i >= 0; i--) {
293 294
		let chCode = str.charCodeAt(i);
		if (chCode !== CharCode.Space && chCode !== CharCode.Tab) {
E
Erich Gamma 已提交
295 296 297 298 299 300
			return i;
		}
	}
	return -1;
}

301 302 303 304 305 306 307 308 309 310
export function compare(a: string, b: string): number {
	if (a < b) {
		return -1;
	} else if(a > b) {
		return 1;
	} else {
		return 0;
	}
}

E
Erich Gamma 已提交
311
function isAsciiChar(code: number): boolean {
312
	return (code >= CharCode.a && code <= CharCode.z) || (code >= CharCode.A && code <= CharCode.Z);
E
Erich Gamma 已提交
313 314 315 316
}

export function equalsIgnoreCase(a: string, b: string): boolean {

B
Benjamin Pasero 已提交
317
	let len1 = a.length,
E
Erich Gamma 已提交
318 319 320 321 322 323
		len2 = b.length;

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

B
Benjamin Pasero 已提交
324
	for (let i = 0; i < len1; i++) {
E
Erich Gamma 已提交
325

B
Benjamin Pasero 已提交
326
		let codeA = a.charCodeAt(i),
E
Erich Gamma 已提交
327 328 329 330 331 332
			codeB = b.charCodeAt(i);

		if (codeA === codeB) {
			continue;

		} else if (isAsciiChar(codeA) && isAsciiChar(codeB)) {
B
Benjamin Pasero 已提交
333
			let diff = Math.abs(codeA - codeB);
E
Erich Gamma 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347
			if (diff !== 0 && diff !== 32) {
				return false;
			}
		} else {
			if (String.fromCharCode(codeA).toLocaleLowerCase() !== String.fromCharCode(codeB).toLocaleLowerCase()) {
				return false;
			}
		}
	}

	return true;
}

/**
348
 * @returns the length of the common prefix of the two strings.
E
Erich Gamma 已提交
349 350 351
 */
export function commonPrefixLength(a: string, b: string): number {

B
Benjamin Pasero 已提交
352
	let i: number,
E
Erich Gamma 已提交
353 354 355 356 357 358 359 360 361 362 363 364
		len = Math.min(a.length, b.length);

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

	return len;
}

/**
365
 * @returns the length of the common suffix of the two strings.
E
Erich Gamma 已提交
366 367 368
 */
export function commonSuffixLength(a: string, b: string): number {

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

B
Benjamin Pasero 已提交
372 373
	let aLastIndex = a.length - 1;
	let bLastIndex = b.length - 1;
E
Erich Gamma 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

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

	return len;
}

// --- 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 已提交
390
//	let chrCode = str.charCodeAt(index);
E
Erich Gamma 已提交
391
//	if (0xD800 <= chrCode && chrCode <= 0xDBFF && index + 1 < len) {
B
Benjamin Pasero 已提交
392
//		let nextChrCode = str.charCodeAt(index + 1);
E
Erich Gamma 已提交
393 394 395 396 397 398 399
//		if (0xDC00 <= nextChrCode && nextChrCode <= 0xDFFF) {
//			return (chrCode - 0xD800) << 10 + (nextChrCode - 0xDC00) + 0x10000;
//		}
//	}
//	return chrCode;
//}
//export function isLeadSurrogate(chr:string) {
B
Benjamin Pasero 已提交
400
//	let chrCode = chr.charCodeAt(0);
E
Erich Gamma 已提交
401 402 403 404
//	return ;
//}
//
//export function isTrailSurrogate(chr:string) {
B
Benjamin Pasero 已提交
405
//	let chrCode = chr.charCodeAt(0);
E
Erich Gamma 已提交
406 407 408
//	return 0xDC00 <= chrCode && chrCode <= 0xDFFF;
//}

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
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
A
Alex Dima 已提交
448
	charCode = +charCode; // @perf
449 450 451 452 453 454 455
	return (
		(charCode >= 0x2E80 && charCode <= 0xD7AF)
		|| (charCode >= 0xF900 && charCode <= 0xFAFF)
		|| (charCode >= 0xFF01 && charCode <= 0xFF5E)
	);
}

E
Erich Gamma 已提交
456 457 458 459 460 461 462 463 464 465 466
/**
 * Computes the difference score for two strings. More similar strings have a higher score.
 * We use largest common subsequence dynamic programming approach but penalize in the end for length differences.
 * Strings that have a large length difference will get a bad default score 0.
 * Complexity - both time and space O(first.length * second.length)
 * Dynamic programming LCS computation http://en.wikipedia.org/wiki/Longest_common_subsequence_problem
 *
 * @param first a string
 * @param second a string
 */
export function difference(first: string, second: string, maxLenDelta: number = 4): number {
B
Benjamin Pasero 已提交
467
	let lengthDifference = Math.abs(first.length - second.length);
E
Erich Gamma 已提交
468 469 470 471
	// We only compute score if length of the currentWord and length of entry.name are similar.
	if (lengthDifference > maxLenDelta) {
		return 0;
	}
P
Pascal Borreli 已提交
472
	// Initialize LCS (largest common subsequence) matrix.
B
Benjamin Pasero 已提交
473 474 475
	let LCS: number[][] = [];
	let zeroArray: number[] = [];
	let i: number, j: number;
E
Erich Gamma 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
	for (i = 0; i < second.length + 1; ++i) {
		zeroArray.push(0);
	}
	for (i = 0; i < first.length + 1; ++i) {
		LCS.push(zeroArray);
	}
	for (i = 1; i < first.length + 1; ++i) {
		for (j = 1; j < second.length + 1; ++j) {
			if (first[i - 1] === second[j - 1]) {
				LCS[i][j] = LCS[i - 1][j - 1] + 1;
			} else {
				LCS[i][j] = Math.max(LCS[i - 1][j], LCS[i][j - 1]);
			}
		}
	}
	return LCS[first.length][second.length] - Math.sqrt(lengthDifference);
}

/**
 * Returns an array in which every entry is the offset of a
 * line. There is always one entry which is zero.
 */
export function computeLineStarts(text: string): number[] {
B
Benjamin Pasero 已提交
499
	let regexp = /\r\n|\r|\n/g,
E
Erich Gamma 已提交
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
		ret: number[] = [0],
		match: RegExpExecArray;
	while ((match = regexp.exec(text))) {
		ret.push(regexp.lastIndex);
	}
	return ret;
}

/**
 * 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): string {

	if (text.length < n) {
		return text;
	}

B
Benjamin Pasero 已提交
518
	let segments = text.split(/\b/),
E
Erich Gamma 已提交
519 520
		count = 0;

B
Benjamin Pasero 已提交
521
	for (let i = segments.length - 1; i >= 0; i--) {
E
Erich Gamma 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534
		count += segments[i].length;

		if (count > n) {
			segments.splice(0, i);
			break;
		}
	}

	return segments.join(empty).replace(/^\s/, empty);
}

// Escape codes
// http://en.wikipedia.org/wiki/ANSI_escape_code
B
Benjamin Pasero 已提交
535 536 537 538
const EL = /\x1B\x5B[12]?K/g; // Erase in line
const LF = /\xA/g; // line feed
const COLOR_START = /\x1b\[\d+m/g; // Color
const COLOR_END = /\x1b\[0?m/g; // Color
E
Erich Gamma 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552

export function removeAnsiEscapeCodes(str: string): string {
	if (str) {
		str = str.replace(EL, '');
		str = str.replace(LF, '\n');
		str = str.replace(COLOR_START, '');
		str = str.replace(COLOR_END, '');
	}

	return str;
}

// -- UTF-8 BOM

B
Benjamin Pasero 已提交
553
const __utf8_bom = 65279;
E
Erich Gamma 已提交
554

B
Benjamin Pasero 已提交
555
export const UTF8_BOM_CHARACTER = String.fromCharCode(__utf8_bom);
E
Erich Gamma 已提交
556 557 558

export function startsWithUTF8BOM(str: string): boolean {
	return (str && str.length > 0 && str.charCodeAt(0) === __utf8_bom);
I
isidor 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
}

/**
 * Appends two strings. If the appended result is longer than maxLength,
 * trims the start of the result and replaces it with '...'.
 */
export function appendWithLimit(first: string, second: string, maxLength: number): string {
	const newLength = first.length + second.length;
	if (newLength > maxLength) {
		first = '...' + first.substr(newLength - maxLength);
	}
	if (second.length > maxLength) {
		first += second.substr(second.length - maxLength);
	} else {
		first += second;
	}

	return first;
}
578 579 580 581


export function safeBtoa(str: string): string {
	return btoa(encodeURIComponent(str)); // we use encodeURIComponent because btoa fails for non Latin 1 values
582 583 584 585 586 587 588 589
}

export function repeat(s:string, count: number): string {
	var result = '';
	for (var i = 0; i < count; i++) {
		result += s;
	}
	return result;
590
}