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

A
Alex Dima 已提交
6
import { CharCode } from 'vs/base/common/charCode';
7
import { onUnexpectedError } from 'vs/base/common/errors';
A
Alex Dima 已提交
8
import { Emitter, Event } from 'vs/base/common/event';
9
import { IMarkdownString } from 'vs/base/common/htmlContent';
A
Alex Dima 已提交
10
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
11 12 13
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { EDITOR_MODEL_DEFAULTS } from 'vs/editor/common/config/editorOptions';
A
Alex Dima 已提交
14
import { LineTokens } from 'vs/editor/common/core/lineTokens';
A
Alex Dima 已提交
15 16 17 18 19
import { IPosition, Position } from 'vs/editor/common/core/position';
import { IRange, Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import * as model from 'vs/editor/common/model';
import { EditStack } from 'vs/editor/common/model/editStack';
A
Alex Dima 已提交
20
import { guessIndentation } from 'vs/editor/common/model/indentationGuesser';
A
Alex Dima 已提交
21
import { IntervalNode, IntervalTree, getNodeIsInOverviewRuler, recomputeMaxEnd } from 'vs/editor/common/model/intervalTree';
22
import { PieceTreeTextBufferBuilder } from 'vs/editor/common/model/pieceTreeTextBuffer/pieceTreeTextBufferBuilder';
A
Alex Dima 已提交
23 24
import { IModelContentChangedEvent, IModelDecorationsChangedEvent, IModelLanguageChangedEvent, IModelLanguageConfigurationChangedEvent, IModelOptionsChangedEvent, IModelTokensChangedEvent, InternalModelContentChangeEvent, ModelRawChange, ModelRawContentChangedEvent, ModelRawEOLChanged, ModelRawFlush, ModelRawLineChanged, ModelRawLinesDeleted, ModelRawLinesInserted } from 'vs/editor/common/model/textModelEvents';
import { SearchData, SearchParams, TextModelSearch } from 'vs/editor/common/model/textModelSearch';
25
import { TextModelTokenization } from 'vs/editor/common/model/textModelTokens';
A
Alex Dima 已提交
26
import { getWordAtText } from 'vs/editor/common/model/wordHelper';
A
Alex Dima 已提交
27
import { LanguageId, LanguageIdentifier, FormattingOptions } from 'vs/editor/common/modes';
A
Alex Dima 已提交
28 29 30 31
import { LanguageConfigurationRegistry } from 'vs/editor/common/modes/languageConfigurationRegistry';
import { NULL_LANGUAGE_IDENTIFIER } from 'vs/editor/common/modes/nullMode';
import { ignoreBracketsInToken } from 'vs/editor/common/modes/supports';
import { BracketsUtils, RichEditBracket, RichEditBrackets } from 'vs/editor/common/modes/supports/richEditBrackets';
A
Alex Dima 已提交
32
import { ThemeColor } from 'vs/platform/theme/common/themeService';
33
import { VSBufferReadableStream, VSBuffer } from 'vs/base/common/buffer';
A
Alexandru Dima 已提交
34
import { TokensStore, MultilineTokens, countEOL, MultilineTokens2, TokensStore2 } from 'vs/editor/common/model/tokensStore';
35
import { Color } from 'vs/base/common/color';
A
Alex Dima 已提交
36
import { EditorTheme } from 'vs/editor/common/view/viewContext';
37
import { IUndoRedoService, ResourceEditStackSnapshot } from 'vs/platform/undoRedo/common/undoRedo';
38
import { TextChange } from 'vs/editor/common/model/textChange';
39
import { Constants } from 'vs/base/common/uint';
40

A
Alex Dima 已提交
41
function createTextBufferBuilder() {
A
Alex Dima 已提交
42
	return new PieceTreeTextBufferBuilder();
A
Alex Dima 已提交
43 44 45 46 47 48 49
}

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

51 52 53 54 55 56 57 58
interface ITextStream {
	on(event: 'data', callback: (data: string) => void): void;
	on(event: 'error', callback: (err: Error) => void): void;
	on(event: 'end', callback: () => void): void;
	on(event: string, callback: any): void;
}

export function createTextBufferFactoryFromStream(stream: ITextStream, filter?: (chunk: string) => string, validator?: (chunk: string) => Error | undefined): Promise<model.ITextBufferFactory>;
59
export function createTextBufferFactoryFromStream(stream: VSBufferReadableStream, filter?: (chunk: VSBuffer) => VSBuffer, validator?: (chunk: VSBuffer) => Error | undefined): Promise<model.ITextBufferFactory>;
60
export function createTextBufferFactoryFromStream(stream: ITextStream | VSBufferReadableStream, filter?: (chunk: any) => string | VSBuffer, validator?: (chunk: any) => Error | undefined): Promise<model.ITextBufferFactory> {
61 62 63
	return new Promise<model.ITextBufferFactory>((resolve, reject) => {
		const builder = createTextBufferBuilder();

64 65
		let done = false;

66 67 68 69 70 71 72 73 74
		stream.on('data', (chunk: string | VSBuffer) => {
			if (validator) {
				const error = validator(chunk);
				if (error) {
					done = true;
					reject(error);
				}
			}

75 76 77 78
			if (filter) {
				chunk = filter(chunk);
			}

79
			builder.acceptChunk((typeof chunk === 'string') ? chunk : chunk.toString());
80 81 82 83 84
		});

		stream.on('error', (error) => {
			if (!done) {
				done = true;
85
				reject(error);
86 87 88 89 90 91
			}
		});

		stream.on('end', () => {
			if (!done) {
				done = true;
92
				resolve(builder.finish());
93 94 95
			}
		});
	});
96 97
}

98
export function createTextBufferFactoryFromSnapshot(snapshot: model.ITextSnapshot): model.ITextBufferFactory {
B
Benjamin Pasero 已提交
99 100
	let builder = createTextBufferBuilder();

A
Alex Dima 已提交
101
	let chunk: string | null;
B
Benjamin Pasero 已提交
102 103 104 105 106 107 108
	while (typeof (chunk = snapshot.read()) === 'string') {
		builder.acceptChunk(chunk);
	}

	return builder.finish();
}

109 110 111 112
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 已提交
113

A
Alex Dima 已提交
114
let MODEL_ID = 0;
E
Erich Gamma 已提交
115

A
Alex Dima 已提交
116
const LIMIT_FIND_COUNT = 999;
117
export const LONG_LINE_BOUNDARY = 10000;
E
Erich Gamma 已提交
118

119
class TextModelSnapshot implements model.ITextSnapshot {
120

121
	private readonly _source: model.ITextSnapshot;
122 123
	private _eos: boolean;

124
	constructor(source: model.ITextSnapshot) {
125 126 127 128
		this._source = source;
		this._eos = false;
	}

A
Alex Dima 已提交
129
	public read(): string | null {
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 155 156 157 158 159 160
		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 已提交
161
const invalidFunc = () => { throw new Error(`Invalid change accessor`); };
A
Alex Dima 已提交
162

163 164 165 166 167 168 169 170 171 172 173
const enum StringOffsetValidationType {
	/**
	 * Even allowed in surrogate pairs
	 */
	Relaxed = 0,
	/**
	 * Not allowed in surrogate pairs
	 */
	SurrogatePairs = 1,
}

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
type ContinueBracketSearchPredicate = null | (() => boolean);

class BracketSearchCanceled {
	public static INSTANCE = new BracketSearchCanceled();
	_searchCanceledBrand = undefined;
	private constructor() { }
}

function stripBracketSearchCanceled<T>(result: T | null | BracketSearchCanceled): T | null {
	if (result instanceof BracketSearchCanceled) {
		return null;
	}
	return result;
}

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

191
	private static readonly MODEL_SYNC_LIMIT = 50 * 1024 * 1024; // 50 MB
192 193
	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 已提交
194

195
	public static DEFAULT_CREATION_OPTIONS: model.ITextModelCreationOptions = {
196
		isForSimpleWidget: false,
197
		tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
D
David Lechner 已提交
198
		indentSize: EDITOR_MODEL_DEFAULTS.indentSize,
199
		insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
200
		detectIndentation: false,
201
		defaultEOL: model.DefaultEndOfLine.LF,
202
		trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
203
		largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
204 205
	};

A
Alex Dima 已提交
206
	public static resolveOptions(textBuffer: model.ITextBuffer, options: model.ITextModelCreationOptions): model.TextModelResolvedOptions {
A
Alex Dima 已提交
207
		if (options.detectIndentation) {
A
Alex Dima 已提交
208 209
			const guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
			return new model.TextModelResolvedOptions({
A
Alex Dima 已提交
210
				tabSize: guessedIndentation.tabSize,
A
Alex Dima 已提交
211
				indentSize: guessedIndentation.tabSize, // TODO@Alex: guess indentSize independent of tabSize
A
Alex Dima 已提交
212 213 214 215 216 217
				insertSpaces: guessedIndentation.insertSpaces,
				trimAutoWhitespace: options.trimAutoWhitespace,
				defaultEOL: options.defaultEOL
			});
		}

A
Alex Dima 已提交
218 219
		return new model.TextModelResolvedOptions({
			tabSize: options.tabSize,
D
David Lechner 已提交
220
			indentSize: options.indentSize,
A
Alex Dima 已提交
221 222 223 224 225
			insertSpaces: options.insertSpaces,
			trimAutoWhitespace: options.trimAutoWhitespace,
			defaultEOL: options.defaultEOL
		});

A
Alex Dima 已提交
226 227
	}

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

232 233 234
	private readonly _onDidChangeDecorations: DidChangeDecorationsEmitter = this._register(new DidChangeDecorationsEmitter());
	public readonly onDidChangeDecorations: Event<IModelDecorationsChangedEvent> = this._onDidChangeDecorations.event;

A
Alex Dima 已提交
235 236 237 238 239 240 241 242 243
	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 已提交
244 245 246
	private readonly _onDidChangeOptions: Emitter<IModelOptionsChangedEvent> = this._register(new Emitter<IModelOptionsChangedEvent>());
	public readonly onDidChangeOptions: Event<IModelOptionsChangedEvent> = this._onDidChangeOptions.event;

247 248 249
	private readonly _onDidChangeAttached: Emitter<void> = this._register(new Emitter<void>());
	public readonly onDidChangeAttached: Event<void> = this._onDidChangeAttached.event;

A
Alex Dima 已提交
250
	private readonly _eventEmitter: DidChangeContentEmitter = this._register(new DidChangeContentEmitter());
251 252 253
	public onDidChangeRawContentFast(listener: (e: ModelRawContentChangedEvent) => void): IDisposable {
		return this._eventEmitter.fastEvent((e: InternalModelContentChangeEvent) => listener(e.rawContentChangedEvent));
	}
254
	public onDidChangeRawContent(listener: (e: ModelRawContentChangedEvent) => void): IDisposable {
255
		return this._eventEmitter.slowEvent((e: InternalModelContentChangeEvent) => listener(e.rawContentChangedEvent));
256
	}
A
Alex Dima 已提交
257 258 259
	public onDidChangeContentFast(listener: (e: IModelContentChangedEvent) => void): IDisposable {
		return this._eventEmitter.fastEvent((e: InternalModelContentChangeEvent) => listener(e.contentChangedEvent));
	}
260
	public onDidChangeContent(listener: (e: IModelContentChangedEvent) => void): IDisposable {
261
		return this._eventEmitter.slowEvent((e: InternalModelContentChangeEvent) => listener(e.contentChangedEvent));
262
	}
A
Alex Dima 已提交
263
	//#endregion
A
Alex Dima 已提交
264

265
	public readonly id: string;
266
	public readonly isForSimpleWidget: boolean;
267
	private readonly _associatedResource: URI;
268
	private readonly _undoRedoService: IUndoRedoService;
J
Johannes Rieken 已提交
269
	private _attachedEditorCount: number;
A
Alex Dima 已提交
270 271
	private _buffer: model.ITextBuffer;
	private _options: model.TextModelResolvedOptions;
E
Erich Gamma 已提交
272

A
Alex Dima 已提交
273 274
	private _isDisposed: boolean;
	private _isDisposing: boolean;
J
Johannes Rieken 已提交
275
	private _versionId: number;
E
Erich Gamma 已提交
276 277 278 279
	/**
	 * Unlike, versionId, this can go down (via undo) or go to previous values (via redo)
	 */
	private _alternativeVersionId: number;
280
	private _initialUndoRedoSnapshot: ResourceEditStackSnapshot | null;
A
Alex Dima 已提交
281
	private readonly _isTooLargeForSyncing: boolean;
A
Alex Dima 已提交
282
	private readonly _isTooLargeForTokenization: boolean;
283

284
	//#region Editing
285
	private readonly _commandManager: EditStack;
A
Alex Dima 已提交
286 287
	private _isUndoing: boolean;
	private _isRedoing: boolean;
A
Alex Dima 已提交
288
	private _trimAutoWhitespaceLines: number[] | null;
289
	//#endregion
A
Alex Dima 已提交
290

291 292 293 294 295 296 297 298 299 300
	//#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 已提交
301

A
Alex Dima 已提交
302 303
	//#region Tokenization
	private _languageIdentifier: LanguageIdentifier;
304
	private readonly _languageRegistryListener: IDisposable;
305
	private readonly _tokens: TokensStore;
A
Alexandru Dima 已提交
306
	private readonly _tokens2: TokensStore2;
307
	private readonly _tokenization: TextModelTokenization;
A
Alex Dima 已提交
308 309
	//#endregion

310 311 312 313 314 315 316
	constructor(
		source: string | model.ITextBufferFactory,
		creationOptions: model.ITextModelCreationOptions,
		languageIdentifier: LanguageIdentifier | null,
		associatedResource: URI | null = null,
		undoRedoService: IUndoRedoService
	) {
A
Alex Dima 已提交
317
		super();
E
Erich Gamma 已提交
318

A
Alex Dima 已提交
319 320 321
		// Generate a new unique model id
		MODEL_ID++;
		this.id = '$model' + MODEL_ID;
322
		this.isForSimpleWidget = creationOptions.isForSimpleWidget;
A
Alex Dima 已提交
323 324 325 326 327
		if (typeof associatedResource === 'undefined' || associatedResource === null) {
			this._associatedResource = URI.parse('inmemory://model/' + MODEL_ID);
		} else {
			this._associatedResource = associatedResource;
		}
328
		this._undoRedoService = undoRedoService;
A
Alex Dima 已提交
329 330
		this._attachedEditorCount = 0;

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

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

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

338 339 340
		// !!! 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.
341 342 343 344 345 346 347 348
		if (creationOptions.largeFileOptimizations) {
			this._isTooLargeForTokenization = (
				(bufferTextLength > TextModel.LARGE_FILE_SIZE_THRESHOLD)
				|| (bufferLineCount > TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD)
			);
		} else {
			this._isTooLargeForTokenization = false;
		}
349

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

A
Alex Dima 已提交
352 353
		this._versionId = 1;
		this._alternativeVersionId = 1;
354
		this._initialUndoRedoSnapshot = null;
A
Alex Dima 已提交
355

E
Erich Gamma 已提交
356 357
		this._isDisposed = false;
		this._isDisposing = false;
A
Alex Dima 已提交
358 359 360 361 362 363 364 365

		this._languageIdentifier = languageIdentifier || NULL_LANGUAGE_IDENTIFIER;

		this._languageRegistryListener = LanguageConfigurationRegistry.onDidChange((e) => {
			if (e.languageIdentifier.id === this._languageIdentifier.id) {
				this._onDidChangeLanguageConfiguration.fire({});
			}
		});
E
Erich Gamma 已提交
366

A
Alex Dima 已提交
367
		this._instanceId = strings.singleLetterHash(MODEL_ID);
368 369 370
		this._lastDecorationId = 0;
		this._decorations = Object.create(null);
		this._decorationsTree = new DecorationsTrees();
A
Alex Dima 已提交
371

372
		this._commandManager = new EditStack(this, undoRedoService);
A
Alex Dima 已提交
373 374 375
		this._isUndoing = false;
		this._isRedoing = false;
		this._trimAutoWhitespaceLines = null;
A
Alex Dima 已提交
376

377
		this._tokens = new TokensStore();
A
Alexandru Dima 已提交
378
		this._tokens2 = new TokensStore2();
A
Alex Dima 已提交
379
		this._tokenization = new TextModelTokenization(this);
A
Alex Dima 已提交
380
	}
A
Alex Dima 已提交
381

E
Erich Gamma 已提交
382 383
	public dispose(): void {
		this._isDisposing = true;
A
Alex Dima 已提交
384
		this._onWillDispose.fire();
A
Alex Dima 已提交
385
		this._languageRegistryListener.dispose();
A
Alex Dima 已提交
386
		this._tokenization.dispose();
A
Alex Dima 已提交
387
		this._isDisposed = true;
E
Erich Gamma 已提交
388 389
		super.dispose();
		this._isDisposing = false;
390 391 392
		// Manually release reference to previous text buffer to avoid large leaks
		// in case someone leaks a TextModel reference
		this._buffer = createTextBuffer('', this._options.defaultEOL);
E
Erich Gamma 已提交
393 394
	}

A
Alex Dima 已提交
395
	private _assertNotDisposed(): void {
396 397 398 399 400
		if (this._isDisposed) {
			throw new Error('Model is disposed!');
		}
	}

401
	public equalsTextBuffer(other: model.ITextBuffer): boolean {
A
Alex Dima 已提交
402 403 404
		this._assertNotDisposed();
		return this._buffer.equals(other);
	}
A
Alex Dima 已提交
405

R
rebornix 已提交
406 407 408 409 410
	public getTextBuffer(): model.ITextBuffer {
		this._assertNotDisposed();
		return this._buffer;
	}

A
Alex Dima 已提交
411
	private _emitContentChangedEvent(rawChange: ModelRawContentChangedEvent, change: IModelContentChangedEvent): void {
A
Alex Dima 已提交
412 413 414 415 416 417
		if (this._isDisposing) {
			// Do not confuse listeners by emitting any event after disposing
			return;
		}
		this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));
	}
418

A
Alex Dima 已提交
419 420 421 422 423 424
	public setValue(value: string): void {
		this._assertNotDisposed();
		if (value === null) {
			// There's nothing to do
			return;
		}
425 426 427

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

430
	private _createContentChanged2(range: Range, rangeOffset: number, rangeLength: number, text: string, isUndoing: boolean, isRedoing: boolean, isFlush: boolean): IModelContentChangedEvent {
A
Alex Dima 已提交
431 432
		return {
			changes: [{
433 434
				range: range,
				rangeOffset: rangeOffset,
A
Alex Dima 已提交
435 436 437 438 439 440 441 442 443
				rangeLength: rangeLength,
				text: text,
			}],
			eol: this._buffer.getEOL(),
			versionId: this.getVersionId(),
			isUndoing: isUndoing,
			isRedoing: isRedoing,
			isFlush: isFlush
		};
A
Alex Dima 已提交
444 445
	}

446
	public setValueFromTextBuffer(textBuffer: model.ITextBuffer): void {
A
Alex Dima 已提交
447
		this._assertNotDisposed();
448
		if (textBuffer === null) {
A
Alex Dima 已提交
449 450
			// There's nothing to do
			return;
A
Alex Dima 已提交
451
		}
A
Alex Dima 已提交
452 453 454 455
		const oldFullModelRange = this.getFullModelRange();
		const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
		const endLineNumber = this.getLineCount();
		const endColumn = this.getLineMaxColumn(endLineNumber);
A
Alex Dima 已提交
456

457
		this._buffer = textBuffer;
A
Alex Dima 已提交
458 459
		this._increaseVersionId();

460 461
		// Flush all tokens
		this._tokens.flush();
A
wip  
Alexandru Dima 已提交
462
		this._tokens2.flush();
463

A
Alex Dima 已提交
464 465 466 467 468
		// Destroy all my decorations
		this._decorations = Object.create(null);
		this._decorationsTree = new DecorationsTrees();

		// Destroy my edit history and settings
469
		this._commandManager.clear();
A
Alex Dima 已提交
470
		this._trimAutoWhitespaceLines = null;
A
Alex Dima 已提交
471 472 473 474 475 476 477 478 479 480

		this._emitContentChangedEvent(
			new ModelRawContentChangedEvent(
				[
					new ModelRawFlush()
				],
				this._versionId,
				false,
				false
			),
481
			this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true)
A
Alex Dima 已提交
482
		);
A
Alex Dima 已提交
483 484
	}

485
	public setEOL(eol: model.EndOfLineSequence): void {
A
Alex Dima 已提交
486
		this._assertNotDisposed();
487
		const newEOL = (eol === model.EndOfLineSequence.CRLF ? '\r\n' : '\n');
A
Alex Dima 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
		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
			),
512
			this._createContentChanged2(new Range(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false)
A
Alex Dima 已提交
513 514
		);
	}
