extHost.api.impl.ts 44.0 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import { Emitter } from 'vs/base/common/event';
8
import { TernarySearchTree } from 'vs/base/common/map';
J
Johannes Rieken 已提交
9
import { score } from 'vs/editor/common/modes/languageSelector';
A
Alex Dima 已提交
10
import * as platform from 'vs/base/common/platform';
E
Erich Gamma 已提交
11
import * as errors from 'vs/base/common/errors';
12 13
import product from 'vs/platform/node/product';
import pkg from 'vs/platform/node/package';
J
Johannes Rieken 已提交
14
import { ExtHostFileSystemEventService } from 'vs/workbench/api/node/extHostFileSystemEventService';
J
Johannes Rieken 已提交
15
import { ExtHostDocumentsAndEditors } from 'vs/workbench/api/node/extHostDocumentsAndEditors';
J
Johannes Rieken 已提交
16
import { ExtHostDocuments } from 'vs/workbench/api/node/extHostDocuments';
17
import { ExtHostDocumentContentProvider } from 'vs/workbench/api/node/extHostDocumentContentProviders';
J
Johannes Rieken 已提交
18 19 20
import { ExtHostDocumentSaveParticipant } from 'vs/workbench/api/node/extHostDocumentSaveParticipant';
import { ExtHostConfiguration } from 'vs/workbench/api/node/extHostConfiguration';
import { ExtHostDiagnostics } from 'vs/workbench/api/node/extHostDiagnostics';
S
Sandeep Somavarapu 已提交
21
import { ExtHostTreeViews } from 'vs/workbench/api/node/extHostTreeViews';
J
Johannes Rieken 已提交
22 23
import { ExtHostWorkspace } from 'vs/workbench/api/node/extHostWorkspace';
import { ExtHostQuickOpen } from 'vs/workbench/api/node/extHostQuickOpen';
24
import { ExtHostProgress } from 'vs/workbench/api/node/extHostProgress';
J
Joao Moreno 已提交
25
import { ExtHostSCM } from 'vs/workbench/api/node/extHostSCM';
J
Johannes Rieken 已提交
26 27 28 29 30 31
import { ExtHostHeapService } from 'vs/workbench/api/node/extHostHeapService';
import { ExtHostStatusBar } from 'vs/workbench/api/node/extHostStatusBar';
import { ExtHostCommands } from 'vs/workbench/api/node/extHostCommands';
import { ExtHostOutputService } from 'vs/workbench/api/node/extHostOutputService';
import { ExtHostTerminalService } from 'vs/workbench/api/node/extHostTerminalService';
import { ExtHostMessageService } from 'vs/workbench/api/node/extHostMessageService';
J
Johannes Rieken 已提交
32
import { ExtHostEditors } from 'vs/workbench/api/node/extHostTextEditors';
J
Johannes Rieken 已提交
33
import { ExtHostLanguages } from 'vs/workbench/api/node/extHostLanguages';
A
Alex Dima 已提交
34
import { ExtHostLanguageFeatures, ISchemeTransformer } from 'vs/workbench/api/node/extHostLanguageFeatures';
35
import { ExtHostApiCommands } from 'vs/workbench/api/node/extHostApiCommands';
36
import { ExtHostTask } from 'vs/workbench/api/node/extHostTask';
37
import { ExtHostDebugService } from 'vs/workbench/api/node/extHostDebugService';
38
import { ExtHostWindow } from 'vs/workbench/api/node/extHostWindow';
J
Johannes Rieken 已提交
39
import * as extHostTypes from 'vs/workbench/api/node/extHostTypes';
40
import { URI } from 'vs/base/common/uri';
E
Erich Gamma 已提交
41
import Severity from 'vs/base/common/severity';
42
import { IExtensionDescription } from 'vs/workbench/services/extensions/common/extensions';
J
Johannes Rieken 已提交
43 44 45
import { ExtHostExtensionService } from 'vs/workbench/api/node/extHostExtensionService';
import { TPromise } from 'vs/base/common/winjs.base';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
46
import * as vscode from 'vscode';
E
Erich Gamma 已提交
47
import * as paths from 'vs/base/common/paths';
48
import * as files from 'vs/platform/files/common/files';
49
import { MainContext, ExtHostContext, IInitData, IMainContext } from './extHost.protocol';
50
import * as languageConfiguration from 'vs/editor/common/modes/languageConfiguration';
51
import { TextEditorCursorStyle } from 'vs/editor/common/config/editorOptions';
A
Alex Dima 已提交
52
import { ProxyIdentifier } from 'vs/workbench/services/extensions/node/proxyIdentifier';
B
Benjamin Pasero 已提交
53
import { ExtHostDialogs } from 'vs/workbench/api/node/extHostDialogs';
54
import { ExtHostFileSystem } from 'vs/workbench/api/node/extHostFileSystem';
55
import { ExtHostDecorations } from 'vs/workbench/api/node/extHostDecorations';
56
import * as typeConverters from 'vs/workbench/api/node/extHostTypeConverters';
A
Alex Dima 已提交
57
import { ExtensionActivatedByAPI } from 'vs/workbench/api/node/extHostExtensionActivator';
A
Alex Dima 已提交
58
import { OverviewRulerLane } from 'vs/editor/common/model';
59
import { ExtHostLogService } from 'vs/workbench/api/node/extHostLogService';
M
Matt Bierner 已提交
60
import { ExtHostWebviews } from 'vs/workbench/api/node/extHostWebview';
M
Matt Bierner 已提交
61
import { ExtHostComments } from './extHostComments';
62
import { ExtHostSearch } from './extHostSearch';
J
Joao Moreno 已提交
63
import { ExtHostUrls } from './extHostUrls';
64 65
import { toLocalISOString } from 'vs/base/common/date';
import { posix } from 'path';
E
Erich Gamma 已提交
66

67
export interface IExtensionApiFactory {
68
	(extension: IExtensionDescription): typeof vscode;
69 70
}

71 72 73 74 75 76 77 78 79 80
export function checkProposedApiEnabled(extension: IExtensionDescription): void {
	if (!extension.enableProposedApi) {
		throwProposedApiError(extension);
	}
}

function throwProposedApiError(extension: IExtensionDescription): never {
	throw new Error(`[${extension.id}]: Proposed API is only available when running out of dev or with the following command line switch: --enable-proposed-api ${extension.id}`);
}

81
function proposedApiFunction<T>(extension: IExtensionDescription, fn: T): T {
82
	if (extension.enableProposedApi) {
83 84
		return fn;
	} else {
85
		return throwProposedApiError.bind(null, extension);
86 87 88
	}
}

E
Erich Gamma 已提交
89
/**
90
 * This method instantiates and returns the extension API surface
E
Erich Gamma 已提交
91
 */
