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

import {OrderGuaranteeEventEmitter} from 'vs/base/common/eventEmitter';
A
Alex Dima 已提交
8
import * as strings from 'vs/base/common/strings';
E
Erich Gamma 已提交
9 10
import {Position} from 'vs/editor/common/core/position';
import {Range} from 'vs/editor/common/core/range';
A
Alex Dima 已提交
11
import * as editorCommon from 'vs/editor/common/editorCommon';
E
Erich Gamma 已提交
12
import {ModelLine} from 'vs/editor/common/model/modelLine';
13
import {guessIndentation} from 'vs/editor/common/model/indentationGuesser';
14
import {DEFAULT_INDENTATION, DEFAULT_TRIM_AUTO_WHITESPACE} from 'vs/editor/common/config/defaultConfig';
E
Erich Gamma 已提交
15 16

var LIMIT_FIND_COUNT = 999;
A
Alex Dima 已提交
17
export const LONG_LINE_BOUNDARY = 1000;
E
Erich Gamma 已提交
18

A
Alex Dima 已提交
19
export class TextModel extends OrderGuaranteeEventEmitter implements editorCommon.ITextModel {
E
Erich Gamma 已提交
20

21 22 23 24
	public static DEFAULT_CREATION_OPTIONS: editorCommon.ITextModelCreationOptions = {
		tabSize: DEFAULT_INDENTATION.tabSize,
		insertSpaces: DEFAULT_INDENTATION.insertSpaces,
		detectIndentation: false,
A
Alex Dima 已提交
25
		defaultEOL: editorCommon.DefaultEndOfLine.LF,
26
		trimAutoWhitespace: DEFAULT_TRIM_AUTO_WHITESPACE,
27 28
	};

E
Erich Gamma 已提交
29 30 31 32
	_lines:ModelLine[];
	_EOL:string;
	_isDisposed:boolean;
	_isDisposing:boolean;
33
	protected _options: editorCommon.ITextModelResolvedOptions;
E
Erich Gamma 已提交
34 35 36 37 38 39 40 41

	private _versionId:number;
	/**
	 * Unlike, versionId, this can go down (via undo) or go to previous values (via redo)
	 */
	private _alternativeVersionId: number;
	private _BOM:string;

A
Alex Dima 已提交
42
	constructor(allowedEventTypes:string[], rawText:editorCommon.IRawText) {
43
		allowedEventTypes.push(editorCommon.EventType.ModelContentChanged, editorCommon.EventType.ModelOptionsChanged);
E
Erich Gamma 已提交
44 45
		super(allowedEventTypes);

46
		this._options = rawText.options;
E
Erich Gamma 已提交
47 48 49 50 51 52
		this._constructLines(rawText);
		this._setVersionId(1);
		this._isDisposed = false;
		this._isDisposing = false;
	}

53 54 55 56
	public getOptions(): editorCommon.ITextModelResolvedOptions {
		return this._options;
	}

57 58 59 60
	public updateOptions(newOpts:editorCommon.ITextModelUpdateOptions): void {
		let somethingChanged = false;
		let changed:editorCommon.IModelOptionsChangedEvent = {
			tabSize: false,
61 62
			insertSpaces: false,
			trimAutoWhitespace: false
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
		};

		if (typeof newOpts.insertSpaces !== 'undefined') {
			if (this._options.insertSpaces !== newOpts.insertSpaces) {
				somethingChanged = true;
				changed.insertSpaces = true;
				this._options.insertSpaces = newOpts.insertSpaces;
			}
		}
		if (typeof newOpts.tabSize !== 'undefined') {
			if (this._options.tabSize !== newOpts.tabSize) {
				somethingChanged = true;
				changed.tabSize = true;
				this._options.tabSize = newOpts.tabSize;
			}
		}
79 80 81 82 83 84 85
		if (typeof newOpts.trimAutoWhitespace !== 'undefined') {
			if (this._options.trimAutoWhitespace !== newOpts.trimAutoWhitespace) {
				somethingChanged = true;
				changed.trimAutoWhitespace = true;
				this._options.trimAutoWhitespace = newOpts.trimAutoWhitespace;
			}
		}
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

		if (somethingChanged) {
			this.emit(editorCommon.EventType.ModelOptionsChanged, changed);
		}
	}

