preferencesService.ts 30.5 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, IConfigurationService } 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';
B
Benjamin Pasero 已提交
24
import { FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
25
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
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 { IJSONEditingService } from 'vs/workbench/services/configuration/common/jsonEditing';
B
Benjamin Pasero 已提交
33
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
34
import { GroupDirection, IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
35
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';
36
import { DefaultPreferencesEditorInput, KeybindingsEditorInput, PreferencesEditorInput, SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
S
Sandeep Somavarapu 已提交
37
import { defaultKeybindingsContents, DefaultKeybindingsEditorModel, DefaultSettings, DefaultSettingsEditorModel, Settings2EditorModel, SettingsEditorModel, WorkspaceConfigurationEditorModel, DefaultRawSettingsEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
38
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
39
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
40
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
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 = null;
49

50
	private readonly _onDispose = this._register(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(
60 61
		@IEditorService private readonly editorService: IEditorService,
		@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,
62
		@ITextFileService private readonly textFileService: ITextFileService,
63
		@IConfigurationService private readonly configurationService: IConfigurationService,
64 65 66 67 68 69
		@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,
70
		@IKeybindingService keybindingService: IKeybindingService,
71 72 73
		@IModelService private readonly modelService: IModelService,
		@IJSONEditingService private readonly jsonEditingService: IJSONEditingService,
		@IModeService private readonly modeService: IModeService,
74 75
		@ILabelService private readonly labelService: ILabelService,
		@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService
76 77
	) {
		super();
78 79
		// 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.
80
		this._register(keybindingService.onDidUpdateKeybindings(() => {
81 82 83 84 85
			const model = modelService.getModel(this.defaultKeybindingsResource);
			if (!model) {
				// model has not been given out => nothing to do
				return;
			}
86
			modelService.updateModel(model, defaultKeybindingsContents(keybindingService));
87
		}));
88 89
	}

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

93
	get userSettingsResource(): URI {
S
Sandeep Somavarapu 已提交
94
		return this.getEditableSettingsURI(ConfigurationTarget.USER)!;
95 96
	}

S
Sandeep Somavarapu 已提交
97
	get workspaceSettingsResource(): URI | null {
98 99 100
		return this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE);
	}

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

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

S
Sandeep Somavarapu 已提交
109
	resolveModel(uri: URI): Promise<ITextModel | null> {
S
Sandeep Somavarapu 已提交
110
		if (this.isDefaultSettingsResource(uri)) {
S
Sandeep Somavarapu 已提交
111

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

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

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

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

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

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

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

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

S
Sandeep Somavarapu 已提交
161
		if (this.userSettingsResource.toString() === uri.toString()) {
R
Rob Lourens 已提交
162
			return this.createEditableSettingsEditorModel(ConfigurationTarget.USER_LOCAL, uri);
163
		}
164

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

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

S
Sandeep Somavarapu 已提交
174
		return Promise.reject(`unknown resource: ${uri.toString()}`);
175 176
	}

177
	openRawDefaultSettings(): Promise<IEditor | null> {
B
Benjamin Pasero 已提交
178
		return this.editorService.openEditor({ resource: this.defaultSettingsRawResource });
S
Sandeep Somavarapu 已提交
179 180
	}

181
	openRawUserSettings(): Promise<IEditor | null> {
182
		return this.editorService.openEditor({ resource: this.userSettingsResource });
S
Sandeep Somavarapu 已提交
183 184
	}

P
Peng Lyu 已提交
185
	openSettings(jsonEditor: boolean | undefined, query: string | undefined): Promise<IEditor | null> {
186 187 188 189
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

190
		if (!jsonEditor) {
P
Peng Lyu 已提交
191
			return this.openSettings2({ query: query });
192 193
		}

194
		const editorInput = this.getActiveSettingsEditorInput() || this.lastOpenedSettingsInput;
S
Sandeep Somavarapu 已提交
195
		const resource = editorInput ? editorInput.master.getResource()! : this.userSettingsResource;
S
Sandeep Somavarapu 已提交
196
		const target = this.getConfigurationTargetFromSettingsResource(resource);
P
Peng Lyu 已提交
197
		return this.openOrSwitchSettings(target, resource, { query: query });
S
Sandeep Somavarapu 已提交
198 199
	}

P
Peng Lyu 已提交
200
	private openSettings2(options?: ISettingsEditorOptions): Promise<IEditor> {
201
		const input = this.settingsEditor2Input;
P
Peng Lyu 已提交
202
		return this.editorGroupService.activeGroup.openEditor(input, options)
S
Sandeep Somavarapu 已提交
203
			.then(() => this.editorGroupService.activeGroup.activeControl!);
204 205
	}

206
	openGlobalSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
207 208 209 210
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

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

216
	async openRemoteSettings(): Promise<IEditor | null> {
R
Rob Lourens 已提交
217 218 219 220
		const environment = await this.remoteAgentService.getEnvironment();
		if (environment) {
			await this.createIfNotExists(environment.settingsPath, emptyEditableSettingsContent);
			return this.editorService.openEditor({ resource: environment.settingsPath, options: { pinned: true, revealIfOpened: true } });
221 222 223 224
		}
		return null;
	}

225
	openWorkspaceSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
226 227 228 229
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;

S
Sandeep Somavarapu 已提交
230
		if (!this.workspaceSettingsResource) {
231
			this.notificationService.info(nls.localize('openFolderFirst', "Open a folder first to create workspace settings"));
S
Sandeep Somavarapu 已提交
232
			return Promise.reject(null);
233
		}
234 235 236

		return jsonEditor ?
			this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE, this.workspaceSettingsResource, options, group) :
237
			this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE, undefined, options, group);
238 239
	}

240
	openFolderSettings(folder: URI, jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
241 242 243
		jsonEditor = typeof jsonEditor === 'undefined' ?
			this.configurationService.getValue('workbench.settings.editor') === 'json' :
			jsonEditor;
S
Sandeep Somavarapu 已提交
244 245 246 247 248 249 250 251
		const folderSettingsUri = this.getEditableSettingsURI(ConfigurationTarget.WORKSPACE_FOLDER, folder);
		if (jsonEditor) {
			if (folderSettingsUri) {
				return this.openOrSwitchSettings(ConfigurationTarget.WORKSPACE_FOLDER, folderSettingsUri, options, group);
			}
			return Promise.reject(`Invalid folder URI - ${folder.toString()}`);
		}
		return this.openOrSwitchSettings2(ConfigurationTarget.WORKSPACE_FOLDER, folder, options, group);
252 253
	}

J
Johannes Rieken 已提交
254
	switchSettings(target: ConfigurationTarget, resource: URI, jsonEditor?: boolean): Promise<void> {
255
		if (!jsonEditor) {
S
Sandeep Somavarapu 已提交
256
			return this.doOpenSettings2(target, resource).then(() => undefined);
257 258
		}

B
Benjamin Pasero 已提交
259 260
		const activeControl = this.editorService.activeControl;
		if (activeControl && activeControl.input instanceof PreferencesEditorInput) {
S
Sandeep Somavarapu 已提交
261
			return this.doSwitchSettings(target, resource, activeControl.input, activeControl.group).then(() => undefined);
262
		} else {
S
Sandeep Somavarapu 已提交
263
			return this.doOpenSettings(target, resource).then(() => undefined);
264
		}
265 266
	}

J
Johannes Rieken 已提交
267
	openGlobalKeybindingSettings(textual: boolean): Promise<void> {
K
kieferrm 已提交
268
		/* __GDPR__
K
kieferrm 已提交
269
			"openKeybindings" : {
K
kieferrm 已提交
270
				"textual" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }
K
kieferrm 已提交
271 272
			}
		*/
273
		this.telemetryService.publicLog('openKeybindings', { textual });
S
Sandeep Somavarapu 已提交
274
		if (textual) {
275
			const emptyContents = '// ' + nls.localize('emptyKeybindingsHeader', "Place your key bindings in this file to override the defaults") + '\n[\n]';
S
Sandeep Somavarapu 已提交
276
			const editableKeybindings = URI.file(this.environmentService.appKeybindingsPath);
N
Nilesh 已提交
277
			const openDefaultKeybindings = !!this.configurationService.getValue('workbench.settings.openDefaultKeybindings');
S
Sandeep Somavarapu 已提交
278 279

			// Create as needed and open in editor
S
Sandeep Somavarapu 已提交
280 281
			return this.createIfNotExists(editableKeybindings, emptyContents).then(() => {
				if (openDefaultKeybindings) {
N
Nilesh 已提交
282 283
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
R
Rob Lourens 已提交
284
					return Promise.all([
S
Sandeep Somavarapu 已提交
285 286
						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 已提交
287
					]).then(editors => undefined);
S
Sandeep Somavarapu 已提交
288
				} else {
R
Rob Lourens 已提交
289
					return this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true, revealIfOpened: true } }).then(() => undefined);
S
Sandeep Somavarapu 已提交
290
				}
S
Sandeep Somavarapu 已提交
291 292
			});
		}
