builder.replaceElement(pattern,
new TextRange(1, patternText.length() - 1),
patternText.substring(1, patternText.length() - 1));
// block vars
GrClosableBlock closure = methodCall.getClosureArguments()[0];
final GrParameter[] blockVars = closure.getAllParameters();
for (GrParameter var : blockVars) {
PsiElement identifier = var.getNameIdentifierGroovy();
builder.replaceElement(identifier, identifier.getText());
}
TemplateManager manager = TemplateManager.getInstance(project);
final Editor editorToRunTemplate;
if (editor == null) {
editorToRunTemplate = IntentionUtils.positionCursor(project, file, methodCall);
}
else {
editorToRunTemplate = editor;
}
Template template = builder.buildTemplate();
TextRange range = methodCall.getTextRange();
editorToRunTemplate.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
editorToRunTemplate.getCaretModel().moveToOffset(range.getStartOffset());
manager.startTemplate(editorToRunTemplate, template, new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
if (brokenOff) return;
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
PsiDocumentManager.getInstance(project).commitDocument(editorToRunTemplate.getDocument());
final int offset = editorToRunTemplate.getCaretModel().getOffset();
GrMethodCall methodCall = PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, GrMethodCall.class, false);
if (methodCall != null) {
GrClosableBlock[] closures = methodCall.getClosureArguments();
if (closures.length == 1) {
GrClosableBlock closure = closures[0];
selectBody(closure, editor);
}
}
}
});