void (Project project, ModPsiUpdater updater, PsiLocalVariable variable) { PsiExpression initializer = Objects.requireNonNull(variable.getInitializer()); PsiElement declaration = variable.getParent(); PsiElement codeBlock = declaration.getParent(); LocalSearchScope scope = new LocalSearchScope(codeBlock); PsiElement last = null; for (PsiReference reference : ReferencesSearch.search(variable, scope).findAll()) { PsiElement usage = PsiTreeUtil.findPrevParent(codeBlock, reference.getElement()); if ((last == null || usage.getTextOffset() > last.getTextOffset())) { last = usage; } } CommentTracker tracker = new CommentTracker(); String text = "try (" + variable.getTypeElement().getText() + " " + variable.getName() + " = " + tracker.text(initializer) + ") {}"; PsiTryStatement armStatement = (PsiTryStatement)JavaPsiFacade.getElementFactory(project).createStatementFromText(text, declaration); List<PsiElement> toFormat = null; if (last != null) { toFormat = moveStatements(last, declaration, armStatement); } armStatement = (PsiTryStatement)tracker.replaceAndRestoreComments(declaration, armStatement); CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); PsiElement formattedElement = codeStyleManager.reformat(armStatement); if (toFormat != null) { for (PsiElement psiElement : toFormat) { codeStyleManager.reformat(psiElement); } } if (last == null) { PsiCodeBlock tryBlock = ((PsiTryStatement)formattedElement).getTryBlock(); if (tryBlock != null) { PsiJavaToken brace = tryBlock.getLBrace(); if (brace != null) { updater.moveTo(brace.getTextOffset() + 1); } } } }