Java Code Examples for com.intellij.codeInsight.lookup.LookupElementBuilder#withInsertHandler()

The following examples show how to use com.intellij.codeInsight.lookup.LookupElementBuilder#withInsertHandler() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: intellij-spring-assistant   File: Suggestion.java    License: MIT License 6 votes vote down vote up
public LookupElementBuilder newLookupElement() {
  LookupElementBuilder builder = LookupElementBuilder.create(this, suggestionToDisplay);
  if (forValue) {
    if (description != null) {
      builder = builder.withTypeText(description, true);
    }
    if (representingDefaultValue) {
      builder = builder.bold();
    }
    builder = builder.withInsertHandler(fileType.newValueInsertHandler());
  } else {
    builder = builder.withRenderer(CUSTOM_SUGGESTION_RENDERER)
        .withInsertHandler(fileType.newKeyInsertHandler());
  }
  return builder;
}
 
Example 2
private boolean completeAnnotations(@NotNull CompletionResultSet result, boolean autoImport, PsiFile file, PsiElement completionElement) {
	final JSGraphQLEndpointFieldDefinition field = PsiTreeUtil.getNextSiblingOfType(completionElement, JSGraphQLEndpointFieldDefinition.class);
	final JSGraphQLEndpointProperty property = PsiTreeUtil.getNextSiblingOfType(completionElement, JSGraphQLEndpointProperty.class);
	final JSGraphQLEndpointAnnotation nextAnnotation = PsiTreeUtil.getNextSiblingOfType(completionElement, JSGraphQLEndpointAnnotation.class);
	final boolean afterAtAnnotation = completionElement.getNode().getElementType() == JSGraphQLEndpointTokenTypes.AT_ANNOTATION;
	final boolean isTopLevelCompletion = completionElement.getParent() instanceof JSGraphQLEndpointFile;
	if (afterAtAnnotation || isTopLevelCompletion || field != null || nextAnnotation != null || property != null) {
		final JSGraphQLConfigurationProvider configurationProvider = JSGraphQLConfigurationProvider.getService(file.getProject());
		for (JSGraphQLSchemaEndpointAnnotation endpointAnnotation : configurationProvider.getEndpointAnnotations(file)) {
			String completion = endpointAnnotation.name;
			if (!afterAtAnnotation) {
				completion = "@" + completion;
			}
			LookupElementBuilder element = LookupElementBuilder.create(completion).withIcon(JSGraphQLIcons.Schema.Attribute);
			if(endpointAnnotation.arguments != null && endpointAnnotation.arguments.size() > 0) {
				element = element.withInsertHandler(ParenthesesInsertHandler.WITH_PARAMETERS);
			}
			result.addElement(element);
		}
		return true;
	}
	return false;
}
 
Example 3
@Override
public void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    resultSet.stopHere();
    final String prefix = getPrefix(parameters);

    resultSet = resultSet.withPrefixMatcher(new GaugePrefixMatcher(prefix));
    Module moduleForPsiElement = GaugeUtil.moduleForPsiElement(parameters.getPosition());
    if (moduleForPsiElement == null) {
        return;
    }
    for (Type item : getStepsInModule(moduleForPsiElement)) {
        LookupElementBuilder element = LookupElementBuilder.create(item.getText()).withTypeText(item.getType(), true);
        element = element.withInsertHandler((InsertionContext context1, LookupElement item1) -> {
            if (context1.getCompletionChar() == '\t') {
                context1.getDocument().insertString(context1.getEditor().getCaretModel().getOffset(), "\n");
                PsiDocumentManager.getInstance(context1.getProject()).commitDocument(context1.getDocument());
            }
            PsiElement stepElement = context1.getFile().findElementAt(context1.getStartOffset()).getParent();
            final TemplateBuilder templateBuilder = TemplateBuilderFactory.getInstance().createTemplateBuilder(stepElement);
            replaceStepParamElements(prefix, context1, stepElement, templateBuilder);
            templateBuilder.run(context1.getEditor(), false);
        });
        resultSet.addElement(element);
    }
}
 
