modelServiceImpl.ts 16.3 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 7 8
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable, dispose } from 'vs/base/common/lifecycle';
import * as platform from 'vs/base/common/platform';
9
import { URI } from 'vs/base/common/uri';
A
Alex Dima 已提交
10 11
import { EDITOR_MODEL_DEFAULTS } from 'vs/editor/common/config/editorOptions';
import { EditOperation } from 'vs/editor/common/core/editOperation';
J
Johannes Rieken 已提交
12
import { Range } from 'vs/editor/common/core/range';
13
import { DefaultEndOfLine, EndOfLinePreference, EndOfLineSequence, IIdentifiedSingleEditOperation, ITextBuffer, ITextBufferFactory, ITextModel, ITextModelCreationOptions } from 'vs/editor/common/model';
14
import { TextModel, createTextBuffer } from 'vs/editor/common/model/textModel';
A
Alex Dima 已提交
15
import { IModelLanguageChangedEvent } from 'vs/editor/common/model/textModelEvents';
A
Alex Dima 已提交
16
import { LanguageIdentifier } from 'vs/editor/common/modes';
A
Alex Dima 已提交
17
import { PLAINTEXT_LANGUAGE_IDENTIFIER } from 'vs/editor/common/modes/modesRegistry';
A
Alex Dima 已提交
18
import { ILanguageSelection } from 'vs/editor/common/services/modeService';
A
Alex Dima 已提交
19
import { IModelService } from 'vs/editor/common/services/modelService';
S
Sandeep Somavarapu 已提交
20
import { ITextResourcePropertiesService } from 'vs/editor/common/services/resourceConfiguration';
A
Alex Dima 已提交
21
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
E
Erich Gamma 已提交
22

B
Benjamin Pasero 已提交
23
function MODEL_ID(resource: URI): string {
A
Alex Dima 已提交
24 25 26 27
	return resource.toString();
}

class ModelData implements IDisposable {
A
Alex Dima 已提交
28 29 30 31
	public readonly model: ITextModel;

	private _languageSelection: ILanguageSelection | null;
	private _languageSelectionListener: IDisposable | null;
E
Erich Gamma 已提交
32

33
	private _modelEventListeners: IDisposable[];
E
Erich Gamma 已提交
34

35
	constructor(
A
Alex Dima 已提交
36 37 38
		model: ITextModel,
		onWillDispose: (model: ITextModel) => void,
		onDidChangeLanguage: (model: ITextModel, e: IModelLanguageChangedEvent) => void
39
	) {
E
Erich Gamma 已提交
40
		this.model = model;
A
Alex Dima 已提交
41

A
Alex Dima 已提交
42 43 44
		this._languageSelection = null;
		this._languageSelectionListener = null;

45 46 47
		this._modelEventListeners = [];
		this._modelEventListeners.push(model.onWillDispose(() => onWillDispose(model)));
		this._modelEventListeners.push(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
E
Erich Gamma 已提交
48 49
	}

A
Alex Dima 已提交
50 51 52 53 54 55 56 57 58 59 60
	private _disposeLanguageSelection(): void {
		if (this._languageSelectionListener) {
			this._languageSelectionListener.dispose();
			this._languageSelectionListener = null;
		}
		if (this._languageSelection) {
			this._languageSelection.dispose();
			this._languageSelection = null;
		}
	}

E
Erich Gamma 已提交
61
	public dispose(): void {
62
		this._modelEventListeners = dispose(this._modelEventListeners);
A
Alex Dima 已提交
63
		this._disposeLanguageSelection();
A
Alex Dima 已提交
64
	}
E
Erich Gamma 已提交
65

A
Alex Dima 已提交
66 67 68 69 70 71
	public setLanguage(languageSelection: ILanguageSelection): void {
		this._disposeLanguageSelection();
		this._languageSelection = languageSelection;
		this._languageSelectionListener = this._languageSelection.onDidChange(() => this.model.setMode(languageSelection.languageIdentifier));
		this.model.setMode(languageSelection.languageIdentifier);
	}
A
Alex Dima 已提交
72
}
E
Erich Gamma 已提交
73

S
Sandeep Somavarapu 已提交
74 75
interface IRawEditorConfig {
	tabSize?: any;
D
David Lechner 已提交
76
	indentSize?: any;
S
Sandeep Somavarapu 已提交
77 78 79 80 81 82 83
	insertSpaces?: any;
	detectIndentation?: any;
	trimAutoWhitespace?: any;
	creationOptions?: any;
	largeFileOptimizations?: any;
}

84
interface IRawConfig {
S
Sandeep Somavarapu 已提交
85 86
	eol?: any;
	editor?: IRawEditorConfig;
87 88
}

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

A
Alex Dima 已提交
91
export class ModelServiceImpl extends Disposable implements IModelService {
92
	public _serviceBrand: any;
E
Erich Gamma 已提交
93

94 95 96
	private readonly _configurationService: IConfigurationService;
	private readonly _configurationServiceSubscription: IDisposable;
	private readonly _resourcePropertiesService: ITextResourcePropertiesService;
E
Erich Gamma 已提交
97

A
Alex Dima 已提交
98 99 100 101 102 103
	private readonly _onModelAdded: Emitter<ITextModel> = this._register(new Emitter<ITextModel>());
	public readonly onModelAdded: Event<ITextModel> = this._onModelAdded.event;

