textModel.ts 27.0 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';

A
Alex Dima 已提交
7
import { OrderGuaranteeEventEmitter, BulkListenerCallback } from 'vs/base/common/eventEmitter';
A
Alex Dima 已提交
8
import * as strings from 'vs/base/common/strings';
J
Johannes Rieken 已提交
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';
J
Johannes Rieken 已提交
12 13 14 15 16
import { ModelLine } from 'vs/editor/common/model/modelLine';
import { guessIndentation } from 'vs/editor/common/model/indentationGuesser';
import { DEFAULT_INDENTATION, DEFAULT_TRIM_AUTO_WHITESPACE } from 'vs/editor/common/config/defaultConfig';
import { PrefixSumComputer } from 'vs/editor/common/viewModel/prefixSumComputer';
import { IndentRange, computeRanges } from 'vs/editor/common/model/indentRanges';
A
Alex Dima 已提交
17
import { TextModelSearch, SearchParams } from 'vs/editor/common/model/textModelSearch';
A
Alex Dima 已提交
18
import { TextSource, ITextSource, IRawTextSource, RawTextSource } from 'vs/editor/common/model/textSource';
A
Alex Dima 已提交
19
import { IDisposable } from 'vs/base/common/lifecycle';
E
Erich Gamma 已提交
20

A
Alex Dima 已提交
21
const LIMIT_FIND_COUNT = 999;
22
export const LONG_LINE_BOUNDARY = 10000;
E
Erich Gamma 已提交
23

A
Alex Dima 已提交
24 25 26 27 28
export interface ITextModelCreationData {
	readonly text: ITextSource;
	readonly options: editorCommon.TextModelResolvedOptions;
}

A
Alex Dima 已提交
29
export class TextModel implements editorCommon.ITextModel {
30 31
	private static MODEL_SYNC_LIMIT = 5 * 1024 * 1024; // 5 MB
	private static MODEL_TOKENIZATION_LIMIT = 20 * 1024 * 1024; // 20 MB
E
Erich Gamma 已提交
32

33 34 35 36
	public static DEFAULT_CREATION_OPTIONS: editorCommon.ITextModelCreationOptions = {
		tabSize: DEFAULT_INDENTATION.tabSize,
		insertSpaces: DEFAULT_INDENTATION.insertSpaces,
		detectIndentation: false,
A
Alex Dima 已提交
37
		defaultEOL: editorCommon.DefaultEndOfLine.LF,
38
		trimAutoWhitespace: DEFAULT_TRIM_AUTO_WHITESPACE,
39 40
	};

A
Alex Dima 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
	public static createFromString(text: string, options: editorCommon.ITextModelCreationOptions = TextModel.DEFAULT_CREATION_OPTIONS): TextModel {
		return new TextModel([], RawTextSource.fromString(text), options);
	}

	public static resolveCreationData(rawTextSource: IRawTextSource, options: editorCommon.ITextModelCreationOptions): ITextModelCreationData {
		const textSource = TextSource.fromRawTextSource(rawTextSource, options.defaultEOL);

		let resolvedOpts: editorCommon.TextModelResolvedOptions;
		if (options.detectIndentation) {
			const guessedIndentation = guessIndentation(textSource.lines, options.tabSize, options.insertSpaces);
			resolvedOpts = new editorCommon.TextModelResolvedOptions({
				tabSize: guessedIndentation.tabSize,
				insertSpaces: guessedIndentation.insertSpaces,
				trimAutoWhitespace: options.trimAutoWhitespace,
				defaultEOL: options.defaultEOL
			});
		} else {
			resolvedOpts = new editorCommon.TextModelResolvedOptions({
				tabSize: options.tabSize,
				insertSpaces: options.insertSpaces,
				trimAutoWhitespace: options.trimAutoWhitespace,
				defaultEOL: options.defaultEOL
			});
		}

		return {
			text: textSource,
			options: resolvedOpts
		};
	}

A
Alex Dima 已提交
72 73 74 75 76 77
	public addBulkListener(listener: BulkListenerCallback): IDisposable {
		return this._eventEmitter.addBulkListener(listener);
	}

