org.eclipse.lsp4j.ServerCapabilities Java Examples

The following examples show how to use org.eclipse.lsp4j.ServerCapabilities. 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: ServerOptions.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
public ServerOptions(ServerCapabilities serverCapabilities) {

        this.capabilities = serverCapabilities;

        if (capabilities.getTextDocumentSync().isRight()) {
            this.syncKind = capabilities.getTextDocumentSync().getRight().getChange();
        } else if (capabilities.getTextDocumentSync().isLeft()) {
            this.syncKind = capabilities.getTextDocumentSync().getLeft();
        }

        this.completionOptions = capabilities.getCompletionProvider();
        this.signatureHelpOptions = capabilities.getSignatureHelpProvider();
        this.codeLensOptions = capabilities.getCodeLensProvider();
        this.documentOnTypeFormattingOptions = capabilities.getDocumentOnTypeFormattingProvider();
        this.documentLinkOptions = capabilities.getDocumentLinkProvider();
        this.executeCommandOptions = capabilities.getExecuteCommandProvider();
        this.semanticHighlightingOptions = capabilities.getSemanticHighlighting();
    }
 
Example #2
Source File: RenameService2.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
private boolean shouldPrepareRename(ILanguageServerAccess access) {
	Either<Boolean, RenameOptions> provider = null;
	if (access != null) {
		InitializeResult initializeResult = access.getInitializeResult();
		if (initializeResult != null) {
			ServerCapabilities capabilities = initializeResult.getCapabilities();
			if (capabilities != null) {
				provider = capabilities.getRenameProvider();
			}
		}
	}
	if (provider != null && provider.isRight()) {
		return Boolean.TRUE.equals(provider.getRight().getPrepareProvider());
	} else {
		return false;
	}
}
 
Example #3
Source File: XMLLanguageServer.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
	LOGGER.info("Initializing XML Language server" + System.lineSeparator() + new ServerInfo().details());

	this.parentProcessId = params.getProcessId();

	// Update XML language service extensions with InitializeParams
	xmlLanguageService.initializeParams(params);

	ExtendedClientCapabilities extendedClientCapabilities = InitializationOptionsExtendedClientCapabilities
			.getExtendedClientCapabilities(params);
	capabilityManager.setClientCapabilities(params.getCapabilities(), extendedClientCapabilities);

	xmlTextDocumentService.updateClientCapabilities(capabilityManager.getClientCapabilities().capabilities,
			capabilityManager.getClientCapabilities().getExtendedCapabilities());

	updateSettings(InitializationOptionsSettings.getSettings(params));

	ServerCapabilities nonDynamicServerCapabilities = ServerCapabilitiesInitializer.getNonDynamicServerCapabilities(
			capabilityManager.getClientCapabilities(), xmlTextDocumentService.isIncrementalSupport());

	return CompletableFuture.completedFuture(new InitializeResult(nonDynamicServerCapabilities));
}
 
Example #4
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets list of LS initialized for given project
 *
 * @param onlyActiveLS true if this method should return only the already running
 *                     language servers, otherwise previously started language servers
 *                     will be re-activated
 * @return list of Language Servers
 */
@Nonnull
public List<LanguageServer> getLanguageServers(@Nullable Module project,
                                                      Predicate<ServerCapabilities> request, boolean onlyActiveLS) {
    List<LanguageServer> serverInfos = new ArrayList<>();
    for (LanguageServerWrapper wrapper : startedServers) {
        if ((!onlyActiveLS || wrapper.isActive()) && (project == null || wrapper.canOperate(project))) {
            @Nullable
            LanguageServer server = wrapper.getServer();
            if (server == null) {
                continue;
            }
            if (request == null
                    || wrapper.getServerCapabilities() == null /* null check is workaround for https://github.com/TypeFox/ls-api/issues/47 */
                    || request.test(wrapper.getServerCapabilities())) {
                serverInfos.add(server);
            }
        }
    }
    return serverInfos;
}
 
