int (@NotNull final Document document, @NotNull final PsiFile file, final int start, final int end) { PsiElement elementAtStartLineEnd = file.findElementAt(start); PsiElement elementAtNextLineStart = file.findElementAt(end); if (elementAtStartLineEnd == null || elementAtNextLineStart == null) return -1; // first line. if (!PsiUtil.isJavaToken(elementAtStartLineEnd, JavaTokenType.SEMICOLON)) return -1; PsiLocalVariable var = ObjectUtils.tryCast(elementAtStartLineEnd.getParent(), PsiLocalVariable.class); if (var == null) return -1; if (!(var.getParent() instanceof PsiDeclarationStatement decl)) return -1; if (decl.getDeclaredElements().length > 1) return -1; //second line. if (!PsiUtil.isJavaToken(elementAtNextLineStart, JavaTokenType.IDENTIFIER)) return -1; if (!(elementAtNextLineStart.getParent() instanceof PsiReferenceExpression ref)) return -1; PsiElement refResolved = ref.resolve(); PsiManager psiManager = ref.getManager(); if (!psiManager.areElementsEquivalent(refResolved, var)) return -1; if (!(ref.getParent() instanceof PsiAssignmentExpression assignment)) return -1; if (!(assignment.getParent() instanceof PsiExpressionStatement statement)) return -1; PsiExpression rExpression = assignment.getRExpression(); if (rExpression == null) return -1; if (ReferencesSearch.search(var, new LocalSearchScope(rExpression), false).findFirst() != null) { return -1; } final PsiExpression initializerExpression = getInitializerExpression(var, assignment); if (initializerExpression == null) return -1; int startOffset = decl.getTextRange().getStartOffset(); try { PsiLocalVariable variable = copyVarWithInitializer(var, initializerExpression); if (variable == null) return -1; PsiDeclarationStatement newDecl = (PsiDeclarationStatement)variable.getParent(); final int offsetBeforeEQ = Objects.requireNonNull(variable.getNameIdentifier()).getTextRange().getEndOffset(); final int offsetAfterEQ = Objects.requireNonNull(variable.getInitializer()).getTextRange().getStartOffset() + 1; newDecl = (PsiDeclarationStatement)CodeStyleManager.getInstance(psiManager).reformatRange(newDecl, offsetBeforeEQ, offsetAfterEQ); PsiElement child = statement.getLastChild(); while (child instanceof PsiComment || child instanceof PsiWhiteSpace) { child = child.getPrevSibling(); } if (child != null && child.getNextSibling() != null) { newDecl.addRangeBefore(child.getNextSibling(), statement.getLastChild(), null); } PsiElement prev = statement.getPrevSibling(); if (prev instanceof PsiWhiteSpace) { prev.delete(); } statement.delete(); decl.replace(newDecl); return startOffset + newDecl.getTextRange().getEndOffset() - newDecl.getTextRange().getStartOffset(); } catch (IncorrectOperationException e) { LOG.error(e); return -1; } }