typescriptMain.ts 8.4 KB
Newer Older
I
isidor 已提交
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.
 *--------------------------------------------------------------------------------------------*/
E
Erich Gamma 已提交
5 6 7 8 9 10 11

/* --------------------------------------------------------------------------------------------
 * Includes code from typescript-sublime-plugin project, obtained from
 * https://github.com/Microsoft/TypeScript-Sublime-Plugin/blob/master/TypeScript%20Indent.tmPreferences
 * ------------------------------------------------------------------------------------------ */
'use strict';

D
Dirk Baeumer 已提交
12
import { languages, commands, workspace, Uri, ExtensionContext, IndentAction, Diagnostic, DiagnosticCollection, Range } from 'vscode';
E
Erich Gamma 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

import * as Proto from './protocol';
import TypeScriptServiceClient from './typescriptServiceClient';
import { ITypescriptServiceClientHost } from './typescriptService';

import * as Configuration from './features/configuration';

import HoverProvider from './features/hoverProvider';
import DefinitionProvider from './features/definitionProvider';
import DocumentHighlightProvider from './features/documentHighlightProvider';
import ReferenceProvider from './features/referenceProvider';
import DocumentSymbolProvider from './features/documentSymbolProvider';
import SignatureHelpProvider from './features/signatureHelpProvider';
import RenameProvider from './features/renameProvider';
import FormattingProvider from './features/formattingProvider';
import BufferSyncSupport from './features/bufferSyncSupport';
import CompletionItemProvider from './features/completionItemProvider';
import WorkspaceSymbolProvider from './features/workspaceSymbolProvider';

export function activate(context: ExtensionContext): void {

	let MODE_ID_TS = 'typescript';
	let MODE_ID_TSX = 'typescriptreact';
	let MY_PLUGIN_ID = 'vs.language.typescript';

	let clientHost = new TypeScriptServiceClientHost();
	let client = clientHost.serviceClient;
D
Dirk Baeumer 已提交
40 41 42 43

	context.subscriptions.push(commands.registerCommand('typescript.reloadProjects', () => {
		clientHost.reloadProjects();
	}));
E
Erich Gamma 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
	// Register the supports for both TS and TSX so that we can have separate grammars but share the mode
	client.onReady().then(() => {
		registerSupports(MODE_ID_TS, clientHost, client);
		registerSupports(MODE_ID_TSX, clientHost, client);
	}, () => {
		// Nothing to do here. The client did show a message;
	})
}

function registerSupports(modeID: string, host: TypeScriptServiceClientHost, client: TypeScriptServiceClient) {

	languages.registerHoverProvider(modeID, new HoverProvider(client));
	languages.registerDefinitionProvider(modeID, new DefinitionProvider(client));
	languages.registerDocumentHighlightProvider(modeID, new DocumentHighlightProvider(client));
	languages.registerReferenceProvider(modeID, new ReferenceProvider(client));
	languages.registerDocumentSymbolProvider(modeID, new DocumentSymbolProvider(client));
60
	languages.registerSignatureHelpProvider(modeID, new SignatureHelpProvider(client), '(', ',');
E
Erich Gamma 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
	languages.registerRenameProvider(modeID, new RenameProvider(client));
	languages.registerDocumentRangeFormattingEditProvider(modeID, new FormattingProvider(client));
	languages.registerOnTypeFormattingEditProvider(modeID, new FormattingProvider(client), ';', '}', '\n');
	languages.registerWorkspaceSymbolProvider(new WorkspaceSymbolProvider(client, modeID));

	languages.setLanguageConfiguration(modeID, {
		indentationRules: {
			// ^(.*\*/)?\s*\}.*$
			decreaseIndentPattern: /^(.*\*\/)?\s*\}.*$/,
			// ^.*\{[^}"']*$
			increaseIndentPattern: /^.*\{[^}"']*$/
		},
		wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
		comments: {
			lineComment: '//',
			blockComment: ['/*', '*/']
		},
		brackets: [
			['{', '}'],
			['[', ']'],
			['(', ')'],
		],
		onEnterRules: [
			{
				// e.g. /** | */
				beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
				afterText: /^\s*\*\/$/,
				action: { indentAction: IndentAction.IndentOutdent, appendText: ' * ' }
			},
			{
				// e.g. /** ...|
				beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
				action: { indentAction: IndentAction.None, appendText: ' * ' }
			},
			{
				// e.g.  * ...|
				beforeText: /^(\t|(\ \ ))*\ \*\ ([^\*]|\*(?!\/))*$/,
				action: { indentAction: IndentAction.None, appendText: '* ' }
			},
			{
				// e.g.  */|
				beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
				action: { indentAction: IndentAction.None, removeText: 1 }
			}
		],

		__electricCharacterSupport: {
			brackets: [
				{ tokenType: 'delimiter.curly.' + modeID, open: '{', close: '}', isElectric: true },
				{ tokenType: 'delimiter.square.' + modeID, open: '[', close: ']', isElectric: true },
				{ tokenType: 'delimiter.paren.' + modeID, open: '(', close: ')', isElectric: true }
			],
			docComment: { scope: 'comment.documentation', open: '/**', lineStart: ' * ', close: ' */' }
		},

		__characterPairSupport: {
			autoClosingPairs: [
				{ open: '{', close: '}' },
				{ open: '[', close: ']' },
				{ open: '(', close: ')' },
				{ open: '"', close: '"', notIn: ['string'] },
				{ open: '\'', close: '\'', notIn: ['string', 'comment'] }
			]
		}
	});

	host.addBufferSyncSupport(new BufferSyncSupport(client, modeID));

	// Register suggest support as soon as possible and load configuration lazily
	let completionItemProvider = new CompletionItemProvider(client);
	languages.registerCompletionItemProvider(modeID, completionItemProvider, '.');
	let reloadConfig = () => {
		completionItemProvider.setConfiguration(Configuration.load(modeID));
	};
	workspace.onDidChangeConfiguration(() => {
		reloadConfig();
	});
	reloadConfig();
}

