diff --git a/java/java-tests/testData/codeInsight/joinLines/IfChainSelection.java b/java/java-tests/testData/codeInsight/joinLines/IfChainSelection.java
new file mode 100644
index 000000000000..4b70f5a32251
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/joinLines/IfChainSelection.java
@@ -0,0 +1,14 @@
+class Foo {
+ void test() {
+ int a = 2;
+ int b = 2;
+
+ if (a == b){
+ if (a > b){
+ System.out.println();
+ }
+ }
+
+ System.out.println();
+ }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/joinLines/IfChainSelection_after.java b/java/java-tests/testData/codeInsight/joinLines/IfChainSelection_after.java
new file mode 100644
index 000000000000..13df0f38a745
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/joinLines/IfChainSelection_after.java
@@ -0,0 +1,10 @@
+class Foo {
+ void test() {
+ int a = 2;
+ int b = 2;
+
+ if (a == b && a > b) System.out.println();
+
+ System.out.println();
+ }
+}
\ No newline at end of file
diff --git a/java/java-tests/testSrc/com/intellij/java/codeInsight/JoinLinesTest.java b/java/java-tests/testSrc/com/intellij/java/codeInsight/JoinLinesTest.java
index e6431e74a0f2..0316421a7e60 100644
--- a/java/java-tests/testSrc/com/intellij/java/codeInsight/JoinLinesTest.java
+++ b/java/java-tests/testSrc/com/intellij/java/codeInsight/JoinLinesTest.java
@@ -56,6 +56,7 @@ public class JoinLinesTest extends LightCodeInsightTestCase {
public void testIfChainPolyadic() { doTest(); }
public void testIfChainNoBraces() { doTest(); }
public void testIfChainElse() { doTest(); }
+ public void testIfChainSelection() { doTest(); }
public void testSCR3493() {
CommonCodeStyleSettings settings = getJavaSettings();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java
index 89642559f114..95c4a03f8b52 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/JoinLinesHandler.java
@@ -88,11 +88,16 @@ public class JoinLinesHandler extends EditorActionHandler {
Ref caretRestoreOffset = new Ref<>(-1);
CodeEditUtil.setNodeReformatStrategy(node -> node.getTextRange().getStartOffset() >= startReformatOffset);
try {
- for (int count = 0; count < lineCount; count++) {
+ int count = 0;
+ while (count < lineCount) {
indicator.checkCanceled();
indicator.setFraction(((double)count) / lineCount);
+ int beforeLines = doc.getLineCount();
ProgressManager.getInstance().executeNonCancelableSection(
() -> doJoinTwoLines(doc, project, docManager, psiFile, line, caretRestoreOffset));
+ int afterLines = doc.getLineCount();
+ // Single Join two lines procedure could join more than two (e.g. if it removes braces)
+ count += Math.max(beforeLines - afterLines, 1);
}
}
finally {