Example #5
Source File: XMLCapabilitiesTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testAllDynamicCapabilities() {
	setAllCapabilities(true);
	setAndInitializeCapabilities();

	assertEquals(11, capabilityIDs.size());

	ServerCapabilities serverCapabilities = ServerCapabilitiesInitializer
			.getNonDynamicServerCapabilities(manager.getClientCapabilities(), false);
	assertEquals(false, serverCapabilities.getDocumentRangeFormattingProvider());
	assertEquals(false, serverCapabilities.getDocumentFormattingProvider());
	assertEquals(false, serverCapabilities.getDocumentSymbolProvider());
	assertEquals(false, serverCapabilities.getHoverProvider());
	assertEquals(false, serverCapabilities.getDocumentHighlightProvider());
	assertEquals(false, serverCapabilities.getRenameProvider().getLeft());
	assertEquals(false, serverCapabilities.getFoldingRangeProvider().getLeft());
	assertEquals(false, serverCapabilities.getCodeActionProvider().getLeft());
	assertEquals(null, serverCapabilities.getCompletionProvider());
	assertEquals(null, serverCapabilities.getDocumentLinkProvider());
}
 
Example #6
Source File: XMLCapabilitiesTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNoDynamicCapabilities() {
	setAllCapabilities(false);
	setAndInitializeCapabilities();

	assertEquals(0, capabilityIDs.size());

	ServerCapabilities serverCapabilities = ServerCapabilitiesInitializer
			.getNonDynamicServerCapabilities(manager.getClientCapabilities(), false);
	assertEquals(true, serverCapabilities.getDocumentRangeFormattingProvider());
	assertEquals(true, serverCapabilities.getDocumentFormattingProvider());
	assertEquals(true, serverCapabilities.getDocumentSymbolProvider());
	assertEquals(true, serverCapabilities.getHoverProvider());
	assertEquals(true, serverCapabilities.getDocumentHighlightProvider());
	assertEquals(true, serverCapabilities.getRenameProvider().getLeft());
	assertEquals(true, serverCapabilities.getFoldingRangeProvider().getLeft());
	assertEquals(true, serverCapabilities.getCodeActionProvider().getLeft());
	assertEquals(DEFAULT_COMPLETION_OPTIONS, serverCapabilities.getCompletionProvider());
	assertEquals(DEFAULT_LINK_OPTIONS, serverCapabilities.getDocumentLinkProvider());
}
 
Example #7
Source File: XMLCapabilitiesTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDynamicFormattingWithPreferenceFalse() {
	textDocumentService.getSharedFormattingSettings().setEnabled(false);
	// Non Dynamic capabilities
	textDocument.setRangeFormatting(new RangeFormattingCapabilities(true));
	textDocument.setFormatting(new FormattingCapabilities(true));

	setAndInitializeCapabilities();

	Set<String> capabilityIDs = manager.getRegisteredCapabilities();
	assertEquals(0, capabilityIDs.size());

	ServerCapabilities serverCapabilities = ServerCapabilitiesInitializer
			.getNonDynamicServerCapabilities(manager.getClientCapabilities(), false);
	assertEquals(false, serverCapabilities.getDocumentRangeFormattingProvider());
	assertEquals(false, serverCapabilities.getDocumentFormattingProvider());
}
 
Example #8
Source File: CamelLanguageServer.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
	Integer processId = params.getProcessId();
	if(processId != null) {
		setParentProcessId(processId.longValue());
	} else {
		LOGGER.info("Missing Parent process ID!!");
		setParentProcessId(0);
	}
	
	new SettingsManager(getTextDocumentService()).apply(params);
	
	ServerCapabilities capabilities = createServerCapabilities();
	InitializeResult result = new InitializeResult(capabilities);
	return CompletableFuture.completedFuture(result);
}
 
Example #9
Source File: XMLCapabilitiesTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDynamicFormattingWithPreferenceTrue() {
	textDocumentService.getSharedFormattingSettings().setEnabled(true);
	// Dynamic capabilities
	textDocument.setRangeFormatting(new RangeFormattingCapabilities(true));
	textDocument.setFormatting(new FormattingCapabilities(true));

	setAndInitializeCapabilities();

	Set<String> capabilityIDs = manager.getRegisteredCapabilities();
	assertEquals(2, capabilityIDs.size());
	assertEquals(true, capabilityIDs.contains(FORMATTING_ID));
	assertEquals(true, capabilityIDs.contains(FORMATTING_RANGE_ID));

	ServerCapabilities serverCapabilities = ServerCapabilitiesInitializer
			.getNonDynamicServerCapabilities(manager.getClientCapabilities(), false);
	assertEquals(false, serverCapabilities.getDocumentRangeFormattingProvider());
	assertEquals(false, serverCapabilities.getDocumentFormattingProvider());
}
 
