Example #1
0
    public doInit(indexInProgress: boolean) {
        console.log("Crane Initialised...");

        this.showIndexingStatusBarMessage();

        var statusBarItem: StatusBarItem = window.createStatusBarItem(StatusBarAlignment.Right);
        statusBarItem.text = Config.version;
        statusBarItem.tooltip = 'Crane (PHP Code-completion) version ' + Config.version;
        statusBarItem.show();

        var serverDebugMessage: NotificationType<{ type: string, message: string }> = { method: "serverDebugMessage" };
        Crane.langClient.onNotification(serverDebugMessage, message => {
            switch (message.type) {
                case 'info': Debug.info(message.message); break;
                case 'error': Debug.error(message.message); break;
                case 'warning': Debug.warning(message.message); break;
                default: Debug.info(message.message); break;
            }
        });

        var requestType: RequestType<any, any, any> = { method: "workDone" };
        Crane.langClient.onRequest(requestType, (tree) => {
            // this.projectBuilding = false;
            Crane.statusBarItem.text = '$(check) PHP File Indexing Complete!';
            // Load settings
            let craneSettings = workspace.getConfiguration("crane");
            Debug.info("Processing complete!");
            if (Config.showBugReport) {
                setTimeout(() => {
                    Crane.statusBarItem.tooltip = "Found a problem with the PHP Intellisense provided by Crane? Click here to file a bug report on Github";
                    Crane.statusBarItem.text = "$(bug) Found a PHP Intellisense Bug?";
                    Crane.statusBarItem.command = "crane.reportBug";
                    Crane.statusBarItem.show();
                }, 5000);
            } else {
                Crane.statusBarItem.hide();
            }
        });

        var types = Config.phpFileTypes;
        Debug.info(`Watching these files: {${types.include.join(',')}}`);

        var fsw: FileSystemWatcher = workspace.createFileSystemWatcher(`{${types.include.join(',')}}`);
        fsw.onDidChange(e => {
            workspace.openTextDocument(e).then(document => {
                if (document.languageId != 'php') return;
                Debug.info('File Changed: ' + e.fsPath);
                Crane.langClient.sendRequest({ method: 'buildObjectTreeForDocument' }, {
                    path: e.fsPath,
                    text: document.getText()
                });
            });
        });
        fsw.onDidCreate(e => {
            workspace.openTextDocument(e).then(document => {
                if (document.languageId != 'php') return;
                Debug.info('File Created: ' + e.fsPath);
                Crane.langClient.sendRequest({ method: 'buildObjectTreeForDocument' }, {
                    path: e.fsPath,
                    text: document.getText()
                });
            });
        });
        fsw.onDidDelete(e => {
            Debug.info('File Deleted: ' + e.fsPath);
            Crane.langClient.sendRequest({ method: 'deleteFile' }, {
                path: e.fsPath
            });
        });

        if (!indexInProgress) {
            // Send request to server to build object tree for all workspace files
            this.processAllFilesInWorkspace();
        }
    }
