textModel.ts 95.2 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 URI from 'vs/base/common/uri';
M
Matt Bierner 已提交
8
import { Event, Emitter } from 'vs/base/common/event';
A
Alex Dima 已提交
9
import * as model from 'vs/editor/common/model';
A
Alex Dima 已提交
10
import { LanguageIdentifier, TokenizationRegistry, LanguageId } from 'vs/editor/common/modes';
A
Alex Dima 已提交
11
import { EditStack } from 'vs/editor/common/model/editStack';
A
Alex Dima 已提交
12
import { Range, IRange } from 'vs/editor/common/core/range';
13
import { Selection } from 'vs/editor/common/core/selection';
14
import { ModelRawContentChangedEvent, IModelDecorationsChangedEvent, IModelLanguageChangedEvent, IModelLanguageConfigurationChangedEvent, IModelTokensChangedEvent, IModelOptionsChangedEvent, IModelContentChangedEvent, InternalModelContentChangeEvent, ModelRawFlush, ModelRawEOLChanged, ModelRawChange, ModelRawLineChanged, ModelRawLinesDeleted, ModelRawLinesInserted } from 'vs/editor/common/model/textModelEvents';
15 16 17 18 19 20
import { onUnexpectedError } from 'vs/base/common/errors';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import * as strings from 'vs/base/common/strings';
import { CharCode } from 'vs/base/common/charCode';
import { ThemeColor } from 'vs/platform/theme/common/themeService';
import { IntervalNode, IntervalTree, recomputeMaxEnd, getNodeIsInOverviewRuler } from 'vs/editor/common/model/intervalTree';
A
Alex Dima 已提交
21 22 23 24 25 26 27 28 29
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { StopWatch } from 'vs/base/common/stopwatch';
import { NULL_LANGUAGE_IDENTIFIER } from 'vs/editor/common/modes/nullMode';
import { ignoreBracketsInToken } from 'vs/editor/common/modes/supports';
import { BracketsUtils, RichEditBrackets, RichEditBracket } from 'vs/editor/common/modes/supports/richEditBrackets';
import { Position, IPosition } from 'vs/editor/common/core/position';
import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry';
import { LineTokens } from 'vs/editor/common/core/lineTokens';
import { getWordAtText } from 'vs/editor/common/model/wordHelper';
A
Rename  
Alex Dima 已提交
30
import { ModelLinesTokens, ModelTokensChangedEventBuilder } from 'vs/editor/common/model/textModelTokens';
A
Alex Dima 已提交
31
import { guessIndentation } from 'vs/editor/common/model/indentationGuesser';
32
import { EDITOR_MODEL_DEFAULTS } from 'vs/editor/common/config/editorOptions';
P
Peng Lyu 已提交
33
import { TextModelSearch, SearchParams, SearchData } from 'vs/editor/common/model/textModelSearch';
34
import { TPromise } from 'vs/base/common/winjs.base';
35
import { IStringStream, ITextSnapshot } from 'vs/platform/files/common/files';
36
import { PieceTreeTextBufferBuilder } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder';
37

A
Alex Dima 已提交
38
function createTextBufferBuilder() {
A
Alex Dima 已提交
39
	return new PieceTreeTextBufferBuilder();
A
Alex Dima 已提交
40 41 42 43 44 45 46
}

export function createTextBufferFactory(text: string): model.ITextBufferFactory {
	const builder = createTextBufferBuilder();
	builder.acceptChunk(text);
	return builder.finish();
}
47

48
export function createTextBufferFactoryFromStream(stream: IStringStream, filter?: (chunk: string) => string): TPromise<model.ITextBufferFactory> {
49 50 51 52 53
	return new TPromise<model.ITextBufferFactory>((c, e, p) => {
		let done = false;
		let builder = createTextBufferBuilder();

		stream.on('data', (chunk) => {
54 55 56 57
			if (filter) {
				chunk = filter(chunk);
			}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
			builder.acceptChunk(chunk);
		});

		stream.on('error', (error) => {
			if (!done) {
				done = true;
				e(error);
			}
		});

		stream.on('end', () => {
			if (!done) {
				done = true;
				c(builder.finish());
			}
		});
	});
75 76
}

B
Benjamin Pasero 已提交
77 78 79 80 81 82 83 84 85 86 87
export function createTextBufferFactoryFromSnapshot(snapshot: ITextSnapshot): model.ITextBufferFactory {
	let builder = createTextBufferBuilder();

	let chunk: string;
	while (typeof (chunk = snapshot.read()) === 'string') {
		builder.acceptChunk(chunk);
	}

	return builder.finish();
}

88 89 90 91
export function createTextBuffer(value: string | model.ITextBufferFactory, defaultEOL: model.DefaultEndOfLine): model.ITextBuffer {
	const factory = (typeof value === 'string' ? createTextBufferFactory(value) : value);
	return factory.create(defaultEOL);
}
E
Erich Gamma 已提交
92

A
Alex Dima 已提交
93
let MODEL_ID = 0;
E
Erich Gamma 已提交
94

95 96 97
/**
 * Produces 'a'-'z', followed by 'A'-'Z'... followed by 'a'-'z', etc.
 */
A
Alex Dima 已提交
98
function singleLetter(result: number): string {
99
	const LETTERS_CNT = (CharCode.Z - CharCode.A + 1);
E
Erich Gamma 已提交
100

101 102 103 104 105 106 107 108
	result = result % (2 * LETTERS_CNT);

	if (result < LETTERS_CNT) {
		return String.fromCharCode(CharCode.a + result);
	}

	return String.fromCharCode(CharCode.A + result - LETTERS_CNT);
}
E
Erich Gamma 已提交
109

A
Alex Dima 已提交
110
const LIMIT_FIND_COUNT = 999;
111
export const LONG_LINE_BOUNDARY = 10000;
E
Erich Gamma 已提交
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 153 154
class TextModelSnapshot implements ITextSnapshot {

	private readonly _source: ITextSnapshot;
	private _eos: boolean;

	constructor(source: ITextSnapshot) {
		this._source = source;
		this._eos = false;
	}

	public read(): string {
		if (this._eos) {
			return null;
		}

		let result: string[] = [], resultCnt = 0, resultLength = 0;

		do {
			let tmp = this._source.read();

			if (tmp === null) {
				// end-of-stream
				this._eos = true;
				if (resultCnt === 0) {
					return null;
				} else {
					return result.join('');
				}
			}

			if (tmp.length > 0) {
				result[resultCnt++] = tmp;
				resultLength += tmp.length;
			}

			if (resultLength >= 64 * 1024) {
				return result.join('');
			}
		} while (true);
	}
}

A
Alex Dima 已提交
155
export class TextModel extends Disposable implements model.ITextModel {
A
Alex Dima 已提交
156

157
	private static readonly MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB
158 159
	private static readonly LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024; // 20 MB;
	private static readonly LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1000; // 300K lines
E
Erich Gamma 已提交
160

161
	public static DEFAULT_CREATION_OPTIONS: model.ITextModelCreationOptions = {
162
		isForSimpleWidget: false,
163 164
		tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
		insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
165
		detectIndentation: false,
166
		defaultEOL: model.DefaultEndOfLine.LF,
167
		trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
168
		largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
169 170
	};

171
	public static createFromString(text: string, options: model.ITextModelCreationOptions = TextModel.DEFAULT_CREATION_OPTIONS, languageIdentifier: LanguageIdentifier = null, uri: URI = null): TextModel {
172
		return new TextModel(text, options, languageIdentifier, uri);
A
Alex Dima 已提交
173 174
	}

A
Alex Dima 已提交
175
	public static resolveOptions(textBuffer: model.ITextBuffer, options: model.ITextModelCreationOptions): model.TextModelResolvedOptions {
A
Alex Dima 已提交
176
		if (options.detectIndentation) {
A
Alex Dima 已提交
177 178
			const guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
			return new model.TextModelResolvedOptions({
A
Alex Dima 已提交
179 180 181 182 183 184 185
				tabSize: guessedIndentation.tabSize,
				insertSpaces: guessedIndentation.insertSpaces,
				trimAutoWhitespace: options.trimAutoWhitespace,
				defaultEOL: options.defaultEOL
			});
		}

A
Alex Dima 已提交
186 187 188 189 190 191 192
		return new model.TextModelResolvedOptions({
			tabSize: options.tabSize,
			insertSpaces: options.insertSpaces,
			trimAutoWhitespace: options.trimAutoWhitespace,
			defaultEOL: options.defaultEOL
		});

A
Alex Dima 已提交
193 194
	}

A
Alex Dima 已提交
195
	//#region Events
196 197
	private readonly _onWillDispose: Emitter<void> = this._register(new Emitter<void>());
	public readonly onWillDispose: Event<void> = this._onWillDispose.event;
E
Erich Gamma 已提交
198

199 200 201
	private readonly _onDidChangeDecorations: DidChangeDecorationsEmitter = this._register(new DidChangeDecorationsEmitter());
	public readonly onDidChangeDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeDecorations.event;

A
Alex Dima 已提交
202 203 204 205 206 207 208 209 210
	private readonly _onDidChangeLanguage: Emitter<IModelLanguageChangedEvent> = this._register(new Emitter<IModelLanguageChangedEvent>());
	public readonly onDidChangeLanguage: Event<IModelLanguageChangedEvent> = this._onDidChangeLanguage.event;

	private readonly _onDidChangeLanguageConfiguration: Emitter<IModelLanguageConfigurationChangedEvent> = this._register(new Emitter<IModelLanguageConfigurationChangedEvent>());
	public readonly onDidChangeLanguageConfiguration: Event<IModelLanguageConfigurationChangedEvent> = this._onDidChangeLanguageConfiguration.event;

