下面列出了怎么用org.eclipse.lsp4j.DocumentFormattingParams的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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));
}
});
});
}
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);
}
@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);
}
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);
}
}
@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);
});
}
@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);
});
}
/**
* 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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
}
@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);
}
}
/**
* 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));
}
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());
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
LOGGER.info("formatting: {}", params.getTextDocument());
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
LOGGER.debug("formatting: {}", params.getTextDocument());
return CompletableFuture.completedFuture(Collections.emptyList());
}
List<? extends org.eclipse.lsp4j.TextEdit> formatting(DocumentFormattingParams params, IProgressMonitor monitor) {
return format(params.getTextDocument().getUri(), params.getOptions(), (Range) null, monitor);
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
logInfo(">> document/formatting");
FormatterHandler handler = new FormatterHandler(preferenceManager);
return computeAsync((monitor) -> handler.formatting(params, monitor));
}
@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);
}
@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);
}
}
/**
* This feature is not implemented at this time.
*/
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params)
{
return CompletableFuture.completedFuture(Collections.emptyList());
}
@Override
public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) {
return requestManager.runRead((cancelIndicator) -> formatting(params, cancelIndicator));
}
/**
* 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();
}