Example #10
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public void documentSaved(long timestamp) {
    this.modificationStamp = timestamp;
    ServerCapabilities serverCapabilities = languageServerWrapper.getServerCapabilities();
    if(serverCapabilities != null ) {
        Either<TextDocumentSyncKind, TextDocumentSyncOptions> textDocumentSync = serverCapabilities.getTextDocumentSync();
        if(textDocumentSync.isRight() && textDocumentSync.getRight().getSave() == null) {
            return;
        }
    }
    TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileUri.toString());
    DidSaveTextDocumentParams params = new DidSaveTextDocumentParams(identifier, document.getText());
    languageServerWrapper.getInitializedServer().thenAcceptAsync(ls -> ls.getTextDocumentService().didSave(params));
}
 
Example #11
Source File: LanguageServerWrapper.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
/**
 * @return if the server supports willSaveWaitUntil
 */
public boolean isWillSaveWaitUntil() {
    return Optional.ofNullable(getServerCapabilities())
      .map(ServerCapabilities::getTextDocumentSync)
      .map(Either::getRight)
      .map(TextDocumentSyncOptions::getWillSaveWaitUntil)
      .orElse(false);
}
 
Example #12
Source File: ServerCapabilitiesInitializer.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns all server capabilities (with default values) that aren't dynamic.
 * 
 * A service's dynamic capability is indicated by the client.
 * 
 * @param clientCapabilities
 * @return ServerCapabilities object
 */
public static ServerCapabilities getNonDynamicServerCapabilities(ClientCapabilitiesWrapper clientCapabilities,
		boolean isIncremental) {
	ServerCapabilities serverCapabilities = new ServerCapabilities();

	serverCapabilities
			.setTextDocumentSync(isIncremental ? TextDocumentSyncKind.Incremental : TextDocumentSyncKind.Full);

	serverCapabilities
			.setDocumentSymbolProvider(!clientCapabilities.isDocumentSymbolDynamicRegistrationSupported());
	serverCapabilities.setDocumentHighlightProvider(!clientCapabilities.isDocumentHighlightDynamicRegistered());
	serverCapabilities.setCodeActionProvider(!clientCapabilities.isCodeActionDynamicRegistered());
	serverCapabilities
			.setDocumentFormattingProvider(!clientCapabilities.isFormattingDynamicRegistrationSupported());
	serverCapabilities.setDocumentRangeFormattingProvider(
			!clientCapabilities.isRangeFormattingDynamicRegistrationSupported());
	serverCapabilities.setHoverProvider(!clientCapabilities.isHoverDynamicRegistered());
	serverCapabilities.setRenameProvider(!clientCapabilities.isRenameDynamicRegistrationSupported());
	serverCapabilities.setFoldingRangeProvider(!clientCapabilities.isRangeFoldingDynamicRegistrationSupported());
	serverCapabilities.setDefinitionProvider(!clientCapabilities.isDefinitionDynamicRegistered());
	serverCapabilities.setTypeDefinitionProvider(!clientCapabilities.isTypeDefinitionDynamicRegistered());
	serverCapabilities.setReferencesProvider(!clientCapabilities.isReferencesDynamicRegistrationSupported());

	if (!clientCapabilities.isLinkDynamicRegistrationSupported()) {
		serverCapabilities.setDocumentLinkProvider(DEFAULT_LINK_OPTIONS);
	}
	if (!clientCapabilities.isCompletionDynamicRegistrationSupported()) {
		serverCapabilities.setCompletionProvider(DEFAULT_COMPLETION_OPTIONS);
	}
	if (!clientCapabilities.isCodeLensDynamicRegistrationSupported()) {
		serverCapabilities.setCodeLensProvider(DEFAULT_CODELENS_OPTIONS);
	}
	return serverCapabilities;
}
 