	private readonly _onDidChangeTokens: Emitter<IModelTokensChangedEvent> = this._register(new Emitter<IModelTokensChangedEvent>());
	public readonly onDidChangeTokens: Event<IModelTokensChangedEvent> = this._onDidChangeTokens.event;

A
Alex Dima 已提交
211 212 213
	private readonly _onDidChangeOptions: Emitter<IModelOptionsChangedEvent> = this._register(new Emitter<IModelOptionsChangedEvent>());
	public readonly onDidChangeOptions: Event<IModelOptionsChangedEvent> = this._onDidChangeOptions.event;

A
Alex Dima 已提交
214
	private readonly _eventEmitter: DidChangeContentEmitter = this._register(new DidChangeContentEmitter());
215 216 217
	public onDidChangeRawContentFast(listener: (e: ModelRawContentChangedEvent) => void): IDisposable {
		return this._eventEmitter.fastEvent((e: InternalModelContentChangeEvent) => listener(e.rawContentChangedEvent));
	}
218
	public onDidChangeRawContent(listener: (e: ModelRawContentChangedEvent) => void): IDisposable {
219
		return this._eventEmitter.slowEvent((e: InternalModelContentChangeEvent) => listener(e.rawContentChangedEvent));
220 221
	}
	public onDidChangeContent(listener: (e: IModelContentChangedEvent) => void): IDisposable {
222
		return this._eventEmitter.slowEvent((e: InternalModelContentChangeEvent) => listener(e.contentChangedEvent));
223
	}
A
Alex Dima 已提交
224
	//#endregion
A
Alex Dima 已提交
225

226
	public readonly id: string;
227
	public readonly isForSimpleWidget: boolean;
228
	private readonly _associatedResource: URI;
J
Johannes Rieken 已提交
229
	private _attachedEditorCount: number;
A
Alex Dima 已提交
230 231
	private _buffer: model.ITextBuffer;
	private _options: model.TextModelResolvedOptions;
E
Erich Gamma 已提交
232

A
Alex Dima 已提交
233 234
	private _isDisposed: boolean;
	private _isDisposing: boolean;
J
Johannes Rieken 已提交
235
	private _versionId: number;
E
Erich Gamma 已提交
236 237 238 239
	/**
	 * Unlike, versionId, this can go down (via undo) or go to previous values (via redo)
	 */
	private _alternativeVersionId: number;
A
Alex Dima 已提交
240
	private readonly _isTooLargeForSyncing: boolean;
A
Alex Dima 已提交
241
	private readonly _isTooLargeForTokenization: boolean;
242

243
	//#region Editing
A
Alex Dima 已提交
244 245 246 247
	private _commandManager: EditStack;
	private _isUndoing: boolean;
	private _isRedoing: boolean;
	private _trimAutoWhitespaceLines: number[];
248
	//#endregion
A
Alex Dima 已提交
249

250 251 252 253 254 255 256 257 258 259
	//#region Decorations
	/**
	 * Used to workaround broken clients that might attempt using a decoration id generated by a different model.
	 * It is not globally unique in order to limit it to one character.
	 */
	private readonly _instanceId: string;
	private _lastDecorationId: number;
	private _decorations: { [decorationId: string]: IntervalNode; };
	private _decorationsTree: DecorationsTrees;
	//#endregion
A
Alex Dima 已提交
260

A
Alex Dima 已提交
261 262 263 264 265
	//#region Tokenization
	private _languageIdentifier: LanguageIdentifier;
	private _tokenizationListener: IDisposable;
	private _languageRegistryListener: IDisposable;
	private _revalidateTokensTimeout: number;
A
Alex Dima 已提交
266
	/*private*/_tokens: ModelLinesTokens;
A
Alex Dima 已提交
267 268
	//#endregion

269
	constructor(source: string | model.ITextBufferFactory, creationOptions: model.ITextModelCreationOptions, languageIdentifier: LanguageIdentifier, associatedResource: URI = null) {
A
Alex Dima 已提交
270
		super();
E
Erich Gamma 已提交
271

A
Alex Dima 已提交
272 273 274
		// Generate a new unique model id
		MODEL_ID++;
		this.id = '$model' + MODEL_ID;
275
		this.isForSimpleWidget = creationOptions.isForSimpleWidget;
A
Alex Dima 已提交
276 277 278 279 280 281 282
		if (typeof associatedResource === 'undefined' || associatedResource === null) {
			this._associatedResource = URI.parse('inmemory://model/' + MODEL_ID);
		} else {
			this._associatedResource = associatedResource;
		}
		this._attachedEditorCount = 0;

283
		this._buffer = createTextBuffer(source, creationOptions.defaultEOL);
A
Alex Dima 已提交
284

A
Alex Dima 已提交
285
		this._options = TextModel.resolveOptions(this._buffer, creationOptions);
A
Alex Dima 已提交
286

A
Alex Dima 已提交
287 288
		const bufferLineCount = this._buffer.getLineCount();
		const bufferTextLength = this._buffer.getValueLengthInRange(new Range(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1), model.EndOfLinePreference.TextDefined);
289

290 291 292
		// !!! Make a decision in the ctor and permanently respect this decision !!!
		// If a model is too large at construction time, it will never get tokenized,
		// under no circumstances.
293 294 295 296 297 298 299 300
		if (creationOptions.largeFileOptimizations) {
			this._isTooLargeForTokenization = (
				(bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD)
				|| (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD)
			);
		} else {
			this._isTooLargeForTokenization = false;
		}
301

A
Alex Dima 已提交
302
		this._isTooLargeForSyncing = (bufferTextLength > TextModel.MODEL_SYNC_LIMIT);
303

E
Erich Gamma 已提交
304 305 306
		this._setVersionId(1);
		this._isDisposed = false;
		this._isDisposing = false;
A
Alex Dima 已提交
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

		this._languageIdentifier = languageIdentifier || NULL_LANGUAGE_IDENTIFIER;
		this._tokenizationListener = TokenizationRegistry.onDidChange((e) => {
			if (e.changedLanguages.indexOf(this._languageIdentifier.language) === -1) {
				return;
			}

			this._resetTokenizationState();
			this.emitModelTokensChangedEvent({
				ranges: [{
					fromLineNumber: 1,
					toLineNumber: this.getLineCount()
				}]
			});

			if (this._shouldAutoTokenize()) {
				this._warmUpTokens();
			}
		});
		this._revalidateTokensTimeout = -1;
		this._languageRegistryListener = LanguageConfigurationRegistry.onDidChange((e) => {
			if (e.languageIdentifier.id === this._languageIdentifier.id) {
				this._onDidChangeLanguageConfiguration.fire({});
			}
		});
		this._resetTokenizationState();
E
Erich Gamma 已提交
333

A
Alex Dima 已提交
334
		this._instanceId = singleLetter(MODEL_ID);
335 336 337
		this._lastDecorationId = 0;
		this._decorations = Object.create(null);
		this._decorationsTree = new DecorationsTrees();
A
Alex Dima 已提交
338

339
		this._commandManager = new EditStack(this);
A
Alex Dima 已提交
340 341 342
		this._isUndoing = false;
		this._isRedoing = false;
		this._trimAutoWhitespaceLines = null;
A
Alex Dima 已提交
343
	}
A
Alex Dima 已提交
344

E
Erich Gamma 已提交
345 346
	public dispose(): void {
		this._isDisposing = true;
A
Alex Dima 已提交
347
		this._onWillDispose.fire();
A
Alex Dima 已提交
348
		this._commandManager = null;
349 350
		this._decorations = null;
		this._decorationsTree = null;
A
Alex Dima 已提交
351 352 353 354
		this._tokenizationListener.dispose();
		this._languageRegistryListener.dispose();
		this._clearTimers();
		this._tokens = null;
A
Alex Dima 已提交
355 356 357
		this._isDisposed = true;
		// Null out members, such that any use of a disposed model will throw exceptions sooner rather than later
		this._buffer = null;
E
Erich Gamma 已提交
358 359 360 361
		super.dispose();
		this._isDisposing = false;
	}

A
Alex Dima 已提交
362
	private _assertNotDisposed(): void {
363 364 365 366 367
		if (this._isDisposed) {
			throw new Error('Model is disposed!');
		}
	}

368
	public equalsTextBuffer(other: model.ITextBuffer): boolean {
A
Alex Dima 已提交
369 370 371
		this._assertNotDisposed();
		return this._buffer.equals(other);
	}
A
Alex Dima 已提交
372

A
Alex Dima 已提交
373
	private _emitContentChangedEvent(rawChange: ModelRawContentChangedEvent, change: IModelContentChangedEvent): void {
A
Alex Dima 已提交
374 375 376 377 378 379
		if (this._isDisposing) {
			// Do not confuse listeners by emitting any event after disposing
			return;
		}
		this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));
	}
380

A
Alex Dima 已提交
381 382 383 384 385 386
	public setValue(value: string): void {
		this._assertNotDisposed();
		if (value === null) {
			// There's nothing to do
			return;
		}
387 388 389

		const textBuffer = createTextBuffer(value, this._options.defaultEOL);
		this.setValueFromTextBuffer(textBuffer);
A
Alex Dima 已提交
390 391
	}

392
	private _createContentChanged2(range: Range, rangeOffset: number, rangeLength: number, text: string, isUndoing: boolean, isRedoing: boolean, isFlush: boolean): IModelContentChangedEvent {
A
Alex Dima 已提交
393 394
		return {
			changes: [{
395 396
				range: range,
				rangeOffset: rangeOffset,
A
Alex Dima 已提交
397 398 399 400 401 402 403 404 405
				rangeLength: rangeLength,
				text: text,
			}],
			eol: this._buffer.getEOL(),
			versionId: this.getVersionId(),
			isUndoing: isUndoing,
			isRedoing: isRedoing,
			isFlush: isFlush
		};
A
Alex Dima 已提交
406 407
	}

408
	public setValueFromTextBuffer(textBuffer: model.ITextBuffer): void {
A
Alex Dima 已提交
409
		this._assertNotDisposed();
410
		if (textBuffer === null) {
A
Alex Dima 已提交
411 412
			// There's nothing to do
			return;
A
Alex Dima 已提交
413
		}
A
Alex Dima 已提交
414 415 416 417
		const oldFullModelRange = this.getFullModelRange();
		const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
		const endLineNumber = this.getLineCount();
		const endColumn = this.getLineMaxColumn(endLineNumber);
A
Alex Dima 已提交
418

419
		this._buffer = textBuffer;
A
Alex Dima 已提交
420 421 422 423 424 425 426 427 428 429 430 431
		this._increaseVersionId();

		// Cancel tokenization, clear all tokens and begin tokenizing
		this._resetTokenizationState();

		// Destroy all my decorations
		this._decorations = Object.create(null);
		this._decorationsTree = new DecorationsTrees();

		// Destroy my edit history and settings
		this._commandManager = new EditStack(this);
		this._trimAutoWhitespaceLines = null;
A
Alex Dima 已提交
432 433 434 435 436 437 438 439 440 441

		this._emitContentChangedEvent(
			new ModelRawContentChangedEvent(
				[
					new ModelRawFlush()
				],
				this._versionId,
				false,
				false
			),
442
			this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true)
A
Alex Dima 已提交
443
		);
A
Alex Dima 已提交
444 445
	}

446
	public setEOL(eol: model.EndOfLineSequence): void {
A
Alex Dima 已提交
447
		this._assertNotDisposed();
448
		const newEOL = (eol === model.EndOfLineSequence.CRLF ? '\r\n' : '\n');
A
Alex Dima 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
		if (this._buffer.getEOL() === newEOL) {
			// Nothing to do
			return;
		}

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

		this._onBeforeEOLChange();
		this._buffer.setEOL(newEOL);
		this._increaseVersionId();
		this._onAfterEOLChange();

		this._emitContentChangedEvent(
			new ModelRawContentChangedEvent(
				[
					new ModelRawEOLChanged()
				],
				this._versionId,
				false,
				false
			),
473
			this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false)
A
Alex Dima 已提交
474 475
		);
	}
476

A
Alex Dima 已提交
477
	private _onBeforeEOLChange(): void {
478 479 480 481 482 483
		// Ensure all decorations get their `range` set.
		const versionId = this.getVersionId();
		const allDecorations = this._decorationsTree.search(0, false, false, versionId);
		this._ensureNodesHaveRanges(allDecorations);
	}

A
Alex Dima 已提交
484
	private _onAfterEOLChange(): void {
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
		// Transform back `range` to offsets
		const versionId = this.getVersionId();
		const allDecorations = this._decorationsTree.collectNodesPostOrder();
		for (let i = 0, len = allDecorations.length; i < len; i++) {
			const node = allDecorations[i];

			const delta = node.cachedAbsoluteStart - node.start;

			const startOffset = this._buffer.getOffsetAt(node.range.startLineNumber, node.range.startColumn);
			const endOffset = this._buffer.getOffsetAt(node.range.endLineNumber, node.range.endColumn);

			node.cachedAbsoluteStart = startOffset;
			node.cachedAbsoluteEnd = endOffset;
			node.cachedVersionId = versionId;

			node.start = startOffset - delta;
			node.end = endOffset - delta;

			recomputeMaxEnd(node);
		}
	}

A
Alex Dima 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
	private _resetTokenizationState(): void {
		this._clearTimers();
		let tokenizationSupport = (
			this._isTooLargeForTokenization
				? null
				: TokenizationRegistry.get(this._languageIdentifier.language)
		);
		this._tokens = new ModelLinesTokens(this._languageIdentifier, tokenizationSupport);
		this._beginBackgroundTokenization();
	}

	private _clearTimers(): void {
		if (this._revalidateTokensTimeout !== -1) {
			clearTimeout(this._revalidateTokensTimeout);
			this._revalidateTokensTimeout = -1;
		}
	}

E
Erich Gamma 已提交
525 526 527 528 529 530 531 532 533 534
	public onBeforeAttached(): void {
		this._attachedEditorCount++;
		// Warm up tokens for the editor
		this._warmUpTokens();
	}

	public onBeforeDetached(): void {
		this._attachedEditorCount--;
	}

A
Alex Dima 已提交
535
	private _shouldAutoTokenize(): boolean {
536 537 538
		return this.isAttachedToEditor();
	}

E
Erich Gamma 已提交
539 540 541 542
	public isAttachedToEditor(): boolean {
		return this._attachedEditorCount > 0;
	}

543 544 545 546
	public getAttachedEditorCount(): number {
		return this._attachedEditorCount;
	}

547
	public isTooLargeForSyncing(): boolean {
A
Alex Dima 已提交
548
		return this._isTooLargeForSyncing;
549 550
	}

551 552 553 554
	public isTooLargeForTokenization(): boolean {
		return this._isTooLargeForTokenization;
	}