Example #2
0
export function activate(context: ExtensionContext) {

	let toDispose = context.subscriptions;

	let packageInfo = getPackageInfo(context);
	let telemetryReporter: TelemetryReporter = packageInfo && new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);
	toDispose.push(telemetryReporter);

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'jsonServerMain.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=6004'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	let documentSelector = ['json'];

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for json documents
		documentSelector,
		synchronize: {
			// Synchronize the setting section 'json' to the server
			configurationSection: ['json', 'http'],
			fileEvents: workspace.createFileSystemWatcher('**/*.json')
		},
		middleware: {
			workspace: {
				didChangeConfiguration: () => client.sendNotification(DidChangeConfigurationNotification.type, { settings: getSettings() })
			}
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('json', localize('jsonserver.name', 'JSON Language Server'), serverOptions, clientOptions);
	client.registerFeature(new ConfigurationFeature(client));

	let disposable = client.start();
	toDispose.push(disposable);
	client.onReady().then(() => {
		client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};
		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => handleContentChange(d.uri)));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		// register color provider
		toDispose.push(languages.registerColorProvider(documentSelector, {
			provideDocumentColors(document: TextDocument): Thenable<ColorInformation[]> {
				let params: DocumentColorParams = {
					textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
				};
				return client.sendRequest(DocumentColorRequest.type, params).then(symbols => {
					return symbols.map(symbol => {
						let range = client.protocol2CodeConverter.asRange(symbol.range);
						let color = new Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
						return new ColorInformation(range, color);
					});
				});
			},
			provideColorPresentations(color: Color, context): Thenable<ColorPresentation[]> {
				let params: ColorPresentationParams = {
					textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),
					color: color,
					range: client.code2ProtocolConverter.asRange(context.range)
				};
				return client.sendRequest(ColorPresentationRequest.type, params).then(presentations => {
					return presentations.map(p => {
						let presentation = new ColorPresentation(p.label);
						presentation.textEdit = p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit);
						presentation.additionalTextEdits = p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
						return presentation;
					});
				});
			}
		}));
	});

	languages.setLanguageConfiguration('json', {
		wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|[^\s{}\[\],:]+/,
		indentationRules: {
			increaseIndentPattern: /^.*(\{[^}]*|\[[^\]]*)$/,
			decreaseIndentPattern: /^\s*[}\]],?\s*$/
		}
	});
}
Example #3
0
export function activate(context: ExtensionContext) {

	let packageInfo = getPackageInfo(context);
	let telemetryReporter: TelemetryReporter = packageInfo && new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);
	context.subscriptions.push(telemetryReporter);

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'jsonServerMain.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for json documents
		documentSelector: ['json'],
		synchronize: {
			// Synchronize the setting section 'json' to the server
			configurationSection: ['json', 'http.proxy', 'http.proxyStrictSSL'],
			fileEvents: workspace.createFileSystemWatcher('**/*.json')
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('json', localize('jsonserver.name', 'JSON Language Server'), serverOptions, clientOptions);
	let disposable = client.start();
	client.onReady().then(() => {
		client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		let colorRequestor = (uri: string) => {
			return client.sendRequest(ColorSymbolRequest.type, uri).then(ranges => ranges.map(client.protocol2CodeConverter.asRange));
		};
		let isDecoratorEnabled = (languageId: string) => {
			return workspace.getConfiguration().get<boolean>(languageId + '.colorDecorators.enable');
		};
		disposable = activateColorDecorations(colorRequestor, { json: true }, isDecoratorEnabled);
		context.subscriptions.push(disposable);
	});

	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);

	languages.setLanguageConfiguration('json', {
		wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|[^\s{}\[\],:]+/,
		indentationRules: {
			increaseIndentPattern: /^.*(\{[^}]*|\[[^\]]*)$/,
			decreaseIndentPattern: /^\s*[}\]],?\s*$/
		}
	});
}
Example #4
0
export function activate(context: vscode.ExtensionContext) {
  vscode.languages.setLanguageConfiguration("argdown", {
    wordPattern: /([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g
  });
  // -- PREVIEW --
  const logger = new Logger();
  const argdownEngine = new ArgdownEngine();
  const cspArbiter = new ExtensionContentSecurityPolicyArbiter(
    context.globalState,
    context.workspaceState
  );
  const contributions = new ArgdownExtensionContributions();
  const contentProvider = new ArgdownContentProvider(
    argdownEngine,
    context,
    cspArbiter,
    contributions
  );

  const previewManager = new ArgdownPreviewManager(
    contentProvider,
    logger,
    contributions,
    argdownEngine
  );
  const previewSecuritySelector = new PreviewSecuritySelector(
    cspArbiter,
    previewManager
  );

  const commandManager = new CommandManager();
  context.subscriptions.push(commandManager);
  commandManager.register(new commands.ShowPreviewCommand(previewManager));
  commandManager.register(
    new commands.ShowPreviewToSideCommand(previewManager)
  );
  commandManager.register(
    new commands.ShowLockedPreviewToSideCommand(previewManager)
  );
  commandManager.register(new commands.ShowSourceCommand(previewManager));
  commandManager.register(new commands.RefreshPreviewCommand(previewManager));
  commandManager.register(new commands.MoveCursorToPositionCommand());
  commandManager.register(
    new commands.ShowPreviewSecuritySelectorCommand(
      previewSecuritySelector,
      previewManager
    )
  );
  commandManager.register(new commands.OnPreviewStyleLoadErrorCommand());
  commandManager.register(new commands.OpenDocumentLinkCommand());
  commandManager.register(new commands.ToggleLockCommand(previewManager));
  commandManager.register(new commands.ExportDocumentToHtmlCommand());
  commandManager.register(new commands.ExportDocumentToJsonCommand());
  commandManager.register(new commands.ExportDocumentToDotCommand());
  commandManager.register(new commands.ExportDocumentToGraphMLCommand());
  commandManager.register(new commands.ExportDocumentToVizjsSvgCommand());
  commandManager.register(new commands.ExportDocumentToVizjsPdfCommand());
  commandManager.register(new commands.ExportContentToVizjsPngCommand());
  commandManager.register(new commands.ExportContentToDagreSvgCommand(logger));
  commandManager.register(new commands.ExportContentToDagrePngCommand());
  commandManager.register(new commands.ExportContentToDagrePdfCommand());
  context.subscriptions.push(
    vscode.workspace.onDidChangeConfiguration(() => {
      logger.updateConfiguration();
      previewManager.updateConfiguration();
    })
  );
  // --- LANGUGAGE SERVER ---

  // The debug options for the server
  let debugOptions: ForkOptions = { execArgv: ["--nolazy", "--inspect=6009"] };

  // If the extension is launched in debug mode then the debug server options are used
  // Otherwise the run options are used
  const modulePath = require.resolve("@argdown/language-server");
  let serverOptions: ServerOptions = {
    run: {
      module: modulePath,
      transport: TransportKind.ipc
    },
    debug: {
      module: modulePath,
      transport: TransportKind.ipc,
      options: debugOptions
    }
  };

  languageServerConfiguration = new LanguageServerConfiguration();
  let middleware: ConfigurationWorkspaceMiddleware | Middleware = {
    workspace: {
      configuration: languageServerConfiguration.computeConfiguration
    }
  };

  // Options to control the language client
  let clientOptions: LanguageClientOptions = {
    // Register the server for plain text documents
    documentSelector: [{ scheme: "file", language: "argdown" }],
    synchronize: {
      // Notify the server about file changes to '.clientrc files contain in the workspace
      fileEvents: vscode.workspace.createFileSystemWatcher("**/.clientrc")
      // In the past this told the client to actively synchronize settings. Since the
      // client now supports 'getConfiguration' requests this active synchronization is not
      // necessary anymore.
      // configurationSection: [ 'lspMultiRootSample' ]
    },
    middleware: middleware as Middleware,
    outputChannelName: "Argdown Language Server"
  };
  // Create the language client and start the client.
  client = new LanguageClient(
    "argdownLanguageServer",
    "Argdown Language Server",
    serverOptions,
    clientOptions
  );
  // Register new proposed protocol if available.
  client.registerProposedFeatures();
  client.onReady().then(() => {
    languageServerConfiguration.initialize(client);
  });

  // Start the client. This will also launch the server
  client.start();
}
Example #5
0
export function realActivate(context: ExtensionContext) {
	linter = getLinter();
	linterName = getLinterName();

		let statusBarItem = Window.createStatusBarItem(StatusBarAlignment.Right, 0);
		let standardStatus: Status = Status.ok;
		let serverRunning: boolean = false;

		statusBarItem.text = linterName;
		statusBarItem.command = 'standard.showOutputChannel';

		function showStatusBarItem(show: boolean): void {
			if (show) {
				statusBarItem.show();
			} else {
				statusBarItem.hide();
			}
		}

		function updateStatus(status: Status) {
			switch (status) {
				case Status.ok:
					statusBarItem.color = undefined;
					break;
				case Status.warn:
					statusBarItem.color = 'yellow';
					break;
				case Status.error:
					statusBarItem.color = 'darkred';
					break;
			}
			standardStatus = status;
			updateStatusBarVisibility(Window.activeTextEditor);
		}

		function updateStatusBarVisibility(editor: TextEditor): void {
			statusBarItem.text = standardStatus === Status.ok ? linterName : `${linterName}!`;
			showStatusBarItem(
				serverRunning &&
				(
					standardStatus !== Status.ok ||
					(editor && (editor.document.languageId === 'javascript' || editor.document.languageId === 'javascriptreact'))
				)
			);
		}

		Window.onDidChangeActiveTextEditor(updateStatusBarVisibility);
		updateStatusBarVisibility(Window.activeTextEditor);

		// We need to go one level up since an extension compile the js code into
		// the output folder.
		// serverModule
		let serverModule = context.asAbsolutePath(path.join('server', 'out', 'server.js'));
		let debugOptions = { execArgv: ["--nolazy", "--inspect=6023"], cwd: process.cwd() };
		let serverOptions: ServerOptions = {
			run: { module: serverModule, transport: TransportKind.ipc, options: { cwd: process.cwd() } },
			debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
		};

		let defaultErrorHandler: ErrorHandler;
		let serverCalledProcessExit: boolean = false;

		let packageJsonFilter: DocumentFilter = { scheme: 'file', pattern: '**/package.json'};
		let syncedDocuments: Map<string, TextDocument> = new Map<string, TextDocument>();

		Workspace.onDidChangeConfiguration(() => {
			for (let textDocument of syncedDocuments.values()) {
				if (!shouldBeValidated(textDocument)) {
					syncedDocuments.delete(textDocument.uri.toString());
					client.sendNotification(DidCloseTextDocumentNotification.type, client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument));
				}
			}
			for (let textDocument of Workspace.textDocuments) {
				if (!syncedDocuments.has(textDocument.uri.toString()) && shouldBeValidated(textDocument)) {
					client.sendNotification(DidOpenTextDocumentNotification.type, client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument));
					syncedDocuments.set(textDocument.uri.toString(), textDocument);
				}
			}
		});
		let clientOptions: LanguageClientOptions = {
			documentSelector: [{  scheme: 'file' }, { scheme: 'untitled'}],
			diagnosticCollectionName: 'standard',
			revealOutputChannelOn: RevealOutputChannelOn.Never,
			synchronize: {
				// configurationSection: 'standard',
				fileEvents: [
					Workspace.createFileSystemWatcher('**/package.json')
				]
			},
			initializationOptions: () => {
				let configuration = Workspace.getConfiguration('standard');
				let folders = Workspace.workspaceFolders;
				return {
					legacyModuleResolve: configuration ? configuration.get('_legacyModuleResolve', false) : false,
					nodePath: configuration ? configuration.get('nodePath', undefined) : undefined,
					languageIds: configuration ? configuration.get('valiadate', defaultLanguages) : defaultLanguages,
					workspaceFolders: folders ? folders.map(folder => folder.toString()) : []
				};
			},
			initializationFailedHandler: (error) => {
				client.error('Server initialization failed.', error);
				client.outputChannel.show(true);
				return false;
			},
			errorHandler: {
				error: (error, message, count): ErrorAction => {
					return defaultErrorHandler.error(error, message, count);
				},
				closed: (): CloseAction => {
					if (serverCalledProcessExit) {
						return CloseAction.DoNotRestart;
					}
					return defaultErrorHandler.closed();
				}
			},
			middleware: {
				didOpen: (document, next) => {
					if (Languages.match(packageJsonFilter, document) || shouldBeValidated(document)) {
						next(document);
						syncedDocuments.set(document.uri.toString(), document);
						return;
					}
				},
				didChange: (event, next) => {
					if (syncedDocuments.has(event.document.uri.toString())) {
						next(event);
					}
				},
				willSave: (event, next) => {
					if (syncedDocuments.has(event.document.uri.toString())) {
						next(event);
					}
				},
				willSaveWaitUntil: (event, next) => {
					if (syncedDocuments.has(event.document.uri.toString())) {
						return next(event);
					} else {
						return Promise.resolve([]);
					}
				},
				didSave: (document, next) => {
					if (syncedDocuments.has(document.uri.toString())) {
						next(document);
					}
				},
				didClose: (document, next) => {
					let uri = document.uri.toString();
					if (syncedDocuments.has(uri)) {
						syncedDocuments.delete(uri);
						next(document);
					}
				},
				provideCodeActions: (document, range, context, token, next): ProviderResult<Command[]> => {
					if (!syncedDocuments.has(document.uri.toString()) || !context.diagnostics || context.diagnostics.length === 0) {
						return [];
					}
					let standardDiagnostics: Diagnostic[] = [];
					for (let diagnostic of context.diagnostics) {
						if (diagnostic.source === 'standard') {
							standardDiagnostics.push(diagnostic);
						}
					}
					if (standardDiagnostics.length === 0) {
						return [];
					}
					let newContext: CodeActionContext = Object.assign({}, context, { diagnostics: standardDiagnostics } as CodeActionContext);
					return next(document, range, newContext, token);
				},
				workspace: {
					configuration: (params: Proposed.ConfigurationParams, _token: CancellationToken, _next: Function): any[] => {
						if (!params.items) {
							return null;
						}
						let result: (TextDocumentSettings | null)[] = [];
						for (let item of params.items) {
							if (item.section || !item.scopeUri) {
								result.push(null);
								continue;
							}
							let resource = client.protocol2CodeConverter.asUri(item.scopeUri);
							let config = Workspace.getConfiguration('standard', resource);
							let settings: TextDocumentSettings = {
								validate: false,
								autoFix: false,
								autoFixOnSave: false,
								semistandard: config.get('semistandard', false),
								usePackageJson: config.get('usePackageJson', false),
								options: config.get('options', {}),
								run: config.get('run', 'onType'),
								nodePath: config.get('nodePath', undefined),
								workingDirectory: undefined,
								workspaceFolder: undefined,
								library: undefined
							}
							let document: TextDocument = syncedDocuments.get(item.scopeUri);
							if (!document) {
								result.push(settings);
								continue;
							}
							if (config.get('enabled', true)) {
								let validateItems = config.get<(ValidateItem | string)[]>('validate', ['javascript', 'javascriptreact']);
								for (let item of validateItems) {
									if (Is.string(item) && item === document.languageId) {
										settings.validate = true;
										if (item === 'javascript' || item === 'javascriptreact') {
											settings.autoFix = true;
										}
										break;
									}
									else if (ValidateItem.is(item) && item.language === document.languageId) {
										settings.validate = true;
										settings.autoFix = item.autoFix;
										break;
									}
								}
							}
							if (settings.validate) {
								settings.autoFixOnSave = settings.autoFix && config.get('autoFixOnSave', false);
							}
							let workspaceFolder = Workspace.getWorkspaceFolder(resource);
							if (workspaceFolder) {
								settings.workspaceFolder = { name: workspaceFolder.name, uri: client.code2ProtocolConverter.asUri(workspaceFolder.uri) };
							}
							let workingDirectories = config.get<(string | DirectoryItem)[]>('workingDirectories', undefined);
							if (Array.isArray(workingDirectories)) {
								let workingDirectory = undefined;
								let workspaceFolderPath = workspaceFolder && workspaceFolder.uri.scheme === 'file' ? workspaceFolder.uri.fsPath : undefined;
								for (let entry of workingDirectories) {
									let directory;
									let changeProcessCWD = false;
									if (Is.string(entry)) {
										directory = entry;
									}
									else if (DirectoryItem.is(entry)) {
										directory = entry.directory;
										changeProcessCWD = !!entry.changeProcessCWD;
									}
									if (directory) {
										if (path.isAbsolute(directory)) {
											directory = directory;
										}
										else if (workspaceFolderPath && directory) {
											directory = path.join(workspaceFolderPath, directory);
										}
										else {
											directory = undefined;
										}
										let filePath = document.uri.scheme === 'file' ? document.uri.fsPath : undefined;
										if (filePath && directory && filePath.startsWith(directory)) {
											if (workingDirectory) {
												if (workingDirectory.directory.length < directory.length) {
													workingDirectory.directory = directory;
													workingDirectory.changeProcessCWD = changeProcessCWD;
												}
											}
											else {
												workingDirectory = { directory, changeProcessCWD };
											}
										}
									}
								}
								settings.workingDirectory = workingDirectory;
							}
							result.push(settings);
						}
						return result;
					}
				} as WorkspaceMiddleware
			}
		};
		let client = new LanguageClient(linterName, serverOptions, clientOptions);
		client.registerProposedFeatures();
		defaultErrorHandler = client.createDefaultErrorHandler();
		const running = `${linterName} server is running.`;
		const stopped = `${linterName} server stopped.`;
		client.onDidChangeState((event) => {
			if (event.newState === ClientState.Running) {
				client.info(running);
				statusBarItem.tooltip = running;
				serverRunning = true;
			} else {
				client.info(stopped);
				statusBarItem.tooltip = stopped;
				serverRunning = false;
			}
			updateStatusBarVisibility(Window.activeTextEditor);
		});
		client.onReady().then(() => {
			client.onNotification(StatusNotification.type, (params) => {
				updateStatus(params.state);
			});

			client.onNotification(exitCalled, (params) => {
				serverCalledProcessExit = true;
				client.error(`Server process exited with code ${params[0]}. This usually indicates a misconfigured ${linterName} setup.`, params[1]);
				Window.showErrorMessage(`${linterName} server shut down itself. See '${linterName}' output channel for details.`);
			});

			client.onRequest(NoStandardLibraryRequest.type, (params) => {
				const key = 'noStandardMessageShown';
				let state = context.globalState.get<NoStandardState>(key, {});
				let uri: Uri = Uri.parse(params.source.uri);
				let workspaceFolder = Workspace.getWorkspaceFolder(uri);
				let config = Workspace.getConfiguration('standard');
				let linter = config.get('semistandard', false) ? 'semistandard' : 'standard';
				if (workspaceFolder) {
					client.info([
						'',
						`Failed to load the ${linterName} library for the document ${uri.fsPath}`,
						'',
						`To use ${linterName} please install ${linterName} by running 'npm install ${linter}' in the workspace folder ${workspaceFolder.name}`,
						`or globally using 'npm install -g ${linter}'. You need to reopen the workspace after installing ${linterName}.`,
						'',
						`Alternatively you can disable ${linterName} for the workspace folder ${workspaceFolder.name} by executing the 'Disable JavaScript Standard Style' command.`
					].join('\n'));
					if (!state.workspaces) {
						state.workspaces = Object.create(null);
					}
					if (!state.workspaces[workspaceFolder.uri.toString()]) {
						state.workspaces[workspaceFolder.uri.toString()] = true;
						client.outputChannel.show(true);
						context.globalState.update(key, state);
					}
				} else {
					client.info([
						`Failed to load the ${linterName} library for the document ${uri.fsPath}`,
						`To use ${linterName} for single JavaScript file install standard globally using 'npm install -g ${linter}'.`,
						`You need to reopen VS Code after installing ${linter}.`,
					].join('\n'));
					if (!state.global) {
						state.global = true;
						client.outputChannel.show(true);
						context.globalState.update(key, state);
					}
				}
				return {};
			});
		});

		if (dummyCommands) {
			dummyCommands.forEach(command => command.dispose());
			dummyCommands = undefined;
		}
		context.subscriptions.push(
			client.start(),
			Commands.registerCommand('standard.executeAutofix', () => {
				let textEditor = Window.activeTextEditor;
				if (!textEditor) {
					return;
				}
				let textDocument: VersionedTextDocumentIdentifier = {
					uri: textEditor.document.uri.toString(),
					version: textEditor.document.version
				};
				let params: ExecuteCommandParams = {
					command: 'standard.applyAutoFix',
					arguments: [textDocument]
				}
				client.sendRequest(ExecuteCommandRequest.type, params).then(undefined, () => {
					Window.showErrorMessage(`Failed to apply ${linterName} fixes to the document. Please consider opening an issue with steps to reproduce.`);
				});
			}),
			Commands.registerCommand('standard.showOutputChannel', () => { client.outputChannel.show(); }),
			statusBarItem
		);
	}
