preferencesService.ts 24.4 KB
Newer Older
1 2 3 4
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
S
Sandeep Somavarapu 已提交
5

6
import * as network from 'vs/base/common/network';
7 8 9 10
import { TPromise } from 'vs/base/common/winjs.base';
import * as nls from 'vs/nls';
import URI from 'vs/base/common/uri';
import * as labels from 'vs/base/common/labels';
11
import * as strings from 'vs/base/common/strings';
S
Sandeep Somavarapu 已提交
12
import { Disposable } from 'vs/base/common/lifecycle';
13
import { Emitter } from 'vs/base/common/event';
14
import { EditorInput, IEditor } from 'vs/workbench/common/editor';
15
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
16
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
B
Benjamin Pasero 已提交
17
import { IEditorOptions } from 'vs/platform/editor/common/editor';
A
Alex Dima 已提交
18
import { ITextModel } from 'vs/editor/common/model';
19
import { IFileService, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
20 21
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
S
Sandeep Somavarapu 已提交
22 23
import { IPreferencesService, IPreferencesEditorModel, ISetting, getSettingsTargetName, FOLDER_SETTINGS_PATH, DEFAULT_SETTINGS_EDITOR_SETTING } from 'vs/workbench/services/preferences/common/preferences';
import { SettingsEditorModel, DefaultSettingsEditorModel, DefaultKeybindingsEditorModel, defaultKeybindingsContents, DefaultSettings, WorkspaceConfigurationEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
C
Christof Marti 已提交
24
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
25
import { DefaultPreferencesEditorInput, PreferencesEditorInput, KeybindingsEditorInput, SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
26
import { ITextModelService } from 'vs/editor/common/services/resolverService';
27
import { getCodeEditor } from 'vs/editor/browser/services/codeEditorService';
28
import { EditOperation } from 'vs/editor/common/core/editOperation';
A
Alex Dima 已提交
29
import { Position, IPosition } from 'vs/editor/common/core/position';
30 31
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IModelService } from 'vs/editor/common/services/modelService';
B
Benjamin Pasero 已提交
32
import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
33
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
34
import { IModeService } from 'vs/editor/common/services/modeService';
S
Sandeep Somavarapu 已提交
35
import { parse } from 'vs/base/common/json';
36
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
37
import { INotificationService } from 'vs/platform/notification/common/notification';
38
import { assign } from 'vs/base/common/objects';
B
Benjamin Pasero 已提交
39
import { INextEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/nextEditorService';
B
Benjamin Pasero 已提交
40
import { INextEditorGroup, INextEditorGroupsService } from 'vs/workbench/services/group/common/nextEditorGroupsService';
41

S
Sandeep Somavarapu 已提交
42 43
const emptyEditableSettingsContent = '{\n}';

44
export class PreferencesService extends Disposable implements IPreferencesService {
45 46

	_serviceBrand: any;
47

48
	private lastOpenedSettingsInput: PreferencesEditorInput = null;
49

M
Matt Bierner 已提交
50
	private readonly _onDispose: Emitter<void> = new Emitter<void>();
51

S
Sandeep Somavarapu 已提交
52 53 54 55 56 57
	private _defaultUserSettingsUriCounter = 0;
	private _defaultUserSettingsContentModel: DefaultSettings;
	private _defaultWorkspaceSettingsUriCounter = 0;
	private _defaultWorkspaceSettingsContentModel: DefaultSettings;
	private _defaultFolderSettingsUriCounter = 0;
	private _defaultFolderSettingsContentModel: DefaultSettings;
R
Rob Lourens 已提交
58

59
	constructor(
B
Benjamin Pasero 已提交
60 61
		@INextEditorService private editorService: INextEditorService,
		@INextEditorGroupsService private editorGroupService: INextEditorGroupsService,
62 63
		@IFileService private fileService: IFileService,
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
64
		@INotificationService private notificationService: INotificationService,
65 66 67
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IEnvironmentService private environmentService: IEnvironmentService,
68
		@ITelemetryService private telemetryService: ITelemetryService,
69
		@ITextModelService private textModelResolverService: ITextModelService,
70
		@IKeybindingService keybindingService: IKeybindingService,
71
		@IModelService private modelService: IModelService,
72 73
		@IJSONEditingService private jsonEditingService: IJSONEditingService,
		@IModeService private modeService: IModeService
74 75
	) {
		super();
76 77 78 79 80 81 82 83
		// The default keybindings.json updates based on keyboard layouts, so here we make sure
		// if a model has been given out we update it accordingly.
		keybindingService.onDidUpdateKeybindings(() => {
			const model = modelService.getModel(this.defaultKeybindingsResource);
			if (!model) {
				// model has not been given out => nothing to do
				return;
			}
84
			modelService.updateModel(model, defaultKeybindingsContents(keybindingService));
85
		});
86 87
	}

S
Sandeep Somavarapu 已提交
88
	readonly defaultKeybindingsResource = URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: '/keybindings.json' });
S
Sandeep Somavarapu 已提交
89
	private readonly defaultSettingsRawResource = URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: '/defaultSettings.json' });
