YAMLValue (InsertionContext context, @NotNull PsiElement elementAtCaret) { final YAMLValue oldValue; if (elementAtCaret.getNode().getElementType() != YAMLTokenTypes.SCALAR_KEY) { deleteLookupPlain(context); return null; } final YAMLKeyValue keyValue = PsiTreeUtil.getParentOfType(elementAtCaret, YAMLKeyValue.class); assert keyValue != null; assert keyValue.getParentMapping() != null; Document document = context.getDocument(); String text = document.getText(TextRange.create(context.getStartOffset(), context.getTailOffset())); if (!keyValue.getKeyText().equals(text)) { // Insertion was performed at the start of existing keyValue, we should delete only inserted text from the key. document.deleteString(context.getStartOffset(), context.getTailOffset()); context.commitDocument(); return null; } context.commitDocument(); if (keyValue.getValue() != null) { // Save old value somewhere final YAMLKeyValue dummyKV = YAMLElementGenerator.getInstance(context.getProject()).createYamlKeyValue("foo", "b"); dummyKV.setValue(keyValue.getValue()); oldValue = dummyKV.getValue(); } else { oldValue = null; } context.setTailOffset(keyValue.getTextRange().getEndOffset()); WriteCommandAction.runWriteCommandAction(context.getProject(), YAMLBundle.message("YamlKeyCompletionInsertHandler.remove.key"), null, () -> { YAMLMapping parentMapping = keyValue.getParentMapping(); boolean delete = parentMapping.getNode().getChildren(null).length == 1; parentMapping.deleteKeyValue(keyValue); if (delete) { parentMapping.delete(); } }); return oldValue; }