	public detectIndentation(defaultInsertSpaces:boolean, defaultTabSize:number): void {
		let lines = this._lines.map(line => line.text);
		let guessedIndentation = guessIndentation(lines, defaultTabSize, defaultInsertSpaces);
		this.updateOptions({
			insertSpaces: guessedIndentation.insertSpaces,
			tabSize: guessedIndentation.tabSize
		});
	}

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
	private _normalizeIndentationFromWhitespace(str:string): string {
		let tabSize = this._options.tabSize;
		let insertSpaces = this._options.insertSpaces;

		let spacesCnt = 0;
		for (let i = 0; i < str.length; i++) {
			if (str.charAt(i) === '\t') {
				spacesCnt += tabSize;
			} else {
				spacesCnt++;
			}
		}

		let result = '';
		if (!insertSpaces) {
			let tabsCnt = Math.floor(spacesCnt / tabSize);
			spacesCnt = spacesCnt % tabSize;
			for (let i = 0; i < tabsCnt; i++) {
				result += '\t';
			}
		}

		for (let i = 0; i < spacesCnt; i++) {
			result += ' ';
		}

		return result;
	}

	public normalizeIndentation(str:string): string {
		let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
		if (firstNonWhitespaceIndex === -1) {
			firstNonWhitespaceIndex = str.length;
		}
		return this._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex)) + str.substring(firstNonWhitespaceIndex);
	}

	public getOneIndent(): string {
		let tabSize = this._options.tabSize;
		let insertSpaces = this._options.insertSpaces;

		if (insertSpaces) {
			let result = '';
			for (let i = 0; i < tabSize; i++) {
				result += ' ';
			}
			return result;
		} else {
			return '\t';
		}
	}

E
Erich Gamma 已提交
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
	public getVersionId(): number {
		return this._versionId;
	}

	public getAlternativeVersionId(): number {
		return this._alternativeVersionId;
	}

	_increaseVersionId(): void {
		this._setVersionId(this._versionId + 1);
	}

	_setVersionId(newVersionId:number): void {
		this._versionId = newVersionId;
		this._alternativeVersionId = this._versionId;
	}

	_overwriteAlternativeVersionId(newAlternativeVersionId:number): void {
		this._alternativeVersionId = newAlternativeVersionId;
	}

	public isDisposed(): boolean {
		return this._isDisposed;
	}

	public dispose(): void {
		this._isDisposed = true;
		// Null out members, such that any use of a disposed model will throw exceptions sooner rather than later
		this._lines = null;
		this._EOL = null;
		this._BOM = null;

		super.dispose();
	}

A
Alex Dima 已提交
188
	_createContentChangedFlushEvent(): editorCommon.IModelContentChangedFlushEvent {
E
Erich Gamma 已提交
189
		return {
A
Alex Dima 已提交
190
			changeType: editorCommon.EventType.ModelContentChangedFlush,
E
Erich Gamma 已提交
191 192 193 194 195 196 197 198 199
			detail: null,
			// TODO@Alex -> remove these fields from here
			versionId: -1,
			isUndoing: false,
			isRedoing: false
		};
	}

	protected _emitContentChanged2(startLineNumber:number, startColumn:number, endLineNumber:number, endColumn:number, rangeLength:number, text:string, isUndoing:boolean, isRedoing:boolean): void {
A
Alex Dima 已提交
200
		var e:editorCommon.IModelContentChangedEvent2 = {
E
Erich Gamma 已提交
201 202 203
			range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
			rangeLength: rangeLength,
			text: text,
204
			eol: this._EOL,
E
Erich Gamma 已提交
205 206 207 208 209
			versionId: this.getVersionId(),
			isUndoing: isUndoing,
			isRedoing: isRedoing
		};
		if (!this._isDisposing) {
A
Alex Dima 已提交
210
			this.emit(editorCommon.EventType.ModelContentChanged2, e);
E
Erich Gamma 已提交
211 212 213
		}
	}