A
Alex Dima 已提交
555 556 557 558 559 560
	public isDisposed(): boolean {
		return this._isDisposed;
	}

	public isDominatedByLongLines(): boolean {
		this._assertNotDisposed();
P
Peng Lyu 已提交
561 562 563 564
		if (this.isTooLargeForTokenization()) {
			// Cannot word wrap huge files anyways, so it doesn't really matter
			return false;
		}
A
Alex Dima 已提交
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
		let smallLineCharCount = 0;
		let longLineCharCount = 0;

		const lineCount = this._buffer.getLineCount();
		for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
			const lineLength = this._buffer.getLineLength(lineNumber);
			if (lineLength >= LONG_LINE_BOUNDARY) {
				longLineCharCount += lineLength;
			} else {
				smallLineCharCount += lineLength;
			}
		}

		return (longLineCharCount > smallLineCharCount);
	}

581
	public get uri(): URI {
E
Erich Gamma 已提交
582 583
		return this._associatedResource;
	}
A
Alex Dima 已提交
584

A
Alex Dima 已提交
585 586
	//#region Options

587
	public getOptions(): model.TextModelResolvedOptions {
588
		this._assertNotDisposed();
589 590 591
		return this._options;
	}

592
	public updateOptions(_newOpts: model.ITextModelUpdateOptions): void {
593
		this._assertNotDisposed();
594 595 596
		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;
597

598
		let newOpts = new model.TextModelResolvedOptions({
599 600 601 602 603
			tabSize: tabSize,
			insertSpaces: insertSpaces,
			defaultEOL: this._options.defaultEOL,
			trimAutoWhitespace: trimAutoWhitespace
		});
604

605 606
		if (this._options.equals(newOpts)) {
			return;
607
		}
608 609 610 611

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

A
Alex Dima 已提交
612
		this._onDidChangeOptions.fire(e);
613 614
	}

J
Johannes Rieken 已提交
615
	public detectIndentation(defaultInsertSpaces: boolean, defaultTabSize: number): void {
616
		this._assertNotDisposed();
A
Alex Dima 已提交
617
		let guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
618 619 620 621 622 623
		this.updateOptions({
			insertSpaces: guessedIndentation.insertSpaces,
			tabSize: guessedIndentation.tabSize
		});
	}

624
	private static _normalizeIndentationFromWhitespace(str: string, tabSize: number, insertSpaces: boolean): string {
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
		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;
	}

650
	public static normalizeIndentation(str: string, tabSize: number, insertSpaces: boolean): string {
651 652 653 654
		let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
		if (firstNonWhitespaceIndex === -1) {
			firstNonWhitespaceIndex = str.length;
		}
655 656 657 658 659 660
		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);
661 662 663
	}

	public getOneIndent(): string {
664
		this._assertNotDisposed();
665 666 667 668 669 670 671 672 673 674 675 676 677 678
		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';
		}
	}

A
Alex Dima 已提交
679 680 681 682
	//#endregion

	//#region Reading

E
Erich Gamma 已提交
683
	public getVersionId(): number {
684
		this._assertNotDisposed();
E
Erich Gamma 已提交
685 686 687
		return this._versionId;
	}

A
Alex Dima 已提交
688
	public mightContainRTL(): boolean {
A
Alex Dima 已提交
689
		return this._buffer.mightContainRTL();
A
Alex Dima 已提交
690 691
	}

692
	public mightContainNonBasicASCII(): boolean {
A
Alex Dima 已提交
693
		return this._buffer.mightContainNonBasicASCII();
694 695
	}

E
Erich Gamma 已提交
696
	public getAlternativeVersionId(): number {
697
		this._assertNotDisposed();
E
Erich Gamma 已提交
698 699 700
		return this._alternativeVersionId;
	}

A
Alex Dima 已提交
701
	public getOffsetAt(rawPosition: IPosition): number {
702
		this._assertNotDisposed();
703
		let position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, false);
A
Alex Dima 已提交
704
		return this._buffer.getOffsetAt(position.lineNumber, position.column);
705 706
	}

707
	public getPositionAt(rawOffset: number): Position {
708
		this._assertNotDisposed();
709
		let offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset)));
A
Alex Dima 已提交
710
		return this._buffer.getPositionAt(offset);
711 712
	}

A
Alex Dima 已提交
713
	private _increaseVersionId(): void {
E
Erich Gamma 已提交
714 715 716
		this._setVersionId(this._versionId + 1);
	}

717
	private _setVersionId(newVersionId: number): void {
E
Erich Gamma 已提交
718 719 720 721
		this._versionId = newVersionId;
		this._alternativeVersionId = this._versionId;
	}

A
Alex Dima 已提交
722
	private _overwriteAlternativeVersionId(newAlternativeVersionId: number): void {
E
Erich Gamma 已提交
723 724 725
		this._alternativeVersionId = newAlternativeVersionId;
	}

726
	public getValue(eol?: model.EndOfLinePreference, preserveBOM: boolean = false): string {
A
Alex Dima 已提交
727
		this._assertNotDisposed();
A
Alex Dima 已提交
728 729
		const fullModelRange = this.getFullModelRange();
		const fullModelValue = this.getValueInRange(fullModelRange, eol);
E
Erich Gamma 已提交
730

A
Alex Dima 已提交
731 732 733
		if (preserveBOM) {
			return this._buffer.getBOM() + fullModelValue;
		}
E
Erich Gamma 已提交
734

A
Alex Dima 已提交
735
		return fullModelValue;
E
Erich Gamma 已提交
736 737
	}

738 739 740 741
	public createSnapshot(preserveBOM: boolean = false): ITextSnapshot {
		return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
	}

742
	public getValueLength(eol?: model.EndOfLinePreference, preserveBOM: boolean = false): number {
A
Alex Dima 已提交
743 744 745
		this._assertNotDisposed();
		const fullModelRange = this.getFullModelRange();
		const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
E
Erich Gamma 已提交
746

A
Alex Dima 已提交
747 748 749 750 751
		if (preserveBOM) {
			return this._buffer.getBOM().length + fullModelValue;
		}

		return fullModelValue;
E
Erich Gamma 已提交
752 753
	}

754
	public getValueInRange(rawRange: IRange, eol: model.EndOfLinePreference = model.EndOfLinePreference.TextDefined): string {
755
		this._assertNotDisposed();
A
Alex Dima 已提交
756
		return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
757 758
	}

759
	public getValueLengthInRange(rawRange: IRange, eol: model.EndOfLinePreference = model.EndOfLinePreference.TextDefined): number {
760
		this._assertNotDisposed();
A
Alex Dima 已提交
761
		return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
762 763
	}

A
Alex Dima 已提交
764
	public getLineCount(): number {
765
		this._assertNotDisposed();
A
Alex Dima 已提交
766
		return this._buffer.getLineCount();
E
Erich Gamma 已提交
767 768
	}

J
Johannes Rieken 已提交
769
	public getLineContent(lineNumber: number): string {
770
		this._assertNotDisposed();
E
Erich Gamma 已提交
771
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
772
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
773 774
		}

A
Alex Dima 已提交
775
		return this._buffer.getLineContent(lineNumber);
E
Erich Gamma 已提交
776 777
	}

A
Alex Dima 已提交
778 779 780 781 782 783 784 785 786
	public getLineLength(lineNumber: number): number {
		this._assertNotDisposed();
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value for lineNumber');
		}

		return this._buffer.getLineLength(lineNumber);
	}

E
Erich Gamma 已提交
787
	public getLinesContent(): string[] {
788
		this._assertNotDisposed();
A
Alex Dima 已提交
789
		return this._buffer.getLinesContent();
E
Erich Gamma 已提交
790 791 792
	}

	public getEOL(): string {
793
		this._assertNotDisposed();
A
Alex Dima 已提交
794
		return this._buffer.getEOL();
E
Erich Gamma 已提交
795 796
	}

J
Johannes Rieken 已提交
797
	public getLineMinColumn(lineNumber: number): number {
798
		this._assertNotDisposed();
E
Erich Gamma 已提交
799 800 801
		return 1;
	}

J
Johannes Rieken 已提交
802
	public getLineMaxColumn(lineNumber: number): number {
803
		this._assertNotDisposed();
E
Erich Gamma 已提交
804
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
805
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
806
		}
A
Alex Dima 已提交
807
		return this._buffer.getLineLength(lineNumber) + 1;
E
Erich Gamma 已提交
808 809 810
	}

	public getLineFirstNonWhitespaceColumn(lineNumber: number): number {
811
		this._assertNotDisposed();
E
Erich Gamma 已提交
812
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
813
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
814
		}
A
Alex Dima 已提交
815
		return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
E
Erich Gamma 已提交
816 817 818
	}

	public getLineLastNonWhitespaceColumn(lineNumber: number): number {
819
		this._assertNotDisposed();
E
Erich Gamma 已提交
820
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
821
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
822
		}
A
Alex Dima 已提交
823
		return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
E
Erich Gamma 已提交
824 825
	}

826
	/**
A
Alex Dima 已提交
827 828 829 830
	 * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
	 * Will try to not allocate if possible.
	 */
	private _validateRangeRelaxedNoAllocations(range: IRange): Range {
A
Alex Dima 已提交
831
		const linesCount = this._buffer.getLineCount();
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888

		const initialStartLineNumber = range.startLineNumber;
		const initialStartColumn = range.startColumn;
		let startLineNumber: number;
		let startColumn: number;

		if (initialStartLineNumber < 1) {
			startLineNumber = 1;
			startColumn = 1;
		} else if (initialStartLineNumber > linesCount) {
			startLineNumber = linesCount;
			startColumn = this.getLineMaxColumn(startLineNumber);
		} else {
			startLineNumber = initialStartLineNumber | 0;
			if (initialStartColumn <= 1) {
				startColumn = 1;
			} else {
				const maxColumn = this.getLineMaxColumn(startLineNumber);
				if (initialStartColumn >= maxColumn) {
					startColumn = maxColumn;
				} else {
					startColumn = initialStartColumn | 0;
				}
			}
		}

		const initialEndLineNumber = range.endLineNumber;
		const initialEndColumn = range.endColumn;
		let endLineNumber: number;
		let endColumn: number;

		if (initialEndLineNumber < 1) {
			endLineNumber = 1;
			endColumn = 1;
		} else if (initialEndLineNumber > linesCount) {
			endLineNumber = linesCount;
			endColumn = this.getLineMaxColumn(endLineNumber);
		} else {
			endLineNumber = initialEndLineNumber | 0;
			if (initialEndColumn <= 1) {
				endColumn = 1;
			} else {
				const maxColumn = this.getLineMaxColumn(endLineNumber);
				if (initialEndColumn >= maxColumn) {
					endColumn = maxColumn;
				} else {
					endColumn = initialEndColumn | 0;
				}
			}
		}

		if (
			initialStartLineNumber === startLineNumber
			&& initialStartColumn === startColumn
			&& initialEndLineNumber === endLineNumber
			&& initialEndColumn === endColumn
			&& range instanceof Range
889
			&& !(range instanceof Selection)
890 891 892 893 894 895 896
		) {
			return range;
		}

		return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
	}

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931
	/**
	 * @param strict Do NOT allow a position inside a high-low surrogate pair
	 */
	private _isValidPosition(lineNumber: number, column: number, strict: boolean): boolean {

		if (lineNumber < 1) {
			return false;
		}

		const lineCount = this._buffer.getLineCount();
		if (lineNumber > lineCount) {
			return false;
		}

		if (column < 1) {
			return false;
		}

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

		if (strict) {
			if (column > 1) {
				const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
				if (strings.isHighSurrogate(charCodeBefore)) {
					return false;
				}
			}
		}

		return true;
	}

932 933 934
	/**
	 * @param strict Do NOT allow a position inside a high-low surrogate pair
	 */
J
Johannes Rieken 已提交
935
	private _validatePosition(_lineNumber: number, _column: number, strict: boolean): Position {
936 937
		const lineNumber = Math.floor(typeof _lineNumber === 'number' ? _lineNumber : 1);
		const column = Math.floor(typeof _column === 'number' ? _column : 1);
A
Alex Dima 已提交
938
		const lineCount = this._buffer.getLineCount();
E
Erich Gamma 已提交
939 940

		if (lineNumber < 1) {
941
			return new Position(1, 1);
E
Erich Gamma 已提交
942
		}
943

A
Alex Dima 已提交
944 945
		if (lineNumber > lineCount) {
			return new Position(lineCount, this.getLineMaxColumn(lineCount));
E
Erich Gamma 已提交
946
		}
947 948 949 950 951 952 953 954 955 956 957 958 959 960

		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
A
Alex Dima 已提交
961
			const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
962 963
			if (strings.isHighSurrogate(charCodeBefore)) {
				return new Position(lineNumber, column - 1);
A
aioute Gao 已提交
964
			}
E
Erich Gamma 已提交
965 966 967 968 969
		}

		return new Position(lineNumber, column);
	}

