vscode-languageclient#LanguageClientOptions TypeScript Examples

The following examples show how to use vscode-languageclient#LanguageClientOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: vscode.ts    From vscode-stripe with MIT License 6 votes vote down vote up
mocks = {
  extensionContextMock: <vscode.ExtensionContext><unknown>{
    subscriptions: [],
    workspaceState: new TestMemento(),
    globalState: new TestMemento(),
    extensionPath: '',
    asAbsolutePath: (relativePath: string) => '',
    storagePath: '',
    globalStoragePath: '',
    logPath: '',
  },

  javaClientOptions: <LanguageClientOptions>{
    documentSelector: [{scheme: 'file', language: 'java'}],
    synchronize: {
      configurationSection: ['java', 'editor.insertSpaces', 'editor.tabSize'],
    },
    revealOutputChannelOn: 4,
  },
}
Example #2
Source File: languageServerClient.ts    From vscode-stripe with MIT License 6 votes vote down vote up
static async startStandardServer(
    context: ExtensionContext,
    clientOptions: LanguageClientOptions,
    serverOptions: ServerOptions,
    outputChannel: OutputChannel,
    telemetry: Telemetry,
  ) {
    if (standardClient.getClientStatus() !== ClientStatus.Uninitialized) {
      return;
    }

    const checkConflicts: boolean = await hasNoBuildToolConflict(context);
    if (!checkConflicts) {
      outputChannel.appendLine(
        `Build tool conflict detected in workspace. Please enable either maven (${IMPORT_MAVEN}) or gradle (${IMPORT_GRADLE}) in user settings.`,
      );
      telemetry.sendEvent('standardJavaServerHasBuildToolConflict');
      return;
    }

    if (javaServerMode === ServerMode.LIGHTWEIGHT) {
      // Before standard server is ready, we are in hybrid.
      javaServerMode = ServerMode.HYBRID;
    }

    await standardClient.initialize(clientOptions, serverOptions);
    standardClient.start();

    outputChannel.appendLine('Java language service (standard) is running.');
    telemetry.sendEvent('standardJavaServerStarted');
  }
Example #3
Source File: languageServerClient.ts    From vscode-stripe with MIT License 6 votes vote down vote up
static async startSyntaxServer(
    clientOptions: LanguageClientOptions,
    serverOptions: ServerOptions,
    outputChannel: OutputChannel,
    telemetry: Telemetry,
  ) {
    await syntaxClient.initialize(clientOptions, serverOptions);
    syntaxClient.start();
    outputChannel.appendLine('Java language service (syntax) is running.');
    telemetry.sendEvent('syntaxJavaServerStarted');
  }
Example #4
Source File: languageServerClient.ts    From vscode-stripe with MIT License 6 votes vote down vote up
static activateUniversalServer(
    context: ExtensionContext,
    outputChannel: OutputChannel,
    serverOptions: ServerOptions,
    telemetry: Telemetry,
  ) {
    outputChannel.appendLine('Starting universal language server');
    const universalClientOptions: LanguageClientOptions = {
      // Register the server for stripe-supported languages. dotnet is not yet supported.
      documentSelector: [
        {scheme: 'file', language: 'javascript'},
        {scheme: 'file', language: 'typescript'},
        {scheme: 'file', language: 'go'},
        // {scheme: 'file', language: 'java'},
        {scheme: 'file', language: 'php'},
        {scheme: 'file', language: 'python'},
        {scheme: 'file', language: 'ruby'},
      ],
      synchronize: {
        fileEvents: workspace.createFileSystemWatcher('**/.clientrc'),
      },
    };

    const universalClient = new LanguageClient(
      'stripeLanguageServer',
      'Stripe Language Server',
      serverOptions,
      universalClientOptions,
    );

    universalClient.onTelemetry((data: any) => {
      const eventData = data.data || null;
      telemetry.sendEvent(data.name, eventData);
    });

    universalClient.start();
    outputChannel.appendLine('Universal language server is running');
    telemetry.sendEvent('universalLanguageServerStarted');
  }
Example #5
Source File: extension.ts    From plugin-vscode with Apache License 2.0 5 votes vote down vote up
private clientOptions: LanguageClientOptions;
Example #6
Source File: extension.ts    From language-tools with MIT License 5 votes vote down vote up
function createLanguageServer(serverOptions: ServerOptions, clientOptions: LanguageClientOptions) {
    return new LanguageClient('svelte', 'Svelte', serverOptions, clientOptions);
}
Example #7
Source File: syntaxLanguageClient.ts    From vscode-stripe with MIT License 5 votes vote down vote up
public initialize(
    clientOptions: LanguageClientOptions,
    serverOptions: ServerOptions,
  ) {
    if (!serverOptions) {
      return;
    }

    const newClientOptions: LanguageClientOptions = Object.assign({}, clientOptions, {
      errorHandler: {
        error: (error: string, message: string) => {
          console.log(message);
          console.log(error);

          return ErrorAction.Continue;
        },
        closed: () => CloseAction.DoNotRestart,
      },
    });

    this.languageClient = new LanguageClient(
      'java',
      EXTENSION_NAME_SYNTAX,
      serverOptions,
      newClientOptions,
    );

    this.languageClient.onReady().then(() => {
      if (this.languageClient) {
        this.languageClient.onNotification(StatusNotification.type, (report: {type: any}) => {
          switch (report.type) {
            case 'Started':
              this.status = ClientStatus.Started;
              break;
            case 'Error':
              this.status = ClientStatus.Error;
              break;
            default:
              break;
          }
        });
      }
    });

    this.status = ClientStatus.Initialized;
  }
