modelServiceImpl.ts 19.9 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';
E
Erich Gamma 已提交
30

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

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

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

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

		this._markerDecorations = [];
49 50 51 52

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

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

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

A
Alex Dima 已提交
66 67
class ModelMarkerHandler {

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

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

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

		modelData.acceptMarkerDecorations(newModelDecorations);
E
Erich Gamma 已提交
81 82
	}

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

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

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

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

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

J
Johannes Rieken 已提交
143
		let hoverMessage: MarkdownString = null;
A
Alex Dima 已提交
144
		let { message, source } = marker;
E
Erich Gamma 已提交
145

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

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

J
Johannes Rieken 已提交
157
			hoverMessage = new MarkdownString().appendCodeblock('_', message);
158 159
		}

E
Erich Gamma 已提交
160
		return {
161
			stickiness: TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
E
Erich Gamma 已提交
162
			className,
163
			hoverMessage,
164
			showIfCollapsed: true,
E
Erich Gamma 已提交
165 166 167
			overviewRuler: {
				color,
				darkColor,
168
				position: OverviewRulerLane.Right
E
Erich Gamma 已提交
169 170 171 172 173
			}
		};
	}
}

174 175 176 177 178 179 180 181
interface IRawConfig {
	files?: {
		eol?: any;
	};
	editor?: {
		tabSize?: any;
		insertSpaces?: any;
		detectIndentation?: any;
182
		trimAutoWhitespace?: any;
183 184 185
	};
}

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

E
Erich Gamma 已提交
188
export class ModelServiceImpl implements IModelService {
189
	public _serviceBrand: any;
E
Erich Gamma 已提交
190 191 192

	private _markerService: IMarkerService;
	private _markerServiceSubscription: IDisposable;
193 194
	private _configurationService: IConfigurationService;
	private _configurationServiceSubscription: IDisposable;
E
Erich Gamma 已提交
195

M
Matt Bierner 已提交
196 197 198
	private readonly _onModelAdded: Emitter<ITextModel>;
	private readonly _onModelRemoved: Emitter<ITextModel>;
	private readonly _onModelModeChanged: Emitter<{ model: ITextModel; oldModeId: string; }>;
199

200
	private _modelCreationOptionsByLanguageAndResource: {
201
		[languageAndResource: string]: ITextModelCreationOptions;
202
	};
A
Alex Dima 已提交
203 204 205 206

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

209
	constructor(
210 211
		@IMarkerService markerService: IMarkerService,
		@IConfigurationService configurationService: IConfigurationService,
212
	) {
E
Erich Gamma 已提交
213
		this._markerService = markerService;
214
		this._configurationService = configurationService;
B
Benjamin Pasero 已提交
215
		this._models = {};
216
		this._modelCreationOptionsByLanguageAndResource = Object.create(null);
A
Alex Dima 已提交
217 218 219
		this._onModelAdded = new Emitter<ITextModel>();
		this._onModelRemoved = new Emitter<ITextModel>();
		this._onModelModeChanged = new Emitter<{ model: ITextModel; oldModeId: string; }>();
B
Benjamin Pasero 已提交
220 221 222 223

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

225
		this._configurationServiceSubscription = this._configurationService.onDidChangeConfiguration(e => this._updateModelOptions());
226 227
		this._updateModelOptions();
	}
J
Joao Moreno 已提交
228

229
	private static _readModelOptions(config: IRawConfig, isForSimpleWidget: boolean): ITextModelCreationOptions {
230
		let tabSize = EDITOR_MODEL_DEFAULTS.tabSize;
231 232 233 234
		if (config.editor && typeof config.editor.tabSize !== 'undefined') {
			let parsedTabSize = parseInt(config.editor.tabSize, 10);
			if (!isNaN(parsedTabSize)) {
				tabSize = parsedTabSize;
235
			}
236
		}
237

238
		let insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;
239 240 241
		if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {
			insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));
		}
242

243
		let newDefaultEOL = DEFAULT_EOL;
244
		const eol = config.files && config.files.eol;
245
		if (eol === '\r\n') {
246
			newDefaultEOL = DefaultEndOfLine.CRLF;
247
		} else if (eol === '\n') {
248
			newDefaultEOL = DefaultEndOfLine.LF;
249
		}
250

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

256
		let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
257 258 259
		if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {
			detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));
		}
260

261
		return {
262
			isForSimpleWidget: isForSimpleWidget,
263 264 265 266 267
			tabSize: tabSize,
			insertSpaces: insertSpaces,
			detectIndentation: detectIndentation,
			defaultEOL: newDefaultEOL,
			trimAutoWhitespace: trimAutoWhitespace
268
		};