214 215 216
	_resetValue(e:editorCommon.IModelContentChangedFlushEvent, newValue:editorCommon.IRawText): void {
		this._constructLines(newValue);

E
Erich Gamma 已提交
217 218 219 220 221 222
		this._increaseVersionId();

		e.detail = this.toRawText();
		e.versionId = this._versionId;
	}

A
Alex Dima 已提交
223
	public toRawText(): editorCommon.IRawText {
E
Erich Gamma 已提交
224 225 226 227
		return {
			BOM: this._BOM,
			EOL: this._EOL,
			lines: this.getLinesContent(),
228
			length: this.getValueLength(),
229
			options: this._options
E
Erich Gamma 已提交
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
	public equals(other: editorCommon.IRawText): boolean {
		if (this._BOM !== other.BOM) {
			return false;
		}
		if (this._EOL !== other.EOL) {
			return false;
		}
		if (this._lines.length !== other.lines.length) {
			return false;
		}
		for (let i = 0, len = this._lines.length; i < len; i++) {
			if (this._lines[i].text !== other.lines[i]) {
				return false;
			}
		}
		return true;
	}

	public setValue(value:string): void {
		let rawText: editorCommon.IRawText = null;
		if (value !== null) {
			rawText = TextModel.toRawText(value, {
				tabSize: this._options.tabSize,
				insertSpaces: this._options.insertSpaces,
257
				trimAutoWhitespace: this._options.trimAutoWhitespace,
258 259 260 261 262 263 264 265
				detectIndentation: false,
				defaultEOL: this._options.defaultEOL
			});
		}
		this.setValueFromRawText(rawText);
	}

	public setValueFromRawText(newValue:editorCommon.IRawText): void {
E
Erich Gamma 已提交
266 267 268 269 270 271 272 273 274
		if (newValue === null) {
			// There's nothing to do
			return;
		}
		var oldFullModelRange = this.getFullModelRange();
		var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
		var endLineNumber = this.getLineCount();
		var endColumn = this.getLineMaxColumn(endLineNumber);
		var e = this._createContentChangedFlushEvent();
275

E
Erich Gamma 已提交
276 277 278 279 280
		this._resetValue(e, newValue);
		this._emitModelContentChangedFlushEvent(e);
		this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false);
	}

A
Alex Dima 已提交
281
	public getValue(eol?:editorCommon.EndOfLinePreference, preserveBOM:boolean=false): string {
E
Erich Gamma 已提交
282 283 284 285 286 287 288 289 290 291
		var fullModelRange = this.getFullModelRange();
		var fullModelValue = this.getValueInRange(fullModelRange, eol);

		if (preserveBOM) {
			return this._BOM + fullModelValue;
		}

		return fullModelValue;
	}

A
Alex Dima 已提交
292
	public getValueLength(eol?: editorCommon.EndOfLinePreference, preserveBOM: boolean = false): number {
E
Erich Gamma 已提交
293 294 295 296 297 298 299 300 301 302
		var fullModelRange = this.getFullModelRange();
		var fullModelValue = this.getValueLengthInRange(fullModelRange, eol);

		if (preserveBOM) {
			return this._BOM.length + fullModelValue;
		}

		return fullModelValue;
	}

A
Alex Dima 已提交
303
	public getEmptiedValueInRange(rawRange:editorCommon.IRange, fillCharacter: string = '', eol:editorCommon.EndOfLinePreference=editorCommon.EndOfLinePreference.TextDefined): string {
E
Erich Gamma 已提交
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
		var range = this.validateRange(rawRange);

		if (range.isEmpty()) {
			return '';
		}

		if (range.startLineNumber === range.endLineNumber) {
			return this._repeatCharacter(fillCharacter, range.endColumn - range.startColumn);
		}

		var lineEnding = this._getEndOfLine(eol),
			startLineIndex = range.startLineNumber - 1,
			endLineIndex = range.endLineNumber - 1,
			resultLines:string[] = [];

		resultLines.push(this._repeatCharacter(fillCharacter, this._lines[startLineIndex].text.length - range.startColumn + 1));
		for (var i = startLineIndex + 1; i < endLineIndex; i++) {
			resultLines.push(this._repeatCharacter(fillCharacter, this._lines[i].text.length));
		}
		resultLines.push(this._repeatCharacter(fillCharacter, range.endColumn - 1));

		return resultLines.join(lineEnding);
	}

	private _repeatCharacter(fillCharacter:string, count:number): string {
		var r = '';
		for (var i = 0; i < count; i++) {
			r += fillCharacter;
		}
		return r;
	}

A
Alex Dima 已提交
336
	public getValueInRange(rawRange:editorCommon.IRange, eol:editorCommon.EndOfLinePreference=editorCommon.EndOfLinePreference.TextDefined): string {
E
Erich Gamma 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
		var range = this.validateRange(rawRange);

		if (range.isEmpty()) {
			return '';
		}

		if (range.startLineNumber === range.endLineNumber) {
			return this._lines[range.startLineNumber - 1].text.substring(range.startColumn - 1, range.endColumn - 1);
		}

		var lineEnding = this._getEndOfLine(eol),
			startLineIndex = range.startLineNumber - 1,
			endLineIndex = range.endLineNumber - 1,
			resultLines:string[] = [];

		resultLines.push(this._lines[startLineIndex].text.substring(range.startColumn - 1));
		for (var i = startLineIndex + 1; i < endLineIndex; i++) {
			resultLines.push(this._lines[i].text);
		}
		resultLines.push(this._lines[endLineIndex].text.substring(0, range.endColumn - 1));

		return resultLines.join(lineEnding);
	}

A
Alex Dima 已提交
361
	public getValueLengthInRange(rawRange:editorCommon.IRange, eol:editorCommon.EndOfLinePreference=editorCommon.EndOfLinePreference.TextDefined): number {
E
Erich Gamma 已提交
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
		var range = this.validateRange(rawRange);

		if (range.isEmpty()) {
			return 0;
		}

		if (range.startLineNumber === range.endLineNumber) {
			return (range.endColumn - range.startColumn);
		}

		var lineEndingLength = this._getEndOfLine(eol).length,
			startLineIndex = range.startLineNumber - 1,
			endLineIndex = range.endLineNumber - 1,
			result = 0;

		result += (this._lines[startLineIndex].text.length - range.startColumn + 1);
		for (var i = startLineIndex + 1; i < endLineIndex; i++) {
			result += lineEndingLength + this._lines[i].text.length;
		}
		result += lineEndingLength + (range.endColumn - 1);

		return result;
	}

A
Alex Dima 已提交
386
	public isDominatedByLongLines(): boolean {
E
Erich Gamma 已提交
387 388 389 390 391 392 393 394 395
		var smallLineCharCount = 0,
			longLineCharCount = 0,
			i: number,
			len: number,
			lines = this._lines,
			lineLength: number;

		for (i = 0, len = this._lines.length; i < len; i++) {
			lineLength = lines[i].text.length;
A
Alex Dima 已提交
396
			if (lineLength >= LONG_LINE_BOUNDARY) {
E
Erich Gamma 已提交
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
				longLineCharCount += lineLength;
			} else {
				smallLineCharCount += lineLength;
			}
		}

		return (longLineCharCount > smallLineCharCount);
	}

	public getLineCount(): number {
		return this._lines.length;
	}

	public getLineContent(lineNumber:number): string {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

		return this._lines[lineNumber - 1].text;
	}

	public getLinesContent(): string[] {
		var r: string[] = [];
		for (var i = 0, len = this._lines.length; i < len; i++) {
			r[i] = this._lines[i].text;
		}
		return r;
	}

	public getEOL(): string {
		return this._EOL;
	}

A
Alex Dima 已提交
430 431
	public setEOL(eol: editorCommon.EndOfLineSequence): void {
		var newEOL = (eol === editorCommon.EndOfLineSequence.CRLF ? '\r\n' : '\n');
E
Erich Gamma 已提交
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
		if (this._EOL === newEOL) {
			// Nothing to do
			return;
		}

		var oldFullModelRange = this.getFullModelRange();
		var oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
		var endLineNumber = this.getLineCount();
		var endColumn = this.getLineMaxColumn(endLineNumber);

		this._EOL = newEOL;
		this._increaseVersionId();

		var e = this._createContentChangedFlushEvent();
		e.detail = this.toRawText();
		e.versionId = this._versionId;

		this._emitModelContentChangedFlushEvent(e);
		this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false);
	}

	public getLineMinColumn(lineNumber:number): number {
		return 1;
	}

	public getLineMaxColumn(lineNumber:number): number {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

		return this._lines[lineNumber - 1].text.length + 1;
	}

	public getLineFirstNonWhitespaceColumn(lineNumber: number): number {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

A
Alex Dima 已提交
470
		var result = strings.firstNonWhitespaceIndex(this._lines[lineNumber - 1].text);
E
Erich Gamma 已提交
471 472 473 474 475 476 477 478 479 480 481
		if (result === -1) {
			return 0;
		}
		return result + 1;
	}

	public getLineLastNonWhitespaceColumn(lineNumber: number): number {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

A
Alex Dima 已提交
482
		var result = strings.lastNonWhitespaceIndex(this._lines[lineNumber - 1].text);
E
Erich Gamma 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
		if (result === -1) {
			return 0;
		}
		return result + 2;
	}

	public validateLineNumber(lineNumber:number): number {
		if (lineNumber < 1) {
			lineNumber = 1;
		}
		if (lineNumber > this._lines.length) {
			lineNumber = this._lines.length;
		}
		return lineNumber;
	}