293

S
Sandeep Somavarapu 已提交
294
		return this.editorService.openEditor(this.instantiationService.createInstance(KeybindingsEditorInput), { pinned: true, revealIfOpened: true }).then(() => undefined);
295 296
	}

297
	openDefaultKeybindingsFile(): Promise<IEditor | null> {
298
		return this.editorService.openEditor({ resource: this.defaultKeybindingsResource, label: nls.localize('defaultKeybindings', "Default Keybindings") });
N
Nilesh 已提交
299 300
	}

301
	configureSettingsForLanguage(language: string): void {
302
		this.openGlobalSettings(true)
S
Sandeep Somavarapu 已提交
303 304
			.then(editor => this.createPreferencesEditorModel(this.userSettingsResource)
				.then((settingsModel: IPreferencesEditorModel<ISetting>) => {
305
					const codeEditor = editor ? getCodeEditor(editor.getControl()) : null;
S
Sandeep Somavarapu 已提交
306
					if (codeEditor) {
S
Sandeep Somavarapu 已提交
307
						this.addLanguageOverrideEntry(language, settingsModel, codeEditor)
S
Sandeep Somavarapu 已提交
308
							.then(position => {
S
Sandeep Somavarapu 已提交
309
								if (codeEditor && position) {
S
Sandeep Somavarapu 已提交
310
									codeEditor.setPosition(position);
311
									codeEditor.revealLine(position.lineNumber);
S
Sandeep Somavarapu 已提交
312 313 314 315 316
									codeEditor.focus();
								}
							});
					}
				}));
317 318
	}