	protected readonly _eventEmitter: OrderGuaranteeEventEmitter;

J
Johannes Rieken 已提交
78 79 80 81
	/*protected*/ _lines: ModelLine[];
	protected _EOL: string;
	protected _isDisposed: boolean;
	protected _isDisposing: boolean;
82
	protected _options: editorCommon.TextModelResolvedOptions;
83
	protected _lineStarts: PrefixSumComputer;
A
Alex Dima 已提交
84
	private _indentRanges: IndentRange[];
E
Erich Gamma 已提交
85

J
Johannes Rieken 已提交
86
	private _versionId: number;
E
Erich Gamma 已提交
87 88 89 90
	/**
	 * Unlike, versionId, this can go down (via undo) or go to previous values (via redo)
	 */
	private _alternativeVersionId: number;
J
Johannes Rieken 已提交
91
	private _BOM: string;
A
Alex Dima 已提交
92
	protected _mightContainRTL: boolean;
93
	protected _mightContainNonBasicASCII: boolean;
E
Erich Gamma 已提交
94

95 96 97
	private _shouldSimplifyMode: boolean;
	private _shouldDenyMode: boolean;

A
Alex Dima 已提交
98
	constructor(allowedEventTypes: string[], rawTextSource: IRawTextSource, creationOptions: editorCommon.ITextModelCreationOptions) {
99
		allowedEventTypes.push(editorCommon.EventType.ModelRawContentChanged, editorCommon.EventType.ModelOptionsChanged, editorCommon.EventType.ModelContentChanged);
A
Alex Dima 已提交
100
		this._eventEmitter = new OrderGuaranteeEventEmitter(allowedEventTypes);
E
Erich Gamma 已提交
101

A
Alex Dima 已提交
102 103
		const textModelData = TextModel.resolveCreationData(rawTextSource, creationOptions);

A
Alex Dima 已提交
104 105
		this._shouldSimplifyMode = (textModelData.text.length > TextModel.MODEL_SYNC_LIMIT);
		this._shouldDenyMode = (textModelData.text.length > TextModel.MODEL_TOKENIZATION_LIMIT);
106

A
Alex Dima 已提交
107 108
		this._options = new editorCommon.TextModelResolvedOptions(textModelData.options);
		this._constructLines(textModelData.text);
E
Erich Gamma 已提交
109 110 111 112 113
		this._setVersionId(1);
		this._isDisposed = false;
		this._isDisposing = false;
	}

114 115 116 117 118 119
	protected _assertNotDisposed(): void {
		if (this._isDisposed) {
			throw new Error('Model is disposed!');
		}
	}

120
	public isTooLargeForHavingAMode(): boolean {
121
		this._assertNotDisposed();
122 123 124 125
		return this._shouldDenyMode;
	}