A
Alex Dima 已提交
499
	public validatePosition(position:editorCommon.IPosition): editorCommon.IEditorPosition {
E
Erich Gamma 已提交
500 501 502 503 504
		var lineNumber = position.lineNumber ? position.lineNumber : 1;
		var column = position.column ? position.column : 1;

		if (lineNumber < 1) {
			lineNumber = 1;
A
aioute Gao 已提交
505
			column = 1;
E
Erich Gamma 已提交
506
		}
A
aioute Gao 已提交
507
		else if (lineNumber > this._lines.length) {
E
Erich Gamma 已提交
508
			lineNumber = this._lines.length;
A
aioute Gao 已提交
509
			column = this.getLineMaxColumn(lineNumber);
E
Erich Gamma 已提交
510
		}
A
aioute Gao 已提交
511 512 513 514 515 516 517 518
		else {
			var maxColumn = this.getLineMaxColumn(lineNumber);
			if (column < 1) {
				column = 1;
			}
			else if (column > maxColumn) {
				column = maxColumn;
			}
E
Erich Gamma 已提交
519 520 521 522 523
		}

		return new Position(lineNumber, column);
	}

A
Alex Dima 已提交
524
	public validateRange(range:editorCommon.IRange): editorCommon.IEditorRange {
E
Erich Gamma 已提交
525 526 527 528 529
		var start = this.validatePosition(new Position(range.startLineNumber, range.startColumn));
		var end = this.validatePosition(new Position(range.endLineNumber, range.endColumn));
		return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
	}

