Skip to content

Commit 8e53c2f

Browse files
plumpycushon
authored andcommitted
Intellij: allow GoogleJavaFormatCodeStyleManager to decide which formatter to use on a per-file basis
This is structural work for allowing the formatter to be configured per-module. MOE_MIGRATED_REVID=134459361
1 parent c79f897 commit 8e53c2f

File tree

5 files changed

+86
-74
lines changed

5 files changed

+86
-74
lines changed

idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatCodeStyleManager.java

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616

1717
package com.google.googlejavaformat.intellij;
1818

19+
import static java.util.Comparator.comparing;
20+
1921
import com.google.common.collect.ImmutableList;
20-
import com.google.common.collect.Ordering;
2122
import com.google.common.collect.Range;
2223
import com.google.googlejavaformat.java.Formatter;
2324
import com.google.googlejavaformat.java.FormatterException;
@@ -34,8 +35,8 @@
3435
import com.intellij.psi.impl.CheckUtil;
3536
import com.intellij.util.IncorrectOperationException;
3637
import java.util.Collection;
37-
import java.util.Comparator;
3838
import java.util.List;
39+
import java.util.stream.Collectors;
3940
import org.jetbrains.annotations.NotNull;
4041

4142
/**
@@ -48,10 +49,6 @@ public class GoogleJavaFormatCodeStyleManager extends CodeStyleManagerDecorator
4849

4950
private final Formatter formatter;
5051

51-
public GoogleJavaFormatCodeStyleManager(@NotNull CodeStyleManager original) {
52-
this(original, JavaFormatterOptions.defaultOptions());
53-
}
54-
5552
public GoogleJavaFormatCodeStyleManager(
5653
@NotNull CodeStyleManager original, @NotNull JavaFormatterOptions formatterOptions) {
5754
super(original);
@@ -61,7 +58,7 @@ public GoogleJavaFormatCodeStyleManager(
6158
@Override
6259
public void reformatText(@NotNull PsiFile file, int startOffset, int endOffset)
6360
throws IncorrectOperationException {
64-
if (StdFileTypes.JAVA.equals(file.getFileType())) {
61+
if (StdFileTypes.JAVA.equals(file.getFileType()) && useGoogleFormatterForFile(file)) {
6562
formatInternal(file, ImmutableList.of(Range.closedOpen(startOffset, endOffset)));
6663
} else {
6764
super.reformatText(file, startOffset, endOffset);
@@ -71,7 +68,7 @@ public void reformatText(@NotNull PsiFile file, int startOffset, int endOffset)
7168
@Override
7269
public void reformatText(@NotNull PsiFile file, @NotNull Collection<TextRange> ranges)
7370
throws IncorrectOperationException {
74-
if (StdFileTypes.JAVA.equals(file.getFileType())) {
71+
if (StdFileTypes.JAVA.equals(file.getFileType()) && useGoogleFormatterForFile(file)) {
7572
formatInternal(file, convertToRanges(ranges));
7673
} else {
7774
super.reformatText(file, ranges);
@@ -81,13 +78,17 @@ public void reformatText(@NotNull PsiFile file, @NotNull Collection<TextRange> r
8178
@Override
8279
public void reformatTextWithContext(@NotNull PsiFile file, @NotNull Collection<TextRange> ranges)
8380
throws IncorrectOperationException {
84-
if (StdFileTypes.JAVA.equals(file.getFileType())) {
81+
if (StdFileTypes.JAVA.equals(file.getFileType()) && useGoogleFormatterForFile(file)) {
8582
formatInternal(file, convertToRanges(ranges));
8683
} else {
8784
super.reformatTextWithContext(file, ranges);
8885
}
8986
}
9087

88+
protected boolean useGoogleFormatterForFile(@NotNull PsiFile file) {
89+
return true;
90+
}
91+
9192
private void formatInternal(PsiFile file, List<Range<Integer>> ranges)
9293
throws IncorrectOperationException {
9394
ApplicationManager.getApplication().assertWriteAccessAllowed();
@@ -97,11 +98,14 @@ private void formatInternal(PsiFile file, List<Range<Integer>> ranges)
9798
Document document = PsiDocumentManager.getInstance(getProject()).getDocument(file);
9899
if (document != null) {
99100
try {
100-
ImmutableList<Replacement> replacements =
101-
formatter.getFormatReplacements(document.getText(), ranges);
102-
List<Replacement> reverseSortedReplacements =
103-
Ordering.from(REPLACEMENT_COMPARATOR).reverse().sortedCopy(replacements);
104-
performReplacements(document, reverseSortedReplacements);
101+
List<Replacement> replacements =
102+
formatter
103+
.getFormatReplacements(document.getText(), ranges)
104+
.stream()
105+
.sorted(
106+
comparing((Replacement r) -> r.getReplaceRange().lowerEndpoint()).reversed())
107+
.collect(Collectors.toList());
108+
performReplacements(document, replacements);
105109
} catch (FormatterException e) {
106110
// Do not format on errors
107111
}
@@ -112,16 +116,13 @@ private void performReplacements(
112116
final Document document, final List<Replacement> reverseSortedReplacements) {
113117
WriteCommandAction.runWriteCommandAction(
114118
getProject(),
115-
new Runnable() {
116-
@Override
117-
public void run() {
118-
for (Replacement replacement : reverseSortedReplacements) {
119-
Range<Integer> range = replacement.getReplaceRange();
120-
document.replaceString(
121-
range.lowerEndpoint(), range.upperEndpoint(), replacement.getReplacementString());
122-
}
123-
PsiDocumentManager.getInstance(getProject()).commitDocument(document);
119+
() -> {
120+
for (Replacement replacement : reverseSortedReplacements) {
121+
Range<Integer> range = replacement.getReplaceRange();
122+
document.replaceString(
123+
range.lowerEndpoint(), range.upperEndpoint(), replacement.getReplacementString());
124124
}
125+
PsiDocumentManager.getInstance(getProject()).commitDocument(document);
125126
});
126127
}
127128

@@ -132,12 +133,4 @@ private static List<Range<Integer>> convertToRanges(Collection<TextRange> textRa
132133
}
133134
return ranges.build();
134135
}
135-
136-
private static final Comparator<Replacement> REPLACEMENT_COMPARATOR =
137-
new Comparator<Replacement>() {
138-
@Override
139-
public int compare(Replacement o1, Replacement o2) {
140-
return o1.getReplaceRange().lowerEndpoint() - o2.getReplaceRange().lowerEndpoint();
141-
}
142-
};
143136
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Copyright 2015 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.googlejavaformat.intellij;
18+
19+
import com.intellij.psi.codeStyle.CodeStyleManager;
20+
import org.jetbrains.annotations.NotNull;
21+
22+
/** Creates a {@link GoogleJavaFormatCodeStyleManager}. */
23+
public interface GoogleJavaFormatCodeStyleManagerFactory {
24+
25+
GoogleJavaFormatCodeStyleManager createFormatter(@NotNull CodeStyleManager delegate);
26+
}

idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatInstaller.java

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
package com.google.googlejavaformat.intellij;
1818

19-
import com.google.googlejavaformat.java.JavaFormatterOptions;
2019
import com.intellij.openapi.project.Project;
2120
import com.intellij.psi.codeStyle.CodeStyleManager;
2221
import org.picocontainer.MutablePicoContainer;
@@ -32,30 +31,28 @@ public final class GoogleJavaFormatInstaller {
3231
private GoogleJavaFormatInstaller() {}
3332

3433
public static void installFormatter(
35-
Project project, boolean useGoogleFormatter, JavaFormatterOptions javaFormatterOptions) {
34+
Project project, GoogleJavaFormatCodeStyleManagerFactory factory) {
3635
CodeStyleManager currentManager = CodeStyleManager.getInstance(project);
37-
CodeStyleManager newManager = null;
38-
39-
if (useGoogleFormatter) {
40-
if (currentManager instanceof GoogleJavaFormatCodeStyleManager) {
41-
// Recreate from delegate, updating the javaFormatterOptions as needed.
42-
currentManager = ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate();
43-
}
44-
newManager = new GoogleJavaFormatCodeStyleManager(currentManager, javaFormatterOptions);
45-
} else {
46-
if (currentManager instanceof GoogleJavaFormatCodeStyleManager) {
47-
newManager = ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate();
48-
}
36+
37+
if (currentManager instanceof GoogleJavaFormatCodeStyleManager) {
38+
currentManager = ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate();
4939
}
5040

41+
setManager(project, factory.createFormatter(currentManager));
42+
}
43+
44+
public static void removeFormatter(Project project) {
45+
CodeStyleManager currentManager = CodeStyleManager.getInstance(project);
46+
if (currentManager instanceof GoogleJavaFormatCodeStyleManager) {
47+
setManager(project, ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate());
48+
}
49+
}
50+
51+
private static void setManager(Project project, CodeStyleManager newManager) {
5152
if (newManager != null) {
5253
MutablePicoContainer container = (MutablePicoContainer) project.getPicoContainer();
5354
container.unregisterComponent(CODE_STYLE_MANAGER_KEY);
5455
container.registerComponentInstance(CODE_STYLE_MANAGER_KEY, newManager);
5556
}
5657
}
57-
58-
public static void installFormatter(Project project, boolean useGoogleFormatter) {
59-
installFormatter(project, useGoogleFormatter, JavaFormatterOptions.defaultOptions());
60-
}
6158
}

idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,15 @@ void setStyle(FormatterStyle formatterStyle) {
8383
}
8484

8585
private void updateFormatterState() {
86-
GoogleJavaFormatInstaller.installFormatter(
87-
myProject, enabled, this.formatterStyle.getJavaFormatterOptions());
86+
if (enabled) {
87+
GoogleJavaFormatInstaller.installFormatter(
88+
myProject,
89+
(delegate) ->
90+
new GoogleJavaFormatCodeStyleManager(
91+
delegate, formatterStyle.getJavaFormatterOptions()));
92+
} else {
93+
GoogleJavaFormatInstaller.removeFormatter(myProject);
94+
}
8895
}
8996

9097
static class State {

idea_plugin/test/com/google/googlejavaformat/intellij/GoogleJavaFormatCodeStyleManagerTest.java

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import com.google.common.base.Joiner;
2020
import com.google.common.collect.ImmutableList;
21+
import com.google.googlejavaformat.java.JavaFormatterOptions;
2122
import com.intellij.openapi.application.ApplicationManager;
2223
import com.intellij.openapi.fileTypes.StdFileTypes;
2324
import com.intellij.openapi.util.TextRange;
@@ -55,54 +56,48 @@ protected void setUp() throws Exception {
5556
public void testFormatFile() {
5657
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
5758
final GoogleJavaFormatCodeStyleManager googleJavaFormat =
58-
new GoogleJavaFormatCodeStyleManager(codeStyleManager);
59+
new GoogleJavaFormatCodeStyleManager(
60+
codeStyleManager, JavaFormatterOptions.defaultOptions());
5961
myFixture.configureByText(
6062
StdFileTypes.JAVA,
6163
"public class Test {public static void main(String[]args){System.out.println();}}");
6264
final int startOffset = 0;
6365
final int endOffset = myFixture.getFile().getTextLength();
6466
ApplicationManager.getApplication()
6567
.runWriteAction(
66-
new Runnable() {
67-
@Override
68-
public void run() {
69-
googleJavaFormat.reformatText(myFixture.getFile(), startOffset, endOffset);
70-
}
71-
});
68+
() -> googleJavaFormat.reformatText(myFixture.getFile(), startOffset, endOffset));
7269
myFixture.checkResult(
7370
join(
7471
"public class Test {",
7572
" public static void main(String[] args) {",
7673
" System.out.println();",
7774
" }",
78-
"}"));
75+
"}",
76+
""));
7977
}
8078

