void (@NotNull PyTargetExpression target, TypeEvalContext context, @NotNull AnnotationInfo info, boolean startTemplate) { if (!FileModificationService.getInstance().preparePsiElementForWrite(target)) return; final String typeCommentText = " " + TYPE_COMMENT_PREFIX + info.getAnnotationText(); final PyStatement statement = PsiTreeUtil.getParentOfType(target, PyStatement.class); final PsiElement insertionAnchor; if (statement instanceof PyAssignmentStatement) { insertionAnchor = statement.getLastChild(); } else if (statement instanceof PyWithStatement) { insertionAnchor = PyUtil.getHeaderEndAnchor((PyStatementListContainer)statement); } else if (statement instanceof PyForStatement) { insertionAnchor = PyUtil.getHeaderEndAnchor(((PyForStatement)statement).getForPart()); } else { throw new IllegalArgumentException("Target expression must belong to an assignment, \"with\" statement or \"for\" loop"); } final ThrowableRunnable<RuntimeException> insertComment; if (insertionAnchor instanceof PsiComment) { final String combinedTypeCommentText = typeCommentText + " " + insertionAnchor.getText(); final PsiElement lastNonComment = PyPsiUtils.getPrevNonCommentSibling(insertionAnchor, true); final int startOffset = lastNonComment.getTextRange().getEndOffset(); final int endOffset = insertionAnchor.getTextRange().getEndOffset(); insertComment = () -> PyUtil.updateDocumentUnblockedAndCommitted(target, document -> { document.replaceString(startOffset, endOffset, combinedTypeCommentText); }); } else if (insertionAnchor != null) { final int offset = insertionAnchor.getTextRange().getEndOffset(); insertComment = () -> PyUtil.updateDocumentUnblockedAndCommitted(target, document -> { document.insertString(offset, typeCommentText); }); } else { return; } WriteAction.run(() -> { insertComment.run(); PsiComment insertedComment = target.getTypeComment(); if (insertedComment == null) return; addImportsForTypeAnnotations(info.getTypes(), context, target.getContainingFile()); insertedComment = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(insertedComment); if (startTemplate && insertedComment != null) { openEditorAndAddTemplateForTypeComment(insertedComment, info.getAnnotationText(), info.getTypeRanges()); } }); }