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

A
Alex Dima 已提交
7
import * as nls from 'vs/nls';
8
import * as network from 'vs/base/common/network';
M
Matt Bierner 已提交
9
import { Event, Emitter } from 'vs/base/common/event';
J
Johannes Rieken 已提交
10
import { MarkdownString } from 'vs/base/common/htmlContent';
11
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
12
import URI from 'vs/base/common/uri';
J
Johannes Rieken 已提交
13
import { TPromise } from 'vs/base/common/winjs.base';
J
Johannes Rieken 已提交
14
import { IMarker, IMarkerService, MarkerSeverity } from 'vs/platform/markers/common/markers';
J
Johannes Rieken 已提交
15
import { Range } from 'vs/editor/common/core/range';
16
import { Selection } from 'vs/editor/common/core/selection';
17
import { TextModel, createTextBuffer } from 'vs/editor/common/model/textModel';
A
Alex Dima 已提交
18
import { IMode, LanguageIdentifier } from 'vs/editor/common/modes';
19
import { IModelService } from 'vs/editor/common/services/modelService';
20
import * as platform from 'vs/base/common/platform';
J
Johannes Rieken 已提交
21
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
22
import { EDITOR_MODEL_DEFAULTS } from 'vs/editor/common/config/editorOptions';
A
Alex Dima 已提交
23
import { PLAINTEXT_LANGUAGE_IDENTIFIER } from 'vs/editor/common/modes/modesRegistry';
24
import { IModelLanguageChangedEvent } from 'vs/editor/common/model/textModelEvents';
A
Alex Dima 已提交
25
import { ClassName } from 'vs/editor/common/model/intervalTree';
26
import { EditOperation } from 'vs/editor/common/core/editOperation';
27
import { themeColorFromId, ThemeColor } from 'vs/platform/theme/common/themeService';
28
import { overviewRulerWarning, overviewRulerError, overviewRulerInfo } from 'vs/editor/common/view/editorColorRegistry';
29
import { ITextModel, IModelDeltaDecoration, IModelDecorationOptions, TrackedRangeStickiness, OverviewRulerLane, DefaultEndOfLine, ITextModelCreationOptions, EndOfLineSequence, IIdentifiedSingleEditOperation, ITextBufferFactory, ITextBuffer, EndOfLinePreference } from 'vs/editor/common/model';
30 31
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import { basename } from 'vs/base/common/paths';
E
Erich Gamma 已提交
32

B
Benjamin Pasero 已提交
33
function MODEL_ID(resource: URI): string {
A
Alex Dima 已提交
34 35 36 37
	return resource.toString();
}

