org.eclipse.lsp4j.DocumentFormattingParams Java Examples

The following examples show how to use org.eclipse.lsp4j.DocumentFormattingParams. 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: EditorEventManager.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Reformat the whole document
 */
public void reformat() {
    pool(() -> {
        if (editor.isDisposed()) {
            return;
        }
        DocumentFormattingParams params = new DocumentFormattingParams();
        params.setTextDocument(identifier);
        FormattingOptions options = new FormattingOptions();
        params.setOptions(options);

        CompletableFuture<List<? extends TextEdit>> request = requestManager.formatting(params);
        if (request == null) {
            return;
        }
        request.thenAccept(formatting -> {
            if (formatting != null) {
                invokeLater(() -> applyEdit((List<TextEdit>) formatting, "Reformat document", false));
            }
        });
    });
}
 
Example #2
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected void testFormatting(final Procedure1<? super DocumentFormattingParams> paramsConfigurator, final Procedure1<? super FormattingConfiguration> configurator) {
  try {
    @Extension
    final FormattingConfiguration configuration = new FormattingConfiguration();
    configuration.setFilePath(("MyModel." + this.fileExtension));
    configurator.apply(configuration);
    final FileInfo fileInfo = this.initializeContext(configuration);
    DocumentFormattingParams _documentFormattingParams = new DocumentFormattingParams();
    final Procedure1<DocumentFormattingParams> _function = (DocumentFormattingParams it) -> {
      String _uri = fileInfo.getUri();
      TextDocumentIdentifier _textDocumentIdentifier = new TextDocumentIdentifier(_uri);
      it.setTextDocument(_textDocumentIdentifier);
      if ((paramsConfigurator != null)) {
        paramsConfigurator.apply(it);
      }
    };
    DocumentFormattingParams _doubleArrow = ObjectExtensions.<DocumentFormattingParams>operator_doubleArrow(_documentFormattingParams, _function);
    final CompletableFuture<List<? extends TextEdit>> changes = this.languageServer.formatting(_doubleArrow);
    String _contents = fileInfo.getContents();
    final Document result = new Document(Integer.valueOf(1), _contents).applyChanges(ListExtensions.<TextEdit>reverse(CollectionLiterals.<TextEdit>newArrayList(((TextEdit[])Conversions.unwrapArray(changes.get(), TextEdit.class)))));
    this.assertEqualsStricter(configuration.getExpectedText(), result.getContents());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #3
Source File: Formatter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void documentFormat(FileObject fo, LSPBindings bindings) throws BadLocationException {
    DocumentFormattingParams dfp = new DocumentFormattingParams();
    dfp.setTextDocument(new TextDocumentIdentifier(Utils.toURI(fo)));
    dfp.setOptions(new FormattingOptions(
        IndentUtils.indentLevelSize(ctx.document()),
        IndentUtils.isExpandTabs(ctx.document())));
    List<TextEdit> edits = new ArrayList<>();
    try {
        edits.addAll(bindings.getTextDocumentService().formatting(dfp).get());
    } catch (InterruptedException | ExecutionException ex) {
        LOG.log(Level.INFO,
            String.format("LSP document format failed for {0}", fo),
            ex);
    }

    applyTextEdits(edits);
}
 
Example #4
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testJavaFormatEnable() throws Exception {
	String text =
	//@formatter:off
			"package org.sample   ;\n\n" +
			"      public class Baz {  String name;}\n";
		//@formatter:on"
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text);
	preferenceManager.getPreferences().setJavaFormatEnabled(false);
	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);
	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(text, newText);
}
 
Example #5
Source File: XMLTextDocumentService.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
	return computeAsync((cancelChecker) -> {
		String uri = params.getTextDocument().getUri();
		TextDocument document = getDocument(uri);
		CompositeSettings settings = new CompositeSettings(getSharedSettings(), params.getOptions());
		return getXMLLanguageService().format(document, null, settings);
	});
}
 