515

A
Alex Dima 已提交
516
	private _onBeforeEOLChange(): void {
517 518 519 520 521 522
		// 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 已提交
523
	private _onAfterEOLChange(): void {
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
		// 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);
		}
	}

E
Erich Gamma 已提交
546 547
	public onBeforeAttached(): void {
		this._attachedEditorCount++;
548 549 550
		if (this._attachedEditorCount === 1) {
			this._onDidChangeAttached.fire(undefined);
		}
E
Erich Gamma 已提交
551 552 553 554
	}

	public onBeforeDetached(): void {
		this._attachedEditorCount--;
555 556 557
		if (this._attachedEditorCount === 0) {
			this._onDidChangeAttached.fire(undefined);
		}
E
Erich Gamma 已提交
558 559 560 561 562 563
	}

	public isAttachedToEditor(): boolean {
		return this._attachedEditorCount > 0;
	}

564 565 566 567
	public getAttachedEditorCount(): number {
		return this._attachedEditorCount;
	}

568
	public isTooLargeForSyncing(): boolean {
A
Alex Dima 已提交
569
		return this._isTooLargeForSyncing;
570 571
	}

572 573 574 575
	public isTooLargeForTokenization(): boolean {
		return this._isTooLargeForTokenization;
	}

A
Alex Dima 已提交
576 577 578 579 580 581
	public isDisposed(): boolean {
		return this._isDisposed;
	}

	public isDominatedByLongLines(): boolean {
		this._assertNotDisposed();
P
Peng Lyu 已提交
582 583 584 585
		if (this.isTooLargeForTokenization()) {
			// Cannot word wrap huge files anyways, so it doesn't really matter
			return false;
		}
A
Alex Dima 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
		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);
	}

602
	public get uri(): URI {
E
Erich Gamma 已提交
603 604
		return this._associatedResource;
	}
A
Alex Dima 已提交
605

A
Alex Dima 已提交
606 607
	//#region Options

608
	public getOptions(): model.TextModelResolvedOptions {
609
		this._assertNotDisposed();
610 611 612
		return this._options;
	}

613 614 615 616 617 618 619
	public getFormattingOptions(): FormattingOptions {
		return {
			tabSize: this._options.indentSize,
			insertSpaces: this._options.insertSpaces
		};
	}

620
	public updateOptions(_newOpts: model.ITextModelUpdateOptions): void {
621
		this._assertNotDisposed();
622
		let tabSize = (typeof _newOpts.tabSize !== 'undefined') ? _newOpts.tabSize : this._options.tabSize;
D
David Lechner 已提交
623
		let indentSize = (typeof _newOpts.indentSize !== 'undefined') ? _newOpts.indentSize : this._options.indentSize;
624 625
		let insertSpaces = (typeof _newOpts.insertSpaces !== 'undefined') ? _newOpts.insertSpaces : this._options.insertSpaces;
		let trimAutoWhitespace = (typeof _newOpts.trimAutoWhitespace !== 'undefined') ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
626

627
		let newOpts = new model.TextModelResolvedOptions({
628
			tabSize: tabSize,
D
David Lechner 已提交
629
			indentSize: indentSize,
630 631 632 633
			insertSpaces: insertSpaces,
			defaultEOL: this._options.defaultEOL,
			trimAutoWhitespace: trimAutoWhitespace
		});
634

635 636
		if (this._options.equals(newOpts)) {
			return;
637
		}
638 639 640 641

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

A
Alex Dima 已提交
642
		this._onDidChangeOptions.fire(e);
643 644
	}

J
Johannes Rieken 已提交
645
	public detectIndentation(defaultInsertSpaces: boolean, defaultTabSize: number): void {
646
		this._assertNotDisposed();
A
Alex Dima 已提交
647
		let guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
648 649
		this.updateOptions({
			insertSpaces: guessedIndentation.insertSpaces,
A
Alex Dima 已提交
650 651
			tabSize: guessedIndentation.tabSize,
			indentSize: guessedIndentation.tabSize, // TODO@Alex: guess indentSize independent of tabSize
652 653 654
		});
	}