	public isTooLargeForHavingARichMode(): boolean {
126
		this._assertNotDisposed();
127 128 129
		return this._shouldSimplifyMode;
	}

130
	public getOptions(): editorCommon.TextModelResolvedOptions {
131
		this._assertNotDisposed();
132 133 134
		return this._options;
	}

135
	public updateOptions(_newOpts: editorCommon.ITextModelUpdateOptions): void {
136
		this._assertNotDisposed();
137 138 139
		let tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
		let insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;
		let trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
140

141 142 143 144 145 146
		let newOpts = new editorCommon.TextModelResolvedOptions({
			tabSize: tabSize,
			insertSpaces: insertSpaces,
			defaultEOL: this._options.defaultEOL,
			trimAutoWhitespace: trimAutoWhitespace
		});
147

148 149
		if (this._options.equals(newOpts)) {
			return;
150
		}
151 152 153 154 155 156 157 158

		let e = this._options.createChangeEvent(newOpts);
		this._options = newOpts;

		if (e.tabSize) {
			let newTabSize = this._options.tabSize;
			for (let i = 0, len = this._lines.length; i < len; i++) {
				this._lines[i].updateTabSize(newTabSize);
159 160
			}
		}
161

A
Alex Dima 已提交
162
		this._eventEmitter.emit(editorCommon.EventType.ModelOptionsChanged, e);
163 164
	}

J
Johannes Rieken 已提交
165
	public detectIndentation(defaultInsertSpaces: boolean, defaultTabSize: number): void {
166
		this._assertNotDisposed();
167 168 169 170 171 172 173 174
		let lines = this._lines.map(line => line.text);
		let guessedIndentation = guessIndentation(lines, defaultTabSize, defaultInsertSpaces);
		this.updateOptions({
			insertSpaces: guessedIndentation.insertSpaces,
			tabSize: guessedIndentation.tabSize
		});
	}

175
	private static _normalizeIndentationFromWhitespace(str: string, tabSize: number, insertSpaces: boolean): string {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
		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;
	}

201
	public static normalizeIndentation(str: string, tabSize: number, insertSpaces: boolean): string {
202 203 204 205
		let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
		if (firstNonWhitespaceIndex === -1) {
			firstNonWhitespaceIndex = str.length;
		}
206 207 208 209 210 211
		return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), tabSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
	}

	public normalizeIndentation(str: string): string {
		this._assertNotDisposed();
		return TextModel.normalizeIndentation(str, this._options.tabSize, this._options.insertSpaces);
212 213 214
	}

	public getOneIndent(): string {
215
		this._assertNotDisposed();
216 217 218 219 220 221 222 223 224 225 226 227 228 229
		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 已提交
230
	public getVersionId(): number {
231
		this._assertNotDisposed();
E
Erich Gamma 已提交
232 233 234
		return this._versionId;
	}

A
Alex Dima 已提交
235 236 237 238
	public mightContainRTL(): boolean {
		return this._mightContainRTL;
	}

239 240 241 242
	public mightContainNonBasicASCII(): boolean {
		return this._mightContainNonBasicASCII;
	}

E
Erich Gamma 已提交
243
	public getAlternativeVersionId(): number {
244
		this._assertNotDisposed();
E
Erich Gamma 已提交
245 246 247
		return this._alternativeVersionId;
	}

248 249 250
	private _ensureLineStarts(): void {
		if (!this._lineStarts) {
			const eolLength = this._EOL.length;
251 252 253 254
			const linesLength = this._lines.length;
			const lineStartValues = new Uint32Array(linesLength);
			for (let i = 0; i < linesLength; i++) {
				lineStartValues[i] = this._lines[i].text.length + eolLength;
255 256 257 258 259 260
			}
			this._lineStarts = new PrefixSumComputer(lineStartValues);
		}
	}

	public getOffsetAt(rawPosition: editorCommon.IPosition): number {
261
		this._assertNotDisposed();
262
		let position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, false);
263 264 265 266 267
		this._ensureLineStarts();
		return this._lineStarts.getAccumulatedValue(position.lineNumber - 2) + position.column - 1;
	}

	public getPositionAt(offset: number): Position {
268
		this._assertNotDisposed();
269 270 271 272 273 274 275 276 277 278 279 280
		offset = Math.floor(offset);
		offset = Math.max(0, offset);

		this._ensureLineStarts();
		let out = this._lineStarts.getIndexOf(offset);

		let lineLength = this._lines[out.index].text.length;

		// Ensure we return a valid position
		return new Position(out.index + 1, Math.min(out.remainder + 1, lineLength + 1));
	}

A
Alex Dima 已提交
281
	protected _increaseVersionId(): void {
E
Erich Gamma 已提交
282 283 284
		this._setVersionId(this._versionId + 1);
	}

J
Johannes Rieken 已提交
285
	protected _setVersionId(newVersionId: number): void {
E
Erich Gamma 已提交
286 287 288 289
		this._versionId = newVersionId;
		this._alternativeVersionId = this._versionId;
	}

J
Johannes Rieken 已提交
290
	protected _overwriteAlternativeVersionId(newAlternativeVersionId: number): void {
E
Erich Gamma 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304
		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;

A
Alex Dima 已提交
305
		this._eventEmitter.dispose();
E
Erich Gamma 已提交
306 307
	}