class ModelData implements IDisposable {
A
Alex Dima 已提交
38
	model: ITextModel;
E
Erich Gamma 已提交
39

A
Alex Dima 已提交
40
	private _markerDecorations: string[];
41
	private _modelEventListeners: IDisposable[];
E
Erich Gamma 已提交
42

43
	constructor(
A
Alex Dima 已提交
44 45 46
		model: ITextModel,
		onWillDispose: (model: ITextModel) => void,
		onDidChangeLanguage: (model: ITextModel, e: IModelLanguageChangedEvent) => void
47
	) {
E
Erich Gamma 已提交
48
		this.model = model;
A
Alex Dima 已提交
49 50

		this._markerDecorations = [];
51 52 53 54

		this._modelEventListeners = [];
		this._modelEventListeners.push(model.onWillDispose(() => onWillDispose(model)));
		this._modelEventListeners.push(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
E
Erich Gamma 已提交
55 56 57
	}

	public dispose(): void {
A
Alex Dima 已提交
58
		this._markerDecorations = this.model.deltaDecorations(this._markerDecorations, []);
59
		this._modelEventListeners = dispose(this._modelEventListeners);
E
Erich Gamma 已提交
60
		this.model = null;
A
Alex Dima 已提交
61
	}
E
Erich Gamma 已提交
62

63
	public acceptMarkerDecorations(newDecorations: IModelDeltaDecoration[]): void {
A
Alex Dima 已提交
64
		this._markerDecorations = this.model.deltaDecorations(this._markerDecorations, newDecorations);
E
Erich Gamma 已提交
65
	}
A
Alex Dima 已提交
66
}
E
Erich Gamma 已提交
67

A
Alex Dima 已提交
68 69
class ModelMarkerHandler {

70
	public static setMarkers(modelData: ModelData, markerService: IMarkerService): void {
E
Erich Gamma 已提交
71 72

		// Limit to the first 500 errors/warnings
73
		const markers = markerService.read({ resource: modelData.model.uri, take: 500 });
E
Erich Gamma 已提交
74

75
		let newModelDecorations: IModelDeltaDecoration[] = markers.map((marker) => {
A
Alex Dima 已提交
76 77
			return {
				range: this._createDecorationRange(modelData.model, marker),
E
Erich Gamma 已提交
78 79 80
				options: this._createDecorationOption(marker)
			};
		});
A
Alex Dima 已提交
81 82

		modelData.acceptMarkerDecorations(newModelDecorations);
E
Erich Gamma 已提交
83 84
	}

A
Alex Dima 已提交
85
	private static _createDecorationRange(model: ITextModel, rawMarker: IMarker): Range {
A
Alex Dima 已提交
86
		let marker = model.validateRange(new Range(rawMarker.startLineNumber, rawMarker.startColumn, rawMarker.endLineNumber, rawMarker.endColumn));
87
		let ret: Range = new Range(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn);
E
Erich Gamma 已提交
88
		if (ret.isEmpty()) {
A
Alex Dima 已提交
89
			let word = model.getWordAtPosition(ret.getStartPosition());
E
Erich Gamma 已提交
90
			if (word) {
91
				ret = new Range(ret.startLineNumber, word.startColumn, ret.endLineNumber, word.endColumn);
E
Erich Gamma 已提交
92
			} else {
A
Alex Dima 已提交
93 94
				let maxColumn = model.getLineLastNonWhitespaceColumn(marker.startLineNumber) ||
					model.getLineMaxColumn(marker.startLineNumber);
E
Erich Gamma 已提交
95 96 97

				if (maxColumn === 1) {
					// empty line
98
					// console.warn('marker on empty line:', marker);
E
Erich Gamma 已提交
99 100
				} else if (ret.endColumn >= maxColumn) {
					// behind eol
101
					ret = new Range(ret.startLineNumber, maxColumn - 1, ret.endLineNumber, maxColumn);
E
Erich Gamma 已提交
102 103
				} else {
					// extend marker to width = 1
104
					ret = new Range(ret.startLineNumber, ret.startColumn, ret.endLineNumber, ret.endColumn + 1);
E
Erich Gamma 已提交
105 106 107
				}
			}
		} else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
A
Alex Dima 已提交
108
			let minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
E
Erich Gamma 已提交
109
			if (minColumn < ret.endColumn) {
110
				ret = new Range(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
E
Erich Gamma 已提交
111 112 113 114 115 116
				rawMarker.startColumn = minColumn;
			}
		}
		return ret;
	}

117
	private static _createDecorationOption(marker: IMarker): IModelDecorationOptions {
E
Erich Gamma 已提交
118 119

		let className: string;
120 121
		let color: ThemeColor;
		let darkColor: ThemeColor;
E
Erich Gamma 已提交
122 123

		switch (marker.severity) {
J
Johannes Rieken 已提交
124
			case MarkerSeverity.Hint:
125
				className = ClassName.EditorHintDecoration;
E
Erich Gamma 已提交
126
				break;
J
Johannes Rieken 已提交
127
			case MarkerSeverity.Warning:
A
Alex Dima 已提交
128
				className = ClassName.EditorWarningDecoration;
129 130
				color = themeColorFromId(overviewRulerWarning);
				darkColor = themeColorFromId(overviewRulerWarning);
E
Erich Gamma 已提交
131
				break;
J
Johannes Rieken 已提交
132
			case MarkerSeverity.Info:
133 134 135 136
				className = ClassName.EditorInfoDecoration;
				color = themeColorFromId(overviewRulerInfo);
				darkColor = themeColorFromId(overviewRulerInfo);
				break;
J
Johannes Rieken 已提交
137
			case MarkerSeverity.Error:
E
Erich Gamma 已提交
138
			default:
A
Alex Dima 已提交
139
				className = ClassName.EditorErrorDecoration;
140 141
				color = themeColorFromId(overviewRulerError);
				darkColor = themeColorFromId(overviewRulerError);
E
Erich Gamma 已提交
142 143 144
				break;
		}

J
Johannes Rieken 已提交
145
		let hoverMessage: MarkdownString = null;
146
		let { message, source, relatedInformation } = marker;
E
Erich Gamma 已提交
147

148
		if (typeof message === 'string') {
J
Joao Moreno 已提交
149 150
			message = message.trim();

151
			if (source) {
J
Joao Moreno 已提交
152 153 154 155 156
				if (/\n/g.test(message)) {
					message = nls.localize('diagAndSourceMultiline', "[{0}]\n{1}", source, message);
				} else {
					message = nls.localize('diagAndSource', "[{0}] {1}", source, message);
				}
157
			}
J
Joao Moreno 已提交
158

J
Johannes Rieken 已提交
159
			hoverMessage = new MarkdownString().appendCodeblock('_', message);
160 161 162 163 164 165 166 167 168 169

			if (!isFalsyOrEmpty(relatedInformation)) {
				hoverMessage.appendMarkdown('\n');
				for (const { message, resource, startLineNumber, startColumn } of relatedInformation) {
					hoverMessage.appendMarkdown(
						`* [${basename(resource.path)}(${startLineNumber}, ${startColumn})](${resource.toString(false)}#${startLineNumber},${startColumn}): \`${message}\` \n`
					);
				}
				hoverMessage.appendMarkdown('\n');
			}
170 171
		}

E
Erich Gamma 已提交
172
		return {
173
			stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
E
Erich Gamma 已提交
174
			className,
175
			hoverMessage,
176
			showIfCollapsed: true,
E
Erich Gamma 已提交
177 178 179
			overviewRuler: {
				color,
				darkColor,
180
				position: OverviewRulerLane.Right
E
Erich Gamma 已提交
181 182 183 184 185
			}
		};
	}
}

186 187 188 189 190 191 192 193
interface IRawConfig {
	files?: {
		eol?: any;
	};
	editor?: {
		tabSize?: any;
		insertSpaces?: any;
		detectIndentation?: any;
194
		trimAutoWhitespace?: any;
195 196 197
	};
}

198
const DEFAULT_EOL = (platform.isLinux || platform.isMacintosh) ? DefaultEndOfLine.LF : DefaultEndOfLine.CRLF;
199

E
Erich Gamma 已提交
200
export class ModelServiceImpl implements IModelService {
201
	public _serviceBrand: any;
E
Erich Gamma 已提交
202 203 204

