preferencesService.ts 28.9 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 7 8
import { Emitter } from 'vs/base/common/event';
import { parse } from 'vs/base/common/json';
import { Disposable } from 'vs/base/common/lifecycle';
9
import * as network from 'vs/base/common/network';
10 11 12 13 14 15 16 17 18 19
import { assign } from 'vs/base/common/objects';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { getCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditOperation } from 'vs/editor/common/core/editOperation';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
20
import * as nls from 'vs/nls';
21
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
22
import { IEditorOptions } from 'vs/platform/editor/common/editor';
23
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
24 25
import { FileOperationError, FileOperationResult, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
26
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
27
import { ILabelService } from 'vs/platform/label/common/label';
28
import { INotificationService } from 'vs/platform/notification/common/notification';
29 30 31 32 33
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import { EditorInput, IEditor } from 'vs/workbench/common/editor';
import { IWorkspaceConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
B
Benjamin Pasero 已提交
34
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
35
import { GroupDirection, IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
36
import { DEFAULT_SETTINGS_EDITOR_SETTING, FOLDER_SETTINGS_PATH, getSettingsTargetName, IPreferencesEditorModel, IPreferencesService, ISetting, ISettingsEditorOptions, SettingsEditorOptions, USE_SPLIT_JSON_SETTING } from 'vs/workbench/services/preferences/common/preferences';
37
import { DefaultPreferencesEditorInput, KeybindingsEditorInput, PreferencesEditorInput, SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
S
Sandeep Somavarapu 已提交
38
import { defaultKeybindingsContents, DefaultKeybindingsEditorModel, DefaultSettings, DefaultSettingsEditorModel, Settings2EditorModel, SettingsEditorModel, WorkspaceConfigurationEditorModel, DefaultRawSettingsEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
39
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
40

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

43
export class PreferencesService extends Disposable implements IPreferencesService {
44 45

	_serviceBrand: any;
46

47
	private lastOpenedSettingsInput: PreferencesEditorInput | null = null;
48

49
	private readonly _onDispose = this._register(new Emitter<void>());
50

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

58
	constructor(
59 60 61 62 63 64 65 66 67 68
		@IEditorService private readonly editorService: IEditorService,
		@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
		@IFileService private readonly fileService: IFileService,
		@IWorkspaceConfigurationService private readonly configurationService: IWorkspaceConfigurationService,
		@INotificationService private readonly notificationService: INotificationService,
		@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
		@IInstantiationService private readonly instantiationService: IInstantiationService,
		@IEnvironmentService private readonly environmentService: IEnvironmentService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@ITextModelService private readonly textModelResolverService: ITextModelService,
69
		@IKeybindingService keybindingService: IKeybindingService,
70 71 72 73
		@IModelService private readonly modelService: IModelService,
		@IJSONEditingService private readonly jsonEditingService: IJSONEditingService,
		@IModeService private readonly modeService: IModeService,
		@ILabelService private readonly labelService: ILabelService
74 75
	) {
		super();
76 77
		// 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.
78
		this._register(keybindingService.onDidUpdateKeybindings(() => {
79 80 81 82 83
			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);
	}

99 100 101 102
	get settingsEditor2Input(): SettingsEditor2Input {
		return this.instantiationService.createInstance(SettingsEditor2Input);
	}

S
Sandeep Somavarapu 已提交
103
	getFolderSettingsResource(resource: URI): URI {
104
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, resource);
S
Sandeep Somavarapu 已提交
105 106
	}

J
Johannes Rieken 已提交
107
	resolveModel(uri: URI): Promise<ITextModel> {
S
Sandeep Somavarapu 已提交
108
		if (this.isDefaultSettingsResource(uri)) {
S
Sandeep Somavarapu 已提交
109

S
Sandeep Somavarapu 已提交
110
			const target = this.getConfigurationTargetFromDefaultSettingsResource(uri);
A
Alex Dima 已提交
111 112
			const languageSelection = this.modeService.create('jsonc');
			const model = this._register(this.modelService.createModel('', languageSelection, uri));
S
Sandeep Somavarapu 已提交
113

114
			let defaultSettings: DefaultSettings | undefined;
S
Sandeep Somavarapu 已提交
115 116 117 118 119 120 121
			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 已提交
122
					defaultSettings = this.getDefaultSettings(target);
123
					this.modelService.updateModel(model, defaultSettings.getContent(true));
124
					defaultSettings._onDidChange.fire();
S
Sandeep Somavarapu 已提交
125 126 127 128 129
				}
			});

			// Check if Default settings is already created and updated in above promise
			if (!defaultSettings) {
S
Sandeep Somavarapu 已提交
130
				defaultSettings = this.getDefaultSettings(target);
131
				this.modelService.updateModel(model, defaultSettings.getContent(true));
S
Sandeep Somavarapu 已提交
132 133
			}

R
Rob Lourens 已提交
134
			return Promise.resolve(model);
135 136
		}

S
Sandeep Somavarapu 已提交
137
		if (this.defaultSettingsRawResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
138
			const defaultRawSettingsEditorModel = this.instantiationService.createInstance(DefaultRawSettingsEditorModel, this.getDefaultSettings(ConfigurationTarget.USER));
A
Alex Dima 已提交
139
			const languageSelection = this.modeService.create('jsonc');
S
Sandeep Somavarapu 已提交
140
			const model = this._register(this.modelService.createModel(defaultRawSettingsEditorModel.content, languageSelection, uri));
R
Rob Lourens 已提交
141
			return Promise.resolve(model);
S
Sandeep Somavarapu 已提交
142 143
		}

144
		if (this.defaultKeybindingsResource.toString() === uri.toString()) {
S
Sandeep Somavarapu 已提交
145
			const defaultKeybindingsEditorModel = this.instantiationService.createInstance(DefaultKeybindingsEditorModel, uri);
A
Alex Dima 已提交
146 147
			const languageSelection = this.modeService.create('jsonc');
			const model = this._register(this.modelService.createModel(defaultKeybindingsEditorModel.content, languageSelection, uri));
R
Rob Lourens 已提交
148
			return Promise.resolve(model);
149 150
		}

R
Rob Lourens 已提交
151
		return Promise.resolve(null);
152 153
	}

J
Johannes Rieken 已提交
154
	createPreferencesEditorModel(uri: URI): Promise<IPreferencesEditorModel<any>> {
S
Sandeep Somavarapu 已提交
155
		if (this.isDefaultSettingsResource(uri)) {
156
			return this.createDefaultSettingsEditorModel(uri);
157 158
		}

159
		if (this.getEditableSettingsURI(ConfigurationTarget.USER).toString() === uri.toString()) {
160
			return this.createEditableSettingsEditorModel(ConfigurationTarget.USER, uri);
161
		}
162

S
Sandeep Somavarapu 已提交
163
		const workspaceSettingsUri = this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
164
		if (workspaceSettingsUri && workspaceSettingsUri.toString() === uri.toString()) {
165
			return this.createEditableSettingsEditorModel(ConfigurationTarget.WORKSPACE, workspaceSettingsUri);
166
		}
167

168
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE) {
169
			return this.createEditableSettingsEditorModel(ConfigurationTarget.WORKSPACE_FOLDER, uri);
170
		}
171

R
Rob Lourens 已提交
172
		return Promise.resolve<IPreferencesEditorModel<any>>(null);
173 174
	}

J
Johannes Rieken 已提交
175
	openRawDefaultSettings(): Promise<IEditor> {
B
Benjamin Pasero 已提交
176
		return this.editorService.openEditor({ resource: this.defaultSettingsRawResource });
S
Sandeep Somavarapu 已提交
177 178
	}

J
Johannes Rieken 已提交
179
	openRawUserSettings(): Promise<IEditor> {
180
		return this.editorService.openEditor({ resource: this.userSettingsResource });
S
Sandeep Somavarapu 已提交
181 182
	}

J
Johannes Rieken 已提交
183
	openSettings(jsonEditor?: boolean): Promise<IEditor> {
184 185 186 187
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

188 189 190 191
		if (!jsonEditor) {
			return this.openSettings2();
		}

192 193
		const editorInput = this.getActiveSettingsEditorInput() || this.lastOpenedSettingsInput;
		const resource = editorInput ? editorInput.master.getResource() : this.userSettingsResource;
S
Sandeep Somavarapu 已提交
194
		const target = this.getConfigurationTargetFromSettingsResource(resource);
195
		return this.openOrSwitchSettings(target, resource);
S
Sandeep Somavarapu 已提交
196 197
	}

J
Johannes Rieken 已提交
198
	private openSettings2(): Promise<IEditor> {
199 200 201
		const input = this.settingsEditor2Input;
		return this.editorGroupService.activeGroup.openEditor(input)
			.then(() => this.editorGroupService.activeGroup.activeControl);
202 203
	}

J
Johannes Rieken 已提交
204
	openGlobalSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
205 206 207 208
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

209 210
		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.USER, this.userSettingsResource, options, group) :
211
			this.openOrSwitchSettings2(ConfigurationTarget.USER, undefined, options, group);
R
Rob Lourens 已提交
212 213
	}

214
	openWorkspaceSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
215 216 217 218
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

219
		if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
220
			this.notificationService.info(nls.localize('openFolderFirst', "Open a folder first to create workspace settings"));
R
Rob Lourens 已提交
221
			return Promise.resolve(null);
222
		}