Example #8
Source File: standardLanguageClient.ts    From vscode-stripe with MIT License 5 votes vote down vote up
public initialize(
    clientOptions: LanguageClientOptions,
    serverOptions: ServerOptions,
  ) {
    if (!serverOptions || this.status !== ClientStatus.Uninitialized) {
      return;
    }

    this.languageClient = new LanguageClient(
      'java',
      EXTENSION_NAME_STANDARD,
      serverOptions,
      clientOptions,
    );

    this.languageClient.onReady().then(() => {
      if (!this.languageClient) {
        return;
      }

      this.languageClient.onNotification(StatusNotification.type, (report: StatusReport) => {
        switch (report.type) {
          case 'ServiceReady':
            updateServerMode(ServerMode.STANDARD);
            break;
          case 'Started':
            this.status = ClientStatus.Started;
            break;
          case 'Error':
            this.status = ClientStatus.Error;
            break;
          case 'Starting':
          case 'Message':
            // message goes to progress report instead
            break;
        }
      });
    });

    this.status = ClientStatus.Initialized;
  }
Example #9
Source File: languageServerClient.ts    From vscode-stripe with MIT License 5 votes vote down vote up
static async registerSwitchJavaServerModeCommand(
    context: ExtensionContext,
    jdkInfo: JDKInfo,
    clientOptions: LanguageClientOptions,
    workspacePath: string,
    outputChannel: OutputChannel,
    telemetry: Telemetry,
  ) {
    if ((await commands.getCommands()).includes(Commands.SWITCH_SERVER_MODE)) {
      return;
    }

    /**
     * Command to switch the server mode. Currently it only supports switch from lightweight to standard.
     * @param force force to switch server mode without asking
     */
    commands.registerCommand(
      Commands.SWITCH_SERVER_MODE,
      async (switchTo: ServerMode, force: boolean = false) => {
        const isWorkspaceTrusted = (workspace as any).isTrusted;
        if (isWorkspaceTrusted !== undefined && !isWorkspaceTrusted) {
          // keep compatibility for old engines < 1.56.0
          const button = 'Manage Workspace Trust';
          const choice = await window.showInformationMessage(
            'For security concern, Java language server cannot be switched to Standard mode in untrusted workspaces.',
            button,
          );
          if (choice === button) {
            commands.executeCommand('workbench.action.manageTrust');
          }
          return;
        }

        const clientStatus: ClientStatus = standardClient.getClientStatus();
        if (clientStatus === ClientStatus.Starting || clientStatus === ClientStatus.Started) {
          return;
        }

        if (javaServerMode === switchTo || javaServerMode === ServerMode.STANDARD) {
          return;
        }

        let choice: string;
        if (force) {
          choice = 'Yes';
        } else {
          choice =
            (await window.showInformationMessage(
              'Are you sure you want to switch the Java language server to Standard mode?',
              'Yes',
              'No',
            )) || 'No';
        }

        if (choice === 'Yes') {
          telemetry.sendEvent('switchToStandardMode');

          try {
            this.startStandardServer(
              context,
              clientOptions,
              prepareExecutable(jdkInfo, workspacePath, context, false, outputChannel, telemetry),
              outputChannel,
              telemetry,
            );
          } catch (e) {
            outputChannel.appendLine(`${e}`);
            telemetry.sendEvent('failedToSwitchToStandardMode');
          }
        }
      },
    );
  }