8179
public void testDontFormatNonJavaFile() {
8280
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
8381
final GoogleJavaFormatCodeStyleManager googleJavaFormat =
84-
new GoogleJavaFormatCodeStyleManager(codeStyleManager);
82+
new GoogleJavaFormatCodeStyleManager(
83+
codeStyleManager, JavaFormatterOptions.defaultOptions());
8584
myFixture.configureByText(
8685
StdFileTypes.PLAIN_TEXT,
8786
"public class Test {public static void main(String[]args){System.out.println();}}");
8887
final int startOffset = 0;
8988
final int endOffset = myFixture.getFile().getTextLength();
9089
ApplicationManager.getApplication()
9190
.runWriteAction(
92-
new Runnable() {
93-
@Override
94-
public void run() {
95-
googleJavaFormat.reformatText(myFixture.getFile(), startOffset, endOffset);
96-
}
97-
});
91+
() -> googleJavaFormat.reformatText(myFixture.getFile(), startOffset, endOffset));
9892
myFixture.checkResult(
9993
"public class Test {public static void main(String[]args){System.out.println();}}");
10094
}
10195

10296
public void testFormatRanges() {
10397
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
10498
final GoogleJavaFormatCodeStyleManager googleJavaFormat =
105-
new GoogleJavaFormatCodeStyleManager(codeStyleManager);
99+
new GoogleJavaFormatCodeStyleManager(
100+
codeStyleManager, JavaFormatterOptions.defaultOptions());
106101
String content =
107102
join(
108103
"public class Test {", //
@@ -118,13 +113,7 @@ public void testFormatRanges() {
118113
final ImmutableList<TextRange> ranges =
119114
ImmutableList.of(new TextRange(aLineStart, aLineEnd), new TextRange(cLineStart, cLineEnd));
120115
ApplicationManager.getApplication()
121-
.runWriteAction(
122-
new Runnable() {
123-
@Override
124-
public void run() {
125-
googleJavaFormat.reformatText(myFixture.getFile(), ranges);
126-
}
127-
});
116+
.runWriteAction(() -> googleJavaFormat.reformatText(myFixture.getFile(), ranges));
128117
myFixture.checkResult(
129118
join(
130119
"public class Test {", //

0 commit comments

Comments
 (0)