90

91 92 93 94 95 96 97 98
	get userSettingsResource(): URI {
		return this.getEditableSettingsURI(ConfigurationTarget.USER);
	}

	get workspaceSettingsResource(): URI {
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
	}

S
Sandeep Somavarapu 已提交
99
	getFolderSettingsResource(resource: URI): URI {
100
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, resource);
S
Sandeep Somavarapu 已提交
101 102
	}

A
Alex Dima 已提交
103
	resolveModel(uri: URI): TPromise<ITextModel> {
S
Sandeep Somavarapu 已提交
104
		if (this.isDefaultSettingsResource(uri)) {
S
Sandeep Somavarapu 已提交
105

S
Sandeep Somavarapu 已提交
106
			const target = this.getConfigurationTargetFromDefaultSettingsResource(uri);
107
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
108 109 110 111 112 113 114 115 116 117
			const model = this._register(this.modelService.createModel('', mode, uri));

			let defaultSettings: DefaultSettings;
			this.configurationService.onDidChangeConfiguration(e => {
				if (e.source === ConfigurationTarget.DEFAULT) {
					const model = this.modelService.getModel(uri);
					if (!model) {
						// model has not been given out => nothing to do
						return;
					}
S
Sandeep Somavarapu 已提交
118
					defaultSettings = this.getDefaultSettings(target);
S
Sandeep Somavarapu 已提交
119
					this.modelService.updateModel(model, defaultSettings.parse());
120
					defaultSettings._onDidChange.fire();
S
Sandeep Somavarapu 已提交
121 122 123 124 125
				}
			});

			// Check if Default settings is already created and updated in above promise
			if (!defaultSettings) {
S
Sandeep Somavarapu 已提交
126
				defaultSettings = this.getDefaultSettings(target);
S
Sandeep Somavarapu 已提交
127 128 129 130
				this.modelService.updateModel(model, defaultSettings.parse());
			}

			return TPromise.as(model);
131 132
		}

S
Sandeep Somavarapu 已提交
133
		if (this.defaultSettingsRawResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
134
			let defaultSettings: DefaultSettings = this.getDefaultSettings(ConfigurationTarget.USER);
135
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
136 137 138 139
			const model = this._register(this.modelService.createModel(defaultSettings.raw, mode, uri));
			return TPromise.as(model);
		}

140
		if (this.defaultKeybindingsResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
141
			const defaultKeybindingsEditorModel = this.instantiationService.createInstance(DefaultKeybindingsEditorModel, uri);
142
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
143 144
			const model = this._register(this.modelService.createModel(defaultKeybindingsEditorModel.content, mode, uri));
			return TPromise.as(model);
145 146 147 148 149 150
		}

		return TPromise.as(null);
	}

	createPreferencesEditorModel(uri: URI): TPromise<IPreferencesEditorModel<any>> {
S
Sandeep Somavarapu 已提交
151
		if (this.isDefaultSettingsResource(uri)) {
152
			return this.createDefaultSettingsEditorModel(uri);
153 154
		}

155
		if (this.getEditableSettingsURI(ConfigurationTarget.USER).toString() === uri.toString()) {
156
			return this.createEditableSettingsEditorModel(ConfigurationTarget.USER, uri);
157
		}
158

S
Sandeep Somavarapu 已提交
159
		const workspaceSettingsUri = this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
160
		if (workspaceSettingsUri && workspaceSettingsUri.toString() === uri.toString()) {
161
			return this.createEditableSettingsEditorModel(ConfigurationTarget.WORKSPACE, workspaceSettingsUri);
162
		}
163

164
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
165
			return this.createEditableSettingsEditorModel(ConfigurationTarget.WORKSPACE_FOLDER, uri);
166
		}