Example #6
0
export function activate(context: ExtensionContext) {
  /**
   * Custom Block Grammar generation command
   */
  context.subscriptions.push(
    vscode.commands.registerCommand('vetur.generateGrammar', () => {
      const customBlocks: { [k: string]: string } =
        workspace.getConfiguration().get('vetur.grammar.customBlocks') || {};
      try {
        const generatedGrammar = getGeneratedGrammar(
          path.resolve(context.extensionPath, 'syntaxes/vue.json'),
          customBlocks
        );
        fs.writeFileSync(path.resolve(context.extensionPath, 'syntaxes/vue-generated.json'), generatedGrammar, 'utf-8');
        vscode.window.showInformationMessage('Successfully generated vue grammar. Reload VS Code to enable it.');
      } catch (e) {
        vscode.window.showErrorMessage(
          'Failed to generate vue grammar. `vetur.grammar.customBlocks` contain invalid language values'
        );
      }
    })
  );

  /**
   * Vue Language Server Initialization
   */
  const serverModule = context.asAbsolutePath(path.join('server', 'dist', 'vueServerMain.js'));
  const debugOptions = { execArgv: ['--nolazy', '--inspect=6005'] };

  const serverOptions: ServerOptions = {
    run: { module: serverModule, transport: TransportKind.ipc },
    debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
  };

  const documentSelector = ['vue'];
  const config = workspace.getConfiguration();

  const clientOptions: LanguageClientOptions = {
    documentSelector,
    synchronize: {
      configurationSection: ['vetur', 'emmet', 'html', 'javascript', 'typescript', 'prettier', 'stylusSupremacy'],
      fileEvents: vscode.workspace.createFileSystemWatcher('{**/*.js,**/*.ts}', true, false, true)
    },
    initializationOptions: {
      config
    },
    revealOutputChannelOn: RevealOutputChannelOn.Never
  };

  const client = new LanguageClient('vetur', 'Vue Language Server', serverOptions, clientOptions);
  const disposable = client.start();
  context.subscriptions.push(disposable);
  const isDecoratorEnabled = workspace.getConfiguration().get<boolean>('vetur.colorDecorators.enable');

  if (isDecoratorEnabled) {
    client.onReady().then(registerColorProvider);
  }

  languages.setLanguageConfiguration('vue-html', {
    wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\$\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g,
    onEnterRules: [
      {
        beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'),
        afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>$/i,
        action: { indentAction: IndentAction.IndentOutdent }
      },
      {
        beforeText: new RegExp(`<(?!(?:${EMPTY_ELEMENTS.join('|')}))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$`, 'i'),
        action: { indentAction: IndentAction.Indent }
      }
    ]
  });

  function registerColorProvider() {
    const colorSubscription = languages.registerColorProvider(documentSelector, {
      provideDocumentColors(doc) {
        const params: DocumentColorParams = {
          textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(doc)
        };
        return client.sendRequest(DocumentColorRequest.type, params)
          .then(symbols => symbols.map(symbol => {
            const range = client.protocol2CodeConverter.asRange(symbol.range);
            const color = new vscode.Color(symbol.color.red, symbol.color.green, symbol.color.blue, symbol.color.alpha);
            return new vscode.ColorInformation(range, color);
          }));
      },
      provideColorPresentations(color, context) {
        const params: ColorPresentationParams = {
          textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(context.document),
          color,
          range: client.code2ProtocolConverter.asRange(context.range)
        };
        return client.sendRequest(ColorPresentationRequest.type, params)
          .then(presentations => presentations.map(p => {
            const presentation = new vscode.ColorPresentation(p.label);
            presentation.textEdit =
              p.textEdit && client.protocol2CodeConverter.asTextEdit(p.textEdit);
            presentation.additionalTextEdits =
              p.additionalTextEdits && client.protocol2CodeConverter.asTextEdits(p.additionalTextEdits);
            return presentation;
          }));
      }
    });
    context.subscriptions.push(colorSubscription);
  }
}
export function activate(context: ExtensionContext) {
	
	let repl_port = 7477;
	var isInitialized = false;
	let regexp = new RegExp('nREPL server started on port');
	var rconn: nrepl_client.Connection;
	let env = {};
	let cwd = "/Users/jnorton/Clojure/repl_test";
	let repl = spawn('/usr/local/bin/lein', ["repl", ":headless", ":port", "" + repl_port], {cwd: cwd, env: env});
	
	// use default completions if none are available from Compliment
	//context.subscriptions.push(languages.registerCompletionItemProvider("clojure", new CompletionItemProvider()))

	repl.stderr.on('data', (data) => {
		var output = '' + data;
		console.log('STDERR: ' + output);
	});

	repl.stdout.on('data', (data) => {
		var output = '' + data;
		console.log('STDOUT: ' + output);
		
		if (!isInitialized && regexp.test(output)) {
			console.log("Connecting to nREPL...");
			isInitialized = true;
			rconn = nrepl_client.connect({port: repl_port, host: "127.0.0.1", verbose: false});
			rconn.eval("(use 'compliment.core)", (err: any, result: any) => {
				context.subscriptions.push(languages.registerCompletionItemProvider("clojure", new ClojureCompletionItemProvider(rconn)));
				context.subscriptions.push(languages.registerDefinitionProvider("clojure", new ClojureDefinitionProvider(rconn)));
				// TODO move code into here so we can wait for this eval to finish
				console.log("Namespace loaded");
			});
		} else {
			console.log("Not connecting");
		}
	});
	
	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'server.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ["--nolazy", "--debug=6004"] };
	
	// If the extension is launched in debug mode the debug server options are used.
	// Otherwise the run options are used.
	let serverOptions: ServerOptions = {
		run : { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	}
	
	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for plain text documents
		documentSelector: ['clojure'],
		synchronize: {
			// Synchronize the setting section 'languageServerExample' to the server
			configurationSection: 'languageServerExample',
			// Notify the server about file changes to '.clientrc files contain in the workspace
			fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
		}
	}
	
	// Create the language client and start the client.
	let client = new LanguageClient('Language Server Example', serverOptions, clientOptions);
	let disposable = client.start();
	let promise = client.onReady();
	// promise.then(() => {
		
	// 		let rconn = nrepl_client.connect({port: repl_port, host: "127.0.0.1", verbose: false});
	// 		rconn.eval("(use 'compliment.core)", (err: any, result: any) => {
	// 		// TODO move code into here so we can wait for this eval to finish
	// 		});
	// });
	// client.onReady(() => void {
		
	// });
	
	// Push the disposable to the context's subscriptions so that the 
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);
	
	
	
	console.log("Clojure extension active");
}
Example #8
0
export function activate(context: ExtensionContext) {
	// We need to go one level up since an extension compile the js code into
	// the output folder.
	let serverModule = path.join(__dirname, '..', 'server', 'server.js');
	let debugOptions = { execArgv: ["--nolazy", "--debug=6004"] };
	let serverOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions}
	};

	let clientOptions: LanguageClientOptions = {
		documentSelector: ['javascript', 'javascriptreact'],
		synchronize: {
			configurationSection: 'eslint',
			fileEvents: [
				workspace.createFileSystemWatcher('**/.eslintr{c.js,c.yaml,c.yml,c,c.json}'),
				workspace.createFileSystemWatcher('**/package.json')
			]
		}
	}

	let client = new LanguageClient('ESLint', serverOptions, clientOptions);

	function applyTextEdits(uri: string, documentVersion: number, edits: TextEdit[]) {
		let textEditor = window.activeTextEditor;
		if (textEditor && textEditor.document.uri.toString() === uri) {
			if (textEditor.document.version !== documentVersion) {
				window.showInformationMessage(`ESLint fixes are outdated and can't be applied to the document.`);
			}
			textEditor.edit(mutator => {
				for(let edit of edits) {
					mutator.replace(Protocol2Code.asRange(edit.range), edit.newText);
				}
			}).then((success) => {
				if (!success) {
					window.showErrorMessage('Failed to apply ESLint fixes to the document. Please consider opening an issue with steps to reproduce.');
				}
			});
		}
	}

	function fixAllProblems() {
		let textEditor = window.activeTextEditor;
		if (!textEditor) {
			return;
		}
		let uri: string = textEditor.document.uri.toString();
		client.sendRequest(AllFixesRequest.type, { textDocument: { uri }}).then((result) => {
			if (result) {
				applyTextEdits(uri, result.documentVersion, result.edits);
			}
		}, (error) => {
			window.showErrorMessage('Failed to apply ESLint fixes to the document. Please consider opening an issue with steps to reproduce.');
		});
	}

	context.subscriptions.push(
		new SettingMonitor(client, 'eslint.enable').start(),
		commands.registerCommand('eslint.applySingleFix', applyTextEdits),
		commands.registerCommand('eslint.applySameFixes', applyTextEdits),
		commands.registerCommand('eslint.applyAllFixes', applyTextEdits),
		commands.registerCommand('eslint.fixAllProblems', fixAllProblems)
	);
}
export function activate(context: vscode.ExtensionContext): void {
    // Asynchronously enable telemetry
    Telemetry.init('cordova-tools', require('./../../package.json').version, {isExtensionProcess: true});

    // Get the project root and check if it is a Cordova project
    if (!vscode.workspace.rootPath) {
        return;
    }

    let cordovaProjectRoot = CordovaProjectHelper.getCordovaProjectRoot(vscode.workspace.rootPath);

    if (!cordovaProjectRoot) {
        return;
    }

    if (path.resolve(cordovaProjectRoot) !== path.resolve(vscode.workspace.rootPath)) {
        vscode.window.showWarningMessage("VSCode Cordova extension requires the workspace root to be your Cordova project's root. The extension hasn't been activated.");

        return;
    }

    let activateExtensionEvent = TelemetryHelper.createTelemetryEvent("activate");
    let projectType: IProjectType;

    TelemetryHelper.determineProjectTypes(cordovaProjectRoot)
        .then((projType) => {
            projectType = projType;
            activateExtensionEvent.properties["projectType"] = projType;
        })
        .finally(() => {
            Telemetry.send(activateExtensionEvent);
        }).done();

    // We need to update the type definitions added to the project
    // as and when plugins are added or removed. For this reason,
    // setup a file system watcher to watch changes to plugins in the Cordova project
    // Note that watching plugins/fetch.json file would suffice

    let watcher = vscode.workspace.createFileSystemWatcher('**/plugins/fetch.json', false /*ignoreCreateEvents*/, false /*ignoreChangeEvents*/, false /*ignoreDeleteEvents*/);

    watcher.onDidChange((e: vscode.Uri) => updatePluginTypeDefinitions(cordovaProjectRoot));
    watcher.onDidDelete((e: vscode.Uri) => updatePluginTypeDefinitions(cordovaProjectRoot));
    watcher.onDidCreate((e: vscode.Uri) => updatePluginTypeDefinitions(cordovaProjectRoot));

    context.subscriptions.push(watcher);
    let extensionServer: ExtensionServer = new ExtensionServer();
    extensionServer.setup();
    context.subscriptions.push(extensionServer);

    // Register Cordova commands
    context.subscriptions.push(vscode.commands.registerCommand('cordova.prepare',
        () => CordovaCommandHelper.executeCordovaCommand(cordovaProjectRoot, "prepare")));
    context.subscriptions.push(vscode.commands.registerCommand('cordova.build',
        () => CordovaCommandHelper.executeCordovaCommand(cordovaProjectRoot, "build")));
    context.subscriptions.push(vscode.commands.registerCommand('cordova.run',
        () => CordovaCommandHelper.executeCordovaCommand(cordovaProjectRoot, "run")));
    context.subscriptions.push(vscode.commands.registerCommand('ionic.prepare',
        () => CordovaCommandHelper.executeCordovaCommand(cordovaProjectRoot, "prepare", true)));
    context.subscriptions.push(vscode.commands.registerCommand('ionic.build',
        () => CordovaCommandHelper.executeCordovaCommand(cordovaProjectRoot, "build", true)));
    context.subscriptions.push(vscode.commands.registerCommand('ionic.run',
        () => CordovaCommandHelper.executeCordovaCommand(cordovaProjectRoot, "run", true)));

    // Install Ionic type definitions if necessary
    if (CordovaProjectHelper.isIonicProject(cordovaProjectRoot)) {
        let ionicTypings: string[] = [
            path.join("angularjs", "angular.d.ts"),
            path.join("jquery", "jquery.d.ts"),
            path.join("ionic", "ionic.d.ts"),
            path.join("cordova-ionic", "plugins", "keyboard.d.ts")
        ];
        TsdHelper.installTypings(CordovaProjectHelper.getOrCreateTypingsTargetPath(cordovaProjectRoot), ionicTypings, cordovaProjectRoot);
    }

    let pluginTypings = getPluginTypingsJson();
    if (!pluginTypings) {
        return;
    }

    // Install the type defintion files for Cordova
    TsdHelper.installTypings(CordovaProjectHelper.getOrCreateTypingsTargetPath(cordovaProjectRoot), [pluginTypings[CORDOVA_TYPINGS_QUERYSTRING].typingFile], cordovaProjectRoot);

    // Install type definition files for the currently installed plugins
    updatePluginTypeDefinitions(cordovaProjectRoot);

    // In VSCode 0.10.10+, if the root doesn't contain jsconfig.json or tsconfig.json, intellisense won't work for files without /// typing references, so add a jsconfig.json here if necessary
    let jsconfigPath: string = path.join(vscode.workspace.rootPath, JSCONFIG_FILENAME);
    let tsconfigPath: string = path.join(vscode.workspace.rootPath, TSCONFIG_FILENAME);

    Q.all([Q.nfcall(fs.exists, jsconfigPath), Q.nfcall(fs.exists, tsconfigPath)]).spread((jsExists: boolean, tsExists: boolean) => {
        if (!jsExists && !tsExists) {
            Q.nfcall(fs.writeFile, jsconfigPath, "{}").then(() => {
                // Any open file must be reloaded to enable intellisense on them, so inform the user
                vscode.window.showInformationMessage("A 'jsconfig.json' file was created to enable IntelliSense. You may need to reload your open JS file(s).");
            });
        }
    });
}
Example #10
0
export function activate(context: ExtensionContext): void {
	const serverModule: string = context.asAbsolutePath(path.join('server', 'out', 'index.js'));
	const debugOptions: { execArgv: string[] } = { execArgv: ['--nolazy', '--inspect=6009'] };

	// If the extension is launched in debug mode then the debug server options are used
	// Otherwise the run options are used
	const serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions },
	};

	const rubyDocumentSelector: { scheme: string; language: string }[] = [
		{ scheme: 'file', language: 'ruby' },
		{ scheme: 'untitled', language: 'ruby' },
	];

	// Options to control the language client
	const clientOptions: LanguageClientOptions = {
		documentSelector: rubyDocumentSelector,
		synchronize: {
			// Notify server of changes to .ruby-version or .rvmrc files
			fileEvents: workspace.createFileSystemWatcher('**/{.ruby-version,.rvmrc}'),
		},
		outputChannel: window.createOutputChannel('Ruby Language Server'),
		middleware: {
			workspace: {
				configuration: (
					params: ConfigurationParams,
					token: CancellationToken,
					next: Function
				): any[] => {
					if (!params.items) {
						return [];
					}
					let result = next(params, token, next);
					let settings = result[0];
					let scopeUri = '';

					for (let item of params.items) {
						if (!item.scopeUri) {
							continue;
						} else {
							scopeUri = item.scopeUri;
						}
					}
					let resource = client.protocol2CodeConverter.asUri(scopeUri);
					let workspaceFolder = workspace.getWorkspaceFolder(resource);
					if (workspaceFolder) {
						// Convert any relative paths to absolute paths
						if (
							settings.lint &&
							settings.lint.rubocop &&
							typeof settings.lint.rubocop === 'object'
						) {
							const {
								lint: { rubocop },
							} = settings;
							for (const key of RUBOCOP_ABSOLUTE_PATH_KEYS) {
								if (rubocop[key]) {
									rubocop[key] = rubocop[key].map(f => convertAbsolute(f, workspaceFolder));
								}
							}
						}

						// Save the file's workspace folder
						const protocolUri = client.code2ProtocolConverter.asUri(workspaceFolder.uri);
						settings.workspaceFolderUri = protocolUri;
					}
					return result;
				},
			} as WorkspaceMiddleware,
		},
	};

	// Create the language client and start the client.
	client = new LanguageClient('ruby', 'Ruby', serverOptions, clientOptions);
	client.registerProposedFeatures();
	client.registerFeature(new WorkspaceRubyEnvironmentFeature(client));

	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(client.start());
}
Example #11
0
export function activate(context: ExtensionContext) {

	let toDispose = context.subscriptions;

	let packageInfo = getPackageInfo(context);
	telemetryReporter = packageInfo && new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);

	let serverMain = readJSONFile(context.asAbsolutePath('./server/package.json')).main;
	let serverModule = context.asAbsolutePath(path.join('server', serverMain));

	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=' + (9000 + Math.round(Math.random() * 10000))] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	let documentSelector = ['json', 'jsonc'];

	let schemaResolutionErrorStatusBarItem = window.createStatusBarItem(StatusBarAlignment.Right, 0);
	schemaResolutionErrorStatusBarItem.command = '_json.retryResolveSchema';
	schemaResolutionErrorStatusBarItem.tooltip = localize('json.schemaResolutionErrorMessage', 'Unable to resolve schema.') + ' ' + localize('json.clickToRetry', 'Click to retry.');
	schemaResolutionErrorStatusBarItem.text = '$(alert)';
	toDispose.push(schemaResolutionErrorStatusBarItem);

	let fileSchemaErrors = new Map<string, string>();

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for json documents
		documentSelector,
		initializationOptions: {
			handledSchemaProtocols: ['file'] // language server only loads file-URI. Fetching schemas with other protocols ('http'...) are made on the client.
		},
		synchronize: {
			// Synchronize the setting section 'json' to the server
			configurationSection: ['json', 'http'],
			fileEvents: workspace.createFileSystemWatcher('**/*.json')
		},
		middleware: {
			workspace: {
				didChangeConfiguration: () => client.sendNotification(DidChangeConfigurationNotification.type, { settings: getSettings() })
			},
			handleDiagnostics: (uri: Uri, diagnostics: Diagnostic[], next: HandleDiagnosticsSignature) => {
				const schemaErrorIndex = diagnostics.findIndex(candidate => candidate.code === /* SchemaResolveError */ 0x300);

				if (schemaErrorIndex === -1) {
					fileSchemaErrors.delete(uri.toString());
					return next(uri, diagnostics);
				}

				const schemaResolveDiagnostic = diagnostics[schemaErrorIndex];
				fileSchemaErrors.set(uri.toString(), schemaResolveDiagnostic.message);

				if (window.activeTextEditor && window.activeTextEditor.document.uri.toString() === uri.toString()) {
					schemaResolutionErrorStatusBarItem.show();
				}

				next(uri, diagnostics);
			}
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('json', localize('jsonserver.name', 'JSON Language Server'), serverOptions, clientOptions);
	client.registerProposedFeatures();

	let disposable = client.start();
	toDispose.push(disposable);
	client.onReady().then(() => {
		disposable = client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			if (uri.scheme !== 'http' && uri.scheme !== 'https') {
				return workspace.openTextDocument(uri).then(doc => {
					return doc.getText();
				}, error => {
					return Promise.reject(error);
				});
			} else {
				const headers = { 'Accept-Encoding': 'gzip, deflate' };
				return xhr({ url: uriPath, followRedirects: 5, headers }).then(response => {
					return response.responseText;
				}, (error: XHRResponse) => {
					return Promise.reject(error.responseText || getErrorStatusDescription(error.status) || error.toString());
				});
			}
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};

		let handleActiveEditorChange = (activeEditor?: TextEditor) => {
			if (!activeEditor) {
				return;
			}

			const activeDocUri = activeEditor.document.uri.toString();

			if (activeDocUri && fileSchemaErrors.has(activeDocUri)) {
				schemaResolutionErrorStatusBarItem.show();
			} else {
				schemaResolutionErrorStatusBarItem.hide();
			}
		};

		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => {
			handleContentChange(d.uri);
			fileSchemaErrors.delete(d.uri.toString());
		}));
		toDispose.push(window.onDidChangeActiveTextEditor(handleActiveEditorChange));

		let handleRetryResolveSchemaCommand = () => {
			if (window.activeTextEditor) {
				schemaResolutionErrorStatusBarItem.text = '$(watch)';
				const activeDocUri = window.activeTextEditor.document.uri.toString();
				client.sendRequest(ForceValidateRequest.type, activeDocUri).then((diagnostics) => {
					const schemaErrorIndex = diagnostics.findIndex(candidate => candidate.code === /* SchemaResolveError */ 0x300);
					if (schemaErrorIndex !== -1) {
						// Show schema resolution errors in status bar only; ref: #51032
						const schemaResolveDiagnostic = diagnostics[schemaErrorIndex];
						fileSchemaErrors.set(activeDocUri, schemaResolveDiagnostic.message);
					} else {
						schemaResolutionErrorStatusBarItem.hide();
					}
					schemaResolutionErrorStatusBarItem.text = '$(alert)';
				});
			}
		};

		toDispose.push(commands.registerCommand('_json.retryResolveSchema', handleRetryResolveSchemaCommand));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		extensions.onDidChange(_ => {
			client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));
		});

		documentSelector.forEach(selector => {
			toDispose.push(languages.registerSelectionRangeProvider(selector, {
				async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[]> {
					const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(document);
					const rawResult = await client.sendRequest<SelectionRange[][]>('$/textDocument/selectionRanges', { textDocument, positions: positions.map(client.code2ProtocolConverter.asPosition) });
					if (Array.isArray(rawResult)) {
						return rawResult.map(rawSelectionRanges => {
							return rawSelectionRanges.reduceRight((parent: SelectionRange | undefined, selectionRange: SelectionRange) => {
								return {
									range: client.protocol2CodeConverter.asRange(selectionRange.range),
									parent,
								};
							}, undefined)!;
						});
					}
					return [];
				}
			}));
		});
	});



	let languageConfiguration: LanguageConfiguration = {
		wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|[^\s{}\[\],:]+/,
		indentationRules: {
			increaseIndentPattern: /^.*(\{[^}]*|\[[^\]]*)$/,
			decreaseIndentPattern: /^\s*[}\]],?\s*$/
		}
	};
	languages.setLanguageConfiguration('json', languageConfiguration);
	languages.setLanguageConfiguration('jsonc', languageConfiguration);
}
Example #12
0
export function activate(context: ExtensionContext) {

	let toDispose = context.subscriptions;

	let packageInfo = getPackageInfo(context);
	telemetryReporter = packageInfo && new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'jsonServerMain.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=' + (9000 + Math.round(Math.random() * 10000))] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	let documentSelector = ['json', 'jsonc'];

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for json documents
		documentSelector,
		synchronize: {
			// Synchronize the setting section 'json' to the server
			configurationSection: ['json', 'http'],
			fileEvents: workspace.createFileSystemWatcher('**/*.json')
		},
		middleware: {
			workspace: {
				didChangeConfiguration: () => client.sendNotification(DidChangeConfigurationNotification.type, { settings: getSettings() })
			}
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('json', localize('jsonserver.name', 'JSON Language Server'), serverOptions, clientOptions);
	client.registerProposedFeatures();
	client.registerFeature({
		fillClientCapabilities(capabilities: FoldingRangeClientCapabilities): void {
			let textDocumentCap = capabilities.textDocument;
			if (!textDocumentCap) {
				textDocumentCap = capabilities.textDocument = {};
			}
			textDocumentCap.foldingRange = {
				dynamicRegistration: false,
				rangeLimit: 5000,
				lineFoldingOnly: true
			};
		},
		initialize(capabilities, documentSelector): void {
		}
	});

	let disposable = client.start();
	toDispose.push(disposable);
	client.onReady().then(() => {
		disposable = client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};
		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => handleContentChange(d.uri)));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		toDispose.push(initFoldingProvider());
	});

	let languageConfiguration: LanguageConfiguration = {
		wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|[^\s{}\[\],:]+/,
		indentationRules: {
			increaseIndentPattern: /^.*(\{[^}]*|\[[^\]]*)$/,
			decreaseIndentPattern: /^\s*[}\]],?\s*$/
		}
	};
	languages.setLanguageConfiguration('json', languageConfiguration);
	languages.setLanguageConfiguration('jsonc', languageConfiguration);

	function initFoldingProvider(): Disposable {
		function getKind(kind: string | undefined): FoldingRangeKind | undefined {
			if (kind) {
				switch (kind) {
					case LSFoldingRangeKind.Comment:
						return FoldingRangeKind.Comment;
					case LSFoldingRangeKind.Imports:
						return FoldingRangeKind.Imports;
					case LSFoldingRangeKind.Region:
						return FoldingRangeKind.Region;
				}
			}
			return void 0;
		}
		return languages.registerFoldingRangeProvider(documentSelector, {
			provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken) {
				const param: FoldingRangeRequestParam = {
					textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document)
				};
				return client.sendRequest(FoldingRangeRequest.type, param, token).then(ranges => {
					if (Array.isArray(ranges)) {
						return ranges.map(r => new FoldingRange(r.startLine, r.endLine, getKind(r.kind)));
					}
					return null;
				}, error => {
					client.logFailedRequest(FoldingRangeRequest.type, error);
					return null;
				});
			}
		});
	}
}
	languages.getLanguages().then(languageIds => {

		// The server is implemented in node
		let serverModule = context.asAbsolutePath(path.join('server', 'server.js'));
		// The debug options for the server
		let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] };

		// If the extension is launch in debug mode the debug server options are use
		// Otherwise the run options are used
		let serverOptions: ServerOptions = {
			run: { module: serverModule, transport: TransportKind.ipc },
			debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
		};

		// Options to control the language client
		let clientOptions: LanguageClientOptions = {
			// Register the server for yaml documents
			documentSelector: ['yaml'],
			synchronize: {
				configurationSection: ['json.schemas', 'http.proxy', 'http.proxyStrictSSL', 'languageServerYamlSchema'],
				fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
				// fileEvents: workspace.createFileSystemWatcher('**/.yaml')
			},
			initializationOptions: {
				languageIds
			}
		};

		// Create the language client and start the client.
  	let client = new LanguageClient('Language Server YAML Schema', serverOptions, clientOptions);
		client.onNotification(TelemetryNotification.type, e => {
			// if (telemetryReporter) {
			// 	telemetryReporter.sendTelemetryEvent(e.key, e.data);
			// }
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let disposable = client.start();

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

		// Push the disposable to the context's subscriptions so that the
		// client can be deactivated on extension deactivation
		context.subscriptions.push(disposable);

		languages.setLanguageConfiguration('yaml', {
			comments: {
				"lineComment": "#"
			},
			"brackets": [
				["{", "}"],
				["[", "]"],
				["(", ")"]
			]
		});
	});