92 93
export function createApiFactory(
	initData: IInitData,
94
	rpcProtocol: IMainContext,
95 96
	extHostWorkspace: ExtHostWorkspace,
	extHostConfiguration: ExtHostConfiguration,
J
Joao Moreno 已提交
97
	extensionService: ExtHostExtensionService,
98
	extHostLogService: ExtHostLogService
99
): IExtensionApiFactory {
100

A
Alex Dima 已提交
101 102
	let schemeTransformer: ISchemeTransformer = null;

103
	// Addressable instances
104
	rpcProtocol.set(ExtHostContext.ExtHostLogService, extHostLogService);
A
Alex Dima 已提交
105 106
	const extHostHeapService = rpcProtocol.set(ExtHostContext.ExtHostHeapService, new ExtHostHeapService());
	const extHostDecorations = rpcProtocol.set(ExtHostContext.ExtHostDecorations, new ExtHostDecorations(rpcProtocol));
M
Matt Bierner 已提交
107
	const extHostWebviews = rpcProtocol.set(ExtHostContext.ExtHostWebviews, new ExtHostWebviews(rpcProtocol));
J
Joao Moreno 已提交
108
	const extHostUrls = rpcProtocol.set(ExtHostContext.ExtHostUrls, new ExtHostUrls(rpcProtocol));
109
	const extHostDocumentsAndEditors = rpcProtocol.set(ExtHostContext.ExtHostDocumentsAndEditors, new ExtHostDocumentsAndEditors(rpcProtocol));
A
Alex Dima 已提交
110
	const extHostDocuments = rpcProtocol.set(ExtHostContext.ExtHostDocuments, new ExtHostDocuments(rpcProtocol, extHostDocumentsAndEditors));
111
	const extHostDocumentContentProviders = rpcProtocol.set(ExtHostContext.ExtHostDocumentContentProviders, new ExtHostDocumentContentProvider(rpcProtocol, extHostDocumentsAndEditors, extHostLogService));
112
	const extHostDocumentSaveParticipant = rpcProtocol.set(ExtHostContext.ExtHostDocumentSaveParticipant, new ExtHostDocumentSaveParticipant(extHostLogService, extHostDocuments, rpcProtocol.getProxy(MainContext.MainThreadTextEditors)));
A
Alex Dima 已提交
113
	const extHostEditors = rpcProtocol.set(ExtHostContext.ExtHostEditors, new ExtHostEditors(rpcProtocol, extHostDocumentsAndEditors));
114
	const extHostCommands = rpcProtocol.set(ExtHostContext.ExtHostCommands, new ExtHostCommands(rpcProtocol, extHostHeapService, extHostLogService));
S
Sandeep Somavarapu 已提交
115
	const extHostTreeViews = rpcProtocol.set(ExtHostContext.ExtHostTreeViews, new ExtHostTreeViews(rpcProtocol.getProxy(MainContext.MainThreadTreeViews), extHostCommands, extHostLogService));
A
Alex Dima 已提交
116 117 118
	rpcProtocol.set(ExtHostContext.ExtHostWorkspace, extHostWorkspace);
	rpcProtocol.set(ExtHostContext.ExtHostConfiguration, extHostConfiguration);
	const extHostDiagnostics = rpcProtocol.set(ExtHostContext.ExtHostDiagnostics, new ExtHostDiagnostics(rpcProtocol));
119
	const extHostLanguageFeatures = rpcProtocol.set(ExtHostContext.ExtHostLanguageFeatures, new ExtHostLanguageFeatures(rpcProtocol, schemeTransformer, extHostDocuments, extHostCommands, extHostHeapService, extHostDiagnostics, extHostLogService));
120
	const extHostFileSystem = rpcProtocol.set(ExtHostContext.ExtHostFileSystem, new ExtHostFileSystem(rpcProtocol, extHostLanguageFeatures));
121
	const extHostFileSystemEvent = rpcProtocol.set(ExtHostContext.ExtHostFileSystemEventService, new ExtHostFileSystemEventService(rpcProtocol, extHostDocumentsAndEditors));
A
Alex Dima 已提交
122
	const extHostQuickOpen = rpcProtocol.set(ExtHostContext.ExtHostQuickOpen, new ExtHostQuickOpen(rpcProtocol, extHostWorkspace, extHostCommands));
123
	const extHostTerminalService = rpcProtocol.set(ExtHostContext.ExtHostTerminalService, new ExtHostTerminalService(rpcProtocol, extHostConfiguration, extHostLogService));
124
	const extHostDebugService = rpcProtocol.set(ExtHostContext.ExtHostDebugService, new ExtHostDebugService(rpcProtocol, extHostWorkspace, extensionService, extHostDocumentsAndEditors, extHostConfiguration, extHostTerminalService));
125
	const extHostSCM = rpcProtocol.set(ExtHostContext.ExtHostSCM, new ExtHostSCM(rpcProtocol, extHostCommands, extHostLogService));
A
Alex Dima 已提交
126
	const extHostSearch = rpcProtocol.set(ExtHostContext.ExtHostSearch, new ExtHostSearch(rpcProtocol, schemeTransformer));
127
	const extHostTask = rpcProtocol.set(ExtHostContext.ExtHostTask, new ExtHostTask(rpcProtocol, extHostWorkspace, extHostDocumentsAndEditors, extHostConfiguration));
A
Alex Dima 已提交
128 129
	const extHostWindow = rpcProtocol.set(ExtHostContext.ExtHostWindow, new ExtHostWindow(rpcProtocol));
	rpcProtocol.set(ExtHostContext.ExtHostExtensionService, extensionService);
130
	const extHostProgress = rpcProtocol.set(ExtHostContext.ExtHostProgress, new ExtHostProgress(rpcProtocol.getProxy(MainContext.MainThreadProgress)));
131
	const exthostCommentProviders = rpcProtocol.set(ExtHostContext.ExtHostComments, new ExtHostComments(rpcProtocol, extHostCommands.converter, extHostDocuments));
132 133

	// Check that no named customers are missing
A
Alex Dima 已提交
134
	const expected: ProxyIdentifier<any>[] = Object.keys(ExtHostContext).map((key) => (<any>ExtHostContext)[key]);
A
Alex Dima 已提交
135
	rpcProtocol.assertRegistered(expected);
136

137
	// Other instances
A
Alex Dima 已提交
138 139 140
	const extHostMessageService = new ExtHostMessageService(rpcProtocol);
	const extHostDialogs = new ExtHostDialogs(rpcProtocol);
	const extHostStatusBar = new ExtHostStatusBar(rpcProtocol);
141 142
	const outputPath = posix.join(initData.logsLocation.fsPath, `output_logging_${toLocalISOString(new Date()).replace(/-|:|\.\d+Z$/g, '')}`);
	const extHostOutputService = new ExtHostOutputService(outputPath, rpcProtocol);
A
Alex Dima 已提交
143
	const extHostLanguages = new ExtHostLanguages(rpcProtocol);
144

145
	// Register API-ish commands
146
	ExtHostApiCommands.register(extHostCommands);
147

148
	return function (extension: IExtensionDescription): typeof vscode {
149

150 151 152 153 154 155
		// Check document selectors for being overly generic. Technically this isn't a problem but
		// in practice many extensions say they support `fooLang` but need fs-access to do so. Those
		// extension should specify then the `file`-scheme, e.g `{ scheme: 'fooLang', language: 'fooLang' }`
		// We only inform once, it is not a warning because we just want to raise awareness and because
		// we cannot say if the extension is doing it right or wrong...
		let checkSelector = (function () {
A
Alex Dima 已提交
156
			let done = (!extension.isUnderDevelopment);
157 158 159 160 161
			function informOnce(selector: vscode.DocumentSelector) {
				if (!done) {
					console.info(`Extension '${extension.id}' uses a document selector without scheme. Learn more about this: https://go.microsoft.com/fwlink/?linkid=872305`);
					done = true;
				}
162
			}
163
			return function perform(selector: vscode.DocumentSelector): vscode.DocumentSelector {
164 165 166 167 168 169 170 171 172 173
				if (Array.isArray(selector)) {
					selector.forEach(perform);
				} else if (typeof selector === 'string') {
					informOnce(selector);
				} else {
					if (typeof selector.scheme === 'undefined') {
						informOnce(selector);
					}
					if (!extension.enableProposedApi && typeof selector.exclusive === 'boolean') {
						throwProposedApiError(extension);
174 175 176 177 178
					}
				}
				return selector;
			};
		})();
179

180 181
		// namespace: commands
		const commands: typeof vscode.commands = {
M
Matt Bierner 已提交
182
			registerCommand(id: string, command: <T>(...args: any[]) => T | Thenable<T>, thisArgs?: any): vscode.Disposable {
183
				return extHostCommands.registerCommand(true, id, command, thisArgs);
184
			},
185
			registerTextEditorCommand(id: string, callback: (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit, ...args: any[]) => void, thisArg?: any): vscode.Disposable {
186
				return extHostCommands.registerCommand(true, id, (...args: any[]): any => {
187 188 189
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
190
						return undefined;
191
					}
192 193 194 195 196 197 198 199 200 201

					return activeTextEditor.edit((edit: vscode.TextEditorEdit) => {
						args.unshift(activeTextEditor, edit);
						callback.apply(thisArg, args);

					}).then((result) => {
						if (!result) {
							console.warn('Edits from command ' + id + ' were not applied.');
						}
					}, (err) => {
202
						console.warn('An error occurred while running command ' + id, err);
203
					});
204
				});
205 206
			},
			registerDiffInformationCommand: proposedApiFunction(extension, (id: string, callback: (diff: vscode.LineChange[], ...args: any[]) => any, thisArg?: any): vscode.Disposable => {
207
				return extHostCommands.registerCommand(true, id, async (...args: any[]) => {
208 209 210 211 212 213 214 215 216
					let activeTextEditor = extHostEditors.getActiveTextEditor();
					if (!activeTextEditor) {
						console.warn('Cannot execute ' + id + ' because there is no active text editor.');
						return undefined;
					}

					const diff = await extHostEditors.getDiffInformation(activeTextEditor.id);
					callback.apply(thisArg, [diff, ...args]);
				});
217
			}),
218
			executeCommand<T>(id: string, ...args: any[]): Thenable<T> {
219
				return extHostCommands.executeCommand<T>(id, ...args);
220
			},
221 222 223
			getCommands(filterInternal: boolean = false): Thenable<string[]> {
				return extHostCommands.getCommands(filterInternal);
			}
224
		};
225

226 227
		// namespace: env
		const env: typeof vscode.env = Object.freeze({
228 229
			get machineId() { return initData.telemetryInfo.machineId; },
			get sessionId() { return initData.telemetryInfo.sessionId; },
A
Alex Dima 已提交
230
			get language() { return platform.language; },
J
Johannes Rieken 已提交
231
			get appName() { return product.nameLong; },
232
			get appRoot() { return initData.environment.appRoot.fsPath; },
233 234 235
			get logLevel() {
				checkProposedApiEnabled(extension);
				return extHostLogService.getLevel();
236 237 238 239
			},
			get onDidChangeLogLevel() {
				checkProposedApiEnabled(extension);
				return extHostLogService.onDidChangeLogLevel;
240
			}
241
		});
E
Erich Gamma 已提交
242

243 244 245
		// namespace: extensions
		const extensions: typeof vscode.extensions = {
			getExtension(extensionId: string): Extension<any> {
246
				let desc = extensionService.getExtensionDescription(extensionId);
247 248 249
				if (desc) {
					return new Extension(extensionService, desc);
				}
250
				return undefined;
251 252
			},
			get all(): Extension<any>[] {
253
				return extensionService.getAllExtensionDescriptions().map((desc) => new Extension(extensionService, desc));
E
Erich Gamma 已提交
254
			}
255
		};
E
Erich Gamma 已提交
256

257 258 259 260 261
		// namespace: languages
		const languages: typeof vscode.languages = {
			createDiagnosticCollection(name?: string): vscode.DiagnosticCollection {
				return extHostDiagnostics.createDiagnosticCollection(name);
			},
262 263 264
			get onDidChangeDiagnostics() {
				return extHostDiagnostics.onDidChangeDiagnostics;
			},
A
Alex Dima 已提交
265
			getDiagnostics: (resource?: vscode.Uri) => {
266 267
				return <any>extHostDiagnostics.getDiagnostics(resource);
			},
268
			getLanguages(): Thenable<string[]> {
269 270
				return extHostLanguages.getLanguages();
			},
271
			changeLanguage(document: vscode.TextDocument, languageId: string): Thenable<void> {
272
				checkProposedApiEnabled(extension);
M
mechatroner 已提交
273
				return extHostLanguages.changeLanguage(document.uri, languageId);
274
			},
275
			match(selector: vscode.DocumentSelector, document: vscode.TextDocument): number {
276
				return score(typeConverters.LanguageSelector.from(selector), document.uri, document.languageId, true);
277
			},
278
			registerCodeActionsProvider(selector: vscode.DocumentSelector, provider: vscode.CodeActionProvider, metadata?: vscode.CodeActionProviderMetadata): vscode.Disposable {
279
				return extHostLanguageFeatures.registerCodeActionProvider(checkSelector(selector), provider, extension, metadata);
280 281
			},
			registerCodeLensProvider(selector: vscode.DocumentSelector, provider: vscode.CodeLensProvider): vscode.Disposable {
282
				return extHostLanguageFeatures.registerCodeLensProvider(checkSelector(selector), provider);
283 284
			},
			registerDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.DefinitionProvider): vscode.Disposable {
285
				return extHostLanguageFeatures.registerDefinitionProvider(checkSelector(selector), provider);
286
			},
M
Matt Bierner 已提交
287
			registerImplementationProvider(selector: vscode.DocumentSelector, provider: vscode.ImplementationProvider): vscode.Disposable {
288
				return extHostLanguageFeatures.registerImplementationProvider(checkSelector(selector), provider);
289
			},
290
			registerTypeDefinitionProvider(selector: vscode.DocumentSelector, provider: vscode.TypeDefinitionProvider): vscode.Disposable {
291
				return extHostLanguageFeatures.registerTypeDefinitionProvider(checkSelector(selector), provider);
292
			},
293
			registerHoverProvider(selector: vscode.DocumentSelector, provider: vscode.HoverProvider): vscode.Disposable {
294
				return extHostLanguageFeatures.registerHoverProvider(checkSelector(selector), provider, extension.id);
295 296
			},
			registerDocumentHighlightProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentHighlightProvider): vscode.Disposable {
297
				return extHostLanguageFeatures.registerDocumentHighlightProvider(checkSelector(selector), provider);
298 299
			},
			registerReferenceProvider(selector: vscode.DocumentSelector, provider: vscode.ReferenceProvider): vscode.Disposable {
300
				return extHostLanguageFeatures.registerReferenceProvider(checkSelector(selector), provider);
301 302
			},
			registerRenameProvider(selector: vscode.DocumentSelector, provider: vscode.RenameProvider): vscode.Disposable {
303
				return extHostLanguageFeatures.registerRenameProvider(checkSelector(selector), provider);
304 305
			},
			registerDocumentSymbolProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentSymbolProvider): vscode.Disposable {
306
				return extHostLanguageFeatures.registerDocumentSymbolProvider(checkSelector(selector), provider, extension);
307 308
			},
			registerWorkspaceSymbolProvider(provider: vscode.WorkspaceSymbolProvider): vscode.Disposable {
309
				return extHostLanguageFeatures.registerWorkspaceSymbolProvider(provider);
310 311
			},
			registerDocumentFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentFormattingEditProvider): vscode.Disposable {
312
				return extHostLanguageFeatures.registerDocumentFormattingEditProvider(checkSelector(selector), provider);
313 314
			},
			registerDocumentRangeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentRangeFormattingEditProvider): vscode.Disposable {
315
				return extHostLanguageFeatures.registerDocumentRangeFormattingEditProvider(checkSelector(selector), provider);
316 317
			},
			registerOnTypeFormattingEditProvider(selector: vscode.DocumentSelector, provider: vscode.OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): vscode.Disposable {
318
				return extHostLanguageFeatures.registerOnTypeFormattingEditProvider(checkSelector(selector), provider, [firstTriggerCharacter].concat(moreTriggerCharacters));
319 320
			},
			registerSignatureHelpProvider(selector: vscode.DocumentSelector, provider: vscode.SignatureHelpProvider, ...triggerCharacters: string[]): vscode.Disposable {
321
				return extHostLanguageFeatures.registerSignatureHelpProvider(checkSelector(selector), provider, triggerCharacters);
322 323
			},
			registerCompletionItemProvider(selector: vscode.DocumentSelector, provider: vscode.CompletionItemProvider, ...triggerCharacters: string[]): vscode.Disposable {
324
				return extHostLanguageFeatures.registerCompletionItemProvider(checkSelector(selector), provider, triggerCharacters);
325 326
			},
			registerDocumentLinkProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentLinkProvider): vscode.Disposable {
327
				return extHostLanguageFeatures.registerDocumentLinkProvider(checkSelector(selector), provider);
328
			},