	private _markerService: IMarkerService;
	private _markerServiceSubscription: IDisposable;
205 206
	private _configurationService: IConfigurationService;
	private _configurationServiceSubscription: IDisposable;
E
Erich Gamma 已提交
207

M
Matt Bierner 已提交
208 209 210
	private readonly _onModelAdded: Emitter<ITextModel>;
	private readonly _onModelRemoved: Emitter<ITextModel>;
	private readonly _onModelModeChanged: Emitter<{ model: ITextModel; oldModeId: string; }>;
211

212
	private _modelCreationOptionsByLanguageAndResource: {
213
		[languageAndResource: string]: ITextModelCreationOptions;
214
	};
A
Alex Dima 已提交
215 216 217 218

	/**
	 * All the models known in the system.
	 */
B
Benjamin Pasero 已提交
219
	private _models: { [modelId: string]: ModelData; };
E
Erich Gamma 已提交
220

221
	constructor(
222 223
		@IMarkerService markerService: IMarkerService,
		@IConfigurationService configurationService: IConfigurationService,
224
	) {
E
Erich Gamma 已提交
225
		this._markerService = markerService;
226
		this._configurationService = configurationService;
B
Benjamin Pasero 已提交
227
		this._models = {};
228
		this._modelCreationOptionsByLanguageAndResource = Object.create(null);
A
Alex Dima 已提交
229 230 231
		this._onModelAdded = new Emitter<ITextModel>();
		this._onModelRemoved = new Emitter<ITextModel>();
		this._onModelModeChanged = new Emitter<{ model: ITextModel; oldModeId: string; }>();
B
Benjamin Pasero 已提交
232 233 234 235

		if (this._markerService) {
			this._markerServiceSubscription = this._markerService.onMarkerChanged(this._handleMarkerChange, this);
		}
236

237
		this._configurationServiceSubscription = this._configurationService.onDidChangeConfiguration(e => this._updateModelOptions());
238 239
		this._updateModelOptions();
	}
J
Joao Moreno 已提交
240

241
	private static _readModelOptions(config: IRawConfig, isForSimpleWidget: boolean): ITextModelCreationOptions {
242
		let tabSize = EDITOR_MODEL_DEFAULTS.tabSize;
243 244 245 246
		if (config.editor && typeof config.editor.tabSize !== 'undefined') {
			let parsedTabSize = parseInt(config.editor.tabSize, 10);
			if (!isNaN(parsedTabSize)) {
				tabSize = parsedTabSize;
247
			}
248
		}
249

250
		let insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;
251 252 253
		if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {
			insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));
		}
254

255
		let newDefaultEOL = DEFAULT_EOL;
256
		const eol = config.files && config.files.eol;
257
		if (eol === '\r\n') {
258
			newDefaultEOL = DefaultEndOfLine.CRLF;
259
		} else if (eol === '\n') {
260
			newDefaultEOL = DefaultEndOfLine.LF;
261
		}
262

263
		let trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
264 265 266
		if (config.editor && typeof config.editor.trimAutoWhitespace !== 'undefined') {
			trimAutoWhitespace = (config.editor.trimAutoWhitespace === 'false' ? false : Boolean(config.editor.trimAutoWhitespace));
		}
267

268
		let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
269 270 271
		if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {
			detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));
		}