Example 4
private void attachTemplateTypeCompletions(@NotNull CompletionResultSet result, @NotNull Project project, @NotNull LatteFile file) {
	LattePhpType type = LatteUtil.findFirstLatteTemplateType(file);
	if (type == null) {
		return;
	}

	Collection<PhpClass> phpClasses = type.getPhpClasses(project);
	if (phpClasses != null) {
		for (PhpClass phpClass : phpClasses) {
			for (Field field : phpClass.getFields()) {
				if (!field.isConstant() && field.getModifier().isPublic()) {
					LookupElementBuilder builder = LookupElementBuilder.create(field, "$" + field.getName());
					builder = builder.withInsertHandler(PhpVariableInsertHandler.getInstance());
					builder = builder.withTypeText(LattePhpType.create(field.getType()).toString());
					builder = builder.withIcon(PhpIcons.VARIABLE);
					if (field.isDeprecated() || field.isInternal()) {
						builder = builder.withStrikeoutness(true);
					}
					result.addElement(builder);
				}
			}
		}
	}
}
 
Example 5
private LookupElementBuilder createBuilderForMacro(LatteTagSettings tag, boolean isEndTag) {
	String name = (isEndTag ? "/" : "") + tag.getMacroName();
	LookupElementBuilder builder = LookupElementBuilder.create(name);
	builder = builder.withInsertHandler(MacroInsertHandler.getInstance());
	if (!isEndTag) {
		String appendText = tag.getType() == LatteTagSettings.Type.PAIR ? (" … {/" + tag.getMacroName() + "}") : "";
		String arguments = tag.getArgumentsInfo();
		if (arguments.length() > 0) {
			builder = builder.withTailText(" " + arguments + "}" + appendText);
		} else {
			builder = builder.withTailText("}" + appendText);
		}
	} else {
		builder = builder.withTailText("}");
	}

	if (tag.isDeprecated()) {
		builder = builder.withStrikeoutness(true);
	}
	builder = builder.withPresentableText("{" + name);
	return builder.withIcon(LatteIcons.MACRO);
}
 
Example 6
private static void buildAccessorKeywordsCompletion(CompletionResultSet resultSet, final CSharpXAccessorOwner accessorOwner, @Nullable InsertHandler<LookupElement> insertHandler)
{
	TokenSet tokenSet = accessorOwner instanceof CSharpEventDeclaration ? TokenSet.create(CSharpSoftTokens.ADD_KEYWORD, CSharpSoftTokens.REMOVE_KEYWORD) : TokenSet.create(CSharpSoftTokens
			.GET_KEYWORD, CSharpSoftTokens.SET_KEYWORD);

	for(IElementType elementType : tokenSet.getTypes())
	{
		if(!isCanShowAccessorKeyword(elementType, accessorOwner))
		{
			continue;
		}
		LookupElementBuilder builder = LookupElementBuilder.create(CSharpCompletionUtil.textOfKeyword(elementType));
		builder = builder.bold();

		if(insertHandler != null)
		{
			builder = builder.withInsertHandler(insertHandler);
		}

		builder.putUserData(CSharpCompletionUtil.KEYWORD_ELEMENT_TYPE, elementType);

		resultSet.addElement(builder);
	}
}
 
Example 7
private static LookupElementBuilder withGenericInsertHandler(PsiElement element, LookupElementBuilder builder)
{
	if(!(element instanceof DotNetGenericParameterListOwner))
	{
		return builder;
	}

	int genericParametersCount = ((DotNetGenericParameterListOwner) element).getGenericParametersCount();
	if(genericParametersCount == 0)
	{
		return builder;
	}

	builder = builder.withInsertHandler(LtGtInsertHandler.getInstance(true));
	return builder;
}
 
Example 8
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;
}
 
Example 9
@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;
}
 
Example 10
/**
 * We need special logic to determine when it should insert "=" at the end of the options
 */
