textModel.ts 29.4 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 9
import * as platform from 'vs/base/common/platform';
import * as strings from 'vs/base/common/strings';
E
Erich Gamma 已提交
10 11
import {Position} from 'vs/editor/common/core/position';
import {Range} from 'vs/editor/common/core/range';
A
Alex Dima 已提交
12
import * as editorCommon from 'vs/editor/common/editorCommon';
E
Erich Gamma 已提交
13 14 15 16 17
import {ModelLine} from 'vs/editor/common/model/modelLine';

var __space = ' '.charCodeAt(0);
var __tab = '\t'.charCodeAt(0);
var LIMIT_FIND_COUNT = 999;
A
Alex Dima 已提交
18
var DEFAULT_PLATFORM_EOL = (platform.isLinux || platform.isMacintosh) ? '\n' : '\r\n';
E
Erich Gamma 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

export interface IIndentationFactors {
	/**
	 * The number of lines that are indented with tabs
	 */
	linesIndentedWithTabs:number;
	/**
	 * relativeSpaceCounts[i] contains the number of times (i spaces) have been encountered in a relative indentation
	 */
	relativeSpaceCounts:number[];
	/**
	 * absoluteSpaceCounts[i] contains the number of times (i spaces) have been encounted in an indentation
	 */
	absoluteSpaceCounts:number[];
}

A
Alex Dima 已提交
35
export class TextModel extends OrderGuaranteeEventEmitter implements editorCommon.ITextModel {
E
Erich Gamma 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48

	_lines:ModelLine[];
	_EOL:string;
	_isDisposed:boolean;
	_isDisposing:boolean;

	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 已提交
49 50
	constructor(allowedEventTypes:string[], rawText:editorCommon.IRawText) {
		allowedEventTypes.push(editorCommon.EventType.ModelContentChanged);
E
Erich Gamma 已提交
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
		super(allowedEventTypes);

		this._constructLines(rawText);
		this._setVersionId(1);
		this._isDisposed = false;
		this._isDisposing = false;
	}

	public getVersionId(): number {
		if (this._isDisposed) {
			throw new Error('TextModel.getVersionId: Model is disposed');
		}

		return this._versionId;
	}