167

168
		return TPromise.wrap<IPreferencesEditorModel<any>>(null);
169 170
	}

B
Benjamin Pasero 已提交
171
	openRawDefaultSettings(): TPromise<IEditor> {
B
Benjamin Pasero 已提交
172
		return this.editorService.openEditor({ resource: this.defaultSettingsRawResource });
S
Sandeep Somavarapu 已提交
173 174
	}

B
Benjamin Pasero 已提交
175
	openRawUserSettings(): TPromise<IEditor> {
A
al 已提交
176
		return this.editorService.openEditor({ resource: this.userSettingsResource }) as TPromise<any>;
S
Sandeep Somavarapu 已提交
177 178
	}

S
Sandeep Somavarapu 已提交
179
	openSettings(): TPromise<IEditor> {
180 181
		const editorInput = this.getActiveSettingsEditorInput() || this.lastOpenedSettingsInput;
		const resource = editorInput ? editorInput.master.getResource() : this.userSettingsResource;
S
Sandeep Somavarapu 已提交
182
		const target = this.getConfigurationTargetFromSettingsResource(resource);
183
		return this.openOrSwitchSettings(target, resource);
S
Sandeep Somavarapu 已提交
184 185
	}

B
Benjamin Pasero 已提交
186 187
	openGlobalSettings(options?: IEditorOptions, group?: INextEditorGroup): TPromise<IEditor> {
		return this.openOrSwitchSettings(ConfigurationTarget.USER, this.userSettingsResource, options, group);
188 189
	}

R
Rob Lourens 已提交
190
	openSettings2(): TPromise<IEditor> {
191
		return this.editorService.openEditor(this.instantiationService.createInstance(SettingsEditor2Input), { pinned: true }).then(() => null);
R
Rob Lourens 已提交
192 193
	}

B
Benjamin Pasero 已提交
194
	openWorkspaceSettings(options?: IEditorOptions, group?: INextEditorGroup): TPromise<IEditor> {
195
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
196
			this.notificationService.info(nls.localize('openFolderFirst', "Open a folder first to create workspace settings"));
S
Sandeep Somavarapu 已提交
197
			return TPromise.as(null);
198
		}
B
Benjamin Pasero 已提交
199
		return this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE, this.workspaceSettingsResource, options, group);
200 201
	}

B
Benjamin Pasero 已提交
202 203
	openFolderSettings(folder: URI, options?: IEditorOptions, group?: INextEditorGroup): TPromise<IEditor> {
		return this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE_FOLDER, this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, folder), options, group);
204 205 206
	}

	switchSettings(target: ConfigurationTarget, resource: URI): TPromise<void> {
B
Benjamin Pasero 已提交
207 208
		const activeControl = this.editorService.activeControl;
		if (activeControl && activeControl.input instanceof PreferencesEditorInput) {
209
			return this.doSwitchSettings(target, resource, activeControl.input, activeControl.group).then(() => null);
210
		} else {
211
			return this.doOpenSettings(target, resource).then(() => null);
212
		}
213 214
	}

