preferencesService.ts 27.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
import { assign } from 'vs/base/common/objects';
import * as strings from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
13
import { TPromise } from 'vs/base/common/winjs.base';
14 15 16 17 18 19 20
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';
21
import * as nls from 'vs/nls';
22
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
B
Benjamin Pasero 已提交
23
import { IEditorOptions } from 'vs/platform/editor/common/editor';
24
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
25 26
import { FileOperationError, FileOperationResult, IFileService } from 'vs/platform/files/common/files';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
27
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
28
import { ILabelService } from 'vs/platform/label/common/label';
29
import { INotificationService } from 'vs/platform/notification/common/notification';
30 31 32 33 34
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 已提交
35
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
36 37 38 39
import { GroupDirection, IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/group/common/editorGroupsService';
import { DEFAULT_SETTINGS_EDITOR_SETTING, FOLDER_SETTINGS_PATH, getSettingsTargetName, IPreferencesEditorModel, IPreferencesService, ISetting, ISettingsEditorOptions, SettingsEditorOptions } from 'vs/workbench/services/preferences/common/preferences';
import { DefaultPreferencesEditorInput, KeybindingsEditorInput, PreferencesEditorInput, SettingsEditor2Input } from 'vs/workbench/services/preferences/common/preferencesEditorInput';
import { defaultKeybindingsContents, DefaultKeybindingsEditorModel, DefaultSettings, DefaultSettingsEditorModel, Settings2EditorModel, SettingsEditorModel, WorkspaceConfigurationEditorModel } from 'vs/workbench/services/preferences/common/preferencesModels';
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;
48

M
Matt Bierner 已提交
49
	private readonly _onDispose: Emitter<void> = 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
		@IEditorService private editorService: IEditorService,
		@IEditorGroupsService private editorGroupService: IEditorGroupsService,
61 62
		@IFileService private fileService: IFileService,
		@IWorkspaceConfigurationService private configurationService: IWorkspaceConfigurationService,
63
		@INotificationService private notificationService: INotificationService,
64 65 66
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IEnvironmentService private environmentService: IEnvironmentService,
67
		@ITelemetryService private telemetryService: ITelemetryService,
68
		@ITextModelService private textModelResolverService: ITextModelService,
69
		@IKeybindingService keybindingService: IKeybindingService,
70
		@IModelService private modelService: IModelService,
71
		@IJSONEditingService private jsonEditingService: IJSONEditingService,
I
isidor 已提交
72
		@IModeService private modeService: IModeService,
I
isidor 已提交
73
		@ILabelService private labelService: ILabelService
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);
	}

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
	}

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

S
Sandeep Somavarapu 已提交
110
			const target = this.getConfigurationTargetFromDefaultSettingsResource(uri);
111
			const mode = this.modeService.getOrCreateMode('jsonc');
S
Sandeep Somavarapu 已提交
112 113 114 115 116 117 118 119 120 121
			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 已提交
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 134
			}

			return TPromise.as(model);
135 136
		}

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

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

		return TPromise.as(null);
	}

	createPreferencesEditorModel(uri: URI): TPromise<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

172
		return TPromise.wrap<IPreferencesEditorModel<any>>(null);
173 174
	}

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

B
Benjamin Pasero 已提交
179
	openRawUserSettings(): TPromise<IEditor> {
180
		return this.editorService.openEditor({ resource: this.userSettingsResource });
S
Sandeep Somavarapu 已提交
181 182
	}

183
	openSettings(jsonEditor?: boolean): TPromise<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
	}

198
	private openSettings2(): TPromise<IEditor> {
199 200 201
		const input = this.settingsEditor2Input;
		return this.editorGroupService.activeGroup.openEditor(input)
			.then(() => this.editorGroupService.activeGroup.activeControl);
202 203
	}