	private readonly _onModelRemoved: Emitter<ITextModel> = this._register(new Emitter<ITextModel>());
	public readonly onModelRemoved: Event<ITextModel> = this._onModelRemoved.event;

104
	private readonly _onModelModeChanged: Emitter<{ model: ITextModel; oldModeId: string; }> = this._register(new Emitter<{ model: ITextModel; oldModeId: string; }>());
A
Alex Dima 已提交
105
	public readonly onModelModeChanged: Event<{ model: ITextModel; oldModeId: string; }> = this._onModelModeChanged.event;
106

107
	private _modelCreationOptionsByLanguageAndResource: {
108
		[languageAndResource: string]: ITextModelCreationOptions;
109
	};
A
Alex Dima 已提交
110 111 112 113

	/**
	 * All the models known in the system.
	 */
114
	private readonly _models: { [modelId: string]: ModelData; };
E
Erich Gamma 已提交
115

116
	constructor(
117
		@IConfigurationService configurationService: IConfigurationService,
118
		@ITextResourcePropertiesService resourcePropertiesService: ITextResourcePropertiesService
119
	) {
A
Alex Dima 已提交
120
		super();
121
		this._configurationService = configurationService;
S
Sandeep Somavarapu 已提交
122
		this._resourcePropertiesService = resourcePropertiesService;
B
Benjamin Pasero 已提交
123
		this._models = {};
124
		this._modelCreationOptionsByLanguageAndResource = Object.create(null);
B
Benjamin Pasero 已提交
125

126
		this._configurationServiceSubscription = this._configurationService.onDidChangeConfiguration(e => this._updateModelOptions());
127 128
		this._updateModelOptions();
	}
J
Joao Moreno 已提交
129

130
	private static _readModelOptions(config: IRawConfig, isForSimpleWidget: boolean): ITextModelCreationOptions {
131
		let tabSize = EDITOR_MODEL_DEFAULTS.tabSize;
132 133 134 135
		if (config.editor && typeof config.editor.tabSize !== 'undefined') {
			let parsedTabSize = parseInt(config.editor.tabSize, 10);
			if (!isNaN(parsedTabSize)) {
				tabSize = parsedTabSize;
136
			}
A
Alex Dima 已提交
137 138 139
			if (tabSize < 1) {
				tabSize = 1;
			}
140
		}
141

D
David Lechner 已提交
142
		let indentSize = tabSize;
A
Alex Dima 已提交
143
		if (config.editor && typeof config.editor.indentSize !== 'undefined' && config.editor.indentSize !== 'tabSize') {
D
David Lechner 已提交
144 145 146 147 148 149 150 151 152
			let parsedIndentSize = parseInt(config.editor.indentSize, 10);
			if (!isNaN(parsedIndentSize)) {
				indentSize = parsedIndentSize;
			}
			if (indentSize < 1) {
				indentSize = 1;
			}
		}

153
		let insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;
154 155 156
		if (config.editor && typeof config.editor.insertSpaces !== 'undefined') {
			insertSpaces = (config.editor.insertSpaces === 'false' ? false : Boolean(config.editor.insertSpaces));
		}
157

158
		let newDefaultEOL = DEFAULT_EOL;
S
Sandeep Somavarapu 已提交
159
		const eol = config.eol;
160
		if (eol === '\r\n') {
161
			newDefaultEOL = DefaultEndOfLine.CRLF;
162
		} else if (eol === '\n') {
163
			newDefaultEOL = DefaultEndOfLine.LF;
164
		}
165

166
		let trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
167 168 169
		if (config.editor && typeof config.editor.trimAutoWhitespace !== 'undefined') {
			trimAutoWhitespace = (config.editor.trimAutoWhitespace === 'false' ? false : Boolean(config.editor.trimAutoWhitespace));
		}
170

171
		let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
172 173 174
		if (config.editor && typeof config.editor.detectIndentation !== 'undefined') {
			detectIndentation = (config.editor.detectIndentation === 'false' ? false : Boolean(config.editor.detectIndentation));
		}
175

176 177 178
		let largeFileOptimizations = EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
		if (config.editor && typeof config.editor.largeFileOptimizations !== 'undefined') {
			largeFileOptimizations = (config.editor.largeFileOptimizations === 'false' ? false : Boolean(config.editor.largeFileOptimizations));
179 180
		}

181
		return {
182
			isForSimpleWidget: isForSimpleWidget,
183
			tabSize: tabSize,
D
David Lechner 已提交
184
			indentSize: indentSize,
185 186 187
			insertSpaces: insertSpaces,
			detectIndentation: detectIndentation,
			defaultEOL: newDefaultEOL,
188
			trimAutoWhitespace: trimAutoWhitespace,
189
			largeFileOptimizations: largeFileOptimizations
190
		};
E
Erich Gamma 已提交
191 192
	}

A
Alex Dima 已提交
193
	public getCreationOptions(language: string, resource: URI | undefined, isForSimpleWidget: boolean): ITextModelCreationOptions {
194
		let creationOptions = this._modelCreationOptionsByLanguageAndResource[language + resource];
195
		if (!creationOptions) {
S
Sandeep Somavarapu 已提交
196
			const editor = this._configurationService.getValue<IRawEditorConfig>('editor', { overrideIdentifier: language, resource });
S
Sandeep Somavarapu 已提交
197
			const eol = this._resourcePropertiesService.getEOL(resource, language);
S
Sandeep Somavarapu 已提交
198
			creationOptions = ModelServiceImpl._readModelOptions({ editor, eol }, isForSimpleWidget);
199
			this._modelCreationOptionsByLanguageAndResource[language + resource] = creationOptions;
200 201
		}
		return creationOptions;
202 203
	}

204
	private _updateModelOptions(): void {
205 206
		let oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
		this._modelCreationOptionsByLanguageAndResource = Object.create(null);
207

208
		// Update options on all models
A
Alex Dima 已提交
209 210 211 212
		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];
213
			const language = modelData.model.getLanguageIdentifier().language;
214 215
			const uri = modelData.model.uri;
			const oldOptions = oldOptionsByLanguageAndResource[language + uri];
216
			const newOptions = this.getCreationOptions(language, uri, modelData.model.isForSimpleWidget);
217 218 219
			ModelServiceImpl._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
		}
	}
