Skip to content

Commit 9d5ece4

Browse files
committed
Optimize imports with open-java-format in IntelliJ IDEA
The formatting service now has OPTIMIZE_IMPORTS, so every way the IDE optimizes imports asks its optimizer instead of the IDE's own JavaImportOptimizer: Optimize Imports, Reformat with "Optimize imports", Actions on Save, the check before a commit, the quick fix for an unused import and "Optimize imports on the fly". The optimizer calls FormatterService.fixImports, which since #221 fixes the imports alone: the unused ones removed, the others sorted, as the command line does. Reformat with "Optimize imports" starts the formatter in the background and the optimizer right after it, on the same document. The platform applies the formatter's text only if the document has not changed since the request started, and IntelliJ IDEA registers no DocumentMerger, so whichever wrote second lost: the formatting or the imports. While a format of the plugin is running on a document, the optimizer now hands the imports over to it, and the format fixes them after the layout, as the command line does. Once the format has its text, the optimizer leaves the document alone until the text is in. The optimizer holds a read action while the formatter runs, which "Optimize imports on the fly" makes typing wait for (#253).
1 parent 3453f13 commit 9d5ece4

5 files changed

Lines changed: 556 additions & 16 deletions

File tree

‎open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/Notifications.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@ static String parsingErrorMessage(String filename) {
2727
return "open-java-format failed. Does " + filename + " have syntax errors?";
2828
}
2929

30+
static String untrustedProjectMessage() {
31+
return "open-java-format requires a trusted project to load the external formatter classpath.";
32+
}
33+
3034
static String formatterFailedMessage(String filename) {
3135
return "open-java-format could not run the formatter on " + filename + ". The details are in idea.log.";
3236
}

‎open-java-format-idea-plugin/src/main/java/com/palantir/javaformat/intellij/PalantirJavaFormatFormattingService.java‎

Lines changed: 143 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,20 @@
2424
import com.intellij.formatting.service.AsyncFormattingRequest;
2525
import com.intellij.ide.highlighter.JavaFileType;
2626
import com.intellij.ide.impl.TrustedProjects;
27+
import com.intellij.lang.ImportOptimizer;
2728
import com.intellij.openapi.diagnostic.Logger;
29+
import com.intellij.openapi.editor.Document;
30+
import com.intellij.openapi.editor.event.DocumentEvent;
31+
import com.intellij.openapi.editor.event.DocumentListener;
2832
import com.intellij.openapi.extensions.PluginAware;
2933
import com.intellij.openapi.extensions.PluginDescriptor;
3034
import com.intellij.openapi.progress.ProcessCanceledException;
3135
import com.intellij.openapi.project.Project;
36+
import com.intellij.openapi.util.Disposer;
37+
import com.intellij.openapi.util.Key;
3238
import com.intellij.openapi.util.NlsSafe;
3339
import com.intellij.openapi.util.TextRange;
40+
import com.intellij.psi.PsiDocumentManager;
3441
import com.intellij.psi.PsiFile;
3542
import com.palantir.javaformat.java.FormatterException;
3643
import com.palantir.javaformat.java.FormatterService;
@@ -40,12 +47,14 @@
4047
import java.util.List;
4148
import java.util.Optional;
4249
import java.util.Set;
50+
import java.util.concurrent.atomic.AtomicReference;
4351
import org.jspecify.annotations.Nullable;
4452

4553
class PalantirJavaFormatFormattingService extends AsyncDocumentFormattingService implements PluginAware {
4654
private static final Logger logger = Logger.getInstance(PalantirJavaFormatFormattingService.class);
4755
private final FormatterProvider formatterProvider =
4856
new FormatterProvider(() -> EmbeddedNativeImage.getInstance().installedPath());
57+
private final ImportOptimizer importOptimizer = new PalantirJavaFormatImportOptimizer(this);
4958

5059
// The platform sets this right after creating the service from plugin.xml: the descriptor of the plugin that
5160
// declared it, which is how the plugin learns its own path and version (see FormatterProvider.getPluginDescriptor).
@@ -66,19 +75,27 @@ Optional<PluginDescriptor> getPluginDescriptor() {
6675
@Nullable
6776
protected FormattingTask createFormattingTask(AsyncFormattingRequest request) {
6877
Project project = request.getContext().getProject();
69-
// The marketplace verifier reports this class as experimental, and newer IDEs also deprecate it. It stays:
70-
// its replacement, com.intellij.ide.trustedProjects.TrustedProjects, is @ApiStatus.Internal — a worse thing
71-
// for a plugin to call.
72-
if (!TrustedProjects.isTrusted(project)) {
78+
if (!isTrusted(project)) {
7379
logger.warn("open-java-format: skipping formatting for untrusted project: " + project.getName());
74-
request.onError(
75-
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
76-
"open-java-format requires a trusted project to load the external formatter classpath.");
80+
request.onError(Notifications.GENERIC_ERROR_NOTIFICATION_GROUP, Notifications.untrustedProjectMessage());
7781
return null;
7882
}
79-
PalantirJavaFormatSettings settings = PalantirJavaFormatSettings.getInstance(project);
80-
Optional<FormatterService> formatter = formatterProvider.get(project, settings);
81-
return new PalantirJavaFormatFormattingTask(request, formatter);
83+
PendingFormat pendingFormat = PendingFormat.start(
84+
project,
85+
PsiDocumentManager.getInstance(project)
86+
.getDocument(request.getContext().getContainingFile()));
87+
return new PalantirJavaFormatFormattingTask(request, getFormatter(project), pendingFormat);
88+
}
89+
90+
static boolean isTrusted(Project project) {
91+
// The marketplace verifier reports this class as experimental, and newer IDEs also deprecate it. It stays:
92+
// its replacement, com.intellij.ide.trustedProjects.TrustedProjects, is @ApiStatus.Internal — a worse thing
93+
// for a plugin to call.
94+
return TrustedProjects.isTrusted(project);
95+
}
96+
97+
Optional<FormatterService> getFormatter(Project project) {
98+
return formatterProvider.get(project, PalantirJavaFormatSettings.getInstance(project));
8299
}
83100

84101
@Override
@@ -91,9 +108,17 @@ protected String getNotificationGroupId() {
91108
return "open-java-format";
92109
}
93110

111+
// OPTIMIZE_IMPORTS: every way the IDE optimizes imports asks the first formatting service that has this feature and
112+
// can format the file for its optimizers (FormattingServiceUtil.findImportsOptimizingService), and so takes ours
113+
// instead of its own JavaImportOptimizer.
94114
@Override
95115
public Set<Feature> getFeatures() {
96-
return Set.of(Feature.FORMAT_FRAGMENTS);
116+
return Set.of(Feature.FORMAT_FRAGMENTS, Feature.OPTIMIZE_IMPORTS);
117+
}
118+
119+
@Override
120+
public Set<ImportOptimizer> getImportOptimizers(PsiFile file) {
121+
return Set.of(importOptimizer);
97122
}
98123

99124
@Override
@@ -102,22 +127,120 @@ public boolean canFormat(PsiFile file) {
102127
&& PalantirJavaFormatSettings.getInstance(file.getProject()).isEnabled();
103128
}
104129

130+
/**
131+
* A formatting request of this service whose text is not in its document yet, kept on the document.
132+
*
133+
* <p>The formatter runs in the background, and the platform applies its text later, only if the document has not
134+
* changed since the request started: IntelliJ IDEA registers no {@code DocumentMerger} to do anything else.
135+
* Reformat with "Optimize imports" starts the formatter and the import optimizer on the same document without
136+
* waiting for the first, so whichever wrote second would lose: the formatted text, or the imports. While a request
137+
* is formatting, the optimizer hands its work over to it, and the request fixes the imports of the text it
138+
* formatted, as the command line does. Once the request has its text, the optimizer leaves the document alone
139+
* until the text is applied.
140+
*/
141+
static final class PendingFormat {
142+
private static final Key<PendingFormat> KEY = Key.create("open-java-format.pendingFormat");
143+
144+
private enum State {
145+
FORMATTING,
146+
FORMATTING_AND_FIXING_IMPORTS,
147+
// Until the document next changes: with the text, or with an edit that makes the platform drop it.
148+
UNAPPLIED,
149+
DONE
150+
}
151+
152+
private final AtomicReference<State> state = new AtomicReference<>(State.FORMATTING);
153+
private final Project project;
154+
155+
@Nullable
156+
private final Document document;
157+
158+
private PendingFormat(Project project, @Nullable Document document) {
159+
this.project = project;
160+
this.document = document;
161+
}
162+
163+
static PendingFormat start(Project project, @Nullable Document document) {
164+
var pendingFormat = new PendingFormat(project, document);
165+
if (document != null) {
166+
document.putUserData(KEY, pendingFormat);
167+
}
168+
return pendingFormat;
169+
}
170+
171+
@Nullable
172+
static PendingFormat of(Document document) {
173+
return document.getUserData(KEY);
174+
}
175+
176+
/** Asks the request to fix the imports too: false if it has finished formatting already. */
177+
boolean handOverImports() {
178+
return state.compareAndSet(State.FORMATTING, State.FORMATTING_AND_FIXING_IMPORTS);
179+
}
180+
181+
boolean isUnapplied() {
182+
return state.get() == State.UNAPPLIED;
183+
}
184+
185+
/** Ends the formatting, and says whether the imports were handed over meanwhile. */
186+
private boolean finishFormatting() {
187+
return state.getAndSet(State.UNAPPLIED) == State.FORMATTING_AND_FIXING_IMPORTS;
188+
}
189+
190+
private void finish(boolean changesDocument) {
191+
if (!changesDocument || document == null) {
192+
state.set(State.DONE);
193+
return;
194+
}
195+
var untilChanged = Disposer.newDisposable("open-java-format: until the formatted text is applied");
196+
if (!Disposer.tryRegister(project, untilChanged)) {
197+
state.set(State.DONE);
198+
return;
199+
}
200+
// Registered before the platform applies the text, which it does only once the task has returned.
201+
document.addDocumentListener(
202+
new DocumentListener() {
203+
@Override
204+
public void documentChanged(DocumentEvent event) {
205+
state.set(State.DONE);
206+
Disposer.dispose(untilChanged);
207+
}
208+
},
209+
untilChanged);
210+
}
211+
}
212+
105213
private static final class PalantirJavaFormatFormattingTask implements FormattingTask {
106214
private final AsyncFormattingRequest request;
107215
private final Optional<FormatterService> formatterService;
216+
private final PendingFormat pendingFormat;
108217

109-
PalantirJavaFormatFormattingTask(AsyncFormattingRequest request, Optional<FormatterService> formatterService) {
218+
PalantirJavaFormatFormattingTask(
219+
AsyncFormattingRequest request,
220+
Optional<FormatterService> formatterService,
221+
PendingFormat pendingFormat) {
110222
this.request = request;
111223
this.formatterService = formatterService;
224+
this.pendingFormat = pendingFormat;
112225
}
113226

114227
@Override
115228
public void run() {
229+
var changesDocument = false;
230+
try {
231+
changesDocument = format();
232+
} finally {
233+
pendingFormat.finish(changesDocument);
234+
}
235+
}
236+
237+
/** Formats, and says whether the text it gave back changes the document. */
238+
private boolean format() {
116239
if (formatterService.isEmpty()) {
117240
request.onError(
118241
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
119242
"Failed to format file because formatterService is not configured");
120-
return;
243+
return false;
121244
}
122245

123246
String preFormatText = request.getDocumentText();
@@ -138,14 +261,18 @@ public void run() {
138261
// returns a change. Thus we must perform a content aware diff / branching.
139262
String formattedText = applyReplacements(
140263
preFormatText, formatterService.get().getFormatReplacements(preFormatText, toRanges(request)));
264+
if (pendingFormat.finishFormatting()) {
265+
formattedText = formatterService.get().fixImports(formattedText);
266+
}
141267

142268
// The Javadoc of this API says that you should set it to null when the document is unchanged
143269
// We should not be trying to format a document that is already formatted
144270
if (preFormatText.equals(formattedText)) {
145271
request.onTextReady(null);
146-
} else {
147-
request.onTextReady(formattedText);
272+
return false;
148273
}
274+
request.onTextReady(formattedText);
275+
return true;
149276
} catch (FormatterException e) {
150277
// A syntax error in the file, not a fault of the plugin: an error would go to its error reports.
151278
logger.warn(
@@ -169,6 +296,7 @@ public void run() {
169296
Notifications.formatterFailedMessage(
170297
request.getContext().getContainingFile().getName()));
171298
}
299+
return false;
172300
}
173301

174302
static String applyReplacements(String input, Collection<Replacement> replacementsCollection) {
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.intellij;
16+
17+
import com.intellij.formatting.service.FormattingNotificationService;
18+
import com.intellij.lang.ImportOptimizer;
19+
import com.intellij.openapi.diagnostic.Logger;
20+
import com.intellij.openapi.editor.Document;
21+
import com.intellij.openapi.progress.ProcessCanceledException;
22+
import com.intellij.openapi.project.Project;
23+
import com.intellij.openapi.util.EmptyRunnable;
24+
import com.intellij.openapi.util.text.StringUtil;
25+
import com.intellij.psi.PsiDocumentManager;
26+
import com.intellij.psi.PsiFile;
27+
import com.palantir.javaformat.intellij.PalantirJavaFormatFormattingService.PendingFormat;
28+
import com.palantir.javaformat.java.FormatterException;
29+
30+
/**
31+
* Optimizes imports as the command line fixes them, with {@code FormatterService.fixImports}: the unused ones removed,
32+
* the others sorted. The IDE takes it instead of its own {@code JavaImportOptimizer} for every way of optimizing
33+
* imports, since {@link PalantirJavaFormatFormattingService} has {@code OPTIMIZE_IMPORTS}.
34+
*/
35+
final class PalantirJavaFormatImportOptimizer implements ImportOptimizer {
36+
private static final Logger logger = Logger.getInstance(PalantirJavaFormatImportOptimizer.class);
37+
38+
private final PalantirJavaFormatFormattingService formattingService;
39+
40+
PalantirJavaFormatImportOptimizer(PalantirJavaFormatFormattingService formattingService) {
41+
this.formattingService = formattingService;
42+
}
43+
44+
@Override
45+
public boolean supports(PsiFile file) {
46+
return formattingService.canFormat(file);
47+
}
48+
49+
// Called under a read action, in the background on most paths; the Runnable runs on the EDT under a write action.
50+
// So the formatter runs here, and the Runnable only writes its text. EmptyRunnable tells the IDE that nothing
51+
// changed. The formatter does not check for cancellation, so a write action waits for it: with "Optimize imports
52+
// on the fly", typing waits (#253).
53+
@Override
54+
public Runnable processFile(PsiFile file) {
55+
Project project = file.getProject();
56+
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
57+
if (document == null || leftToPendingFormat(document)) {
58+
return EmptyRunnable.getInstance();
59+
}
60+
if (!PalantirJavaFormatFormattingService.isTrusted(project)) {
61+
logger.warn("open-java-format: skipping optimizing imports for untrusted project: " + project.getName());
62+
reportError(
63+
project, Notifications.GENERIC_ERROR_NOTIFICATION_GROUP, Notifications.untrustedProjectMessage());
64+
return EmptyRunnable.getInstance();
65+
}
66+
var formatter = formattingService.getFormatter(project);
67+
if (formatter.isEmpty()) {
68+
reportError(
69+
project,
70+
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
71+
"Failed to optimize imports because formatterService is not configured");
72+
return EmptyRunnable.getInstance();
73+
}
74+
75+
String text = document.getText();
76+
String fixedText;
77+
try {
78+
fixedText = formatter.get().fixImports(text);
79+
} catch (FormatterException e) {
80+
// A syntax error in the file, not a fault of the plugin: an error would go to its error reports.
81+
logger.warn(String.format("Failed to optimize imports of file %s", file.getName()), e);
82+
reportError(project, Notifications.PARSING_ERROR_TITLE, Notifications.parsingErrorMessage(file.getName()));
83+
return EmptyRunnable.getInstance();
84+
} catch (ProcessCanceledException e) {
85+
throw e;
86+
} catch (RuntimeException e) {
87+
// As in the formatting task: an error, so that it goes to the plugin's error reports.
88+
logger.error("open-java-format could not run the formatter", e);
89+
reportError(
90+
project,
91+
Notifications.GENERIC_ERROR_NOTIFICATION_GROUP,
92+
Notifications.formatterFailedMessage(file.getName()));
93+
return EmptyRunnable.getInstance();
94+
}
95+
if (fixedText.equals(text)) {
96+
return EmptyRunnable.getInstance();
97+
}
98+
99+
return () -> {
100+
// The document can have changed since: typed into, or given the text of a formatting request. Or a request
101+
// can have started formatting it meanwhile, which takes the imports over.
102+
if (StringUtil.equals(document.getImmutableCharSequence(), text) && !leftToPendingFormat(document)) {
103+
document.setText(fixedText);
104+
}
105+
};
106+
}
107+
108+
/**
109+
* Whether a formatting request is pending on the document: one that is still formatting fixes the imports itself,
110+
* and one whose text is not applied yet would lose it if the document changed now.
111+
*/
112+
private static boolean leftToPendingFormat(Document document) {
113+
PendingFormat pendingFormat = PendingFormat.of(document);
114+
return pendingFormat != null && (pendingFormat.handOverImports() || pendingFormat.isUnapplied());
115+
}
116+
117+
private static void reportError(Project project, String title, String message) {
118+
FormattingNotificationService.getInstance(project)
119+
.reportError(Notifications.PARSING_ERROR_NOTIFICATION_GROUP, title, message);
120+
}
121+
}

‎open-java-format-idea-plugin/src/main/resources/META-INF/plugin.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
Gradle build no longer sets one. Only tags the marketplace renders: p, a, b, code, ul, ol, li. -->
1010
<description><![CDATA[
1111
<p>Formats Java code with <a href="https://github.com/openjavaformat/open-java-format">open-java-format</a>, a maintained fork of palantir-java-format: 120 columns, 4-space indents and lambda-friendly line breaking.</p>
12-
<p>With the plugin enabled, <b>Reformat Code</b> 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.</p>
12+
<p>With the plugin enabled, <b>Reformat Code</b> runs open-java-format instead of the IDE's built-in Java formatter, and <b>Optimize Imports</b> 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.</p>
1313
<p>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 <code>dev.openjavaformat.java-format</code> Gradle plugin takes the formatter version from the build; every other project uses the version bundled with this plugin.</p>
1414
<p>For many files at once, tick <b>Use native binary</b> 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.</p>
1515
<p>Requires IntelliJ IDEA 2024.2 or later, or another IDE with Java support such as Android Studio.</p>

0 commit comments

Comments
 (0)