A
Alex Dima 已提交
530
	public modifyPosition(rawPosition: editorCommon.IPosition, offset: number) : editorCommon.IEditorPosition {
E
Erich Gamma 已提交
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
		var position = this.validatePosition(rawPosition);

		// Handle positive offsets, one line at a time
		while (offset > 0) {
			var maxColumn = this.getLineMaxColumn(position.lineNumber);

			// Get to end of line
			if (position.column < maxColumn) {
				var subtract = Math.min(offset, maxColumn - position.column);
				offset -= subtract;
				position.column += subtract;
			}

			if (offset === 0) {
				break;
			}

			// Go to next line
			offset -= this._EOL.length;
			if (offset < 0) {
				throw new Error('TextModel.modifyPosition: Breaking line terminators');
			}

			++position.lineNumber;
			if (position.lineNumber > this._lines.length) {
				throw new Error('TextModel.modifyPosition: Offset goes beyond the end of the model');
			}

			position.column = 1;
		}

		// Handle negative offsets, one line at a time
		while (offset < 0) {

			// Get to the start of the line
			if (position.column > 1) {
				var add = Math.min(-offset, position.column - 1);
				offset += add;
				position.column -= add;
			}

			if (offset === 0) {
				break;
			}

			// Go to the previous line
			offset += this._EOL.length;
			if (offset > 0) {
				throw new Error('TextModel.modifyPosition: Breaking line terminators');
			}

			--position.lineNumber;
			if (position.lineNumber < 1) {
				throw new Error('TextModel.modifyPosition: Offset goes beyond the beginning of the model');
			}

			position.column = this.getLineMaxColumn(position.lineNumber);
		}

		return position;
	}