272

273
		return {
274
			isForSimpleWidget: isForSimpleWidget,
275 276 277 278 279
			tabSize: tabSize,
			insertSpaces: insertSpaces,
			detectIndentation: detectIndentation,
			defaultEOL: newDefaultEOL,
			trimAutoWhitespace: trimAutoWhitespace
280
		};
E
Erich Gamma 已提交
281 282
	}

283
	public getCreationOptions(language: string, resource: URI, isForSimpleWidget: boolean): ITextModelCreationOptions {
284
		let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];
285
		if (!creationOptions) {
286
			creationOptions = ModelServiceImpl._readModelOptions(this._configurationService.getValue({ overrideIdentifier: language, resource }), isForSimpleWidget);
287
			this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;
288 289
		}
		return creationOptions;
290 291
	}

292
	private _updateModelOptions(): void {
293 294
		let oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
		this._modelCreationOptionsByLanguageAndResource = Object.create(null);
295

296
		// Update options on all models
A
Alex Dima 已提交
297 298 299 300
		let keys = Object.keys(this._models);
		for (let i = 0, len = keys.length; i < len; i++) {
			let modelId = keys[i];
			let modelData = this._models[modelId];
301
			const language = modelData.model.getLanguageIdentifier().language;
302 303
			const uri = modelData.model.uri;
			const oldOptions = oldOptionsByLanguageAndResource[language + uri];
304
			const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
305 306 307
			ModelServiceImpl._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
		}
	}
308