319
	private openOrSwitchSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): Promise<IEditor | null> {
B
Benjamin Pasero 已提交
320
		const editorInput = this.getActiveSettingsEditorInput(group);
S
Sandeep Somavarapu 已提交
321 322 323 324 325
		if (editorInput) {
			const editorInputResource = editorInput.master.getResource();
			if (editorInputResource && editorInputResource.fsPath !== resource.fsPath) {
				return this.doSwitchSettings(configurationTarget, resource, editorInput, group, options);
			}
326
		}
B
Benjamin Pasero 已提交
327
		return this.doOpenSettings(configurationTarget, resource, options, group);
328 329
	}

330
	private openOrSwitchSettings2(configurationTarget: ConfigurationTarget, folderUri?: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): Promise<IEditor | null> {
331
		return this.doOpenSettings2(configurationTarget, folderUri, options, group);
332 333
	}

334
	private doOpenSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
335 336 337 338 339
		const openSplitJSON = !!this.configurationService.getValue(USE_SPLIT_JSON_SETTING);
		if (openSplitJSON) {
			return this.doOpenSplitJSON(configurationTarget, resource, options, group);
		}

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

342
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
343
			.then(editableSettingsEditorInput => {
344 345 346
				if (!options) {
					options = { pinned: true };
				} else {
347
					options = assign(options, { pinned: true });
348 349
				}

350
				if (openDefaultSettings) {
351 352 353 354 355
					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)
S
Sandeep Somavarapu 已提交
356
					]).then(([defaultEditor, editor]) => editor);