Example #13
Source File: CamelLanguageServer.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
private ServerCapabilities createServerCapabilities() {
	ServerCapabilities capabilities = new ServerCapabilities();
	capabilities.setTextDocumentSync(TextDocumentSyncKind.Full);
	capabilities.setCompletionProvider(new CompletionOptions(Boolean.TRUE, Arrays.asList(".","?","&", "\"", "=")));
	capabilities.setHoverProvider(Boolean.TRUE);
	capabilities.setDocumentSymbolProvider(Boolean.TRUE);
	capabilities.setReferencesProvider(Boolean.TRUE);
	capabilities.setDefinitionProvider(Boolean.TRUE);
	capabilities.setCodeActionProvider(new CodeActionOptions(Arrays.asList(CodeActionKind.QuickFix)));
	return capabilities;
}
 
Example #14
Source File: RdfLintLanguageServer.java    From rdflint with MIT License 5 votes vote down vote up
@Override
public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
  // initialize rdflint
  String rootPath = convertUri2FilePath(params.getRootUri());
  String configPath = ConfigurationLoader.searchConfigPath(rootPath);
  try {
    rdflintParams = ConfigurationLoader.loadConfig(configPath);
    rdflintParams.setTargetDir(rootPath);
    rdflintParams.setOutputDir(rootPath);
    if (rdflintParams.getSuppressPath() == null) {
      rdflintParams.setSuppressPath(ConfigurationLoader.searchSuppressPath(rootPath));
    }
  } catch (IOException ex) {
    showException("Error cannot initialize rdflint", ex);
  }
  validators = new LinkedList<>();
  validators.add(new TrimValidator());
  validators.add(new UndefinedSubjectValidator());
  validators.add(new ShaclValidator());
  validators.forEach(v ->
      v.setParameters(rdflintParams)
  );
  refreshFileTripleSet();

  ServerCapabilities capabilities = new ServerCapabilities();
  capabilities.setTextDocumentSync(TextDocumentSyncKind.Full);
  InitializeResult result = new InitializeResult(capabilities);
  return CompletableFuture.completedFuture(result);
}
 
Example #15
Source File: CompletionProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean hasCompletionResolve(LSPBindings server) {
    ServerCapabilities capabilities = server.getInitResult().getCapabilities();
    if (capabilities == null) return false;
    CompletionOptions completionProvider = capabilities.getCompletionProvider();
    if (completionProvider == null) return false;
    Boolean resolveProvider = completionProvider.getResolveProvider();
    return resolveProvider != null && resolveProvider;
}
 
Example #16
Source File: CompletionProviderImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isTriggerCharacter(LSPBindings server, String text) {
    InitializeResult init = server.getInitResult();
    if (init == null) return false;
    ServerCapabilities capabilities = init.getCapabilities();
    if (capabilities == null) return false;
    CompletionOptions completionOptions = capabilities.getCompletionProvider();
    if (completionOptions == null) return false;
    List<String> triggerCharacters = completionOptions.getTriggerCharacters();
    if (triggerCharacters == null) return false;
    return triggerCharacters.stream().anyMatch(trigger -> text.endsWith(trigger));
}
 
Example #17
Source File: LSPBindings.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static InitializeResult initServer(Process p, LanguageServer server, FileObject root) throws InterruptedException, ExecutionException {
   InitializeParams initParams = new InitializeParams();
   initParams.setRootUri(Utils.toURI(root));
   initParams.setRootPath(FileUtil.toFile(root).getAbsolutePath()); //some servers still expect root path
   initParams.setProcessId(0);
   TextDocumentClientCapabilities tdcc = new TextDocumentClientCapabilities();
   DocumentSymbolCapabilities dsc = new DocumentSymbolCapabilities();
   dsc.setHierarchicalDocumentSymbolSupport(true);
   dsc.setSymbolKind(new SymbolKindCapabilities(Arrays.asList(SymbolKind.values())));
   tdcc.setDocumentSymbol(dsc);
   WorkspaceClientCapabilities wcc = new WorkspaceClientCapabilities();
   wcc.setWorkspaceEdit(new WorkspaceEditCapabilities());
   wcc.getWorkspaceEdit().setDocumentChanges(true);
   wcc.getWorkspaceEdit().setResourceOperations(Arrays.asList(ResourceOperationKind.Create, ResourceOperationKind.Delete, ResourceOperationKind.Rename));
   initParams.setCapabilities(new ClientCapabilities(wcc, tdcc, null));
   CompletableFuture<InitializeResult> initResult = server.initialize(initParams);
   while (true) {
       try {
           return initResult.get(100, TimeUnit.MILLISECONDS);
       } catch (TimeoutException ex) {
           if (p != null && !p.isAlive()) {
               InitializeResult emptyResult = new InitializeResult();
               emptyResult.setCapabilities(new ServerCapabilities());
               return emptyResult;
           }
       }
   }
}
 
