diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Notifications.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Notifications.java
index 3f9e12a1f..8a0a11271 100644
--- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Notifications.java
+++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Notifications.java
@@ -27,6 +27,10 @@ static String parsingErrorMessage(String filename) {
return "open-java-format failed. Does " + filename + " have syntax errors?";
}
+ static String untrustedProjectMessage() {
+ return "open-java-format requires a trusted project to run its formatter.";
+ }
+
static String formatterFailedMessage(String filename) {
return "open-java-format could not run the formatter on " + filename + ". The details are in idea.log.";
}
diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatCodeStyleSettingsModifier.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatCodeStyleSettingsModifier.java
new file mode 100644
index 000000000..f27e7c9b7
--- /dev/null
+++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatCodeStyleSettingsModifier.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.palantir.javaformat.intellij;
+
+import com.intellij.ide.highlighter.JavaFileType;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.codeStyle.CodeStyleSettings;
+import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
+import com.intellij.psi.codeStyle.PackageEntry;
+import com.intellij.psi.codeStyle.PackageEntryTable;
+import com.intellij.psi.codeStyle.modifier.CodeStyleSettingsModifier;
+import com.intellij.psi.codeStyle.modifier.CodeStyleStatusBarUIContributor;
+import com.intellij.psi.codeStyle.modifier.TransientCodeStyleSettings;
+import java.util.function.Consumer;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * Gives the Java files the plugin formats the import settings that open-java-format writes by. The IDE inserts imports
+ * through auto-import, Alt+Enter and completion by these settings, and no import optimizer sees them: with the IDE's
+ * defaults, five classes from one package become {@code import java.util.*;}, which open-java-format keeps.
+ *
+ *
The platform applies only the first modifier that changes a file's settings, and EditorConfig's is registered
+ * first: in a project whose {@code .editorconfig} sets code style properties for Java files, these settings do not
+ * apply, and its {@code ij_java_*} properties can set them there instead.
+ */
+final class PalantirJavaFormatCodeStyleSettingsModifier implements CodeStyleSettingsModifier {
+ // More names than a file imports from one package, so that an import on demand is never written.
+ private static final int NEVER_IMPORT_ON_DEMAND = 999;
+
+ @Override
+ public boolean modifySettings(TransientCodeStyleSettings settings, PsiFile file) {
+ if (!JavaFileType.INSTANCE.equals(file.getFileType())
+ || !PalantirJavaFormatSettings.getInstance(file.getProject()).isEnabled()) {
+ return false;
+ }
+ var javaSettings = settings.getCustomSettings(JavaCodeStyleSettings.class);
+ javaSettings.USE_SINGLE_CLASS_IMPORTS = true;
+ javaSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND = NEVER_IMPORT_ON_DEMAND;
+ javaSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND = NEVER_IMPORT_ON_DEMAND;
+ javaSettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.copyFrom(new PackageEntryTable());
+ // Static imports, a blank line, then the others, each group in the order of its names: ImportOrderer's.
+ javaSettings.LAYOUT_STATIC_IMPORTS_SEPARATELY = true;
+ var importLayout = new PackageEntryTable();
+ importLayout.addEntry(PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY);
+ importLayout.addEntry(PackageEntry.BLANK_LINE_ENTRY);
+ importLayout.addEntry(PackageEntry.ALL_OTHER_IMPORTS_ENTRY);
+ javaSettings.IMPORT_LAYOUT_TABLE.copyFrom(importLayout);
+ return true;
+ }
+
+ // The Code Style page then says that its settings may be overridden by open-java-format.
+ @Override
+ public boolean mayOverrideSettingsOf(Project project) {
+ return PalantirJavaFormatSettings.getInstance(project).isEnabled();
+ }
+
+ @Override
+ public String getName() {
+ return "open-java-format";
+ }
+
+ @Override
+ @Nullable
+ public CodeStyleStatusBarUIContributor getStatusBarUiContributor(TransientCodeStyleSettings transientSettings) {
+ return null;
+ }
+
+ // What the Disable link next to that message runs: these settings come with the plugin, so it switches the plugin
+ // off for the project, as unticking it on the plugin's settings page does.
+ @Override
+ public Consumer getDisablingFunction(Project project) {
+ return settings -> PalantirJavaFormatSettings.getInstance(project)
+ .setEnabled(PalantirJavaFormatSettings.disabledState(project));
+ }
+}
diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java
index 0b5dc9d97..431cc0591 100644
--- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java
+++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurable.java
@@ -25,6 +25,7 @@
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Disposer;
+import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.components.ActionLink;
import com.intellij.ui.components.JBTextArea;
@@ -174,16 +175,16 @@ public void apply() throws ConfigurationException {
throw new ConfigurationException("Download the embedded version or choose a binary");
}
}
- settings.setEnabled(enable.isSelected() ? EnabledState.ENABLED : getDisabledState());
+ var wasEnabled = settings.isEnabled();
+ settings.setEnabled(
+ enable.isSelected() ? EnabledState.ENABLED : PalantirJavaFormatSettings.disabledState(project));
settings.setUseNativeImage(useNativeImage.isSelected());
settings.setNativeImagePath(path);
- }
-
- private EnabledState getDisabledState() {
- // The default settings (inherited by new projects) are either 'enabled' or
- // 'show notification'. There's no way to default new projects to disabled. If someone wants
- // that, we can add another checkbox, I suppose.
- return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED;
+ if (settings.isEnabled() != wasEnabled) {
+ // The Java import settings of each file are cached, and PalantirJavaFormatCodeStyleSettingsModifier sets
+ // them while the plugin is enabled.
+ CodeStyleSettingsManager.getInstance(project).notifyCodeStyleSettingsChanged();
+ }
}
@Override
diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java
index ccb1c5a8d..e503e6f22 100644
--- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java
+++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java
@@ -24,13 +24,20 @@
import com.intellij.formatting.service.AsyncFormattingRequest;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.ide.impl.TrustedProjects;
+import com.intellij.lang.ImportOptimizer;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.event.DocumentEvent;
+import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.extensions.PluginAware;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Disposer;
+import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.TextRange;
+import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.palantir.javaformat.java.FormatterException;
import com.palantir.javaformat.java.FormatterService;
@@ -40,12 +47,14 @@
import java.util.List;
import java.util.Optional;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
import org.jspecify.annotations.Nullable;
class PalantirJavaFormatFormattingService extends AsyncDocumentFormattingService implements PluginAware {
private static final Logger logger = Logger.getInstance(PalantirJavaFormatFormattingService.class);
private final FormatterProvider formatterProvider =
new FormatterProvider(() -> EmbeddedNativeImage.getInstance().installedPath());
+ private final ImportOptimizer importOptimizer = new PalantirJavaFormatImportOptimizer(this);
// The platform sets this right after creating the service from plugin.xml: the descriptor of the plugin that
// declared it, which is how the plugin learns its own path and version (see FormatterProvider.getPluginDescriptor).
@@ -66,19 +75,27 @@ Optional getPluginDescriptor() {
@Nullable
protected FormattingTask createFormattingTask(AsyncFormattingRequest request) {
Project project = request.getContext().getProject();
- // The marketplace verifier reports this class as experimental, and newer IDEs also deprecate it. It stays:
- // its replacement, com.intellij.ide.trustedProjects.TrustedProjects, is @ApiStatus.Internal — a worse thing
- // for a plugin to call.
- if (!TrustedProjects.isTrusted(project)) {
+ if (!isTrusted(project)) {
logger.warn("open-java-format: skipping formatting for untrusted project: " + project.getName());
- request.onError(
- Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
- "open-java-format requires a trusted project to load the external formatter classpath.");
+ request.onError(Notifications.GENERIC_ERROR_NOTIFICATION_GROUP, Notifications.untrustedProjectMessage());
return null;
}
- PalantirJavaFormatSettings settings = PalantirJavaFormatSettings.getInstance(project);
- Optional formatter = formatterProvider.get(project, settings);
- return new PalantirJavaFormatFormattingTask(request, formatter);
+ PendingFormat pendingFormat = PendingFormat.start(
+ project,
+ PsiDocumentManager.getInstance(project)
+ .getDocument(request.getContext().getContainingFile()));
+ return new PalantirJavaFormatFormattingTask(request, getFormatter(project), pendingFormat);
+ }
+
+ static boolean isTrusted(Project project) {
+ // TrustedProjects.isTrusted is @ApiStatus.Experimental, and deprecated since 2025.1. Its replacement,
+ // com.intellij.ide.trustedProjects.TrustedProjects.isProjectTrusted, is public only from 2025.1, and this
+ // plugin still supports 2024.2: switch to it when sinceBuild reaches 251.
+ return TrustedProjects.isTrusted(project);
+ }
+
+ Optional getFormatter(Project project) {
+ return formatterProvider.get(project, PalantirJavaFormatSettings.getInstance(project));
}
@Override
@@ -91,9 +108,17 @@ protected String getNotificationGroupId() {
return "open-java-format";
}
+ // OPTIMIZE_IMPORTS: every way the IDE optimizes imports asks the first formatting service that has this feature and
+ // can format the file for its optimizers (FormattingServiceUtil.findImportsOptimizingService), and so takes ours
+ // instead of its own JavaImportOptimizer.
@Override
public Set getFeatures() {
- return Set.of(Feature.FORMAT_FRAGMENTS);
+ return Set.of(Feature.FORMAT_FRAGMENTS, Feature.OPTIMIZE_IMPORTS);
+ }
+
+ @Override
+ public Set getImportOptimizers(PsiFile file) {
+ return Set.of(importOptimizer);
}
@Override
@@ -102,22 +127,120 @@ public boolean canFormat(PsiFile file) {
&& PalantirJavaFormatSettings.getInstance(file.getProject()).isEnabled();
}
+ /**
+ * A formatting request of this service whose text is not in its document yet, kept on the document.
+ *
+ * The formatter runs in the background, and the platform applies its text later, only if the document has not
+ * changed since the request started: IntelliJ IDEA registers no {@code DocumentMerger} to do anything else.
+ * Reformat with "Optimize imports" starts the formatter and the import optimizer on the same document without
+ * waiting for the first, so whichever wrote second would lose: the formatted text, or the imports. While a request
+ * is formatting, the optimizer hands its work over to it, and the request fixes the imports of the text it
+ * formatted, as the command line does. Once the request has its text, the optimizer leaves the document alone
+ * until the text is applied.
+ */
+ static final class PendingFormat {
+ private static final Key KEY = Key.create("open-java-format.pendingFormat");
+
+ private enum State {
+ FORMATTING,
+ FORMATTING_AND_FIXING_IMPORTS,
+ // Until the document next changes: with the text, or with an edit that makes the platform drop it.
+ UNAPPLIED,
+ DONE
+ }
+
+ private final AtomicReference state = new AtomicReference<>(State.FORMATTING);
+ private final Project project;
+
+ @Nullable
+ private final Document document;
+
+ private PendingFormat(Project project, @Nullable Document document) {
+ this.project = project;
+ this.document = document;
+ }
+
+ static PendingFormat start(Project project, @Nullable Document document) {
+ var pendingFormat = new PendingFormat(project, document);
+ if (document != null) {
+ document.putUserData(KEY, pendingFormat);
+ }
+ return pendingFormat;
+ }
+
+ @Nullable
+ static PendingFormat of(Document document) {
+ return document.getUserData(KEY);
+ }
+
+ /** Asks the request to fix the imports too: false if it has finished formatting already. */
+ boolean handOverImports() {
+ return state.compareAndSet(State.FORMATTING, State.FORMATTING_AND_FIXING_IMPORTS);
+ }
+
+ boolean isUnapplied() {
+ return state.get() == State.UNAPPLIED;
+ }
+
+ /** Ends the formatting, and says whether the imports were handed over meanwhile. */
+ private boolean finishFormatting() {
+ return state.getAndSet(State.UNAPPLIED) == State.FORMATTING_AND_FIXING_IMPORTS;
+ }
+
+ private void finish(boolean changesDocument) {
+ if (!changesDocument || document == null) {
+ state.set(State.DONE);
+ return;
+ }
+ var untilChanged = Disposer.newDisposable("open-java-format: until the formatted text is applied");
+ if (!Disposer.tryRegister(project, untilChanged)) {
+ state.set(State.DONE);
+ return;
+ }
+ // Registered before the platform applies the text, which it does only once the task has returned.
+ document.addDocumentListener(
+ new DocumentListener() {
+ @Override
+ public void documentChanged(DocumentEvent event) {
+ state.set(State.DONE);
+ Disposer.dispose(untilChanged);
+ }
+ },
+ untilChanged);
+ }
+ }
+
private static final class PalantirJavaFormatFormattingTask implements FormattingTask {
private final AsyncFormattingRequest request;
private final Optional formatterService;
+ private final PendingFormat pendingFormat;
- PalantirJavaFormatFormattingTask(AsyncFormattingRequest request, Optional formatterService) {
+ PalantirJavaFormatFormattingTask(
+ AsyncFormattingRequest request,
+ Optional formatterService,
+ PendingFormat pendingFormat) {
this.request = request;
this.formatterService = formatterService;
+ this.pendingFormat = pendingFormat;
}
@Override
public void run() {
+ var changesDocument = false;
+ try {
+ changesDocument = format();
+ } finally {
+ pendingFormat.finish(changesDocument);
+ }
+ }
+
+ /** Formats, and says whether the text it gave back changes the document. */
+ private boolean format() {
if (formatterService.isEmpty()) {
request.onError(
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
"Failed to format file because formatterService is not configured");
- return;
+ return false;
}
String preFormatText = request.getDocumentText();
@@ -138,14 +261,18 @@ public void run() {
// returns a change. Thus we must perform a content aware diff / branching.
String formattedText = applyReplacements(
preFormatText, formatterService.get().getFormatReplacements(preFormatText, toRanges(request)));
+ if (pendingFormat.finishFormatting()) {
+ formattedText = formatterService.get().fixImports(formattedText);
+ }
// The Javadoc of this API says that you should set it to null when the document is unchanged
// We should not be trying to format a document that is already formatted
if (preFormatText.equals(formattedText)) {
request.onTextReady(null);
- } else {
- request.onTextReady(formattedText);
+ return false;
}
+ request.onTextReady(formattedText);
+ return true;
} catch (FormatterException e) {
// A syntax error in the file, not a fault of the plugin: an error would go to its error reports.
logger.warn(
@@ -169,6 +296,7 @@ public void run() {
Notifications.formatterFailedMessage(
request.getContext().getContainingFile().getName()));
}
+ return false;
}
static String applyReplacements(String input, Collection replacementsCollection) {
diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java
new file mode 100644
index 000000000..a2d468a79
--- /dev/null
+++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizer.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.palantir.javaformat.intellij;
+
+import com.intellij.formatting.service.FormattingNotificationService;
+import com.intellij.lang.ImportOptimizer;
+import com.intellij.lang.ImportOptimizer.CollectingInfoRunnable;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.progress.ProcessCanceledException;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.EmptyRunnable;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiFile;
+import com.palantir.javaformat.intellij.PalantirJavaFormatFormattingService.PendingFormat;
+import com.palantir.javaformat.java.FormatterException;
+
+/**
+ * Optimizes imports as the command line fixes them, with {@code FormatterService.fixImports}: the unused ones removed,
+ * the others sorted. The IDE takes it instead of its own {@code JavaImportOptimizer} for every way of optimizing
+ * imports, since {@link PalantirJavaFormatFormattingService} has {@code OPTIMIZE_IMPORTS}.
+ */
+final class PalantirJavaFormatImportOptimizer implements ImportOptimizer {
+ private static final Logger logger = Logger.getInstance(PalantirJavaFormatImportOptimizer.class);
+
+ // Changes nothing. An explicit Optimize Imports shows the message in its hint, instead of "No unused imports
+ // found"; on the fly nothing shows it.
+ private static final CollectingInfoRunnable UNTRUSTED_PROJECT = new CollectingInfoRunnable() {
+ @Override
+ public void run() {}
+
+ @Override
+ public String getUserNotificationInfo() {
+ return Notifications.untrustedProjectMessage();
+ }
+ };
+
+ private final PalantirJavaFormatFormattingService formattingService;
+
+ PalantirJavaFormatImportOptimizer(PalantirJavaFormatFormattingService formattingService) {
+ this.formattingService = formattingService;
+ }
+
+ @Override
+ public boolean supports(PsiFile file) {
+ return formattingService.canFormat(file);
+ }
+
+ // Called under a read action, in the background on most paths; the Runnable runs on the EDT under a write action.
+ // So the formatter runs here, and the Runnable only writes its text. EmptyRunnable tells the IDE that nothing
+ // changed. The formatter does not check for cancellation, so a write action waits for it: with "Optimize imports
+ // on the fly", typing waits (#253).
+ @Override
+ public Runnable processFile(PsiFile file) {
+ Project project = file.getProject();
+ Document document = PsiDocumentManager.getInstance(project).getDocument(file);
+ if (document == null || leftToPendingFormat(document)) {
+ return EmptyRunnable.getInstance();
+ }
+ if (!PalantirJavaFormatFormattingService.isTrusted(project)) {
+ // Safe mode is a normal state, and on the fly this runs on every highlighting pass: no warning, no balloon.
+ return UNTRUSTED_PROJECT;
+ }
+ var formatter = formattingService.getFormatter(project);
+ if (formatter.isEmpty()) {
+ reportError(
+ project,
+ Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
+ "Failed to optimize imports because formatterService is not configured");
+ return EmptyRunnable.getInstance();
+ }
+
+ String text = document.getText();
+ String fixedText;
+ try {
+ fixedText = formatter.get().fixImports(text);
+ } catch (FormatterException e) {
+ // A syntax error in the file, not a fault of the plugin: an error would go to its error reports.
+ logger.warn(String.format("Failed to optimize imports of file %s", file.getName()), e);
+ reportError(project, Notifications.PARSING_ERROR_TITLE, Notifications.parsingErrorMessage(file.getName()));
+ return EmptyRunnable.getInstance();
+ } catch (ProcessCanceledException e) {
+ throw e;
+ } catch (RuntimeException e) {
+ // As in the formatting task: an error, so that it goes to the plugin's error reports.
+ logger.error("open-java-format could not run the formatter", e);
+ reportError(
+ project,
+ Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
+ Notifications.formatterFailedMessage(file.getName()));
+ return EmptyRunnable.getInstance();
+ }
+ if (fixedText.equals(text)) {
+ return EmptyRunnable.getInstance();
+ }
+
+ return () -> {
+ // The document can have changed since: typed into, or given the text of a formatting request. Or a request
+ // can have started formatting it meanwhile, which takes the imports over.
+ if (StringUtil.equals(document.getImmutableCharSequence(), text) && !leftToPendingFormat(document)) {
+ document.setText(fixedText);
+ }
+ };
+ }
+
+ /**
+ * Whether a formatting request is pending on the document: one that is still formatting fixes the imports itself,
+ * and one whose text is not applied yet would lose it if the document changed now.
+ */
+ private static boolean leftToPendingFormat(Document document) {
+ PendingFormat pendingFormat = PendingFormat.of(document);
+ return pendingFormat != null && (pendingFormat.handOverImports() || pendingFormat.isUnapplied());
+ }
+
+ private static void reportError(Project project, String title, String message) {
+ FormattingNotificationService.getInstance(project)
+ .reportError(Notifications.PARSING_ERROR_NOTIFICATION_GROUP, title, message);
+ }
+}
diff --git a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java
index 1306237d6..d0d187571 100644
--- a/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java
+++ b/open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatSettings.java
@@ -67,6 +67,15 @@ void setEnabled(EnabledState enabled) {
state.enabled = enabled;
}
+ /**
+ * The state that switches the plugin off. The default settings (inherited by new projects) are either 'enabled' or
+ * 'show notification'. There's no way to default new projects to disabled. If someone wants that, we can add
+ * another checkbox, I suppose.
+ */
+ static EnabledState disabledState(Project project) {
+ return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED;
+ }
+
boolean isUninitialized() {
return state.enabled.equals(EnabledState.UNKNOWN);
}
diff --git a/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml b/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml
index a4a5bf339..06b45b020 100644
--- a/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml
+++ b/open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml
@@ -9,7 +9,7 @@
Gradle build no longer sets one. Only tags the marketplace renders: p, a, b, code, ul, ol, li. -->
Formats Java code with open-java-format, a maintained fork of palantir-java-format: 120 columns, 4-space indents and lambda-friendly line breaking.
- With the plugin enabled, Reformat Code runs open-java-format instead of the IDE's built-in Java formatter, so the IDE and your build produce identical files. The IDE's own Java code style settings no longer apply.
+ With the plugin enabled, Reformat Code runs open-java-format instead of the IDE's built-in Java formatter, and Optimize Imports removes unused imports and sorts the others as open-java-format does, so the IDE and your build produce identical files. The IDE's own Java code style settings no longer apply.
The formatter runs in a process of its own, on the IDE's runtime, so the project SDK can be any version. A project that applies the dev.openjavaformat.java-format Gradle plugin takes the formatter version from the build; every other project uses the version bundled with this plugin.
For many files at once, tick Use native binary on the plugin's settings page: the plugin downloads the formatter compiled to a native binary for your platform, which starts without a JVM, in a Maven, Gradle or any other project. A binary of your own works too.
Requires IntelliJ IDEA 2024.2 or later, or another IDE with Java support such as Android Studio.
@@ -22,6 +22,8 @@
+
projectBuilder = IdeaTestFixtureFactory.getFixtureFactory()
+ .createLightFixtureBuilder(
+ new DefaultLightProjectDescriptor(), getClass().getName());
+ // Files in the light project's source root, so that the imports between them resolve.
+ fixture = JavaTestFixtureFactory.getFixtureFactory()
+ .createCodeInsightFixture(projectBuilder.getFixture(), new LightTempDirTestFixtureImpl(true));
+ fixture.setUp();
+ settings = PalantirJavaFormatSettings.getInstance(fixture.getProject());
+ var resetState = new StoredSettings();
+ resetState.setEnabled("true");
+ settings.loadState(resetState);
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ fixture.tearDown();
+ }
+
+ @Test
+ void java_files_get_the_import_settings_that_open_java_format_writes_by() {
+ var transientSettings = transientSettings(fixture.configureByText("A.java", "class A {}"));
+
+ assertThat(modifier.modifySettings(transientSettings, fixture.getFile()))
+ .isTrue();
+
+ var javaSettings = transientSettings.getCustomSettings(JavaCodeStyleSettings.class);
+ assertThat(javaSettings.USE_SINGLE_CLASS_IMPORTS).isTrue();
+ assertThat(javaSettings.CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND).isEqualTo(999);
+ assertThat(javaSettings.NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND).isEqualTo(999);
+ assertThat(javaSettings.PACKAGES_TO_USE_IMPORT_ON_DEMAND.getEntries()).isEmpty();
+ assertThat(javaSettings.LAYOUT_STATIC_IMPORTS_SEPARATELY).isTrue();
+ assertThat(javaSettings.IMPORT_LAYOUT_TABLE.getEntries())
+ .containsExactly(
+ PackageEntry.ALL_OTHER_STATIC_IMPORTS_ENTRY,
+ PackageEntry.BLANK_LINE_ENTRY,
+ PackageEntry.ALL_OTHER_IMPORTS_ENTRY);
+ // The project's own settings stay as they were.
+ assertThat(JavaCodeStyleSettings.getInstance(fixture.getProject()).CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND)
+ .isEqualTo(5);
+ }
+
+ @Test
+ void the_settings_stay_as_they_are_with_the_plugin_disabled() {
+ settings.setEnabled(false);
+ var transientSettings = transientSettings(fixture.configureByText("A.java", "class A {}"));
+
+ assertThat(modifier.modifySettings(transientSettings, fixture.getFile()))
+ .isFalse();
+ assertThat(modifier.mayOverrideSettingsOf(fixture.getProject())).isFalse();
+ }
+
+ @Test
+ void files_of_other_languages_keep_their_settings() {
+ var transientSettings = transientSettings(fixture.configureByText("a.txt", "text"));
+
+ assertThat(modifier.modifySettings(transientSettings, fixture.getFile()))
+ .isFalse();
+ assertThat(modifier.mayOverrideSettingsOf(fixture.getProject())).isTrue();
+ }
+
+ @Test
+ void the_disable_link_of_the_code_style_page_switches_the_plugin_off() {
+ requireNonNull(modifier.getDisablingFunction(fixture.getProject()))
+ .accept(CodeStyle.getSettings(fixture.getProject()));
+
+ assertThat(settings.isEnabled()).isFalse();
+ }
+
+ @Test
+ void an_import_the_ide_adds_is_a_single_class_import_however_many_come_from_its_package() {
+ assertThat(CodeStyleSettingsModifier.EP_NAME.getExtensionList())
+ .hasAtLeastOneElementOfType(PalantirJavaFormatCodeStyleSettingsModifier.class);
+
+ assertThat(addFifthImportFromOnePackage()).isEqualTo("""
+ import p.A;
+ import p.B;
+ import p.C;
+ import p.D;
+ import p.E;
+
+ class Main {}
+ """);
+ }
+
+ @Test
+ void with_the_plugin_disabled_the_ide_imports_a_fifth_class_from_a_package_on_demand() {
+ settings.setEnabled(false);
+
+ assertThat(addFifthImportFromOnePackage()).isEqualTo("""
+ import p.*;
+
+ class Main {}
+ """);
+ }
+
+ /** Adds an import as auto-import, Alt+Enter and completion do, through the IDE's ImportHelper. */
+ private String addFifthImportFromOnePackage() {
+ // The test fixture gives every file the same temporary settings, which no modifier sees.
+ CodeStyle.dropTemporarySettings(fixture.getProject());
+ for (var name : List.of("A", "B", "C", "D")) {
+ fixture.addClass("package p; public class " + name + " {}");
+ }
+ var fifth = fixture.addClass("package p; public class E {}");
+ var file = (PsiJavaFile) fixture.configureByText("Main.java", """
+ import p.A;
+ import p.B;
+ import p.C;
+ import p.D;
+
+ class Main {}
+ """);
+
+ WriteCommandAction.runWriteCommandAction(fixture.getProject(), () -> {
+ JavaCodeStyleManager.getInstance(fixture.getProject()).addImport(file, fifth);
+ });
+ return file.getText();
+ }
+
+ private TransientCodeStyleSettings transientSettings(PsiFile file) {
+ CodeStyleSettings projectSettings = CodeStyle.getSettings(fixture.getProject());
+ return new TransientCodeStyleSettings(file.getVirtualFile(), fixture.getProject(), projectSettings);
+ }
+}
diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java
index c74d18bf6..c20c7c5f2 100644
--- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java
+++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java
@@ -19,6 +19,7 @@
import static com.google.common.collect.MoreCollectors.onlyElement;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import com.intellij.application.options.CodeStyle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.ComboBox;
@@ -123,6 +124,24 @@ void readsAndWritesTheEnabledSetting() throws Throwable {
assertThat(settings.isEnabled()).isTrue();
}
+ @Test
+ void refreshesTheCodeStyleOfOpenFilesWhenOpenJavaFormatIsSwitchedOnOrOff() throws Throwable {
+ // The import settings of each file are cached, and the plugin sets them while it is on.
+ var tracker = CodeStyle.getSettings(fixture.getProject()).getModificationTracker();
+ var countBefore = tracker.getModificationCount();
+
+ EdtTestUtil.runInEdtAndWait(() -> {
+ configurable.reset();
+ configurable.apply();
+ assertThat(tracker.getModificationCount()).isEqualTo(countBefore);
+
+ findCheckBox("Enable open-java-format").setSelected(false);
+ configurable.apply();
+ });
+
+ assertThat(tracker.getModificationCount()).isGreaterThan(countBefore);
+ }
+
@Test
void sitsUnderTools() {
var page = Configurable.PROJECT_CONFIGURABLE.getExtensions(fixture.getProject()).stream()
diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java
new file mode 100644
index 000000000..e69d569fd
--- /dev/null
+++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatImportOptimizerTest.java
@@ -0,0 +1,307 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.palantir.javaformat.intellij;
+
+import static java.util.Objects.requireNonNull;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.intellij.application.options.CodeStyle;
+import com.intellij.codeInsight.actions.OptimizeImportsProcessor;
+import com.intellij.codeInsight.actions.ReformatCodeProcessor;
+import com.intellij.formatting.FormattingContext;
+import com.intellij.formatting.service.AsyncFormattingRequest;
+import com.intellij.formatting.service.CoreFormattingService;
+import com.intellij.formatting.service.FormattingService;
+import com.intellij.ide.impl.TrustedProjects;
+import com.intellij.lang.ImportOptimizer;
+import com.intellij.openapi.command.WriteCommandAction;
+import com.intellij.openapi.util.TextRange;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiFile;
+import com.intellij.testFramework.ExtensionTestUtil;
+import com.intellij.testFramework.fixtures.DefaultLightProjectDescriptor;
+import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
+import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
+import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture;
+import com.intellij.testFramework.fixtures.JavaTestFixtureFactory;
+import com.intellij.testFramework.fixtures.TestFixtureBuilder;
+import com.palantir.javaformat.intellij.PalantirJavaFormatSettings.StoredSettings;
+import java.io.File;
+import java.util.List;
+import java.util.Set;
+import org.jspecify.annotations.Nullable;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+final class PalantirJavaFormatImportOptimizerTest {
+ private static final String UNOPTIMIZED = """
+ package com.foo;
+
+ import java.util.Map;
+ import static java.util.Objects.requireNonNull;
+ import java.util.List;
+ import java.util.ArrayList;
+
+ class ImportTest {
+ Map map;
+ List list = requireNonNull(null);
+ }
+ """;
+
+ private JavaCodeInsightTestFixture fixture;
+ private PalantirJavaFormatSettings settings;
+ private DelegatingFormatter delegatingFormatter;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ TestFixtureBuilder projectBuilder = IdeaTestFixtureFactory.getFixtureFactory()
+ .createLightFixtureBuilder(
+ new DefaultLightProjectDescriptor(), getClass().getName());
+ fixture = JavaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(projectBuilder.getFixture());
+ fixture.setUp();
+
+ // The IDE's own service stays, after ours, for the IDE's own optimizer when the plugin is disabled.
+ delegatingFormatter = new DelegatingFormatter();
+ ExtensionTestUtil.maskExtensions(
+ FormattingService.EP_NAME,
+ List.of(delegatingFormatter, new CoreFormattingService()),
+ fixture.getProjectDisposable());
+
+ settings = PalantirJavaFormatSettings.getInstance(fixture.getProject());
+ var resetState = new StoredSettings();
+ resetState.setEnabled("true");
+ settings.loadState(resetState);
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ fixture.tearDown();
+ }
+
+ @Test
+ void optimize_imports_removes_the_unused_ones_and_sorts_the_others_as_the_command_line_does() {
+ PsiFile file = createPsiFile(UNOPTIMIZED);
+
+ run(new OptimizeImportsProcessor(file.getProject(), file));
+
+ assertThat(file.getText()).isEqualTo("""
+ package com.foo;
+
+ import static java.util.Objects.requireNonNull;
+
+ import java.util.List;
+ import java.util.Map;
+
+ class ImportTest {
+ Map map;
+ List list = requireNonNull(null);
+ }
+ """);
+ assertThat(delegatingFormatter.optimizerInvoked).isTrue();
+ }
+
+ @Test
+ void reformat_with_optimize_imports_gives_what_the_command_line_gives() throws Exception {
+ PsiFile file = createPsiFile(UNOPTIMIZED);
+
+ run(new OptimizeImportsProcessor(new ReformatCodeProcessor(file, false)));
+
+ assertThat(file.getText()).isEqualTo(commandLineOutput(UNOPTIMIZED));
+ }
+
+ @Test
+ void optimize_imports_hands_the_imports_over_to_a_format_still_running_on_the_document() throws Exception {
+ PsiFile file = createPsiFile(UNOPTIMIZED);
+ var request = new RecordingRequest(file);
+ Runnable task = startFormatting(request);
+
+ // The platform starts the optimizer while the formatter runs in the background: if it wrote the imports now,
+ // the platform would drop the formatted text, the document having changed since the request started.
+ run(new OptimizeImportsProcessor(file.getProject(), file));
+ assertThat(file.getText()).isEqualTo(UNOPTIMIZED);
+
+ task.run();
+ assertThat(request.text).isEqualTo(commandLineOutput(UNOPTIMIZED));
+ }
+
+ @Test
+ void optimize_imports_writes_nothing_while_a_format_has_text_not_yet_applied() throws Exception {
+ PsiFile file = createPsiFile(UNOPTIMIZED);
+ var request = new RecordingRequest(file);
+ Runnable task = startFormatting(request);
+ task.run();
+
+ run(new OptimizeImportsProcessor(file.getProject(), file));
+ assertThat(file.getText()).isEqualTo(UNOPTIMIZED);
+
+ // Once the platform applies the formatted text, optimizing imports works on that.
+ WriteCommandAction.runWriteCommandAction(fixture.getProject(), () -> {
+ var documentManager = PsiDocumentManager.getInstance(fixture.getProject());
+ requireNonNull(documentManager.getDocument(file)).setText(requireNonNull(request.text));
+ documentManager.commitAllDocuments();
+ });
+ run(new OptimizeImportsProcessor(file.getProject(), file));
+ assertThat(file.getText()).isEqualTo(commandLineOutput(UNOPTIMIZED));
+ }
+
+ @Test
+ void optimize_imports_is_the_ides_own_when_the_plugin_is_disabled() {
+ settings.setEnabled(false);
+ PsiFile file = createPsiFile(UNOPTIMIZED);
+
+ run(new OptimizeImportsProcessor(file.getProject(), file));
+
+ assertThat(delegatingFormatter.optimizerInvoked).isFalse();
+ }
+
+ @Test
+ void optimize_imports_in_an_untrusted_project_changes_nothing_and_says_why_in_the_hint() {
+ PsiFile file = createPsiFile(UNOPTIMIZED);
+ TrustedProjects.setTrusted(fixture.getProject(), false);
+ try {
+ var processor = new OptimizeImportsProcessor(file.getProject(), file);
+ processor.setCollectInfo(true);
+
+ run(processor);
+
+ assertThat(file.getText()).isEqualTo(UNOPTIMIZED);
+ assertThat(requireNonNull(processor.getInfoCollector()).getOptimizeImportsNotification())
+ .isEqualTo(Notifications.untrustedProjectMessage());
+ } finally {
+ // The light project outlives the test.
+ TrustedProjects.setTrusted(fixture.getProject(), true);
+ }
+ }
+
+ private String commandLineOutput(String input) throws Exception {
+ return delegatingFormatter
+ .getFormatter(fixture.getProject())
+ .orElseThrow()
+ .formatSourceReflowStringsAndFixImports(input);
+ }
+
+ /** Starts a formatting request on the document as the platform does, without running it yet. */
+ private Runnable startFormatting(AsyncFormattingRequest request) {
+ return WriteCommandAction.writeCommandAction(fixture.getProject())
+ .compute(() -> (Runnable) delegatingFormatter.createFormattingTask(request));
+ }
+
+ private void run(OptimizeImportsProcessor processor) {
+ WriteCommandAction.runWriteCommandAction(fixture.getProject(), () -> {
+ processor.run();
+ PsiDocumentManager.getInstance(fixture.getProject()).commitAllDocuments();
+ });
+ }
+
+ private PsiFile createPsiFile(String contents) {
+ PsiFile psiFile = fixture.configureByText("ImportTest.java", contents);
+ assertThat(psiFile).isNotNull();
+ return psiFile;
+ }
+
+ /** A request as the platform makes it for a Reformat of the whole file, which records the text it is given. */
+ private static final class RecordingRequest implements AsyncFormattingRequest {
+ private final PsiFile file;
+ private final String documentText;
+
+ @Nullable
+ private String text;
+
+ RecordingRequest(PsiFile file) {
+ this.file = file;
+ this.documentText = file.getText();
+ }
+
+ @Override
+ public String getDocumentText() {
+ return documentText;
+ }
+
+ @Override
+ @Nullable
+ public File getIOFile() {
+ return null;
+ }
+
+ @Override
+ public List getFormattingRanges() {
+ return List.of(file.getTextRange());
+ }
+
+ @Override
+ public boolean canChangeWhitespaceOnly() {
+ return false;
+ }
+
+ @Override
+ public boolean isQuickFormat() {
+ return false;
+ }
+
+ @Override
+ public FormattingContext getContext() {
+ return FormattingContext.create(file, CodeStyle.getSettings(file));
+ }
+
+ @Override
+ public void onTextReady(@Nullable String updatedText) {
+ text = updatedText;
+ }
+
+ @Override
+ public void onError(String title, String message) {
+ throw new AssertionError(title + ": " + message);
+ }
+
+ @Override
+ public void onError(String title, String message, int offset) {
+ onError(title, message);
+ }
+ }
+
+ private static final class DelegatingFormatter extends PalantirJavaFormatFormattingService {
+ private boolean optimizerInvoked = false;
+
+ DelegatingFormatter() {
+ this.setPluginDescriptor(
+ requireNonNull(FormattingService.EP_NAME.findExtension(PalantirJavaFormatFormattingService.class))
+ .getPluginDescriptor()
+ .orElseThrow());
+ }
+
+ @Override
+ public Set getImportOptimizers(PsiFile file) {
+ var delegate = super.getImportOptimizers(file).iterator().next();
+ return Set.of(new ImportOptimizer() {
+ @Override
+ public boolean supports(PsiFile file) {
+ return delegate.supports(file);
+ }
+
+ @Override
+ public Runnable processFile(PsiFile file) {
+ optimizerInvoked = true;
+ return delegate.processFile(file);
+ }
+ });
+ }
+
+ @Override
+ protected FormattingTask createFormattingTask(AsyncFormattingRequest request) {
+ return requireNonNull(super.createFormattingTask(request));
+ }
+ }
+}