Example #10
Source File: extension.ts    From reach-ide with Eclipse Public License 2.0 5 votes vote down vote up
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
	// --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging
	let debugOptions = { 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
	let serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: {
			module: serverModule,
			transport: TransportKind.ipc,
			options: debugOptions
		}
	};

	terminal = window.createTerminal({ name: 'Reach IDE' });
	const reachExecutablePath = workspace.getConfiguration().get('reachide.executableLocation') as string;
	const wf = workspace.workspaceFolders[0].uri.path || '.';
	const reachPath = (reachExecutablePath === './reach')
		? path.join(wf, 'reach')
		: reachExecutablePath;
	registerCommands(context, reachPath);


	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for Reach .rsh documents
		documentSelector: [
			{
			  pattern: '**/*.rsh',
			  scheme: 'file'
			}
		],
		synchronize: {
			// Notify the server about file changes to '.clientrc files contained in the workspace
			fileEvents: workspace.createFileSystemWatcher('**/*.rsh')
		}
	};

	// Create the language client and start the client.
	client = new LanguageClient(
		'reachide',
		'Reach IDE',
		serverOptions,
		clientOptions
	);

	// Start the client. This will also launch the server
	client.start();

	initButtons(context);

	// Inject association for .rsh file type
	if (workspace.workspaceFolders !== undefined) {
		rootFolder = url.fileURLToPath( workspace.workspaceFolders[0].uri.toString() );
	}
	associateRshFiles();

	window.registerTreeDataProvider('reach-commands', new CommandsTreeDataProvider());
	window.registerTreeDataProvider('reach-help', new HelpTreeDataProvider());
	window.registerTreeDataProvider('reach-docs', new DocumentationTreeDataProvider());
}
Example #11
Source File: lsp.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
export function startClient(opts: { context: ExtensionContext; port: number }) {
  const { context, port } = opts;
  // The server is implemented in node
  const pathToDev = path.join(
    __dirname,
    "..",
    "node_modules",
    "@dendronhq",
    "lsp-server",
    "out",
    "server.js"
  );

  let serverModule: string;
  const isDev = fs.existsSync(pathToDev);
  if (isDev) {
    serverModule = pathToDev;
  } else {
    serverModule = context.asAbsolutePath(
      path.join("dist", "lsp-server", "dist", "server.js")
    );
  }
  const ctx = "startLSPClient";
  Logger.info({ ctx, serverModule, isDev, msg: "starting client" });

  // TODO: don't hradcode
  // let expressModule = context.asAbsolutePath(
  //   path.join("express-server", "dist", "src", "index.js")
  // );
  // const { app: server } = require(expressModule);
  // The debug options for the server
  // --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging
  const debugOptions = { 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,
    },
  };

  // Options to control the language client
  const clientOptions: LanguageClientOptions = {
    // Register the server for plain text documents
    documentSelector: [{ scheme: "file", language: "markdown" }],
    synchronize: {
      // Notify the server about file changes to '.clientrc files contained in the workspace
      fileEvents: workspace.createFileSystemWatcher("dendron.yml"),
    },
    initializationOptions: {
      wsRoot: path.dirname(DendronExtension.workspaceFile().fsPath),
      port,
    },
  };

  // Create the language client and start the client.
  const client = new LanguageClient(
    "dendron.lsp",
    "Dendron LSP",
    serverOptions,
    clientOptions,
    true
  );

  // Start the client. This will also launch the server
  client.start();
  // const port = 3000;
  // server.listen(3000, () => {
  //   console.log("express server started");
  // });
  return { client };
}
Example #12
Source File: extension.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
export function activate(context: ExtensionContext) {
  // The server is implemented in node
  let serverModule = context.asAbsolutePath(
    path.join("server", "out", "server.js")
  );

  // TODO: don't hradcode
  let expressModule = context.asAbsolutePath(
    path.join("express-server", "dist", "src", "index.js")
  );
  // const { app: server } = require(expressModule);
  // The debug options for the server
  // --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging
  let debugOptions = { 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
  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: [{ scheme: "file", language: "markdown" }],
    synchronize: {
      // Notify the server about file changes to '.clientrc files contained in the workspace
      fileEvents: workspace.createFileSystemWatcher("**/.clientrc"),
    },
  };

  // Create the language client and start the client.
  client = new LanguageClient(
    "languageServerExample",
    "Language Server Example",
    serverOptions,
    clientOptions
  );

  // Start the client. This will also launch the server
  client.start();
  const port = 3000;
  // server.listen(3000, () => {
  //   console.log("express server started");
  // });
}
Example #13
Source File: extension.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
export async function activate(context: ExtensionContext): Promise<void> {
  const debugOptions = { execArgv: ["--nolazy", "--inspect=6009"] };

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

  const meta = JSON.parse(
    readFileSync(resolve(context.extensionPath, "package.json"), "utf8")
  );

  const logLevel = workspace.getConfiguration().get(LOGGING_LEVEL_CONFIG_PROP);

  const initializationOptions: ServerInitializationOptions = {
    modelCachePath: context.globalStoragePath,
    publisher: meta.publisher,
    name: meta.name,
    // validation of the logLevel value is done on the language server process.
    logLevel: logLevel as LogLevel,
  };

  const clientOptions: LanguageClientOptions = {
    documentSelector: [{ scheme: "file", pattern: "**/*.{view,fragment}.xml" }],
    synchronize: {
      fileEvents: [workspace.createFileSystemWatcher("**/manifest.json")],
    },
    outputChannelName: meta.displayName,
    initializationOptions: initializationOptions,
  };

  client = new LanguageClient(
    "UI5LanguageAssistant",
    "UI5 Language Assistant",
    serverOptions,
    clientOptions
  );

  client.start();
}
Example #14
Source File: languageServerClient.ts    From vscode-stripe with MIT License 4 votes vote down vote up
static async activateDotNetServer(
    context: ExtensionContext,
    outputChannel: OutputChannel,
    projectFile: string,
    telemetry: Telemetry,
  ) {
    outputChannel.appendLine('Detected C# Project file: ' + projectFile);

    // Applie Silicon is not supported for dotnet < 6.0:
    // https://github.com/dotnet/core/issues/4879#issuecomment-729046912
    if (getOSType() === OSType.macOSarm) {
      outputChannel.appendLine(
        `.NET runtime v${REQUIRED_DOTNET_RUNTIME_VERSION} is not supported for M1`,
      );
      telemetry.sendEvent('dotnetRuntimeAcquisitionSkippedForM1');
      return;
    }

    const result = await commands.executeCommand<{dotnetPath: string}>('dotnet.acquire', {
      version: REQUIRED_DOTNET_RUNTIME_VERSION,
      requestingExtensionId: 'stripe.vscode-stripe',
    });

    if (!result) {
      outputChannel.appendLine(
        `Failed to install .NET runtime v${REQUIRED_DOTNET_RUNTIME_VERSION}. Unable to start language server`,
      );

      telemetry.sendEvent('dotnetRuntimeAcquisitionFailed');
      return;
    }

    const dotNetExecutable = path.resolve(result.dotnetPath);
    outputChannel.appendLine('dotnet runtime acquired: ' + dotNetExecutable);

    const serverAssembly = context.asAbsolutePath(
      'dist/stripeDotnetLanguageServer/stripe.LanguageServer.dll',
    );

    const serverOptions: ServerOptions = {
      command: dotNetExecutable,
      args: [serverAssembly, projectFile],
    };

    // Options to control the language client
    const clientOptions: LanguageClientOptions = {
      // Register the server for plain text documents
      documentSelector: [{scheme: 'file', language: 'csharp'}],
      synchronize: {
        configurationSection: 'stripeCsharpLangaugeServer',
        fileEvents: workspace.createFileSystemWatcher('**/*.cs'),
      },
      diagnosticCollectionName: 'Stripe C# language server',
      errorHandler: {
        error: (error, message, count) => {
          console.log(message);
          console.log(error);

          return ErrorAction.Continue;
        },
        closed: () => CloseAction.DoNotRestart,
      },
    };

    // Create the language client and start the client.
    // We are overriding the show notification for the dotnet client.
    const dotnetClient = new (class extends LanguageClient {
      error(message: string, data: any, showNotification: boolean) {
        super.error(message, data, false);
      }
    })('stripeCsharpLanguageServer', 'Stripe C# Server', serverOptions, clientOptions);

    dotnetClient.trace = Trace.Verbose;
    outputChannel.appendLine('Starting C# language service for ' + projectFile);

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

    await dotnetClient.onReady();
    outputChannel.appendLine('C# language service is running.');
    telemetry.sendEvent('dotnetServerStarted');
  }