Example #18
Source File: TeiidDdlLanguageServer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static ServerCapabilities createServerCapabilities() {
    ServerCapabilities capabilities = new ServerCapabilities();
    capabilities.setTextDocumentSync(TextDocumentSyncKind.Full);
    capabilities.setHoverProvider(Boolean.TRUE);
    capabilities.setDocumentHighlightProvider(Boolean.TRUE);
    capabilities.setDocumentSymbolProvider(Boolean.TRUE);
    // TODO: define capabilities, usually the first provided is completion
    capabilities.setCompletionProvider(DEFAULT_COMPLETION_OPTIONS);
    return capabilities;
}
 
Example #19
Source File: SyntaxInitHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void registerCapabilities(InitializeResult initializeResult) {
	ServerCapabilities capabilities = new ServerCapabilities();
	if (!preferenceManager.getClientPreferences().isClientDocumentSymbolProviderRegistered() && !preferenceManager.getClientPreferences().isDocumentSymbolDynamicRegistered()) {
		capabilities.setDocumentSymbolProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isDefinitionDynamicRegistered()) {
		capabilities.setDefinitionProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isTypeDefinitionDynamicRegistered()) {
		capabilities.setTypeDefinitionProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isFoldgingRangeDynamicRegistered()) {
		capabilities.setFoldingRangeProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isSelectionRangeDynamicRegistered()) {
		capabilities.setSelectionRangeProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isHoverDynamicRegistered()) {
		capabilities.setHoverProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isCompletionDynamicRegistered()) {
		capabilities.setCompletionProvider(CompletionHandler.DEFAULT_COMPLETION_OPTIONS);
	}
	TextDocumentSyncOptions textDocumentSyncOptions = new TextDocumentSyncOptions();
	textDocumentSyncOptions.setOpenClose(Boolean.TRUE);
	textDocumentSyncOptions.setSave(new SaveOptions(Boolean.TRUE));
	textDocumentSyncOptions.setChange(TextDocumentSyncKind.Incremental);
	capabilities.setTextDocumentSync(textDocumentSyncOptions);

	WorkspaceServerCapabilities wsCapabilities = new WorkspaceServerCapabilities();
	WorkspaceFoldersOptions wsFoldersOptions = new WorkspaceFoldersOptions();
	wsFoldersOptions.setSupported(Boolean.TRUE);
	wsFoldersOptions.setChangeNotifications(Boolean.TRUE);
	wsCapabilities.setWorkspaceFolders(wsFoldersOptions);
	capabilities.setWorkspace(wsCapabilities);

	initializeResult.setCapabilities(capabilities);
}
 
Example #20
Source File: LanguageServerWrapper.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
void unregisterCommands(List<String> cmds) {
    ServerCapabilities caps = this.getServerCapabilities();
    if (caps != null) {
        ExecuteCommandOptions commandProvider = caps.getExecuteCommandProvider();
        if (commandProvider != null) {
            List<String> existingCommands = commandProvider.getCommands();
            existingCommands.removeAll(cmds);
        }
    }
}
 
Example #21
Source File: GroovyLanguageServer.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<InitializeResult> initialize(InitializeParams params) {
    String rootUriString = params.getRootUri();
    if (rootUriString != null) {
        URI uri = URI.create(params.getRootUri());
        Path workspaceRoot = Paths.get(uri);
        groovyServices.setWorkspaceRoot(workspaceRoot);
    }

    CompletionOptions completionOptions = new CompletionOptions(false, Arrays.asList("."));
    ServerCapabilities serverCapabilities = new ServerCapabilities();
    serverCapabilities.setCompletionProvider(completionOptions);
    serverCapabilities.setTextDocumentSync(TextDocumentSyncKind.Full);
    serverCapabilities.setDocumentSymbolProvider(true);
    serverCapabilities.setWorkspaceSymbolProvider(true);
    serverCapabilities.setDocumentSymbolProvider(true);
    serverCapabilities.setReferencesProvider(true);
    serverCapabilities.setDefinitionProvider(true);
    serverCapabilities.setTypeDefinitionProvider(true);
    serverCapabilities.setHoverProvider(true);
    serverCapabilities.setRenameProvider(true);
    SignatureHelpOptions signatureHelpOptions = new SignatureHelpOptions();
    signatureHelpOptions.setTriggerCharacters(Arrays.asList("(", ","));
    serverCapabilities.setSignatureHelpProvider(signatureHelpOptions);

    InitializeResult initializeResult = new InitializeResult(serverCapabilities);
    return CompletableFuture.completedFuture(initializeResult);
}
 