	public getAlternativeVersionId(): number {
		if (this._isDisposed) {
			throw new Error('TextModel.getAlternativeVersionId: Model is disposed');
		}

		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 {
		if (this._isDisposed) {
			throw new Error('TextModel.dispose: Model is disposed');
		}

		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 已提交
106
	_createContentChangedFlushEvent(): editorCommon.IModelContentChangedFlushEvent {
E
Erich Gamma 已提交
107
		return {
A
Alex Dima 已提交
108
			changeType: editorCommon.EventType.ModelContentChangedFlush,
E
Erich Gamma 已提交
109 110 111 112 113 114 115 116 117
			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 已提交
118
		var e:editorCommon.IModelContentChangedEvent2 = {
E
Erich Gamma 已提交
119 120 121
			range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
			rangeLength: rangeLength,
			text: text,
122
			eol: this._EOL,
E
Erich Gamma 已提交
123 124 125 126 127
			versionId: this.getVersionId(),
			isUndoing: isUndoing,
			isRedoing: isRedoing
		};
		if (!this._isDisposing) {
A
Alex Dima 已提交
128
			this.emit(editorCommon.EventType.ModelContentChanged2, e);
E
Erich Gamma 已提交
129 130 131
		}
	}

A
Alex Dima 已提交
132
	_resetValue(e:editorCommon.IModelContentChangedFlushEvent, newValue:string): void {
E
Erich Gamma 已提交
133 134 135 136 137 138 139
		this._constructLines(TextModel.toRawText(newValue));
		this._increaseVersionId();

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

A
Alex Dima 已提交
140
	public toRawText(): editorCommon.IRawText {
E
Erich Gamma 已提交
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
		return {
			BOM: this._BOM,
			EOL: this._EOL,
			lines: this.getLinesContent(),
			length: this.getValueLength()
		};
	}

	public setValue(newValue:string): void {
		if (this._isDisposed) {
			throw new Error('TextModel.setValue: Model is disposed');
		}

		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();
		this._resetValue(e, newValue);
		this._emitModelContentChangedFlushEvent(e);
		this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false);
	}

A
Alex Dima 已提交
168
	public getValue(eol?:editorCommon.EndOfLinePreference, preserveBOM:boolean=false): string {
E
Erich Gamma 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182
		if (this._isDisposed) {
			throw new Error('TextModel.getValue: Model is disposed');
		}

		var fullModelRange = this.getFullModelRange();
		var fullModelValue = this.getValueInRange(fullModelRange, eol);

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

		return fullModelValue;
	}

A
Alex Dima 已提交
183
	public getValueLength(eol?: editorCommon.EndOfLinePreference, preserveBOM: boolean = false): number {
E
Erich Gamma 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197
		if (this._isDisposed) {
			throw new Error('TextModel.getValueLength: Model is disposed');
		}

		var fullModelRange = this.getFullModelRange();
		var fullModelValue = this.getValueLengthInRange(fullModelRange, eol);

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

		return fullModelValue;
	}

A
Alex Dima 已提交
198
	public getEmptiedValueInRange(rawRange:editorCommon.IRange, fillCharacter: string = '', eol:editorCommon.EndOfLinePreference=editorCommon.EndOfLinePreference.TextDefined): string {
E
Erich Gamma 已提交
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
		if (this._isDisposed) {
			throw new Error('TextModel.getEmptiedValueInRange: Model is disposed');
		}

		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 已提交
235
	public getValueInRange(rawRange:editorCommon.IRange, eol:editorCommon.EndOfLinePreference=editorCommon.EndOfLinePreference.TextDefined): string {
E
Erich Gamma 已提交
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
		if (this._isDisposed) {
			throw new Error('TextModel.getValueInRange: Model is disposed');
		}

		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 已提交
264
	public getValueLengthInRange(rawRange:editorCommon.IRange, eol:editorCommon.EndOfLinePreference=editorCommon.EndOfLinePreference.TextDefined): number {
E
Erich Gamma 已提交
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
		if (this._isDisposed) {
			throw new Error('TextModel.getValueInRange: Model is disposed');
		}

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

	public isDominatedByLongLines(longLineBoundary:number): boolean {
		if (this._isDisposed) {
			throw new Error('TextModel.isDominatedByLongLines: Model is disposed');
		}

		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;
			if (lineLength >= longLineBoundary) {
				longLineCharCount += lineLength;
			} else {
				smallLineCharCount += lineLength;
			}
		}

		return (longLineCharCount > smallLineCharCount);
	}

	_extractIndentationFactors(): IIndentationFactors {

		var i:number,
			len:number,
			j:number,
			lenJ:number,
			charCode:number,
			prevLineCharCode:number,
			lines = this._lines,
			/**
			 * text on current line
			 */
			currentLineText: string,
			/**
			 * the content of the previous line that had non whitespace characters
			 */
			previousLineTextWithContent = '',
			/**
			 * the char index at which `previousLineTextWithContent` has a non whitespace character
			 */
			previousLineIndentation = 0,
			/**
			 * does `currentLineText` have non whitespace characters?
			 */
			currentLineHasContent:boolean,
			/**
			 * the char index at which `currentLineText` has a non whitespace character
			 */
			currentLineIndentation:number,
			/**
			 * relativeSpaceCounts[i] contains the number of times (i spaces) have been encountered in a relative indentation
			 */
			relativeSpaceCounts:number[] = [],
			/**
			 * The total number of tabs that appear in indentations
			 */
			linesIndentedWithTabs:number = 0,
			/**
			 * absoluteSpaceCounts[i] contains the number of times (i spaces) have been encounted in an indentation
			 */
			absoluteSpaceCounts:number[] = [],
			tmpTabCounts: number,
			tmpSpaceCounts: number;

		for (i = 0, len = lines.length; i < len; i++) {
			currentLineText = lines[i].text;

			currentLineHasContent = false;
			currentLineIndentation = 0;
			tmpSpaceCounts = 0;
			tmpTabCounts = 0;
			for (j = 0, lenJ = currentLineText.length; j < lenJ; j++) {
				charCode = currentLineText.charCodeAt(j);

				if (charCode === __tab) {
					tmpTabCounts++;
				} else if (charCode === __space) {
					tmpSpaceCounts++;
				} else {
					// Hit non whitespace character on this line
					currentLineHasContent = true;
					currentLineIndentation = j;
					break;
				}
			}

			// Ignore `space` if it occurs exactly once in the indentation
			if (tmpSpaceCounts === 1) {
				tmpSpaceCounts = 0;
			}

			if (currentLineHasContent && (tmpTabCounts > 0 || tmpSpaceCounts > 0)) {
				if (tmpTabCounts > 0) {
					linesIndentedWithTabs++;
				}
				if (tmpSpaceCounts > 0) {
					absoluteSpaceCounts[tmpSpaceCounts] = (absoluteSpaceCounts[tmpSpaceCounts] || 0) + 1;
				}
			}

			if (currentLineHasContent) {
				// Only considering lines with content, look at the relative indentation between previous line's indentation and current line's indentation

				// This can go both ways (e.g.):
				//  - previousLineIndentation: "\t\t"
				//  - currentLineIndentation: "\t    "
				//  => This should count 1 tab and 4 spaces
				tmpSpaceCounts = 0;

				var stillMatchingIndentation = true;
				for (j = 0; j < previousLineIndentation && j < currentLineIndentation; j++) {
					prevLineCharCode = previousLineTextWithContent.charCodeAt(j);
					charCode = currentLineText.charCodeAt(j);

					if (stillMatchingIndentation && prevLineCharCode !== charCode) {
						stillMatchingIndentation = false;
					}

					if (!stillMatchingIndentation) {
						if (prevLineCharCode === __space) {
							tmpSpaceCounts++;
						}
						if (charCode === __space) {
							tmpSpaceCounts++;
						}
					}
				}

				for (;j < previousLineIndentation; j++) {
					prevLineCharCode = previousLineTextWithContent.charCodeAt(j);
					if (prevLineCharCode === __space) {
						tmpSpaceCounts++;
					}
				}

				for (;j < currentLineIndentation; j++) {
					charCode = currentLineText.charCodeAt(j);
					if (charCode === __space) {
						tmpSpaceCounts++;
					}
				}

				// Ignore `space` if it occurs exactly once in the indentation
				if (tmpSpaceCounts === 1) {
					tmpSpaceCounts = 0;
				}

				if (tmpSpaceCounts > 0) {
					relativeSpaceCounts[tmpSpaceCounts] = (relativeSpaceCounts[tmpSpaceCounts] || 0) + 1;
				}

				previousLineIndentation = currentLineIndentation;
				previousLineTextWithContent = currentLineText;
			}
		}

		return {
			linesIndentedWithTabs: linesIndentedWithTabs,
			relativeSpaceCounts: relativeSpaceCounts,
			absoluteSpaceCounts: absoluteSpaceCounts
		};
	}

A
Alex Dima 已提交
460
	public guessIndentation(defaultTabSize:number): editorCommon.IGuessedIndentation {
E
Erich Gamma 已提交
461 462 463 464
		if (this._isDisposed) {
			throw new Error('TextModel.guessIndentation: Model is disposed');
		}

465
		let i:number,
E
Erich Gamma 已提交
466 467 468 469 470 471 472
			len:number,
			factors = this._extractIndentationFactors(),
			linesIndentedWithTabs = factors.linesIndentedWithTabs,
			absoluteSpaceCounts = factors.absoluteSpaceCounts,
			relativeSpaceCounts = factors.relativeSpaceCounts;

		// Count the absolute number of times tabs or spaces have been used as indentation
473
		let linesIndentedWithSpaces = 0;
E
Erich Gamma 已提交
474 475 476 477
		for (i = 1, len = absoluteSpaceCounts.length; i < len; i++) {
			linesIndentedWithSpaces += (absoluteSpaceCounts[i] || 0);
		}

478
		let candidate:number,
E
Erich Gamma 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
			candidateScore:number,
			penalization:number,
			m:number,
			scores:number[] = [];

		for (candidate = 2, len = absoluteSpaceCounts.length; candidate < len; candidate++) {
			if (!absoluteSpaceCounts[candidate]) {
				continue;
			}

			// Try to compute a score that `candidate` is the `tabSize`
			candidateScore = 0;
			penalization = 0;
			for (m = candidate; m < len; m += candidate) {
				if (absoluteSpaceCounts[m]) {
					candidateScore += absoluteSpaceCounts[m];
				} else {
					// Penalize this candidate, but penalize less with every mutliple..
					penalization += candidate / m;
				}
			}
			scores[candidate] = candidateScore / (1 + penalization);
		}

503 504 505 506 507 508
		// console.log('----------');
		// console.log('linesIndentedWithTabs: ', linesIndentedWithTabs);
		// console.log('absoluteSpaceCounts: ', absoluteSpaceCounts);
		// console.log('relativeSpaceCounts: ', relativeSpaceCounts);
		// console.log('=> linesIndentedWithSpaces: ', linesIndentedWithSpaces);
		// console.log('=> scores: ', scores);
E
Erich Gamma 已提交
509

510
		let bestCandidate = defaultTabSize,
E
Erich Gamma 已提交
511 512
			bestCandidateScore = 0;

513
		let allowedGuesses = [2, 4, 6, 8];
E
Erich Gamma 已提交
514 515 516 517 518 519 520 521 522

		for (i = 0; i < allowedGuesses.length; i++) {
			candidate = allowedGuesses[i];
			candidateScore = (scores[candidate] || 0) + (relativeSpaceCounts[candidate] || 0);
			if (candidateScore > bestCandidateScore) {
				bestCandidate = candidate;
				bestCandidateScore = candidateScore;
			}
		}
523 524 525 526 527 528 529

		let insertSpaces = true;
		if (linesIndentedWithTabs > linesIndentedWithSpaces) {
			// More lines indented with tabs
			insertSpaces = false;
		}

E
Erich Gamma 已提交
530
		return {
531
			insertSpaces: insertSpaces,
E
Erich Gamma 已提交
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
			tabSize: bestCandidate
		};
	}

	public getLineCount(): number {
		if (this._isDisposed) {
			throw new Error('TextModel.getLineCount: Model is disposed');
		}

		return this._lines.length;
	}

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

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

	public getLinesContent(): string[] {
		if (this._isDisposed) {
			throw new Error('TextModel.getLineContent: Model is disposed');
		}

		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 {
		if (this._isDisposed) {
			throw new Error('TextModel.getEOL: Model is disposed');
		}

		return this._EOL;
	}

A
Alex Dima 已提交
575 576
	public setEOL(eol: editorCommon.EndOfLineSequence): void {
		var newEOL = (eol === editorCommon.EndOfLineSequence.CRLF ? '\r\n' : '\n');
E
Erich Gamma 已提交
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
		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 (this._isDisposed) {
			throw new Error('TextModel.getLineMaxColumn: Model is disposed');
		}
		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 (this._isDisposed) {
			throw new Error('TextModel.getLineFirstNonWhitespaceColumn: Model is disposed');
		}
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

A
Alex Dima 已提交
621
		var result = strings.firstNonWhitespaceIndex(this._lines[lineNumber - 1].text);
E
Erich Gamma 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635
		if (result === -1) {
			return 0;
		}
		return result + 1;
	}

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

A
Alex Dima 已提交
636
		var result = strings.lastNonWhitespaceIndex(this._lines[lineNumber - 1].text);
E
Erich Gamma 已提交
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
		if (result === -1) {
			return 0;
		}
		return result + 2;
	}

	public validateLineNumber(lineNumber:number): number {
		if (this._isDisposed) {
			throw new Error('TextModel.validateLineNumber: Model is disposed');
		}

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

A
Alex Dima 已提交
657
	public validatePosition(position:editorCommon.IPosition): editorCommon.IEditorPosition {
E
Erich Gamma 已提交
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
		if (this._isDisposed) {
			throw new Error('TextModel.validatePosition: Model is disposed');
		}

		var lineNumber = position.lineNumber ? position.lineNumber : 1;
		var column = position.column ? position.column : 1;

		if (lineNumber < 1) {
			lineNumber = 1;
		}
		if (lineNumber > this._lines.length) {
			lineNumber = this._lines.length;
		}

		if (column < 1) {
			column = 1;
		}
		var maxColumn = this.getLineMaxColumn(lineNumber);
		if (column > maxColumn) {
			column = maxColumn;
		}

		return new Position(lineNumber, column);
	}

A
Alex Dima 已提交
683
	public validateRange(range:editorCommon.IRange): editorCommon.IEditorRange {
E
Erich Gamma 已提交
684 685 686 687 688 689 690 691 692
		if (this._isDisposed) {
			throw new Error('TextModel.validateRange: Model is disposed');
		}

		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 已提交
693
	public modifyPosition(rawPosition: editorCommon.IPosition, offset: number) : editorCommon.IEditorPosition {
E
Erich Gamma 已提交
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
		if (this._isDisposed) {
			throw new Error('TextModel.modifyPosition: Model is disposed');
		}

		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 已提交
760
	public getFullModelRange(): editorCommon.IEditorRange {
E
Erich Gamma 已提交
761 762 763 764 765 766 767 768
		if (this._isDisposed) {
			throw new Error('TextModel.getFullModelRange: Model is disposed');
		}

		var lineCount = this.getLineCount();
		return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
	}

A
Alex Dima 已提交
769
	_emitModelContentChangedFlushEvent(e:editorCommon.IModelContentChangedFlushEvent): void {
E
Erich Gamma 已提交
770
		if (!this._isDisposing) {
A
Alex Dima 已提交
771
			this.emit(editorCommon.EventType.ModelContentChanged, e);
E
Erich Gamma 已提交
772 773 774
		}
	}

A
Alex Dima 已提交
775
	public static toRawText(rawText:string): editorCommon.IRawText {
E
Erich Gamma 已提交
776 777 778 779 780 781 782 783 784 785 786 787
		// 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 已提交
788 789
		if (strings.startsWithUTF8BOM(lines[0])) {
			BOM = strings.UTF8_BOM_CHARACTER;
E
Erich Gamma 已提交
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
			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
			EOL = DEFAULT_PLATFORM_EOL;
		} 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';
		}

		return {
			BOM: BOM,
			EOL: EOL,
			lines: lines,
			length: rawText.length
		};
	}

A
Alex Dima 已提交
814
	_constructLines(rawText:editorCommon.IRawText): void {
E
Erich Gamma 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827
		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 已提交
828
	private _getEndOfLine(eol:editorCommon.EndOfLinePreference): string {
E
Erich Gamma 已提交
829
		switch (eol) {
A
Alex Dima 已提交
830
			case editorCommon.EndOfLinePreference.LF:
E
Erich Gamma 已提交
831
				return '\n';
A
Alex Dima 已提交
832
			case editorCommon.EndOfLinePreference.CRLF:
E
Erich Gamma 已提交
833
				return '\r\n';
A
Alex Dima 已提交
834
			case editorCommon.EndOfLinePreference.TextDefined:
E
Erich Gamma 已提交
835 836 837 838 839
				return this.getEOL();
		}
		throw new Error('Unknown EOL preference');
	}

A
Alex Dima 已提交
840
	public findMatches(searchString:string, rawSearchScope:any, isRegex:boolean, matchCase:boolean, wholeWord:boolean, limitResultCount:number = LIMIT_FIND_COUNT): editorCommon.IEditorRange[] {
E
Erich Gamma 已提交
841 842 843 844
		if (this._isDisposed) {
			throw new Error('Model.findMatches: Model is disposed');
		}

A
Alex Dima 已提交
845
		var regex = strings.createSafeRegExp(searchString, isRegex, matchCase, wholeWord);
E
Erich Gamma 已提交
846 847 848 849
		if (!regex) {
			return [];
		}

A
Alex Dima 已提交
850
		var searchRange:editorCommon.IEditorRange;
E
Erich Gamma 已提交
851 852 853 854 855 856 857 858 859
		if (Range.isIRange(rawSearchScope)) {
			searchRange = rawSearchScope;
		} else {
			searchRange = this.getFullModelRange();
		}

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

A
Alex Dima 已提交
860
	public findNextMatch(searchString:string, rawSearchStart:editorCommon.IPosition, isRegex:boolean, matchCase:boolean, wholeWord:boolean): editorCommon.IEditorRange {
E
Erich Gamma 已提交
861 862 863 864
		if (this._isDisposed) {
			throw new Error('Model.findNextMatch: Model is disposed');
		}

A
Alex Dima 已提交
865
		var regex = strings.createSafeRegExp(searchString, isRegex, matchCase, wholeWord);
E
Erich Gamma 已提交
866 867 868 869 870 871 872 873
		if (!regex) {
			return null;
		}

		var searchStart = this.validatePosition(rawSearchStart),
			lineCount = this.getLineCount(),
			startLineNumber = searchStart.lineNumber,
			text: string,
A
Alex Dima 已提交
874
			r: editorCommon.IEditorRange;
E
Erich Gamma 已提交
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

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

		for (var i = 1; i < lineCount; i++) {
			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 已提交
895
	public findPreviousMatch(searchString:string, rawSearchStart:editorCommon.IPosition, isRegex:boolean, matchCase:boolean, wholeWord:boolean): editorCommon.IEditorRange {
896 897 898 899
		if (this._isDisposed) {
			throw new Error('Model.findPreviousMatch: Model is disposed');
		}

A
Alex Dima 已提交
900
		var regex = strings.createSafeRegExp(searchString, isRegex, matchCase, wholeWord);
901 902 903 904 905 906 907 908
		if (!regex) {
			return null;
		}

		var searchStart = this.validatePosition(rawSearchStart),
			lineCount = this.getLineCount(),
			startLineNumber = searchStart.lineNumber,
			text: string,
A
Alex Dima 已提交
909
			r: editorCommon.IEditorRange;
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929

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

		for (var i = 1; i < lineCount; i++) {
			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 已提交
930 931
	private _doFindMatches(searchRange:editorCommon.IEditorRange, searchRegex:RegExp, limitResultCount:number): editorCommon.IEditorRange[] {
		var result:editorCommon.IEditorRange[] = [],
E
Erich Gamma 已提交
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
			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 已提交
960
	private _findMatchInLine(searchRegex:RegExp, text:string, lineNumber:number, deltaOffset:number): editorCommon.IEditorRange {
E
Erich Gamma 已提交
961 962 963 964 965 966 967
		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 已提交
968 969
	private _findLastMatchInLine(searchRegex:RegExp, text:string, lineNumber:number): editorCommon.IEditorRange {
		let bestResult: editorCommon.IEditorRange = null;
970 971 972 973 974 975 976 977 978 979 980
		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 已提交
981
	private _findMatchesInLine(searchRegex:RegExp, text:string, lineNumber:number, deltaOffset:number, counter:number, result:editorCommon.IEditorRange[], limitResultCount:number): number {
E
Erich Gamma 已提交
982
		var m:RegExpExecArray;
983 984
		// Reset regex to search from the beginning
		searchRegex.lastIndex = 0;
E
Erich Gamma 已提交
985 986 987
		do {
			m = searchRegex.exec(text);
			if (m) {
988 989 990 991 992 993
				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 已提交
994 995 996 997 998 999 1000 1001
				counter++;
				if (counter >= limitResultCount) {
					return counter;
				}
			}
		} while(m);
		return counter;
	}
1002
}