A
Alex Dima 已提交
655
	private static _normalizeIndentationFromWhitespace(str: string, indentSize: number, insertSpaces: boolean): string {
656 657 658
		let spacesCnt = 0;
		for (let i = 0; i < str.length; i++) {
			if (str.charAt(i) === '\t') {
A
Alex Dima 已提交
659
				spacesCnt += indentSize;
660 661 662 663 664 665 666
			} else {
				spacesCnt++;
			}
		}

		let result = '';
		if (!insertSpaces) {
A
Alex Dima 已提交
667 668
			let tabsCnt = Math.floor(spacesCnt / indentSize);
			spacesCnt = spacesCnt % indentSize;
669 670 671 672 673 674 675 676 677 678 679 680
			for (let i = 0; i < tabsCnt; i++) {
				result += '\t';
			}
		}

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

		return result;
	}

A
Alex Dima 已提交
681
	public static normalizeIndentation(str: string, indentSize: number, insertSpaces: boolean): string {
682 683 684 685
		let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(str);
		if (firstNonWhitespaceIndex === -1) {
			firstNonWhitespaceIndex = str.length;
		}
A
Alex Dima 已提交
686
		return TextModel._normalizeIndentationFromWhitespace(str.substring(0, firstNonWhitespaceIndex), indentSize, insertSpaces) + str.substring(firstNonWhitespaceIndex);
687 688 689 690
	}

	public normalizeIndentation(str: string): string {
		this._assertNotDisposed();
A
Alex Dima 已提交
691
		return TextModel.normalizeIndentation(str, this._options.indentSize, this._options.insertSpaces);
692 693
	}

A
Alex Dima 已提交
694 695 696 697
	//#endregion

	//#region Reading

E
Erich Gamma 已提交
698
	public getVersionId(): number {
699
		this._assertNotDisposed();
E
Erich Gamma 已提交
700 701 702
		return this._versionId;
	}

A
Alex Dima 已提交
703
	public mightContainRTL(): boolean {
A
Alex Dima 已提交
704
		return this._buffer.mightContainRTL();
A
Alex Dima 已提交
705 706
	}

707 708 709 710 711 712 713
	public mightContainUnusualLineTerminators(): boolean {
		return this._buffer.mightContainUnusualLineTerminators();
	}

	public removeUnusualLineTerminators(selections: Selection[] | null = null): void {
		const matches = this.findMatches(strings.UNUSUAL_LINE_TERMINATORS.source, false, true, false, null, false, Constants.MAX_SAFE_SMALL_INTEGER);
		this._buffer.resetMightContainUnusualLineTerminators();
714
		this.pushEditOperations(selections, matches.map(m => ({ range: m.range, text: null })), () => null);
715 716
	}

717
	public mightContainNonBasicASCII(): boolean {
A
Alex Dima 已提交
718
		return this._buffer.mightContainNonBasicASCII();
719 720
	}

E
Erich Gamma 已提交
721
	public getAlternativeVersionId(): number {
722
		this._assertNotDisposed();
E
Erich Gamma 已提交
723 724 725
		return this._alternativeVersionId;
	}

726 727 728 729 730
	public getInitialUndoRedoSnapshot(): ResourceEditStackSnapshot | null {
		this._assertNotDisposed();
		return this._initialUndoRedoSnapshot;
	}

A
Alex Dima 已提交
731
	public getOffsetAt(rawPosition: IPosition): number {
732
		this._assertNotDisposed();
733
		let position = this._validatePosition(rawPosition.lineNumber, rawPosition.column, StringOffsetValidationType.Relaxed);
A
Alex Dima 已提交
734
		return this._buffer.getOffsetAt(position.lineNumber, position.column);
735 736
	}

737
	public getPositionAt(rawOffset: number): Position {
738
		this._assertNotDisposed();
739
		let offset = (Math.min(this._buffer.getLength(), Math.max(0, rawOffset)));
A
Alex Dima 已提交
740
		return this._buffer.getPositionAt(offset);
741 742
	}

A
Alex Dima 已提交
743
	private _increaseVersionId(): void {
A
Alex Dima 已提交
744
		this._versionId = this._versionId + 1;
E
Erich Gamma 已提交
745
		this._alternativeVersionId = this._versionId;
746 747 748 749
	}

	public _overwriteVersionId(versionId: number): void {
		this._versionId = versionId;
E
Erich Gamma 已提交
750 751
	}

752
	public _overwriteAlternativeVersionId(newAlternativeVersionId: number): void {
E
Erich Gamma 已提交
753 754 755
		this._alternativeVersionId = newAlternativeVersionId;
	}

756 757 758 759
	public _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot: ResourceEditStackSnapshot | null): void {
		this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot;
	}

760
	public getValue(eol?: model.EndOfLinePreference, preserveBOM: boolean = false): string {
A
Alex Dima 已提交
761
		this._assertNotDisposed();
A
Alex Dima 已提交
762 763
		const fullModelRange = this.getFullModelRange();
		const fullModelValue = this.getValueInRange(fullModelRange, eol);
E
Erich Gamma 已提交
764

A
Alex Dima 已提交
765 766 767
		if (preserveBOM) {
			return this._buffer.getBOM() + fullModelValue;
		}
E
Erich Gamma 已提交
768

A
Alex Dima 已提交
769
		return fullModelValue;
E
Erich Gamma 已提交
770 771
	}

772
	public createSnapshot(preserveBOM: boolean = false): model.ITextSnapshot {
773 774 775
		return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
	}

776
	public getValueLength(eol?: model.EndOfLinePreference, preserveBOM: boolean = false): number {
A
Alex Dima 已提交
777 778 779
		this._assertNotDisposed();
		const fullModelRange = this.getFullModelRange();
		const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
E
Erich Gamma 已提交
780

A
Alex Dima 已提交
781 782 783 784 785
		if (preserveBOM) {
			return this._buffer.getBOM().length + fullModelValue;
		}

		return fullModelValue;
E
Erich Gamma 已提交
786 787
	}

788
	public getValueInRange(rawRange: IRange, eol: model.EndOfLinePreference = model.EndOfLinePreference.TextDefined): string {
789
		this._assertNotDisposed();
A
Alex Dima 已提交
790
		return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
791 792
	}

793
	public getValueLengthInRange(rawRange: IRange, eol: model.EndOfLinePreference = model.EndOfLinePreference.TextDefined): number {
794
		this._assertNotDisposed();
A
Alex Dima 已提交
795
		return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
796 797
	}

798 799 800 801 802
	public getCharacterCountInRange(rawRange: IRange, eol: model.EndOfLinePreference = model.EndOfLinePreference.TextDefined): number {
		this._assertNotDisposed();
		return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
	}

A
Alex Dima 已提交
803
	public getLineCount(): number {
804
		this._assertNotDisposed();
A
Alex Dima 已提交
805
		return this._buffer.getLineCount();
E
Erich Gamma 已提交
806 807
	}

J
Johannes Rieken 已提交
808
	public getLineContent(lineNumber: number): string {
809
		this._assertNotDisposed();
E
Erich Gamma 已提交
810
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
811
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
812 813
		}

A
Alex Dima 已提交
814
		return this._buffer.getLineContent(lineNumber);
E
Erich Gamma 已提交
815 816
	}

A
Alex Dima 已提交
817 818 819 820 821 822 823 824 825
	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 已提交
826
	public getLinesContent(): string[] {
827
		this._assertNotDisposed();
A
Alex Dima 已提交
828
		return this._buffer.getLinesContent();
E
Erich Gamma 已提交
829 830 831
	}

	public getEOL(): string {
832
		this._assertNotDisposed();
A
Alex Dima 已提交
833
		return this._buffer.getEOL();
E
Erich Gamma 已提交
834 835
	}

836 837 838 839 840 841 842 843 844
	public getEndOfLineSequence(): model.EndOfLineSequence {
		this._assertNotDisposed();
		return (
			this._buffer.getEOL() === '\n'
				? model.EndOfLineSequence.LF
				: model.EndOfLineSequence.CRLF
		);
	}

J
Johannes Rieken 已提交
845
	public getLineMinColumn(lineNumber: number): number {
846
		this._assertNotDisposed();
E
Erich Gamma 已提交
847 848 849
		return 1;
	}

J
Johannes Rieken 已提交
850
	public getLineMaxColumn(lineNumber: number): number {
851
		this._assertNotDisposed();
E
Erich Gamma 已提交
852
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
853
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
854
		}
A
Alex Dima 已提交
855
		return this._buffer.getLineLength(lineNumber) + 1;
E
Erich Gamma 已提交
856 857 858
	}

	public getLineFirstNonWhitespaceColumn(lineNumber: number): number {
859
		this._assertNotDisposed();
E
Erich Gamma 已提交
860
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
861
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
862
		}
A
Alex Dima 已提交
863
		return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
E
Erich Gamma 已提交
864 865 866
	}

	public getLineLastNonWhitespaceColumn(lineNumber: number): number {
867
		this._assertNotDisposed();
E
Erich Gamma 已提交
868
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
869
			throw new Error('Illegal value for lineNumber');
E
Erich Gamma 已提交
870
		}
A
Alex Dima 已提交
871
		return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
E
Erich Gamma 已提交
872 873
	}

