下面列出了怎么用org.eclipse.lsp4j.FormattingOptions的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));
}
});
});
}
@Test
public void formatSettings() {
// formatting options coming from request
FormattingOptions formattingOptions = new FormattingOptions();
formattingOptions.setTabSize(5);
formattingOptions.setInsertSpaces(false);
XMLFormattingOptions xmlFormattingOptions = new XMLFormattingOptions(formattingOptions, false);
assertEquals(5, xmlFormattingOptions.getTabSize()); // value coming from the request formattingOptions
assertFalse(xmlFormattingOptions.isInsertSpaces()); // formattingOptions doesn't defines insert spaces
assertFalse(xmlFormattingOptions.isJoinCommentLines());// Since default for JoinCommentLines is False
XMLFormattingOptions sharedXMLFormattingOptions = new XMLFormattingOptions(true);
sharedXMLFormattingOptions.setTabSize(10);
sharedXMLFormattingOptions.setInsertSpaces(true);
sharedXMLFormattingOptions.setJoinCommentLines(true);
// merge with shared sharedXMLFormattingOptions (formatting settings created in
// the InitializeParams
xmlFormattingOptions.merge(sharedXMLFormattingOptions);
assertEquals(10, xmlFormattingOptions.getTabSize());
assertTrue(xmlFormattingOptions.isInsertSpaces());
assertTrue(xmlFormattingOptions.isJoinCommentLines());
}
private void rangeFormat(FileObject fo, LSPBindings bindings) throws BadLocationException {
DocumentRangeFormattingParams drfp = new DocumentRangeFormattingParams();
drfp.setTextDocument(new TextDocumentIdentifier(Utils.toURI(fo)));
drfp.setOptions(new FormattingOptions(
IndentUtils.indentLevelSize(ctx.document()),
IndentUtils.isExpandTabs(ctx.document())));
drfp.setRange(new Range(
Utils.createPosition(ctx.document(), ctx.startOffset()),
Utils.createPosition(ctx.document(), ctx.endOffset())));
List<TextEdit> edits = new ArrayList<>();
try {
edits = new ArrayList<>(bindings.getTextDocumentService().rangeFormatting(drfp).get());
} catch (InterruptedException | ExecutionException ex) {
LOG.log(Level.INFO,
String.format("LSP document rangeFormat failed for {0}", fo),
ex);
}
applyTextEdits(edits);
}
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);
}
private List<org.eclipse.lsp4j.TextEdit> format(String uri, FormattingOptions options, Range range, IProgressMonitor monitor) {
if (!preferenceManager.getPreferences().isJavaFormatEnabled()) {
return Collections.emptyList();
}
ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
if (cu == null) {
return Collections.emptyList();
}
IRegion region = null;
IDocument document = null;
try {
document = JsonRpcHelpers.toDocument(cu.getBuffer());
if (document != null) {
region = (range == null ? new Region(0, document.getLength()) : getRegion(range, document));
}
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
}
if (region == null) {
return Collections.emptyList();
}
return format(cu, document, region, options, preferenceManager.getPreferences().isJavaFormatComments(), monitor);
}
public static Map<String, String> getOptions(FormattingOptions options, ICompilationUnit cu) {
Map<String, String> eclipseOptions = cu.getJavaProject().getOptions(true);
Map<String, String> customOptions = options.entrySet().stream().filter(map -> chekIfValueIsNotNull(map.getValue())).collect(toMap(e -> e.getKey(), e -> getOptionValue(e.getValue())));
eclipseOptions.putAll(customOptions);
Integer tabSize = options.getTabSize();
if (tabSize != null) {
int tSize = tabSize.intValue();
if (tSize > 0) {
eclipseOptions.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, Integer.toString(tSize));
}
}
boolean insertSpaces = options.isInsertSpaces();
eclipseOptions.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, insertSpaces ? JavaCore.SPACE : JavaCore.TAB);
return eclipseOptions;
}
private List<? extends org.eclipse.lsp4j.TextEdit> format(String uri, FormattingOptions options, Position position, String triggerChar, IProgressMonitor monitor) {
if (!preferenceManager.getPreferences().isJavaFormatOnTypeEnabled()) {
return Collections.emptyList();
}
ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
if (cu == null) {
return Collections.emptyList();
}
IRegion region = null;
IDocument document = null;
try {
document = JsonRpcHelpers.toDocument(cu.getBuffer());
if (document != null && position != null) {
region = getRegion(cu, document, position, triggerChar);
}
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException(e.getMessage(), e);
}
if (region == null) {
return Collections.emptyList();
}
return format(cu, document, region, options, false, monitor);
}
@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);
}
@Test
public void testDisableFormattingOnType() throws Exception {
//@formatter:off
String text = "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(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 28), "\n");
params.setTextDocument(textDocument);
params.setOptions(options);
//Check it's disabled by default
List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
assertNotNull(edits);
String newText = TextEditUtil.apply(unit, edits);
assertEquals(text, newText);
}
/**
* @since 2.14
*/
public List<TextEdit> format(XtextResource resource, Document document, int offset, int length,
FormattingOptions options) {
String indent = indentationInformation.getIndentString();
if (options != null) {
if (options.isInsertSpaces()) {
indent = Strings.padEnd("", options.getTabSize(), ' ');
}
}
List<TextEdit> result = new ArrayList<>();
if (this.formatter2Provider != null) {
MapBasedPreferenceValues preferences = new MapBasedPreferenceValues();
preferences.put("indentation", indent);
List<ITextReplacement> replacements = format2(resource, new TextRegion(offset, length), preferences);
for (ITextReplacement r : replacements) {
result.add(toTextEdit(document, r.getReplacementText(), r.getOffset(), r.getLength()));
}
}
return result;
}
/**
* Reformat the text currently selected in the editor
*/
public void reformatSelection() {
pool(() -> {
if (editor.isDisposed()) {
return;
}
DocumentRangeFormattingParams params = new DocumentRangeFormattingParams();
params.setTextDocument(identifier);
SelectionModel selectionModel = editor.getSelectionModel();
int start = computableReadAction(selectionModel::getSelectionStart);
int end = computableReadAction(selectionModel::getSelectionEnd);
Position startingPos = DocumentUtils.offsetToLSPPos(editor, start);
Position endPos = DocumentUtils.offsetToLSPPos(editor, end);
params.setRange(new Range(startingPos, endPos));
// Todo - Make Formatting Options configurable
FormattingOptions options = new FormattingOptions();
params.setOptions(options);
CompletableFuture<List<? extends TextEdit>> request = requestManager.rangeFormatting(params);
if (request == null) {
return;
}
request.thenAccept(formatting -> {
if (formatting == null) {
return;
}
invokeLater(() -> {
if (!editor.isDisposed()) {
applyEdit((List<TextEdit>) formatting, "Reformat selection", false);
}
});
});
});
}
@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 testRangeFormatting() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n" +
" public class Baz {\n"+
"\tvoid foo(){\n" +
" }\n"+
" }\n"
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
Range range = new Range(new Position(2, 0), new Position(3, 5));// range around foo()
DocumentRangeFormattingParams params = new DocumentRangeFormattingParams(range);
params.setTextDocument(textDocument);
params.setOptions(new FormattingOptions(3, true));// ident == 3 spaces
List<? extends TextEdit> edits = server.rangeFormatting(params).get();
//@formatter:off
String expectedText =
"package org.sample;\n" +
" public class Baz {\n"+
" void foo() {\n" +
" }\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);
}
}
@Test // typing ; should format the current line
public void testFormattingOnTypeSemiColumn() 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"
+ "String name ;\n"//typed ; here
+ "}\n"
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, false);// ident == tab
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 27), ";");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
assertNotNull(edits);
//@formatter:off
String expectedText =
"package org.sample;\n"
+ "\n"
+ "public class Baz { \n"
+ "\tString name;\n"
+ "}\n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
@Test // typing new_line should format the current line if previous character doesn't close a block
public void testFormattingOnTypeNewLine() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"
+ "String name ;\n"//typed \n here
+ "}\n"
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(3, 28), "\n");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
assertNotNull(edits);
//@formatter:off
String expectedText =
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"//this part won't be formatted
+ " String name;\n"
+ "}\n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
@Test // typing } should format the previous block
public void testFormattingOnTypeCloseBlock() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"
+ "String name ;\n"
+ "} "//typed } here
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(4, 0), "}");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
assertNotNull(edits);
//@formatter:off
String expectedText =
"package org.sample;\n"
+ "\n"
+ "public class Baz {\n"
+ " String name;\n"
+ "}";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
@Test // typing new_line after opening a block should only format the current line
public void testFormattingOnTypeReturnAfterOpeningBlock() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"//typed \n here
+ "String name ;\n"
+ "} \n"
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(2, 33), "\n");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(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 // typing new_line after closing a block should format the that block
public void testFormattingOnTypeReturnAfterClosedBlock() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"
+ "String name ;\n"
+ "} \n"//typed \n here
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(4, 3), "\n");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(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 // typing new_line after inserting a new line should format the previous block if previous non-whitespace char is }
public void testFormattingOnTypeReturnAfterEmptyLine() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz { \n"
+ "String name ;\n"
+ "} \n"
+ " \n"//typed \n here
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(5, 3), "\n");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
assertNotNull(edits);
//@formatter:off
String expectedText =
"package org.sample;\n"
+ "\n"
+ "public class Baz {\n"
+ " String name;\n"
+ "}\n"
+ " \n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
@Test // typing new_line after an empty block on a single line should format that block
public void testFormattingOnTypeReturnAfterEmptyBlock() throws Exception {
ICompilationUnit unit = getWorkingCopy("src/org/sample/Baz.java",
//@formatter:off
"package org.sample;\n"
+ "\n"
+ " public class Baz {} \n"//typed \n here
//@formatter:on
);
String uri = JDTUtils.toURI(unit);
TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uri);
FormattingOptions options = new FormattingOptions(4, true);// ident == 4 spaces
DocumentOnTypeFormattingParams params = new DocumentOnTypeFormattingParams(new Position(2, 34), "\n");
params.setTextDocument(textDocument);
params.setOptions(options);
preferenceManager.getPreferences().setJavaFormatOnTypeEnabled(true);
List<? extends TextEdit> edits = server.onTypeFormatting(params).get();
assertNotNull(edits);
//@formatter:off
String expectedText =
"package org.sample;\n"
+ "\n"
+ "public class Baz {\n"
+ "}\n";
//@formatter:on
String newText = TextEditUtil.apply(unit, edits);
assertEquals(expectedText, newText);
}
public CompositeSettings(SharedSettings settings, FormattingOptions formatting) {
super(settings);
this.getFormattingSettings().merge(formatting);
}
public XMLFormattingOptions(FormattingOptions options, boolean initializeDefaultSettings) {
if (initializeDefaultSettings) {
initializeDefaultSettings();
}
merge(options);
}
public XMLFormattingOptions(FormattingOptions options) {
this(options, true);
}
public XMLFormattingOptions merge(FormattingOptions formattingOptions) {
formattingOptions.entrySet().stream().forEach(entry -> {
this.put(entry.getKey(), entry.getValue());
});
return this;
}
public static XMLFormattingOptions create(FormattingOptions options, FormattingOptions sharedFormattingOptions) {
return new XMLFormattingOptions(options).merge(sharedFormattingOptions);
}