void (@NotNull PsiStatement statement, PsiStatement blockCandidate) { if (!statement.isValid()) { LOG.assertTrue(false); } if (!checkRangeContainsElement(blockCandidate)) return; if (blockCandidate instanceof PsiEmptyStatement) return; final PsiManager manager = statement.getManager(); LOG.assertTrue(manager != null); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); String oldText = blockCandidate.getText(); // There is a possible case that target block to wrap ends with single-line comment. Example: // if (true) i = 1; // Cool assignment // We can't just surround target block of code with curly braces because the closing one will be treated as comment as well. // Hence, we perform a check if we have such situation at the moment and insert new line before the closing brace. int lastLineFeedIndex = oldText.lastIndexOf("\n"); lastLineFeedIndex = Math.max(0, lastLineFeedIndex); int lastLineCommentIndex = oldText.indexOf("//", lastLineFeedIndex); StringBuilder buf = new StringBuilder(oldText.length() + 5); buf.append("{ ").append(oldText); if (lastLineCommentIndex >= 0) { buf.append("\n"); } buf.append(" }"); final int oldTextLength = statement.getTextLength(); try { CodeEditUtil.replaceChild(SourceTreeToPsiMap.psiElementToTree(statement), SourceTreeToPsiMap.psiElementToTree(blockCandidate), SourceTreeToPsiMap.psiElementToTree(factory.createStatementFromText(buf.toString(), null))); CodeStyleManager.getInstance(statement.getProject()).reformat(statement, true); } catch (IncorrectOperationException e) { LOG.error(e); } finally { updateResultRange(oldTextLength , statement.getTextLength()); } }