Example #15
Source File: languageServerClient.ts    From vscode-stripe with MIT License 4 votes vote down vote up
static async activateJavaServer(
    context: ExtensionContext,
    jdkInfo: JDKInfo,
    outputChannel: OutputChannel,
    projectFiles: string[],
    telemetry: Telemetry,
  ) {
    outputChannel.appendLine('Detected Java Project file: ' + projectFiles[0]);

    let storagePath = context.storagePath;
    if (!storagePath) {
      storagePath = path.resolve(os.tmpdir(), 'vscodesws_' + makeRandomHexString(5));
    }

    const workspacePath = path.resolve(storagePath + '/jdt_ws');
    const syntaxServerWorkspacePath = path.resolve(storagePath + '/ss_ws');

    javaServerMode = getJavaServerLaunchMode();
    commands.executeCommand('setContext', 'java:serverMode', javaServerMode);
    const requireSyntaxServer = javaServerMode !== ServerMode.STANDARD;
    const requireStandardServer = javaServerMode !== ServerMode.LIGHTWEIGHT;

    // Options to control the language client
    const clientOptions: LanguageClientOptions = {
      // Register the server for java
      documentSelector: [{scheme: 'file', language: 'java'}],
      synchronize: {
        configurationSection: ['java', 'editor.insertSpaces', 'editor.tabSize'],
      },
      initializationOptions: {
        extendedClientCapabilities: {
          classFileContentsSupport: true,
          clientHoverProvider: true,
          clientDocumentSymbolProvider: true,
          shouldLanguageServerExitOnShutdown: true,
        },
        projectFiles,
      },
      revealOutputChannelOn: 4, // never
      errorHandler: {
        error: (error, message, count) => {
          console.log(message);
          console.log(error);

          return ErrorAction.Continue;
        },
        closed: () => CloseAction.DoNotRestart,
      },
    };

    if (requireSyntaxServer) {
      try {
        await this.startSyntaxServer(
          clientOptions,
          prepareExecutable(
            jdkInfo,
            syntaxServerWorkspacePath,
            context,
            true,
            outputChannel,
            telemetry,
          ),
          outputChannel,
          telemetry,
        );
      } catch (e) {
        outputChannel.appendLine(`${e}`);
        telemetry.sendEvent('syntaxJavaServerFailedToStart');
      }
    }

    // handle server mode changes from syntax to standard
    this.registerSwitchJavaServerModeCommand(
      context,
      jdkInfo,
      clientOptions,
      workspacePath,
      outputChannel,
      telemetry,
    );

    onDidServerModeChangeEmitter.event((event: ServerMode) => {
      if (event === ServerMode.STANDARD) {
        syntaxClient.stop();
      }
      commands.executeCommand('setContext', 'java:serverMode', event);
    });

    // register hover provider
    registerHoverProvider(context);

    if (requireStandardServer) {
      try {
        await this.startStandardServer(
          context,
          clientOptions,
          prepareExecutable(jdkInfo, workspacePath, context, false, outputChannel, telemetry),
          outputChannel,
          telemetry,
        );
      } catch (e) {
        outputChannel.appendLine(`${e}`);
        telemetry.sendEvent('standardJavaServerFailedToStart');
      }
    }
  }
