org.eclipse.lsp4j.TextDocumentSyncKind Java Examples

The following examples show how to use org.eclipse.lsp4j.TextDocumentSyncKind. 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: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
    checkEvent(event);
    if (syncKind == TextDocumentSyncKind.Full) {
        createChangeEvent(event);
    }

    if (changeParams != null) {
        final DidChangeTextDocumentParams changeParamsToSend = changeParams;
        changeParams = null;

        changeParamsToSend.getTextDocument().setVersion(++version);
        languageServerWrapper.getInitializedServer()
                .thenAcceptAsync(ls -> ls.getTextDocumentService().didChange(changeParamsToSend));
    }
}
 
Example #2
Source File: ServerCapabilities.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
public void setTextDocumentSync(final TextDocumentSyncKind textDocumentSync) {
  if (textDocumentSync == null) {
    this.textDocumentSync = null;
    return;
  }
  this.textDocumentSync = Either.forLeft(textDocumentSync);
}
 
Example #3
Source File: InitHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testWillSaveAndWillSaveWaitUntilCapabilities() throws Exception {
	ClientPreferences mockCapabilies = mock(ClientPreferences.class);
	when(mockCapabilies.isExecuteCommandDynamicRegistrationSupported()).thenReturn(Boolean.TRUE);
	when(preferenceManager.getClientPreferences()).thenReturn(mockCapabilies);
	when(mockCapabilies.isWillSaveRegistered()).thenReturn(Boolean.TRUE);
	when(mockCapabilies.isWillSaveWaitUntilRegistered()).thenReturn(Boolean.TRUE);
	InitializeResult result = initialize(true);
	Either<TextDocumentSyncKind, TextDocumentSyncOptions> o = result.getCapabilities().getTextDocumentSync();
	assertTrue(o.isRight());
	assertTrue(o.getRight().getWillSave());
	assertTrue(o.getRight().getWillSaveWaitUntil());
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert IntelliJ {@link DocumentEvent} to LS according {@link TextDocumentSyncKind}.
 *
 * @param event
 *            IntelliJ {@link DocumentEvent}
 * @return true if change event is ready to be sent
 */
private boolean createChangeEvent(DocumentEvent event) {
    changeParams = new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(), Collections.singletonList(new TextDocumentContentChangeEvent()));
    changeParams.getTextDocument().setUri(fileUri.toString());

    Document document = event.getDocument();
    TextDocumentContentChangeEvent changeEvent = null;
    TextDocumentSyncKind syncKind = getTextDocumentSyncKind();
    switch (syncKind) {
        case None:
            return false;
        case Full:
            changeParams.getContentChanges().get(0).setText(event.getDocument().getText());
            break;
        case Incremental:
            changeEvent = changeParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int length = event.getOldLength();
            try {
                // try to convert the Eclipse start/end offset to LS range.
                Range range = new Range(LSPIJUtils.toPosition(offset, document),
                        LSPIJUtils.toPosition(offset + length, document));
                changeEvent.setRange(range);
                changeEvent.setText(newText.toString());
                changeEvent.setRangeLength(length);
            } finally {
            }
            break;
    }
    return true;
}
 
Example #11
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentChange(DocumentEvent event) {
    checkEvent(event);
    if (syncKind == TextDocumentSyncKind.Incremental) {
        // this really needs to happen before event gets actually
        // applied, to properly compute positions
        createChangeEvent(event);
    }
}
 