A
Alex Dima 已提交
309
	private static _setModelOptionsForModel(model: ITextModel, newOptions: ITextModelCreationOptions, currentOptions: ITextModelCreationOptions): void {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
		if (currentOptions
			&& (currentOptions.detectIndentation === newOptions.detectIndentation)
			&& (currentOptions.insertSpaces === newOptions.insertSpaces)
			&& (currentOptions.tabSize === newOptions.tabSize)
			&& (currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace)
		) {
			// Same indent opts, no need to touch the model
			return;
		}

		if (newOptions.detectIndentation) {
			model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
			model.updateOptions({
				trimAutoWhitespace: newOptions.trimAutoWhitespace
			});
		} else {
			model.updateOptions({
				insertSpaces: newOptions.insertSpaces,
				tabSize: newOptions.tabSize,
				trimAutoWhitespace: newOptions.trimAutoWhitespace
			});
331
		}
332 333
	}

E
Erich Gamma 已提交
334
	public dispose(): void {
B
Benjamin Pasero 已提交
335
		if (this._markerServiceSubscription) {
E
Erich Gamma 已提交
336 337
			this._markerServiceSubscription.dispose();
		}
338
		this._configurationServiceSubscription.dispose();
E
Erich Gamma 已提交
339 340 341
	}

	private _handleMarkerChange(changedResources: URI[]): void {
A
Alex Dima 已提交
342 343 344 345
		changedResources.forEach((resource) => {
			let modelId = MODEL_ID(resource);
			let modelData = this._models[modelId];
			if (!modelData) {
E
Erich Gamma 已提交
346 347
				return;
			}
348
			ModelMarkerHandler.setMarkers(modelData, this._markerService);
E
Erich Gamma 已提交
349 350 351
		});
	}

A
Alex Dima 已提交
352
	private _cleanUp(model: ITextModel): void {
S
Sandeep Somavarapu 已提交
353 354
		// clean up markers for internal, transient models
		if (model.uri.scheme === network.Schemas.inMemory
B
Benjamin Pasero 已提交
355 356 357 358 359
			|| model.uri.scheme === network.Schemas.internal
			|| model.uri.scheme === network.Schemas.vscode) {
			if (this._markerService) {
				this._markerService.read({ resource: model.uri }).map(marker => marker.owner).forEach(owner => this._markerService.remove(owner, [model.uri]));
			}
S
Sandeep Somavarapu 已提交
360
		}
361 362 363

		// clean up cache
		delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageIdentifier().language + model.uri];
S
Sandeep Somavarapu 已提交
364 365
	}

E
Erich Gamma 已提交
366 367
	// --- begin IModelService

368
	private _createModelData(value: string | ITextBufferFactory, languageIdentifier: LanguageIdentifier, resource: URI, isForSimpleWidget: boolean): ModelData {
A
Alex Dima 已提交
369
		// create & save the model
370
		const options = this.getCreationOptions(languageIdentifier.language, resource, isForSimpleWidget);
371 372
		const model: TextModel = new TextModel(value, options, languageIdentifier, resource);
		const modelId = MODEL_ID(model.uri);
E
Erich Gamma 已提交
373 374 375

		if (this._models[modelId]) {
			// There already exists a model with this id => this is a programmer error
376
			throw new Error('ModelService: Cannot add model because it already exists!');
E
Erich Gamma 已提交
377 378
		}

379
		const modelData = new ModelData(
380 381 382 383
			model,
			(model) => this._onWillDispose(model),
			(model, e) => this._onDidChangeLanguage(model, e)
		);
A
Alex Dima 已提交
384
		this._models[modelId] = modelData;
E
Erich Gamma 已提交
385

A
Alex Dima 已提交
386
		return modelData;
E
Erich Gamma 已提交
387 388
	}