A
Alex Dima 已提交
970
	public validatePosition(position: IPosition): Position {
971
		this._assertNotDisposed();
972 973 974 975 976 977 978 979

		// Avoid object allocation and cover most likely case
		if (position instanceof Position) {
			if (this._isValidPosition(position.lineNumber, position.column, true)) {
				return position;
			}
		}

980 981 982
		return this._validatePosition(position.lineNumber, position.column, true);
	}

983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	/**
	 * @param strict Do NOT allow a range to have its boundaries inside a high-low surrogate pair
	 */
	private _isValidRange(range: Range, strict: boolean): boolean {
		const startLineNumber = range.startLineNumber;
		const startColumn = range.startColumn;
		const endLineNumber = range.endLineNumber;
		const endColumn = range.endColumn;

		if (!this._isValidPosition(startLineNumber, startColumn, false)) {
			return false;
		}
		if (!this._isValidPosition(endLineNumber, endColumn, false)) {
			return false;
		}

		if (strict) {
			const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
			const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);

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

			if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
				return true;
			}

			return false;
		}

		return true;
	}

A
Alex Dima 已提交
1016
	public validateRange(_range: IRange): Range {
1017
		this._assertNotDisposed();
1018 1019 1020 1021 1022 1023 1024 1025

		// Avoid object allocation and cover most likely case
		if ((_range instanceof Range) && !(_range instanceof Selection)) {
			if (this._isValidRange(_range, true)) {
				return _range;
			}
		}

1026 1027 1028 1029 1030 1031 1032 1033
		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;

A
Alex Dima 已提交
1034 1035
		const charCodeBeforeStart = (startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0);
		const charCodeBeforeEnd = (endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0);
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

		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 已提交
1061 1062
	}

A
Alex Dima 已提交
1063
	public modifyPosition(rawPosition: IPosition, offset: number): Position {
1064
		this._assertNotDisposed();
1065 1066
		let candidate = this.getOffsetAt(rawPosition) + offset;
		return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
E
Erich Gamma 已提交
1067 1068
	}

1069
	public getFullModelRange(): Range {
1070
		this._assertNotDisposed();
A
Alex Dima 已提交
1071
		const lineCount = this.getLineCount();
E
Erich Gamma 已提交
1072 1073 1074
		return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
	}

P
Peng Lyu 已提交
1075 1076 1077 1078
	private findMatchesLineByLine(searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): model.FindMatch[] {
		return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
	}

1079
	public findMatches(searchString: string, rawSearchScope: any, isRegex: boolean, matchCase: boolean, wordSeparators: string, captureMatches: boolean, limitResultCount: number = LIMIT_FIND_COUNT): model.FindMatch[] {
1080
		this._assertNotDisposed();
E
Erich Gamma 已提交
1081

J
Johannes Rieken 已提交
1082
		let searchRange: Range;
E
Erich Gamma 已提交
1083
		if (Range.isIRange(rawSearchScope)) {
A
Alex Dima 已提交
1084
			searchRange = this.validateRange(rawSearchScope);
E
Erich Gamma 已提交
1085 1086 1087 1088
		} else {
			searchRange = this.getFullModelRange();
		}

A
Alex Dima 已提交
1089
		if (!isRegex && searchString.indexOf('\n') < 0) {
P
Peng Lyu 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
			// not regex, not multi line
			const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
			const searchData = searchParams.parseSearchRequest();

			if (!searchData) {
				return [];
			}

			return this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
		}

1101
		return TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount);
E
Erich Gamma 已提交
1102 1103
	}

1104
	public findNextMatch(searchString: string, rawSearchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string, captureMatches: boolean): model.FindMatch {
1105
		this._assertNotDisposed();
1106
		const searchStart = this.validatePosition(rawSearchStart);
1107

A
Alex Dima 已提交
1108
		if (!isRegex && searchString.indexOf('\n') < 0) {
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
			const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
			const searchData = searchParams.parseSearchRequest();
			const lineCount = this.getLineCount();
			let searchRange = new Range(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
			let ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
			TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
			if (ret.length > 0) {
				return ret[0];
			}

			searchRange = new Range(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
			ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);

			if (ret.length > 0) {
				return ret[0];
			}

			return null;
		}

1129
		return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
E
Erich Gamma 已提交
1130 1131
	}

1132
	public findPreviousMatch(searchString: string, rawSearchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string, captureMatches: boolean): model.FindMatch {
1133
		this._assertNotDisposed();
1134
		const searchStart = this.validatePosition(rawSearchStart);
1135
		return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
E
Erich Gamma 已提交
1136
	}
A
Alex Dima 已提交
1137 1138 1139

	//#endregion

A
Alex Dima 已提交
1140 1141 1142 1143 1144 1145
	//#region Editing

	public pushStackElement(): void {
		this._commandManager.pushStackElement();
	}

1146
	public pushEditOperations(beforeCursorState: Selection[], editOperations: model.IIdentifiedSingleEditOperation[], cursorStateComputer: model.ICursorStateComputer): Selection[] {
A
Alex Dima 已提交
1147 1148
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
1149
			this._eventEmitter.beginDeferredEmit();
A
Alex Dima 已提交
1150 1151 1152
			return this._pushEditOperations(beforeCursorState, editOperations, cursorStateComputer);
		} finally {
			this._eventEmitter.endDeferredEmit();
1153
			this._onDidChangeDecorations.endDeferredEmit();
A
Alex Dima 已提交
1154 1155 1156
		}
	}

1157
	private _pushEditOperations(beforeCursorState: Selection[], editOperations: model.IIdentifiedSingleEditOperation[], cursorStateComputer: model.ICursorStateComputer): Selection[] {
A
Alex Dima 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
		if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
			// Go through each saved line number and insert a trim whitespace edit
			// if it is safe to do so (no conflicts with other edits).

			let incomingEdits = editOperations.map((op) => {
				return {
					range: this.validateRange(op.range),
					text: op.text
				};
			});

			// Sometimes, auto-formatters change ranges automatically which can cause undesired auto whitespace trimming near the cursor
			// We'll use the following heuristic: if the edits occur near the cursor, then it's ok to trim auto whitespace
			let editsAreNearCursors = true;
			for (let i = 0, len = beforeCursorState.length; i < len; i++) {
				let sel = beforeCursorState[i];
				let foundEditNearSel = false;
				for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
					let editRange = incomingEdits[j].range;
					let selIsAbove = editRange.startLineNumber > sel.endLineNumber;
					let selIsBelow = sel.startLineNumber > editRange.endLineNumber;
					if (!selIsAbove && !selIsBelow) {
						foundEditNearSel = true;
						break;
					}
				}
				if (!foundEditNearSel) {
					editsAreNearCursors = false;
					break;
				}
			}

			if (editsAreNearCursors) {
				for (let i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) {
					let trimLineNumber = this._trimAutoWhitespaceLines[i];
					let maxLineColumn = this.getLineMaxColumn(trimLineNumber);

					let allowTrimLine = true;
					for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
						let editRange = incomingEdits[j].range;
						let editText = incomingEdits[j].text;

						if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
							// `trimLine` is completely outside this edit
							continue;
						}

						// At this point:
						//   editRange.startLineNumber <= trimLine <= editRange.endLineNumber

						if (
							trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn
							&& editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === '\n'
						) {
							// This edit inserts a new line (and maybe other text) after `trimLine`
							continue;
						}

						// Looks like we can't trim this line as it would interfere with an incoming edit
						allowTrimLine = false;
						break;
					}

					if (allowTrimLine) {
						editOperations.push({
							range: new Range(trimLineNumber, 1, trimLineNumber, maxLineColumn),
1224
							text: null
A
Alex Dima 已提交
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
						});
					}

				}
			}

			this._trimAutoWhitespaceLines = null;
		}
		return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);
	}

1236
	public applyEdits(rawOperations: model.IIdentifiedSingleEditOperation[]): model.IIdentifiedSingleEditOperation[] {
A
Alex Dima 已提交
1237 1238
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
1239
			this._eventEmitter.beginDeferredEmit();
A
Alex Dima 已提交
1240 1241 1242
			return this._applyEdits(rawOperations);
		} finally {
			this._eventEmitter.endDeferredEmit();
1243
			this._onDidChangeDecorations.endDeferredEmit();
A
Alex Dima 已提交
1244 1245 1246
		}
	}

1247
	private static _eolCount(text: string): [number, number] {
1248
		let eolCount = 0;
1249
		let firstLineLength = 0;
1250 1251 1252 1253
		for (let i = 0, len = text.length; i < len; i++) {
			const chr = text.charCodeAt(i);

			if (chr === CharCode.CarriageReturn) {
1254 1255 1256
				if (eolCount === 0) {
					firstLineLength = i;
				}
1257 1258 1259 1260 1261 1262 1263 1264
				eolCount++;
				if (i + 1 < len && text.charCodeAt(i + 1) === CharCode.LineFeed) {
					// \r\n... case
					i++; // skip \n
				} else {
					// \r... case
				}
			} else if (chr === CharCode.LineFeed) {
1265 1266 1267
				if (eolCount === 0) {
					firstLineLength = i;
				}
1268 1269 1270
				eolCount++;
			}
		}
1271 1272 1273 1274
		if (eolCount === 0) {
			firstLineLength = text.length;
		}
		return [eolCount, firstLineLength];
1275 1276
	}

1277
	private _applyEdits(rawOperations: model.IIdentifiedSingleEditOperation[]): model.IIdentifiedSingleEditOperation[] {
A
Alex Dima 已提交
1278 1279 1280
		for (let i = 0, len = rawOperations.length; i < len; i++) {
			rawOperations[i].range = this.validateRange(rawOperations[i].range);
		}
1281 1282

		const oldLineCount = this._buffer.getLineCount();
A
Alex Dima 已提交
1283
		const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace);
1284 1285
		const newLineCount = this._buffer.getLineCount();

A
Alex Dima 已提交
1286 1287 1288
		const contentChanges = result.changes;
		this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;

1289 1290 1291 1292
		if (contentChanges.length !== 0) {
			let rawContentChanges: ModelRawChange[] = [];

			let lineCount = oldLineCount;
A
Alex Dima 已提交
1293
			for (let i = 0, len = contentChanges.length; i < len; i++) {
1294
				const change = contentChanges[i];
1295 1296
				const [eolCount, firstLineLength] = TextModel._eolCount(change.text);
				this._tokens.applyEdits(change.range, eolCount, firstLineLength);
1297
				this._onDidChangeDecorations.fire();
1298 1299 1300 1301 1302 1303
				this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);

				const startLineNumber = change.range.startLineNumber;
				const endLineNumber = change.range.endLineNumber;

				const deletingLinesCnt = endLineNumber - startLineNumber;
1304
				const insertingLinesCnt = eolCount;
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
				const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);

				const changeLineCountDelta = (insertingLinesCnt - deletingLinesCnt);

				for (let j = editingLinesCnt; j >= 0; j--) {
					const editLineNumber = startLineNumber + j;
					const currentEditLineNumber = newLineCount - lineCount - changeLineCountDelta + editLineNumber;
					rawContentChanges.push(new ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber)));
				}

				if (editingLinesCnt < deletingLinesCnt) {
					// Must delete some lines
					const spliceStartLineNumber = startLineNumber + editingLinesCnt;
					rawContentChanges.push(new ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
				}

				if (editingLinesCnt < insertingLinesCnt) {
					// Must insert some lines
					const spliceLineNumber = startLineNumber + editingLinesCnt;
					const cnt = insertingLinesCnt - editingLinesCnt;
					const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
					let newLines: string[] = [];
					for (let i = 0; i < cnt; i++) {
						let lineNumber = fromLineNumber + i;
						newLines[lineNumber - fromLineNumber] = this.getLineContent(lineNumber);
					}
					rawContentChanges.push(new ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines));
				}

				lineCount += changeLineCountDelta;
