void (final Project project, ModPsiUpdater updater, PsiExpression expression) { PsiType type = Objects.requireNonNull(expression.getType()); final PsiType[] types = Stream.of(new TypeSelectorManagerImpl(project, type, expression, PsiExpression.EMPTY_ARRAY).getTypesForAll()) .filter(SurroundAutoCloseableAction::rightType) .toArray(PsiType[]::new); TypeExpression typeExpression = new TypeExpression(project, types); PsiStatement statement = (PsiStatement)expression.getParent(); CommentTracker commentTracker = new CommentTracker(); final List<String> names = new VariableNameGenerator(expression, VariableKind.LOCAL_VARIABLE).byType(type).byExpression(expression) .generateAll(true); String text = "try (" + type.getCanonicalText(true) + " " + names.get(0) + " = " + commentTracker.text(expression) + ") {}"; PsiTryStatement tryStatement = (PsiTryStatement)commentTracker.replaceAndRestoreComments(statement, text); tryStatement = (PsiTryStatement)CodeStyleManager.getInstance(project).reformat(tryStatement); tryStatement = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(tryStatement); PsiResourceList resourceList = tryStatement.getResourceList(); if (resourceList != null) { final PsiResourceVariable var = (PsiResourceVariable)resourceList.iterator().next(); final PsiIdentifier id = var.getNameIdentifier(); PsiExpression initializer = var.getInitializer(); if (id != null && initializer != null) { updater.templateBuilder() .field(id, new ConstantNode(var.getName()).withLookupStrings(names)) .field(var.getTypeElement(), typeExpression); } } }