389
	public updateModel(model: ITextModel, value: string | ITextBufferFactory): void {
390
		const options = this.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
391
		const textBuffer = createTextBuffer(value, options.defaultEOL);
392 393

		// Return early if the text is already set in that form
394
		if (model.equalsTextBuffer(textBuffer)) {
395 396
			return;
		}
397 398

		// Otherwise find a diff between the values and update model
399
		model.setEOL(textBuffer.getEOL() === '\r\n' ? EndOfLineSequence.CRLF : EndOfLineSequence.LF);
400 401
		model.pushEditOperations(
			[new Selection(1, 1, 1, 1)],
402
			ModelServiceImpl._computeEdits(model, textBuffer),
403
			(inverseEditOperations: IIdentifiedSingleEditOperation[]) => [new Selection(1, 1, 1, 1)]
404
		);
405 406
	}

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
	private static _commonPrefix(a: ILineSequence, aLen: number, aDelta: number, b: ILineSequence, bLen: number, bDelta: number): number {
		const maxResult = Math.min(aLen, bLen);

		let result = 0;
		for (let i = 0; i < maxResult && a.getLineContent(aDelta + i) === b.getLineContent(bDelta + i); i++) {
			result++;
		}
		return result;
	}

	private static _commonSuffix(a: ILineSequence, aLen: number, aDelta: number, b: ILineSequence, bLen: number, bDelta: number): number {
		const maxResult = Math.min(aLen, bLen);

		let result = 0;
		for (let i = 0; i < maxResult && a.getLineContent(aDelta + aLen - i) === b.getLineContent(bDelta + bLen - i); i++) {
			result++;
		}
		return result;
	}

427 428 429
	/**
	 * Compute edits to bring `model` to the state of `textSource`.
	 */
430
	public static _computeEdits(model: ITextModel, textBuffer: ITextBuffer): IIdentifiedSingleEditOperation[] {
431
		const modelLineCount = model.getLineCount();
432 433
		const textBufferLineCount = textBuffer.getLineCount();
		const commonPrefix = this._commonPrefix(model, modelLineCount, 1, textBuffer, textBufferLineCount, 1);
434

435 436 437 438
		if (modelLineCount === textBufferLineCount && commonPrefix === modelLineCount) {
			// equality case
			return [];
		}
439

440
		const commonSuffix = this._commonSuffix(model, modelLineCount - commonPrefix, commonPrefix, textBuffer, textBufferLineCount - commonPrefix, commonPrefix);
441

442 443 444 445 446 447 448 449 450 451
		let oldRange: Range, newRange: Range;
		if (commonSuffix > 0) {
			oldRange = new Range(commonPrefix + 1, 1, modelLineCount - commonSuffix + 1, 1);
			newRange = new Range(commonPrefix + 1, 1, textBufferLineCount - commonSuffix + 1, 1);
		} else if (commonPrefix > 0) {
			oldRange = new Range(commonPrefix, model.getLineMaxColumn(commonPrefix), modelLineCount, model.getLineMaxColumn(modelLineCount));
			newRange = new Range(commonPrefix, 1 + textBuffer.getLineLength(commonPrefix), textBufferLineCount, 1 + textBuffer.getLineLength(textBufferLineCount));
		} else {
			oldRange = new Range(1, 1, modelLineCount, model.getLineMaxColumn(modelLineCount));
			newRange = new Range(1, 1, textBufferLineCount, 1 + textBuffer.getLineLength(textBufferLineCount));
452 453
		}

454
		return [EditOperation.replace(oldRange, textBuffer.getValueInRange(newRange, EndOfLinePreference.TextDefined))];
455 456
	}

457
	public createModel(value: string | ITextBufferFactory, modeOrPromise: TPromise<IMode> | IMode, resource: URI, isForSimpleWidget: boolean = false): ITextModel {
458 459 460
		let modelData: ModelData;

		if (!modeOrPromise || TPromise.is(modeOrPromise)) {
461
			modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_IDENTIFIER, resource, isForSimpleWidget);
462 463
			this.setMode(modelData.model, modeOrPromise);
		} else {
464
			modelData = this._createModelData(value, modeOrPromise.getLanguageIdentifier(), resource, isForSimpleWidget);
465
		}
E
Erich Gamma 已提交
466

A
Alex Dima 已提交
467 468
		// handle markers (marker service => model)
		if (this._markerService) {
469
			ModelMarkerHandler.setMarkers(modelData, this._markerService);
E
Erich Gamma 已提交
470 471
		}

