int (@NotNull final Document document, @NotNull final PsiFile psiFile, final int start, final int end) { PsiElement elementAtStartLineEnd = psiFile.findElementAt(start); PsiElement elementAtNextLineStart = psiFile.findElementAt(end); if (elementAtStartLineEnd == null || elementAtNextLineStart == null) return -1; if (!PsiUtil.isJavaToken(elementAtStartLineEnd, JavaTokenType.LBRACE)) { return -1; } final PsiElement codeBlock = elementAtStartLineEnd.getParent(); if (!(codeBlock instanceof PsiCodeBlock)) return -1; if (!(codeBlock.getParent() instanceof PsiBlockStatement)) return -1; final PsiElement parentStatement = codeBlock.getParent().getParent(); if (getForceBraceSetting(parentStatement) == CommonCodeStyleSettings.FORCE_BRACES_ALWAYS) { return CANNOT_JOIN; } PsiElement foundStatement = null; for (PsiElement element = elementAtStartLineEnd.getNextSibling(); element != null; element = element.getNextSibling()) { if (element instanceof PsiWhiteSpace) continue; if (PsiUtil.isJavaToken(element, JavaTokenType.RBRACE) && element.getParent() == codeBlock) { if (foundStatement == null) return -1; break; } if (foundStatement != null) return -1; foundStatement = element; } if (!(foundStatement instanceof PsiStatement)) return -1; PsiElement parent = codeBlock.getParent(); if (isPotentialShortIf(foundStatement) && parent instanceof PsiBlockStatement) { PsiElement grandParent = parent.getParent(); if (grandParent instanceof PsiIfStatement && ((PsiIfStatement)grandParent).getThenBranch() == parent && ((PsiIfStatement)grandParent).getElseBranch() != null) { /* like "if(...) {if(...){...}} else {...}" unwrapping the braces of outer 'if' then-branch will cause semantics change */ return -1; } } try { final PsiElement newStatement = parent.replace(foundStatement); return newStatement.getTextRange().getStartOffset(); } catch (IncorrectOperationException e) { LOG.error(e); } return -1; }