223 224 225

		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE, this.workspaceSettingsResource, options, group) :
226
			this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE, undefined, options, group);
227 228
	}

J
Johannes Rieken 已提交
229
	openFolderSettings(folder: URI, jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
230 231 232 233
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

234 235
		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE_FOLDER, this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, folder), options, group) :
236
			this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE_FOLDER, folder, options, group);
237 238
	}

J
Johannes Rieken 已提交
239
	switchSettings(target: ConfigurationTarget, resource: URI, jsonEditor?: boolean): Promise<void> {
240
		if (!jsonEditor) {
241
			return this.doOpenSettings2(target, resource).then(() => null);
242 243
		}

B
Benjamin Pasero 已提交
244 245
		const activeControl = this.editorService.activeControl;
		if (activeControl && activeControl.input instanceof PreferencesEditorInput) {
246
			return this.doSwitchSettings(target, resource, activeControl.input, activeControl.group).then(() => null);
247
		} else {
248
			return this.doOpenSettings(target, resource).then(() => null);
249
		}
250 251
	}

J
Johannes Rieken 已提交
252
	openGlobalKeybindingSettings(textual: boolean): Promise<void> {
K
kieferrm 已提交
253
		/* __GDPR__
K
kieferrm 已提交
254
			"openKeybindings" : {
K
kieferrm 已提交
255
				"textual" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
K
kieferrm 已提交
256 257
			}
		*/
258
		this.telemetryService.publicLog('openKeybindings', { textual });
S
Sandeep Somavarapu 已提交
259
		if (textual) {
260
			const emptyContents = '// ' + nls.localize('emptyKeybindingsHeader', "Place your key bindings in this file to override the defaults") + '\n[\n]';
S
Sandeep Somavarapu 已提交
261
			const editableKeybindings = URI.file(this.environmentService.appKeybindingsPath);
N
Nilesh 已提交
262
			const openDefaultKeybindings = !!this.configurationService.getValue('workbench.settings.openDefaultKeybindings');
S
Sandeep Somavarapu 已提交
263 264

			// Create as needed and open in editor
S
Sandeep Somavarapu 已提交
265 266
			return this.createIfNotExists(editableKeybindings, emptyContents).then(() => {
				if (openDefaultKeybindings) {
N
Nilesh 已提交
267 268
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
R
Rob Lourens 已提交
269
					return Promise.all([
S
Sandeep Somavarapu 已提交
270 271
						this.editorService.openEditor({ resource: this.defaultKeybindingsResource, options: { pinned: true, preserveFocus: true, revealIfOpened: true }, label: nls.localize('defaultKeybindings', "Default Keybindings"), description: '' }),
						this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true, revealIfOpened: true } }, sideEditorGroup.id)
R
Rob Lourens 已提交
272
					]).then(editors => undefined);
S
Sandeep Somavarapu 已提交
273
				} else {
R
Rob Lourens 已提交
274
					return this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true, revealIfOpened: true } }).then(() => undefined);