S
Sandeep Somavarapu 已提交
215
	openGlobalKeybindingSettings(textual: boolean): TPromise<void> {
K
kieferrm 已提交
216
		/* __GDPR__
K
kieferrm 已提交
217
			"openKeybindings" : {
K
kieferrm 已提交
218
				"textual" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
K
kieferrm 已提交
219 220
			}
		*/
221
		this.telemetryService.publicLog('openKeybindings', { textual });
S
Sandeep Somavarapu 已提交
222 223 224 225 226 227
		if (textual) {
			const emptyContents = '// ' + nls.localize('emptyKeybindingsHeader', "Place your key bindings in this file to overwrite the defaults") + '\n[\n]';
			const editableKeybindings = URI.file(this.environmentService.appKeybindingsPath);

			// Create as needed and open in editor
			return this.createIfNotExists(editableKeybindings, emptyContents).then(() => {
B
Benjamin Pasero 已提交
228 229 230 231
				return TPromise.join([
					this.editorService.openEditor({ resource: this.defaultKeybindingsResource, options: { pinned: true, preserveFocus: true }, label: nls.localize('defaultKeybindings', "Default Keybindings"), description: '' }),
					this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true } }, SIDE_GROUP)
				]).then(editors => void 0);
S
Sandeep Somavarapu 已提交
232 233
			});
		}
B
Benjamin Pasero 已提交
234
		return this.editorService.openEditor(this.instantiationService.createInstance(KeybindingsEditorInput), { pinned: true }).then(() => null);
235 236
	}

237 238 239 240 241 242 243 244 245 246 247 248
	configureSettingsForLanguage(language: string): void {
		this.openGlobalSettings()
			.then(editor => {
				const codeEditor = getCodeEditor(editor);
				this.getPosition(language, codeEditor)
					.then(position => {
						codeEditor.setPosition(position);
						codeEditor.focus();
					});
			});
	}

B
Benjamin Pasero 已提交
249
	private openOrSwitchSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: IEditorOptions, group: INextEditorGroup = this.editorGroupService.activeGroup): TPromise<IEditor> {
B
Benjamin Pasero 已提交
250
		const editorInput = this.getActiveSettingsEditorInput(group);
251
		if (editorInput && editorInput.master.getResource().fsPath !== resource.fsPath) {
B
Benjamin Pasero 已提交
252
			return this.doSwitchSettings(configurationTarget, resource, editorInput, group);
253
		}
B
Benjamin Pasero 已提交
254
		return this.doOpenSettings(configurationTarget, resource, options, group);
255 256
	}

B
Benjamin Pasero 已提交
257
	private doOpenSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: IEditorOptions, group?: INextEditorGroup): TPromise<IEditor> {
S
Sandeep Somavarapu 已提交
258
		const openDefaultSettings = !!this.configurationService.getValue(DEFAULT_SETTINGS_EDITOR_SETTING);
259
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
260
			.then(editableSettingsEditorInput => {
261 262 263
				if (!options) {
					options = { pinned: true };
				} else {
264
					options = assign(options, { pinned: true });
265 266
				}

267
				if (openDefaultSettings) {
S
Sandeep Somavarapu 已提交
268
					const defaultPreferencesEditorInput = this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(configurationTarget));
269
					const preferencesEditorInput = new PreferencesEditorInput(this.getPreferencesEditorInputName(configurationTarget, resource), editableSettingsEditorInput.getDescription(), defaultPreferencesEditorInput, <EditorInput>editableSettingsEditorInput);
270
					this.lastOpenedSettingsInput = preferencesEditorInput;
B
Benjamin Pasero 已提交
271
					return this.editorService.openEditor(preferencesEditorInput, options, group);
272
				}
B
Benjamin Pasero 已提交
273
				return this.editorService.openEditor(editableSettingsEditorInput, options, group);
274
			});
275 276
	}

B
Benjamin Pasero 已提交
277
	private doSwitchSettings(target: ConfigurationTarget, resource: URI, input: PreferencesEditorInput, group: INextEditorGroup): TPromise<IEditor> {
278 279 280
		return this.getOrCreateEditableSettingsEditorInput(target, this.getEditableSettingsURI(target, resource))
			.then(toInput => {
				const replaceWith = new PreferencesEditorInput(this.getPreferencesEditorInputName(target, resource), toInput.getDescription(), this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(target)), toInput);
B
Benjamin Pasero 已提交
281 282 283 284 285

				return group.replaceEditors([{
					editor: input,
					replacement: replaceWith
				}]).then(() => {
286
					this.lastOpenedSettingsInput = replaceWith;
B
Benjamin Pasero 已提交
287
					return group.activeControl;
288 289 290 291
				});
			});
	}