Example #6
Source File: FormattingService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
public List<? extends TextEdit> format(Document document, XtextResource resource, DocumentFormattingParams params,
		CancelIndicator cancelIndicator) {
	int offset = 0;
	int length = document.getContents().length();
	if (length == 0 || resource.getContents().isEmpty()) {
		return Collections.emptyList();
	}
	return format(resource, document, offset, length, params.getOptions());
}
 
Example #7
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create the text edits for the formatter. Executed in a read request.
 * @since 2.20
 */
protected List<? extends TextEdit> formatting(DocumentFormattingParams params, CancelIndicator cancelIndicator) {
	URI uri = getURI(params.getTextDocument());
	FormattingService formatterService = getService(uri, FormattingService.class);
	if (formatterService == null) {
		return Collections.emptyList();
	}
	return workspaceManager.doRead(uri,
			(document, resource) -> formatterService.format(document, resource, params, cancelIndicator));
}
 
Example #8
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGoogleFormatterFilePath() throws Exception {
	try {
		String text =
		//@formatter:off
				"package org.sample;\n\n" +
				"public class Baz {\n" +
				"  String name;\n" +
				"}\n";
			//@formatter:on"
		ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text);
		String uri = JDTUtils.toURI(unit);
		TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
		FormattingOptions options = new FormattingOptions(2, true);// ident == 2 spaces
		DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
		Bundle bundle = Platform.getBundle(JavaLanguageServerTestPlugin.PLUGIN_ID);
		URL googleFormatter = bundle.getEntry("/formatter resources/eclipse-java-google-style.xml");
		URL url = FileLocator.resolve(googleFormatter);
		File file = ResourceUtils.toFile(URIUtil.toURI(url));
		preferenceManager.getPreferences().setFormatterUrl(file.getAbsolutePath());
		FormatterManager.configureFormatter(preferenceManager, projectsManager);
		List<? extends TextEdit> edits = server.formatting(params).get();
		assertNotNull(edits);
		String newText = TextEditUtil.apply(unit, edits);
		assertEquals(text, newText);
	} finally {
		preferenceManager.getPreferences().setFormatterUrl(null);
		FormatterManager.configureFormatter(preferenceManager, projectsManager);
	}
}
 
Example #9
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGoogleFormatter() throws Exception {
	try {
		String text =
		//@formatter:off
				"package org.sample;\n\n" +
				"public class Baz {\n" +
				"  String name;\n" +
				"}\n";
			//@formatter:on"
		ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java", text);
		String uri = JDTUtils.toURI(unit);
		TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
		FormattingOptions options = new FormattingOptions(2, true);// ident == 2 spaces
		DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
		Bundle bundle = Platform.getBundle(JavaLanguageServerTestPlugin.PLUGIN_ID);
		URL googleFormatter = bundle.getEntry("/formatter resources/eclipse-java-google-style.xml");
		URL url = FileLocator.resolve(googleFormatter);
		preferenceManager.getPreferences().setFormatterUrl(url.toExternalForm());
		FormatterManager.configureFormatter(preferenceManager, projectsManager);
		List<? extends TextEdit> edits = server.formatting(params).get();
		assertNotNull(edits);
		String newText = TextEditUtil.apply(unit, edits);
		assertEquals(text, newText);
	} finally {
		preferenceManager.getPreferences().setFormatterUrl(null);
		FormatterManager.configureFormatter(preferenceManager, projectsManager);
	}
}
 
Example #10
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDocumentFormattingWithCustomOption() throws Exception {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
		//@formatter:off
		"@Deprecated package org.sample;\n\n" +
			"public class Baz {\n"+
			"    /**Java doc @param a some parameter*/\n"+
			"\tvoid foo(int a){;;\n"+
			"}\n"+
			"}\n"
		//@formatter:on
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(2, true);
	options.putNumber("org.eclipse.jdt.core.formatter.blank_lines_before_package", Integer.valueOf(2));
	options.putString("org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package", "do not insert");
	options.putBoolean("org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line", Boolean.TRUE);
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	preferenceManager.getPreferences().setJavaFormatComments(false);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);

	String expectedText =
		"\n"+
			"\n"+
			"@Deprecated package org.sample;\n"+
			"\n"+
			"public class Baz {\n"+
			"  /**Java doc @param a some parameter*/\n"+
			"  void foo(int a) {\n"+
			"    ;\n"+
			"    ;\n"+
			"  }\n"+
			"}\n";
	String newText = TextEditUtil.apply(unit, edits);
	preferenceManager.getPreferences().setJavaFormatComments(true);
	assertEquals(expectedText, newText);
}
 