308
	private _createContentChangedFlushEvent(): editorCommon.IModelRawContentChangedFlushEvent {
E
Erich Gamma 已提交
309
		return {
A
Alex Dima 已提交
310
			changeType: editorCommon.EventType.ModelRawContentChangedFlush,
311
			versionId: this._versionId,
E
Erich Gamma 已提交
312 313 314 315 316 317
			// TODO@Alex -> remove these fields from here
			isUndoing: false,
			isRedoing: false
		};
	}

318 319 320 321 322 323 324
	private _emitContentChanged2(startLineNumber: number, startColumn: number, endLineNumber: number, endColumn: number, rangeLength: number, text: string, isUndoing: boolean, isRedoing: boolean, isFlush: boolean): void {
		const e: editorCommon.IModelContentChangedEvent = {
			changes: [{
				range: new Range(startLineNumber, startColumn, endLineNumber, endColumn),
				rangeLength: rangeLength,
				text: text,
			}],
325
			eol: this._EOL,
E
Erich Gamma 已提交
326 327
			versionId: this.getVersionId(),
			isUndoing: isUndoing,
328 329
			isRedoing: isRedoing,
			isFlush: isFlush
E
Erich Gamma 已提交
330 331
		};
		if (!this._isDisposing) {
A
Alex Dima 已提交
332
			this._eventEmitter.emit(editorCommon.EventType.ModelContentChanged, e);
E
Erich Gamma 已提交
333 334 335
		}
	}

A
Alex Dima 已提交
336
	protected _resetValue(newValue: ITextSource): void {
337
		this._constructLines(newValue);
E
Erich Gamma 已提交
338 339 340
		this._increaseVersionId();
	}

A
Alex Dima 已提交
341
	public equals(other: ITextSource): boolean {
342
		this._assertNotDisposed();
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
		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;
	}

J
Johannes Rieken 已提交
360
	public setValue(value: string): void {
361
		this._assertNotDisposed();
A
Alex Dima 已提交
362 363 364
		if (value === null) {
			// There's nothing to do
			return;
365
		}
A
Alex Dima 已提交
366
		const textSource = TextSource.fromString(value, this._options.defaultEOL);
A
Alex Dima 已提交
367
		this.setValueFromTextSource(textSource);
368 369
	}

A
Alex Dima 已提交
370
	public setValueFromTextSource(newValue: ITextSource): void {
371
		this._assertNotDisposed();
E
Erich Gamma 已提交
372 373 374 375 376 377 378 379
		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);
380

381 382 383 384
		this._resetValue(newValue);

		this._emitModelContentChangedFlushEvent(this._createContentChangedFlushEvent());

385
		this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false, true);
E
Erich Gamma 已提交
386 387
	}

J
Johannes Rieken 已提交
388
	public getValue(eol?: editorCommon.EndOfLinePreference, preserveBOM: boolean = false): string {
389
		this._assertNotDisposed();
E
Erich Gamma 已提交
390 391 392 393 394 395 396 397 398 399
		var fullModelRange = this.getFullModelRange();
		var fullModelValue = this.getValueInRange(fullModelRange, eol);

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

		return fullModelValue;
	}

A
Alex Dima 已提交
400
	public getValueLength(eol?: editorCommon.EndOfLinePreference, preserveBOM: boolean = false): number {
401
		this._assertNotDisposed();
E
Erich Gamma 已提交
402 403 404 405 406 407 408 409 410 411
		var fullModelRange = this.getFullModelRange();
		var fullModelValue = this.getValueLengthInRange(fullModelRange, eol);

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

		return fullModelValue;
	}

