LookupElementBuilder (final String key, final boolean addHandler) { LookupElementBuilder item; item = LookupElementBuilder .create(key) .withTypeText("dict key") .withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Parameter)); if (addHandler) { item = item.withInsertHandler(new InsertHandler<>() { @Override public void handleInsert(@NotNull final InsertionContext context, @NotNull final LookupElement item) { final PyStringLiteralExpression str = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PyStringLiteralExpression.class, false); if (str != null) { final boolean isDictKeys = PsiTreeUtil.getParentOfType(str, PySubscriptionExpression.class) != null; if (isDictKeys) { final int off = context.getStartOffset() + str.getTextLength(); final PsiElement element = context.getFile().findElementAt(off); final boolean atRBrace = element == null || element.getNode().getElementType() == PyTokenTypes.RBRACKET; final boolean badQuoting = (!StringUtil.startsWithChar(str.getText(), '\'') || !StringUtil.endsWithChar(str.getText(), '\'')) && (!StringUtil.startsWithChar(str.getText(), '"') || !StringUtil.endsWithChar(str.getText(), '"')); if (badQuoting || !atRBrace) { final Document document = context.getEditor().getDocument(); final int offset = context.getTailOffset(); document.deleteString(offset - 1, offset); } } } } }); } return item; }