void (final Project myProject, final Editor editor, final List<? extends TemplateGenerationInfo> templates, final int index) { TemplateGenerationInfo info = templates.get(index); final Template template = info.getTemplate(); PsiElement element = Objects.requireNonNull(info.getPsiMember()); final TextRange range = element.getTextRange(); WriteAction.run(() -> editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset())); int offset = range.getStartOffset(); editor.getCaretModel().moveToOffset(offset); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); TemplateManager.getInstance(myProject).startTemplate(editor, template, new TemplateEditingAdapter() { @Override public void templateFinished(@NotNull Template template, boolean brokenOff) { if (index + 1 < templates.size()){ ApplicationManager.getApplication().invokeLater(() -> WriteCommandAction.runWriteCommandAction(myProject, ()-> runTemplates(myProject, editor, templates, index + 1) )); } } }); }