E
Erich Gamma 已提交
269 270
	}

271
	public getCreationOptions(language: string, resource: URI, isForSimpleWidget: boolean): ITextModelCreationOptions {
272
		let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];
273
		if (!creationOptions) {
274
			creationOptions = ModelServiceImpl._readModelOptions(this._configurationService.getValue({ overrideIdentifier: language, resource }), isForSimpleWidget);
275
			this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;
276 277
		}
		return creationOptions;
278 279
	}

280
	private _updateModelOptions(): void {
281 282
		let oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
		this._modelCreationOptionsByLanguageAndResource = Object.create(null);
283

284
		// Update options on all models
A
Alex Dima 已提交
285 286 287 288
		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];
289
			const language = modelData.model.getLanguageIdentifier().language;
290 291
			const uri = modelData.model.uri;
			const oldOptions = oldOptionsByLanguageAndResource[language + uri];
292
			const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
293 294 295
			ModelServiceImpl._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
		}
	}
296

A
Alex Dima 已提交
297
	private static _setModelOptionsForModel(model: ITextModel, newOptions: ITextModelCreationOptions, currentOptions: ITextModelCreationOptions): void {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
		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
			});
319
		}
320 321
	}

E
Erich Gamma 已提交
322
	public dispose(): void {
B
Benjamin Pasero 已提交
323
		if (this._markerServiceSubscription) {
E
Erich Gamma 已提交
324 325
			this._markerServiceSubscription.dispose();
		}
326
		this._configurationServiceSubscription.dispose();
E
Erich Gamma 已提交
327 328 329
	}

	private _handleMarkerChange(changedResources: URI[]): void {
A
Alex Dima 已提交
330 331 332 333
		changedResources.forEach((resource) => {
			let modelId = MODEL_ID(resource);
			let modelData = this._models[modelId];
			if (!modelData) {
E
Erich Gamma 已提交
334 335
				return;
			}
336
			ModelMarkerHandler.setMarkers(modelData, this._markerService);
E
Erich Gamma 已提交
337 338 339
		});
	}

A
Alex Dima 已提交
340
	private _cleanUp(model: ITextModel): void {
S
Sandeep Somavarapu 已提交
341 342
		// clean up markers for internal, transient models
		if (model.uri.scheme === network.Schemas.inMemory
B
Benjamin Pasero 已提交
343 344 345 346 347
			|| 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 已提交
348
		}
349 350 351

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

E
Erich Gamma 已提交
354 355
	// --- begin IModelService

356
	private _createModelData(value: string | ITextBufferFactory, languageIdentifier: LanguageIdentifier, resource: URI, isForSimpleWidget: boolean): ModelData {
A
Alex Dima 已提交
357
		// create & save the model
358
		const options = this.getCreationOptions(languageIdentifier.language, resource, isForSimpleWidget);
359 360
		const model: TextModel = new TextModel(value, options, languageIdentifier, resource);
		const modelId = MODEL_ID(model.uri);
E
Erich Gamma 已提交
361 362 363

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

367
		const modelData = new ModelData(
368 369 370 371
			model,
			(model) => this._onWillDispose(model),
			(model, e) => this._onDidChangeLanguage(model, e)
		);
A
Alex Dima 已提交
372
		this._models[modelId] = modelData;
E
Erich Gamma 已提交
373

A
Alex Dima 已提交
374
		return modelData;
E
Erich Gamma 已提交
375 376
	}

377
	public updateModel(model: ITextModel, value: string | ITextBufferFactory): void {
378
		const options = this.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
379
		const textBuffer = createTextBuffer(value, options.defaultEOL);
380 381

		// Return early if the text is already set in that form
382
		if (model.equalsTextBuffer(textBuffer)) {
383 384
			return;
		}
385 386

		// Otherwise find a diff between the values and update model
387
		model.setEOL(textBuffer.getEOL() === '\r\n' ? EndOfLineSequence.CRLF : EndOfLineSequence.LF);
388 389
		model.pushEditOperations(
			[new Selection(1, 1, 1, 1)],
390
			ModelServiceImpl._computeEdits(model, textBuffer),
391
			(inverseEditOperations: IIdentifiedSingleEditOperation[]) => [new Selection(1, 1, 1, 1)]
392
		);
393 394
	}

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
	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;
	}

415 416 417
	/**
	 * Compute edits to bring `model` to the state of `textSource`.
	 */
418
	public static _computeEdits(model: ITextModel, textBuffer: ITextBuffer): IIdentifiedSingleEditOperation[] {
419
		const modelLineCount = model.getLineCount();
420 421
		const textBufferLineCount = textBuffer.getLineCount();
		const commonPrefix = this._commonPrefix(model, modelLineCount, 1, textBuffer, textBufferLineCount, 1);
422

423 424 425 426
		if (modelLineCount === textBufferLineCount && commonPrefix === modelLineCount) {
			// equality case
			return [];
		}
427

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

430 431 432 433 434 435 436 437 438 439
		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));