220

A
Alex Dima 已提交
221
	private static _setModelOptionsForModel(model: ITextModel, newOptions: ITextModelCreationOptions, currentOptions: ITextModelCreationOptions): void {
222 223 224 225
		if (currentOptions
			&& (currentOptions.detectIndentation === newOptions.detectIndentation)
			&& (currentOptions.insertSpaces === newOptions.insertSpaces)
			&& (currentOptions.tabSize === newOptions.tabSize)
A
Alex Dima 已提交
226
			&& (currentOptions.indentSize === newOptions.indentSize)
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
			&& (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,
A
Alex Dima 已提交
242
				indentSize: newOptions.indentSize,
243 244
				trimAutoWhitespace: newOptions.trimAutoWhitespace
			});
245
		}
246 247
	}

E
Erich Gamma 已提交
248
	public dispose(): void {
249
		this._configurationServiceSubscription.dispose();
A
Alex Dima 已提交
250
		super.dispose();
E
Erich Gamma 已提交
251 252 253 254
	}

	// --- begin IModelService

A
Alex Dima 已提交
255
	private _createModelData(value: string | ITextBufferFactory, languageIdentifier: LanguageIdentifier, resource: URI | undefined, isForSimpleWidget: boolean): ModelData {
A
Alex Dima 已提交
256
		// create & save the model
257
		const options = this.getCreationOptions(languageIdentifier.language, resource, isForSimpleWidget);
258 259
		const model: TextModel = new TextModel(value, options, languageIdentifier, resource);
		const modelId = MODEL_ID(model.uri);
E
Erich Gamma 已提交
260 261 262

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

266
		const modelData = new ModelData(
267 268 269 270
			model,
			(model) => this._onWillDispose(model),
			(model, e) => this._onDidChangeLanguage(model, e)
		);
A
Alex Dima 已提交
271
		this._models[modelId] = modelData;
E
Erich Gamma 已提交
272

A
Alex Dima 已提交
273
		return modelData;
E
Erich Gamma 已提交
274 275
	}

276
	public updateModel(model: ITextModel, value: string | ITextBufferFactory): void {
277
		const options = this.getCreationOptions(model.getLanguageIdentifier().language, model.uri, model.isForSimpleWidget);
278
		const textBuffer = createTextBuffer(value, options.defaultEOL);
279 280

		// Return early if the text is already set in that form
281
		if (model.equalsTextBuffer(textBuffer)) {
282 283
			return;
		}
284 285

		// Otherwise find a diff between the values and update model
286
		model.pushStackElement();
A
Alex Dima 已提交
287
		model.pushEOL(textBuffer.getEOL() === '\r\n' ? EndOfLineSequence.CRLF : EndOfLineSequence.LF);
288
		model.pushEditOperations(
289
			[],
290
			ModelServiceImpl._computeEdits(model, textBuffer),
291
			(inverseEditOperations: IIdentifiedSingleEditOperation[]) => []
292
		);
293
		model.pushStackElement();
294 295
	}

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
	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;
	}