329
			registerColorProvider(selector: vscode.DocumentSelector, provider: vscode.DocumentColorProvider): vscode.Disposable {
330
				return extHostLanguageFeatures.registerColorProvider(checkSelector(selector), provider);
331
			},
332
			registerFoldingRangeProvider(selector: vscode.DocumentSelector, provider: vscode.FoldingRangeProvider): vscode.Disposable {
333
				return extHostLanguageFeatures.registerFoldingRangeProvider(checkSelector(selector), provider);
334
			},
335
			setLanguageConfiguration: (language: string, configuration: vscode.LanguageConfiguration): vscode.Disposable => {
336
				return extHostLanguageFeatures.setLanguageConfiguration(language, configuration);
337
			}
338
		};
E
Erich Gamma 已提交
339

340 341 342 343 344 345 346 347
		// namespace: window
		const window: typeof vscode.window = {
			get activeTextEditor() {
				return extHostEditors.getActiveTextEditor();
			},
			get visibleTextEditors() {
				return extHostEditors.getVisibleTextEditors();
			},
348 349 350
			get activeTerminal() {
				return proposedApiFunction(extension, extHostTerminalService.activeTerminal);
			},
D
Daniel Imms 已提交
351
			get terminals() {
D
Daniel Imms 已提交
352
				return extHostTerminalService.terminals;
D
Daniel Imms 已提交
353
			},
354
			showTextDocument(documentOrUri: vscode.TextDocument | vscode.Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean): Thenable<vscode.TextEditor> {
B
Benjamin Pasero 已提交
355
				let documentPromise: TPromise<vscode.TextDocument>;
J
Johannes Rieken 已提交
356 357
				if (URI.isUri(documentOrUri)) {
					documentPromise = TPromise.wrap(workspace.openTextDocument(documentOrUri));
B
Benjamin Pasero 已提交
358
				} else {
J
Johannes Rieken 已提交
359
					documentPromise = TPromise.wrap(<vscode.TextDocument>documentOrUri);
B
Benjamin Pasero 已提交
360 361 362 363
				}
				return documentPromise.then(document => {
					return extHostEditors.showTextDocument(document, columnOrOptions, preserveFocus);
				});
364 365 366 367
			},
			createTextEditorDecorationType(options: vscode.DecorationRenderOptions): vscode.TextEditorDecorationType {
				return extHostEditors.createTextEditorDecorationType(options);
			},
368 369 370
			onDidChangeActiveTextEditor(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeActiveTextEditor(listener, thisArg, disposables);
			},
371 372 373
			onDidChangeVisibleTextEditors(listener, thisArg, disposables) {
				return extHostEditors.onDidChangeVisibleTextEditors(listener, thisArg, disposables);
			},
374
			onDidChangeTextEditorSelection(listener: (e: vscode.TextEditorSelectionChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
375 376
				return extHostEditors.onDidChangeTextEditorSelection(listener, thisArgs, disposables);
			},
377
			onDidChangeTextEditorOptions(listener: (e: vscode.TextEditorOptionsChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
378 379
				return extHostEditors.onDidChangeTextEditorOptions(listener, thisArgs, disposables);
			},
380
			onDidChangeTextEditorVisibleRanges(listener: (e: vscode.TextEditorVisibleRangesChangeEvent) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) {
381
				return extHostEditors.onDidChangeTextEditorVisibleRanges(listener, thisArgs, disposables);
382
			},
383 384 385
			onDidChangeTextEditorViewColumn(listener, thisArg?, disposables?) {
				return extHostEditors.onDidChangeTextEditorViewColumn(listener, thisArg, disposables);
			},
386 387 388
			onDidCloseTerminal(listener, thisArg?, disposables?) {
				return extHostTerminalService.onDidCloseTerminal(listener, thisArg, disposables);
			},
D
Daniel Imms 已提交
389
			onDidOpenTerminal(listener, thisArg?, disposables?) {
390
				return extHostTerminalService.onDidOpenTerminal(listener, thisArg, disposables);
D
Daniel Imms 已提交
391
			},
392 393 394
			onDidChangeActiveTerminal: proposedApiFunction(extension, (listener, thisArg?, disposables?) => {
				return extHostTerminalService.onDidChangeActiveTerminal(listener, thisArg, disposables);
			}),
J
Joao Moreno 已提交
395 396
			get state() {
				return extHostWindow.state;
397
			},
J
Joao Moreno 已提交
398
			onDidChangeWindowState(listener, thisArg?, disposables?) {
J
Joao Moreno 已提交
399
				return extHostWindow.onDidChangeWindowState(listener, thisArg, disposables);
J
Joao Moreno 已提交
400
			},
J
Joao Moreno 已提交
401
			showInformationMessage(message, first, ...rest) {
402
				return extHostMessageService.showMessage(extension, Severity.Info, message, first, rest);
403
			},
J
Joao Moreno 已提交
404
			showWarningMessage(message, first, ...rest) {
405
				return extHostMessageService.showMessage(extension, Severity.Warning, message, first, rest);
406
			},
J
Joao Moreno 已提交
407
			showErrorMessage(message, first, ...rest) {
408
				return extHostMessageService.showMessage(extension, Severity.Error, message, first, rest);
409
			},
C
Christof Marti 已提交
410
			showQuickPick(items: any, options: vscode.QuickPickOptions, token?: vscode.CancellationToken): any {
411
				return extHostQuickOpen.showQuickPick(items, options, token);
412
			},
413
			showWorkspaceFolderPick(options: vscode.WorkspaceFolderPickOptions) {
414
				return extHostQuickOpen.showWorkspaceFolderPick(options);
415
			},
416
			showInputBox(options?: vscode.InputBoxOptions, token?: vscode.CancellationToken) {
417
				return extHostQuickOpen.showInput(options, token);
C
Christof Marti 已提交
418
			},
419 420 421 422 423 424
			showOpenDialog(options) {
				return extHostDialogs.showOpenDialog(options);
			},
			showSaveDialog(options) {
				return extHostDialogs.showSaveDialog(options);
			},
425
			createStatusBarItem(position?: vscode.StatusBarAlignment, priority?: number): vscode.StatusBarItem {
426
				return extHostStatusBar.createStatusBarEntry(extension.id, <number>position, priority);
427 428 429 430
			},
			setStatusBarMessage(text: string, timeoutOrThenable?: number | Thenable<any>): vscode.Disposable {
				return extHostStatusBar.setStatusBarMessage(text, timeoutOrThenable);
			},
431
			withScmProgress<R>(task: (progress: vscode.Progress<number>) => Thenable<R>) {
432
				console.warn(`[Deprecation Warning] function 'withScmProgress' is deprecated and should no longer be used. Use 'withProgress' instead.`);
433
				return extHostProgress.withProgress(extension, { location: extHostTypes.ProgressLocation.SourceControl }, (progress, token) => task({ report(n: number) { /*noop*/ } }));
J
Johannes Rieken 已提交
434
			},
435
			withProgress<R>(options: vscode.ProgressOptions, task: (progress: vscode.Progress<{ message?: string; worked?: number }>, token: vscode.CancellationToken) => Thenable<R>) {
J
Johannes Rieken 已提交
436
				return extHostProgress.withProgress(extension, options, task);
437
			},
438 439 440
			createOutputChannel(name: string): vscode.OutputChannel {
				return extHostOutputService.createOutputChannel(name);
			},
441
			createWebviewPanel(viewType: string, title: string, showOptions: vscode.ViewColumn | { viewColumn: vscode.ViewColumn, preserveFocus?: boolean }, options: vscode.WebviewPanelOptions & vscode.WebviewOptions): vscode.WebviewPanel {
M
Matt Bierner 已提交
442
				return extHostWebviews.createWebview(extension.extensionLocation, viewType, title, showOptions, options);
443
			},
444 445 446 447
			createTerminal(nameOrOptions: vscode.TerminalOptions | string, shellPath?: string, shellArgs?: string[]): vscode.Terminal {
				if (typeof nameOrOptions === 'object') {
					return extHostTerminalService.createTerminalFromOptions(<vscode.TerminalOptions>nameOrOptions);
				}
D
Daniel Imms 已提交
448
				return extHostTerminalService.createTerminal(<string>nameOrOptions, shellPath, shellArgs);
449
			},
450
			createTerminalRenderer: proposedApiFunction(extension, (name: string) => {
451
				return extHostTerminalService.createTerminalRenderer(name);
452
			}),
453 454 455 456 457
			registerTreeDataProvider(viewId: string, treeDataProvider: vscode.TreeDataProvider<any>): vscode.Disposable {
				return extHostTreeViews.registerTreeDataProvider(viewId, treeDataProvider);
			},
			createTreeView(viewId: string, options: { treeDataProvider: vscode.TreeDataProvider<any> }): vscode.TreeView<any> {
				return extHostTreeViews.createTreeView(viewId, options);
S
Sandeep Somavarapu 已提交
458
			},
459 460 461
			registerWebviewPanelSerializer: (viewType: string, serializer: vscode.WebviewPanelSerializer) => {
				return extHostWebviews.registerWebviewPanelSerializer(viewType, serializer);
			},
462 463
			// proposed API
			sampleFunction: proposedApiFunction(extension, () => {
464
				return extHostMessageService.showMessage(extension, Severity.Info, 'Hello Proposed Api!', {}, []);
465
			}),
466 467
			registerDecorationProvider: proposedApiFunction(extension, (provider: vscode.DecorationProvider) => {
				return extHostDecorations.registerDecorationProvider(provider, extension.id);
M
Matt Bierner 已提交
468
			}),
J
Joao Moreno 已提交
469
			registerUriHandler(handler: vscode.UriHandler) {
J
Joao Moreno 已提交
470
				return extHostUrls.registerUriHandler(extension.id, handler);
J
Joao Moreno 已提交
471
			},
C
Christof Marti 已提交
472
			createQuickPick<T extends vscode.QuickPickItem>(): vscode.QuickPick<T> {
473
				return extHostQuickOpen.createQuickPick(extension.id);
C
Christof Marti 已提交
474 475
			},
			createInputBox(): vscode.InputBox {
476
				return extHostQuickOpen.createInputBox(extension.id);
C
Christof Marti 已提交
477
			},
478
		};
E
Erich Gamma 已提交
479

480 481 482 483 484 485 486 487
		// namespace: workspace
		const workspace: typeof vscode.workspace = {
			get rootPath() {
				return extHostWorkspace.getPath();
			},
			set rootPath(value) {
				throw errors.readonly();
			},
488 489
			getWorkspaceFolder(resource) {
				return extHostWorkspace.getWorkspaceFolder(resource);
490
			},
491
			get workspaceFolders() {
492
				return extHostWorkspace.getWorkspaceFolders();
493
			},
494
			get name() {
I
isidor 已提交
495
				return extHostWorkspace.name;
496 497 498 499
			},
			set name(value) {
				throw errors.readonly();
			},
500 501 502
			updateWorkspaceFolders: (index, deleteCount, ...workspaceFoldersToAdd) => {
				return extHostWorkspace.updateWorkspaceFolders(extension, index, deleteCount || 0, ...workspaceFoldersToAdd);
			},
503
			onDidChangeWorkspaceFolders: function (listener, thisArgs?, disposables?) {
504
				return extHostWorkspace.onDidChangeWorkspace(listener, thisArgs, disposables);
505
			},
J
Johannes Rieken 已提交
506 507
			asRelativePath: (pathOrUri, includeWorkspace) => {
				return extHostWorkspace.getRelativePath(pathOrUri, includeWorkspace);
508 509
			},
			findFiles: (include, exclude, maxResults?, token?) => {
510
				return extHostWorkspace.findFiles(typeConverters.GlobPattern.from(include), typeConverters.GlobPattern.from(exclude), maxResults, extension.id, token);
511
			},
512 513 514 515 516 517 518 519 520 521 522 523 524
			findTextInFiles: (query: vscode.TextSearchQuery, optionsOrCallback, callbackOrToken?, token?: vscode.CancellationToken) => {
				let options: vscode.FindTextInFilesOptions;
				let callback: (result: vscode.TextSearchResult) => void;

				if (typeof optionsOrCallback === 'object') {
					options = optionsOrCallback;
					callback = callbackOrToken;
				} else {
					options = {};
					callback = optionsOrCallback;
					token = callbackOrToken;
				}

525
				return extHostWorkspace.findTextInFiles(query, options || {}, callback, extension.id, token);
R
Rob Lourens 已提交
526
			},
527 528 529
			saveAll: (includeUntitled?) => {
				return extHostWorkspace.saveAll(includeUntitled);
			},
530
			applyEdit(edit: vscode.WorkspaceEdit): Thenable<boolean> {
531
				return extHostEditors.applyWorkspaceEdit(edit);
532 533
			},
			createFileSystemWatcher: (pattern, ignoreCreate, ignoreChange, ignoreDelete): vscode.FileSystemWatcher => {
534
				return extHostFileSystemEvent.createFileSystemWatcher(typeConverters.GlobPattern.from(pattern), ignoreCreate, ignoreChange, ignoreDelete);
535 536 537 538 539 540 541
			},
			get textDocuments() {
				return extHostDocuments.getAllDocumentData().map(data => data.document);
			},
			set textDocuments(value) {
				throw errors.readonly();
			},
542
			openTextDocument(uriOrFileNameOrOptions?: vscode.Uri | string | { language?: string; content?: string; }) {
543
				let uriPromise: Thenable<URI>;
B
Benjamin Pasero 已提交
544

545
				let options = uriOrFileNameOrOptions as { language?: string; content?: string; };
B
Benjamin Pasero 已提交
546
				if (typeof uriOrFileNameOrOptions === 'string') {
B
Benjamin Pasero 已提交
547 548
					uriPromise = TPromise.as(URI.file(uriOrFileNameOrOptions));
				} else if (uriOrFileNameOrOptions instanceof URI) {
J
Johannes Rieken 已提交
549
					uriPromise = TPromise.as(uriOrFileNameOrOptions);
B
Benjamin Pasero 已提交
550 551
				} else if (!options || typeof options === 'object') {
					uriPromise = extHostDocuments.createDocumentData(options);
552
				} else {
B
Benjamin Pasero 已提交
553
					throw new Error('illegal argument - uriOrFileNameOrOptions');
554
				}
B
Benjamin Pasero 已提交
555 556 557 558 559 560

				return uriPromise.then(uri => {
					return extHostDocuments.ensureDocumentData(uri).then(() => {
						const data = extHostDocuments.getDocumentData(uri);
						return data && data.document;
					});
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
				});
			},
			onDidOpenTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidAddDocument(listener, thisArgs, disposables);
			},
			onDidCloseTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidRemoveDocument(listener, thisArgs, disposables);
			},
			onDidChangeTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidChangeDocument(listener, thisArgs, disposables);
			},
			onDidSaveTextDocument: (listener, thisArgs?, disposables?) => {
				return extHostDocuments.onDidSaveDocument(listener, thisArgs, disposables);
			},
			onWillSaveTextDocument: (listener, thisArgs?, disposables?) => {
576
				return extHostDocumentSaveParticipant.getOnWillSaveTextDocumentEvent(extension)(listener, thisArgs, disposables);
577
			},