Example #22
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public @Nonnull
List<CompletableFuture<LanguageServer>> getInitializedLanguageServers(@Nonnull VirtualFile file,
                                                                      @Nullable Predicate<ServerCapabilities> request) throws IOException {
    synchronized (startedServers) {
        Collection<LanguageServerWrapper> wrappers = getLSWrappers(file, request);
        return wrappers.stream().map(wrapper -> wrapper.getInitializedServer().thenApplyAsync(server -> {
            try {
                wrapper.connect(file, null);
            } catch (IOException e) {
                LOGGER.warn(e.getLocalizedMessage(), e);
            }
            return server;
        })).collect(Collectors.toList());
    }
}
 
Example #23
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get the requested language server instance for the given file. Starts the language server if not already started.
 *
 * @param file
 * @param lsDefinition
 * @param capabilitiesPredicate a predicate to check capabilities
 * @return a LanguageServer for the given file, which is defined with provided server ID and conforms to specified request
 * @deprecated use {@link #getInitializedLanguageServer(IFile, LanguageServerDefinition, Predicate)} instead.
 */
@Deprecated
public LanguageServer getLanguageServer(@Nonnull VirtualFile file, @Nonnull LanguageServersRegistry.LanguageServerDefinition lsDefinition,
                                               Predicate<ServerCapabilities> capabilitiesPredicate)
        throws IOException {
    LanguageServerWrapper wrapper = getLSWrapperForConnection(LSPIJUtils.getProject(file), lsDefinition, LSPIJUtils.toUri(file));
    if (capabilitiesPredicate == null
            || wrapper.getServerCapabilities() == null /* null check is workaround for https://github.com/TypeFox/ls-api/issues/47 */
            || capabilitiesPredicate.test(wrapper.getServerCapabilities())) {
        wrapper.connect(file, null);
        return wrapper.getServer();
    }
    return null;
}
 
Example #24
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Get the requested language server instance for the given file. Starts the language server if not already started.
 *
 * @param file
 * @param lsDefinition
 * @param capabilitiesPredicate a predicate to check capabilities
 * @return a LanguageServer for the given file, which is defined with provided server ID and conforms to specified request
 */
public CompletableFuture<LanguageServer> getInitializedLanguageServer(@Nonnull VirtualFile file,
                                                                             @Nonnull LanguageServersRegistry.LanguageServerDefinition lsDefinition,
                                                                             Predicate<ServerCapabilities> capabilitiesPredicate)
        throws IOException {
    LanguageServerWrapper wrapper = getLSWrapperForConnection(LSPIJUtils.getProject(file), lsDefinition, LSPIJUtils.toUri(file));
    if (capabilitiesPredicate == null
            || wrapper.getServerCapabilities() == null /* null check is workaround for https://github.com/TypeFox/ls-api/issues/47 */
            || capabilitiesPredicate.test(wrapper.getServerCapabilities())) {
        wrapper.connect(file, null);
        return wrapper.getInitializedServer();
    }
    return null;
}
 
Example #25
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * TODO we need a similar method for generic IDocument (enabling non-IFiles)
 *
 * @param file
 * @param request
 * @return
 * @throws IOException
 * @noreference This method is currently internal and should only be referenced
 * for testing
 */
@Nonnull
public Collection<LanguageServerWrapper> getLSWrappers(@Nonnull VirtualFile file,
                                                              @Nullable Predicate<ServerCapabilities> request) throws IOException {
    LinkedHashSet<LanguageServerWrapper> res = new LinkedHashSet<>();
    Module project = LSPIJUtils.getProject(file);
    if (project == null) {
        return res;
    }

    res.addAll(getMatchingStartedWrappers(file, request));

    // look for running language servers via content-type
    Queue<FileType> contentTypes = new LinkedList<>();
    Set<FileType> addedContentTypes = new HashSet<>();
    contentTypes.addAll(LSPIJUtils.getFileContentTypes(file));
    addedContentTypes.addAll(contentTypes);

    while (!contentTypes.isEmpty()) {
        FileType contentType = contentTypes.poll();
        if (contentType == null) {
            continue;
        }
        for (ContentTypeToLanguageServerDefinition mapping : LanguageServersRegistry.getInstance().findProviderFor(contentType)) {
            if (mapping != null && mapping.getValue() != null && mapping.isEnabled()) {
                LanguageServerWrapper wrapper = getLSWrapperForConnection(project, mapping.getValue(), LSPIJUtils.toUri(file));
                if (request == null
                        || wrapper.getServerCapabilities() == null /* null check is workaround for https://github.com/TypeFox/ls-api/issues/47 */
                        || request.test(wrapper.getServerCapabilities())) {
                    res.add(wrapper);
                }
            }
        }
    }
    return res;
}
 
Example #26
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private Collection<LanguageServerWrapper> getMatchingStartedWrappers(@Nonnull VirtualFile file,
                                                                            @Nullable Predicate<ServerCapabilities> request) {
    synchronized (startedServers) {
        return startedServers.stream().filter(wrapper -> wrapper.isConnectedTo(LSPIJUtils.toUri(file))
                || (LanguageServersRegistry.getInstance().matches(file, wrapper.serverDefinition)
                && wrapper.canOperate(LSPIJUtils.getProject(file)))).filter(wrapper -> request == null
                || (wrapper.getServerCapabilities() == null || request.test(wrapper.getServerCapabilities())))
                .collect(Collectors.toList());
    }
}
 
Example #27
Source File: LanguageServiceAccessor.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param document
 * @param filter
 * @return
 * @since 0.9
 */
@Nonnull
public CompletableFuture<List<LanguageServer>> getLanguageServers(@Nonnull Document document,
                                                                         Predicate<ServerCapabilities> filter) {
    URI uri = LSPIJUtils.toUri(document);
    if (uri == null) {
        return CompletableFuture.completedFuture(Collections.emptyList());
    }
    final List<LanguageServer> res = Collections.synchronizedList(new ArrayList<>());
    try {
        return CompletableFuture.allOf(getLSWrappers(document).stream().map(wrapper ->
                wrapper.getInitializedServer().thenComposeAsync(server -> {
                    if (server != null && (filter == null || filter.test(wrapper.getServerCapabilities()))) {
                        try {
                            return wrapper.connect(document);
                        } catch (IOException ex) {
                            LOGGER.warn(ex.getLocalizedMessage(), ex);
                        }
                    }
                    return CompletableFuture.completedFuture(null);
                }).thenAccept(server -> {
                    if (server != null) {
                        res.add(server);
                    }
                })).toArray(CompletableFuture[]::new)).thenApply(theVoid -> res);
    } catch (final Exception e) {
        LOGGER.warn(e.getLocalizedMessage(), e);
    }
    return CompletableFuture.completedFuture(Collections.emptyList());


}
 
Example #28
Source File: InitializeResult.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public InitializeResult(@NonNull final ServerCapabilities capabilities) {
  this.capabilities = Preconditions.<ServerCapabilities>checkNotNull(capabilities, "capabilities");
}
 
Example #29
Source File: InitializeResult.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public InitializeResult(@NonNull final ServerCapabilities capabilities, final ServerInfo serverInfo) {
  this(capabilities);
  this.serverInfo = serverInfo;
}
 
Example #30
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Configure the server capabilities for this instance.
 *
 * @param params
 *            the initialization parametrs
 * @return the server capabilities
 * @since 2.20
 */
protected ServerCapabilities createServerCapabilities(InitializeParams params) {
	ServerCapabilities serverCapabilities = new ServerCapabilities();
	serverCapabilities.setHoverProvider(true);
	serverCapabilities.setDefinitionProvider(true);
	serverCapabilities.setReferencesProvider(true);
	serverCapabilities.setDocumentSymbolProvider(true);
	serverCapabilities.setWorkspaceSymbolProvider(true);
	Set<? extends IResourceServiceProvider> allLanguages = getAllLanguages();
	if (allLanguages.stream().anyMatch((serviceProvider) -> serviceProvider.get(ICodeLensService.class) != null)) {
		CodeLensOptions codeLensOptions = new CodeLensOptions();
		codeLensOptions.setResolveProvider(allLanguages.stream()
				.anyMatch((serviceProvider) -> serviceProvider.get(ICodeLensResolver.class) != null));
		serverCapabilities.setCodeLensProvider(codeLensOptions);
	}
	serverCapabilities.setCodeActionProvider(allLanguages.stream()
			.anyMatch((serviceProvider) -> serviceProvider.get(ICodeActionService2.class) != null));

	serverCapabilities.setSignatureHelpProvider(new SignatureHelpOptions(ImmutableList.of("(", ",")));
	serverCapabilities.setTextDocumentSync(TextDocumentSyncKind.Incremental);
	CompletionOptions completionOptions = new CompletionOptions();
	completionOptions.setResolveProvider(false);
	completionOptions.setTriggerCharacters(ImmutableList.of("."));
	serverCapabilities.setCompletionProvider(completionOptions);
	serverCapabilities.setDocumentFormattingProvider(true);
	serverCapabilities.setDocumentRangeFormattingProvider(true);
	serverCapabilities.setDocumentHighlightProvider(true);
	ClientCapabilities clientCapabilities = null;
	if (params != null) {
		clientCapabilities = params.getCapabilities();
	}
	TextDocumentClientCapabilities textDocument = null;
	if (clientCapabilities != null) {
		textDocument = clientCapabilities.getTextDocument();
	}
	RenameCapabilities rename = null;
	if (textDocument != null) {
		rename = textDocument.getRename();
	}
	Boolean prepareSupport = null;
	if (rename != null) {
		prepareSupport = rename.getPrepareSupport();
	}
	boolean clientPrepareSupport = Objects.equal(Boolean.TRUE, prepareSupport);
	if (clientPrepareSupport && allLanguages.stream()
			.anyMatch(serviceProvider -> serviceProvider.get(IRenameService2.class) != null)) {
		RenameOptions renameOptions = new RenameOptions();
		renameOptions.setPrepareProvider(true);
		serverCapabilities.setRenameProvider(Either.<Boolean, RenameOptions>forRight(renameOptions));
	} else {
		serverCapabilities.setRenameProvider(Either.forLeft(allLanguages.stream()
				.anyMatch((serviceProvider) -> serviceProvider.get(IRenameService2.class) != null)));
	}
	WorkspaceClientCapabilities workspace = null;
	if (clientCapabilities != null) {
		workspace = clientCapabilities.getWorkspace();
	}
	ExecuteCommandCapabilities executeCommand = null;
	if (workspace != null) {
		executeCommand = workspace.getExecuteCommand();
		if (workspace.getWorkspaceFolders() == Boolean.TRUE && workspaceManager.isSupportsWorkspaceFolders()) {
			WorkspaceFoldersOptions workspaceFoldersOptions = new WorkspaceFoldersOptions();
			workspaceFoldersOptions.setSupported(true);
			workspaceFoldersOptions.setChangeNotifications(true);
			serverCapabilities.setWorkspace(new WorkspaceServerCapabilities(workspaceFoldersOptions));
		}
	}
	if (executeCommand != null) {
		commandRegistry.initialize(allLanguages, clientCapabilities, client);
		ExecuteCommandOptions executeCommandOptions = new ExecuteCommandOptions();
		executeCommandOptions.setCommands(commandRegistry.getCommands());
		serverCapabilities.setExecuteCommandProvider(executeCommandOptions);
	}
	semanticHighlightingRegistry.initialize(allLanguages, clientCapabilities, client);
	serverCapabilities.setSemanticHighlighting(
			new SemanticHighlightingServerCapabilities(semanticHighlightingRegistry.getAllScopes()));

	for (IResourceServiceProvider language : allLanguages) {
		ICapabilitiesContributor capabilitiesContributor = language.get(ICapabilitiesContributor.class);
		if (capabilitiesContributor != null) {
			capabilitiesContributor.contribute(serverCapabilities, params);
		}
	}
	return serverCapabilities;
}