Example #11
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testFormatting_onOffTags() throws Exception {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		"package org.sample;\n\n" +
		"      public class Baz {\n"+
		"// @formatter:off\n"+
		"\tvoid foo(){\n"+
		"    }\n"+
		"// @formatter:on\n"+
		"}\n"
	//@formatter:off
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, false);// ident == tab
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);

	//@formatter:off
	String expectedText =
		"package org.sample;\n\n" +
		"public class Baz {\n"+
		"// @formatter:off\n"+
		"\tvoid foo(){\n"+
		"    }\n"+
		"// @formatter:on\n"+
		"}\n";
	//@formatter:on

	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);

}
 
Example #12
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDocumentFormattingWithTabs() throws Exception {
	javaProject.setOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);

	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		"package org.sample;\n\n" +
		"public class Baz {\n"+
		"    void foo(){\n"+
		"}\n"+
		"}\n"
	//@formatter:on
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(2, false);// ident == tab
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);

	//@formatter:off
	String expectedText =
		"package org.sample;\n"+
		"\n"+
		"public class Baz {\n"+
		"\tvoid foo() {\n"+
		"\t}\n"+
		"}\n";
	//@formatter:on
	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);
}
 
Example #13
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDocumentFormatting() throws Exception {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		"package org.sample   ;\n\n" +
		"      public class Baz {  String name;}\n"
	//@formatter:on
	);

	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);

	//@formatter:off
	String expectedText =
		"package org.sample;\n"
		+ "\n"
		+ "public class Baz {\n"
		+ "    String name;\n"
		+ "}\n";
	//@formatter:on

	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);
}
 
Example #14
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create the text edits for the formatter. Executed in a read request.
 */
protected List<? extends TextEdit> formatting(OpenFileContext ofc, DocumentFormattingParams params,
		CancelIndicator cancelIndicator) {
	URI uri = ofc.getURI();
	FormattingService formatterService = getService(uri, FormattingService.class);
	if ((formatterService == null)) {
		return Collections.emptyList();
	}
	XtextResource res = ofc.getResource();
	XDocument doc = ofc.getDocument();
	return formatterService.format(doc, res, params, cancelIndicator);
}
 
Example #15
Source File: XLanguageServerImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
	URI uri = getURI(params.getTextDocument());
	return openFilesManager.runInOpenFileContext(uri, "formatting", (ofc, ci) -> {
		return formatting(ofc, params, ci);
	});
}
 
Example #16
Source File: JDTLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
	logInfo(">> document/formatting");
	FormatterHandler handler = new FormatterHandler(preferenceManager);
	return computeAsync((monitor) -> handler.formatting(params, monitor));
}
 