B
Benjamin Pasero 已提交
292
	private getActiveSettingsEditorInput(group: INextEditorGroup = this.editorGroupService.activeGroup): PreferencesEditorInput {
B
Benjamin Pasero 已提交
293
		return <PreferencesEditorInput>group.editors.filter(e => e instanceof PreferencesEditorInput)[0];
294 295
	}

S
Sandeep Somavarapu 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
	private getConfigurationTargetFromSettingsResource(resource: URI): ConfigurationTarget {
		if (this.userSettingsResource.toString() === resource.toString()) {
			return ConfigurationTarget.USER;
		}

		const workspaceSettingsResource = this.workspaceSettingsResource;
		if (workspaceSettingsResource && workspaceSettingsResource.toString() === resource.toString()) {
			return ConfigurationTarget.WORKSPACE;
		}

		const folder = this.contextService.getWorkspaceFolder(resource);
		if (folder) {
			return ConfigurationTarget.WORKSPACE_FOLDER;
		}

		return ConfigurationTarget.USER;
	}

S
Sandeep Somavarapu 已提交
314 315 316 317
	private getConfigurationTargetFromDefaultSettingsResource(uri: URI) {
		return this.isDefaultWorkspaceSettingsResource(uri) ? ConfigurationTarget.WORKSPACE : this.isDefaultFolderSettingsResource(uri) ? ConfigurationTarget.WORKSPACE_FOLDER : ConfigurationTarget.USER;
	}

R
Rob Lourens 已提交
318
	private isDefaultSettingsResource(uri: URI): boolean {
S
Sandeep Somavarapu 已提交
319 320 321 322
		return this.isDefaultUserSettingsResource(uri) || this.isDefaultWorkspaceSettingsResource(uri) || this.isDefaultFolderSettingsResource(uri);
	}

	private isDefaultUserSettingsResource(uri: URI): boolean {
323
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?settings\.json$/);
R
Rob Lourens 已提交
324 325
	}

S
Sandeep Somavarapu 已提交
326 327 328 329 330
	private isDefaultWorkspaceSettingsResource(uri: URI): boolean {
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?workspaceSettings\.json$/);
	}

	private isDefaultFolderSettingsResource(uri: URI): boolean {
331
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
R
Rob Lourens 已提交
332 333
	}

S
Sandeep Somavarapu 已提交
334
	private getDefaultSettingsResource(configurationTarget: ConfigurationTarget): URI {
S
Sandeep Somavarapu 已提交
335 336 337 338 339
		switch (configurationTarget) {
			case ConfigurationTarget.WORKSPACE:
				return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultWorkspaceSettingsUriCounter++}/workspaceSettings.json` });
			case ConfigurationTarget.WORKSPACE_FOLDER:
				return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultFolderSettingsUriCounter++}/resourceSettings.json` });
S
Sandeep Somavarapu 已提交
340
		}