578
			onDidChangeConfiguration: (listener: (_: any) => any, thisArgs?: any, disposables?: extHostTypes.Disposable[]) => {
579 580
				return extHostConfiguration.onDidChangeConfiguration(listener, thisArgs, disposables);
			},
581 582
			getConfiguration(section?: string, resource?: vscode.Uri): vscode.WorkspaceConfiguration {
				resource = arguments.length === 1 ? void 0 : resource;
S
Sandeep Somavarapu 已提交
583
				return extHostConfiguration.getConfiguration(section, resource, extension.id);
584
			},
585 586
			registerTextDocumentContentProvider(scheme: string, provider: vscode.TextDocumentContentProvider) {
				return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
587
			},
588
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
589
				return extHostTask.registerTaskProvider(extension, provider);
J
Johannes Rieken 已提交
590
			},
591
			registerFileSystemProvider(scheme, provider, options) {
592
				return extHostFileSystem.registerFileSystemProvider(scheme, provider, options);
593
			},
594 595
			registerFileSearchProvider: proposedApiFunction(extension, (scheme, provider) => {
				return extHostSearch.registerFileSearchProvider(scheme, provider);
M
Matt Bierner 已提交
596
			}),
597 598 599 600
			registerSearchProvider: proposedApiFunction(extension, () => {
				// Temp for live share in Insiders
				return { dispose: () => { } };
			}),