874
	/**
A
Alex Dima 已提交
875 876 877 878
	 * 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 已提交
879
		const linesCount = this._buffer.getLineCount();
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 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 932 933 934 935 936

		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
937
			&& !(range instanceof Selection)
938 939 940 941 942 943 944
		) {
			return range;
		}

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

945
	private _isValidPosition(lineNumber: number, column: number, validationType: StringOffsetValidationType): boolean {
946
		if (typeof lineNumber !== 'number' || typeof column !== 'number') {
947 948
			return false;
		}
949

950
		if (isNaN(lineNumber) || isNaN(column)) {
951 952 953
			return false;
		}

954
		if (lineNumber < 1 || column < 1) {
955 956 957
			return false;
		}

958
		if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
959 960 961
			return false;
		}

962 963
		const lineCount = this._buffer.getLineCount();
		if (lineNumber > lineCount) {
964 965 966
			return false;
		}

967 968 969 970
		if (column === 1) {
			return true;
		}

971 972 973 974 975
		const maxColumn = this.getLineMaxColumn(lineNumber);
		if (column > maxColumn) {
			return false;
		}

976 977 978 979
		if (validationType === StringOffsetValidationType.SurrogatePairs) {
			// !!At this point, column > 1
			const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
			if (strings.isHighSurrogate(charCodeBefore)) {
980
				return false;
981 982 983 984 985 986
			}
		}

		return true;
	}

987
	private _validatePosition(_lineNumber: number, _column: number, validationType: StringOffsetValidationType): Position {
988 989
		const lineNumber = Math.floor((typeof _lineNumber === 'number' && !isNaN(_lineNumber)) ? _lineNumber : 1);
		const column = Math.floor((typeof _column === 'number' && !isNaN(_column)) ? _column : 1);
A
Alex Dima 已提交
990
		const lineCount = this._buffer.getLineCount();
E
Erich Gamma 已提交
991 992

		if (lineNumber < 1) {
993
			return new Position(1, 1);
E
Erich Gamma 已提交
994
		}
995

A
Alex Dima 已提交
996 997
		if (lineNumber > lineCount) {
			return new Position(lineCount, this.getLineMaxColumn(lineCount));
E
Erich Gamma 已提交
998
		}
999 1000 1001 1002 1003 1004 1005 1006 1007 1008

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

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

1009 1010 1011 1012 1013 1014 1015
		if (validationType === StringOffsetValidationType.SurrogatePairs) {
			// If the position would end up in the middle of a high-low surrogate pair,
			// we move it to before the pair
			// !!At this point, column > 1
			const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
			if (strings.isHighSurrogate(charCodeBefore)) {
				return new Position(lineNumber, column - 1);
A
aioute Gao 已提交
1016
			}
E
Erich Gamma 已提交
1017 1018 1019 1020 1021
		}

		return new Position(lineNumber, column);
	}

A
Alex Dima 已提交
1022
	public validatePosition(position: IPosition): Position {
1023
		const validationType = StringOffsetValidationType.SurrogatePairs;
1024
		this._assertNotDisposed();
1025 1026 1027

		// Avoid object allocation and cover most likely case
		if (position instanceof Position) {
1028
			if (this._isValidPosition(position.lineNumber, position.column, validationType)) {
1029 1030 1031 1032
				return position;
			}
		}

1033
		return this._validatePosition(position.lineNumber, position.column, validationType);
1034 1035
	}

1036
	private _isValidRange(range: Range, validationType: StringOffsetValidationType): boolean {
1037 1038 1039 1040 1041
		const startLineNumber = range.startLineNumber;
		const startColumn = range.startColumn;
		const endLineNumber = range.endLineNumber;
		const endColumn = range.endColumn;

1042
		if (!this._isValidPosition(startLineNumber, startColumn, StringOffsetValidationType.Relaxed)) {
1043 1044
			return false;
		}
1045
		if (!this._isValidPosition(endLineNumber, endColumn, StringOffsetValidationType.Relaxed)) {
1046 1047 1048
			return false;
		}

1049 1050 1051
		if (validationType === StringOffsetValidationType.SurrogatePairs) {
			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);
1052

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

1056 1057 1058 1059
			if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
				return true;
			}
			return false;
1060 1061 1062 1063 1064
		}

		return true;
	}

A
Alex Dima 已提交
1065
	public validateRange(_range: IRange): Range {
1066
		const validationType = StringOffsetValidationType.SurrogatePairs;
1067
		this._assertNotDisposed();
1068 1069 1070

		// Avoid object allocation and cover most likely case
		if ((_range instanceof Range) && !(_range instanceof Selection)) {
1071
			if (this._isValidRange(_range, validationType)) {
1072 1073 1074 1075
				return _range;
			}
		}

1076 1077
		const start = this._validatePosition(_range.startLineNumber, _range.startColumn, StringOffsetValidationType.Relaxed);
		const end = this._validatePosition(_range.endLineNumber, _range.endColumn, StringOffsetValidationType.Relaxed);
1078 1079

		const startLineNumber = start.lineNumber;
1080
		const startColumn = start.column;
1081
		const endLineNumber = end.lineNumber;
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
		const endColumn = end.column;

		if (validationType === StringOffsetValidationType.SurrogatePairs) {
			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 new Range(startLineNumber, startColumn, endLineNumber, endColumn);
1093
			}
1094

1095 1096 1097
			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);
1098
			}
1099 1100 1101 1102

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

1105 1106 1107
			if (startInsideSurrogatePair) {
				// only expand range at the start
				return new Range(startLineNumber, startColumn - 1, endLineNumber, endColumn);
1108
			}
1109 1110 1111

			// only expand range at the end
			return new Range(startLineNumber, startColumn, endLineNumber, endColumn + 1);
1112 1113
		}

1114
		return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
E
Erich Gamma 已提交
1115 1116
	}

A
Alex Dima 已提交
1117
	public modifyPosition(rawPosition: IPosition, offset: number): Position {
1118
		this._assertNotDisposed();
1119 1120
		let candidate = this.getOffsetAt(rawPosition) + offset;
		return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
E
Erich Gamma 已提交
1121 1122
	}

1123
	public getFullModelRange(): Range {
1124
		this._assertNotDisposed();
A
Alex Dima 已提交
1125
		const lineCount = this.getLineCount();
E
Erich Gamma 已提交
1126 1127 1128
		return new Range(1, 1, lineCount, this.getLineMaxColumn(lineCount));
	}

P
Peng Lyu 已提交
1129 1130 1131 1132
	private findMatchesLineByLine(searchRange: Range, searchData: SearchData, captureMatches: boolean, limitResultCount: number): model.FindMatch[] {
		return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
	}

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

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
		let searchRanges: Range[] | null = null;

		if (rawSearchScope !== null) {
			if (!Array.isArray(rawSearchScope)) {
				rawSearchScope = [rawSearchScope];
			}

			if (rawSearchScope.every((searchScope: Range) => Range.isIRange(searchScope))) {
				searchRanges = rawSearchScope.map((searchScope: Range) => this.validateRange(searchScope));
			}
		}

		if (searchRanges === null) {
			searchRanges = [this.getFullModelRange()];
E
Erich Gamma 已提交
1150 1151
		}

R
rebornix 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
		searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn);

		const uniqueSearchRanges: Range[] = [];
		uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => {
			if (Range.areIntersecting(prev, curr)) {
				return prev.plusRange(curr);
			}

			uniqueSearchRanges.push(prev);
			return curr;
		}));

1164
		let matchMapper: (value: Range, index: number, array: Range[]) => model.FindMatch[];
A
Alex Dima 已提交
1165
		if (!isRegex && searchString.indexOf('\n') < 0) {
P
Peng Lyu 已提交
1166 1167 1168 1169 1170 1171 1172 1173
			// not regex, not multi line
			const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
			const searchData = searchParams.parseSearchRequest();

			if (!searchData) {
				return [];
			}

1174 1175 1176
			matchMapper = (searchRange: Range) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
		} else {
			matchMapper = (searchRange: Range) => TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchRange, captureMatches, limitResultCount);
P
Peng Lyu 已提交
1177 1178
		}

R
rebornix 已提交
1179
		return uniqueSearchRanges.map(matchMapper).reduce((arr, matches: model.FindMatch[]) => arr.concat(matches), []);
E
Erich Gamma 已提交
1180 1181
	}

A
Alex Dima 已提交
1182
	public findNextMatch(searchString: string, rawSearchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string, captureMatches: boolean): model.FindMatch | null {
1183
		this._assertNotDisposed();
1184
		const searchStart = this.validatePosition(rawSearchStart);
1185

A
Alex Dima 已提交
1186
		if (!isRegex && searchString.indexOf('\n') < 0) {
1187 1188
			const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators);
			const searchData = searchParams.parseSearchRequest();
A
Alex Dima 已提交
1189 1190 1191 1192
			if (!searchData) {
				return null;
			}

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
			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;
		}

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

A
Alex Dima 已提交
1214
	public findPreviousMatch(searchString: string, rawSearchStart: IPosition, isRegex: boolean, matchCase: boolean, wordSeparators: string, captureMatches: boolean): model.FindMatch | null {
1215
		this._assertNotDisposed();
1216
		const searchStart = this.validatePosition(rawSearchStart);
1217
		return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators), searchStart, captureMatches);
E
Erich Gamma 已提交
1218
	}
A
Alex Dima 已提交
1219 1220 1221

	//#endregion

A
Alex Dima 已提交
1222 1223 1224 1225 1226 1227
	//#region Editing

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

A
Alex Dima 已提交
1228 1229 1230 1231 1232 1233 1234 1235
	public pushEOL(eol: model.EndOfLineSequence): void {
		const currentEOL = (this.getEOL() === '\n' ? model.EndOfLineSequence.LF : model.EndOfLineSequence.CRLF);
		if (currentEOL === eol) {
			return;
		}
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
			this._eventEmitter.beginDeferredEmit();
1236 1237 1238
			if (this._initialUndoRedoSnapshot === null) {
				this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
			}
A
Alex Dima 已提交
1239 1240 1241 1242 1243 1244 1245
			this._commandManager.pushEOL(eol);
		} finally {
			this._eventEmitter.endDeferredEmit();
			this._onDidChangeDecorations.endDeferredEmit();
		}
	}

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
	private _validateEditOperation(rawOperation: model.IIdentifiedSingleEditOperation): model.ValidAnnotatedEditOperation {
		if (rawOperation instanceof model.ValidAnnotatedEditOperation) {
			return rawOperation;
		}
		return new model.ValidAnnotatedEditOperation(
			rawOperation.identifier || null,
			this.validateRange(rawOperation.range),
			rawOperation.text,
			rawOperation.forceMoveMarkers || false,
			rawOperation.isAutoWhitespaceEdit || false,
			rawOperation._isTracked || false
		);
	}

	private _validateEditOperations(rawOperations: model.IIdentifiedSingleEditOperation[]): model.ValidAnnotatedEditOperation[] {
		const result: model.ValidAnnotatedEditOperation[] = [];
		for (let i = 0, len = rawOperations.length; i < len; i++) {
			result[i] = this._validateEditOperation(rawOperations[i]);
		}
		return result;
	}

A
Alex Dima 已提交
1268
	public pushEditOperations(beforeCursorState: Selection[] | null, editOperations: model.IIdentifiedSingleEditOperation[], cursorStateComputer: model.ICursorStateComputer | null): Selection[] | null {
A
Alex Dima 已提交
1269 1270
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
1271
			this._eventEmitter.beginDeferredEmit();
1272
			return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer);
A
Alex Dima 已提交
1273 1274
		} finally {
			this._eventEmitter.endDeferredEmit();
1275
			this._onDidChangeDecorations.endDeferredEmit();
A
Alex Dima 已提交
1276 1277 1278
		}
	}

A
Alex Dima 已提交
1279
	private _pushEditOperations(beforeCursorState: Selection[] | null, editOperations: model.ValidAnnotatedEditOperation[], cursorStateComputer: model.ICursorStateComputer | null): Selection[] | null {
A
Alex Dima 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
		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;
A
Alex Dima 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
			if (beforeCursorState) {
				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;
A
Alex Dima 已提交
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 1335 1336 1337 1338 1339
						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;
						}

1340 1341 1342 1343 1344 1345 1346 1347
						if (
							trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1
							&& editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === '\n'
						) {
							// This edit inserts a new line (and maybe other text) before `trimLine`
							continue;
						}

A
Alex Dima 已提交
1348 1349 1350 1351 1352 1353
						// Looks like we can't trim this line as it would interfere with an incoming edit
						allowTrimLine = false;
						break;
					}

					if (allowTrimLine) {
1354 1355
						const trimRange = new Range(trimLineNumber, 1, trimLineNumber, maxLineColumn);
						editOperations.push(new model.ValidAnnotatedEditOperation(null, trimRange, null, false, false, false));
A
Alex Dima 已提交
1356 1357 1358 1359 1360 1361 1362
					}

				}
			}

			this._trimAutoWhitespaceLines = null;
		}
1363 1364 1365
		if (this._initialUndoRedoSnapshot === null) {
			this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
		}
A
Alex Dima 已提交
1366 1367 1368
		return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer);
	}

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
	_applyUndo(changes: TextChange[], eol: model.EndOfLineSequence, resultingAlternativeVersionId: number, resultingSelection: Selection[] | null): void {
		const edits = changes.map<model.IIdentifiedSingleEditOperation>((change) => {
			const rangeStart = this.getPositionAt(change.newPosition);
			const rangeEnd = this.getPositionAt(change.newEnd);
			return {
				range: new Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
				text: change.oldText
			};
		});
		this._applyUndoRedoEdits(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection);
	}

	_applyRedo(changes: TextChange[], eol: model.EndOfLineSequence, resultingAlternativeVersionId: number, resultingSelection: Selection[] | null): void {
		const edits = changes.map<model.IIdentifiedSingleEditOperation>((change) => {
			const rangeStart = this.getPositionAt(change.oldPosition);
			const rangeEnd = this.getPositionAt(change.oldEnd);
			return {
				range: new Range(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
				text: change.newText
			};
		});
		this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
	}

	private _applyUndoRedoEdits(edits: model.IIdentifiedSingleEditOperation[], eol: model.EndOfLineSequence, isUndoing: boolean, isRedoing: boolean, resultingAlternativeVersionId: number, resultingSelection: Selection[] | null): void {
1394 1395 1396 1397 1398
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
			this._eventEmitter.beginDeferredEmit();
			this._isUndoing = isUndoing;
			this._isRedoing = isRedoing;
1399
			this.applyEdits(edits, false);
1400
			this.setEOL(eol);
1401 1402 1403
			this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
		} finally {
			this._isUndoing = false;
1404
			this._isRedoing = false;
1405 1406 1407 1408 1409
			this._eventEmitter.endDeferredEmit(resultingSelection);
			this._onDidChangeDecorations.endDeferredEmit();
		}
	}

1410 1411 1412 1413
	public applyEdits(operations: model.IIdentifiedSingleEditOperation[]): void;
	public applyEdits(operations: model.IIdentifiedSingleEditOperation[], computeUndoEdits: false): void;
	public applyEdits(operations: model.IIdentifiedSingleEditOperation[], computeUndoEdits: true): model.IValidEditOperation[];
	public applyEdits(rawOperations: model.IIdentifiedSingleEditOperation[], computeUndoEdits: boolean = false): void | model.IValidEditOperation[] {
A
Alex Dima 已提交
1414 1415
		try {
			this._onDidChangeDecorations.beginDeferredEmit();
1416
			this._eventEmitter.beginDeferredEmit();
1417 1418
			const operations = this._validateEditOperations(rawOperations);
			return this._doApplyEdits(operations, computeUndoEdits);
A
Alex Dima 已提交
1419 1420
		} finally {
			this._eventEmitter.endDeferredEmit();
1421
			this._onDidChangeDecorations.endDeferredEmit();
A
Alex Dima 已提交
1422 1423 1424
		}
	}

1425
	private _doApplyEdits(rawOperations: model.ValidAnnotatedEditOperation[], computeUndoEdits: boolean): void | model.IValidEditOperation[] {
1426 1427

		const oldLineCount = this._buffer.getLineCount();
1428
		const result = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits);
1429 1430
		const newLineCount = this._buffer.getLineCount();

A
Alex Dima 已提交
1431 1432 1433
		const contentChanges = result.changes;
		this._trimAutoWhitespaceLines = result.trimAutoWhitespaceLineNumbers;

1434 1435 1436 1437
		if (contentChanges.length !== 0) {
			let rawContentChanges: ModelRawChange[] = [];

			let lineCount = oldLineCount;
A
Alex Dima 已提交
1438
			for (let i = 0, len = contentChanges.length; i < len; i++) {
1439
				const change = contentChanges[i];
A
Alexandru Dima 已提交
1440
				const [eolCount, firstLineLength, lastLineLength] = countEOL(change.text);
1441
				this._tokens.acceptEdit(change.range, eolCount, firstLineLength);
A
Alexandru Dima 已提交
1442
				this._tokens2.acceptEdit(change.range, eolCount, firstLineLength, lastLineLength, change.text.length > 0 ? change.text.charCodeAt(0) : CharCode.Null);
1443
				this._onDidChangeDecorations.fire();
1444 1445 1446 1447 1448 1449
				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;
1450
				const insertingLinesCnt = eolCount;
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
				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 已提交
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
			}

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

1503
		return (result.reverseEdits === null ? undefined : result.reverseEdits);
A
Alex Dima 已提交
1504 1505
	}

A
Alex Dima 已提交
1506 1507
	public undo(): void | Promise<void> {
		return this._undoRedoService.undo(this.uri);
A
Alex Dima 已提交
1508 1509
	}

A
Alex Dima 已提交
1510
	public canUndo(): boolean {
1511
		return this._undoRedoService.canUndo(this.uri);
A
Alex Dima 已提交
1512 1513
	}

A
Alex Dima 已提交
1514 1515
	public redo(): void | Promise<void> {
		return this._undoRedoService.redo(this.uri);
A
Alex Dima 已提交
1516 1517
	}

A
Alex Dima 已提交
1518
	public canRedo(): boolean {
1519
		return this._undoRedoService.canRedo(this.uri);
A
Alex Dima 已提交
1520 1521
	}

A
Alex Dima 已提交
1522
	//#endregion
1523 1524 1525

	//#region Decorations

A
Alex Dima 已提交
1526
	public changeDecorations<T>(callback: (changeAccessor: model.IModelDecorationsChangeAccessor) => T, ownerId: number = 0): T | null {
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
		this._assertNotDisposed();

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

A
Alex Dima 已提交
1537
	private _changeDecorations<T>(ownerId: number, callback: (changeAccessor: model.IModelDecorationsChangeAccessor) => T): T | null {
1538 1539
		let changeAccessor: model.IModelDecorationsChangeAccessor = {
			addDecoration: (range: IRange, options: model.IModelDecorationOptions): string => {
1540 1541 1542 1543 1544
				return this._deltaDecorationsImpl(ownerId, [], [{ range: range, options: options }])[0];
			},
			changeDecoration: (id: string, newRange: IRange): void => {
				this._changeDecorationImpl(id, newRange);
			},
1545
			changeDecorationOptions: (id: string, options: model.IModelDecorationOptions) => {
1546 1547 1548 1549 1550
				this._changeDecorationOptionsImpl(id, _normalizeOptions(options));
			},
			removeDecoration: (id: string): void => {
				this._deltaDecorationsImpl(ownerId, [id], []);
			},
1551
			deltaDecorations: (oldDecorations: string[], newDecorations: model.IModelDeltaDecoration[]): string[] => {
1552 1553 1554 1555 1556 1557 1558
				if (oldDecorations.length === 0 && newDecorations.length === 0) {
					// nothing to do
					return [];
				}
				return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
			}
		};
A
Alex Dima 已提交
1559
		let result: T | null = null;
1560 1561 1562 1563 1564 1565
		try {
			result = callback(changeAccessor);
		} catch (e) {
			onUnexpectedError(e);
		}
		// Invalidate change accessor
A
Alex Dima 已提交
1566 1567 1568 1569 1570
		changeAccessor.addDecoration = invalidFunc;
		changeAccessor.changeDecoration = invalidFunc;
		changeAccessor.changeDecorationOptions = invalidFunc;
		changeAccessor.removeDecoration = invalidFunc;
		changeAccessor.deltaDecorations = invalidFunc;
1571 1572 1573
		return result;
	}

1574
	public deltaDecorations(oldDecorations: string[], newDecorations: model.IModelDeltaDecoration[], ownerId: number = 0): string[] {
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
		this._assertNotDisposed();
		if (!oldDecorations) {
			oldDecorations = [];
		}
		if (oldDecorations.length === 0 && newDecorations.length === 0) {
			// nothing to do
			return [];
		}

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

A
Alex Dima 已提交
1592
	_getTrackedRange(id: string): Range | null {
1593 1594 1595
		return this.getDecorationRange(id);
	}

A
Alex Dima 已提交
1596 1597
	_setTrackedRange(id: string | null, newRange: null, newStickiness: model.TrackedRangeStickiness): null;
	_setTrackedRange(id: string | null, newRange: Range, newStickiness: model.TrackedRangeStickiness): string;
A
Alex Dima 已提交
1598
	_setTrackedRange(id: string | null, newRange: Range | null, newStickiness: model.TrackedRangeStickiness): string | null {
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
		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];
		}
	}

A
Alex Dima 已提交
1641
	public getDecorationOptions(decorationId: string): model.IModelDecorationOptions | null {
1642 1643 1644 1645 1646 1647 1648
		const node = this._decorations[decorationId];
		if (!node) {
			return null;
		}
		return node.options;
	}

A
Alex Dima 已提交
1649
	public getDecorationRange(decorationId: string): Range | null {
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
		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;
	}

1664
	public getLineDecorations(lineNumber: number, ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1665 1666 1667 1668 1669 1670 1671
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			return [];
		}

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

1672
	public getLinesDecorations(_startLineNumber: number, _endLineNumber: number, ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1673 1674 1675 1676 1677 1678 1679
		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);
	}

1680
	public getDecorationsInRange(range: IRange, ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1681 1682 1683 1684
		let validatedRange = this.validateRange(range);
		return this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation);
	}

1685
	public getOverviewRulerDecorations(ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1686 1687 1688 1689 1690
		const versionId = this.getVersionId();
		const result = this._decorationsTree.search(ownerId, filterOutValidation, true, versionId);
		return this._ensureNodesHaveRanges(result);
	}

1691
	public getAllDecorations(ownerId: number = 0, filterOutValidation: boolean = false): model.IModelDecoration[] {
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
		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);
1733
		this._onDidChangeDecorations.checkAffectedAndFire(node.options);
1734 1735 1736 1737 1738 1739 1740 1741
	}

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

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

1745 1746 1747
		this._onDidChangeDecorations.checkAffectedAndFire(node.options);
		this._onDidChangeDecorations.checkAffectedAndFire(options);

1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
		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);
		}
	}

1758
	private _deltaDecorationsImpl(ownerId: number, oldDecorationsIds: string[], newDecorations: model.IModelDeltaDecoration[]): string[] {
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
		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) {

A
Alex Dima 已提交
1770
			let node: IntervalNode | null = null;
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780

			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);
1781
					this._onDidChangeDecorations.checkAffectedAndFire(node.options);
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
				}
			}

			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);
1804
				this._onDidChangeDecorations.checkAffectedAndFire(options);
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821

				this._decorationsTree.insert(node);

				result[newDecorationIndex] = node.id;

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

		return result;
	}

	//#endregion
A
Alex Dima 已提交
1822 1823 1824

	//#region Tokenization

1825
	public setLineTokens(lineNumber: number, tokens: Uint32Array | ArrayBuffer | null): void {
1826 1827 1828 1829
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
			throw new Error('Illegal value for lineNumber');
		}

1830
		this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), tokens, false);
1831 1832
	}

1833 1834 1835 1836 1837 1838 1839 1840 1841
	public setTokens(tokens: MultilineTokens[]): void {
		if (tokens.length === 0) {
			return;
		}

		let ranges: { fromLineNumber: number; toLineNumber: number; }[] = [];

		for (let i = 0, len = tokens.length; i < len; i++) {
			const element = tokens[i];
1842 1843 1844
			let minChangedLineNumber = 0;
			let maxChangedLineNumber = 0;
			let hasChange = false;
1845
			for (let j = 0, lenJ = element.tokens.length; j < lenJ; j++) {
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
				const lineNumber = element.startLineNumber + j;
				if (hasChange) {
					this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], false);
					maxChangedLineNumber = lineNumber;
				} else {
					const lineHasChange = this._tokens.setTokens(this._languageIdentifier.id, lineNumber - 1, this._buffer.getLineLength(lineNumber), element.tokens[j], true);
					if (lineHasChange) {
						hasChange = true;
						minChangedLineNumber = lineNumber;
						maxChangedLineNumber = lineNumber;
					}
				}
			}
			if (hasChange) {
				ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber });
1861 1862 1863
			}
		}

1864 1865 1866
		if (ranges.length > 0) {
			this._emitModelTokensChangedEvent({
				tokenizationSupportChanged: false,
M
Martin Aeschlimann 已提交
1867
				semanticTokensApplied: false,
1868 1869 1870
				ranges: ranges
			});
		}
1871 1872
	}

1873 1874
	public setSemanticTokens(tokens: MultilineTokens2[] | null, isComplete: boolean): void {
		this._tokens2.set(tokens, isComplete);
A
Alexandru Dima 已提交
1875 1876 1877

		this._emitModelTokensChangedEvent({
			tokenizationSupportChanged: false,
M
Martin Aeschlimann 已提交
1878
			semanticTokensApplied: tokens !== null,
A
Alexandru Dima 已提交
1879 1880
			ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }]
		});
A
wip  
Alexandru Dima 已提交
1881 1882
	}

1883 1884 1885 1886
	public hasSemanticTokens(): boolean {
		return this._tokens2.isComplete();
	}

A
Alex Dima 已提交
1887
	public setPartialSemanticTokens(range: Range, tokens: MultilineTokens2[]): void {
1888 1889 1890
		if (this.hasSemanticTokens()) {
			return;
		}
A
Alex Dima 已提交
1891 1892 1893 1894 1895 1896 1897
		const changedRange = this._tokens2.setPartial(range, tokens);

		this._emitModelTokensChangedEvent({
			tokenizationSupportChanged: false,
			semanticTokensApplied: true,
			ranges: [{ fromLineNumber: changedRange.startLineNumber, toLineNumber: changedRange.endLineNumber }]
		});
1898 1899
	}

P
Peng Lyu 已提交
1900
	public tokenizeViewport(startLineNumber: number, endLineNumber: number): void {
1901 1902
		startLineNumber = Math.max(1, startLineNumber);
		endLineNumber = Math.min(this._buffer.getLineCount(), endLineNumber);
A
Alex Dima 已提交
1903
		this._tokenization.tokenizeViewport(startLineNumber, endLineNumber);
P
Peng Lyu 已提交
1904 1905
	}

1906 1907
	public clearTokens(): void {
		this._tokens.flush();
1908 1909
		this._emitModelTokensChangedEvent({
			tokenizationSupportChanged: true,
M
Martin Aeschlimann 已提交
1910
			semanticTokensApplied: false,
1911 1912 1913 1914 1915 1916 1917
			ranges: [{
				fromLineNumber: 1,
				toLineNumber: this._buffer.getLineCount()
			}]
		});
	}

A
wip  
Alexandru Dima 已提交
1918 1919
	public clearSemanticTokens(): void {
		this._tokens2.flush();
1920

1921 1922
		this._emitModelTokensChangedEvent({
			tokenizationSupportChanged: false,
1923
			semanticTokensApplied: false,
1924 1925
			ranges: [{ fromLineNumber: 1, toLineNumber: this.getLineCount() }]
		});
A
wip  
Alexandru Dima 已提交
1926 1927
	}

1928 1929 1930 1931
	private _emitModelTokensChangedEvent(e: IModelTokensChangedEvent): void {
		if (!this._isDisposing) {
			this._onDidChangeTokens.fire(e);
		}
1932 1933 1934 1935
	}

	public resetTokenization(): void {
		this._tokenization.reset();
A
Alex Dima 已提交
1936 1937
	}

A
Alex Dima 已提交
1938 1939
	public forceTokenization(lineNumber: number): void {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
1940
			throw new Error('Illegal value for lineNumber');
A
Alex Dima 已提交
1941 1942
		}

A
Alex Dima 已提交
1943
		this._tokenization.forceTokenization(lineNumber);
A
Alex Dima 已提交
1944 1945 1946
	}

	public isCheapToTokenize(lineNumber: number): boolean {
A
Alex Dima 已提交
1947
		return this._tokenization.isCheapToTokenize(lineNumber);
A
Alex Dima 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
	}

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

	public getLineTokens(lineNumber: number): LineTokens {
		if (lineNumber < 1 || lineNumber > this.getLineCount()) {
1958
			throw new Error('Illegal value for lineNumber');
A
Alex Dima 已提交
1959 1960 1961 1962 1963 1964
		}

		return this._getLineTokens(lineNumber);
	}

	private _getLineTokens(lineNumber: number): LineTokens {
1965
		const lineText = this.getLineContent(lineNumber);
A
Alexandru Dima 已提交
1966 1967
		const syntacticTokens = this._tokens.getTokens(this._languageIdentifier.id, lineNumber - 1, lineText);
		return this._tokens2.addSemanticTokens(lineNumber, syntacticTokens);
A
Alex Dima 已提交
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
	}

	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;

		this._onDidChangeLanguage.fire(e);
		this._onDidChangeLanguageConfiguration.fire({});
	}

A
Alex Dima 已提交
1995 1996
	public getLanguageIdAtPosition(lineNumber: number, column: number): LanguageId {
		const position = this.validatePosition(new Position(lineNumber, column));
1997 1998
		const lineTokens = this.getLineTokens(position.lineNumber);
		return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
A
Alex Dima 已提交
1999 2000 2001 2002
	}

	// Having tokens allows implementing additional helper methods

A
Alex Dima 已提交
2003
	public getWordAtPosition(_position: IPosition): model.IWordAtPosition | null {
A
Alex Dima 已提交
2004 2005 2006 2007
		this._assertNotDisposed();
		const position = this.validatePosition(_position);
		const lineContent = this.getLineContent(position.lineNumber);
		const lineTokens = this._getLineTokens(position.lineNumber);
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
		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
		);
2018 2019
		// Make sure the result touches the original passed in position
		if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
			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
			);
2033 2034
			// Make sure the result touches the original passed in position
			if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {
2035 2036 2037 2038 2039 2040 2041 2042
				return leftBiasedWord;
			}
		}

		return null;
	}

	private static _findLanguageBoundaries(lineTokens: LineTokens, tokenIndex: number): [number, number] {
A
Alex Dima 已提交
2043 2044 2045
		const languageId = lineTokens.getLanguageId(tokenIndex);

		// go left until a different language is hit
A
Alex Dima 已提交
2046
		let startOffset = 0;
A
Alex Dima 已提交
2047 2048 2049 2050 2051
		for (let i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {
			startOffset = lineTokens.getStartOffset(i);
		}

		// go right until a different language is hit
A
Alex Dima 已提交
2052
		let endOffset = lineTokens.getLineContent().length;
A
Alex Dima 已提交
2053 2054 2055 2056
		for (let i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {
			endOffset = lineTokens.getEndOffset(i);
		}

2057
		return [startOffset, endOffset];
A
Alex Dima 已提交
2058 2059
	}

2060
	public getWordUntilPosition(position: IPosition): model.IWordAtPosition {
A
Alex Dima 已提交
2061
		const wordAtPosition = this.getWordAtPosition(position);
A
Alex Dima 已提交
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
		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
		};
	}

A
Alex Dima 已提交
2076
	public findMatchingBracketUp(_bracket: string, _position: IPosition): Range | null {
A
Alex Dima 已提交
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
		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;
		}

2094
		return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, null));
A
Alex Dima 已提交
2095 2096
	}

A
Alex Dima 已提交
2097
	public matchBracket(position: IPosition): [Range, Range] | null {
A
Alex Dima 已提交
2098 2099 2100
		return this._matchBracket(this.validatePosition(position));
	}

A
Alex Dima 已提交
2101
	private _matchBracket(position: Position): [Range, Range] | null {
A
Alex Dima 已提交
2102 2103
		const lineNumber = position.lineNumber;
		const lineTokens = this._getLineTokens(lineNumber);
A
Alex Dima 已提交
2104
		const tokenCount = lineTokens.getCount();
A
Alex Dima 已提交
2105 2106
		const lineText = this._buffer.getLineContent(lineNumber);

2107
		const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
A
Alex Dima 已提交
2108 2109 2110 2111 2112 2113 2114 2115
		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`
2116
			let searchStartOffset = Math.max(0, position.column - 1 - currentModeBrackets.maxBracketLength);
A
Alex Dima 已提交
2117 2118 2119 2120 2121 2122 2123 2124 2125
			for (let i = tokenIndex - 1; i >= 0; i--) {
				const tokenEndOffset = lineTokens.getEndOffset(i);
				if (tokenEndOffset <= searchStartOffset) {
					break;
				}
				if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i))) {
					searchStartOffset = tokenEndOffset;
				}
			}
A
Alex Dima 已提交
2126
			// limit search to not go after `maxBracketLength`
2127
			const searchEndOffset = Math.min(lineText.length, position.column - 1 + currentModeBrackets.maxBracketLength);
A
Alex Dima 已提交
2128

2129 2130
			// it might be the case that [currentTokenStart -> currentTokenEnd] contains multiple brackets
			// `bestResult` will contain the most right-side result
A
Alex Dima 已提交
2131
			let bestResult: [Range, Range] | null = null;
A
Alex Dima 已提交
2132
			while (true) {
2133
				const foundBracket = BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
A
Alex Dima 已提交
2134
				if (!foundBracket) {
2135
					// there are no more brackets in this text
A
Alex Dima 已提交
2136 2137 2138 2139 2140
					break;
				}

				// check that we didn't hit a bracket too far away from position
				if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
2141
					const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
2142
					const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], null);
A
Alex Dima 已提交
2143
					if (r) {
2144 2145 2146
						if (r instanceof BracketSearchCanceled) {
							return null;
						}
2147
						bestResult = r;
A
Alex Dima 已提交
2148 2149 2150 2151 2152
					}
				}

				searchStartOffset = foundBracket.endColumn - 1;
			}
2153 2154 2155 2156

			if (bestResult) {
				return bestResult;
			}
A
Alex Dima 已提交
2157 2158 2159 2160
		}

		// If position is in between two tokens, try also looking in the previous token
		if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
2161 2162
			const prevTokenIndex = tokenIndex - 1;
			const prevModeBrackets = LanguageConfigurationRegistry.getBracketsSupport(lineTokens.getLanguageId(prevTokenIndex));
A
Alex Dima 已提交
2163 2164

			// check that previous token is not to be ignored
2165
			if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) {
A
Alex Dima 已提交
2166
				// limit search in case previous token is very large, there's no need to go beyond `maxBracketLength`
2167
				const searchStartOffset = Math.max(0, position.column - 1 - prevModeBrackets.maxBracketLength);
A
Alex Dima 已提交
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
				let searchEndOffset = Math.min(lineText.length, position.column - 1 + prevModeBrackets.maxBracketLength);
				for (let i = prevTokenIndex + 1; i < tokenCount; i++) {
					const tokenStartOffset = lineTokens.getStartOffset(i);
					if (tokenStartOffset >= searchEndOffset) {
						break;
					}
					if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i))) {
						searchEndOffset = tokenStartOffset;
					}
				}
2178
				const foundBracket = BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
A
Alex Dima 已提交
2179 2180 2181

				// check that we didn't hit a bracket too far away from position
				if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
2182
					const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
2183
					const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], null);
A
Alex Dima 已提交
2184
					if (r) {
2185 2186 2187
						if (r instanceof BracketSearchCanceled) {
							return null;
						}
A
Alex Dima 已提交
2188 2189 2190 2191 2192 2193 2194 2195 2196
						return r;
					}
				}
			}
		}

		return null;
	}

2197
	private _matchFoundBracket(foundBracket: Range, data: RichEditBracket, isOpen: boolean, continueSearchPredicate: ContinueBracketSearchPredicate): [Range, Range] | null | BracketSearchCanceled {
A
Alex Dima 已提交
2198 2199 2200 2201
		if (!data) {
			return null;
		}

2202 2203 2204 2205 2206 2207 2208 2209
		const matched = (
			isOpen
				? this._findMatchingBracketDown(data, foundBracket.getEndPosition(), continueSearchPredicate)
				: this._findMatchingBracketUp(data, foundBracket.getStartPosition(), continueSearchPredicate)
		);

		if (!matched) {
			return null;
A
Alex Dima 已提交
2210 2211
		}

2212 2213 2214 2215 2216
		if (matched instanceof BracketSearchCanceled) {
			return matched;
		}

		return [foundBracket, matched];
A
Alex Dima 已提交
2217 2218
	}

2219
	private _findMatchingBracketUp(bracket: RichEditBracket, position: Position, continueSearchPredicate: ContinueBracketSearchPredicate): Range | null | BracketSearchCanceled {
A
Alex Dima 已提交
2220 2221 2222 2223 2224 2225
		// console.log('_findMatchingBracketUp: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));

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

2226 2227
		let totalCallCount = 0;
		const searchPrevMatchingBracketInRange = (lineNumber: number, lineText: string, searchStartOffset: number, searchEndOffset: number): Range | null | BracketSearchCanceled => {
2228
			while (true) {
2229 2230 2231
				if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
					return BracketSearchCanceled.INSTANCE;
				}
2232 2233 2234 2235 2236 2237
				const r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (!r) {
					break;
				}

				const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
2238
				if (bracket.isOpen(hitText)) {
2239
					count++;
2240
				} else if (bracket.isClose(hitText)) {
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
					count--;
				}

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

				searchEndOffset = r.startColumn - 1;
			}

			return null;
		};

A
Alex Dima 已提交
2254 2255 2256 2257 2258 2259
		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;
2260 2261
			let searchStartOffset = lineText.length;
			let searchEndOffset = lineText.length;
A
Alex Dima 已提交
2262 2263
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
2264 2265
				searchStartOffset = position.column - 1;
				searchEndOffset = position.column - 1;
A
Alex Dima 已提交
2266 2267
			}

2268
			let prevSearchInToken = true;
A
Alex Dima 已提交
2269
			for (; tokenIndex >= 0; tokenIndex--) {
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
				const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));

				if (searchInToken) {
					// this token should be searched
					if (prevSearchInToken) {
						// the previous token should be searched, simply extend searchStartOffset
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
					} else {
						// the previous token should not be searched
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					}
				} else {
					// this token should not be searched
					if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
A
Alex Dima 已提交
2287 2288 2289 2290 2291
							return r;
						}
					}
				}

2292 2293 2294 2295 2296 2297 2298 2299
				prevSearchInToken = searchInToken;
			}

			if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
				const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (r) {
					return r;
				}
A
Alex Dima 已提交
2300 2301 2302 2303 2304 2305
			}
		}

		return null;
	}

2306
	private _findMatchingBracketDown(bracket: RichEditBracket, position: Position, continueSearchPredicate: ContinueBracketSearchPredicate): Range | null | BracketSearchCanceled {
A
Alex Dima 已提交
2307 2308 2309 2310 2311 2312
		// console.log('_findMatchingBracketDown: ', 'bracket: ', JSON.stringify(bracket), 'startPosition: ', String(position));

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

2313 2314
		let totalCallCount = 0;
		const searchNextMatchingBracketInRange = (lineNumber: number, lineText: string, searchStartOffset: number, searchEndOffset: number): Range | null | BracketSearchCanceled => {
2315
			while (true) {
2316 2317 2318
				if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
					return BracketSearchCanceled.INSTANCE;
				}
2319 2320 2321 2322 2323 2324
				const r = BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (!r) {
					break;
				}

				const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
2325
				if (bracket.isOpen(hitText)) {
2326
					count++;
2327
				} else if (bracket.isClose(hitText)) {
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
					count--;
				}

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

				searchStartOffset = r.endColumn - 1;
			}

			return null;
		};

		const lineCount = this.getLineCount();
		for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
A
Alex Dima 已提交
2343 2344 2345 2346 2347 2348
			const lineTokens = this._getLineTokens(lineNumber);
			const tokenCount = lineTokens.getCount();
			const lineText = this._buffer.getLineContent(lineNumber);

			let tokenIndex = 0;
			let searchStartOffset = 0;
2349
			let searchEndOffset = 0;
A
Alex Dima 已提交
2350 2351 2352
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStartOffset = position.column - 1;
2353
				searchEndOffset = position.column - 1;
A
Alex Dima 已提交
2354 2355
			}

2356
			let prevSearchInToken = true;
A
Alex Dima 已提交
2357
			for (; tokenIndex < tokenCount; tokenIndex++) {
2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
				const searchInToken = (lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));

				if (searchInToken) {
					// this token should be searched
					if (prevSearchInToken) {
						// the previous token should be searched, simply extend searchEndOffset
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					} else {
						// the previous token should not be searched
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					}
				} else {
					// this token should not be searched
					if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
A
Alex Dima 已提交
2375 2376 2377 2378 2379
							return r;
						}
					}
				}

2380 2381 2382 2383 2384 2385 2386 2387
				prevSearchInToken = searchInToken;
			}

			if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
				const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (r) {
					return r;
				}
A
Alex Dima 已提交
2388 2389 2390 2391 2392 2393
			}
		}

		return null;
	}

A
Alex Dima 已提交
2394
	public findPrevBracket(_position: IPosition): model.IFoundBracket | null {
A
Alex Dima 已提交
2395 2396 2397
		const position = this.validatePosition(_position);

		let languageId: LanguageId = -1;
A
Alex Dima 已提交
2398
		let modeBrackets: RichEditBrackets | null = null;
A
Alex Dima 已提交
2399 2400 2401 2402 2403 2404
		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;
2405 2406
			let searchStartOffset = lineText.length;
			let searchEndOffset = lineText.length;
A
Alex Dima 已提交
2407 2408
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
2409 2410 2411 2412 2413 2414 2415
				searchStartOffset = position.column - 1;
				searchEndOffset = position.column - 1;
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
				if (languageId !== tokenLanguageId) {
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
				}
A
Alex Dima 已提交
2416 2417
			}

2418
			let prevSearchInToken = true;
A
Alex Dima 已提交
2419 2420 2421 2422
			for (; tokenIndex >= 0; tokenIndex--) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);

				if (languageId !== tokenLanguageId) {
2423 2424 2425 2426 2427 2428 2429 2430
					// language id change!
					if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
							return this._toFoundBracket(modeBrackets, r);
						}
						prevSearchInToken = false;
					}
A
Alex Dima 已提交
2431 2432 2433
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
				}
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453

				const searchInToken = (!!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));

				if (searchInToken) {
					// this token should be searched
					if (prevSearchInToken) {
						// the previous token should be searched, simply extend searchStartOffset
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
					} else {
						// the previous token should not be searched
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					}
				} else {
					// this token should not be searched
					if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
							return this._toFoundBracket(modeBrackets, r);
						}
A
Alex Dima 已提交
2454 2455 2456
					}
				}

2457 2458 2459 2460 2461 2462 2463 2464
				prevSearchInToken = searchInToken;
			}

			if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
				const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (r) {
					return this._toFoundBracket(modeBrackets, r);
				}
A
Alex Dima 已提交
2465 2466 2467 2468 2469 2470
			}
		}

		return null;
	}

A
Alex Dima 已提交
2471
	public findNextBracket(_position: IPosition): model.IFoundBracket | null {
A
Alex Dima 已提交
2472
		const position = this.validatePosition(_position);
2473
		const lineCount = this.getLineCount();
A
Alex Dima 已提交
2474 2475

		let languageId: LanguageId = -1;
A
Alex Dima 已提交
2476
		let modeBrackets: RichEditBrackets | null = null;
2477
		for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
A
Alex Dima 已提交
2478 2479 2480 2481 2482 2483
			const lineTokens = this._getLineTokens(lineNumber);
			const tokenCount = lineTokens.getCount();
			const lineText = this._buffer.getLineContent(lineNumber);

			let tokenIndex = 0;
			let searchStartOffset = 0;
2484
			let searchEndOffset = 0;
A
Alex Dima 已提交
2485 2486 2487
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStartOffset = position.column - 1;
2488 2489 2490 2491 2492 2493
				searchEndOffset = position.column - 1;
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
				if (languageId !== tokenLanguageId) {
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
				}
A
Alex Dima 已提交
2494 2495
			}

2496
			let prevSearchInToken = true;
A
Alex Dima 已提交
2497 2498 2499 2500
			for (; tokenIndex < tokenCount; tokenIndex++) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);

				if (languageId !== tokenLanguageId) {
2501 2502 2503 2504 2505 2506 2507 2508
					// language id change!
					if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
							return this._toFoundBracket(modeBrackets, r);
						}
						prevSearchInToken = false;
					}
A
Alex Dima 已提交
2509 2510 2511
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
				}
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530

				const searchInToken = (!!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
				if (searchInToken) {
					// this token should be searched
					if (prevSearchInToken) {
						// the previous token should be searched, simply extend searchEndOffset
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					} else {
						// the previous token should not be searched
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					}
				} else {
					// this token should not be searched
					if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
							return this._toFoundBracket(modeBrackets, r);
						}
A
Alex Dima 已提交
2531 2532 2533
					}
				}

2534 2535 2536 2537 2538 2539 2540
				prevSearchInToken = searchInToken;
			}

			if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
				const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (r) {
					return this._toFoundBracket(modeBrackets, r);
A
Alex Dima 已提交
2541 2542 2543 2544 2545 2546 2547
				}
			}
		}

		return null;
	}

2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
	public findEnclosingBrackets(_position: IPosition, maxDuration?: number): [Range, Range] | null {
		let continueSearchPredicate: ContinueBracketSearchPredicate;
		if (typeof maxDuration === 'undefined') {
			continueSearchPredicate = null;
		} else {
			const startTime = Date.now();
			continueSearchPredicate = () => {
				return (Date.now() - startTime <= maxDuration);
			};
		}
2558 2559
		const position = this.validatePosition(_position);
		const lineCount = this.getLineCount();
2560
		const savedCounts = new Map<number, number[]>();
A
Alex Dima 已提交
2561

2562
		let counts: number[] = [];
2563 2564 2565 2566 2567 2568 2569
		const resetCounts = (languageId: number, modeBrackets: RichEditBrackets | null) => {
			if (!savedCounts.has(languageId)) {
				let tmp = [];
				for (let i = 0, len = modeBrackets ? modeBrackets.brackets.length : 0; i < len; i++) {
					tmp[i] = 0;
				}
				savedCounts.set(languageId, tmp);
2570
			}
2571
			counts = savedCounts.get(languageId)!;
2572
		};
2573 2574 2575

		let totalCallCount = 0;
		const searchInRange = (modeBrackets: RichEditBrackets, lineNumber: number, lineText: string, searchStartOffset: number, searchEndOffset: number): [Range, Range] | null | BracketSearchCanceled => {
2576
			while (true) {
2577 2578 2579
				if (continueSearchPredicate && (++totalCallCount) % 100 === 0 && !continueSearchPredicate()) {
					return BracketSearchCanceled.INSTANCE;
				}
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
				const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (!r) {
					break;
				}

				const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
				const bracket = modeBrackets.textIsBracket[hitText];
				if (bracket) {
					if (bracket.isOpen(hitText)) {
						counts[bracket.index]++;
					} else if (bracket.isClose(hitText)) {
						counts[bracket.index]--;
					}

					if (counts[bracket.index] === -1) {
2595
						return this._matchFoundBracket(r, bracket, false, continueSearchPredicate);
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
					}
				}

				searchStartOffset = r.endColumn - 1;
			}
			return null;
		};

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

			let tokenIndex = 0;
			let searchStartOffset = 0;
			let searchEndOffset = 0;
			if (lineNumber === position.lineNumber) {
				tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
				searchStartOffset = position.column - 1;
				searchEndOffset = position.column - 1;
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
A
Alex Dima 已提交
2619 2620 2621
				if (languageId !== tokenLanguageId) {
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
2622
					resetCounts(languageId, modeBrackets);
A
Alex Dima 已提交
2623
				}
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
			}

			let prevSearchInToken = true;
			for (; tokenIndex < tokenCount; tokenIndex++) {
				const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);

				if (languageId !== tokenLanguageId) {
					// language id change!
					if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
2635
							return stripBracketSearchCanceled(r);
2636 2637
						}
						prevSearchInToken = false;
A
Alex Dima 已提交
2638
					}
2639 2640
					languageId = tokenLanguageId;
					modeBrackets = LanguageConfigurationRegistry.getBracketsSupport(languageId);
2641
					resetCounts(languageId, modeBrackets);
A
Alex Dima 已提交
2642 2643
				}

2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
				const searchInToken = (!!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex)));
				if (searchInToken) {
					// this token should be searched
					if (prevSearchInToken) {
						// the previous token should be searched, simply extend searchEndOffset
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					} else {
						// the previous token should not be searched
						searchStartOffset = lineTokens.getStartOffset(tokenIndex);
						searchEndOffset = lineTokens.getEndOffset(tokenIndex);
					}
				} else {
					// this token should not be searched
					if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
						const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
						if (r) {
2660
							return stripBracketSearchCanceled(r);
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
						}
					}
				}

				prevSearchInToken = searchInToken;
			}

			if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
				const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
				if (r) {
2671
					return stripBracketSearchCanceled(r);
2672
				}
A
Alex Dima 已提交
2673 2674 2675 2676 2677 2678
			}
		}

		return null;
	}

A
Alex Dima 已提交
2679
	private _toFoundBracket(modeBrackets: RichEditBrackets, r: Range): model.IFoundBracket | null {
A
Alex Dima 已提交
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
		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]
		};
	}

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
	/**
	 * 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 已提交
2729
	private _computeIndentLevel(lineIndex: number): number {
2730
		return TextModel.computeIndentLevel(this._buffer.getLineContent(lineIndex + 1), this._options.tabSize);
A
Alex Dima 已提交
2731 2732
	}

2733
	public getActiveIndentGuide(lineNumber: number, minLineNumber: number, maxLineNumber: number): model.IActiveIndentGuideInfo {
A
Alex Dima 已提交
2734 2735 2736 2737 2738 2739 2740 2741
		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);
A
Alex Dima 已提交
2742
		const offSide = Boolean(foldingRules && foldingRules.offSide);
A
Alex Dima 已提交
2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821

		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;

2822 2823
		let initialIndent = 0;

A
Alex Dima 已提交
2824 2825 2826 2827
		for (let distance = 0; goUp || goDown; distance++) {
			const upLineNumber = lineNumber - distance;
			const downLineNumber = lineNumber + distance;

2828
			if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
A
Alex Dima 已提交
2829 2830
				goUp = false;
			}
2831
			if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
A
Alex Dima 已提交
2832 2833
				goDown = false;
			}
2834 2835 2836 2837 2838
			if (distance > 50000) {
				// stop processing
				goUp = false;
				goDown = false;
			}
A
Alex Dima 已提交
2839

2840
			let upLineIndentLevel: number = -1;
A
Alex Dima 已提交
2841 2842 2843 2844 2845 2846 2847 2848
			if (goUp) {
				// compute indent level going up
				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;
D
David Lechner 已提交
2849
					upLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);
A
Alex Dima 已提交
2850 2851 2852 2853 2854 2855
				} else {
					up_resolveIndents(upLineNumber);
					upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
				}
			}

2856
			let downLineIndentLevel = -1;
A
Alex Dima 已提交
2857 2858 2859 2860 2861 2862 2863 2864
			if (goDown) {
				// compute indent level going down
				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;
D
David Lechner 已提交
2865
					downLineIndentLevel = Math.ceil(currentIndent / this._options.indentSize);
A
Alex Dima 已提交
2866 2867 2868 2869
				} else {
					down_resolveIndents(downLineNumber);
					downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
				}
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
			}

			if (distance === 0) {
				initialIndent = upLineIndentLevel;
				continue;
			}

			if (distance === 1) {
				if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) {
					// This is the beginning of a scope, we have special handling here, since we want the
					// child scope indent to be active, not the parent scope
					goUp = false;
					startLineNumber = downLineNumber;
					endLineNumber = downLineNumber;
					indent = downLineIndentLevel;
					continue;
				}

				if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) {
					// This is the end of a scope, just like above
					goDown = false;
					startLineNumber = upLineNumber;
					endLineNumber = upLineNumber;
					indent = upLineIndentLevel;
					continue;
				}

				startLineNumber = lineNumber;
				endLineNumber = lineNumber;
				indent = initialIndent;
				if (indent === 0) {
					// No need to continue
					return { startLineNumber, endLineNumber, indent };
				}
			}
A
Alex Dima 已提交
2905

2906 2907 2908 2909 2910 2911 2912 2913
			if (goUp) {
				if (upLineIndentLevel >= indent) {
					startLineNumber = upLineNumber;
				} else {
					goUp = false;
				}
			}
			if (goDown) {
A
Alex Dima 已提交
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
				if (downLineIndentLevel >= indent) {
					endLineNumber = downLineNumber;
				} else {
					goDown = false;
				}
			}
		}

		return { startLineNumber, endLineNumber, indent };
	}

A
Alex Dima 已提交
2925 2926 2927 2928 2929
	public getLinesIndentGuides(startLineNumber: number, endLineNumber: number): number[] {
		this._assertNotDisposed();
		const lineCount = this.getLineCount();

		if (startLineNumber < 1 || startLineNumber > lineCount) {
2930
			throw new Error('Illegal value for startLineNumber');
A
Alex Dima 已提交
2931 2932
		}
		if (endLineNumber < 1 || endLineNumber > lineCount) {
2933
			throw new Error('Illegal value for endLineNumber');
A
Alex Dima 已提交
2934 2935 2936
		}

		const foldingRules = LanguageConfigurationRegistry.getFoldingRules(this._languageIdentifier.id);
A
Alex Dima 已提交
2937
		const offSide = Boolean(foldingRules && foldingRules.offSide);
A
Alex Dima 已提交
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955

		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;
D
David Lechner 已提交
2956
				result[resultIndex] = Math.ceil(currentIndent / this._options.indentSize);
A
Alex Dima 已提交
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
				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 已提交
2990 2991 2992 2993 2994
			result[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);

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

A
Alex Dima 已提交
2996 2997 2998 2999
	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 已提交
3000

A
Alex Dima 已提交
3001 3002
		} else if (aboveContentLineIndent < belowContentLineIndent) {
			// we are inside the region above
D
David Lechner 已提交
3003
			return (1 + Math.floor(aboveContentLineIndent / this._options.indentSize));
A
Alex Dima 已提交
3004

A
Alex Dima 已提交
3005 3006
		} else if (aboveContentLineIndent === belowContentLineIndent) {
			// we are in between two regions
D
David Lechner 已提交
3007
			return Math.ceil(belowContentLineIndent / this._options.indentSize);
A
Alex Dima 已提交
3008

A
Alex Dima 已提交
3009
		} else {
A
Alex Dima 已提交
3010

A
Alex Dima 已提交
3011 3012
			if (offSide) {
				// same level as region below
D
David Lechner 已提交
3013
				return Math.ceil(belowContentLineIndent / this._options.indentSize);
A
Alex Dima 已提交
3014 3015
			} else {
				// we are inside the region that ends below
D
David Lechner 已提交
3016
				return (1 + Math.floor(belowContentLineIndent / this._options.indentSize));
A
Alex Dima 已提交
3017
			}
A
Alex Dima 已提交
3018

A
Alex Dima 已提交
3019 3020
		}
	}
A
Alex Dima 已提交
3021

A
Alex Dima 已提交
3022
	//#endregion
3023 3024 3025 3026 3027 3028 3029 3030 3031
}

//#region Decorations

class DecorationsTrees {

	/**
	 * This tree holds decorations that do not show up in the overview ruler.
	 */