@NotNull
private static LookupElementBuilder addInsertHandler(final Editor editor, final LookupElementBuilder builder,
                                                     final String suffix) {
    return builder.withInsertHandler((context, item) -> {
        // enforce using replace select char as we want to replace any existing option
        if (context.getCompletionChar() == Lookup.NORMAL_SELECT_CHAR) {
            int endSelectOffBy = 0;
            if (context.getFile() instanceof PropertiesFileImpl) {
                //if it's a property file the PsiElement does not start and end with an quot
                endSelectOffBy = 1;
            }
            final char text = context
                    .getDocument()
                    .getCharsSequence()
                    .charAt(context.getSelectionEndOffset() - endSelectOffBy);
            if (text != '=') {
                EditorModificationUtil.insertStringAtCaret(editor, "=");
            }
        } else if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
            // we still want to keep the suffix because they are other options
            String value = suffix;
            final int pos = value.indexOf("&");
            if (pos > -1) {
                // strip out first part of suffix until next option
                value = value.substring(pos);
            }
            EditorModificationUtil.insertStringAtCaret(editor, "=" + value);
            // and move cursor back again
            final int offset = -1 * value.length();
            EditorModificationUtil.moveCaretRelatively(editor, offset);
        }

    });
}
 
Example 11
private void completeTopLevelKeywords() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
            final LogicalPosition completionPos = parameters.getEditor().offsetToLogicalPosition(parameters.getOffset());
            final PsiElement prevVisibleLeaf = PsiTreeUtil.prevVisibleLeaf(parameters.getPosition());
            if (prevVisibleLeaf != null) {
                // NOTE: "type Foo <completion>" would grammatically allow a new definition to follow immediately
                // but this completion at that position is likely to be unexpected and would interfere with "implements" on types
                // so we expect top level keywords to be the first visible element on the line to complete
                if (completionPos.line == parameters.getEditor().offsetToLogicalPosition(prevVisibleLeaf.getTextOffset()).line) {
                    return;
                }
            }
            for (String keyword : TOP_LEVEL_KEYWORDS) {
                // TODO filter schema if already declared
                LookupElementBuilder element = LookupElementBuilder.create(keyword).withBoldness(true);
                if (keyword.equals("{")) {
                    element = element.withInsertHandler((ctx, item) -> {
                        EditorModificationUtil.insertStringAtCaret(ctx.getEditor(), "}");
                        PsiDocumentManager.getInstance(ctx.getProject()).commitDocument(ctx.getEditor().getDocument());
                        ctx.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, false);
                    });
                } else {
                    element = element.withInsertHandler(AddSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP);
                }
                result.addElement(element);
            }
        }
    };
    extend(CompletionType.BASIC, TOP_LEVEL_KEYWORD_PATTERN, provider);
}
 
Example 12
private boolean completeKeywordsAndDefinitionAnnotations(@NotNull CompletionResultSet result, boolean autoImport, PsiElement completionElement, PsiElement leafBeforeCompletion, PsiElement parent) {
	if (parent instanceof JSGraphQLEndpointFile || isTopLevelError(parent)) {

		if (isKeyword(leafBeforeCompletion)) {
			// no keyword suggestions right after another keyword
			return true;
		}

		// implements after TYPE NamedType
		if(completeImplementsKeyword(result, completionElement)) {
			return true;
		}

		for (String keyword : TOP_LEVEL_KEYWORDS) {
			LookupElementBuilder element = LookupElementBuilder.create(keyword).withBoldness(true);
			if(keyword.equals(JSGraphQLEndpointTokenTypes.IMPORT.toString())) {
				element = element.withInsertHandler(JSGraphQLEndpointImportInsertHandler.INSTANCE_WITH_AUTO_POPUP);
			} else {
				element = element.withInsertHandler(AddSpaceInsertHandler.INSTANCE_WITH_AUTO_POPUP);
			}
			result.addElement(element);
		}

		completeAnnotations(result, autoImport, completionElement.getContainingFile(), completionElement);

		return true;

	}
	if(parent instanceof JSGraphQLEndpointAnnotation && parent.getParent() instanceof JSGraphQLEndpointNamedTypeDefinition) {
		// completing inside a definition/top level annotation
		return completeAnnotations(result, autoImport, completionElement.getContainingFile(), completionElement);
	}
	return false;
}
 