440 441
		}

442
		return [EditOperation.replace(oldRange, textBuffer.getValueInRange(newRange, EndOfLinePreference.TextDefined))];
443 444
	}

445
	public createModel(value: string | ITextBufferFactory, modeOrPromise: TPromise<IMode> | IMode, resource: URI, isForSimpleWidget: boolean = false): ITextModel {
446 447 448
		let modelData: ModelData;

		if (!modeOrPromise || TPromise.is(modeOrPromise)) {
449
			modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_IDENTIFIER, resource, isForSimpleWidget);
450 451
			this.setMode(modelData.model, modeOrPromise);
		} else {
452
			modelData = this._createModelData(value, modeOrPromise.getLanguageIdentifier(), resource, isForSimpleWidget);
453
		}
E
Erich Gamma 已提交
454

A
Alex Dima 已提交
455 456
		// handle markers (marker service => model)
		if (this._markerService) {
457
			ModelMarkerHandler.setMarkers(modelData, this._markerService);
E
Erich Gamma 已提交
458 459
		}

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

A
Alex Dima 已提交
462
		return modelData.model;
E
Erich Gamma 已提交
463 464
	}

A
Alex Dima 已提交
465
	public setMode(model: ITextModel, modeOrPromise: TPromise<IMode> | IMode): void {
466 467 468 469 470 471
		if (!modeOrPromise) {
			return;
		}
		if (TPromise.is(modeOrPromise)) {
			modeOrPromise.then((mode) => {
				if (!model.isDisposed()) {
A
Alex Dima 已提交
472
					model.setMode(mode.getLanguageIdentifier());
473 474 475
				}
			});
		} else {
A
Alex Dima 已提交
476
			model.setMode(modeOrPromise.getLanguageIdentifier());
477 478 479
		}
	}

J
Johannes Rieken 已提交
480
	public destroyModel(resource: URI): void {
A
Alex Dima 已提交
481 482 483 484
		// 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 已提交
485
		}
A
Alex Dima 已提交
486
		modelData.model.dispose();
E
Erich Gamma 已提交
487 488
	}

A
Alex Dima 已提交
489 490
	public getModels(): ITextModel[] {
		let ret: ITextModel[] = [];
A
Alex Dima 已提交
491 492 493 494 495

		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 已提交
496
		}
A
Alex Dima 已提交
497

E
Erich Gamma 已提交
498 499 500
		return ret;
	}

A
Alex Dima 已提交
501
	public getModel(resource: URI): ITextModel {
A
Alex Dima 已提交
502 503 504 505
		let modelId = MODEL_ID(resource);
		let modelData = this._models[modelId];
		if (!modelData) {
			return null;
E
Erich Gamma 已提交
506
		}
A
Alex Dima 已提交
507
		return modelData.model;
E
Erich Gamma 已提交
508 509
	}

A
Alex Dima 已提交
510
	public get onModelAdded(): Event<ITextModel> {
511
		return this._onModelAdded ? this._onModelAdded.event : null;
E
Erich Gamma 已提交
512 513
	}

A
Alex Dima 已提交
514
	public get onModelRemoved(): Event<ITextModel> {
515
		return this._onModelRemoved ? this._onModelRemoved.event : null;
E
Erich Gamma 已提交
516 517
	}

A
Alex Dima 已提交
518
	public get onModelModeChanged(): Event<{ model: ITextModel; oldModeId: string; }> {
519
		return this._onModelModeChanged ? this._onModelModeChanged.event : null;
E
Erich Gamma 已提交
520 521 522 523
	}

	// --- end IModelService

A
Alex Dima 已提交
524
	private _onWillDispose(model: ITextModel): void {
525
		let modelId = MODEL_ID(model.uri);
A
Alex Dima 已提交
526 527 528 529 530
		let modelData = this._models[modelId];

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

531
		this._cleanUp(model);
A
Alex Dima 已提交
532 533 534
		this._onModelRemoved.fire(model);
	}

A
Alex Dima 已提交
535
	private _onDidChangeLanguage(model: ITextModel, e: IModelLanguageChangedEvent): void {
536 537
		const oldModeId = e.oldLanguage;
		const newModeId = model.getLanguageIdentifier().language;
538 539
		const oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget);
		const newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget);
540 541
		ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions);
		this._onModelModeChanged.fire({ model, oldModeId });
E
Erich Gamma 已提交
542 543
	}
}
544 545 546 547

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