3032
	private readonly _decorationsTree0: IntervalTree;
3033 3034 3035 3036

	/**
	 * This tree holds decorations that show up in the overview ruler.
	 */
3037
	private readonly _decorationsTree1: IntervalTree;
3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102

	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 {
3103
	return className.replace(/[^a-z0-9\-_]/gi, ' ');
3104 3105
}

3106
class DecorationOptions implements model.IDecorationOptions {
3107 3108 3109
	readonly color: string | ThemeColor;
	readonly darkColor: string | ThemeColor;

3110
	constructor(options: model.IDecorationOptions) {
J
jrieken 已提交
3111 3112
		this.color = options.color || '';
		this.darkColor = options.darkColor || '';
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122

	}
}

export class ModelDecorationOverviewRulerOptions extends DecorationOptions {
	readonly position: model.OverviewRulerLane;
	private _resolvedColor: string | null;

	constructor(options: model.IModelDecorationOverviewRulerOptions) {
		super(options);
3123
		this._resolvedColor = null;
3124
		this.position = (typeof options.position === 'number' ? options.position : model.OverviewRulerLane.Center);
A
Alex Dima 已提交
3125 3126
	}

A
Alex Dima 已提交
3127
	public getColor(theme: EditorTheme): string {
A
Alex Dima 已提交
3128
		if (!this._resolvedColor) {
3129 3130 3131 3132 3133
			if (theme.type !== 'light' && this.darkColor) {
				this._resolvedColor = this._resolveColor(this.darkColor, theme);
			} else {
				this._resolvedColor = this._resolveColor(this.color, theme);
			}
A
Alex Dima 已提交
3134 3135 3136 3137 3138 3139 3140 3141
		}
		return this._resolvedColor;
	}