A
Alex Dima 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
			}

			this._increaseVersionId();

			this._emitContentChangedEvent(
				new ModelRawContentChangedEvent(
					rawContentChanges,
					this.getVersionId(),
					this._isUndoing,
					this._isRedoing
				),
				{
					changes: contentChanges,
					eol: this._buffer.getEOL(),
					versionId: this.getVersionId(),
					isUndoing: this._isUndoing,
					isRedoing: this._isRedoing,
					isFlush: false
				}
			);
		}

		if (this._tokens.hasLinesToTokenize(this._buffer)) {
			this._beginBackgroundTokenization();
		}

		return result.reverseEdits;
	}

	private _undo(): Selection[] {
		this._isUndoing = true;
		let r = this._commandManager.undo();
		this._isUndoing = false;

		if (!r) {
			return null;
		}

		this._overwriteAlternativeVersionId(r.recordedVersionId);

		return r.selections;
	}

	public undo(): Selection[] {
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
1381
			this._eventEmitter.beginDeferredEmit();
A
Alex Dima 已提交
1382 1383 1384
			return this._undo();
		} finally {
			this._eventEmitter.endDeferredEmit();
1385
			this._onDidChangeDecorations.endDeferredEmit();
A
Alex Dima 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
		}
	}

	private _redo(): Selection[] {
		this._isRedoing = true;
		let r = this._commandManager.redo();
		this._isRedoing = false;

		if (!r) {
			return null;
		}

		this._overwriteAlternativeVersionId(r.recordedVersionId);

		return r.selections;
	}

	public redo(): Selection[] {
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
1406
			this._eventEmitter.beginDeferredEmit();
A
Alex Dima 已提交
1407 1408 1409
			return this._redo();
		} finally {
			this._eventEmitter.endDeferredEmit();
1410
			this._onDidChangeDecorations.endDeferredEmit();
A
Alex Dima 已提交
1411 1412 1413 1414
		}
	}

	//#endregion
1415 1416 1417

	//#region Decorations

1418
	public changeDecorations<T>(callback: (changeAccessor: model.IModelDecorationsChangeAccessor) => T, ownerId: number = 0): T {
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
		this._assertNotDisposed();

		try {
			this._onDidChangeDecorations.beginDeferredEmit();
			return this._changeDecorations(ownerId, callback);
		} finally {
			this._onDidChangeDecorations.endDeferredEmit();
		}
	}

1429 1430 1431
	private _changeDecorations<T>(ownerId: number, callback: (changeAccessor: model.IModelDecorationsChangeAccessor) => T): T {
		let changeAccessor: model.IModelDecorationsChangeAccessor = {
			addDecoration: (range: IRange, options: model.IModelDecorationOptions): string => {
1432 1433 1434 1435 1436 1437 1438
				this._onDidChangeDecorations.fire();
				return this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];
			},
			changeDecoration: (id: string, newRange: IRange): void => {
				this._onDidChangeDecorations.fire();
				this._changeDecorationImpl(id, newRange);
			},
1439
			changeDecorationOptions: (id: string, options: model.IModelDecorationOptions) => {
1440 1441 1442 1443 1444 1445 1446
				this._onDidChangeDecorations.fire();
				this._changeDecorationOptionsImpl(id, _normalizeOptions(options));
			},
			removeDecoration: (id: string): void => {
				this._onDidChangeDecorations.fire();
				this._deltaDecorationsImpl(ownerId, [id], []);
			},
1447
			deltaDecorations: (oldDecorations: string[], newDecorations: model.IModelDeltaDecoration[]): string[] => {
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
				if (oldDecorations.length === 0 && newDecorations.length === 0) {
					// nothing to do
					return [];
				}
				this._onDidChangeDecorations.fire();
				return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
			}
		};
		let result: T = null;
		try {
			result = callback(changeAccessor);
		} catch (e) {
			onUnexpectedError(e);
		}
		// Invalidate change accessor
		changeAccessor.addDecoration = null;
		changeAccessor.changeDecoration = null;
		changeAccessor.removeDecoration = null;
		changeAccessor.deltaDecorations = null;
		return result;
	}

1470
	public deltaDecorations(oldDecorations: string[], newDecorations: model.IModelDeltaDecoration[], ownerId: number = 0): string[] {
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
		this._assertNotDisposed();
		if (!oldDecorations) {
			oldDecorations = [];
		}
		if (oldDecorations.length === 0 && newDecorations.length === 0) {
			// nothing to do
			return [];
		}

		try {
			this._onDidChangeDecorations.beginDeferredEmit();
			this._onDidChangeDecorations.fire();
			return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
		} finally {
			this._onDidChangeDecorations.endDeferredEmit();
		}
	}

	_getTrackedRange(id: string): Range {
		return this.getDecorationRange(id);
	}

1493
	_setTrackedRange(id: string, newRange: Range, newStickiness: model.TrackedRangeStickiness): string {
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
		const node = (id ? this._decorations[id] : null);

		if (!node) {
			if (!newRange) {
				// node doesn't exist, the request is to delete => nothing to do
				return null;
			}
			// node doesn't exist, the request is to set => add the tracked range
			return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }])[0];
		}

		if (!newRange) {
			// node exists, the request is to delete => delete node
			this._decorationsTree.delete(node);
			delete this._decorations[node.id];
			return null;
		}

		// node exists, the request is to set => change the tracked range and its options
		const range = this._validateRangeRelaxedNoAllocations(newRange);
		const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
		const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);
		this._decorationsTree.delete(node);
		node.reset(this.getVersionId(), startOffset, endOffset, range);
		node.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
		this._decorationsTree.insert(node);
		return node.id;
	}

	public removeAllDecorationsWithOwnerId(ownerId: number): void {
		if (this._isDisposed) {
			return;
		}
		const nodes = this._decorationsTree.collectNodesFromOwner(ownerId);
		for (let i = 0, len = nodes.length; i < len; i++) {
			const node = nodes[i];

			this._decorationsTree.delete(node);
			delete this._decorations[node.id];
		}
	}

1536
	public getDecorationOptions(decorationId: string): model.IModelDecorationOptions {
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
		const node = this._decorations[decorationId];
		if (!node) {
			return null;
		}
		return node.options;
	}

	public getDecorationRange(decorationId: string): Range {
		const node = this._decorations[decorationId];
		if (!node) {
			return null;
		}
		const versionId = this.getVersionId();
		if (node.cachedVersionId !== versionId) {
			this._decorationsTree.resolveNode(node, versionId);
		}
		if (node.range === null) {
			node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
		}
		return node.range;
	}

1559
	public getLineDecorations(lineNumber: number, ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1560 1561 1562 1563 1564 1565 1566
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			return [];
		}

		return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);
	}

1567
	public getLinesDecorations(_startLineNumber: number, _endLineNumber: number, ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1568 1569 1570 1571 1572 1573 1574
		let lineCount = this.getLineCount();
		let startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
		let endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
		let endColumn = this.getLineMaxColumn(endLineNumber);
		return this._getDecorationsInRange(new Range(startLineNumber, 1, endLineNumber, endColumn), ownerId, filterOutValidation);
	}

1575
	public getDecorationsInRange(range: IRange, ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1576 1577 1578 1579
		let validatedRange = this.validateRange(range);
		return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
	}

1580
	public getOverviewRulerDecorations(ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1581 1582 1583 1584 1585
		const versionId = this.getVersionId();
		const result = this._decorationsTree.search(ownerId, filterOutValidation, true, versionId);
		return this._ensureNodesHaveRanges(result);
	}

1586
	public getAllDecorations(ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
		const versionId = this.getVersionId();
		const result = this._decorationsTree.search(ownerId, filterOutValidation, false, versionId);
		return this._ensureNodesHaveRanges(result);
	}

	private _getDecorationsInRange(filterRange: Range, filterOwnerId: number, filterOutValidation: boolean): IntervalNode[] {
		const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
		const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);

		const versionId = this.getVersionId();
		const result = this._decorationsTree.intervalSearch(startOffset, endOffset, filterOwnerId, filterOutValidation, versionId);

		return this._ensureNodesHaveRanges(result);
	}

	private _ensureNodesHaveRanges(nodes: IntervalNode[]): IntervalNode[] {
		for (let i = 0, len = nodes.length; i < len; i++) {
			const node = nodes[i];
			if (node.range === null) {
				node.range = this._getRangeAt(node.cachedAbsoluteStart, node.cachedAbsoluteEnd);
			}
		}
		return nodes;
	}

	private _getRangeAt(start: number, end: number): Range {
		return this._buffer.getRangeAt(start, end - start);
	}

	private _changeDecorationImpl(decorationId: string, _range: IRange): void {
		const node = this._decorations[decorationId];
		if (!node) {
			return;
		}
		const range = this._validateRangeRelaxedNoAllocations(_range);
		const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
		const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);

		this._decorationsTree.delete(node);
		node.reset(this.getVersionId(), startOffset, endOffset, range);
		this._decorationsTree.insert(node);
	}

	private _changeDecorationOptionsImpl(decorationId: string, options: ModelDecorationOptions): void {
		const node = this._decorations[decorationId];
		if (!node) {
			return;
		}

		const nodeWasInOverviewRuler = (node.options.overviewRuler.color ? true : false);
		const nodeIsInOverviewRuler = (options.overviewRuler.color ? true : false);

		if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
			// Delete + Insert due to an overview ruler status change
			this._decorationsTree.delete(node);
			node.setOptions(options);
			this._decorationsTree.insert(node);
		} else {
			node.setOptions(options);
		}
	}

1649
	private _deltaDecorationsImpl(ownerId: number, oldDecorationsIds: string[], newDecorations: model.IModelDeltaDecoration[]): string[] {
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
		const versionId = this.getVersionId();

		const oldDecorationsLen = oldDecorationsIds.length;
		let oldDecorationIndex = 0;

		const newDecorationsLen = newDecorations.length;
		let newDecorationIndex = 0;

		let result = new Array<string>(newDecorationsLen);
		while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {

			let node: IntervalNode = null;

			if (oldDecorationIndex < oldDecorationsLen) {
				// (1) get ourselves an old node
				do {
					node = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
				} while (!node && oldDecorationIndex < oldDecorationsLen);

				// (2) remove the node from the tree (if it exists)
				if (node) {
					this._decorationsTree.delete(node);
				}
			}

			if (newDecorationIndex < newDecorationsLen) {
				// (3) create a new node if necessary
				if (!node) {
					const internalDecorationId = (++this._lastDecorationId);
					const decorationId = `${this._instanceId};${internalDecorationId}`;
					node = new IntervalNode(decorationId, 0, 0);
					this._decorations[decorationId] = node;
				}

				// (4) initialize node
				const newDecoration = newDecorations[newDecorationIndex];
				const range = this._validateRangeRelaxedNoAllocations(newDecoration.range);
				const options = _normalizeOptions(newDecoration.options);
				const startOffset = this._buffer.getOffsetAt(range.startLineNumber, range.startColumn);
				const endOffset = this._buffer.getOffsetAt(range.endLineNumber, range.endColumn);

				node.ownerId = ownerId;
				node.reset(versionId, startOffset, endOffset, range);
				node.setOptions(options);

				this._decorationsTree.insert(node);

				result[newDecorationIndex] = node.id;

				newDecorationIndex++;
			} else {
				if (node) {
					delete this._decorations[node.id];
				}
			}
		}

		return result;
	}

	//#endregion
A
Alex Dima 已提交
1711 1712 1713

	//#region Tokenization