S
Sandeep Somavarapu 已提交
275
				}
S
Sandeep Somavarapu 已提交
276 277
			});
		}
278

S
Sandeep Somavarapu 已提交
279
		return this.editorService.openEditor(this.instantiationService.createInstance(KeybindingsEditorInput), { pinned: true, revealIfOpened: true }).then(() => null);
280 281
	}

J
Johannes Rieken 已提交
282
	openDefaultKeybindingsFile(): Promise<IEditor> {
283
		return this.editorService.openEditor({ resource: this.defaultKeybindingsResource, label: nls.localize('defaultKeybindings', "Default Keybindings") });
N
Nilesh 已提交
284 285
	}

286
	configureSettingsForLanguage(language: string): void {
287
		this.openGlobalSettings(true)
S
Sandeep Somavarapu 已提交
288 289 290 291
			.then(editor => this.createPreferencesEditorModel(this.userSettingsResource)
				.then((settingsModel: IPreferencesEditorModel<ISetting>) => {
					const codeEditor = getCodeEditor(editor.getControl());
					if (codeEditor) {
S
Sandeep Somavarapu 已提交
292
						this.addLanguageOverrideEntry(language, settingsModel, codeEditor)
S
Sandeep Somavarapu 已提交
293 294 295
							.then(position => {
								if (codeEditor) {
									codeEditor.setPosition(position);
296
									codeEditor.revealLine(position.lineNumber);
S
Sandeep Somavarapu 已提交
297 298 299 300 301
									codeEditor.focus();
								}
							});
					}
				}));
302 303
	}