Example #16
Source File: extension.ts    From vscode-microprofile with Apache License 2.0 4 votes vote down vote up
function connectToLS(context: ExtensionContext, api: JavaExtensionAPI) {
  const microprofileContributions: MicroProfileContribution[] = collectMicroProfileJavaExtensions(extensions.all);
  return requirements.resolveRequirements(api).then(requirements => {
    const clientOptions: LanguageClientOptions = {
      documentSelector: getDocumentSelector(microprofileContributions),
      // wrap with key 'settings' so it can be handled same a DidChangeConfiguration
      initializationOptions: {
        settings: getVSCodeMicroProfileSettings(),
        extendedClientCapabilities: {
          commands: {
            commandsKind: {
              valueSet: [
                CommandKind.COMMAND_CONFIGURATION_UPDATE,
                CommandKind.COMMAND_OPEN_URI
              ]
            }
          },
          completion: {
            skipSendingJavaCompletionThroughLanguageServer: true
          },
          shouldLanguageServerExitOnShutdown: true
        }
      },
      synchronize: {
        // preferences starting with these will trigger didChangeConfiguration
        configurationSection: ['microprofile', '[microprofile]']
      },
      middleware: {
        workspace: {
          didChangeConfiguration: () => {
            languageClient.sendNotification(DidChangeConfigurationNotification.type, { settings: getVSCodeMicroProfileSettings() });
          }
        }
      }
    };

    const serverOptions = prepareExecutable(requirements, getMicroProfileJarExtensions(microprofileContributions));

    languageClient = new LanguageClient('microprofile.tools', 'Tools for MicroProfile', serverOptions, clientOptions);
    context.subscriptions.push(languageClient.start());

    if (extensions.onDidChange) {// Theia doesn't support this API yet
      context.subscriptions.push(extensions.onDidChange(() => {
        // if extensions that contribute mp java extensions change we need to reload the window
        handleExtensionChange(extensions.all);
      }));
    }

    return languageClient.onReady();
  });

  /**
   * Returns the document selector.
   *
   * The returned document selector contains the microprofile-properties and java document selectors
   * and all document selectors contained in `microProfileContributions`.
   *
   * @param microProfileContributions MicroProfile language server contributions from other VS Code extensions
   */
  function getDocumentSelector(microProfileContributions: MicroProfileContribution[]): DocumentSelector {
    let documentSelector: DocumentSelector = [
      { scheme: 'file', language: 'microprofile-properties' },
      { scheme: 'file', language: 'java' }
    ];
    microProfileContributions.forEach((contribution: MicroProfileContribution) => {
      documentSelector = documentSelector.concat(contribution.documentSelector);
    });
    return documentSelector;
  }

  /**
   * Returns a json object with key 'microprofile' and a json object value that
   * holds all microprofile settings.
   */
  function getVSCodeMicroProfileSettings(): { microprofile: any } {
    const defaultMicroProfileSettings = {};
    const configMicroProfile = workspace.getConfiguration().get('microprofile');
    const microprofileSettings = configMicroProfile ? configMicroProfile : defaultMicroProfileSettings;

    return {
      microprofile: microprofileSettings,
    };
  }

  /**
   * Returns an array of paths to MicroProfileLS extension jars within `microProfileContributions`
   *
   * @param microProfileContributions MicroProfile language server contributions from other VS Code extensions
   */
  function getMicroProfileJarExtensions(microProfileContributions: MicroProfileContribution[]): string[] {
    let jarPaths: string[] = [];
    microProfileContributions.forEach((contribution: MicroProfileContribution) => {
      if (contribution.jarExtensions && contribution.jarExtensions.length > 0) {
        jarPaths = jarPaths.concat(contribution.jarExtensions);
      }
    });
    return jarPaths;
  }
}
Example #17
Source File: extension.ts    From vscode-groovy-lint with GNU General Public License v3.0 4 votes vote down vote up
export function activate(context: ExtensionContext) {

	// Create diagnostics collection
	diagnosticsCollection = vscode.languages.createDiagnosticCollection(DIAGNOSTICS_COLLECTION_NAME);

	///////////////////////////////////////////////
	/////////////// Server + client ///////////////
	///////////////////////////////////////////////

	// The server is implemented in node
	let serverModule = context.asAbsolutePath(path.join('server', 'out', 'server.js'));
	// If the extension is launched in debug mode then 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: {
				execArgv: ['--nolazy', '--inspect=6009'],
				env: { "DEBUG": "vscode-groovy-lint,npm-groovy-lint" }
			}
		}
	};
	// Options to control the language client
	let clientOptions: LanguageClientOptions = {
		// Register the server for groovy documents
		documentSelector: [{ scheme: 'file', language: 'groovy' }],
		diagnosticCollectionName: DIAGNOSTICS_COLLECTION_NAME,
		progressOnInitialization: true,
		synchronize: {
			// Notify the server about file changes to '.clientrc files contained in the workspace
			fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
		}
	};
	// Create the language client and start the client.
	client = new LanguageClient(
		'groovyLint',
		'Groovy Lint',
		serverOptions,
		clientOptions
	);

	// Manage status bar item (with loading icon)
	statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
	statusBarItem.command = 'groovyLint.lint';
	statusBarItem.text = 'GroovyLint $(clock~spin)';
	statusBarItem.show();

	client.registerProposedFeatures();

	// Start the client. This will also launch the server
	context.subscriptions.push(
		client.start()
	);

	// Actions after client is ready
	client.onReady().then(() => {

		// Show status bar item to display & run groovy lint
		refreshStatusBar();

		// Manage status notifications
		client.onNotification(StatusNotification.type, async (status) => {
			await updateStatus(status);
		});

		// Open file in workspace when language server requests it
		client.onNotification(OpenNotification.type, async (notifParams: any) => {
			// Open textDocument from file path
			if (notifParams.file) {
				const openPath = vscode.Uri.parse("file:///" + notifParams.file); //A request file path
				const doc = await vscode.workspace.openTextDocument(openPath);
				await vscode.window.showTextDocument(doc, {
					preserveFocus: true,
					// eslint-disable-next-line eqeqeq
					preview: (notifParams.preview != null) ? notifParams.preview : true
				});
			}
			// Open textDocument from URI
			else if (notifParams.uri) {
				const openPath = vscode.Uri.parse(notifParams.uri); //A request file path
				const doc = await vscode.workspace.openTextDocument(openPath);
				await vscode.window.showTextDocument(doc, {
					preserveFocus: true,
					// eslint-disable-next-line eqeqeq
					preview: (notifParams.preview != null) ? notifParams.preview : true
				});
			}
			// Open url in external browser
			else if (notifParams.url) {
				await vscode.env.openExternal(notifParams.url);
			}
		});

		// Refresh status bar when active tab changes
		vscode.window.onDidChangeActiveTextEditor(async () => {
			await refreshStatusBar();
			await notifyDocumentToServer();
		});

	});
}
Example #18
Source File: extension.ts    From sorbet-lsp with MIT License 4 votes vote down vote up
export function activate(context: ExtensionContext) {
	let disposableClient: Disposable;

	const startLanguageServer = () => {
		let cmd = [];

		let vsconfig = vscode.workspace.getConfiguration('sorbet');
		const commandPath = vsconfig.commandPath || 'srb';
		const useBundler = vsconfig.useBundler;
		const useWatchman = vsconfig.useWatchman;
		const bundlerPath = vsconfig.bundlerPath || 'bundle';

		if (useBundler) {
			cmd = cmd.concat([bundlerPath, 'exec', 'srb']);
		} else {
			cmd.push(commandPath);
		}

		cmd = cmd.concat(['tc', '--lsp', '--enable-all-experimental-lsp-features']);

		if (!useWatchman) {
			cmd.push('--disable-watchman');
		}

		const firstWorkspace = (workspace.workspaceFolders && workspace.workspaceFolders[0]) ? workspace.workspaceFolders[0].uri.fsPath : null;

		if (!existsSync(`${firstWorkspace}/sorbet/config`)) {
			vscode.window.showInformationMessage('Sorbet config not found. Sorbet server will not be started');
			return;
		}

		const env = commonOptions(firstWorkspace);

		// The debug options for the server
		// --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging
		let debugOptions = { execArgv: ['--nolazy', '--inspect=6009'] };

		const serverOptions: ServerOptions = () => {
			return new Promise((resolve) => {
				let child = spawnWithBash(cmd, env);
				child.stderr.on('data', (data: Buffer) => {
					console.log(data.toString());
				});
				child.on('exit', (code, signal) => {
					console.log('Sorbet exited with code', code, signal);
				});
				resolve(child);
			});
		}

		// Options to control the language client
    let clientOptions: LanguageClientOptions = {
      // Register the server for plain text documents
      documentSelector: [{ scheme: 'file', language: 'ruby' }],
      synchronize: {
        // Notify the server about changes to relevant files in the workspace
        fileEvents: workspace.createFileSystemWatcher('{**/*.rb,**/*.gemspec,**/Gemfile}')
      },
      outputChannelName: 'Sorbet Language Server',
      revealOutputChannelOn: RevealOutputChannelOn.Never
    };


    // Create the language client and start the client.
    client = new LanguageClient(
      'sorbetLanguageServer',
      'Sorbet Language Server',
      serverOptions,
      clientOptions
    );

		// Start the client. This will also launch the server
		disposableClient = client.start();
	}

	const restartLanguageServer = function (): Promise<void> {
		return new Promise((resolve) => {
			if (disposableClient) {
				client.stop().then(() => {
					disposableClient.dispose();
					startLanguageServer();
					resolve();
				});
			} else {
				startLanguageServer();
				resolve();
			}
		});
	}

	// Restart command
	var disposableRestart = vscode.commands.registerCommand('sorbet.restart', () => {
		restartLanguageServer().then(() => {
			vscode.window.showInformationMessage('Sorbet server restarted.');
		});
	});
	context.subscriptions.push(disposableRestart);

	startLanguageServer();
}
Example #19
Source File: extension.ts    From language-tools with MIT License 4 votes vote down vote up
export function activateSvelteLanguageServer(context: ExtensionContext) {
    warnIfOldExtensionInstalled();

    const runtimeConfig = workspace.getConfiguration('svelte.language-server');

    const { workspaceFolders } = workspace;
    const rootPath = Array.isArray(workspaceFolders) ? workspaceFolders[0].uri.fsPath : undefined;

    const tempLsPath = runtimeConfig.get<string>('ls-path');
    // Returns undefined if path is empty string
    // Return absolute path if not already
    const lsPath =
        tempLsPath && tempLsPath.trim() !== ''
            ? path.isAbsolute(tempLsPath)
                ? tempLsPath
                : path.join(rootPath as string, tempLsPath)
            : undefined;

    const serverModule = require.resolve(lsPath || 'svelte-language-server/bin/server.js');
    console.log('Loading server from ', serverModule);

    // Add --experimental-modules flag for people using node 12 < version < 12.17
    // Remove this in mid 2022 and bump vs code minimum required version to 1.55
    const runExecArgv: string[] = ['--experimental-modules'];
    let port = runtimeConfig.get<number>('port') ?? -1;
    if (port < 0) {
        port = 6009;
    } else {
        console.log('setting port to', port);
        runExecArgv.push(`--inspect=${port}`);
    }
    const debugOptions = { execArgv: ['--nolazy', '--experimental-modules', `--inspect=${port}`] };

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

    const serverRuntime = runtimeConfig.get<string>('runtime');
    if (serverRuntime) {
        serverOptions.run.runtime = serverRuntime;
        serverOptions.debug.runtime = serverRuntime;
        console.log('setting server runtime to', serverRuntime);
    }

    const clientOptions: LanguageClientOptions = {
        documentSelector: [{ scheme: 'file', language: 'svelte' }],
        revealOutputChannelOn: RevealOutputChannelOn.Never,
        synchronize: {
            // TODO deprecated, rework upon next VS Code minimum version bump
            configurationSection: [
                'svelte',
                'prettier',
                'emmet',
                'javascript',
                'typescript',
                'css',
                'less',
                'scss'
            ],
            fileEvents: workspace.createFileSystemWatcher('{**/*.js,**/*.ts}', false, false, false)
        },
        initializationOptions: {
            configuration: {
                svelte: workspace.getConfiguration('svelte'),
                prettier: workspace.getConfiguration('prettier'),
                emmet: workspace.getConfiguration('emmet'),
                typescript: workspace.getConfiguration('typescript'),
                javascript: workspace.getConfiguration('javascript'),
                css: workspace.getConfiguration('css'),
                less: workspace.getConfiguration('less'),
                scss: workspace.getConfiguration('scss')
            },
            dontFilterIncompleteCompletions: true, // VSCode filters client side and is smarter at it than us
            isTrusted: (workspace as any).isTrusted
        }
    };

    let ls = createLanguageServer(serverOptions, clientOptions);
    context.subscriptions.push(ls.start());

    ls.onReady().then(() => {
        const tagRequestor = (document: TextDocument, position: Position) => {
            const param = ls.code2ProtocolConverter.asTextDocumentPositionParams(
                document,
                position
            );
            return ls.sendRequest(TagCloseRequest.type, param);
        };
        const disposable = activateTagClosing(
            tagRequestor,
            { svelte: true },
            'html.autoClosingTags'
        );
        context.subscriptions.push(disposable);
    });

    workspace.onDidSaveTextDocument(async (doc) => {
        const parts = doc.uri.toString(true).split(/\/|\\/);
        if (
            [
                /^tsconfig\.json$/,
                /^jsconfig\.json$/,
                /^svelte\.config\.(js|cjs|mjs)$/,
                // https://prettier.io/docs/en/configuration.html
                /^\.prettierrc$/,
                /^\.prettierrc\.(json|yml|yaml|json5|toml)$/,
                /^\.prettierrc\.(js|cjs)$/,
                /^\.prettierrc\.config\.(js|cjs)$/
            ].some((regex) => regex.test(parts[parts.length - 1]))
        ) {
            await restartLS(false);
        }
    });

    context.subscriptions.push(
        commands.registerCommand('svelte.restartLanguageServer', async () => {
            await restartLS(true);
        })
    );

    let restartingLs = false;
    async function restartLS(showNotification: boolean) {
        if (restartingLs) {
            return;
        }

        restartingLs = true;
        await ls.stop();
        ls = createLanguageServer(serverOptions, clientOptions);
        context.subscriptions.push(ls.start());
        await ls.onReady();
        if (showNotification) {
            window.showInformationMessage('Svelte language server restarted.');
        }
        restartingLs = false;
    }

    function getLS() {
        return ls;
    }

    addDidChangeTextDocumentListener(getLS);

    addFindFileReferencesListener(getLS, context);

    addRenameFileListener(getLS);

    addCompilePreviewCommand(getLS, context);

    addExtracComponentCommand(getLS, context);

    languages.setLanguageConfiguration('svelte', {
        indentationRules: {
            // Matches a valid opening tag that is:
            //  - Not a doctype
            //  - Not a void element
            //  - Not a closing tag
            //  - Not followed by a closing tag of the same element
            // Or matches `<!--`
            // Or matches open curly brace
            //
            increaseIndentPattern:
                // eslint-disable-next-line max-len, no-useless-escape
                /<(?!\?|(?:area|base|br|col|frame|hr|html|img|input|link|meta|param)\b|[^>]*\/>)([-_\.A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*<\/\1>)|<!--(?!.*-->)|\{[^}"']*$/,
            // Matches a closing tag that:
            //  - Follows optional whitespace
            //  - Is not `</html>`
            // Or matches `-->`
            // Or closing curly brace
            //
            // eslint-disable-next-line no-useless-escape
            decreaseIndentPattern: /^\s*(<\/(?!html)[-_\.A-Za-z0-9]+\b[^>]*>|-->|\})/
        },
        // Matches a number or word that either:
        //  - Is a number with an optional negative sign and optional full number
        //    with numbers following the decimal point. e.g `-1.1px`, `.5`, `-.42rem`, etc
        //  - Is a sequence of characters without spaces and not containing
        //    any of the following: `~!@$^&*()=+[{]}\|;:'",.<>/
        //
        wordPattern:
            // eslint-disable-next-line max-len, no-useless-escape
            /(-?\d*\.\d\w*)|([^\`\~\!\@\$\#\^\&\*\(\)\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\s]+)/g,
        onEnterRules: [
            {
                // Matches an opening tag that:
                //  - Isn't an empty element
                //  - Is possibly namespaced
                //  - Isn't a void element
                //  - Isn't followed by another tag on the same line
                //
                // eslint-disable-next-line no-useless-escape
                beforeText: new RegExp(
                    `<(?!(?:${EMPTY_ELEMENTS.join(
                        '|'
                    )}))([_:\\w][_:\\w-.\\d]*)([^/>]*(?!/)>)[^<]*$`,
                    'i'
                ),
                // Matches a closing tag that:
                //  - Is possibly namespaced
                //  - Possibly has excess whitespace following tagname
                afterText: /^<\/([_:\w][_:\w-.\d]*)\s*>/i,
                action: { indentAction: IndentAction.IndentOutdent }
            },
            {
                // Matches an opening tag that:
                //  - Isn't an empty element
                //  - Isn't namespaced
                //  - Isn't a void element
                //  - Isn't followed by another tag on the same line
                //
                // eslint-disable-next-line no-useless-escape
                beforeText: new RegExp(
                    `<(?!(?:${EMPTY_ELEMENTS.join('|')}))(\\w[\\w\\d]*)([^/>]*(?!/)>)[^<]*$`,
                    'i'
                ),
                action: { indentAction: IndentAction.Indent }
            }
        ]
    });

    return {
        getLS
    };
}