601 602 603
			registerTextSearchProvider: proposedApiFunction(extension, (scheme, provider) => {
				return extHostSearch.registerTextSearchProvider(scheme, provider);
			}),
604 605
			registerFileIndexProvider: proposedApiFunction(extension, (scheme, provider) => {
				return extHostSearch.registerFileIndexProvider(scheme, provider);
M
Matt Bierner 已提交
606
			}),
607 608 609 610 611
			registerDocumentCommentProvider: proposedApiFunction(extension, (provider: vscode.DocumentCommentProvider) => {
				return exthostCommentProviders.registerDocumentCommentProvider(provider);
			}),
			registerWorkspaceCommentProvider: proposedApiFunction(extension, (provider: vscode.WorkspaceCommentProvider) => {
				return exthostCommentProviders.registerWorkspaceCommentProvider(provider);
612
			}),
613 614
			onDidRenameFile: proposedApiFunction(extension, (listener, thisArg?, disposables?) => {
				return extHostFileSystemEvent.onDidRenameFile(listener, thisArg, disposables);
615 616
			}),
			onWillRenameFile: proposedApiFunction(extension, (listener, thisArg?, disposables?) => {
617
				return extHostFileSystemEvent.getOnWillRenameFileEvent(extension)(listener, thisArg, disposables);
J
Johannes Rieken 已提交
618
			})