Example #17
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testFormatting_indent_switchstatementsDefault() throws Exception {
	ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
	//@formatter:off
		"package org.sample;\n" +
		"\n" +
		"public class Baz {\n" +
		"    private enum Numbers {One, Two};\n" +
		"    public void foo() {\n" +
		"        Numbers n = Numbers.One;\n" +
		"        switch (n) {\n" +
		"        case One:\n" +
		"        return;\n" +
		"        case Two:\n" +
		"        return;\n" +
		"        default:\n" +
		"        break;\n" +
		"        }\n" +
		"    }\n" +
		"}"
	//@formatter:off
	);
	String uri = JDTUtils.toURI(unit);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
	FormattingOptions options = new FormattingOptions(4, true);
	DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
	List<? extends TextEdit> edits = server.formatting(params).get();
	assertNotNull(edits);
	//@formatter:off
	String expectedText =
		"package org.sample;\n" +
		"\n" +
		"public class Baz {\n" +
		"    private enum Numbers {\n" +
		"        One, Two\n" +
		"    };\n" +
		"\n" +
		"    public void foo() {\n" +
		"        Numbers n = Numbers.One;\n" +
		"        switch (n) {\n" +
		"            case One:\n" +
		"                return;\n" +
		"            case Two:\n" +
		"                return;\n" +
		"            default:\n" +
		"                break;\n" +
		"        }\n" +
		"    }\n" +
		"}";
	//@formatter:on
	String newText = TextEditUtil.apply(unit, edits);
	assertEquals(expectedText, newText);
}
 
Example #18
Source File: FormatterHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testFormatting_indent_switchstatementsFalse() throws Exception {
	String original = javaProject.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, true);
	try {
		javaProject.setOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, DefaultCodeFormatterConstants.FALSE);
		ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
		//@formatter:off
			"package org.sample;\n" +
			"\n" +
			"public class Baz {\n" +
			"    private enum Numbers {One, Two};\n" +
			"    public void foo() {\n" +
			"        Numbers n = Numbers.One;\n" +
			"        switch (n) {\n" +
			"        case One:\n" +
			"        return;\n" +
			"        case Two:\n" +
			"        return;\n" +
			"        default:\n" +
			"        break;\n" +
			"        }\n" +
			"    }\n" +
			"}"
		//@formatter:off
		);
		String uri = JDTUtils.toURI(unit);
		TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
		FormattingOptions options = new FormattingOptions(4, true);
		DocumentFormattingParams params = new DocumentFormattingParams(textDocument, options);
		List<? extends TextEdit> edits = server.formatting(params).get();
		assertNotNull(edits);
		//@formatter:off
		String expectedText =
			"package org.sample;\n" +
			"\n" +
			"public class Baz {\n" +
			"    private enum Numbers {\n" +
			"        One, Two\n" +
			"    };\n" +
			"\n" +
			"    public void foo() {\n" +
			"        Numbers n = Numbers.One;\n" +
			"        switch (n) {\n" +
			"        case One:\n" +
			"            return;\n" +
			"        case Two:\n" +
			"            return;\n" +
			"        default:\n" +
			"            break;\n" +
			"        }\n" +
			"    }\n" +
			"}";
		//@formatter:on
		String newText = TextEditUtil.apply(unit, edits);
		assertEquals(expectedText, newText);
	} finally {
		javaProject.setOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, original);
	}
}
 
Example #19
Source File: FormatterHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
List<? extends org.eclipse.lsp4j.TextEdit> formatting(DocumentFormattingParams params, IProgressMonitor monitor) {
	return format(params.getTextDocument().getUri(), params.getOptions(), (Range) null, monitor);
}
 
Example #20
Source File: TeiidDdlTextDocumentService.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
    LOGGER.debug("formatting: {}", params.getTextDocument());
    return CompletableFuture.completedFuture(Collections.emptyList());
}
 
Example #21
Source File: TextDocumentServiceImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams arg0) {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example #22
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 4 votes vote down vote up
/**
 * This feature is not implemented at this time.
 */
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params)
{
    return CompletableFuture.completedFuture(Collections.emptyList());
}
 
Example #23
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
	return requestManager.runRead((cancelIndicator) -> formatting(params, cancelIndicator));
}
 
Example #24
Source File: CamelTextDocumentService.java    From camel-language-server with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
	LOGGER.info("formatting: {}", params.getTextDocument());
	return CompletableFuture.completedFuture(Collections.emptyList());
}
 
Example #25
Source File: TextDocumentService.java    From lsp4j with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * The document formatting request is sent from the client to the server to
 * format a whole document.
 * 
 * Registration Options: TextDocumentRegistrationOptions
 */
@JsonRequest
default CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
	throw new UnsupportedOperationException();
}