A
Alex Dima 已提交
593
	public getFullModelRange(): editorCommon.IEditorRange {
E
Erich Gamma 已提交
594 595 596 597
		var lineCount = this.getLineCount();
		return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
	}

A
Alex Dima 已提交
598
	_emitModelContentChangedFlushEvent(e:editorCommon.IModelContentChangedFlushEvent): void {
E
Erich Gamma 已提交
599
		if (!this._isDisposing) {
A
Alex Dima 已提交
600
			this.emit(editorCommon.EventType.ModelContentChanged, e);
E
Erich Gamma 已提交
601 602 603
		}
	}

604
	public static toRawText(rawText:string, opts:editorCommon.ITextModelCreationOptions): editorCommon.IRawText {
E
Erich Gamma 已提交
605 606 607 608 609 610 611 612 613 614 615 616
		// Count the number of lines that end with \r\n
		var carriageReturnCnt = 0,
			lastCarriageReturnIndex = -1;
		while ((lastCarriageReturnIndex = rawText.indexOf('\r', lastCarriageReturnIndex + 1)) !== -1) {
			carriageReturnCnt++;
		}

		// Split the text into liens
		var lines = rawText.split(/\r\n|\r|\n/);

		// Remove the BOM (if present)
		var BOM = '';
A
Alex Dima 已提交
617 618
		if (strings.startsWithUTF8BOM(lines[0])) {
			BOM = strings.UTF8_BOM_CHARACTER;
E
Erich Gamma 已提交
619 620 621 622 623 624 625
			lines[0] = lines[0].substr(1);
		}

		var lineFeedCnt = lines.length - 1;
		var EOL = '';
		if (lineFeedCnt === 0) {
			// This is an empty file or a file with precisely one line
626
			EOL = (opts.defaultEOL === editorCommon.DefaultEndOfLine.LF ? '\n' : '\r\n');
E
Erich Gamma 已提交
627 628 629 630 631 632 633 634
		} else if (carriageReturnCnt > lineFeedCnt / 2) {
			// More than half of the file contains \r\n ending lines
			EOL = '\r\n';
		} else {
			// At least one line more ends in \n
			EOL = '\n';
		}

635
		let resolvedOpts: editorCommon.ITextModelResolvedOptions;
636
		if (opts.detectIndentation) {
637
			let guessedIndentation = guessIndentation(lines, opts.tabSize, opts.insertSpaces);
638 639 640
			resolvedOpts = {
				tabSize: guessedIndentation.tabSize,
				insertSpaces: guessedIndentation.insertSpaces,
641
				trimAutoWhitespace: opts.trimAutoWhitespace,
642 643 644 645 646 647
				defaultEOL: opts.defaultEOL
			};
		} else {
			resolvedOpts = {
				tabSize: opts.tabSize,
				insertSpaces: opts.insertSpaces,
648
				trimAutoWhitespace: opts.trimAutoWhitespace,
649 650 651 652
				defaultEOL: opts.defaultEOL
			};
		}

E
Erich Gamma 已提交
653 654 655 656
		return {
			BOM: BOM,
			EOL: EOL,
			lines: lines,
657
			length: rawText.length,
658
			options: resolvedOpts
E
Erich Gamma 已提交
659 660 661
		};
	}

A
Alex Dima 已提交
662
	_constructLines(rawText:editorCommon.IRawText): void {
E
Erich Gamma 已提交
663 664 665 666 667 668 669 670 671 672 673 674 675
		var rawLines = rawText.lines,
			modelLines: ModelLine[] = [],
			i: number,
			len: number;

		for (i = 0, len = rawLines.length; i < len; i++) {
			modelLines.push(new ModelLine(i + 1, rawLines[i]));
		}
		this._BOM = rawText.BOM;
		this._EOL = rawText.EOL;
		this._lines = modelLines;
	}