619
		};
620

621 622
		// namespace: scm
		const scm: typeof vscode.scm = {
623
			get inputBox() {
J
Joao Moreno 已提交
624
				return extHostSCM.getLastInputBox(extension);
625
			},
J
Joao Moreno 已提交
626 627
			createSourceControl(id: string, label: string, rootUri?: vscode.Uri) {
				return extHostSCM.createSourceControl(extension, id, label, rootUri);
J
Joao Moreno 已提交
628
			}
629
		};
J
Joao Moreno 已提交
630

631 632
		// namespace: debug
		const debug: typeof vscode.debug = {
633 634 635
			get activeDebugSession() {
				return extHostDebugService.activeDebugSession;
			},
636 637
			get activeDebugConsole() {
				return extHostDebugService.activeDebugConsole;
638
			},
639 640
			get breakpoints() {
				return extHostDebugService.breakpoints;
641
			},
642 643 644
			onDidStartDebugSession(listener, thisArg?, disposables?) {
				return extHostDebugService.onDidStartDebugSession(listener, thisArg, disposables);
			},
645
			onDidTerminateDebugSession(listener, thisArg?, disposables?) {
646
				return extHostDebugService.onDidTerminateDebugSession(listener, thisArg, disposables);
647
			},
A
Andre Weinand 已提交
648
			onDidChangeActiveDebugSession(listener, thisArg?, disposables?) {
649
				return extHostDebugService.onDidChangeActiveDebugSession(listener, thisArg, disposables);
A
Andre Weinand 已提交
650 651
			},
			onDidReceiveDebugSessionCustomEvent(listener, thisArg?, disposables?) {
A
Andre Weinand 已提交
652
				return extHostDebugService.onDidReceiveDebugSessionCustomEvent(listener, thisArg, disposables);
653
			},
654
			onDidChangeBreakpoints(listener, thisArgs?, disposables?) {
655 656
				return extHostDebugService.onDidChangeBreakpoints(listener, thisArgs, disposables);
			},
A
Andre Weinand 已提交
657
			registerDebugConfigurationProvider(debugType: string, provider: vscode.DebugConfigurationProvider) {
658
				return extHostDebugService.registerDebugConfigurationProvider(debugType, provider);
659
			},
660 661 662 663
			startDebugging(folder: vscode.WorkspaceFolder | undefined, nameOrConfig: string | vscode.DebugConfiguration) {
				return extHostDebugService.startDebugging(folder, nameOrConfig);
			},
			addBreakpoints(breakpoints: vscode.Breakpoint[]) {
664
				return extHostDebugService.addBreakpoints(breakpoints);
665 666
			},
			removeBreakpoints(breakpoints: vscode.Breakpoint[]) {
667
				return extHostDebugService.removeBreakpoints(breakpoints);
668
			}
669 670
		};