Example #12
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public DocumentContentSynchronizer(@Nonnull LanguageServerWrapper languageServerWrapper,
                                   @Nonnull Document document,
                                   TextDocumentSyncKind syncKind) {
    this.languageServerWrapper = languageServerWrapper;
    this.fileUri = LSPIJUtils.toUri(document);
    this.modificationStamp = new File(fileUri).lastModified();
    this.syncKind = syncKind != null ? syncKind : TextDocumentSyncKind.Full;

    this.document = document;
    // add a document buffer
    TextDocumentItem textDocument = new TextDocumentItem();
    textDocument.setUri(fileUri.toString());
    textDocument.setText(document.getText());

    List<FileType> contentTypes = LSPIJUtils.getDocumentContentTypes(this.document);

    String languageId = languageServerWrapper.getLanguageId(contentTypes.toArray(new FileType[0]));

    //TODO: determine languageId more precisely
    /*IPath fromPortableString = Path.fromPortableString(this.fileUri.getPath());
    if (languageId == null) {
        languageId = fromPortableString.getFileExtension();
        if (languageId == null) {
            languageId = fromPortableString.lastSegment();
        }
    }*/

    textDocument.setLanguageId(languageId);
    textDocument.setVersion(++version);
    didOpenFuture = languageServerWrapper.getInitializedServer()
            .thenAcceptAsync(ls -> ls.getTextDocumentService().didOpen(new DidOpenTextDocumentParams(textDocument)));
}
 
Example #13
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 #14
Source File: TextDocumentSyncOptions.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full
 * and TextDocumentSyncKind.Incremental.
 */
@Pure
public TextDocumentSyncKind getChange() {
  return this.change;
}
 
Example #15
Source File: TextDocumentChangeRegistrationOptions.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * How documents are synced to the server. See TextDocumentSyncKind.Full
 * and TextDocumentSyncKind.Incremental.
 */
@Pure
@NonNull
public TextDocumentSyncKind getSyncKind() {
  return this.syncKind;
}
 
Example #16
Source File: ServerCapabilities.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Defines how text documents are synced. Is either a detailed structure defining each notification or
 * for backwards compatibility the TextDocumentSyncKind number.
 */
@Pure
public Either<TextDocumentSyncKind, TextDocumentSyncOptions> getTextDocumentSync() {
  return this.textDocumentSync;
}
 
Example #17
Source File: TextDocumentChangeRegistrationOptions.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public TextDocumentChangeRegistrationOptions(@NonNull final TextDocumentSyncKind syncKind) {
  this.syncKind = Preconditions.<TextDocumentSyncKind>checkNotNull(syncKind, "syncKind");
}
 
Example #18
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Configure the server capabilities for this instance.
 *
 * @param params
 *            the initialization parameters
 * @return the server capabilities
 */
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);
	}
	boolean supportsCodeActions = allLanguages.stream()
			.anyMatch((serviceProvider) -> serviceProvider.get(ICodeActionService.class) != null
					|| serviceProvider.get(ICodeActionService2.class) != null);
	if (supportsCodeActions) {
		Optional<List<String>> supportedKinds = getSupportedCodeActionKinds();
		if (supportedKinds.isPresent()) {
			serverCapabilities.setCodeActionProvider(new CodeActionOptions(supportedKinds.get()));
		} else {
			serverCapabilities.setCodeActionProvider(true);
		}
	} else {
		serverCapabilities.setCodeActionProvider(false);
	}

	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(IRenameService.class) != null
						|| serviceProvider.get(IRenameService2.class) != null)));
	}
	WorkspaceClientCapabilities workspace = null;
	if (clientCapabilities != null) {
		workspace = clientCapabilities.getWorkspace();
	}
	ExecuteCommandCapabilities executeCommand = null;
	if (workspace != null) {
		executeCommand = workspace.getExecuteCommand();
	}
	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;
}
 
Example #19
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;
}
 