A
Alex Dima 已提交
472
		this._onModelAdded.fire(modelData.model);
E
Erich Gamma 已提交
473

A
Alex Dima 已提交
474
		return modelData.model;
E
Erich Gamma 已提交
475 476
	}

A
Alex Dima 已提交
477
	public setMode(model: ITextModel, modeOrPromise: TPromise<IMode> | IMode): void {
478 479 480 481 482 483
		if (!modeOrPromise) {
			return;
		}
		if (TPromise.is(modeOrPromise)) {
			modeOrPromise.then((mode) => {
				if (!model.isDisposed()) {
A
Alex Dima 已提交
484
					model.setMode(mode.getLanguageIdentifier());
485 486 487
				}
			});
		} else {
A
Alex Dima 已提交
488
			model.setMode(modeOrPromise.getLanguageIdentifier());
489 490 491
		}
	}

J
Johannes Rieken 已提交
492
	public destroyModel(resource: URI): void {
A
Alex Dima 已提交
493 494 495 496
		// We need to support that not all models get disposed through this service (i.e. model.dispose() should work!)
		let modelData = this._models[MODEL_ID(resource)];
		if (!modelData) {
			return;
E
Erich Gamma 已提交
497
		}
A
Alex Dima 已提交
498
		modelData.model.dispose();
E
Erich Gamma 已提交
499 500
	}

A
Alex Dima 已提交
501 502
	public getModels(): ITextModel[] {
		let ret: ITextModel[] = [];
A
Alex Dima 已提交
503 504 505 506 507

		let keys = Object.keys(this._models);
		for (let i = 0, len = keys.length; i < len; i++) {
			let modelId = keys[i];
			ret.push(this._models[modelId].model);
E
Erich Gamma 已提交
508
		}
A
Alex Dima 已提交
509

E
Erich Gamma 已提交
510 511 512
		return ret;
	}

A
Alex Dima 已提交
513
	public getModel(resource: URI): ITextModel {
A
Alex Dima 已提交
514 515 516 517
		let modelId = MODEL_ID(resource);
		let modelData = this._models[modelId];
		if (!modelData) {
			return null;
E
Erich Gamma 已提交
518
		}
A
Alex Dima 已提交
519
		return modelData.model;
E
Erich Gamma 已提交
520 521
	}

A
Alex Dima 已提交
522
	public get onModelAdded(): Event<ITextModel> {
523
		return this._onModelAdded ? this._onModelAdded.event : null;
E
Erich Gamma 已提交
524 525
	}

A
Alex Dima 已提交
526
	public get onModelRemoved(): Event<ITextModel> {
527
		return this._onModelRemoved ? this._onModelRemoved.event : null;
E
Erich Gamma 已提交
528 529
	}

A
Alex Dima 已提交
530
	public get onModelModeChanged(): Event<{ model: ITextModel; oldModeId: string; }> {
531
		return this._onModelModeChanged ? this._onModelModeChanged.event : null;
E
Erich Gamma 已提交
532 533 534 535
	}

	// --- end IModelService

A
Alex Dima 已提交
536
	private _onWillDispose(model: ITextModel): void {
537
		let modelId = MODEL_ID(model.uri);
A
Alex Dima 已提交
538 539 540 541 542
		let modelData = this._models[modelId];

		delete this._models[modelId];
		modelData.dispose();

543
		this._cleanUp(model);
A
Alex Dima 已提交
544 545 546
		this._onModelRemoved.fire(model);
	}

A
Alex Dima 已提交
547
	private _onDidChangeLanguage(model: ITextModel, e: IModelLanguageChangedEvent): void {
548 549
		const oldModeId = e.oldLanguage;
		const newModeId = model.getLanguageIdentifier().language;
550 551
		const oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget);
		const newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget);
552 553
		ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions);
		this._onModelModeChanged.fire({ model, oldModeId });
E
Erich Gamma 已提交
554 555
	}
}
556 557 558 559

export interface ILineSequence {
	getLineContent(lineNumber: number): string;
}