Example 13
private LookupElementBuilder withAutoImport(LookupElementBuilder element, JSGraphQLEndpointTypeResult typeResult, boolean autoImport) {
	if(autoImport && typeResult.fileToImport != null) {
		element = element.withInsertHandler(new JSGraphQLEndpointAutoImportInsertHandler(typeResult.fileToImport));
		element = element.withTypeText(typeResult.fileToImport.getName(), true);
	}
	return element;
}
 
Example 14
private LookupElementBuilder createBuilderWithHelp(LatteFunctionSettings settings) {
	LookupElementBuilder builder = LookupElementBuilder.create(settings.getFunctionName());
	builder = builder.withIcon(PhpIcons.FUNCTION_ICON);
	builder = builder.withInsertHandler(MacroCustomFunctionInsertHandler.getInstance());
	if (settings.getFunctionHelp().trim().length() > 0) {
		builder = builder.withTailText(settings.getFunctionHelp());
	}
	return builder.withTypeText(settings.getFunctionReturnType());
}
 
Example 15
private LookupElementBuilder createBuilderWithHelp(LatteFilterSettings modifier) {
	LookupElementBuilder builder = LookupElementBuilder.create(modifier.getModifierName());
	if (modifier.getModifierDescription().trim().length() > 0) {
		builder = builder.withTypeText(modifier.getModifierDescription());
	}
	if (modifier.getModifierHelp().trim().length() > 0) {
		builder = builder.withTailText(modifier.getModifierHelp());
	}
	builder = builder.withInsertHandler(FilterInsertHandler.getInstance());
	return builder.withIcon(LatteIcons.MODIFIER);
}
 
Example 16
@Nonnull
protected LookupElement installInsertHandler(@Nonnull LookupElementBuilder builder) {
  InsertHandler<LookupElement> handler = builder.getInsertHandler();
  if (handler == null) return builder.withInsertHandler(myInsertHandler);
  return builder.withInsertHandler(new InsertHandler<LookupElement>() {
    @Override
    public void handleInsert(InsertionContext context, LookupElement item) {
      myInsertHandler.handleInsert(context, item);
      handler.handleInsert(context, item);
    }
  });
}
 
Example 17
@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;
}
 
Example 18
private LookupElementBuilder createBuilderForTag(String name) {
	LookupElementBuilder builder = LookupElementBuilder.create(name);
	builder = builder.withInsertHandler(AttrMacroInsertHandler.getInstance());
	return builder.withIcon(LatteIcons.N_TAG);
}
 
Example 19
@Nonnull
@RequiredReadAction
private static LookupElement buildForMethodReference(final CSharpMethodDeclaration methodDeclaration, CSharpTypeDeclaration contextType, final CSharpReferenceExpressionEx expression)
{
	LookupElementBuilder builder = LookupElementBuilder.create(methodDeclaration.getName());
	builder = builder.withIcon((Image) AllIcons.Nodes.MethodReference);

	final DotNetTypeRef[] parameterTypes = methodDeclaration.getParameterTypeRefs();

	String genericText = DotNetElementPresentationUtil.formatGenericParameters(methodDeclaration);

	String parameterText = genericText + "(" + StringUtil.join(parameterTypes, new Function<DotNetTypeRef, String>()
	{
		@Override
		@RequiredReadAction
		public String fun(DotNetTypeRef parameter)
		{
			return CSharpTypeRefPresentationUtil.buildShortText(parameter, methodDeclaration);
		}
	}, ", ") + ")";

	if(CSharpMethodImplUtil.isExtensionWrapper(methodDeclaration))
	{
		builder = builder.withItemTextUnderlined(true);
	}
	builder = builder.withTypeText(CSharpTypeRefPresentationUtil.buildShortText(methodDeclaration.getReturnTypeRef(), methodDeclaration), true);
	builder = builder.withTailText(parameterText, true);
	if(DotNetAttributeUtil.hasAttribute(methodDeclaration, DotNetTypes.System.ObsoleteAttribute))
	{
		builder = builder.withStrikeoutness(true);
	}
	builder = builder.withInsertHandler(new InsertHandler<LookupElement>()
	{
		@Override
		@RequiredWriteAction
		public void handleInsert(InsertionContext context, LookupElement item)
		{
			char completionChar = context.getCompletionChar();
			switch(completionChar)
			{
				case ',':
					if(expression != null && expression.getParent() instanceof CSharpCallArgument)
					{
						context.setAddCompletionChar(false);
						TailType.COMMA.processTail(context.getEditor(), context.getTailOffset());
					}
					break;
			}
		}
	});

	if(contextType != null && contextType.isEquivalentTo(methodDeclaration.getParent()))
	{
		builder = builder.bold();
	}

	CSharpCompletionSorting.force(builder, CSharpCompletionSorting.KindSorter.Type.member);
	return builder;
}
 