Example #20
Source File: InitHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void registerCapabilities(InitializeResult initializeResult) {
	ServerCapabilities capabilities = new ServerCapabilities();
	if (!preferenceManager.getClientPreferences().isCompletionDynamicRegistered()) {
		capabilities.setCompletionProvider(CompletionHandler.DEFAULT_COMPLETION_OPTIONS);
	}
	if (!preferenceManager.getClientPreferences().isFormattingDynamicRegistrationSupported()) {
		capabilities.setDocumentFormattingProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isRangeFormattingDynamicRegistrationSupported()) {
		capabilities.setDocumentRangeFormattingProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isOnTypeFormattingDynamicRegistrationSupported()) {
		capabilities.setDocumentOnTypeFormattingProvider(new DocumentOnTypeFormattingOptions(";", Arrays.asList("\n", "}")));
	}
	if (!preferenceManager.getClientPreferences().isCodeLensDynamicRegistrationSupported()) {
		capabilities.setCodeLensProvider(new CodeLensOptions(true));
	}
	if (!preferenceManager.getClientPreferences().isSignatureHelpDynamicRegistrationSupported()) {
		capabilities.setSignatureHelpProvider(SignatureHelpHandler.createOptions());
	}
	if (!preferenceManager.getClientPreferences().isRenameDynamicRegistrationSupported()) {
		capabilities.setRenameProvider(RenameHandler.createOptions());
	}
	if (!preferenceManager.getClientPreferences().isCodeActionDynamicRegistered()) {
		capabilities.setCodeActionProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isExecuteCommandDynamicRegistrationSupported()) {
		Set<String> commands = commandHandler.getAllCommands();
		if (!commands.isEmpty()) {
			capabilities.setExecuteCommandProvider(new ExecuteCommandOptions(new ArrayList<>(commands)));
		}
	} else {
		// Send static command at the startup - they remain registered all the time
		Set<String> staticCommands = commandHandler.getStaticCommands();
		if (!staticCommands.isEmpty()) {
			capabilities.setExecuteCommandProvider(new ExecuteCommandOptions(new ArrayList<>(staticCommands)));
		}
	}
	if (!preferenceManager.getClientPreferences().isWorkspaceSymbolDynamicRegistered()) {
		capabilities.setWorkspaceSymbolProvider(Boolean.TRUE);
	}
	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().isClientHoverProviderRegistered() && !preferenceManager.getClientPreferences().isHoverDynamicRegistered()) {
		capabilities.setHoverProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isReferencesDynamicRegistered()) {
		capabilities.setReferencesProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isDocumentHighlightDynamicRegistered()) {
		capabilities.setDocumentHighlightProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isFoldgingRangeDynamicRegistered()) {
		capabilities.setFoldingRangeProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isImplementationDynamicRegistered()) {
		capabilities.setImplementationProvider(Boolean.TRUE);
	}
	if (!preferenceManager.getClientPreferences().isSelectionRangeDynamicRegistered()) {
		capabilities.setSelectionRangeProvider(Boolean.TRUE);
	}
	capabilities.setCallHierarchyProvider(Boolean.TRUE);
	TextDocumentSyncOptions textDocumentSyncOptions = new TextDocumentSyncOptions();
	textDocumentSyncOptions.setOpenClose(Boolean.TRUE);
	textDocumentSyncOptions.setSave(new SaveOptions(Boolean.TRUE));
	textDocumentSyncOptions.setChange(TextDocumentSyncKind.Incremental);
	if (preferenceManager.getClientPreferences().isWillSaveRegistered()) {
		textDocumentSyncOptions.setWillSave(Boolean.TRUE);
	}

	if (preferenceManager.getClientPreferences().isWillSaveWaitUntilRegistered()) {
		textDocumentSyncOptions.setWillSaveWaitUntil(Boolean.TRUE);
	}
	capabilities.setTextDocumentSync(textDocumentSyncOptions);

	if (preferenceManager.getClientPreferences().isSemanticHighlightingSupported()) {
		SemanticHighlightingServerCapabilities semanticHighlightingCapabilities = new SemanticHighlightingServerCapabilities();
		semanticHighlightingCapabilities.setScopes(SemanticHighlightingService.getAllScopes());
		capabilities.setSemanticHighlighting(semanticHighlightingCapabilities);
	}

	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 #21
Source File: LanguageServerWrapper.java    From lsp4intellij with Apache License 2.0 4 votes vote down vote up
/**
 * Connects an editor to the languageServer
 *
 * @param editor the editor
 */