class TypeScriptServiceClientHost implements ITypescriptServiceClientHost {
	private client: TypeScriptServiceClient;

	private syntaxDiagnostics: { [key: string]: Diagnostic[] };
	private currentDiagnostics: DiagnosticCollection;
	private bufferSyncSupports: BufferSyncSupport[];

	constructor() {
		this.bufferSyncSupports = [];
		this.currentDiagnostics = languages.createDiagnosticCollection('typescript');
		let handleProjectCreateOrDelete = () => {
			this.client.execute('reloadProjects', null, false);
			this.triggerAllDiagnostics();
		};
		let handleProjectChange = () => {
D
Dirk Baeumer 已提交
156 157 158
			setTimeout(() => {
				this.triggerAllDiagnostics();
			}, 1500);
E
Erich Gamma 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172
		}
		let watcher = workspace.createFileSystemWatcher('**/tsconfig.json');
		watcher.onDidCreate(handleProjectCreateOrDelete);
		watcher.onDidDelete(handleProjectCreateOrDelete);
		watcher.onDidChange(handleProjectChange);

		this.client = new TypeScriptServiceClient(this);
		this.syntaxDiagnostics = Object.create(null);
	}

	public get serviceClient(): TypeScriptServiceClient {
		return this.client;
	}

D
Dirk Baeumer 已提交
173 174 175 176 177
	public reloadProjects(): void {
		this.client.execute('reloadProjects', null, false);
		this.triggerAllDiagnostics();
	}

E
Erich Gamma 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	public addBufferSyncSupport(support: BufferSyncSupport): void {
		this.bufferSyncSupports.push(support);
	}

	private triggerAllDiagnostics() {
		this.bufferSyncSupports.forEach(support => support.requestAllDiagnostics());
	}

	/* internal */ populateService(): void {
		this.currentDiagnostics.clear();
		this.syntaxDiagnostics = Object.create(null);
		// See https://github.com/Microsoft/TypeScript/issues/5530
		workspace.saveAll(false).then((value) => {
			this.bufferSyncSupports.forEach(support => {
				support.reOpenDocuments();
				support.requestAllDiagnostics();
			});
		});
	}

	/* internal */ syntaxDiagnosticsReceived(event: Proto.DiagnosticEvent): void {
		let body = event.body;
		if (body.diagnostics) {
			let markers = this.createMarkerDatas(body.diagnostics);
			this.syntaxDiagnostics[body.file] = markers;
		}
	}

	/* internal */ semanticDiagnosticsReceived(event: Proto.DiagnosticEvent): void {
		let body = event.body;
		if (body.diagnostics) {
			let diagnostics = this.createMarkerDatas(body.diagnostics);
			let syntaxMarkers = this.syntaxDiagnostics[body.file];
			if (syntaxMarkers) {
				delete this.syntaxDiagnostics[body.file];
				diagnostics = syntaxMarkers.concat(diagnostics);
			}
			this.currentDiagnostics.set(Uri.file(body.file), diagnostics);
		}
	}

	private createMarkerDatas(diagnostics: Proto.Diagnostic[]): Diagnostic[] {
		let result: Diagnostic[] = [];
		for (let diagnostic of diagnostics) {
			let {start, end, text} = diagnostic;
			let range = new Range(start.line - 1, start.offset - 1, end.line - 1, end.offset - 1);
			result.push(new Diagnostic(range, text));
		}
		return result;
	}
}