P
Peng Lyu 已提交
1714 1715 1716 1717 1718
	public tokenizeViewport(startLineNumber: number, endLineNumber: number): void {
		if (!this._tokens.tokenizationSupport) {
			return;
		}

1719 1720 1721 1722
		// we tokenize `this._tokens.inValidLineStartIndex` lines in around 20ms so it's a good baseline.
		const contextBefore = Math.floor(this._tokens.inValidLineStartIndex * 0.3);
		startLineNumber = Math.max(1, startLineNumber - contextBefore);

1723 1724 1725 1726
		if (startLineNumber <= this._tokens.inValidLineStartIndex) {
			this.forceTokenization(endLineNumber);
			return;
		}
1727

P
Peng Lyu 已提交
1728
		const eventBuilder = new ModelTokensChangedEventBuilder();
1729
		let nonWhitespaceColumn = this.getLineFirstNonWhitespaceColumn(startLineNumber);
P
Peng Lyu 已提交
1730 1731
		let fakeLines = [];
		let i = startLineNumber - 1;
1732
		let initialState = null;
P
Peng Lyu 已提交
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
		if (nonWhitespaceColumn > 0) {
			while (nonWhitespaceColumn > 0 && i >= 1) {
				let newNonWhitespaceIndex = this.getLineFirstNonWhitespaceColumn(i);

				if (newNonWhitespaceIndex === 0) {
					i--;
					continue;
				}

				if (newNonWhitespaceIndex < nonWhitespaceColumn) {
1743 1744 1745 1746
					initialState = this._tokens._getState(i - 1);
					if (initialState) {
						break;
					}
P
Peng Lyu 已提交
1747 1748 1749 1750 1751 1752 1753 1754
					fakeLines.push(this.getLineContent(i));
					nonWhitespaceColumn = newNonWhitespaceIndex;
				}

				i--;
			}
		}

1755 1756 1757 1758
		if (!initialState) {
			initialState = this._tokens.tokenizationSupport.getInitialState();
		}

P
Peng Lyu 已提交
1759 1760
		let state = initialState.clone();
		for (let i = fakeLines.length - 1; i >= 0; i--) {
1761
			let r = this._tokens._tokenizeText(this._buffer, fakeLines[i], state);
P
Peng Lyu 已提交
1762 1763 1764 1765 1766 1767 1768
			if (r) {
				state = r.endState.clone();
			} else {
				state = initialState.clone();
			}
		}

1769 1770
		const contextAfter = Math.floor(this._tokens.inValidLineStartIndex * 0.4);
		endLineNumber = Math.min(this.getLineCount(), endLineNumber + contextAfter);
P
Peng Lyu 已提交
1771 1772
		for (let i = startLineNumber; i <= endLineNumber; i++) {
			let text = this.getLineContent(i);
1773
			let r = this._tokens._tokenizeText(this._buffer, text, state);
P
Peng Lyu 已提交
1774 1775
			if (r) {
				this._tokens._setTokens(this._tokens.languageIdentifier.id, i - 1, text.length, r.tokens);
1776 1777 1778 1779 1780 1781 1782 1783
				/*
				 * we think it's valid and give it a state but we don't update `_invalidLineStartIndex` then the top-to-bottom tokenization
				 * goes through the viewport, it can skip them if they already have correct tokens and state, and the lines after the viewport
				 * can still be tokenized.
				 */
				this._tokens._setIsInvalid(i - 1, false);
				this._tokens._setState(i - 1, state);
				state = r.endState.clone();
P
Peng Lyu 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
				eventBuilder.registerChangedTokens(i);
			} else {
				state = initialState.clone();
			}
		}

		const e = eventBuilder.build();
		if (e) {
			this._onDidChangeTokens.fire(e);
		}
	}

A
Alex Dima 已提交
1796 1797
	public forceTokenization(lineNumber: number): void {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
1798
			throw new Error('Illegal value for lineNumber');
A
Alex Dima 已提交
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
		}

		const eventBuilder = new ModelTokensChangedEventBuilder();

		this._tokens._updateTokensUntilLine(this._buffer, eventBuilder, lineNumber);

		const e = eventBuilder.build();
		if (e) {
			this._onDidChangeTokens.fire(e);
		}
	}

	public isCheapToTokenize(lineNumber: number): boolean {
		return this._tokens.isCheapToTokenize(lineNumber);
	}

	public tokenizeIfCheap(lineNumber: number): void {
		if (this.isCheapToTokenize(lineNumber)) {
			this.forceTokenization(lineNumber);
		}
	}

	public getLineTokens(lineNumber: number): LineTokens {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
1823
			throw new Error('Illegal value for lineNumber');
A
Alex Dima 已提交
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
		}

		return this._getLineTokens(lineNumber);
	}

	private _getLineTokens(lineNumber: number): LineTokens {
		const lineText = this._buffer.getLineContent(lineNumber);
		return this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText);
	}

	public getLanguageIdentifier(): LanguageIdentifier {
		return this._languageIdentifier;
	}

	public getModeId(): string {
		return this._languageIdentifier.language;
	}

	public setMode(languageIdentifier: LanguageIdentifier): void {
		if (this._languageIdentifier.id === languageIdentifier.id) {
			// There's nothing to do
			return;
		}

		let e: IModelLanguageChangedEvent = {
			oldLanguage: this._languageIdentifier.language,
			newLanguage: languageIdentifier.language
		};

		this._languageIdentifier = languageIdentifier;

		// Cancel tokenization, clear all tokens and begin tokenizing
		this._resetTokenizationState();

		this.emitModelTokensChangedEvent({
			ranges: [{
				fromLineNumber: 1,
				toLineNumber: this.getLineCount()
			}]
		});
		this._onDidChangeLanguage.fire(e);
		this._onDidChangeLanguageConfiguration.fire({});
	}

	public getLanguageIdAtPosition(_lineNumber: number, _column: number): LanguageId {
		if (!this._tokens.tokenizationSupport) {
			return this._languageIdentifier.id;
		}
		let { lineNumber, column } = this.validatePosition({ lineNumber: _lineNumber, column: _column });

		let lineTokens = this._getLineTokens(lineNumber);
		return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(column - 1));
	}

A
Alex Dima 已提交
1878
	private _beginBackgroundTokenization(): void {
A
Alex Dima 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
		if (this._shouldAutoTokenize() && this._revalidateTokensTimeout === -1) {
			this._revalidateTokensTimeout = setTimeout(() => {
				this._revalidateTokensTimeout = -1;
				this._revalidateTokensNow();
			}, 0);
		}
	}

	_warmUpTokens(): void {
		// Warm up first 100 lines (if it takes less than 50ms)
A
Alex Dima 已提交
1889
		const maxLineNumber = Math.min(100, this.getLineCount());
A
Alex Dima 已提交
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
		this._revalidateTokensNow(maxLineNumber);

		if (this._tokens.hasLinesToTokenize(this._buffer)) {
			this._beginBackgroundTokenization();
		}
	}

	private _revalidateTokensNow(toLineNumber: number = this._buffer.getLineCount()): void {
		const MAX_ALLOWED_TIME = 20;
		const eventBuilder = new ModelTokensChangedEventBuilder();
		const sw = StopWatch.create(false);

		while (this._tokens.hasLinesToTokenize(this._buffer)) {
			if (sw.elapsed() > MAX_ALLOWED_TIME) {
				// Stop if MAX_ALLOWED_TIME is reached
				break;
			}

			const tokenizedLineNumber = this._tokens._tokenizeOneLine(this._buffer, eventBuilder);

			if (tokenizedLineNumber >= toLineNumber) {
				break;
			}
		}

		if (this._tokens.hasLinesToTokenize(this._buffer)) {
			this._beginBackgroundTokenization();
		}

		const e = eventBuilder.build();
		if (e) {
			this._onDidChangeTokens.fire(e);
		}
	}

	private emitModelTokensChangedEvent(e: IModelTokensChangedEvent): void {
		if (!this._isDisposing) {
			this._onDidChangeTokens.fire(e);
		}
	}

	// Having tokens allows implementing additional helper methods

1933
	public getWordAtPosition(_position: IPosition): model.IWordAtPosition {
A
Alex Dima 已提交
1934 1935 1936 1937
		this._assertNotDisposed();
		const position = this.validatePosition(_position);
		const lineContent = this.getLineContent(position.lineNumber);
		const lineTokens = this._getLineTokens(position.lineNumber);
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
		const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);

		// (1). First try checking right biased word
		const [rbStartOffset, rbEndOffset] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex);
		const rightBiasedWord = getWordAtText(
			position.column,
			LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex)),
			lineContent.substring(rbStartOffset, rbEndOffset),
			rbStartOffset
		);
		if (rightBiasedWord) {
			return rightBiasedWord;
		}

		// (2). Else, if we were at a language boundary, check the left biased word
		if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
			// edge case, where `position` sits between two tokens belonging to two different languages
			const [lbStartOffset, lbEndOffset] = TextModel._findLanguageBoundaries(lineTokens, tokenIndex - 1);
			const leftBiasedWord = getWordAtText(
				position.column,
				LanguageConfigurationRegistry.getWordDefinition(lineTokens.getLanguageId(tokenIndex - 1)),
				lineContent.substring(lbStartOffset, lbEndOffset),
				lbStartOffset
			);
			if (leftBiasedWord) {
				return leftBiasedWord;
			}
		}

		return null;
	}

	private static _findLanguageBoundaries(lineTokens: LineTokens, tokenIndex: number): [number, number] {
A
Alex Dima 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
		const languageId = lineTokens.getLanguageId(tokenIndex);

		// go left until a different language is hit
		let startOffset: number;
		for (let i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {
			startOffset = lineTokens.getStartOffset(i);
		}

		// go right until a different language is hit
		let endOffset: number;
		for (let i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {
			endOffset = lineTokens.getEndOffset(i);
		}

1985
		return [startOffset, endOffset];
A
Alex Dima 已提交
1986 1987
	}

1988
	public getWordUntilPosition(position: IPosition): model.IWordAtPosition {
A
Alex Dima 已提交
1989
		const wordAtPosition = this.getWordAtPosition(position);
A
Alex Dima 已提交
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
		if (!wordAtPosition) {
			return {
				word: '',
				startColumn: position.column,
				endColumn: position.column
			};
		}
		return {
			word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),
			startColumn: wordAtPosition.startColumn,
			endColumn: position.column
		};
	}

	public findMatchingBracketUp(_bracket: string, _position: IPosition): Range {
		let bracket = _bracket.toLowerCase();
		let position = this.validatePosition(_position);

		let lineTokens = this._getLineTokens(position.lineNumber);
		let languageId = lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
		let bracketsSupport = LanguageConfigurationRegistry.getBracketsSupport(languageId);

		if (!bracketsSupport) {
			return null;
		}

		let data = bracketsSupport.textIsBracket[bracket];

		if (!data) {
			return null;
		}

		return this._findMatchingBracketUp(data, position);
	}

	public matchBracket(position: IPosition): [Range, Range] {
		return this._matchBracket(this.validatePosition(position));
	}

	private _matchBracket(position: Position): [Range, Range] {
		const lineNumber = position.lineNumber;
		const lineTokens = this._getLineTokens(lineNumber);
		const lineText = this._buffer.getLineContent(lineNumber);

		let tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
		if (tokenIndex < 0) {
			return null;
		}
		const currentModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));

		// check that the token is not to be ignored
		if (currentModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
			// limit search to not go before `maxBracketLength`
			let searchStartOffset = Math.max(lineTokens.getStartOffset(tokenIndex), position.column - 1 - currentModeBrackets.maxBracketLength);
			// limit search to not go after `maxBracketLength`
			const searchEndOffset = Math.min(lineTokens.getEndOffset(tokenIndex), position.column - 1 + currentModeBrackets.maxBracketLength);

2047 2048 2049
			// it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets
			// `bestResult` will contain the most right-side result
			let bestResult: [Range, Range] = null;
A
Alex Dima 已提交
2050 2051 2052
			while (true) {
				let foundBracket = BracketsUtils.findNextBracketInToken(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (!foundBracket) {
2053
					// there are no more brackets in this text
A
Alex Dima 已提交
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
					break;
				}

				// check that we didn't hit a bracket too far away from position
				if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
					let foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1);
					foundBracketText = foundBracketText.toLowerCase();

					let r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText]);

					// check that we can actually match this bracket
					if (r) {
2066
						bestResult = r;
A
Alex Dima 已提交
2067 2068 2069 2070 2071
					}
				}

				searchStartOffset = foundBracket.endColumn - 1;
			}
2072 2073 2074 2075

			if (bestResult) {
				return bestResult;
			}
