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

The following examples show how to use com.intellij.codeInsight.lookup.LookupElementBuilder#create() . 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 File: WordCompletionContributor.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void addWordCompletionVariants(CompletionResultSet result, final CompletionParameters parameters, Set<String> excludes) {
  final Set<String> realExcludes = new HashSet<>(excludes);
  for (String exclude : excludes) {
    String[] words = exclude.split("[ \\.-]");
    if (words.length > 0 && StringUtil.isNotEmpty(words[0])) {
      realExcludes.add(words[0]);
    }
  }

  int startOffset = parameters.getOffset();
  final PsiElement position = parameters.getPosition();
  final CompletionResultSet javaResultSet = result.withPrefixMatcher(CompletionUtil.findJavaIdentifierPrefix(parameters));
  final CompletionResultSet plainResultSet = result.withPrefixMatcher(CompletionUtil.findAlphanumericPrefix(parameters));
  for (final String word : getAllWords(position, startOffset)) {
    if (!realExcludes.contains(word)) {
      final LookupElement item = LookupElementBuilder.create(word);
      javaResultSet.addElement(item);
      plainResultSet.addElement(item);
    }
  }

  addValuesFromOtherStringLiterals(result, parameters, realExcludes, position);
}
 
Example 2
Source File: ShaderReference.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
public static void consumeProperties(@Nonnull ShaderLabFile file, @Nonnull Consumer<LookupElement> consumer)
{
	for(ShaderProperty shaderProperty : file.getProperties())
	{
		String name = shaderProperty.getName();
		if(name == null)
		{
			continue;
		}
		LookupElementBuilder builder = LookupElementBuilder.create(name);
		builder = builder.withIcon((Image) AllIcons.Nodes.Property);
		ShaderPropertyType type = shaderProperty.getType();
		if(type != null)
		{
			builder = builder.withTypeText(type.getTargetText(), true);
		}
		consumer.consume(builder);
	}
}
 
Example 3
Source File: StaticArgCompletionProvider.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    String prefix = getPrefix(parameters);
    resultSet = resultSet.withPrefixMatcher(new PlainPrefixMatcher(prefix));
    PsiFile specFile = parameters.getOriginalFile();
    SpecDetail specDetail = PsiTreeUtil.getChildOfType(specFile, SpecDetail.class);
    List<SpecStep> stepsInFile = new ArrayList<>();
    addContextSteps(specDetail, stepsInFile);
    addStepsInScenarios(specFile, stepsInFile);

    Set<String> staticArgs = getArgsFromSteps(stepsInFile);
    for (String arg : staticArgs) {
        if (arg != null) {
            LookupElementBuilder item = LookupElementBuilder.create(arg);
            resultSet.addElement(item);
        }
    }
}
 
Example 4
Source File: CamelSmartCompletionEndpointOptions.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
public static List<LookupElement> addSmartCompletionSuggestionsContextPath(String val,
                                                                           final ComponentModel component,
                                                                           final Map<String, String> existing,
                                                                           final boolean xmlMode,
                                                                           final PsiElement psiElement) {
    final List<LookupElement> answer = new ArrayList<>();

    // show the syntax as the only choice for now
    LookupElementBuilder builder = LookupElementBuilder.create(val);
    builder = builder.withIcon(getCamelPreferenceService().getCamelIcon());
    builder = builder.withBoldness(true);
    builder = builder.withPresentableText(component.getSyntax());

    final LookupElement element = builder.withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
    answer.add(element);
    val = removeUnknownEnum(val, psiElement);
    final List<LookupElement> old = addSmartCompletionContextPathEnumSuggestions(val, component, existing);
    if (!old.isEmpty()) {
        answer.addAll(old);
    }

    return answer;
}
 
Example 5
Source File: LatteCompletionContributor.java    From intellij-latte with MIT License 6 votes vote down vote up
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
Source File: CSharpCompletionUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
public static void elementToLookup(@Nonnull CompletionResultSet resultSet,
		@Nonnull IElementType elementType,
		@Nullable NotNullPairFunction<LookupElementBuilder, IElementType, LookupElement> decorator,
		@Nullable Condition<IElementType> condition)
{
	if(condition != null && !condition.value(elementType))
	{
		return;
	}

	String keyword = ourCache.get(elementType);
	LookupElementBuilder builder = LookupElementBuilder.create(elementType, keyword);
	builder = builder.bold();
	LookupElement item = builder;
	if(decorator != null)
	{
		item = decorator.fun(builder, elementType);
	}

	item.putUserData(KEYWORD_ELEMENT_TYPE, elementType);
	resultSet.addElement(item);
}
 
