void (@NotNull PsiLocalVariable outOfScopeVariable, @NotNull PsiReferenceExpression reference) { PsiFile file = outOfScopeVariable.getContainingFile(); Project project = file.getProject(); outOfScopeVariable.normalizeDeclaration(); PsiUtil.setModifierProperty(outOfScopeVariable, PsiModifier.FINAL, false); PsiElement commonParent = PsiTreeUtil.findCommonParent(outOfScopeVariable, reference); LOG.assertTrue(commonParent != null); PsiElement child = outOfScopeVariable.getTextRange().getStartOffset() < reference.getTextRange().getStartOffset() ? outOfScopeVariable : reference; while(child.getParent() != commonParent) child = child.getParent(); PsiDeclarationStatement newDeclaration = (PsiDeclarationStatement)JavaPsiFacade.getElementFactory(project) .createStatementFromText("int i = 0", null); PsiVariable variable = (PsiVariable)newDeclaration.getDeclaredElements()[0].replace(outOfScopeVariable); if (variable.getInitializer() != null) { PsiTypeElement typeElement = variable.getTypeElement(); if (typeElement != null && typeElement.isInferredType()) { PsiTypesUtil.replaceWithExplicitType(typeElement); } variable.getInitializer().delete(); } while(!(child instanceof PsiStatement) || !(child.getParent() instanceof PsiCodeBlock)) { child = child.getParent(); commonParent = commonParent.getParent(); } LOG.assertTrue(commonParent != null); PsiDeclarationStatement added = (PsiDeclarationStatement)commonParent.addBefore(newDeclaration, child); final PsiElement[] declaredElements = added.getDeclaredElements(); LOG.assertTrue(declaredElements.length > 0, added.getText()); PsiLocalVariable addedVar = (PsiLocalVariable)declaredElements[0]; assert addedVar != null : added; CodeStyleManager.getInstance(project).reformat(commonParent); //Leave initializer assignment PsiExpression initializer = outOfScopeVariable.getInitializer(); if (initializer != null) { PsiExpressionStatement assignment = (PsiExpressionStatement)JavaPsiFacade.getElementFactory(project).createStatementFromText( outOfScopeVariable.getName() + "= e;", null); Objects.requireNonNull(((PsiAssignmentExpression)assignment.getExpression()).getRExpression()).replace(initializer); assignment = (PsiExpressionStatement)CodeStyleManager.getInstance(project).reformat(assignment); PsiDeclarationStatement declStatement = PsiTreeUtil.getParentOfType(outOfScopeVariable, PsiDeclarationStatement.class); LOG.assertTrue(declStatement != null); PsiElement parent = declStatement.getParent(); if (parent instanceof PsiForStatement) { declStatement.replace(assignment); } else { parent.addAfter(assignment, declStatement); } } if (outOfScopeVariable.isValid()) { outOfScopeVariable.delete(); } if (HighlightControlFlowUtil.checkVariableInitializedBeforeUsage(reference, addedVar, new HashMap<>(), file) != null) { initialize(addedVar); } }