204 205 206 207 208
	openGlobalSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		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 215 216 217 218
	openWorkspaceSettings(jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		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"));
S
Sandeep Somavarapu 已提交
221
			return TPromise.as(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
	}

229 230 231 232 233
	openFolderSettings(folder: URI, jsonEditor?: boolean, options?: ISettingsEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		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
	}

239 240
	switchSettings(target: ConfigurationTarget, resource: URI, jsonEditor?: boolean): TPromise<void> {
		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
	}

S
Sandeep Somavarapu 已提交
252
	openGlobalKeybindingSettings(textual: boolean): TPromise<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 260 261
		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);
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 269 270 271 272
					const activeEditorGroup = this.editorGroupService.activeGroup;
					const sideEditorGroup = this.editorGroupService.addGroup(activeEditorGroup.id, GroupDirection.RIGHT);
					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 } }, sideEditorGroup.id)
					]).then(editors => void 0);
S
Sandeep Somavarapu 已提交
273 274 275
				} else {
					return this.editorService.openEditor({ resource: editableKeybindings, options: { pinned: true } }).then(() => void 0);
				}
S
Sandeep Somavarapu 已提交
276 277
			});
		}
278

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

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

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

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

311
	private openOrSwitchSettings2(configurationTarget: ConfigurationTarget, folderUri?: URI, options?: ISettingsEditorOptions, group: IEditorGroup = this.editorGroupService.activeGroup): TPromise<IEditor> {
312
		return this.doOpenSettings2(configurationTarget, folderUri, options, group);
313 314
	}

315
	private doOpenSettings(configurationTarget: ConfigurationTarget, resource: URI, options?: ISettingsEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
S
Sandeep Somavarapu 已提交
316
		const openDefaultSettings = !!this.configurationService.getValue(DEFAULT_SETTINGS_EDITOR_SETTING);
317
		return this.getOrCreateEditableSettingsEditorInput(configurationTarget, resource)
318
			.then(editableSettingsEditorInput => {
319 320 321
				if (!options) {
					options = { pinned: true };
				} else {
322
					options = assign(options, { pinned: true });
323 324
				}

325
				if (openDefaultSettings) {
S
Sandeep Somavarapu 已提交
326
					const defaultPreferencesEditorInput = this.instantiationService.createInstance(DefaultPreferencesEditorInput, this.getDefaultSettingsResource(configurationTarget));
327
					const preferencesEditorInput = new PreferencesEditorInput(this.getPreferencesEditorInputName(configurationTarget, resource), editableSettingsEditorInput.getDescription(), defaultPreferencesEditorInput, <EditorInput>editableSettingsEditorInput);
328
					this.lastOpenedSettingsInput = preferencesEditorInput;
329
					return this.editorService.openEditor(preferencesEditorInput, SettingsEditorOptions.create(options), group);
330
				}
331
				return this.editorService.openEditor(editableSettingsEditorInput, SettingsEditorOptions.create(options), group);
332
			});
333 334
	}

335 336 337 338 339 340 341 342 343 344 345 346 347
	public createSettings2EditorModel(): Settings2EditorModel {
		return this.instantiationService.createInstance(Settings2EditorModel, this.getDefaultSettings(ConfigurationTarget.USER));
	}

	private doOpenSettings2(target: ConfigurationTarget, folderUri: URI | undefined, options?: IEditorOptions, group?: IEditorGroup): TPromise<IEditor> {
		const input = this.settingsEditor2Input;
		const settingsOptions: ISettingsEditorOptions = {
			...options,
			target,
			folderUri
		};

		return this.editorService.openEditor(input, SettingsEditorOptions.create(settingsOptions), group);
348 349
	}

350
	private doSwitchSettings(target: ConfigurationTarget, resource: URI, input: PreferencesEditorInput, group: IEditorGroup, options?: ISettingsEditorOptions): TPromise<IEditor> {
351 352
		return this.getOrCreateEditableSettingsEditorInput(target, this.getEditableSettingsURI(target, resource))
			.then(toInput => {
B
Benjamin Pasero 已提交
353 354 355 356 357
				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,
358 359
						replacement: replaceWith,
						options: SettingsEditorOptions.create(options)
B
Benjamin Pasero 已提交
360 361 362 363
					}]).then(() => {
						this.lastOpenedSettingsInput = replaceWith;
						return group.activeControl;
					});
364 365 366 367
				});
			});
	}

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

S
Sandeep Somavarapu 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
	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 已提交