public void connect(Editor editor) {
    if (editor == null) {
        LOG.warn("editor is null for " + serverDefinition);
        return;
    }
    if (!FileUtils.isEditorSupported(editor)) {
        LOG.debug("Editor hosts a unsupported file type by the LS library.");
        return;
    }

    String uri = editorToURIString(editor);
    uriToLanguageServerWrapper.put(new MutablePair<>(uri, editorToProjectFolderUri(editor)), this);
    if (connectedEditors.containsKey(uri)) {
        return;
    }
    start();
    if (initializeFuture != null) {
        ServerCapabilities capabilities = getServerCapabilities();
        if (capabilities == null) {
            LOG.warn("Capabilities are null for " + serverDefinition);
            return;
        }

        initializeFuture.thenRun(() -> {
            if (connectedEditors.containsKey(uri)) {
                return;
            }
            try {
                Either<TextDocumentSyncKind, TextDocumentSyncOptions> syncOptions = capabilities.getTextDocumentSync();
                if (syncOptions != null) {
                    //Todo - Implement
                    //  SelectionListenerImpl selectionListener = new SelectionListenerImpl();
                    DocumentListenerImpl documentListener = new DocumentListenerImpl();
                    EditorMouseListenerImpl mouseListener = new EditorMouseListenerImpl();
                    EditorMouseMotionListenerImpl mouseMotionListener = new EditorMouseMotionListenerImpl();
                    LSPCaretListenerImpl caretListener = new LSPCaretListenerImpl();

                    ServerOptions serverOptions = new ServerOptions(capabilities);
                    EditorEventManager manager;
                    if (extManager != null) {
                        manager = extManager.getExtendedEditorEventManagerFor(editor, documentListener,
                                mouseListener, mouseMotionListener, caretListener, requestManager, serverOptions,
                                this);
                        if (manager == null) {
                            manager = new EditorEventManager(editor, documentListener, mouseListener,
                                    mouseMotionListener, caretListener,
                                    requestManager, serverOptions, this);
                        }
                    } else {
                        manager = new EditorEventManager(editor, documentListener, mouseListener,
                                mouseMotionListener, caretListener,
                                requestManager, serverOptions, this);
                    }
                    // selectionListener.setManager(manager);
                    documentListener.setManager(manager);
                    mouseListener.setManager(manager);
                    mouseMotionListener.setManager(manager);
                    caretListener.setManager(manager);
                    manager.registerListeners();
                    connectedEditors.put(uri, manager);
                    manager.documentOpened();
                    LOG.info("Created a manager for " + uri);
                    synchronized (toConnect) {
                        toConnect.remove(editor);
                    }
                    for (Editor ed : toConnect) {
                        connect(ed);
                    }
                    // Triggers annotators since this is the first editor which starts the LS
                    // and annotators are executed before LS is bootstrap to provide diagnostics.
                    computableReadAction(() -> {
                        PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
                        if (psiFile != null) {
                            DaemonCodeAnalyzer.getInstance(project).restart(psiFile);
                        }
                        return null;
                    });
                }
            } catch (Exception e) {
                LOG.error(e);
            }
        });

    } else {
        synchronized (toConnect) {
            toConnect.add(editor);
        }
    }
}
 
Example #22
Source File: LanguageServerWrapper.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * To make public when we support non IFiles
 *
 * @return null if not connection has happened, a future that completes when file is initialized otherwise
 * @noreference internal so far
 */
private CompletableFuture<LanguageServer> connect(@Nonnull URI absolutePath, Document document) throws IOException {
    final URI thePath = absolutePath; // should be useless

    VirtualFile file = FileDocumentManager.getInstance().getFile(document);
    if (file != null && file.exists()) {
        watchProject(LSPIJUtils.getProject(file), false);
    }

    if (this.connectedDocuments.containsKey(thePath)) {
        return CompletableFuture.completedFuture(languageServer);
    }
    start();
    if (this.initializeFuture == null) {
        return null;
    }
    if (document == null) {
        VirtualFile docFile = LSPIJUtils.findResourceFor(thePath);
        document = LSPIJUtils.getDocument(docFile);
    }
    if (document == null) {
        return null;
    }
    final Document theDocument = document;
    return initializeFuture.thenComposeAsync(theVoid -> {
        synchronized (connectedDocuments) {
            if (this.connectedDocuments.containsKey(thePath)) {
                return CompletableFuture.completedFuture(null);
            }
            Either<TextDocumentSyncKind, TextDocumentSyncOptions> syncOptions = initializeFuture == null ? null
                    : this.serverCapabilities.getTextDocumentSync();
            TextDocumentSyncKind syncKind = null;
            if (syncOptions != null) {
                if (syncOptions.isRight()) {
                    syncKind = syncOptions.getRight().getChange();
                } else if (syncOptions.isLeft()) {
                    syncKind = syncOptions.getLeft();
                }
            }
            DocumentContentSynchronizer listener = new DocumentContentSynchronizer(this, theDocument, syncKind);
            theDocument.addDocumentListener(listener);
            LanguageServerWrapper.this.connectedDocuments.put(thePath, listener);
            return listener.didOpenFuture;
        }
    }).thenApply(theVoid -> languageServer);
}
 