A
Alex Dima 已提交
676
	private _getEndOfLine(eol:editorCommon.EndOfLinePreference): string {
E
Erich Gamma 已提交
677
		switch (eol) {
A
Alex Dima 已提交
678
			case editorCommon.EndOfLinePreference.LF:
E
Erich Gamma 已提交
679
				return '\n';
A
Alex Dima 已提交
680
			case editorCommon.EndOfLinePreference.CRLF:
E
Erich Gamma 已提交
681
				return '\r\n';
A
Alex Dima 已提交
682
			case editorCommon.EndOfLinePreference.TextDefined:
E
Erich Gamma 已提交
683 684 685 686 687
				return this.getEOL();
		}
		throw new Error('Unknown EOL preference');
	}

A
Alex Dima 已提交
688 689
	public findMatches(searchString:string, rawSearchScope:any, isRegex:boolean, matchCase:boolean, wholeWord:boolean, limitResultCount:number = LIMIT_FIND_COUNT): editorCommon.IEditorRange[] {
		var regex = strings.createSafeRegExp(searchString, isRegex, matchCase, wholeWord);
E
Erich Gamma 已提交
690 691 692 693
		if (!regex) {
			return [];
		}

A
Alex Dima 已提交
694
		var searchRange:editorCommon.IEditorRange;
E
Erich Gamma 已提交
695 696 697 698 699 700 701 702 703
		if (Range.isIRange(rawSearchScope)) {
			searchRange = rawSearchScope;
		} else {
			searchRange = this.getFullModelRange();
		}

		return this._doFindMatches(searchRange, regex, limitResultCount);
	}

A
Alex Dima 已提交
704 705
	public findNextMatch(searchString:string, rawSearchStart:editorCommon.IPosition, isRegex:boolean, matchCase:boolean, wholeWord:boolean): editorCommon.IEditorRange {
		var regex = strings.createSafeRegExp(searchString, isRegex, matchCase, wholeWord);
E
Erich Gamma 已提交
706 707 708 709 710 711 712 713
		if (!regex) {
			return null;
		}

		var searchStart = this.validatePosition(rawSearchStart),
			lineCount = this.getLineCount(),
			startLineNumber = searchStart.lineNumber,
			text: string,
A
Alex Dima 已提交
714
			r: editorCommon.IEditorRange;
E
Erich Gamma 已提交
715 716 717 718 719 720 721 722

		// Look in first line
		text = this._lines[startLineNumber - 1].text.substring(searchStart.column - 1);
		r = this._findMatchInLine(regex, text, startLineNumber, searchStart.column - 1);
		if (r) {
			return r;
		}

723
		for (var i = 1; i <= lineCount; i++) {
E
Erich Gamma 已提交
724 725 726 727 728 729 730 731 732 733 734
			var lineIndex = (startLineNumber + i - 1) % lineCount;
			text = this._lines[lineIndex].text;
			r = this._findMatchInLine(regex, text, lineIndex + 1, 0);
			if (r) {
				return r;
			}
		}

		return null;
	}

A
Alex Dima 已提交
735 736
	public findPreviousMatch(searchString:string, rawSearchStart:editorCommon.IPosition, isRegex:boolean, matchCase:boolean, wholeWord:boolean): editorCommon.IEditorRange {
		var regex = strings.createSafeRegExp(searchString, isRegex, matchCase, wholeWord);
737 738 739 740 741 742 743 744
		if (!regex) {
			return null;
		}

		var searchStart = this.validatePosition(rawSearchStart),
			lineCount = this.getLineCount(),
			startLineNumber = searchStart.lineNumber,
			text: string,
A
Alex Dima 已提交
745
			r: editorCommon.IEditorRange;
746 747 748 749 750 751 752 753

		// Look in first line
		text = this._lines[startLineNumber - 1].text.substring(0, searchStart.column - 1);
		r = this._findLastMatchInLine(regex, text, startLineNumber);
		if (r) {
			return r;
		}

754
		for (var i = 1; i <= lineCount; i++) {
755 756 757 758 759 760 761 762 763 764 765
			var lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;
			text = this._lines[lineIndex].text;
			r = this._findLastMatchInLine(regex, text, lineIndex + 1);
			if (r) {
				return r;
			}
		}

		return null;
	}