390 391 392 393
	private getConfigurationTargetFromDefaultSettingsResource(uri: URI) {
		return this.isDefaultWorkspaceSettingsResource(uri) ? ConfigurationTarget.WORKSPACE : this.isDefaultFolderSettingsResource(uri) ? ConfigurationTarget.WORKSPACE_FOLDER : ConfigurationTarget.USER;
	}

R
Rob Lourens 已提交
394
	private isDefaultSettingsResource(uri: URI): boolean {
S
Sandeep Somavarapu 已提交
395 396 397 398
		return this.isDefaultUserSettingsResource(uri) || this.isDefaultWorkspaceSettingsResource(uri) || this.isDefaultFolderSettingsResource(uri);
	}

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

S
Sandeep Somavarapu 已提交
402 403 404 405 406
	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 {
407
		return uri.authority === 'defaultsettings' && uri.scheme === network.Schemas.vscode && !!uri.path.match(/\/(\d+\/)?resourceSettings\.json$/);
R
Rob Lourens 已提交
408 409
	}

S
Sandeep Somavarapu 已提交
410
	private getDefaultSettingsResource(configurationTarget: ConfigurationTarget): URI {
S
Sandeep Somavarapu 已提交
411 412 413 414 415
		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 已提交
416
		}
S
Sandeep Somavarapu 已提交
417
		return URI.from({ scheme: network.Schemas.vscode, authority: 'defaultsettings', path: `/${this._defaultUserSettingsUriCounter++}/settings.json` });
S
Sandeep Somavarapu 已提交
418 419
	}

420 421
	private getPreferencesEditorInputName(target: ConfigurationTarget, resource: URI): string {
		const name = getSettingsTargetName(target, resource, this.contextService);
422
		return target === ConfigurationTarget.WORKSPACE_FOLDER ? nls.localize('folderSettingsName', "{0} (Folder Settings)", name) : name;
423 424
	}

425 426 427
	private getOrCreateEditableSettingsEditorInput(target: ConfigurationTarget, resource: URI): TPromise<EditorInput> {
		return this.createSettingsIfNotExists(target, resource)
			.then(() => <EditorInput>this.editorService.createInput({ resource }));
428 429
	}

430 431
	private createEditableSettingsEditorModel(configurationTarget: ConfigurationTarget, resource: URI): TPromise<SettingsEditorModel> {
		const settingsUri = this.getEditableSettingsURI(configurationTarget, resource);
432
		if (settingsUri) {
S
Sandeep Somavarapu 已提交
433 434 435 436
			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));
437
			}
438
			return this.textModelResolverService.createModelReference(settingsUri)
S
Sandeep Somavarapu 已提交
439
				.then(reference => this.instantiationService.createInstance(SettingsEditorModel, reference, configurationTarget));
440
		}
441
		return TPromise.wrap<SettingsEditorModel>(null);
442 443
	}

444 445 446
	private createDefaultSettingsEditorModel(defaultSettingsUri: URI): TPromise<DefaultSettingsEditorModel> {
		return this.textModelResolverService.createModelReference(defaultSettingsUri)
			.then(reference => {
S
Sandeep Somavarapu 已提交
447 448
				const target = this.getConfigurationTargetFromDefaultSettingsResource(defaultSettingsUri);
				return this.instantiationService.createInstance(DefaultSettingsEditorModel, defaultSettingsUri, reference, this.getDefaultSettings(target));
449 450 451
			});
	}

S
Sandeep Somavarapu 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
	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);
467
		}
S
Sandeep Somavarapu 已提交
468
		return this._defaultUserSettingsContentModel;
469 470
	}

471
	private getEditableSettingsURI(configurationTarget: ConfigurationTarget, resource?: URI): URI {
472 473 474 475
		switch (configurationTarget) {
			case ConfigurationTarget.USER:
				return URI.file(this.environmentService.appSettingsPath);
			case ConfigurationTarget.WORKSPACE:
476
				if (this.contextService.getWorkbenchState() === WorkbenchState.EMPTY) {
477 478
					return null;
				}
479
				const workspace = this.contextService.getWorkspace();
480
				return workspace.configuration || workspace.folders[0].toResource(FOLDER_SETTINGS_PATH);
481
			case ConfigurationTarget.WORKSPACE_FOLDER:
S
Sandeep Somavarapu 已提交
482
				const folder = this.contextService.getWorkspaceFolder(resource);
483
				return folder ? folder.toResource(FOLDER_SETTINGS_PATH) : null;
484
		}
485
		return null;
486 487
	}

