Ejemplo n.º 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();
        }
    }
Ejemplo n.º 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*$/
		}
	});
}
Ejemplo n.º 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*$/
		}
	});
}
Ejemplo n.º 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();
}
Ejemplo n.º 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
		);
	}
Ejemplo n.º 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");
}
Ejemplo n.º 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)
	);
}
Ejemplo n.º 9
0
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).");
            });
        }
    });
}
Ejemplo n.º 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());
}