export function monitorConfigChanges() {
  const watcher = workspace.createFileSystemWatcher(CONFIG_FILE);
  watcher.onDidChange(uri => {
    displayDefaultUserName(uri.fsPath);
  });
}
Example #15
0
export function activate(context: ExtensionContext) {

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'server.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--debug=6004'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for json documents
		documentSelector: ['json'],
		synchronize: {
			// Synchronize the setting section 'json' to the server
			configurationSection: ['json.schemas', 'http.proxy', 'http.proxyStrictSSL'],
			fileEvents: workspace.createFileSystemWatcher('**/.json')
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('JSON Server', serverOptions, clientOptions);
	client.onNotification(TelemetryNotification.type, (e) => {
		// to be done
	});

	// handle content request
	client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
		let uri = Uri.parse(uriPath);
		return workspace.openTextDocument(uri).then(doc => {
			return doc.getText();
		}, error => {
			return Promise.reject(error);
		});
	});

	let disposable = client.start();

	client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));

	// Push the disposable to the context's subscriptions so that the
	// client can be deactivated on extension deactivation
	context.subscriptions.push(disposable);

	languages.setLanguageConfiguration('json', {
		wordPattern: /(-?\d*\.\d\w*)|([^\[\{\]\}\:\"\,\s]+)/g,
		__characterPairSupport: {
			autoClosingPairs: [
				{ open: '{', close: '}' },
				{ open: '[', close: ']' },
				{ open: '(', close: ')' },
				{ open: '"', close: '"', notIn: ['string'] },
				{ open: '\'', close: '\'', notIn: ['string', 'comment'] },
				{ open: '`', close: '`', notIn: ['string', 'comment'] }
			]
		}
	});
}
Example #16
0
export function activate(context: ExtensionContext) {

	let toDispose = context.subscriptions;

	let packageInfo = getPackageInfo(context);
	telemetryReporter = packageInfo && new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey);

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'jsonServerMain.js'));
	// The debug options for the server
	let debugOptions = { execArgv: ['--nolazy', '--inspect=6046'] };

	// If the extension is launch in debug mode the debug server options are use
	// Otherwise the run options are used
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
	};

	let documentSelector = ['json', 'jsonc'];

	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for json documents
		documentSelector,
		synchronize: {
			// Synchronize the setting section 'json' to the server
			configurationSection: ['json', 'http'],
			fileEvents: workspace.createFileSystemWatcher('**/*.json')
		},
		middleware: {
			workspace: {
				didChangeConfiguration: () => client.sendNotification(DidChangeConfigurationNotification.type, { settings: getSettings() })
			}
		}
	};

	// Create the language client and start the client.
	let client = new LanguageClient('json', localize('jsonserver.name', 'JSON Language Server'), serverOptions, clientOptions);
	client.registerProposedFeatures();

	let disposable = client.start();
	toDispose.push(disposable);
	client.onReady().then(() => {
		client.onTelemetry(e => {
			if (telemetryReporter) {
				telemetryReporter.sendTelemetryEvent(e.key, e.data);
			}
		});

		// handle content request
		client.onRequest(VSCodeContentRequest.type, (uriPath: string) => {
			let uri = Uri.parse(uriPath);
			return workspace.openTextDocument(uri).then(doc => {
				return doc.getText();
			}, error => {
				return Promise.reject(error);
			});
		});

		let handleContentChange = (uri: Uri) => {
			if (uri.scheme === 'vscode' && uri.authority === 'schemas') {
				client.sendNotification(SchemaContentChangeNotification.type, uri.toString());
			}
		};
		toDispose.push(workspace.onDidChangeTextDocument(e => handleContentChange(e.document.uri)));
		toDispose.push(workspace.onDidCloseTextDocument(d => handleContentChange(d.uri)));

		client.sendNotification(SchemaAssociationNotification.type, getSchemaAssociation(context));
	});

	let languageConfiguration: LanguageConfiguration = {
		wordPattern: /("(?:[^\\\"]*(?:\\.)?)*"?)|[^\s{}\[\],:]+/,
		indentationRules: {
			increaseIndentPattern: /^.*(\{[^}]*|\[[^\]]*)$/,
			decreaseIndentPattern: /^\s*[}\]],?\s*$/
		}
	};
	languages.setLanguageConfiguration('json', languageConfiguration);
	languages.setLanguageConfiguration('jsonc', languageConfiguration);
}
Example #17
0
export async function activate(context: ExtensionContext) {

  // sbt command support
  context.subscriptions.push(new Sbt(context));

  // find JDK_HOME or JAVA_HOME
  const req = new Requirements();
  let javaHome;
  try {
    javaHome = await req.getJavaHome();
  } catch (pathNotFound) {
    window.showErrorMessage(pathNotFound);
    return;
  }

  const toolsJar = javaHome + '/lib/tools.jar';
  console.info('Adding to classpath ' + toolsJar);

  // The server is implemented in Scala
  const coursierPath = path.join(context.extensionPath, './coursier');
  console.info('Using coursier ' + coursierPath);

  console.log('Workspace location is: ' + workspace.rootPath);

  let proxyArgs = [];
  const proxySettings = workspace.getConfiguration().get('http.proxy').toString();
  if (proxySettings !== '') {
    console.log('Using proxy: ' + proxySettings);
    const proxyUrl = URL.parse(proxySettings);
    const javaProxyHttpHost = '-Dhttp.proxyHost=' + proxyUrl.hostname;
    const javaProxyHtppPort = '-Dhttp.proxyPort=' + proxyUrl.port;
    const javaProxyHttpsHost = '-Dhttps.proxyHost=' + proxyUrl.hostname;
    const javaProxyHttpsPort = '-Dhttps.proxyPort=' + proxyUrl.port;
    proxyArgs = [javaProxyHttpHost,javaProxyHtppPort,javaProxyHttpsHost,javaProxyHttpsPort];
  } else proxyArgs = [];
  const logLevel = workspace.getConfiguration().get('scalaLanguageServer.logLevel');
  let logLevelStr = '';
  if (logLevel != null) logLevelStr = logLevel.toString();

  const heapSize = workspace.getConfiguration().get('scalaLanguageServer.heapSize');
  let heapSizeStr = '-Xmx768M';
  if (heapSize != null) heapSizeStr = '-Xmx' + heapSize.toString();

  // tslint:disable-next-line:max-line-length
  const coursierArgs = ['launch', '-r', 'https://dl.bintray.com/dhpcs/maven', '-r', 'sonatype:releases', '-J', toolsJar, 'com.github.dragos:ensime-lsp_2.12:0.2.3', '-M', 'org.github.dragos.vscode.Main'];

  const javaArgs = proxyArgs.concat([
    heapSizeStr,
    '-Dvscode.workspace=' + workspace.rootPath,
    '-Dvscode.logLevel=' + logLevel,
    '-Densime.index.no.reverse.lookups=true',
    '-jar', coursierPath,
  ]).concat(coursierArgs);

  // The debug options for the server
  // tslint:disable-next-line:max-line-length
  const debugOptions = ['-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000,quiet=y'];

  // If the extension is launched in debug mode then the debug server options are used
  // Otherwise the run options are used
  const serverOptions: ServerOptions = {
    run: { command: 'java', args: javaArgs },
    debug: { command: 'java', args: debugOptions.concat(javaArgs) },
  };

  // Options to control the language client
  const clientOptions: LanguageClientOptions = {
    // Register the server for plain text documents
    documentSelector: [
      { language: 'scala', scheme: 'file' },
      { language: 'scala', scheme: 'untitled' },
    ],
    synchronize: {
      // // Synchronize the setting section 'languageServerExample' to the server
      // configurationSection: 'languageServerExample',
      // Notify the server about file changes to '.clientrc files contain in the workspace
      fileEvents: workspace.createFileSystemWatcher(workspace.rootPath + '/.ensime'),
    },
  };

  // Create the language client and start the client.
  // tslint:disable-next-line:max-line-length
  const disposable = new LanguageClient('Scala Server', serverOptions, clientOptions, false).start();

  // Push the disposable to the context's subscriptions so that the
  // client can be deactivated on extension deactivation
  context.subscriptions.push(disposable);

  // Taken from the Java plugin, this configuration can't be (yet) defined in the
  //  `scala.configuration.json` file
  languages.setLanguageConfiguration('scala', {
    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 },
      },
    ],
  });
}
Example #18
0
export function activate(context: ExtensionContext) {
    // The server is implemented in Node.
    const serverModule = context.asAbsolutePath(path.join("server", "sass-lint-server.js"));

    // The debug options for the server.
    const debugOptions = {
        execArgv: ["--nolazy", "--inspect=6010"]
    };

    // If the extension is launched in debug mode the debug server options are used, otherwise the run options are used.
    const serverOptions: ServerOptions = {
        run: {
            module: serverModule,
            transport: TransportKind.ipc
        },
        debug: {
            module: serverModule,
            transport: TransportKind.ipc,
            options: debugOptions
        }
    };

    // Options to control the language client.
    const clientOptions: LanguageClientOptions = {
        // Register the server for Sass documents.
        documentSelector: [
            {language: "sass", scheme: "file"},
            {language: "scss", scheme: "file"}
        ],
        synchronize: {
            // Synchronize the setting section "sasslint" to the server.
            configurationSection: "sasslint",
            fileEvents: workspace.createFileSystemWatcher("**/.{sass-lint.yml,sasslintrc}")
        },
        diagnosticCollectionName: "sass-lint",
        initializationFailedHandler: (error) => {
            client.error("Server initialization failed.", error);
            client.outputChannel.show(true);

            return false;
        },
        middleware: {
            workspace: {
                configuration: (params, token, next) => {
                    if (!params.items) {
                        return [];
                    }

                    const result = next(params, token);
                    let scopeUri = "";

                    for (const item of params.items) {
                        if (!item.scopeUri) {
                            continue;
                        } else {
                            scopeUri = item.scopeUri;
                        }
                    }

                    const resource = client.protocol2CodeConverter.asUri(scopeUri);
                    const workspaceFolder = workspace.getWorkspaceFolder(resource);

                    if (workspaceFolder) {
                        convertToAbsolutePaths(result[0], workspaceFolder);

                        if (workspaceFolder.uri.scheme === "file") {
                            result[0].workspaceFolderPath = workspaceFolder.uri.fsPath;
                        }
                    }

                    return result;
                }
            }
        }
    };

    function convertToAbsolutePaths(settings: Settings, folder: WorkspaceFolder) {
        const configFile = settings.configFile;
        if (configFile) {
            settings.configFile = convertAbsolute(configFile, folder);
        }

        const nodePath = settings.nodePath;
        if (nodePath) {
            settings.nodePath = convertAbsolute(nodePath, folder);
        }
    }

    function convertAbsolute(file: string, folder: WorkspaceFolder): string {
        if (path.isAbsolute(file)) {
            return file;
        }

        const folderPath = folder.uri.fsPath;
        if (!folderPath) {
            return file;
        }

        return path.join(folderPath, file);
    }

    // Create the language client and start it.
    const client = new LanguageClient("sasslint", "Sass Lint", serverOptions, clientOptions);
    client.registerProposedFeatures();

    void client.onReady().then(() => {
        client.onRequest(NoSassLintLibraryRequest.type, (params) => {
            const uri: Uri = Uri.parse(params.source.uri);

            const workspaceFolder = workspace.getWorkspaceFolder(uri);
            const packageManager = workspace.getConfiguration("sasslint", uri).get("packageManager", "npm");

            client.info(getInstallFailureMessage(uri, workspaceFolder, packageManager));

            return {};
        });
    });

    function getInstallFailureMessage(
        uri: Uri,
        workspaceFolder: WorkspaceFolder | undefined,
        packageManager: string
    ): string {
        const localCommands = {
            npm: "npm install sass-lint",
            yarn: "yarn add sass-lint"
        };

        const globalCommands = {
            npm: "npm install -g sass-lint",
            yarn: "yarn global add sass-lint"
        };

        const localCmd = localCommands[packageManager];
        const globalCmd = globalCommands[packageManager];

        const failureMessage = `Failed to load the sass-lint library for the document "${uri.fsPath}"\n\n`;

        if (workspaceFolder) { // Workspace opened on a folder.
            return [
                failureMessage,
                `To use sass-lint in this workspace, install it using "${localCmd}", or globally using "${globalCmd}".`,
                "\n\nYou need to reopen the workspace after installing sass-lint."
            ].join("");
        } else {
            return [
                failureMessage,
                `To use sass-lint for a single file, install it globally using "${globalCmd}".`,
                "\n\nYou need to reopen VS Code after installing sass-lint."
            ].join("");
        }
    }

    context.subscriptions.push(
        commands.registerCommand("sasslint.showOutputChannel", () => { client.outputChannel.show(); })
    );

    client.start();
}
Example #19
0
    isJava8(javaExecutablePath).then(eight => {
        if (!eight) {
            VSCode.window.showErrorMessage('Java language support requires Java 8 (using ' + javaExecutablePath + ')');
            
            return;
        }
                    
        // Options to control the language client
        let clientOptions: LanguageClientOptions = {
            // Register the server for java documents
            documentSelector: ['java'],
            synchronize: {
                // Synchronize the setting section 'java' to the server
                // NOTE: this currently doesn't do anything
                configurationSection: 'java',
                // Notify the server about file changes to 'javaconfig.json' files contain in the workspace
                fileEvents: [
                    VSCode.workspace.createFileSystemWatcher('**/javaconfig.json'),
                    VSCode.workspace.createFileSystemWatcher('**/*.java')
                ]
            }
        }
        
        function createServer(): Promise<StreamInfo> {
            return new Promise((resolve, reject) => {
                PortFinder.getPort((err, port) => {
                    let fatJar = Path.resolve(context.extensionPath, "out", "fat-jar.jar");
                    
                    let args = [
                        '-cp', fatJar, 
                        '-Djavacs.port=' + port,
                        'org.javacs.Main'
                    ];
                    
                    console.log(javaExecutablePath + ' ' + args.join(' '));
                    
                    Net.createServer(socket => {
                        console.log('Child process connected on port ' + port);

                        resolve({
                            reader: socket,
                            writer: socket
                        });
                    }).listen(port, () => {
                        let options = { stdio: 'inherit', cwd: VSCode.workspace.rootPath };
                        
                        // Start the child java process
                        ChildProcess.execFile(javaExecutablePath, args, options);
                    });
                });
            });
        }

        // Create the language client and start the client.
        let client = new LanguageClient('Language Server Example', createServer, clientOptions);
        let disposable = client.start();

        // Push the disposable to the context's subscriptions so that the 
        // client can be deactivated on extension deactivation
        context.subscriptions.push(disposable);
        
        // Set indentation rules
        VSCode.languages.setLanguageConfiguration('java', {
            indentationRules: {
                // ^(.*\*/)?\s*\}.*$
                decreaseIndentPattern: /^(.*\*\/)?\s*\}.*$/,
                // ^.*\{[^}"']*$
                increaseIndentPattern: /^.*\{[^}"']*$/
            },
            wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g,
            comments: {
                lineComment: '//',
                blockComment: ['/*', '*/']
            },
            brackets: [
                ['{', '}'],
                ['[', ']'],
                ['(', ')'],
            ],
            onEnterRules: [
                {
                    // e.g. /** | */
                    beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
                    afterText: /^\s*\*\/$/,
                    action: { indentAction: VSCode.IndentAction.IndentOutdent, appendText: ' * ' }
                },
                {
                    // e.g. /** ...|
                    beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/,
                    action: { indentAction: VSCode.IndentAction.None, appendText: ' * ' }
                },
                {
                    // e.g.  * ...|
                    beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/,
                    action: { indentAction: VSCode.IndentAction.None, appendText: '* ' }
                },
                {
                    // e.g.  */|
                    beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/,
                    action: { indentAction: VSCode.IndentAction.None, removeText: 1 }
                }
            ],
            
            // TODO equivalent of this from typescript when replacement for __electricCharacterSupport API is released
            // __electricCharacterSupport: {
            //     docComment: { scope: 'comment.documentation', open: '/**', lineStart: ' * ', close: ' */' }
            // }
        });
    });