J
Johannes Rieken 已提交
304
	private openOrSwitchSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): Promise<IEditor> {
B
Benjamin Pasero 已提交
305
		const editorInput = this.getActiveSettingsEditorInput(group);
306
		if (editorInput && editorInput.master.getResource().fsPath !== resource.fsPath) {
307
			return this.doSwitchSettings(configurationTarget, resource, editorInput, group, options);
308
		}
B
Benjamin Pasero 已提交
309
		return this.doOpenSettings(configurationTarget, resource, options, group);
310 311
	}

J
Johannes Rieken 已提交
312
	private openOrSwitchSettings2(configurationTarget: ConfigurationTarget, folderUri?: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): Promise<IEditor> {
313
		return this.doOpenSettings2(configurationTarget, folderUri, options, group);
314 315
	}

J
Johannes Rieken 已提交
316
	private doOpenSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
317 318 319 320 321
		const openSplitJSON = !!this.configurationService.getValue(USE_SPLIT_JSON_SETTING);
		if (openSplitJSON) {
			return this.doOpenSplitJSON(configurationTarget, resource, options, group);
		}

S
Sandeep Somavarapu 已提交
322
		const openDefaultSettings = !!this.configurationService.getValue(DEFAULT_SETTINGS_EDITOR_SETTING);
323

324
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
325
			.then(editableSettingsEditorInput => {
326 327 328
				if (!options) {
					options = { pinned: true };
				} else {
329
					options = assign(options, { pinned: true });
330 331
				}

332
				if (openDefaultSettings) {
333 334 335 336 337 338 339 340
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
					return Promise.all([
						this.editorService.openEditor({ resource: this.defaultSettingsRawResource, options: { pinned: true, preserveFocus: true, revealIfOpened: true }, label: nls.localize('defaultSettings', "Default Settings"), description: '' }),
						this.editorService.openEditor(editableSettingsEditorInput, { pinned: true, revealIfOpened: true }, sideEditorGroup.id)
					]).then(() => null);
				} else {
					return this.editorService.openEditor(editableSettingsEditorInput, SettingsEditorOptions.create(options), group);
341
				}
342
			});