J
Johannes Rieken 已提交
412
	public getEmptiedValueInRange(rawRange: editorCommon.IRange, fillCharacter: string = '', eol: editorCommon.EndOfLinePreference = editorCommon.EndOfLinePreference.TextDefined): string {
413
		this._assertNotDisposed();
E
Erich Gamma 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426
		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,
J
Johannes Rieken 已提交
427
			resultLines: string[] = [];
E
Erich Gamma 已提交
428 429 430 431 432 433 434 435 436 437

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

J
Johannes Rieken 已提交
438
	private _repeatCharacter(fillCharacter: string, count: number): string {
E
Erich Gamma 已提交
439 440 441 442 443 444 445
		var r = '';
		for (var i = 0; i < count; i++) {
			r += fillCharacter;
		}
		return r;
	}

J
Johannes Rieken 已提交
446
	public getValueInRange(rawRange: editorCommon.IRange, eol: editorCommon.EndOfLinePreference = editorCommon.EndOfLinePreference.TextDefined): string {
447
		this._assertNotDisposed();
E
Erich Gamma 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460
		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,
J
Johannes Rieken 已提交
461
			resultLines: string[] = [];
E
Erich Gamma 已提交
462 463 464 465 466 467 468 469 470 471

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

J
Johannes Rieken 已提交
472
	public getValueLengthInRange(rawRange: editorCommon.IRange, eol: editorCommon.EndOfLinePreference = editorCommon.EndOfLinePreference.TextDefined): number {
473
		this._assertNotDisposed();
E
Erich Gamma 已提交
474 475 476 477 478 479 480 481 482 483
		var range = this.validateRange(rawRange);

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

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

484 485 486
		let startOffset = this.getOffsetAt(new Position(range.startLineNumber, range.startColumn));
		let endOffset = this.getOffsetAt(new Position(range.endLineNumber, range.endColumn));
		return endOffset - startOffset;
E
Erich Gamma 已提交
487 488
	}

A
Alex Dima 已提交
489
	public isDominatedByLongLines(): boolean {
490
		this._assertNotDisposed();
E
Erich Gamma 已提交
491 492 493 494 495 496 497 498 499
		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 已提交
500
			if (lineLength >= LONG_LINE_BOUNDARY) {
E
Erich Gamma 已提交
501 502 503 504 505 506 507 508 509 510
				longLineCharCount += lineLength;
			} else {
				smallLineCharCount += lineLength;
			}
		}

		return (longLineCharCount > smallLineCharCount);
	}

	public getLineCount(): number {
511
		this._assertNotDisposed();
E
Erich Gamma 已提交
512 513 514
		return this._lines.length;
	}

J
Johannes Rieken 已提交
515
	public getLineContent(lineNumber: number): string {
516
		this._assertNotDisposed();
E
Erich Gamma 已提交
517 518 519 520 521 522 523
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

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

J
Johannes Rieken 已提交
524
	public getIndentLevel(lineNumber: number): number {
525
		this._assertNotDisposed();
526 527 528 529 530 531 532
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

		return this._lines[lineNumber - 1].getIndentLevel();
	}

A
Alex Dima 已提交
533 534 535 536
	protected _resetIndentRanges(): void {
		this._indentRanges = null;
	}

A
Alex Dima 已提交
537
	private _getIndentRanges(): IndentRange[] {
A
Alex Dima 已提交
538 539 540
		if (!this._indentRanges) {
			this._indentRanges = computeRanges(this);
		}
A
Alex Dima 已提交
541 542 543 544
		return this._indentRanges;
	}

	public getIndentRanges(): IndentRange[] {
545
		this._assertNotDisposed();
A
Alex Dima 已提交
546 547 548 549
		let indentRanges = this._getIndentRanges();
		return IndentRange.deepCloneArr(indentRanges);
	}

J
Johannes Rieken 已提交
550
	private _toValidLineIndentGuide(lineNumber: number, indentGuide: number): number {
551 552 553 554 555 556 557 558
		let lineIndentLevel = this._lines[lineNumber - 1].getIndentLevel();
		if (lineIndentLevel === -1) {
			return indentGuide;
		}
		let maxIndentGuide = Math.ceil(lineIndentLevel / this._options.tabSize);
		return Math.min(maxIndentGuide, indentGuide);
	}

J
Johannes Rieken 已提交
559
	public getLineIndentGuide(lineNumber: number): number {
560
		this._assertNotDisposed();
A
Alex Dima 已提交
561 562 563 564 565 566 567 568 569
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

		let indentRanges = this._getIndentRanges();

		for (let i = indentRanges.length - 1; i >= 0; i--) {
			let rng = indentRanges[i];

570
			if (rng.startLineNumber === lineNumber) {
571
				return this._toValidLineIndentGuide(lineNumber, Math.ceil(rng.indent / this._options.tabSize));
572
			}
A
Alex Dima 已提交
573
			if (rng.startLineNumber < lineNumber && lineNumber <= rng.endLineNumber) {
574
				return this._toValidLineIndentGuide(lineNumber, 1 + Math.floor(rng.indent / this._options.tabSize));
A
Alex Dima 已提交
575
			}
576
			if (rng.endLineNumber + 1 === lineNumber) {
577 578 579 580 581 582 583
				let bestIndent = rng.indent;
				while (i > 0) {
					i--;
					rng = indentRanges[i];
					if (rng.endLineNumber + 1 === lineNumber) {
						bestIndent = rng.indent;
					}
584
				}
585
				return this._toValidLineIndentGuide(lineNumber, Math.ceil(bestIndent / this._options.tabSize));
586
			}
A
Alex Dima 已提交
587 588 589
		}

		return 0;
A
Alex Dima 已提交
590 591
	}

E
Erich Gamma 已提交
592
	public getLinesContent(): string[] {
593
		this._assertNotDisposed();
E
Erich Gamma 已提交
594 595 596 597 598 599 600 601
		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 {
602
		this._assertNotDisposed();
E
Erich Gamma 已提交
603 604 605
		return this._EOL;
	}

A
Alex Dima 已提交
606
	public setEOL(eol: editorCommon.EndOfLineSequence): void {
607
		this._assertNotDisposed();
608
		const newEOL = (eol === editorCommon.EndOfLineSequence.CRLF ? '\r\n' : '\n');
E
Erich Gamma 已提交
609 610 611 612 613
		if (this._EOL === newEOL) {
			// Nothing to do
			return;
		}

614 615 616 617
		const oldFullModelRange = this.getFullModelRange();
		const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
		const endLineNumber = this.getLineCount();
		const endColumn = this.getLineMaxColumn(endLineNumber);
E
Erich Gamma 已提交
618 619

		this._EOL = newEOL;
620
		this._lineStarts = null;
E
Erich Gamma 已提交
621 622
		this._increaseVersionId();

623
		this._emitModelContentChangedFlushEvent(this._createContentChangedFlushEvent());
E
Erich Gamma 已提交
624

625
		this._emitContentChanged2(1, 1, endLineNumber, endColumn, oldModelValueLength, this.getValue(), false, false, false);
E
Erich Gamma 已提交
626 627
	}

J
Johannes Rieken 已提交
628
	public getLineMinColumn(lineNumber: number): number {
629
		this._assertNotDisposed();
E
Erich Gamma 已提交
630 631 632
		return 1;
	}

J
Johannes Rieken 已提交
633
	public getLineMaxColumn(lineNumber: number): number {
634
		this._assertNotDisposed();
E
Erich Gamma 已提交
635 636 637 638 639 640 641 642
		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 {
643
		this._assertNotDisposed();
E
Erich Gamma 已提交
644 645 646 647
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

A
Alex Dima 已提交
648
		var result = strings.firstNonWhitespaceIndex(this._lines[lineNumber - 1].text);
E
Erich Gamma 已提交
649 650 651 652 653 654 655
		if (result === -1) {
			return 0;
		}
		return result + 1;
	}

	public getLineLastNonWhitespaceColumn(lineNumber: number): number {
656
		this._assertNotDisposed();
E
Erich Gamma 已提交
657 658 659 660
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value ' + lineNumber + ' for `lineNumber`');
		}

A
Alex Dima 已提交
661
		var result = strings.lastNonWhitespaceIndex(this._lines[lineNumber - 1].text);
E
Erich Gamma 已提交
662 663 664 665 666 667
		if (result === -1) {
			return 0;
		}
		return result + 2;
	}

J
Johannes Rieken 已提交
668
	public validateLineNumber(lineNumber: number): number {
669
		this._assertNotDisposed();
E
Erich Gamma 已提交
670 671 672 673 674 675 676 677 678
		if (lineNumber < 1) {
			lineNumber = 1;
		}
		if (lineNumber > this._lines.length) {
			lineNumber = this._lines.length;
		}
		return lineNumber;
	}

679 680 681
	/**
	 * @param strict Do NOT allow a position inside a high-low surrogate pair
	 */
J
Johannes Rieken 已提交
682
	private _validatePosition(_lineNumber: number, _column: number, strict: boolean): Position {
683 684
		const lineNumber = Math.floor(typeof _lineNumber === 'number' ? _lineNumber : 1);
		const column = Math.floor(typeof _column === 'number' ? _column : 1);
E
Erich Gamma 已提交
685 686

		if (lineNumber < 1) {
687
			return new Position(1, 1);
E
Erich Gamma 已提交
688
		}
689 690 691

		if (lineNumber > this._lines.length) {
			return new Position(this._lines.length, this.getLineMaxColumn(this._lines.length));
E
Erich Gamma 已提交
692
		}
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

		if (column <= 1) {
			return new Position(lineNumber, 1);
		}

		const maxColumn = this.getLineMaxColumn(lineNumber);
		if (column >= maxColumn) {
			return new Position(lineNumber, maxColumn);
		}

		if (strict) {
			// If the position would end up in the middle of a high-low surrogate pair,
			// we move it to before the pair
			// !!At this point, column > 1
			const charCodeBefore = this._lines[lineNumber - 1].text.charCodeAt(column - 2);
			if (strings.isHighSurrogate(charCodeBefore)) {
				return new Position(lineNumber, column - 1);
A
aioute Gao 已提交
710
			}
E
Erich Gamma 已提交
711 712 713 714 715
		}

		return new Position(lineNumber, column);
	}

J
Johannes Rieken 已提交
716
	public validatePosition(position: editorCommon.IPosition): Position {
717
		this._assertNotDisposed();
718 719 720
		return this._validatePosition(position.lineNumber, position.column, true);
	}

J
Johannes Rieken 已提交
721
	public validateRange(_range: editorCommon.IRange): Range {
722
		this._assertNotDisposed();
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
		const start = this._validatePosition(_range.startLineNumber, _range.startColumn, false);
		const end = this._validatePosition(_range.endLineNumber, _range.endColumn, false);

		const startLineNumber = start.lineNumber;
		const startColumn = start.column;
		const endLineNumber = end.lineNumber;
		const endColumn = end.column;

		const startLineText = this._lines[startLineNumber - 1].text;
		const endLineText = this._lines[endLineNumber - 1].text;

		const charCodeBeforeStart = (startColumn > 1 ? startLineText.charCodeAt(startColumn - 2) : 0);
		const charCodeBeforeEnd = (endColumn > 1 && endColumn <= endLineText.length ? endLineText.charCodeAt(endColumn - 2) : 0);

		const startInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeStart);
		const endInsideSurrogatePair = strings.isHighSurrogate(charCodeBeforeEnd);

		if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
			return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
		}

		if (startLineNumber === endLineNumber && startColumn === endColumn) {
			// do not expand a collapsed range, simply move it to a valid location
			return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
		}

		if (startInsideSurrogatePair && endInsideSurrogatePair) {
			// expand range at both ends
			return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
		}

		if (startInsideSurrogatePair) {
			// only expand range at the start
			return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);
		}

		// only expand range at the end
		return new Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);