Example #23
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 4 votes vote down vote up
public void documentChanged(DocumentEvent event) {
    if (editor.isDisposed()) {
        return;
    }
    if (event.getDocument() == editor.getDocument()) {
        //Todo - restore when adding hover support
        // long predTime = System.nanoTime(); //So that there are no hover events while typing
        changesParams.getTextDocument().setVersion(version++);

        if (syncKind == TextDocumentSyncKind.Incremental) {
            TextDocumentContentChangeEvent changeEvent = changesParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int newTextLength = event.getNewLength();
            Position lspPosition = DocumentUtils.offsetToLSPPos(editor, offset);
            int startLine = lspPosition.getLine();
            int startColumn = lspPosition.getCharacter();
            CharSequence oldText = event.getOldFragment();

            //if text was deleted/replaced, calculate the end position of inserted/deleted text
            int endLine, endColumn;
            if (oldText.length() > 0) {
                endLine = startLine + StringUtil.countNewLines(oldText);
                String[] oldLines = oldText.toString().split("\n");
                int oldTextLength = oldLines.length == 0 ? 0 : oldLines[oldLines.length - 1].length();
                endColumn = oldLines.length == 1 ? startColumn + oldTextLength : oldTextLength;
            } else { //if insert or no text change, the end position is the same
                endLine = startLine;
                endColumn = startColumn;
            }
            Range range = new Range(new Position(startLine, startColumn), new Position(endLine, endColumn));
            changeEvent.setRange(range);
            changeEvent.setRangeLength(newTextLength);
            changeEvent.setText(newText.toString());
        } else if (syncKind == TextDocumentSyncKind.Full) {
            changesParams.getContentChanges().get(0).setText(editor.getDocument().getText());
        }
        requestManager.didChange(changesParams);
    } else {
        LOG.error("Wrong document for the EditorEventManager");
    }
}
 
Example #24
Source File: TextDocumentChangeRegistrationOptions.java    From lsp4j with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * How documents are synced to the server. See TextDocumentSyncKind.Full
 * and TextDocumentSyncKind.Incremental.
 */
public void setSyncKind(@NonNull final TextDocumentSyncKind syncKind) {
  this.syncKind = Preconditions.checkNotNull(syncKind, "syncKind");
}
 
Example #25
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns the text document sync kind capabilities of the server and {@link TextDocumentSyncKind#Full} otherwise.
 *
 * @return the text document sync kind capabilities of the server and {@link TextDocumentSyncKind#Full} otherwise.
 */
private TextDocumentSyncKind getTextDocumentSyncKind() {
    return syncKind;
}
 
Example #26
Source File: TextDocumentSyncOptions.java    From lsp4j with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full
 * and TextDocumentSyncKind.Incremental.
 */
public void setChange(final TextDocumentSyncKind change) {
  this.change = change;
}
 
Example #27
Source File: ServerCapabilities.java    From lsp4j with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Defines how text documents are synced. Is either a detailed structure defining each notification or
 * for backwards compatibility the TextDocumentSyncKind number.
 */
public void setTextDocumentSync(final Either<TextDocumentSyncKind, TextDocumentSyncOptions> textDocumentSync) {
  this.textDocumentSync = textDocumentSync;
}