PsiStatement (@NotNull Project project, @NotNull PsiElementFactory factory) { PsiResourceList list = Objects.requireNonNull(myStatement.getResourceList()); PsiTryStatement copy = (PsiTryStatement)myStatement.copy(); PsiResourceList copyList = copy.getResourceList(); if (copyList == null) return myStatement; PsiCodeBlock tryBlock = myStatement.getTryBlock(); if (tryBlock == null) return myStatement; List<PsiResourceListElement> elementsToMove = StreamEx.of(list.iterator()).dropWhile(e -> e != myVariable).toList(); for (PsiResourceListElement element : elementsToMove) { element.delete(); } for (PsiResourceListElement element : StreamEx.of(copyList.iterator()) .limit(copyList.getResourceVariablesCount() - elementsToMove.size()).toList()) { element.delete(); } PsiElement[] children = copyList.getChildren(); if (children[0].textMatches("(") && children[1] instanceof PsiWhiteSpace) { children[1].delete(); } for (PsiCatchSection section : copy.getCatchSections()) { section.delete(); } PsiCodeBlock copyFinally = copy.getFinallyBlock(); if (copyFinally != null) { PsiElement element = PsiTreeUtil.skipWhitespacesAndCommentsBackward(copyFinally); if (element != null && element.textMatches(PsiKeyword.FINALLY)) { element.delete(); } copyFinally.delete(); } PsiElement codeBlock = tryBlock.replace(factory.createCodeBlock()); return (PsiStatement)codeBlock.add(copy); }