void (@NotNull AnActionEvent e) { Pair<PsiFile, Editor> fileAndEditor = getFileAndEditor(e); if (fileAndEditor == null) { return; } final Editor editor = fileAndEditor.getSecond(); final PsiFile file = fileAndEditor.getFirst(); Caret caret = editor.getCaretModel().getCurrentCaret(); final var elements = MarkdownActionUtil.getElementsUnderCaretOrSelection(file, caret); PsiElement link = MarkdownActionUtil.getCommonTopmostParentOfTypes(elements.getFirst(), elements.getSecond(), MarkdownTokenTypeSets.LINKS); if (link == null) { return; } Project project = link.getProject(); WriteCommandAction.runWriteCommandAction(file.getProject(), null, null, () -> { //disable postprocess reformatting, cause otherwise we will lose psi pointers after [doPostponedOperationsAndUnblockDocument] PostprocessReformattingAspect.getInstance(file.getProject()).disablePostprocessFormattingInside( () -> { if (!file.isValid()) { return; } Pair<PsiElement, PsiElement> referencePair = createLinkDeclarationAndReference(project, link, "reference"); insertLastNewLines(file, 2); PsiElement declaration = file.addAfter(referencePair.getSecond(), file.getLastChild()); PsiElement reference = link.replace(referencePair.getFirst()); String url = Objects.requireNonNull(PsiTreeUtil.getChildOfType(declaration, MarkdownLinkDestination.class)).getText(); PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); TemplateBuilderImpl builder = (TemplateBuilderImpl)TemplateBuilderFactory.getInstance().createTemplateBuilder(file); PsiElement declarationLabel = declaration.getFirstChild(); PsiElement referenceLabel = reference.getFirstChild().getLastChild(); Expression expression = ApplicationManager.getApplication().isUnitTestMode() ? new TextExpression("reference") : new EmptyExpression(); builder .replaceElement(declarationLabel, TextRange.create(1, declarationLabel.getTextLength() - 1), VAR_NAME, expression, true); builder .replaceElement(referenceLabel, TextRange.create(1, referenceLabel.getTextLength() - 1), VAR_NAME, expression, true); editor.getCaretModel().moveToOffset(0); Template template = builder.buildInlineTemplate(); PsiElement title = referencePair.getSecond().getLastChild(); String titleText = null; if (PsiUtilCore.getElementType(title) == LINK_TITLE) { titleText = title.getText(); } TemplateManager.getInstance(project).startTemplate(editor, template, new DuplicatesFinder(file, editor, url, titleText)); }); //reformat at the end PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument()); }); }