357 358
				} else {
					return this.editorService.openEditor(editableSettingsEditorInput, SettingsEditorOptions.create(options), group);
359
				}
360
			});
361 362
	}

363
	private doOpenSplitJSON(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
		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);
			});
	}

379
	public createSettings2EditorModel(): Settings2EditorModel {
R
Rob Lourens 已提交
380
		return this.instantiationService.createInstance(Settings2EditorModel, this.getDefaultSettings(ConfigurationTarget.USER_LOCAL));
381 382
	}

383
	private doOpenSettings2(target: ConfigurationTarget, folderUri: URI | undefined, options?: IEditorOptions, group?: IEditorGroup): Promise<IEditor | null> {
384 385 386 387 388 389 390 391
		const input = this.settingsEditor2Input;
		const settingsOptions: ISettingsEditorOptions = {
			...options,
			target,
			folderUri
		};

		return this.editorService.openEditor(input, SettingsEditorOptions.create(settingsOptions), group);
392 393
	}

J
Johannes Rieken 已提交
394
	private doSwitchSettings(target: ConfigurationTarget, resource: URI, input: PreferencesEditorInput, group: IEditorGroup, options?: ISettingsEditorOptions): Promise<IEditor> {
S
Sandeep Somavarapu 已提交
395 396 397 398 399
		const settingsURI = this.getEditableSettingsURI(target, resource);
		if (!settingsURI) {
			return Promise.reject(`Invalid settings URI - ${resource.toString()}`);
		}
		return this.getOrCreateEditableSettingsEditorInput(target, settingsURI)
400
			.then(toInput => {
B
Benjamin Pasero 已提交
401 402 403 404 405
				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,
406
						replacement: replaceWith,
S
Sandeep Somavarapu 已提交
407
						options: options ? SettingsEditorOptions.create(options) : undefined
B
Benjamin Pasero 已提交
408 409
					}]).then(() => {
						this.lastOpenedSettingsInput = replaceWith;
S
Sandeep Somavarapu 已提交
410
						return group.activeControl!;
B
Benjamin Pasero 已提交
411
					});
412 413 414 415
				});
			});
	}

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

S
Sandeep Somavarapu 已提交
420 421
	private getConfigurationTargetFromSettingsResource(resource: URI): ConfigurationTarget {
		if (this.userSettingsResource.toString() === resource.toString()) {
R
Rob Lourens 已提交
422
			return ConfigurationTarget.USER_LOCAL;
S
Sandeep Somavarapu 已提交
423 424 425 426 427 428 429 430 431 432 433 434
		}

		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;
		}

R
Rob Lourens 已提交
435
		return ConfigurationTarget.USER_LOCAL;
S
Sandeep Somavarapu 已提交
436 437
	}

S
Sandeep Somavarapu 已提交
438
	private getConfigurationTargetFromDefaultSettingsResource(uri: URI) {
R
Rob Lourens 已提交
439 440 441 442 443
		return this.isDefaultWorkspaceSettingsResource(uri) ?
			ConfigurationTarget.WORKSPACE :
			this.isDefaultFolderSettingsResource(uri) ?
				ConfigurationTarget.WORKSPACE_FOLDER :
				ConfigurationTarget.USER_LOCAL;
S
Sandeep Somavarapu 已提交
444 445
	}

R
Rob Lourens 已提交
446
	private isDefaultSettingsResource(uri: URI): boolean {
S
Sandeep Somavarapu 已提交
447 448 449 450
		return this.isDefaultUserSettingsResource(uri) || this.isDefaultWorkspaceSettingsResource(uri) || this.isDefaultFolderSettingsResource(uri);
	}

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

S
Sandeep Somavarapu 已提交
454 455 456 457 458
	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 {
459
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
R
Rob Lourens 已提交
460 461
	}

S
Sandeep Somavarapu 已提交
462
	private getDefaultSettingsResource(configurationTarget: ConfigurationTarget): URI {
S
Sandeep Somavarapu 已提交
463 464 465 466 467
		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 已提交
468
		}