	public invalidateCachedColor(): void {
		this._resolvedColor = null;
	}

A
Alex Dima 已提交
3142
	private _resolveColor(color: string | ThemeColor, theme: EditorTheme): string {
A
Alex Dima 已提交
3143 3144 3145 3146 3147
		if (typeof color === 'string') {
			return color;
		}
		let c = color ? theme.getColor(color.id) : null;
		if (!c) {
J
jrieken 已提交
3148
			return '';
A
Alex Dima 已提交
3149 3150
		}
		return c.toString();
3151 3152 3153
	}
}

3154 3155
export class ModelDecorationMinimapOptions extends DecorationOptions {
	readonly position: model.MinimapPosition;
3156 3157
	private _resolvedColor: Color | undefined;

3158 3159 3160 3161 3162

	constructor(options: model.IModelDecorationMinimapOptions) {
		super(options);
		this.position = options.position;
	}
3163

A
Alex Dima 已提交
3164
	public getColor(theme: EditorTheme): Color | undefined {
3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
		if (!this._resolvedColor) {
			if (theme.type !== 'light' && this.darkColor) {
				this._resolvedColor = this._resolveColor(this.darkColor, theme);
			} else {
				this._resolvedColor = this._resolveColor(this.color, theme);
			}
		}

		return this._resolvedColor;
	}

3176 3177 3178 3179
	public invalidateCachedColor(): void {
		this._resolvedColor = undefined;
	}

A
Alex Dima 已提交
3180
	private _resolveColor(color: string | ThemeColor, theme: EditorTheme): Color | undefined {
3181 3182 3183 3184 3185
		if (typeof color === 'string') {
			return Color.fromHex(color);
		}
		return theme.getColor(color.id);
	}
3186 3187
}