Example 7
Source File: CamelSmartCompletionEndpointValue.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
private static void addEnumSuggestions(Editor editor, String val, String suffix, List<LookupElement> answer,
                                       String deprecated, String enums, String defaultValue, boolean xmlMode) {
    String[] parts = enums.split(",");
    for (String part : parts) {
        String lookup = val + part;
        LookupElementBuilder builder = LookupElementBuilder.create(lookup);
        builder = addInsertHandler(editor, suffix, builder, xmlMode);

        // only show the option in the UI
        builder = builder.withPresentableText(part);
        builder = builder.withBoldness(true);
        if ("true".equals(deprecated)) {
            // mark as deprecated
            builder = builder.withStrikeoutness(true);
        }
        boolean isDefaultValue = defaultValue != null && part.equals(defaultValue);
        if (isDefaultValue) {
            builder = builder.withTailText(" (default value)");
            // add default value first in the list
            answer.add(0, builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
        } else {
            answer.add(builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
        }
    }
}
 
Example 8
Source File: CamelJavaBeanReferenceSmartCompletion.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
private LookupElement buildLookupElement(PsiMethod method, String presentableMethod) {
    LookupElementBuilder builder = LookupElementBuilder.create(method);
    builder = builder.withPresentableText(presentableMethod);
    builder = builder.withTypeText(method.getContainingClass().getName(), true);
    builder = builder.withIcon(AllIcons.Nodes.Method);
    if (getCamelIdeaUtils().isAnnotatedWithHandler(method)) {
        //@Handle methods are marked with
        builder = builder.withBoldness(true);
    }
    if (method.isDeprecated()) {
        // mark as deprecated
        builder = builder.withStrikeoutness(true);
    }
    return  builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE);
}
 
Example 9
Source File: Suggestion.java    From intellij-spring-assistant with 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 10
Source File: CamelSmartCompletionEndpointValue.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
private static void addBooleanSuggestions(Editor editor, String val, String suffix, List<LookupElement> answer,
                                          String deprecated, String defaultValue, boolean xmlMode) {
    // for boolean types then give a choice between true|false
    String lookup = val + "true";
    LookupElementBuilder builder = LookupElementBuilder.create(lookup);
    builder = addInsertHandler(editor, suffix, builder, xmlMode);
    // only show the option in the UI
    builder = builder.withPresentableText("true");
    if ("true".equals(deprecated)) {
        // mark as deprecated
        builder = builder.withStrikeoutness(true);
    }
    boolean isDefaultValue = defaultValue != null && "true".equals(defaultValue);
    if (isDefaultValue) {
        builder = builder.withTailText(" (default value)");
        // add default value first in the list
        answer.add(0, builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
    } else {
        answer.add(builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
    }

    lookup = val + "false";
    builder = LookupElementBuilder.create(lookup);
    builder = addInsertHandler(editor, suffix, builder, xmlMode);
    // only show the option in the UI
    builder = builder.withPresentableText("false");
    if ("true".equals(deprecated)) {
        // mark as deprecated
        builder = builder.withStrikeoutness(true);
    }
    isDefaultValue = defaultValue != null && "false".equals(defaultValue);
    if (isDefaultValue) {
        builder = builder.withTailText(" (default value)");
        // add default value first in the list
        answer.add(0, builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
    } else {
        answer.add(builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
    }
}
 
Example 11
Source File: FieldCompletion.java    From intellij-swagger with MIT License 5 votes vote down vote up
private LookupElementBuilder create(final Field field) {
  LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(field, field.getName());

  if (field.isRequired()) {
    lookupElementBuilder = lookupElementBuilder.bold();
  }

  return lookupElementBuilder;
}
 
Example 12
Source File: InplaceVariableIntroducer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private LookupElement[] createLookupItems(String name, Editor editor, PsiNamedElement psiVariable) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (psiVariable != null) {
    final TextResult insertedValue =
      templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null;
    if (insertedValue != null) {
      final String text = insertedValue.getText();
      if (!text.isEmpty() && !Comparing.strEqual(text, name)) {
        final LinkedHashSet<String> names = new LinkedHashSet<String>();
        names.add(text);
        for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
          final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(psiVariable, psiVariable, names);
          if (suggestedNameInfo != null &&
              provider instanceof PreferrableNameSuggestionProvider &&
              !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
            break;
          }
        }
        final LookupElement[] items = new LookupElement[names.size()];
        final Iterator<String> iterator = names.iterator();
        for (int i = 0; i < items.length; i++) {
          items[i] = LookupElementBuilder.create(iterator.next());
        }
        return items;
      }
    }
  }
  return myLookupItems;
}
 
Example 13
Source File: LattePhpFunctionCompletionProvider.java    From intellij-latte with MIT License 5 votes vote down vote up
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 14
Source File: ReturnSourceUtil.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
public static LookupElementBuilder buildLookupElement(@NotNull Method method, @NotNull String contents, @Nullable JsonRawLookupElement jsonRawLookupElement) {
    LookupElementBuilder lookupElement = LookupElementBuilder.create(contents);
    PhpClass phpClass = method.getContainingClass();

    if(phpClass != null) {
        lookupElement = lookupElement.withTypeText(phpClass.getPresentableFQN(), true);
        lookupElement = lookupElement.withIcon(phpClass.getIcon());
    }

    return JsonParseUtil.getDecoratedLookupElementBuilder(
        lookupElement,
        jsonRawLookupElement
    );
}
 
Example 15
Source File: LatteCompletionContributor.java    From intellij-latte with MIT License 5 votes vote down vote up
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
Source File: ConceptDynamicArgCompletionProvider.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
public void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    String prefix = getPrefix(parameters);
    resultSet = resultSet.withPrefixMatcher(new PlainPrefixMatcher(prefix));
    Collection<ConceptDynamicArg> args = PsiTreeUtil.collectElementsOfType(parameters.getOriginalFile(), ConceptDynamicArg.class);
    for (ConceptDynamicArg arg : args) {
        LookupElementBuilder item = LookupElementBuilder.create(arg.getText().replaceAll("<|>", ""));
        resultSet.addElement(item);
    }
}
 
Example 17
Source File: CSharpNoVariantsDelegator.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 18
Source File: CSharpExpressionCompletionContributor.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@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 19
Source File: LatteCompletionContributor.java    From intellij-latte with MIT License 4 votes vote down vote up
private LookupElementBuilder createBuilderForTag(String name) {
	LookupElementBuilder builder = LookupElementBuilder.create(name);
	builder = builder.withInsertHandler(AttrMacroInsertHandler.getInstance());
	return builder.withIcon(LatteIcons.N_TAG);
}
 
Example 20
Source File: UnitySpecificMethodCompletion.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
@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;
}