343 344
	}

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
	private doOpenSplitJSON(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor> {
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
			.then(editableSettingsEditorInput => {
				if (!options) {
					options = { pinned: true };
				} else {
					options = assign(options, { pinned: true });
				}

				const defaultPreferencesEditorInput = this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(configurationTarget));
				const preferencesEditorInput = new PreferencesEditorInput(this.getPreferencesEditorInputName(configurationTarget, resource), editableSettingsEditorInput.getDescription(), defaultPreferencesEditorInput, <EditorInput>editableSettingsEditorInput);
				this.lastOpenedSettingsInput = preferencesEditorInput;
				return this.editorService.openEditor(preferencesEditorInput, SettingsEditorOptions.create(options), group);
			});
	}

361 362 363 364
	public createSettings2EditorModel(): Settings2EditorModel {
		return this.instantiationService.createInstance(Settings2EditorModel, this.getDefaultSettings(ConfigurationTarget.USER));
	}

J
Johannes Rieken 已提交
365
	private doOpenSettings2(target: ConfigurationTarget, folderUri: URI | undefined, options?: IEditorOptions, group?: IEditorGroup): Promise<IEditor> {
366 367 368 369 370 371 372 373
		const input = this.settingsEditor2Input;
		const settingsOptions: ISettingsEditorOptions = {
			...options,
			target,
			folderUri
		};

		return this.editorService.openEditor(input, SettingsEditorOptions.create(settingsOptions), group);
374 375
	}

J
Johannes Rieken 已提交
376
	private doSwitchSettings(target: ConfigurationTarget, resource: URI, input: PreferencesEditorInput, group: IEditorGroup, options?: ISettingsEditorOptions): Promise<IEditor> {
377 378
		return this.getOrCreateEditableSettingsEditorInput(target, this.getEditableSettingsURI(target, resource))
			.then(toInput => {
B
Benjamin Pasero 已提交
379 380 381 382 383
				return group.openEditor(input).then(() => {
					const replaceWith = new PreferencesEditorInput(this.getPreferencesEditorInputName(target, resource), toInput.getDescription(), this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(target)), toInput);

					return group.replaceEditors([{
						editor: input,
384 385
						replacement: replaceWith,
						options: SettingsEditorOptions.create(options)
B
Benjamin Pasero 已提交
386 387 388 389
					}]).then(() => {
						this.lastOpenedSettingsInput = replaceWith;
						return group.activeControl;
					});
390 391 392 393
				});
			});
	}

394
	private getActiveSettingsEditorInput(group: IEditorGroup = this.editorGroupService.activeGroup): PreferencesEditorInput {
B
Benjamin Pasero 已提交
395
		return <PreferencesEditorInput>group.editors.filter(e => e instanceof PreferencesEditorInput)[0];
396 397
	}

S
Sandeep Somavarapu 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
	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 已提交
416 417 418 419
	private getConfigurationTargetFromDefaultSettingsResource(uri: URI) {
		return this.isDefaultWorkspaceSettingsResource(uri) ? ConfigurationTarget.WORKSPACE : this.isDefaultFolderSettingsResource(uri) ? ConfigurationTarget.WORKSPACE_FOLDER : ConfigurationTarget.USER;
	}

R
Rob Lourens 已提交
420
	private isDefaultSettingsResource(uri: URI): boolean {
S
Sandeep Somavarapu 已提交
421 422 423 424
		return this.isDefaultUserSettingsResource(uri) || this.isDefaultWorkspaceSettingsResource(uri) || this.isDefaultFolderSettingsResource(uri);
	}

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

S
Sandeep Somavarapu 已提交
428 429 430 431 432
	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 {
433
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
R
Rob Lourens 已提交
434 435
	}

S
Sandeep Somavarapu 已提交
436
	private getDefaultSettingsResource(configurationTarget: ConfigurationTarget): URI {
S
Sandeep Somavarapu 已提交
437 438 439 440 441
		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 已提交
442
		}