3188
export class ModelDecorationOptions implements model.IModelDecorationOptions {
3189 3190 3191

	public static EMPTY: ModelDecorationOptions;

3192
	public static register(options: model.IModelDecorationOptions): ModelDecorationOptions {
3193
		return new ModelDecorationOptions(options);
3194 3195
	}

3196
	public static createDynamic(options: model.IModelDecorationOptions): ModelDecorationOptions {
3197
		return new ModelDecorationOptions(options);
3198 3199
	}

3200
	readonly stickiness: model.TrackedRangeStickiness;
3201
	readonly zIndex: number;
A
Alex Dima 已提交
3202 3203 3204
	readonly className: string | null;
	readonly hoverMessage: IMarkdownString | IMarkdownString[] | null;
	readonly glyphMarginHoverMessage: IMarkdownString | IMarkdownString[] | null;
3205 3206
	readonly isWholeLine: boolean;
	readonly showIfCollapsed: boolean;
3207
	readonly collapseOnReplaceEdit: boolean;
A
Alex Dima 已提交
3208
	readonly overviewRuler: ModelDecorationOverviewRulerOptions | null;
3209
	readonly minimap: ModelDecorationMinimapOptions | null;
A
Alex Dima 已提交
3210 3211
	readonly glyphMarginClassName: string | null;
	readonly linesDecorationsClassName: string | null;
M
Martin Aeschlimann 已提交
3212
	readonly firstLineDecorationClassName: string | null;
A
Alex Dima 已提交
3213 3214
	readonly marginClassName: string | null;
	readonly inlineClassName: string | null;
A
Alex Dima 已提交
3215
	readonly inlineClassNameAffectsLetterSpacing: boolean;
A
Alex Dima 已提交
3216 3217
	readonly beforeContentClassName: string | null;
	readonly afterContentClassName: string | null;
3218

3219
	private constructor(options: model.IModelDecorationOptions) {
3220
		this.stickiness = options.stickiness || model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges;
3221
		this.zIndex = options.zIndex || 0;
3222
		this.className = options.className ? cleanClassName(options.className) : null;
3223 3224
		this.hoverMessage = options.hoverMessage || null;
		this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null;
3225 3226
		this.isWholeLine = options.isWholeLine || false;
		this.showIfCollapsed = options.showIfCollapsed || false;
3227
		this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
3228
		this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
3229
		this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
3230 3231
		this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
		this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
M
Martin Aeschlimann 已提交
3232
		this.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : null;
3233 3234
		this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
		this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
A
Alex Dima 已提交
3235
		this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
3236 3237
		this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
		this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
3238 3239 3240 3241 3242 3243 3244 3245
	}
}
ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({});