Example #20
0
export function activate(context: ExtensionContext)
{
    let qol: QualityOfLife = new QualityOfLife();

    let serverModule = context.asAbsolutePath(path.join("server", "server.js"));
    let debugOptions = { execArgv: ["--nolazy", "--debug=6004"] };

    let serverOptions: ServerOptions = {
        run : { module: serverModule, transport: TransportKind.ipc },
        debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions }
    }

    let clientOptions: LanguageClientOptions = {
        documentSelector: ["php"],
        synchronize: {
            configurationSection: "languageServerExample",
            fileEvents: workspace.createFileSystemWatcher("**/.clientrc")
        }
    }

    // Create the language client and start the client.
    var langClient: LanguageClient = new LanguageClient("Crane Language Server", serverOptions, clientOptions);

    // Use this to handle a request sent from the server
    // https://github.com/Microsoft/vscode/blob/80bd73b5132268f68f624a86a7c3e56d2bbac662/extensions/json/client/src/jsonMain.ts
    // https://github.com/Microsoft/vscode/blob/580d19ab2e1fd6488c3e515e27fe03dceaefb819/extensions/json/server/src/server.ts
    //langClient.onRequest()

    let disposable = langClient.start();

    let crane: Crane = new Crane(langClient);

    var requestType: RequestType<any, any, any> = { method: "workDone" };
    langClient.onRequest(requestType, () => {
        // Load settings
        let craneSettings = workspace.getConfiguration("crane");
        if (craneSettings) {
            var showStatusBarItem = craneSettings.get<boolean>("showStatusBarBugReportLink", true);
            if (showStatusBarItem) {
                crane.statusBarItem.text = "$(bug) Report PHP Intellisense Bug";
                crane.statusBarItem.tooltip = "Found a problem with the PHP Intellisense provided by Crane? Click here to file a bug report on Github";
                crane.statusBarItem.command = "crane.reportBug";
                crane.statusBarItem.show();
            } else {
                crane.statusBarItem.hide();
            }
        } else {
            crane.statusBarItem.hide();
        }
    });

    // Register commands for QoL improvements
    let duplicateLineCommand = commands.registerCommand("crane.duplicateLine", qol.duplicateLineOrSelection);
    let reportBugCommand = commands.registerCommand("crane.reportBug", crane.reportBug);
    let semiColonCommand = commands.registerCommand("crane.handleSemiColonPress", () => crane.handleKeypress(";"));
    let curlyBraceCommand = commands.registerCommand("crane.handleClosingCurlyBracePress", () => crane.handleKeypress("}"));
    let bracketCommand = commands.registerCommand("crane.handleClosingBracketPress", () => crane.handleKeypress(")"));

    context.subscriptions.push(disposable);
    context.subscriptions.push(duplicateLineCommand);
    context.subscriptions.push(semiColonCommand);
    context.subscriptions.push(curlyBraceCommand);
    context.subscriptions.push(bracketCommand);
}