A
Alex Dima 已提交
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
		}

		// If position is in between two tokens, try also looking in the previous token
		if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
			const searchEndOffset = lineTokens.getStartOffset(tokenIndex);
			tokenIndex--;
			const prevModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(tokenIndex));

			// check that previous token is not to be ignored
			if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
				// limit search in case previous token is very large, there's no need to go beyond `maxBracketLength`
				const searchStartOffset = Math.max(lineTokens.getStartOffset(tokenIndex), position.column - 1 - prevModeBrackets.maxBracketLength);
				const foundBracket = BracketsUtils.findPrevBracketInToken(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);

				// check that we didn't hit a bracket too far away from position
				if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
					let foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1);
					foundBracketText = foundBracketText.toLowerCase();

					let r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText]);

					// check that we can actually match this bracket
					if (r) {
						return r;
					}
				}
			}
		}

		return null;
	}

	private _matchFoundBracket(foundBracket: Range, data: RichEditBracket, isOpen: boolean): [Range, Range] {
A
Alex Dima 已提交
2109 2110 2111 2112
		if (!data) {
			return null;
		}

A
Alex Dima 已提交
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
		if (isOpen) {
			let matched = this._findMatchingBracketDown(data, foundBracket.getEndPosition());
			if (matched) {
				return [foundBracket, matched];
			}
		} else {
			let matched = this._findMatchingBracketUp(data, foundBracket.getStartPosition());
			if (matched) {
				return [foundBracket, matched];
			}
		}

		return null;
	}

	private _findMatchingBracketUp(bracket: RichEditBracket, position: Position): Range {
		// console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));

		const languageId = bracket.languageIdentifier.id;
		const reversedBracketRegex = bracket.reversedRegex;
		let count = -1;

		for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
			const lineTokens = this._getLineTokens(lineNumber);
			const tokenCount = lineTokens.getCount();
			const lineText = this._buffer.getLineContent(lineNumber);

			let tokenIndex = tokenCount - 1;
			let searchStopOffset = -1;
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStopOffset = position.column - 1;
			}

			for (; tokenIndex >= 0; tokenIndex--) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
				const tokenType = lineTokens.getStandardTokenType(tokenIndex);
				const tokenStartOffset = lineTokens.getStartOffset(tokenIndex);
				const tokenEndOffset = lineTokens.getEndOffset(tokenIndex);

				if (searchStopOffset === -1) {
					searchStopOffset = tokenEndOffset;
				}

				if (tokenLanguageId === languageId && !ignoreBracketsInToken(tokenType)) {

					while (true) {
						let r = BracketsUtils.findPrevBracketInToken(reversedBracketRegex, lineNumber, lineText, tokenStartOffset, searchStopOffset);
						if (!r) {
							break;
						}

						let hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1);
						hitText = hitText.toLowerCase();

						if (hitText === bracket.open) {
							count++;
						} else if (hitText === bracket.close) {
							count--;
						}

						if (count === 0) {
							return r;
						}

						searchStopOffset = r.startColumn - 1;
					}
				}

				searchStopOffset = -1;
			}
		}

		return null;
	}

	private _findMatchingBracketDown(bracket: RichEditBracket, position: Position): Range {
		// console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));

		const languageId = bracket.languageIdentifier.id;
		const bracketRegex = bracket.forwardRegex;
		let count = 1;

		for (let lineNumber = position.lineNumber, lineCount = this.getLineCount(); lineNumber <= lineCount; lineNumber++) {
			const lineTokens = this._getLineTokens(lineNumber);
			const tokenCount = lineTokens.getCount();
			const lineText = this._buffer.getLineContent(lineNumber);

			let tokenIndex = 0;
			let searchStartOffset = 0;
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStartOffset = position.column - 1;
			}

			for (; tokenIndex < tokenCount; tokenIndex++) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
				const tokenType = lineTokens.getStandardTokenType(tokenIndex);
				const tokenStartOffset = lineTokens.getStartOffset(tokenIndex);
				const tokenEndOffset = lineTokens.getEndOffset(tokenIndex);

				if (searchStartOffset === 0) {
					searchStartOffset = tokenStartOffset;
				}

				if (tokenLanguageId === languageId && !ignoreBracketsInToken(tokenType)) {
					while (true) {
						let r = BracketsUtils.findNextBracketInToken(bracketRegex, lineNumber, lineText, searchStartOffset, tokenEndOffset);
						if (!r) {
							break;
						}

						let hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1);
						hitText = hitText.toLowerCase();

						if (hitText === bracket.open) {
							count++;
						} else if (hitText === bracket.close) {
							count--;
						}

						if (count === 0) {
							return r;
						}

						searchStartOffset = r.endColumn - 1;
					}
				}

				searchStartOffset = 0;
			}
		}

		return null;
	}

2249
	public findPrevBracket(_position: IPosition): model.IFoundBracket {
A
Alex Dima 已提交
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
		const position = this.validatePosition(_position);

		let languageId: LanguageId = -1;
		let modeBrackets: RichEditBrackets = null;
		for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
			const lineTokens = this._getLineTokens(lineNumber);
			const tokenCount = lineTokens.getCount();
			const lineText = this._buffer.getLineContent(lineNumber);

			let tokenIndex = tokenCount - 1;
			let searchStopOffset = -1;
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStopOffset = position.column - 1;
			}

			for (; tokenIndex >= 0; tokenIndex--) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
				const tokenType = lineTokens.getStandardTokenType(tokenIndex);
				const tokenStartOffset = lineTokens.getStartOffset(tokenIndex);
				const tokenEndOffset = lineTokens.getEndOffset(tokenIndex);

				if (searchStopOffset === -1) {
					searchStopOffset = tokenEndOffset;
				}
				if (languageId !== tokenLanguageId) {
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
				}
				if (modeBrackets && !ignoreBracketsInToken(tokenType)) {
					let r = BracketsUtils.findPrevBracketInToken(modeBrackets.reversedRegex, lineNumber, lineText, tokenStartOffset, searchStopOffset);
					if (r) {
						return this._toFoundBracket(modeBrackets, r);
					}
				}

				searchStopOffset = -1;
			}
		}

		return null;
	}

2293
	public findNextBracket(_position: IPosition): model.IFoundBracket {
A
Alex Dima 已提交
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
		const position = this.validatePosition(_position);

		let languageId: LanguageId = -1;
		let modeBrackets: RichEditBrackets = null;
		for (let lineNumber = position.lineNumber, lineCount = this.getLineCount(); lineNumber <= lineCount; lineNumber++) {
			const lineTokens = this._getLineTokens(lineNumber);
			const tokenCount = lineTokens.getCount();
			const lineText = this._buffer.getLineContent(lineNumber);

			let tokenIndex = 0;
			let searchStartOffset = 0;
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStartOffset = position.column - 1;
			}

			for (; tokenIndex < tokenCount; tokenIndex++) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
				const tokenType = lineTokens.getStandardTokenType(tokenIndex);
				const tokenStartOffset = lineTokens.getStartOffset(tokenIndex);
				const tokenEndOffset = lineTokens.getEndOffset(tokenIndex);

				if (searchStartOffset === 0) {
					searchStartOffset = tokenStartOffset;
				}

				if (languageId !== tokenLanguageId) {
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
				}
				if (modeBrackets && !ignoreBracketsInToken(tokenType)) {
					let r = BracketsUtils.findNextBracketInToken(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, tokenEndOffset);
					if (r) {
						return this._toFoundBracket(modeBrackets, r);
					}
				}

				searchStartOffset = 0;
			}
		}

		return null;
	}

2338
	private _toFoundBracket(modeBrackets: RichEditBrackets, r: Range): model.IFoundBracket {
A
Alex Dima 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
		if (!r) {
			return null;
		}

		let text = this.getValueInRange(r);
		text = text.toLowerCase();

		let data = modeBrackets.textIsBracket[text];
		if (!data) {
			return null;
		}

		return {
			range: r,
			open: data.open,
			close: data.close,
			isOpen: modeBrackets.textIsOpenBracket[text]
		};
	}

2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
	/**
	 * Returns:
	 *  - -1 => the line consists of whitespace
	 *  - otherwise => the indent level is returned value
	 */
	public static computeIndentLevel(line: string, tabSize: number): number {
		let indent = 0;
		let i = 0;
		let len = line.length;

		while (i < len) {
			let chCode = line.charCodeAt(i);
			if (chCode === CharCode.Space) {
				indent++;
			} else if (chCode === CharCode.Tab) {
				indent = indent - indent % tabSize + tabSize;
			} else {
				break;
			}
			i++;
		}

		if (i === len) {
			return -1; // line only consists of whitespace
		}

		return indent;
	}

A
Alex Dima 已提交
2388
	private _computeIndentLevel(lineIndex: number): number {
2389
		return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize);
A
Alex Dima 已提交
2390 2391
	}

2392
	public getActiveIndentGuide(lineNumber: number, minLineNumber: number, maxLineNumber: number): model.IActiveIndentGuideInfo {
A
Alex Dima 已提交
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
		this._assertNotDisposed();
		const lineCount = this.getLineCount();

		if (lineNumber < 1 || lineNumber > lineCount) {
			throw new Error('Illegal value for lineNumber');
		}

		const foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
		const offSide = foldingRules && foldingRules.offSide;

		let up_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
		let up_aboveContentLineIndent = -1;
		let up_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
		let up_belowContentLineIndent = -1;
		const up_resolveIndents = (lineNumber: number) => {
			if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber - 1)) {
				up_aboveContentLineIndex = -1;
				up_aboveContentLineIndent = -1;

				// must find previous line with content
				for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
					let indent = this._computeIndentLevel(lineIndex);
					if (indent >= 0) {
						up_aboveContentLineIndex = lineIndex;
						up_aboveContentLineIndent = indent;
						break;
					}
				}
			}

			if (up_belowContentLineIndex === -2) {
				up_belowContentLineIndex = -1;
				up_belowContentLineIndent = -1;

				// must find next line with content
				for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
					let indent = this._computeIndentLevel(lineIndex);
					if (indent >= 0) {
						up_belowContentLineIndex = lineIndex;
						up_belowContentLineIndent = indent;
						break;
					}
				}
			}
		};

		let down_aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
		let down_aboveContentLineIndent = -1;
		let down_belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
		let down_belowContentLineIndent = -1;
		const down_resolveIndents = (lineNumber: number) => {
			if (down_aboveContentLineIndex === -2) {
				down_aboveContentLineIndex = -1;
				down_aboveContentLineIndent = -1;

				// must find previous line with content
				for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
					let indent = this._computeIndentLevel(lineIndex);
					if (indent >= 0) {
						down_aboveContentLineIndex = lineIndex;
						down_aboveContentLineIndent = indent;
						break;
					}
				}
			}

			if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber - 1)) {
				down_belowContentLineIndex = -1;
				down_belowContentLineIndent = -1;

				// must find next line with content
				for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
					let indent = this._computeIndentLevel(lineIndex);
					if (indent >= 0) {
						down_belowContentLineIndex = lineIndex;
						down_belowContentLineIndent = indent;
						break;
					}
				}
			}
		};

		let startLineNumber = 0;
		let goUp = true;
		let endLineNumber = 0;
		let goDown = true;
		let indent = 0;

		for (let distance = 0; goUp || goDown; distance++) {
			const upLineNumber = lineNumber - distance;
			const downLineNumber = lineNumber + distance;

2485
			if (upLineNumber < 1 || upLineNumber < minLineNumber) {
A
Alex Dima 已提交
2486 2487
				goUp = false;
			}
2488
			if (downLineNumber > lineCount || downLineNumber > maxLineNumber) {
A
Alex Dima 已提交
2489 2490
				goDown = false;
			}
2491 2492 2493 2494 2495
			if (distance > 50000) {
				// stop processing
				goUp = false;
				goDown = false;
			}
A
Alex Dima 已提交
2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

			if (goUp) {
				// compute indent level going up
				let upLineIndentLevel: number;

				const currentIndent = this._computeIndentLevel(upLineNumber - 1);
				if (currentIndent >= 0) {
					// This line has content (besides whitespace)
					// Use the line's indent
					up_belowContentLineIndex = upLineNumber - 1;
					up_belowContentLineIndent = currentIndent;
					upLineIndentLevel = Math.ceil(currentIndent / this._options.tabSize);
				} else {
					up_resolveIndents(upLineNumber);
					upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
				}

				if (distance === 0) {
					// This is the initial line number
					startLineNumber = upLineNumber;
					endLineNumber = downLineNumber;
					indent = upLineIndentLevel;
					if (indent === 0) {
						// No need to continue
						return { startLineNumber, endLineNumber, indent };
					}
					continue;
				}

				if (upLineIndentLevel >= indent) {
					startLineNumber = upLineNumber;
				} else {
					goUp = false;
				}
			}

			if (goDown) {
				// compute indent level going down
				let downLineIndentLevel: number;

				const currentIndent = this._computeIndentLevel(downLineNumber - 1);
				if (currentIndent >= 0) {
					// This line has content (besides whitespace)
					// Use the line's indent
					down_aboveContentLineIndex = downLineNumber - 1;
					down_aboveContentLineIndent = currentIndent;
					downLineIndentLevel = Math.ceil(currentIndent / this._options.tabSize);
				} else {
					down_resolveIndents(downLineNumber);
					downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
				}

				if (downLineIndentLevel >= indent) {
					endLineNumber = downLineNumber;
				} else {
					goDown = false;
				}
			}
		}

		return { startLineNumber, endLineNumber, indent };
	}