D
Dirk Baeumer 已提交
671 672 673 674
		const tasks: typeof vscode.tasks = {
			registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
				return extHostTask.registerTaskProvider(extension, provider);
			},
675
			fetchTasks: (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => {
D
Dirk Baeumer 已提交
676
				return extHostTask.fetchTasks(filter);
677 678
			},
			executeTask: (task: vscode.Task): Thenable<vscode.TaskExecution> => {
D
Dirk Baeumer 已提交
679
				return extHostTask.executeTask(extension, task);
680
			},
D
Dirk Baeumer 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
			get taskExecutions(): vscode.TaskExecution[] {
				return extHostTask.taskExecutions;
			},
			onDidStartTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidStartTask(listeners, thisArgs, disposables);
			},
			onDidEndTask: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidEndTask(listeners, thisArgs, disposables);
			},
			onDidStartTaskProcess: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidStartTaskProcess(listeners, thisArgs, disposables);
			},
			onDidEndTaskProcess: (listeners, thisArgs?, disposables?) => {
				return extHostTask.onDidEndTaskProcess(listeners, thisArgs, disposables);
			}
		};
697

698
		return <typeof vscode>{
699 700 701
			version: pkg.version,
			// namespaces
			commands,
702
			debug,
703 704 705
			env,
			extensions,
			languages,
J
Joao Moreno 已提交
706
			scm,
D
Dirk Baeumer 已提交
707
			tasks,
708 709
			window,
			workspace,
710
			// types
711
			Breakpoint: extHostTypes.Breakpoint,
712
			CancellationTokenSource: CancellationTokenSource,
713
			CodeAction: extHostTypes.CodeAction,
M
Matt Bierner 已提交
714
			CodeActionKind: extHostTypes.CodeActionKind,
715
			CodeActionTrigger: extHostTypes.CodeActionTrigger,
716
			CodeLens: extHostTypes.CodeLens,
717
			Color: extHostTypes.Color,
718
			ColorInformation: extHostTypes.ColorInformation,
719 720
			ColorPresentation: extHostTypes.ColorPresentation,
			CommentThreadCollapsibleState: extHostTypes.CommentThreadCollapsibleState,
721 722 723
			CompletionItem: extHostTypes.CompletionItem,
			CompletionItemKind: extHostTypes.CompletionItemKind,
			CompletionList: extHostTypes.CompletionList,
M
Matt Bierner 已提交
724
			CompletionTriggerKind: extHostTypes.CompletionTriggerKind,
725
			ConfigurationTarget: extHostTypes.ConfigurationTarget,
726
			DebugAdapterExecutable: extHostTypes.DebugAdapterExecutable,
727
			DecorationRangeBehavior: extHostTypes.DecorationRangeBehavior,
728
			Diagnostic: extHostTypes.Diagnostic,
729
			DiagnosticRelatedInformation: extHostTypes.DiagnosticRelatedInformation,
730
			DiagnosticSeverity: extHostTypes.DiagnosticSeverity,
731
			DiagnosticTag: extHostTypes.DiagnosticTag,
732 733 734
			Disposable: extHostTypes.Disposable,
			DocumentHighlight: extHostTypes.DocumentHighlight,
			DocumentHighlightKind: extHostTypes.DocumentHighlightKind,
735
			DocumentLink: extHostTypes.DocumentLink,
736 737
			DocumentSymbol: extHostTypes.DocumentSymbol,
			EndOfLine: extHostTypes.EndOfLine,
738
			EventEmitter: Emitter,
739 740 741 742 743
			FileChangeType: extHostTypes.FileChangeType,
			FileSystemError: extHostTypes.FileSystemError,
			FileType: files.FileType,
			FoldingRange: extHostTypes.FoldingRange,
			FoldingRangeKind: extHostTypes.FoldingRangeKind,
744
			FunctionBreakpoint: extHostTypes.FunctionBreakpoint,
745
			Hover: extHostTypes.Hover,
746
			IndentAction: languageConfiguration.IndentAction,
747
			Location: extHostTypes.Location,
748
			LogLevel: extHostTypes.LogLevel,
749
			MarkdownString: extHostTypes.MarkdownString,
750
			OverviewRulerLane: OverviewRulerLane,
751 752
			ParameterInformation: extHostTypes.ParameterInformation,
			Position: extHostTypes.Position,
753 754
			ProcessExecution: extHostTypes.ProcessExecution,
			ProgressLocation: extHostTypes.ProgressLocation,
755
			QuickInputButtons: extHostTypes.QuickInputButtons,
756
			Range: extHostTypes.Range,
757
			RelativePattern: extHostTypes.RelativePattern,
758
			Selection: extHostTypes.Selection,
759 760
			ShellExecution: extHostTypes.ShellExecution,
			ShellQuoting: extHostTypes.ShellQuoting,
761 762 763
			SignatureHelp: extHostTypes.SignatureHelp,
			SignatureInformation: extHostTypes.SignatureInformation,
			SnippetString: extHostTypes.SnippetString,
764
			SourceBreakpoint: extHostTypes.SourceBreakpoint,
765
			SourceControlInputBoxValidationType: extHostTypes.SourceControlInputBoxValidationType,
766 767 768
			StatusBarAlignment: extHostTypes.StatusBarAlignment,
			SymbolInformation: extHostTypes.SymbolInformation,
			SymbolKind: extHostTypes.SymbolKind,
769 770 771 772 773
			Task: extHostTypes.Task,
			TaskGroup: extHostTypes.TaskGroup,
			TaskPanelKind: extHostTypes.TaskPanelKind,
			TaskRevealKind: extHostTypes.TaskRevealKind,
			TaskScope: extHostTypes.TaskScope,
774 775
			TextDocumentSaveReason: extHostTypes.TextDocumentSaveReason,
			TextEdit: extHostTypes.TextEdit,
776
			TextEditorCursorStyle: TextEditorCursorStyle,
777
			TextEditorLineNumbersStyle: extHostTypes.TextEditorLineNumbersStyle,
778
			TextEditorRevealType: extHostTypes.TextEditorRevealType,
779
			TextEditorSelectionChangeKind: extHostTypes.TextEditorSelectionChangeKind,
780 781 782 783
			ThemeColor: extHostTypes.ThemeColor,
			ThemeIcon: extHostTypes.ThemeIcon,
			TreeItem: extHostTypes.TreeItem,
			TreeItemCollapsibleState: extHostTypes.TreeItemCollapsibleState,
784
			Uri: URI,
785 786
			ViewColumn: extHostTypes.ViewColumn,
			WorkspaceEdit: extHostTypes.WorkspaceEdit,
J
Joao Moreno 已提交
787
			// functions
788
		};
