下面列出了怎么用 com.intellij.codeInsight.completion.InsertHandler 的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @param qualifiedName the name of the class to create lookup
* @param project to find the lookup annotation class
* @param insertHandler adds custom actions to the insert handling
* @throws IncorrectOperationException if the qualifiedName does not specify a valid type
* @return new {@link LookupElement} or cached instance if it was created previously
*/
static LookupElement create(
String qualifiedName, Project project, InsertHandler<LookupElement> insertHandler)
throws IncorrectOperationException {
if (CACHE.containsKey(qualifiedName)) {
return CACHE.get(qualifiedName);
}
PsiClass typeCls = PsiSearchUtils.findClass(project, qualifiedName);
if (typeCls != null) {
SpecLookupElement lookupElement = new SpecLookupElement(typeCls, insertHandler);
CACHE.put(qualifiedName, lookupElement);
return lookupElement;
}
// This is a dummy class, we don't want to cache it.
typeCls =
JavaPsiFacade.getInstance(project)
.getElementFactory()
.createClass(LithoClassNames.shortName(qualifiedName));
return new SpecLookupElement(typeCls, insertHandler);
}
@Nullable
@Override
protected InsertHandler<LookupElement> createInsertHandler(@Nonnull VcsRef item) {
return (context, item1) -> {
mySelectedRef = (VcsRef)item1.getObject();
ApplicationManager.getApplication().invokeLater(() -> {
// handleInsert is called in the middle of some other code that works with editor
// (see CodeCompletionHandlerBase.insertItem)
// for example, scrolls editor
// problem is that in onOk we make text field not editable
// by some reason this is done by disposing its editor and creating a new one
// so editor gets disposed here and CodeCompletionHandlerBase can not finish doing whatever it is doing with it
// I counter this by invoking onOk in invokeLater
myTextField.onOk();
});
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LookupElementBuilder that = (LookupElementBuilder)o;
final InsertHandler<LookupElement> insertHandler = that.myInsertHandler;
if (myInsertHandler != null && insertHandler != null ? !myInsertHandler.getClass().equals(insertHandler.getClass()) : myInsertHandler != insertHandler) {
return false;
}
if (!myLookupString.equals(that.myLookupString)) return false;
if (!myObject.equals(that.myObject)) return false;
final LookupElementRenderer<LookupElement> renderer = that.myRenderer;
if (myRenderer != null && renderer != null ? !myRenderer.getClass().equals(renderer.getClass()) : myRenderer != renderer) return false;
return true;
}
public LookupElementBuilder createLookupBuilder(@Nonnull final T item) {
LookupElementBuilder builder = LookupElementBuilder.create(item, getLookupString(item))
.withIcon(getIcon(item));
final InsertHandler<LookupElement> handler = createInsertHandler(item);
if (handler != null) {
builder = builder.withInsertHandler(handler);
}
final String tailText = getTailText(item);
if (tailText != null) {
builder = builder.withTailText(tailText, true);
}
final String typeText = getTypeText(item);
if (typeText != null) {
builder = builder.withTypeText(typeText);
}
return builder;
}
@Nonnull
@Override
public LookupElementBuilder createLookupBuilder(@Nonnull T item) {
LookupElementBuilder builder = LookupElementBuilder.create(item, getLookupString(item))
.withIcon(getIcon(item));
InsertHandler<LookupElement> handler = createInsertHandler(item);
if (handler != null) {
builder = builder.withInsertHandler(handler);
}
String tailText = getTailText(item);
if (tailText != null) {
builder = builder.withTailText(tailText, true);
}
String typeText = getTypeText(item);
if (typeText != null) {
builder = builder.withTypeText(typeText);
}
return builder;
}
ReplacingConsumer(
Collection<String> replacedQualifiedNames,
CompletionResultSet result,
InsertHandler<LookupElement> insertHandler) {
this.replacedQualifiedNames = new HashSet<>(replacedQualifiedNames);
this.result = result;
this.insertHandler = insertHandler;
}
private static InsertHandler<LookupElement> insertDivider(SectionParser parser) {
return (context, item) -> {
Editor editor = context.getEditor();
Document document = editor.getDocument();
context.commitDocument();
String nextTokenText = findNextTokenText(context);
if (nextTokenText == null || nextTokenText.equals("\n")) {
document.insertString(context.getTailOffset(), getDivider(parser));
editor.getCaretModel().moveToOffset(context.getTailOffset());
}
};
}
private static InsertHandler<LookupElement> getInsertHandler(
BuildFile file, String packageLocation, String symbol) {
ParenthesesInsertHandler<LookupElement> base =
ParenthesesInsertHandler.getInstance(/* hasParameters= */ true);
return (context, item) -> {
base.handleInsert(context, item);
insertLoadStatement(context, file, packageLocation, symbol);
};
}
private static InsertHandler<LookupElement> getInsertHandler(
String ruleName, @Nullable BuildLanguageSpec spec) {
if (spec == null) {
return ParenthesesInsertHandler.getInstance(true);
}
return RulesTemplates.templateForRule(ruleName, spec)
.map(BuiltInFunctionCompletionContributor::createTemplateInsertHandler)
.orElse(ParenthesesInsertHandler.getInstance(true));
}
@Nonnull
public static InsertHandler<LookupElement> buildInsertHandler(final IElementType elementType)
{
char open = '(';
char close = ')';
if(elementType == DO_KEYWORD || elementType == TRY_KEYWORD || elementType == CATCH_KEYWORD || elementType == UNSAFE_KEYWORD || elementType == FINALLY_KEYWORD)
{
open = '{';
close = '}';
}
return new ExpressionOrStatementInsertHandler<>(open, close);
}
private LookupElementBuilder(@Nonnull String lookupString,
@Nonnull Object object,
@Nullable InsertHandler<LookupElement> insertHandler,
@Nullable LookupElementRenderer<LookupElement> renderer,
@Nullable LookupElementPresentation hardcodedPresentation,
@Nonnull Set<String> allLookupStrings,
boolean caseSensitive) {
myLookupString = lookupString;
myObject = object;
myInsertHandler = insertHandler;
myRenderer = renderer;
myHardcodedPresentation = hardcodedPresentation;
myAllLookupStrings = Collections.unmodifiableSet(allLookupStrings);
myCaseSensitive = caseSensitive;
}
@Override
public void handleInsert(final InsertionContext context) {
final InsertHandler<? extends LookupElement> handler = getInsertHandler();
if (handler != null) {
//noinspection unchecked
((InsertHandler)handler).handleInsert(context, this);
}
if (getTailType() != TailType.UNKNOWN && myInsertHandler == null) {
context.setAddCompletionChar(false);
final TailType type = handleCompletionChar(context.getEditor(), this, context.getCompletionChar());
type.processTail(context.getEditor(), context.getTailOffset());
}
}
private static LookupElement[] initLookupItems(LinkedHashSet<String> names,
PsiNamedElement elementToRename,
PsiElement nameSuggestionContext,
final boolean shouldSelectAll) {
if (names == null) {
names = new LinkedHashSet<String>();
for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, nameSuggestionContext, names);
if (suggestedNameInfo != null &&
provider instanceof PreferrableNameSuggestionProvider &&
!((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
break;
}
}
}
final LookupElement[] lookupElements = new LookupElement[names.size()];
final Iterator<String> iterator = names.iterator();
for (int i = 0; i < lookupElements.length; i++) {
final String suggestion = iterator.next();
lookupElements[i] = LookupElementBuilder.create(suggestion).withInsertHandler(new InsertHandler<LookupElement>() {
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
if (shouldSelectAll) return;
final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor());
final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
if (templateState != null) {
final TextRange range = templateState.getCurrentVariableRange();
if (range != null) {
topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion);
}
}
}
});
}
return lookupElements;
}
static LookupElement create(
LookupElement delegate, String qualifiedName, InsertHandler<LookupElement> insertHandler) {
SpecLookupElement lookupElement = new SpecLookupElement(delegate, insertHandler);
CACHE.put(qualifiedName, lookupElement);
return lookupElement;
}
private SpecLookupElement(PsiClass typeCls, InsertHandler<LookupElement> insertHandler) {
this(JavaClassNameCompletionContributor.createClassLookupItem(typeCls, true), insertHandler);
}
private SpecLookupElement(
LookupElement delegate, InsertHandler<LookupElement> lookupElementDecoratorInsertHandler) {
super(delegate);
insertHandler = lookupElementDecoratorInsertHandler;
}
public UserFuncLookupElement(@NotNull String name, @NotNull StubIndexKey indexKey, @NotNull Icon ico, PhpType phpType, @NotNull Project project, InsertHandler handler) {
super(name, indexKey, ico, phpType, project, handler);
}
public UserFuncLookupElement(@NotNull String name, @NotNull StubIndexKey indexKey, @NotNull Project project, InsertHandler handler) {
super(name, indexKey, project, handler);
}
private LookupElementBuilder create(
final Value value, final InsertHandler<LookupElement> insertHandler) {
return LookupElementBuilder.create(value.getValue()).withInsertHandler(insertHandler);
}
private LookupElementBuilder create(
final Field field, final InsertHandler<LookupElement> insertHandler) {
return create(field).withInsertHandler(insertHandler);
}
public InsertHandler<LookupElement> createInsertFieldHandler(final Field field) {
return traversal.createInsertFieldHandler(field);
}
public InsertHandler<LookupElement> createInsertValueHandler(final Value value) {
return traversal.createInsertValueHandler(value);
}
@Override
public InsertHandler<LookupElement> createInsertFieldHandler(final Field field) {
return new YamlInsertFieldHandler(field);
}
@Override
public InsertHandler<LookupElement> createInsertValueHandler(final Value value) {
return new YamlInsertValueHandler();
}
@Override
public InsertHandler<LookupElement> createInsertFieldHandler(final Field field) {
return new JsonInsertFieldHandler(this, field);
}
@Override
public InsertHandler<LookupElement> createInsertValueHandler(final Value value) {
return new JsonInsertValueHandler(value);
}
private static InsertHandler<LookupElement> createTemplateInsertHandler(Template t) {
return (context, item) ->
TemplateManager.getInstance(context.getProject()).startTemplate(context.getEditor(), t);
}
@Nonnull
@RequiredReadAction
private static LookupElementBuilder buildLookupItem(UnityFunctionManager.FunctionInfo functionInfo, CSharpTypeDeclaration scope)
{
StringBuilder builder = new StringBuilder();
builder.append("void ");
builder.append(functionInfo.getName());
builder.append("(");
boolean first = true;
for(Map.Entry<String, String> entry : functionInfo.getParameters().entrySet())
{
if(first)
{
first = false;
}
else
{
builder.append(", ");
}
DotNetTypeRef typeRef = UnityFunctionManager.createTypeRef(scope, entry.getValue());
builder.append(CSharpTypeRefPresentationUtil.buildShortText(typeRef, scope));
builder.append(" ");
builder.append(entry.getKey());
}
builder.append(")");
String presentationText = builder.toString();
builder.append("{\n");
builder.append("}");
LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(builder.toString());
lookupElementBuilder = lookupElementBuilder.withPresentableText(presentationText);
lookupElementBuilder = lookupElementBuilder.withLookupString(functionInfo.getName());
lookupElementBuilder = lookupElementBuilder.withTailText("{...}", true);
IconDescriptor iconDescriptor = new IconDescriptor(new IconDescriptor(AllIcons.Nodes.Method).toIcon());
iconDescriptor.setRightIcon(Unity3dIcons.EventMethod);
lookupElementBuilder = lookupElementBuilder.withIcon(iconDescriptor.toIcon());
lookupElementBuilder = lookupElementBuilder.withInsertHandler(new InsertHandler<LookupElement>()
{
@Override
@RequiredUIAccess
public void handleInsert(InsertionContext context, LookupElement item)
{
CaretModel caretModel = context.getEditor().getCaretModel();
PsiElement elementAt = context.getFile().findElementAt(caretModel.getOffset() - 1);
if(elementAt == null)
{
return;
}
DotNetVirtualImplementOwner virtualImplementOwner = PsiTreeUtil.getParentOfType(elementAt, DotNetVirtualImplementOwner.class);
if(virtualImplementOwner == null)
{
return;
}
if(virtualImplementOwner instanceof CSharpMethodDeclaration)
{
PsiElement codeBlock = ((CSharpMethodDeclaration) virtualImplementOwner).getCodeBlock().getElement();
if(codeBlock instanceof CSharpBlockStatementImpl)
{
DotNetStatement[] statements = ((CSharpBlockStatementImpl) codeBlock).getStatements();
if(statements.length > 0)
{
caretModel.moveToOffset(statements[0].getTextOffset() + statements[0].getTextLength());
}
else
{
caretModel.moveToOffset(((CSharpBlockStatementImpl) codeBlock).getLeftBrace().getTextOffset() + 1);
}
}
}
context.commitDocument();
CodeStyleManager.getInstance(context.getProject()).reformat(virtualImplementOwner);
}
});
return lookupElementBuilder;
}
public void withInsertHandler(InsertHandler<RouteLookupElement> insertHandler) {
this.insertHandler = insertHandler;
}
public DoctrineTypeLookup(String typeName, InsertHandler<LookupElement> insertHandler) {
this.name = typeName;
this.insertHandler = insertHandler;
}