S
Sandeep Somavarapu 已提交
443
		return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultUserSettingsUriCounter++}/settings.json` });
S
Sandeep Somavarapu 已提交
444 445
	}

446 447
	private getPreferencesEditorInputName(target: ConfigurationTarget, resource: URI): string {
		const name = getSettingsTargetName(target, resource, this.contextService);
448
		return target === ConfigurationTarget.WORKSPACE_FOLDER ? nls.localize('folderSettingsName', "{0} (Folder Settings)", name) : name;
449 450
	}

J
Johannes Rieken 已提交
451
	private getOrCreateEditableSettingsEditorInput(target: ConfigurationTarget, resource: URI): Promise<EditorInput> {
452 453
		return this.createSettingsIfNotExists(target, resource)
			.then(() => <EditorInput>this.editorService.createInput({ resource }));
454 455
	}

J
Johannes Rieken 已提交
456
	private createEditableSettingsEditorModel(configurationTarget: ConfigurationTarget, resource: URI): Promise<SettingsEditorModel> {
457
		const settingsUri = this.getEditableSettingsURI(configurationTarget, resource);
458
		if (settingsUri) {
S
Sandeep Somavarapu 已提交
459 460 461 462
			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));
463
			}
464
			return this.textModelResolverService.createModelReference(settingsUri)
S
Sandeep Somavarapu 已提交
465
				.then(reference => this.instantiationService.createInstance(SettingsEditorModel, reference, configurationTarget));
466
		}
R
Rob Lourens 已提交
467
		return Promise.resolve<SettingsEditorModel>(null);
468 469
	}

J
Johannes Rieken 已提交
470
	private createDefaultSettingsEditorModel(defaultSettingsUri: URI): Promise<DefaultSettingsEditorModel> {
471 472
		return this.textModelResolverService.createModelReference(defaultSettingsUri)
			.then(reference => {
S
Sandeep Somavarapu 已提交
473 474
				const target = this.getConfigurationTargetFromDefaultSettingsResource(defaultSettingsUri);
				return this.instantiationService.createInstance(DefaultSettingsEditorModel, defaultSettingsUri, reference, this.getDefaultSettings(target));
475 476 477
			});
	}

S
Sandeep Somavarapu 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
	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);
493
		}
S
Sandeep Somavarapu 已提交
494
		return this._defaultUserSettingsContentModel;
495 496
	}

497
	private getEditableSettingsURI(configurationTarget: ConfigurationTarget, resource?: URI): URI {
498 499 500 501
		switch (configurationTarget) {
			case ConfigurationTarget.USER:
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.WORKSPACE:
502
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
503 504
					return null;
				}
505
				const workspace = this.contextService.getWorkspace();
506
				return workspace.configuration || workspace.folders[0].toResource(FOLDER_SETTINGS_PATH);
507
			case ConfigurationTarget.WORKSPACE_FOLDER:
S
Sandeep Somavarapu 已提交
508
				const folder = this.contextService.getWorkspaceFolder(resource);
509
				return folder ? folder.toResource(FOLDER_SETTINGS_PATH) : null;
510
		}
511
		return null;
512 513
	}

J
Johannes Rieken 已提交
514
	private createSettingsIfNotExists(target: ConfigurationTarget, resource: URI): Promise<void> {
515
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && target === ConfigurationTarget.WORKSPACE) {
R
Rob Lourens 已提交
516 517
			const workspaceConfig = this.contextService.getWorkspace().configuration;
			if (!workspaceConfig) {
R
Rob Lourens 已提交
518
				return Promise.resolve(undefined);
R
Rob Lourens 已提交
519 520 521
			}

			return this.fileService.resolveContent(workspaceConfig)
S
Sandeep Somavarapu 已提交
522 523
				.then(content => {
					if (Object.keys(parse(content.value)).indexOf('settings') === -1) {
R
Rob Lourens 已提交
524
						return this.jsonEditingService.write(resource, { key: 'settings', value: {} }, true).then(undefined, () => { });
S
Sandeep Somavarapu 已提交
525 526 527
					}
					return null;
				});
528
		}
S
Sandeep Somavarapu 已提交
529
		return this.createIfNotExists(resource, emptyEditableSettingsContent).then(() => { });
530 531
	}

J
Johannes Rieken 已提交
532
	private createIfNotExists(resource: URI, contents: string): Promise<any> {
R
Rob Lourens 已提交
533
		return this.fileService.resolveContent(resource, { acceptTextOnly: true }).then(undefined, error => {
534
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
R
Rob Lourens 已提交
535
				return this.fileService.updateContent(resource, contents).then(undefined, error => {
R
Rob Lourens 已提交
536
					return Promise.reject(new Error(nls.localize('fail.createSettings', "Unable to create '{0}' ({1}).", this.labelService.getUriLabel(resource, { relative: true }), error)));
537 538 539
				});
			}

R
Rob Lourens 已提交
540
			return Promise.reject(error);
541 542 543
		});
	}

544 545
	private getMostCommonlyUsedSettings(): string[] {
		return [
S
Sandeep Somavarapu 已提交
546
			'files.autoSave',
547
			'editor.fontSize',
S
Sandeep Somavarapu 已提交
548 549 550
			'editor.fontFamily',
			'editor.tabSize',
			'editor.renderWhitespace',
S
Sandeep Somavarapu 已提交
551
			'editor.cursorStyle',
552
			'editor.multiCursorModifier',
S
Sandeep Somavarapu 已提交
553
			'editor.insertSpaces',
554
			'editor.wordWrap',
555
			'files.exclude',
S
Sandeep Somavarapu 已提交
556
			'files.associations'
557
		];
S
Sandeep Somavarapu 已提交
558
	}
559

J
Johannes Rieken 已提交
560
	private addLanguageOverrideEntry(language: string, settingsModel: IPreferencesEditorModel<ISetting>, codeEditor: ICodeEditor): Promise<IPosition> {
S
Sandeep Somavarapu 已提交
561 562 563
		const languageKey = `[${language}]`;
		let setting = settingsModel.getPreference(languageKey);
		const model = codeEditor.getModel();
S
Sandeep Somavarapu 已提交
564 565
		const configuration = this.configurationService.getValue<{ editor: { tabSize: number; insertSpaces: boolean } }>();
		const eol = model.getEOL();
S
Sandeep Somavarapu 已提交
566 567 568
		if (setting) {
			if (setting.overrides.length) {
				const lastSetting = setting.overrides[setting.overrides.length - 1];
S
Sandeep Somavarapu 已提交
569
				return Promise.resolve({ lineNumber: lastSetting.valueRange.endLineNumber, column: model.getLineMaxColumn(lastSetting.valueRange.endLineNumber) });
S
Sandeep Somavarapu 已提交
570
			}
R
Rob Lourens 已提交
571
			return Promise.resolve({ lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 });
S
Sandeep Somavarapu 已提交
572 573 574 575 576 577 578 579 580 581
		}
		return this.configurationService.updateValue(languageKey, {}, ConfigurationTarget.USER)
			.then(() => {
				setting = settingsModel.getPreference(languageKey);
				let content = eol + this.spaces(2, configuration.editor) + eol + this.spaces(1, configuration.editor);
				let editOperation = EditOperation.insert(new Position(setting.valueRange.endLineNumber, setting.valueRange.endColumn - 1), content);
				model.pushEditOperations([], [editOperation], () => []);
				let lineNumber = setting.valueRange.endLineNumber + 1;
				settingsModel.dispose();
				return { lineNumber, column: model.getLineMaxColumn(lineNumber) };
582 583 584
			});
	}

A
Alex Dima 已提交
585
	private spaces(count: number, { tabSize, insertSpaces }: { tabSize: number; insertSpaces: boolean }): string {
586 587 588
		return insertSpaces ? strings.repeat(' ', tabSize * count) : strings.repeat('\t', count);
	}

589
	public dispose(): void {
590
		this._onDispose.fire();
591 592
		super.dispose();
	}
593
}
594 595

registerSingleton(IPreferencesService, PreferencesService);