Example 20
@RequiredReadAction
private static void consumeType(final CompletionParameters completionParameters,
		CSharpReferenceExpression referenceExpression,
		Consumer<LookupElement> consumer,
		boolean insideUsingList,
		DotNetTypeDeclaration someType)
{
	final String parentQName = someType.getPresentableParentQName();
	if(StringUtil.isEmpty(parentQName))
	{
		return;
	}

	String presentationText = MsilHelper.cutGenericMarker(someType.getName());

	int genericCount;
	DotNetGenericParameter[] genericParameters = someType.getGenericParameters();
	if((genericCount = genericParameters.length) > 0)
	{
		presentationText += "<" + StringUtil.join(genericParameters, parameter -> parameter.getName(), ", ");
		presentationText += ">";
	}

	String lookupString = insideUsingList ? someType.getPresentableQName() : someType.getName();
	if(lookupString == null)
	{
		return;
	}
	lookupString = MsilHelper.cutGenericMarker(lookupString);

	DotNetQualifiedElement targetElementForLookup = someType;
	CSharpMethodDeclaration methodDeclaration = someType.getUserData(CSharpResolveUtil.DELEGATE_METHOD_TYPE);
	if(methodDeclaration != null)
	{
		targetElementForLookup = methodDeclaration;
	}
	LookupElementBuilder builder = LookupElementBuilder.create(targetElementForLookup, lookupString);
	builder = builder.withPresentableText(presentationText);
	builder = builder.withIcon(IconDescriptorUpdaters.getIcon(targetElementForLookup, Iconable.ICON_FLAG_VISIBILITY));

	builder = builder.withTypeText(parentQName, true);
	final InsertHandler<LookupElement> ltGtInsertHandler = genericCount == 0 ? null : LtGtInsertHandler.getInstance(genericCount > 0);
	if(insideUsingList)
	{
		builder = builder.withInsertHandler(ltGtInsertHandler);
	}
	else
	{
		builder = builder.withInsertHandler(new InsertHandler<LookupElement>()
		{
			@Override
			@RequiredWriteAction
			public void handleInsert(InsertionContext context, LookupElement item)
			{
				if(ltGtInsertHandler != null)
				{
					ltGtInsertHandler.handleInsert(context, item);
				}

				context.commitDocument();

				new AddUsingAction(completionParameters.getEditor(), context.getFile(), Collections.<NamespaceReference>singleton(new NamespaceReference(parentQName, null))).execute();
			}
		});
	}

	if(DotNetAttributeUtil.hasAttribute(someType, DotNetTypes.System.ObsoleteAttribute))
	{
		builder = builder.withStrikeoutness(true);
	}

	CSharpTypeLikeLookupElement element = CSharpTypeLikeLookupElement.create(builder, DotNetGenericExtractor.EMPTY, referenceExpression);
	element.putUserData(CSharpNoVariantsDelegator.NOT_IMPORTED, Boolean.TRUE);
	consumer.consume(element);
}