316 317 318
	/**
	 * Compute edits to bring `model` to the state of `textSource`.
	 */
319
	public static _computeEdits(model: ITextModel, textBuffer: ITextBuffer): IIdentifiedSingleEditOperation[] {
320
		const modelLineCount = model.getLineCount();
321 322
		const textBufferLineCount = textBuffer.getLineCount();
		const commonPrefix = this._commonPrefix(model, modelLineCount, 1, textBuffer, textBufferLineCount, 1);
323

324 325 326 327
		if (modelLineCount === textBufferLineCount && commonPrefix === modelLineCount) {
			// equality case
			return [];
		}
328

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

331 332 333 334 335 336 337 338 339 340
		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));
341 342
		}

343
		return [EditOperation.replaceMove(oldRange, textBuffer.getValueInRange(newRange, EndOfLinePreference.TextDefined))];
344 345
	}

A
Alex Dima 已提交
346
	public createModel(value: string | ITextBufferFactory, languageSelection: ILanguageSelection | null, resource?: URI, isForSimpleWidget: boolean = false): ITextModel {
347 348
		let modelData: ModelData;

A
Alex Dima 已提交
349 350 351
		if (languageSelection) {
			modelData = this._createModelData(value, languageSelection.languageIdentifier, resource, isForSimpleWidget);
			this.setMode(modelData.model, languageSelection);
352
		} else {
A
Alex Dima 已提交
353
			modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_IDENTIFIER, resource, isForSimpleWidget);
354
		}
E
Erich Gamma 已提交
355

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

A
Alex Dima 已提交
358
		return modelData.model;
E
Erich Gamma 已提交
359 360
	}

A
Alex Dima 已提交
361 362
	public setMode(model: ITextModel, languageSelection: ILanguageSelection): void {
		if (!languageSelection) {
363 364
			return;
		}
A
Alex Dima 已提交
365 366 367
		let modelData = this._models[MODEL_ID(model.uri)];
		if (!modelData) {
			return;
368
		}
A
Alex Dima 已提交
369
		modelData.setLanguage(languageSelection);
370 371
	}

J
Johannes Rieken 已提交
372
	public destroyModel(resource: URI): void {
A
Alex Dima 已提交
373 374 375 376
		// 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 已提交
377
		}
A
Alex Dima 已提交
378
		modelData.model.dispose();
E
Erich Gamma 已提交
379 380
	}

A
Alex Dima 已提交
381 382
	public getModels(): ITextModel[] {
		let ret: ITextModel[] = [];
A
Alex Dima 已提交
383 384 385 386 387

		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 已提交
388
		}
A
Alex Dima 已提交
389

E
Erich Gamma 已提交
390 391 392
		return ret;
	}

A
Alex Dima 已提交
393
	public getModel(resource: URI): ITextModel | null {
A
Alex Dima 已提交
394 395 396 397
		let modelId = MODEL_ID(resource);
		let modelData = this._models[modelId];
		if (!modelData) {
			return null;
E
Erich Gamma 已提交
398
		}
A
Alex Dima 已提交
399
		return modelData.model;
E
Erich Gamma 已提交
400 401 402 403
	}

	// --- end IModelService

A
Alex Dima 已提交
404
	private _onWillDispose(model: ITextModel): void {
405
		let modelId = MODEL_ID(model.uri);
A
Alex Dima 已提交
406 407 408 409 410
		let modelData = this._models[modelId];

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

411 412 413
		// clean up cache
		delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageIdentifier().language + model.uri];

A
Alex Dima 已提交
414 415 416
		this._onModelRemoved.fire(model);
	}

A
Alex Dima 已提交
417
	private _onDidChangeLanguage(model: ITextModel, e: IModelLanguageChangedEvent): void {
418 419
		const oldModeId = e.oldLanguage;
		const newModeId = model.getLanguageIdentifier().language;
420 421
		const oldOptions = this.getCreationOptions(oldModeId, model.uri, model.isForSimpleWidget);
		const newOptions = this.getCreationOptions(newModeId, model.uri, model.isForSimpleWidget);
422 423
		ModelServiceImpl._setModelOptionsForModel(model, newOptions, oldOptions);
		this._onModelModeChanged.fire({ model, oldModeId });
E
Erich Gamma 已提交
424 425
	}
}
426 427 428 429

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