S
Sandeep Somavarapu 已提交
469
		return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultUserSettingsUriCounter++}/settings.json` });
S
Sandeep Somavarapu 已提交
470 471
	}

472 473
	private getPreferencesEditorInputName(target: ConfigurationTarget, resource: URI): string {
		const name = getSettingsTargetName(target, resource, this.contextService);
474
		return target === ConfigurationTarget.WORKSPACE_FOLDER ? nls.localize('folderSettingsName', "{0} (Folder Settings)", name) : name;
475 476
	}

J
Johannes Rieken 已提交
477
	private getOrCreateEditableSettingsEditorInput(target: ConfigurationTarget, resource: URI): Promise<EditorInput> {
478 479
		return this.createSettingsIfNotExists(target, resource)
			.then(() => <EditorInput>this.editorService.createInput({ resource }));
480 481
	}

J
Johannes Rieken 已提交
482
	private createEditableSettingsEditorModel(configurationTarget: ConfigurationTarget, resource: URI): Promise<SettingsEditorModel> {
483
		const settingsUri = this.getEditableSettingsURI(configurationTarget, resource);
484
		if (settingsUri) {
S
Sandeep Somavarapu 已提交
485 486 487 488
			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));
489
			}
490
			return this.textModelResolverService.createModelReference(settingsUri)
S
Sandeep Somavarapu 已提交
491
				.then(reference => this.instantiationService.createInstance(SettingsEditorModel, reference, configurationTarget));
492
		}
S
Sandeep Somavarapu 已提交
493
		return Promise.reject(`unknown target: ${configurationTarget} and resource: ${resource.toString()}`);
494 495
	}

J
Johannes Rieken 已提交
496
	private createDefaultSettingsEditorModel(defaultSettingsUri: URI): Promise<DefaultSettingsEditorModel> {
497 498
		return this.textModelResolverService.createModelReference(defaultSettingsUri)
			.then(reference => {
S
Sandeep Somavarapu 已提交
499 500
				const target = this.getConfigurationTargetFromDefaultSettingsResource(defaultSettingsUri);
				return this.instantiationService.createInstance(DefaultSettingsEditorModel, defaultSettingsUri, reference, this.getDefaultSettings(target));
501 502 503
			});
	}

S
Sandeep Somavarapu 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
	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);
519
		}
S
Sandeep Somavarapu 已提交
520
		return this._defaultUserSettingsContentModel;
521 522
	}

S
Sandeep Somavarapu 已提交
523
	private getEditableSettingsURI(configurationTarget: ConfigurationTarget, resource?: URI): URI | null {
524 525
		switch (configurationTarget) {
			case ConfigurationTarget.USER:
R
Rob Lourens 已提交
526 527 528
			case ConfigurationTarget.USER_LOCAL:
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.USER_REMOTE:
529 530
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.WORKSPACE:
531
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
532 533
					return null;
				}
534
				const workspace = this.contextService.getWorkspace();
535
				return workspace.configuration || workspace.folders[0].toResource(FOLDER_SETTINGS_PATH);
536
			case ConfigurationTarget.WORKSPACE_FOLDER:
S
Sandeep Somavarapu 已提交
537 538 539 540
				if (resource) {
					const folder = this.contextService.getWorkspaceFolder(resource);
					return folder ? folder.toResource(FOLDER_SETTINGS_PATH) : null;
				}
541
		}
542
		return null;
543 544
	}

J
Johannes Rieken 已提交
545
	private createSettingsIfNotExists(target: ConfigurationTarget, resource: URI): Promise<void> {
546
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && target === ConfigurationTarget.WORKSPACE) {
R
Rob Lourens 已提交
547 548
			const workspaceConfig = this.contextService.getWorkspace().configuration;
			if (!workspaceConfig) {
R
Rob Lourens 已提交
549
				return Promise.resolve(undefined);
R
Rob Lourens 已提交
550 551
			}

B
Benjamin Pasero 已提交
552
			return this.textFileService.read(workspaceConfig)
S
Sandeep Somavarapu 已提交
553 554
				.then(content => {
					if (Object.keys(parse(content.value)).indexOf('settings') === -1) {
R
Rob Lourens 已提交
555
						return this.jsonEditingService.write(resource, { key: 'settings', value: {} }, true).then(undefined, () => { });
S
Sandeep Somavarapu 已提交
556
					}
S
Sandeep Somavarapu 已提交
557
					return undefined;
S
Sandeep Somavarapu 已提交
558
				});
559
		}
S
Sandeep Somavarapu 已提交
560
		return this.createIfNotExists(resource, emptyEditableSettingsContent).then(() => { });
561 562
	}

J
Johannes Rieken 已提交
563
	private createIfNotExists(resource: URI, contents: string): Promise<any> {
B
Benjamin Pasero 已提交
564
		return this.textFileService.read(resource, { acceptTextOnly: true }).then(undefined, error => {
565
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
B
Benjamin Pasero 已提交
566
				return this.textFileService.write(resource, contents).then(undefined, error => {
R
Rob Lourens 已提交
567
					return Promise.reject(new Error(nls.localize('fail.createSettings', "Unable to create '{0}' ({1}).", this.labelService.getUriLabel(resource, { relative: true }), error)));
568 569 570
				});
			}

R
Rob Lourens 已提交
571
			return Promise.reject(error);
572 573 574
		});
	}

575 576
	private getMostCommonlyUsedSettings(): string[] {
		return [
S
Sandeep Somavarapu 已提交
577
			'files.autoSave',
578
			'editor.fontSize',
S
Sandeep Somavarapu 已提交
579 580 581
			'editor.fontFamily',
			'editor.tabSize',
			'editor.renderWhitespace',
S
Sandeep Somavarapu 已提交
582
			'editor.cursorStyle',
583
			'editor.multiCursorModifier',
S
Sandeep Somavarapu 已提交
584
			'editor.insertSpaces',
585
			'editor.wordWrap',
586
			'files.exclude',
S
Sandeep Somavarapu 已提交
587
			'files.associations'
588
		];
S
Sandeep Somavarapu 已提交
589
	}
590

S
Sandeep Somavarapu 已提交
591
	private addLanguageOverrideEntry(language: string, settingsModel: IPreferencesEditorModel<ISetting>, codeEditor: ICodeEditor): Promise<IPosition | null> {
S
Sandeep Somavarapu 已提交
592 593 594
		const languageKey = `[${language}]`;
		let setting = settingsModel.getPreference(languageKey);
		const model = codeEditor.getModel();
S
Sandeep Somavarapu 已提交
595 596 597 598 599 600 601 602 603
		if (model) {
			const configuration = this.configurationService.getValue<{ editor: { tabSize: number; insertSpaces: boolean } }>();
			const eol = model.getEOL();
			if (setting) {
				if (setting.overrides && setting.overrides.length) {
					const lastSetting = setting.overrides[setting.overrides.length - 1];
					return Promise.resolve({ lineNumber: lastSetting.valueRange.endLineNumber, column: model.getLineMaxColumn(lastSetting.valueRange.endLineNumber) });
				}
				return Promise.resolve({ lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 });
S
Sandeep Somavarapu 已提交
604
			}
S
Sandeep Somavarapu 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617
			return this.configurationService.updateValue(languageKey, {}, ConfigurationTarget.USER)
				.then(() => {
					setting = settingsModel.getPreference(languageKey);
					if (setting) {
						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) };
					}
					return null;
				});
S
Sandeep Somavarapu 已提交
618
		}
S
Sandeep Somavarapu 已提交
619
		return Promise.resolve(null);
620 621
	}

A
Alex Dima 已提交
622
	private spaces(count: number, { tabSize, insertSpaces }: { tabSize: number; insertSpaces: boolean }): string {
623 624 625
		return insertSpaces ? strings.repeat(' ', tabSize * count) : strings.repeat('\t', count);
	}

626
	public dispose(): void {
627
		this._onDispose.fire();
628 629
		super.dispose();
	}
630
}
631 632

registerSingleton(IPreferencesService, PreferencesService);