E
Erich Gamma 已提交
761 762
	}

J
Johannes Rieken 已提交
763
	public modifyPosition(rawPosition: editorCommon.IPosition, offset: number): Position {
764
		this._assertNotDisposed();
765
		return this.getPositionAt(this.getOffsetAt(rawPosition) + offset);
E
Erich Gamma 已提交
766 767
	}

768
	public getFullModelRange(): Range {
769
		this._assertNotDisposed();
E
Erich Gamma 已提交
770 771 772 773
		var lineCount = this.getLineCount();
		return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
	}

774
	protected _emitModelContentChangedFlushEvent(e: editorCommon.IModelRawContentChangedFlushEvent): void {
E
Erich Gamma 已提交
775
		if (!this._isDisposing) {
A
Alex Dima 已提交
776
			this._eventEmitter.emit(editorCommon.EventType.ModelRawContentChanged, e);
E
Erich Gamma 已提交
777 778 779
		}
	}

A
Alex Dima 已提交
780
	private _constructLines(textSource: ITextSource): void {
781
		const tabSize = this._options.tabSize;
A
Alex Dima 已提交
782
		let rawLines = textSource.lines;
783
		let modelLines: ModelLine[] = [];
E
Erich Gamma 已提交
784

785 786
		for (let i = 0, len = rawLines.length; i < len; i++) {
			modelLines[i] = new ModelLine(i + 1, rawLines[i], tabSize);
E
Erich Gamma 已提交
787
		}
A
Alex Dima 已提交
788 789 790 791
		this._BOM = textSource.BOM;
		this._mightContainRTL = textSource.containsRTL;
		this._mightContainNonBasicASCII = !textSource.isBasicASCII;
		this._EOL = textSource.EOL;
E
Erich Gamma 已提交
792
		this._lines = modelLines;
793
		this._lineStarts = null;
A
Alex Dima 已提交
794
		this._resetIndentRanges();
E
Erich Gamma 已提交
795 796
	}