S
Sandeep Somavarapu 已提交
341
		return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultUserSettingsUriCounter++}/settings.json` });
S
Sandeep Somavarapu 已提交
342 343
	}

344 345
	private getPreferencesEditorInputName(target: ConfigurationTarget, resource: URI): string {
		const name = getSettingsTargetName(target, resource, this.contextService);
346
		return target === ConfigurationTarget.WORKSPACE_FOLDER ? nls.localize('folderSettingsName', "{0} (Folder Settings)", name) : name;
347 348
	}

349 350 351
	private getOrCreateEditableSettingsEditorInput(target: ConfigurationTarget, resource: URI): TPromise<EditorInput> {
		return this.createSettingsIfNotExists(target, resource)
			.then(() => <EditorInput>this.editorService.createInput({ resource }));
352 353
	}

354 355
	private createEditableSettingsEditorModel(configurationTarget: ConfigurationTarget, resource: URI): TPromise<SettingsEditorModel> {
		const settingsUri = this.getEditableSettingsURI(configurationTarget, resource);
356
		if (settingsUri) {
S
Sandeep Somavarapu 已提交
357 358 359 360
			const workspace = this.contextService.getWorkspace();
			if (workspace.configuration && workspace.configuration.toString() === settingsUri.toString()) {
				return this.textModelResolverService.createModelReference(settingsUri)
					.then(reference => this.instantiationService.createInstance(WorkspaceConfigurationEditorModel, reference, configurationTarget));
361
			}
362
			return this.textModelResolverService.createModelReference(settingsUri)
S
Sandeep Somavarapu 已提交
363
				.then(reference => this.instantiationService.createInstance(SettingsEditorModel, reference, configurationTarget));
364
		}
365
		return TPromise.wrap<SettingsEditorModel>(null);
366 367
	}

368 369 370
	private createDefaultSettingsEditorModel(defaultSettingsUri: URI): TPromise<DefaultSettingsEditorModel> {
		return this.textModelResolverService.createModelReference(defaultSettingsUri)
			.then(reference => {
S
Sandeep Somavarapu 已提交
371 372
				const target = this.getConfigurationTargetFromDefaultSettingsResource(defaultSettingsUri);
				return this.instantiationService.createInstance(DefaultSettingsEditorModel, defaultSettingsUri, reference, this.getDefaultSettings(target));
373 374 375
			});
	}

S
Sandeep Somavarapu 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
	private getDefaultSettings(target: ConfigurationTarget): DefaultSettings {
		if (target === ConfigurationTarget.WORKSPACE) {
			if (!this._defaultWorkspaceSettingsContentModel) {
				this._defaultWorkspaceSettingsContentModel = new DefaultSettings(this.getMostCommonlyUsedSettings(), target);
			}
			return this._defaultWorkspaceSettingsContentModel;
		}
		if (target === ConfigurationTarget.WORKSPACE_FOLDER) {
			if (!this._defaultFolderSettingsContentModel) {
				this._defaultFolderSettingsContentModel = new DefaultSettings(this.getMostCommonlyUsedSettings(), target);
			}
			return this._defaultFolderSettingsContentModel;
		}
		if (!this._defaultUserSettingsContentModel) {
			this._defaultUserSettingsContentModel = new DefaultSettings(this.getMostCommonlyUsedSettings(), target);
391
		}
S
Sandeep Somavarapu 已提交
392
		return this._defaultUserSettingsContentModel;
393 394
	}

395
	private getEditableSettingsURI(configurationTarget: ConfigurationTarget, resource?: URI): URI {
396 397 398 399
		switch (configurationTarget) {
			case ConfigurationTarget.USER:
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.WORKSPACE:
400
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
401 402
					return null;
				}
403
				const workspace = this.contextService.getWorkspace();
404
				return workspace.configuration || workspace.folders[0].toResource(FOLDER_SETTINGS_PATH);
405
			case ConfigurationTarget.WORKSPACE_FOLDER:
S
Sandeep Somavarapu 已提交
406
				const folder = this.contextService.getWorkspaceFolder(resource);
407
				return folder ? folder.toResource(FOLDER_SETTINGS_PATH) : null;
408
		}
409
		return null;
410 411
	}

412
	private createSettingsIfNotExists(target: ConfigurationTarget, resource: URI): TPromise<void> {
413
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && target === ConfigurationTarget.WORKSPACE) {
S
Sandeep Somavarapu 已提交
414 415 416 417 418 419 420
			return this.fileService.resolveContent(this.contextService.getWorkspace().configuration)
				.then(content => {
					if (Object.keys(parse(content.value)).indexOf('settings') === -1) {
						return this.jsonEditingService.write(resource, { key: 'settings', value: {} }, true).then(null, () => { });
					}
					return null;
				});
421
		}
S
Sandeep Somavarapu 已提交
422
		return this.createIfNotExists(resource, emptyEditableSettingsContent).then(() => { });
423 424
	}

R
Ron Buckton 已提交
425
	private createIfNotExists(resource: URI, contents: string): TPromise<any> {
426
		return this.fileService.resolveContent(resource, { acceptTextOnly: true }).then(null, error => {
427
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
428
				return this.fileService.updateContent(resource, contents).then(null, error => {
R
Ron Buckton 已提交
429
					return TPromise.wrapError(new Error(nls.localize('fail.createSettings', "Unable to create '{0}' ({1}).", labels.getPathLabel(resource, this.contextService, this.environmentService), error)));
430 431 432
				});
			}

R
Ron Buckton 已提交
433
			return TPromise.wrapError(error);
434 435 436
		});
	}

437 438
	private getMostCommonlyUsedSettings(): string[] {
		return [
S
Sandeep Somavarapu 已提交
439
			'files.autoSave',
440
			'editor.fontSize',
S
Sandeep Somavarapu 已提交
441 442 443
			'editor.fontFamily',
			'editor.tabSize',
			'editor.renderWhitespace',
S
Sandeep Somavarapu 已提交
444
			'editor.cursorStyle',
445
			'editor.multiCursorModifier',
S
Sandeep Somavarapu 已提交
446
			'editor.insertSpaces',
447
			'editor.wordWrap',
448
			'files.exclude',
S
Sandeep Somavarapu 已提交
449
			'files.associations'
450
		];
S
Sandeep Somavarapu 已提交
451
	}
452

453
	private getPosition(language: string, codeEditor: ICodeEditor): TPromise<IPosition> {
S
Sandeep Somavarapu 已提交
454
		return this.createPreferencesEditorModel(this.userSettingsResource)
455 456 457 458
			.then((settingsModel: IPreferencesEditorModel<ISetting>) => {
				const languageKey = `[${language}]`;
				let setting = settingsModel.getPreference(languageKey);
				const model = codeEditor.getModel();
459 460
				const configuration = this.configurationService.getValue<{ editor: { tabSize: number; insertSpaces: boolean }, files: { eol: string } }>();
				const eol = configuration.files && configuration.files.eol;
461 462 463 464 465
				if (setting) {
					if (setting.overrides.length) {
						const lastSetting = setting.overrides[setting.overrides.length - 1];
						let content;
						if (lastSetting.valueRange.endLineNumber === setting.range.endLineNumber) {
466
							content = ',' + eol + this.spaces(2, configuration.editor) + eol + this.spaces(1, configuration.editor);
467
						} else {
468
							content = ',' + eol + this.spaces(2, configuration.editor);
469 470 471 472 473 474 475
						}
						const editOperation = EditOperation.insert(new Position(lastSetting.valueRange.endLineNumber, lastSetting.valueRange.endColumn), content);
						model.pushEditOperations([], [editOperation], () => []);
						return { lineNumber: lastSetting.valueRange.endLineNumber + 1, column: model.getLineMaxColumn(lastSetting.valueRange.endLineNumber + 1) };
					}
					return { lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 };
				}
476
				return this.configurationService.updateValue(languageKey, {}, ConfigurationTarget.USER)
477 478
					.then(() => {
						setting = settingsModel.getPreference(languageKey);
479
						let content = eol + this.spaces(2, configuration.editor) + eol + this.spaces(1, configuration.editor);
480 481 482
						let editOperation = EditOperation.insert(new Position(setting.valueRange.endLineNumber, setting.valueRange.endColumn - 1), content);
						model.pushEditOperations([], [editOperation], () => []);
						let lineNumber = setting.valueRange.endLineNumber + 1;
S
Sandeep Somavarapu 已提交
483
						settingsModel.dispose();
484 485 486 487 488
						return { lineNumber, column: model.getLineMaxColumn(lineNumber) };
					});
			});
	}

A
Alex Dima 已提交
489
	private spaces(count: number, { tabSize, insertSpaces }: { tabSize: number; insertSpaces: boolean }): string {
490 491 492
		return insertSpaces ? strings.repeat(' ', tabSize * count) : strings.repeat('\t', count);
	}

493
	public dispose(): void {
494
		this._onDispose.fire();
495 496
		super.dispose();
	}
497
}