488
	private createSettingsIfNotExists(target: ConfigurationTarget, resource: URI): TPromise<void> {
489
		if (this.contextService.getWorkbenchState() === WorkbenchState.WORKSPACE && target === ConfigurationTarget.WORKSPACE) {
S
Sandeep Somavarapu 已提交
490 491 492 493 494 495 496
			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;
				});
497
		}
S
Sandeep Somavarapu 已提交
498
		return this.createIfNotExists(resource, emptyEditableSettingsContent).then(() => { });
499 500
	}

R
Ron Buckton 已提交
501
	private createIfNotExists(resource: URI, contents: string): TPromise<any> {
502
		return this.fileService.resolveContent(resource, { acceptTextOnly: true }).then(null, error => {
503
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND) {
504
				return this.fileService.updateContent(resource, contents).then(null, error => {
505
					return TPromise.wrapError(new Error(nls.localize('fail.createSettings', "Unable to create '{0}' ({1}).", this.labelService.getUriLabel(resource, { relative: true }), error)));
506 507 508
				});
			}

R
Ron Buckton 已提交
509
			return TPromise.wrapError(error);
510 511 512
		});
	}

513 514
	private getMostCommonlyUsedSettings(): string[] {
		return [
S
Sandeep Somavarapu 已提交
515
			'files.autoSave',
516
			'editor.fontSize',
S
Sandeep Somavarapu 已提交
517 518 519
			'editor.fontFamily',
			'editor.tabSize',
			'editor.renderWhitespace',
S
Sandeep Somavarapu 已提交
520
			'editor.cursorStyle',
521
			'editor.multiCursorModifier',
S
Sandeep Somavarapu 已提交
522
			'editor.insertSpaces',
523
			'editor.wordWrap',
524
			'files.exclude',
S
Sandeep Somavarapu 已提交
525
			'files.associations'
526
		];
S
Sandeep Somavarapu 已提交
527
	}
528

S
Sandeep Somavarapu 已提交
529 530 531 532 533 534 535 536 537 538 539 540 541 542
	private getPosition(language: string, settingsModel: IPreferencesEditorModel<ISetting>, codeEditor: ICodeEditor): TPromise<IPosition> {
		const languageKey = `[${language}]`;
		let setting = settingsModel.getPreference(languageKey);
		const model = codeEditor.getModel();
		const configuration = this.configurationService.getValue<{ editor: { tabSize: number; insertSpaces: boolean }, files: { eol: string } }>();
		const eol = configuration.files && configuration.files.eol;
		if (setting) {
			if (setting.overrides.length) {
				const lastSetting = setting.overrides[setting.overrides.length - 1];
				let content;
				if (lastSetting.valueRange.endLineNumber === setting.range.endLineNumber) {
					content = ',' + eol + this.spaces(2, configuration.editor) + eol + this.spaces(1, configuration.editor);
				} else {
					content = ',' + eol + this.spaces(2, configuration.editor);
543
				}
S
Sandeep Somavarapu 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
				const editOperation = EditOperation.insert(new Position(lastSetting.valueRange.endLineNumber, lastSetting.valueRange.endColumn), content);
				model.pushEditOperations([], [editOperation], () => []);
				return TPromise.as({ lineNumber: lastSetting.valueRange.endLineNumber + 1, column: model.getLineMaxColumn(lastSetting.valueRange.endLineNumber + 1) });
			}
			return TPromise.as({ lineNumber: setting.valueRange.startLineNumber, column: setting.valueRange.startColumn + 1 });
		}
		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) };
559 560 561
			});
	}

A
Alex Dima 已提交
562
	private spaces(count: number, { tabSize, insertSpaces }: { tabSize: number; insertSpaces: boolean }): string {
563 564 565
		return insertSpaces ? strings.repeat(' ', tabSize * count) : strings.repeat('\t', count);
	}

566
	public dispose(): void {
567
		this._onDispose.fire();
568 569
		super.dispose();
	}
570
}