A
Alex Dima 已提交
2559 2560 2561 2562 2563
	public getLinesIndentGuides(startLineNumber: number, endLineNumber: number): number[] {
		this._assertNotDisposed();
		const lineCount = this.getLineCount();

		if (startLineNumber < 1 || startLineNumber > lineCount) {
2564
			throw new Error('Illegal value for startLineNumber');
A
Alex Dima 已提交
2565 2566
		}
		if (endLineNumber < 1 || endLineNumber > lineCount) {
2567
			throw new Error('Illegal value for endLineNumber');
A
Alex Dima 已提交
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623
		}

		const foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
		const offSide = foldingRules && foldingRules.offSide;

		let result: number[] = new Array<number>(endLineNumber - startLineNumber + 1);

		let aboveContentLineIndex = -2; /* -2 is a marker for not having computed it */
		let aboveContentLineIndent = -1;

		let belowContentLineIndex = -2; /* -2 is a marker for not having computed it */
		let belowContentLineIndent = -1;

		for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
			let resultIndex = lineNumber - startLineNumber;

			const currentIndent = this._computeIndentLevel(lineNumber - 1);
			if (currentIndent >= 0) {
				// This line has content (besides whitespace)
				// Use the line's indent
				aboveContentLineIndex = lineNumber - 1;
				aboveContentLineIndent = currentIndent;
				result[resultIndex] = Math.ceil(currentIndent / this._options.tabSize);
				continue;
			}

			if (aboveContentLineIndex === -2) {
				aboveContentLineIndex = -1;
				aboveContentLineIndent = -1;

				// must find previous line with content
				for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
					let indent = this._computeIndentLevel(lineIndex);
					if (indent >= 0) {
						aboveContentLineIndex = lineIndex;
						aboveContentLineIndent = indent;
						break;
					}
				}
			}

			if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
				belowContentLineIndex = -1;
				belowContentLineIndent = -1;

				// must find next line with content
				for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
					let indent = this._computeIndentLevel(lineIndex);
					if (indent >= 0) {
						belowContentLineIndex = lineIndex;
						belowContentLineIndent = indent;
						break;
					}
				}
			}

A
Alex Dima 已提交
2624 2625 2626 2627 2628
			result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);

		}
		return result;
	}
A
Alex Dima 已提交
2629

A
Alex Dima 已提交
2630 2631 2632 2633
	private _getIndentLevelForWhitespaceLine(offSide: boolean, aboveContentLineIndent: number, belowContentLineIndent: number): number {
		if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
			// At the top or bottom of the file
			return 0;
A
Alex Dima 已提交
2634

A
Alex Dima 已提交
2635 2636 2637
		} else if (aboveContentLineIndent < belowContentLineIndent) {
			// we are inside the region above
			return (1 + Math.floor(aboveContentLineIndent / this._options.tabSize));
A
Alex Dima 已提交
2638

A
Alex Dima 已提交
2639 2640 2641
		} else if (aboveContentLineIndent === belowContentLineIndent) {
			// we are in between two regions
			return Math.ceil(belowContentLineIndent / this._options.tabSize);
A
Alex Dima 已提交
2642

A
Alex Dima 已提交
2643
		} else {
A
Alex Dima 已提交
2644

A
Alex Dima 已提交
2645 2646 2647 2648 2649 2650
			if (offSide) {
				// same level as region below
				return Math.ceil(belowContentLineIndent / this._options.tabSize);
			} else {
				// we are inside the region that ends below
				return (1 + Math.floor(belowContentLineIndent / this._options.tabSize));
A
Alex Dima 已提交
2651
			}
A
Alex Dima 已提交
2652

A
Alex Dima 已提交
2653 2654
		}
	}
A
Alex Dima 已提交
2655

A
Alex Dima 已提交
2656
	//#endregion
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
}

//#region Decorations

class DecorationsTrees {

	/**
	 * This tree holds decorations that do not show up in the overview ruler.
	 */
	private _decorationsTree0: IntervalTree;

	/**
	 * This tree holds decorations that show up in the overview ruler.
	 */
	private _decorationsTree1: IntervalTree;

	constructor() {
		this._decorationsTree0 = new IntervalTree();
		this._decorationsTree1 = new IntervalTree();
	}

	public intervalSearch(start: number, end: number, filterOwnerId: number, filterOutValidation: boolean, cachedVersionId: number): IntervalNode[] {
		const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
		const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId);
		return r0.concat(r1);
	}

	public search(filterOwnerId: number, filterOutValidation: boolean, overviewRulerOnly: boolean, cachedVersionId: number): IntervalNode[] {
		if (overviewRulerOnly) {
			return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
		} else {
			const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId);
			const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId);
			return r0.concat(r1);
		}
	}

	public collectNodesFromOwner(ownerId: number): IntervalNode[] {
		const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);
		const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);
		return r0.concat(r1);
	}

	public collectNodesPostOrder(): IntervalNode[] {
		const r0 = this._decorationsTree0.collectNodesPostOrder();
		const r1 = this._decorationsTree1.collectNodesPostOrder();
		return r0.concat(r1);
	}

	public insert(node: IntervalNode): void {
		if (getNodeIsInOverviewRuler(node)) {
			this._decorationsTree1.insert(node);
		} else {
			this._decorationsTree0.insert(node);
		}
	}

	public delete(node: IntervalNode): void {
		if (getNodeIsInOverviewRuler(node)) {
			this._decorationsTree1.delete(node);
		} else {
			this._decorationsTree0.delete(node);
		}
	}

	public resolveNode(node: IntervalNode, cachedVersionId: number): void {
		if (getNodeIsInOverviewRuler(node)) {
			this._decorationsTree1.resolveNode(node, cachedVersionId);
		} else {
			this._decorationsTree0.resolveNode(node, cachedVersionId);
		}
	}

	public acceptReplace(offset: number, length: number, textLength: number, forceMoveMarkers: boolean): void {
		this._decorationsTree0.acceptReplace(offset, length, textLength, forceMoveMarkers);
		this._decorationsTree1.acceptReplace(offset, length, textLength, forceMoveMarkers);
	}
}

function cleanClassName(className: string): string {
	return className.replace(/[^a-z0-9\-]/gi, ' ');
}

2740
export class ModelDecorationOverviewRulerOptions implements model.IModelDecorationOverviewRulerOptions {
2741 2742 2743
	readonly color: string | ThemeColor;
	readonly darkColor: string | ThemeColor;
	readonly hcColor: string | ThemeColor;
2744
	readonly position: model.OverviewRulerLane;
2745 2746
	_resolvedColor: string;

2747
	constructor(options: model.IModelDecorationOverviewRulerOptions) {
2748 2749 2750
		this.color = strings.empty;
		this.darkColor = strings.empty;
		this.hcColor = strings.empty;
2751
		this.position = model.OverviewRulerLane.Center;
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
		this._resolvedColor = null;

		if (options && options.color) {
			this.color = options.color;
		}
		if (options && options.darkColor) {
			this.darkColor = options.darkColor;
			this.hcColor = options.darkColor;
		}
		if (options && options.hcColor) {
			this.hcColor = options.hcColor;
		}
		if (options && options.hasOwnProperty('position')) {
			this.position = options.position;
		}
	}
}

2770
export class ModelDecorationOptions implements model.IModelDecorationOptions {
2771 2772 2773

	public static EMPTY: ModelDecorationOptions;

2774
	public static register(options: model.IModelDecorationOptions): ModelDecorationOptions {
2775
		return new ModelDecorationOptions(options);
2776 2777
	}

2778
	public static createDynamic(options: model.IModelDecorationOptions): ModelDecorationOptions {
2779
		return new ModelDecorationOptions(options);
2780 2781
	}

2782
	readonly stickiness: model.TrackedRangeStickiness;
2783
	readonly zIndex: number;
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793
	readonly className: string;
	readonly hoverMessage: IMarkdownString | IMarkdownString[];
	readonly glyphMarginHoverMessage: IMarkdownString | IMarkdownString[];
	readonly isWholeLine: boolean;
	readonly showIfCollapsed: boolean;
	readonly overviewRuler: ModelDecorationOverviewRulerOptions;
	readonly glyphMarginClassName: string;
	readonly linesDecorationsClassName: string;
	readonly marginClassName: string;
	readonly inlineClassName: string;
A
Alex Dima 已提交
2794
	readonly inlineClassNameAffectsLetterSpacing: boolean;
2795 2796 2797
	readonly beforeContentClassName: string;
	readonly afterContentClassName: string;

2798
	private constructor(options: model.IModelDecorationOptions) {
2799
		this.stickiness = options.stickiness || model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges;
2800
		this.zIndex = options.zIndex || 0;
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
		this.className = options.className ? cleanClassName(options.className) : strings.empty;
		this.hoverMessage = options.hoverMessage || [];
		this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || [];
		this.isWholeLine = options.isWholeLine || false;
		this.showIfCollapsed = options.showIfCollapsed || false;
		this.overviewRuler = new ModelDecorationOverviewRulerOptions(options.overviewRuler);
		this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : strings.empty;
		this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : strings.empty;
		this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : strings.empty;
		this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : strings.empty;
A
Alex Dima 已提交
2811
		this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
		this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : strings.empty;
		this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : strings.empty;
	}
}
ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({});

/**
 * The order carefully matches the values of the enum.
 */
const TRACKED_RANGE_OPTIONS = [
2822 2823 2824 2825
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges }),
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges }),
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore }),
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter }),
2826 2827
];

2828
function _normalizeOptions(options: model.IModelDecorationOptions): ModelDecorationOptions {
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
	if (options instanceof ModelDecorationOptions) {
		return options;
	}
	return ModelDecorationOptions.createDynamic(options);
}

export class DidChangeDecorationsEmitter extends Disposable {

	private readonly _actual: Emitter<IModelDecorationsChangedEvent> = this._register(new Emitter<IModelDecorationsChangedEvent>());
	public readonly event: Event<IModelDecorationsChangedEvent> = this._actual.event;

	private _deferredCnt: number;
	private _shouldFire: boolean;

	constructor() {
		super();
		this._deferredCnt = 0;
		this._shouldFire = false;
	}

	public beginDeferredEmit(): void {
		this._deferredCnt++;
	}

	public endDeferredEmit(): void {
		this._deferredCnt--;
		if (this._deferredCnt === 0) {
			if (this._shouldFire) {
				this._shouldFire = false;
				this._actual.fire({});
			}
		}
	}

	public fire(): void {
		this._shouldFire = true;
	}
E
Erich Gamma 已提交
2866
}
2867 2868

//#endregion
2869 2870 2871

export class DidChangeContentEmitter extends Disposable {

2872 2873 2874 2875 2876 2877 2878
	/**
	 * Both `fastEvent` and `slowEvent` work the same way and contain the same events, but first we invoke `fastEvent` and then `slowEvent`.
	 */
	private readonly _fastEmitter: Emitter<InternalModelContentChangeEvent> = this._register(new Emitter<InternalModelContentChangeEvent>());
	public readonly fastEvent: Event<InternalModelContentChangeEvent> = this._fastEmitter.event;
	private readonly _slowEmitter: Emitter<InternalModelContentChangeEvent> = this._register(new Emitter<InternalModelContentChangeEvent>());
	public readonly slowEvent: Event<InternalModelContentChangeEvent> = this._slowEmitter.event;
2879 2880

	private _deferredCnt: number;
2881
	private _deferredEvent: InternalModelContentChangeEvent;
2882 2883 2884 2885

	constructor() {
		super();
		this._deferredCnt = 0;
2886
		this._deferredEvent = null;
2887 2888 2889 2890 2891 2892 2893 2894 2895
	}

	public beginDeferredEmit(): void {
		this._deferredCnt++;
	}

	public endDeferredEmit(): void {
		this._deferredCnt--;
		if (this._deferredCnt === 0) {
2896 2897 2898
			if (this._deferredEvent !== null) {
				const e = this._deferredEvent;
				this._deferredEvent = null;
2899 2900
				this._fastEmitter.fire(e);
				this._slowEmitter.fire(e);
2901 2902 2903 2904 2905 2906
			}
		}
	}

	public fire(e: InternalModelContentChangeEvent): void {
		if (this._deferredCnt > 0) {
2907 2908 2909 2910 2911
			if (this._deferredEvent) {
				this._deferredEvent = this._deferredEvent.merge(e);
			} else {
				this._deferredEvent = e;
			}
2912 2913
			return;
		}
2914 2915
		this._fastEmitter.fire(e);
		this._slowEmitter.fire(e);
2916 2917
	}
}