/**
 * The order carefully matches the values of the enum.
 */
const TRACKED_RANGE_OPTIONS = [
3246 3247 3248 3249
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges }),
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges }),
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore }),
	ModelDecorationOptions.register({ stickiness: model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter }),
3250 3251
];

3252
function _normalizeOptions(options: model.IModelDecorationOptions): ModelDecorationOptions {
3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
	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;
3266 3267
	private _affectsMinimap: boolean;
	private _affectsOverviewRuler: boolean;
3268 3269 3270 3271 3272

	constructor() {
		super();
		this._deferredCnt = 0;
		this._shouldFire = false;
3273 3274
		this._affectsMinimap = false;
		this._affectsOverviewRuler = false;
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
	}

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

	public endDeferredEmit(): void {
		this._deferredCnt--;
		if (this._deferredCnt === 0) {
			if (this._shouldFire) {
3285 3286 3287 3288
				const event: IModelDecorationsChangedEvent = {
					affectsMinimap: this._affectsMinimap,
					affectsOverviewRuler: this._affectsOverviewRuler,
				};
3289
				this._shouldFire = false;
3290 3291 3292
				this._affectsMinimap = false;
				this._affectsOverviewRuler = false;
				this._actual.fire(event);
3293 3294 3295 3296
			}
		}
	}

3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
	public checkAffectedAndFire(options: ModelDecorationOptions): void {
		if (!this._affectsMinimap) {
			this._affectsMinimap = options.minimap && options.minimap.position ? true : false;
		}
		if (!this._affectsOverviewRuler) {
			this._affectsOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
		}
		this._shouldFire = true;
	}

3307
	public fire(): void {
3308 3309
		this._affectsMinimap = true;
		this._affectsOverviewRuler = true;
3310 3311
		this._shouldFire = true;
	}
E
Erich Gamma 已提交
3312
}
3313 3314

//#endregion
3315 3316 3317

export class DidChangeContentEmitter extends Disposable {

3318 3319 3320 3321 3322 3323 3324
	/**
	 * 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;
3325 3326

	private _deferredCnt: number;
A
Alex Dima 已提交
3327
	private _deferredEvent: InternalModelContentChangeEvent | null;
3328 3329 3330 3331

	constructor() {
		super();
		this._deferredCnt = 0;
3332
		this._deferredEvent = null;
3333 3334 3335 3336 3337 3338
	}

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

3339
	public endDeferredEmit(resultingSelection: Selection[] | null = null): void {
3340 3341
		this._deferredCnt--;
		if (this._deferredCnt === 0) {
3342
			if (this._deferredEvent !== null) {
3343
				this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection;
3344 3345
				const e = this._deferredEvent;
				this._deferredEvent = null;
3346 3347
				this._fastEmitter.fire(e);
				this._slowEmitter.fire(e);
3348 3349 3350 3351 3352 3353
			}
		}
	}

	public fire(e: InternalModelContentChangeEvent): void {
		if (this._deferredCnt > 0) {
3354 3355 3356 3357 3358
			if (this._deferredEvent) {
				this._deferredEvent = this._deferredEvent.merge(e);
			} else {
				this._deferredEvent = e;
			}
3359 3360
			return;
		}
3361 3362
		this._fastEmitter.fire(e);
		this._slowEmitter.fire(e);
3363 3364
	}
}