789
	};
E
Erich Gamma 已提交
790 791
}

792 793 794 795 796 797 798 799 800 801 802 803
/**
 * Returns the original fs path (using the original casing for the drive letter)
 */
export function originalFSPath(uri: URI): string {
	const result = uri.fsPath;
	if (/^[a-zA-Z]:/.test(result) && uri.path.charAt(1).toLowerCase() === result.charAt(0)) {
		// Restore original drive letter casing
		return uri.path.charAt(1) + result.substr(1);
	}
	return result;
}

E
Erich Gamma 已提交
804 805
class Extension<T> implements vscode.Extension<T> {

A
Alex Dima 已提交
806
	private _extensionService: ExtHostExtensionService;
E
Erich Gamma 已提交
807 808 809 810 811

	public id: string;
	public extensionPath: string;
	public packageJSON: any;

J
Johannes Rieken 已提交
812
	constructor(extensionService: ExtHostExtensionService, description: IExtensionDescription) {
A
Alex Dima 已提交
813
		this._extensionService = extensionService;
E
Erich Gamma 已提交
814
		this.id = description.id;
815
		this.extensionPath = paths.normalize(originalFSPath(description.extensionLocation), true);
E
Erich Gamma 已提交
816 817 818 819
		this.packageJSON = description;
	}

	get isActive(): boolean {
A
Alex Dima 已提交
820
		return this._extensionService.isActivated(this.id);
E
Erich Gamma 已提交
821 822 823
	}

	get exports(): T {
A
Alex Dima 已提交
824
		return <T>this._extensionService.getExtensionExports(this.id);
E
Erich Gamma 已提交
825 826 827
	}

	activate(): Thenable<T> {
828
		return this._extensionService.activateByIdWithErrors(this.id, new ExtensionActivatedByAPI(false)).then(() => this.exports);
E
Erich Gamma 已提交
829 830 831
	}
}

J
Johannes Rieken 已提交
832
export function initializeExtensionApi(extensionService: ExtHostExtensionService, apiFactory: IExtensionApiFactory): TPromise<void> {
833
	return extensionService.getExtensionPathIndex().then(trie => defineAPI(apiFactory, trie));
J
Johannes Rieken 已提交
834 835
}

836
function defineAPI(factory: IExtensionApiFactory, extensionPaths: TernarySearchTree<IExtensionDescription>): void {
J
Johannes Rieken 已提交
837 838

	// each extension is meant to get its own api implementation
J
Johannes Rieken 已提交
839
	const extApiImpl = new Map<string, typeof vscode>();
J
Johannes Rieken 已提交
840
	let defaultApiImpl: typeof vscode;
841 842 843

	const node_module = <any>require.__$__nodeRequire('module');
	const original = node_module._load;
A
Alex Dima 已提交
844
	node_module._load = function load(request: string, parent: any, isMain: any) {
845 846 847 848 849
		if (request !== 'vscode') {
			return original.apply(this, arguments);
		}

		// get extension id from filename and api for extension
850
		const ext = extensionPaths.findSubstr(URI.file(parent.filename).fsPath);
851
		if (ext) {
J
Johannes Rieken 已提交
852
			let apiImpl = extApiImpl.get(ext.id);
853
			if (!apiImpl) {
J
Johannes Rieken 已提交
854 855
				apiImpl = factory(ext);
				extApiImpl.set(ext.id, apiImpl);
856 857 858 859 860 861
			}
			return apiImpl;
		}

		// fall back to a default implementation
		if (!defaultApiImpl) {
862 863 864
			let extensionPathsPretty = '';
			extensionPaths.forEach((value, index) => extensionPathsPretty += `\t${index} -> ${value.id}\n`);
			console.warn(`Could not identify extension for 'vscode' require call from ${parent.filename}. These are the extension path mappings: \n${extensionPathsPretty}`);
865
			defaultApiImpl = factory(nullExtensionDescription);
E
Erich Gamma 已提交
866
		}
867
		return defaultApiImpl;
E
Erich Gamma 已提交
868 869
	};
}
870 871 872 873 874 875 876 877 878 879

const nullExtensionDescription: IExtensionDescription = {
	id: 'nullExtensionDescription',
	name: 'Null Extension Description',
	publisher: 'vscode',
	activationEvents: undefined,
	contributes: undefined,
	enableProposedApi: false,
	engines: undefined,
	extensionDependencies: undefined,
880
	extensionLocation: undefined,
881
	isBuiltin: false,
882
	isUnderDevelopment: false,
883 884 885
	main: undefined,
	version: undefined
};