J
Johannes Rieken 已提交
797
	private _getEndOfLine(eol: editorCommon.EndOfLinePreference): string {
E
Erich Gamma 已提交
798
		switch (eol) {
A
Alex Dima 已提交
799
			case editorCommon.EndOfLinePreference.LF:
E
Erich Gamma 已提交
800
				return '\n';
A
Alex Dima 已提交
801
			case editorCommon.EndOfLinePreference.CRLF:
E
Erich Gamma 已提交
802
				return '\r\n';
A
Alex Dima 已提交
803
			case editorCommon.EndOfLinePreference.TextDefined:
E
Erich Gamma 已提交
804 805 806 807 808
				return this.getEOL();
		}
		throw new Error('Unknown EOL preference');
	}

809
	public findMatches(searchString: string, rawSearchScope: any, isRegex: boolean, matchCase: boolean, wholeWord: boolean, captureMatches: boolean, limitResultCount: number = LIMIT_FIND_COUNT): editorCommon.FindMatch[] {
810
		this._assertNotDisposed();
E
Erich Gamma 已提交
811

J
Johannes Rieken 已提交
812
		let searchRange: Range;
E
Erich Gamma 已提交
813
		if (Range.isIRange(rawSearchScope)) {
A
Alex Dima 已提交
814
			searchRange = this.validateRange(rawSearchScope);
E
Erich Gamma 已提交
815 816 817 818
		} else {
			searchRange = this.getFullModelRange();
		}

819
		return TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wholeWord), searchRange, captureMatches, limitResultCount);
E
Erich Gamma 已提交
820 821
	}

822
	public findNextMatch(searchString: string, rawSearchStart: editorCommon.IPosition, isRegex: boolean, matchCase: boolean, wholeWord: boolean, captureMatches: boolean): editorCommon.FindMatch {
823
		this._assertNotDisposed();
824 825
		const searchStart = this.validatePosition(rawSearchStart);
		return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wholeWord), searchStart, captureMatches);
E
Erich Gamma 已提交
826 827
	}

828
	public findPreviousMatch(searchString: string, rawSearchStart: editorCommon.IPosition, isRegex: boolean, matchCase: boolean, wholeWord: boolean, captureMatches: boolean): editorCommon.FindMatch {
829
		this._assertNotDisposed();
830 831
		const searchStart = this.validatePosition(rawSearchStart);
		return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wholeWord), searchStart, captureMatches);
E
Erich Gamma 已提交
832
	}
833
}