A
Alex Dima 已提交
766 767
	private _doFindMatches(searchRange:editorCommon.IEditorRange, searchRegex:RegExp, limitResultCount:number): editorCommon.IEditorRange[] {
		var result:editorCommon.IEditorRange[] = [],
E
Erich Gamma 已提交
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
			text: string,
			counter = 0;

		// Early case for a search range that starts & stops on the same line number
		if (searchRange.startLineNumber === searchRange.endLineNumber) {
			text = this._lines[searchRange.startLineNumber - 1].text.substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
			counter = this._findMatchesInLine(searchRegex, text, searchRange.startLineNumber, searchRange.startColumn - 1, counter, result, limitResultCount);
			return result;
		}

		// Collect results from first line
		text = this._lines[searchRange.startLineNumber - 1].text.substring(searchRange.startColumn - 1);
		counter = this._findMatchesInLine(searchRegex, text, searchRange.startLineNumber, searchRange.startColumn - 1, counter, result, limitResultCount);

		// Collect results from middle lines
		for (var lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && counter < limitResultCount; lineNumber++) {
			counter = this._findMatchesInLine(searchRegex, this._lines[lineNumber - 1].text, lineNumber, 0, counter, result, limitResultCount);
		}

		// Collect results from last line
		if (counter < limitResultCount) {
			text = this._lines[searchRange.endLineNumber - 1].text.substring(0, searchRange.endColumn - 1);
			counter = this._findMatchesInLine(searchRegex, text, searchRange.endLineNumber, 0, counter, result, limitResultCount);
		}

		return result;
	}

A
Alex Dima 已提交
796
	private _findMatchInLine(searchRegex:RegExp, text:string, lineNumber:number, deltaOffset:number): editorCommon.IEditorRange {
E
Erich Gamma 已提交
797 798 799 800 801 802 803
		var m = searchRegex.exec(text);
		if (!m) {
			return null;
		}
		return new Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset);
	}

A
Alex Dima 已提交
804 805
	private _findLastMatchInLine(searchRegex:RegExp, text:string, lineNumber:number): editorCommon.IEditorRange {
		let bestResult: editorCommon.IEditorRange = null;
806 807 808 809 810 811 812 813 814 815 816
		let m:RegExpExecArray;
		while ((m = searchRegex.exec(text))) {
			let result = new Range(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length);
			if (result.equalsRange(bestResult)) {
				break;
			}
			bestResult = result;
		}
		return bestResult;
	}

A
Alex Dima 已提交
817
	private _findMatchesInLine(searchRegex:RegExp, text:string, lineNumber:number, deltaOffset:number, counter:number, result:editorCommon.IEditorRange[], limitResultCount:number): number {
E
Erich Gamma 已提交
818
		var m:RegExpExecArray;
819 820
		// Reset regex to search from the beginning
		searchRegex.lastIndex = 0;
E
Erich Gamma 已提交
821 822 823
		do {
			m = searchRegex.exec(text);
			if (m) {
824 825 826 827 828 829
				var range = new Range(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset);
				// Exit early if the regex matches the same range
				if (range.equalsRange(result[result.length - 1])) {
					return counter;
				}
				result.push(range);
E
Erich Gamma 已提交
830 831 832 833 834 835 836 837
				counter++;
				if (counter >= limitResultCount) {
					return counter;
				}
			}
		} while(m);
		return counter;
	}
838
}
839 840 841 842 843 844 845 846 847 848 849 850

export class RawText {

	public static fromString(rawText:string, opts:editorCommon.ITextModelCreationOptions): editorCommon.IRawText {
		return TextModel.toRawText(rawText, opts);
	}

	public static fromStringWithModelOptions(rawText:string, model:editorCommon.IModel): editorCommon.IRawText {
		let opts = model.getOptions();
		return TextModel.toRawText(rawText, {
			tabSize: opts.tabSize,
			insertSpaces: opts.insertSpaces,
851
			trimAutoWhitespace: opts.trimAutoWhitespace,
852 853 854 855 856
			detectIndentation: false,
			defaultEOL: opts.defaultEOL
		});
	}

A
aioute Gao 已提交
857
}