类 com.intellij.codeInsight.completion.PrioritizedLookupElement 源码实例Demo

下面列出了怎么用 com.intellij.codeInsight.completion.PrioritizedLookupElement 的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: litho   文件: MethodChainLookupElement.java

/**
 * @param lookupPresentation delegate for rendering the lookup element in completion suggestion
 *     results.
 * @param firstMethodName first method name in a method call chain. It is expected to be the same
 *     method as in the lookupPresentation.
 * @param otherMethodNames other names in a method call chain.
 * @param placeholder element in a PsiFile that will be replaced with the method call chain.
 */
public static LookupElement create(
    LookupElement lookupPresentation,
    String firstMethodName,
    List<? extends String> otherMethodNames,
    PsiElement placeholder,
    Project project) {
  return Optional.of(createMethodChain(project, firstMethodName, otherMethodNames))
      .map(placeholder::replace)
      .map(elementInTree -> CodeStyleManager.getInstance(project).reformat(elementInTree, false))
      .map(MethodChainLookupElement::createTemplate)
      .<LookupElement>map(
          template -> {
            final LookupElement prioritized =
                PrioritizedLookupElement.withPriority(lookupPresentation, Integer.MAX_VALUE);
            return new MethodChainLookupElement(prioritized, template);
          })
      .orElse(lookupPresentation);
}
 

public static void addVariables(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result,
								@NotNull PsiElement cursor, boolean forLocalVars) {
	HashSet<String> putVars = new HashSet<>();
	PsiUtil.traverseDepthFirstSearch(parameters.getOriginalFile().getNode(), astNode -> {
		PsiElement nodeAsElement = astNode.getPsi();
		if (nodeAsElement == cursor) {
			return false;
		}
		if (!(nodeAsElement instanceof SQFVariable)) {
			return false;
		}
		SQFVariable var = (SQFVariable) nodeAsElement;
		if (((var.isLocal() && forLocalVars) || (!var.isLocal() && !forLocalVars)) && !putVars.contains(var.getVarName().toLowerCase())) {
			putVars.add(var.getVarName().toLowerCase());
			result.addElement(PrioritizedLookupElement.withPriority(
					LookupElementBuilder.createWithSmartPointer(var.getVarName(), var)
							.withTailText(var.isMagicVar() ? " (Magic Var)" : (
											forLocalVars ? " (Local Variable)" : " (Global Variable)"
									)
							)
							.withIcon(var.isMagicVar() ? ArmaPluginIcons.ICON_SQF_MAGIC_VARIABLE : ArmaPluginIcons.ICON_SQF_VARIABLE), VAR_PRIORITY)
			);
		}
		return false;
	});
}
 

/**
 * Adds all description.ext/config.cpp functions to the completion result
 */
public static void addFunctions(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
	List<HeaderConfigFunction> allConfigFunctions = ArmaPluginUserData.getInstance().getAllConfigFunctions(parameters.getOriginalFile());
	if (allConfigFunctions == null) {
		return;
	}
	for (HeaderConfigFunction function : allConfigFunctions) {
		result.addElement(
				PrioritizedLookupElement.withPriority(
						LookupElementBuilder.create(function)
								.withIcon(HeaderConfigFunction.getIcon())
								.withPresentableText(function.getCallableName()), FUNCTION_PRIORITY
				)
		);
	}
}
 

public static void addVariables(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result,
								@NotNull PsiElement cursor, boolean forLocalVars) {
	HashSet<String> putVars = new HashSet<>();
	PsiUtil.traverseDepthFirstSearch(parameters.getOriginalFile().getNode(), astNode -> {
		PsiElement nodeAsElement = astNode.getPsi();
		if (nodeAsElement == cursor) {
			return false;
		}
		if (!(nodeAsElement instanceof SQFVariable)) {
			return false;
		}
		SQFVariable var = (SQFVariable) nodeAsElement;
		if (((var.isLocal() && forLocalVars) || (!var.isLocal() && !forLocalVars)) && !putVars.contains(var.getVarName().toLowerCase())) {
			putVars.add(var.getVarName().toLowerCase());
			result.addElement(PrioritizedLookupElement.withPriority(
					LookupElementBuilder.createWithSmartPointer(var.getVarName(), var)
							.withTailText(var.isMagicVar() ? " (Magic Var)" : (
											forLocalVars ? " (Local Variable)" : " (Global Variable)"
									)
							)
							.withIcon(var.isMagicVar() ? ArmaPluginIcons.ICON_SQF_MAGIC_VARIABLE : ArmaPluginIcons.ICON_SQF_VARIABLE), VAR_PRIORITY)
			);
		}
		return false;
	});
}
 

/**
 * Adds all description.ext/config.cpp functions to the completion result
 */
public static void addFunctions(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
	List<HeaderConfigFunction> allConfigFunctions = ArmaPluginUserData.getInstance().getAllConfigFunctions(parameters.getOriginalFile());
	if (allConfigFunctions == null) {
		return;
	}
	for (HeaderConfigFunction function : allConfigFunctions) {
		result.addElement(
				PrioritizedLookupElement.withPriority(
						LookupElementBuilder.create(function)
								.withIcon(HeaderConfigFunction.getIcon())
								.withPresentableText(function.getCallableName()), FUNCTION_PRIORITY
				)
		);
	}
}
 

static Collection<LookupElement> createItems(Collection<String> lookupStrings, final Icon icon, boolean trimLookupString, Integer groupId) {
    return lookupStrings
            .stream()
            .map(item -> {
                LookupElementBuilder elementBuilder = LookupElementBuilder.create(item).withCaseSensitivity(true);
                if (icon != null) {
                    elementBuilder = elementBuilder.withIcon(icon);
                }

                if (trimLookupString) {
                    elementBuilder = elementBuilder.withLookupString(item.replace("_", ""));
                }

                if (groupId != null) {
                    return PrioritizedLookupElement.withGrouping(elementBuilder, groupId);
                }
                return elementBuilder;
            })
            .collect(Collectors.toList());
}
 

@NotNull
@Override
public Collection<LookupElement> getLookupElements() {

    final Collection<LookupElement> lookupElements = new ArrayList<>();

    ControllerCollector.visitController(getProject(), (method, name) ->
        namespaceCutter.cut(name, (processedClassName, prioritised) -> {
            LookupElement lookupElement = LookupElementBuilder.create(processedClassName)
                    .withIcon(LaravelIcons.ROUTE);

            if(prioritised) {
                lookupElement = PrioritizedLookupElement.withPriority(lookupElement, 10);
            }

            lookupElements.add(lookupElement);
        })
    );

    return lookupElements;
}
 
源代码8 项目: litho   文件: OnEventCompletionProvider.java

@Override
protected void addCompletions(
    CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
  final Optional<PsiClass> maybeCls =
      CompletionUtils.findFirstParent(parameters.getPosition(), LithoPluginUtils::isLithoSpec);
  if (!maybeCls.isPresent()) return;

  final PsiClass lithoSpecCls = maybeCls.get();
  final PsiClass clickEventCls =
      getOrCreateClass(LithoClassNames.CLICK_EVENT_CLASS_NAME, lithoSpecCls.getProject());
  final PsiMethod onEventMethod =
      OnEventGenerateUtils.createOnEventMethod(
          lithoSpecCls, clickEventCls, Collections.emptyList());
  result.addElement(
      PrioritizedLookupElement.withPriority(
          createMethodLookup(
              onEventMethod,
              clickEventCls,
              OnEventGenerateUtils.createOnEventLookupString(clickEventCls),
              () -> {
                final Map<String, String> data = new HashMap<>();
                data.put(EventLogger.KEY_TARGET, EventLogger.VALUE_COMPLETION_TARGET_METHOD);
                data.put(EventLogger.KEY_CLASS, "OnEvent");
                LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_COMPLETION, data);
                LithoPluginUtils.getFirstLayoutSpec(parameters.getOriginalFile())
                    .ifPresent(ComponentGenerateUtils::updateLayoutComponent);
              }),
          Integer.MAX_VALUE));
}
 

@Override
protected void addCompletions(
    CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
  PsiElement position = parameters.getPosition();
  if (!CompletionUtils.findFirstParent(position, LithoPluginUtils::isLayoutSpec).isPresent())
    return;

  final Project project = position.getProject();
  for (String annotationFQN : ANNOTATION_QUALIFIED_NAMES) {
    LookupElement lookup =
        PrioritizedLookupElement.withPriority(
            createLookup(annotationFQN, project), Integer.MAX_VALUE);
    result.addElement(lookup);
  }
}
 
源代码10 项目: litho   文件: ReplacingConsumer.java

/** Adds {@link LookupElement} for the {@link #replacedQualifiedNames} unseen before. */
void addRemainingCompletions(Project project) {
  for (String qualifiedName : replacedQualifiedNames) {
    result.addElement(
        PrioritizedLookupElement.withPriority(
            SpecLookupElement.create(qualifiedName, project, insertHandler), Integer.MAX_VALUE));
  }
}
 

@Override
protected void addFileKeywords(@NotNull CompletionResultSet result) {
    for (String keyword : KEYWORDS) {
        LookupElementBuilder builder = LookupElementBuilder.create(keyword).
                withInsertHandler(INSERT_SPACE).
                bold();

        result.addElement(PrioritizedLookupElement.withPriority(builder, KEYWORD_PRIORITY));
    }
}
 

@Override
protected void addFileKeywords(@NotNull CompletionResultSet result) {
    for (String keyword : KEYWORDS) {
        LookupElementBuilder builder = LookupElementBuilder.create(keyword).
                withInsertHandler(INSERT_SPACE).
                bold();

        result.addElement(PrioritizedLookupElement.withPriority(builder, KEYWORD_PRIORITY));
    }
}
 

protected void fillCompletionResultSet(@NotNull CompletionResultSet completionResultSet, @NotNull Project project) {
    for(Map.Entry<String, String> entry : EnvironmentVariablesApi.getAllKeyValues(project).entrySet()) {
        LookupElementBuilder lockup = LookupElementBuilder.create(entry.getKey())
                .withLookupString(entry.getKey().toLowerCase());

        if(StringUtils.isNotEmpty(entry.getValue())) {
            lockup = lockup.withTailText(" = " + entry.getValue(), true);
        }

        completionResultSet.addElement(PrioritizedLookupElement.withPriority(lockup, 100));
    }
}
 
源代码14 项目: component-runtime   文件: Suggestion.java

public LookupElement newLookupElement(final int priority) {
    return PrioritizedLookupElement
            .withPriority(LookupElementBuilder
                    .create(this, getKey())
                    .withRenderer(new LookupElementRenderer<LookupElement>() {

                        @Override
                        public void renderElement(final LookupElement element,
                                final LookupElementPresentation presentation) {
                            final Suggestion suggestion = Suggestion.class.cast(element.getObject());
                            presentation.setItemText(suggestion.getKey());
                            if (Type.Family.equals(suggestion.getType())) {
                                presentation.setIcon(AllIcons.Nodes.ModuleGroup);
                                presentation.appendTailText("  Family", true);
                            } else if (Type.Component.equals(suggestion.getType())) {
                                presentation.setIcon(Icons.TACOKIT.getIcon());
                                presentation.appendTailText("  Component", true);
                            } else if (Type.Configuration.equals(suggestion.getType())) {
                                presentation.setIcon(AllIcons.Hierarchy.Class);
                                presentation.appendTailText("  Configuration", true);
                            } else if (Type.Action.equals(suggestion.getType())) {
                                presentation.setIcon(findSubmit());
                                presentation.appendTailText("  Action", true);
                            }
                        }
                    }), priority);
}
 

/**
 * Adds all literals to completion set for all parent commands expression at the cursor.
 *
 * @see CommandDescriptor#getAllLiterals()
 */
public static void addLiterals(@NotNull PsiElement cursor, @NotNull CompletionResultSet result, boolean trimQuotes) {
	ASTNode ancestor = PsiUtil.getFirstAncestorOfType(cursor.getNode(), SQFTypes.EXPRESSION_STATEMENT, null);
	if (ancestor == null) {
		return;
	}

	PsiUtil.traverseDepthFirstSearch(ancestor, astNode -> {
		PsiElement nodeAsPsi = astNode.getPsi();
		if (nodeAsPsi == cursor) {
			return true;
		}
		if (!(nodeAsPsi instanceof SQFCommandExpression)) {
			return false;
		}
		SQFCommandExpression commandExpression = (SQFCommandExpression) nodeAsPsi;
		SQFExpressionOperator operator = commandExpression.getExprOperator();

		CommandDescriptor descriptor = SQFSyntaxHelper.getInstance().getDescriptor(operator.getText());
		if (descriptor == null) {
			return false;
		}
		for (String s : descriptor.getAllLiterals()) {
			result.addElement(
					PrioritizedLookupElement.withPriority(LookupElementBuilder.create(trimQuotes ? s.substring(1, s.length() - 1) : s)
							.bold()
							.withTailText(" (" + SQFStatic.getSQFBundle().getString("CompletionContributors.literal") + ")")
							, LITERAL_PRIORITY
					)
			);
		}

		return false;
	});
}
 

/**
 * Adds all literals to completion set for all parent commands expression at the cursor.
 *
 * @see CommandDescriptor#getAllLiterals()
 */
public static void addLiterals(@NotNull PsiElement cursor, @NotNull CompletionResultSet result, boolean trimQuotes) {
	ASTNode ancestor = PsiUtil.getFirstAncestorOfType(cursor.getNode(), SQFTypes.EXPRESSION_STATEMENT, null);
	if (ancestor == null) {
		return;
	}

	PsiUtil.traverseDepthFirstSearch(ancestor, astNode -> {
		PsiElement nodeAsPsi = astNode.getPsi();
		if (nodeAsPsi == cursor) {
			return true;
		}
		if (!(nodeAsPsi instanceof SQFCommandExpression)) {
			return false;
		}
		SQFCommandExpression commandExpression = (SQFCommandExpression) nodeAsPsi;
		SQFExpressionOperator operator = commandExpression.getExprOperator();

		CommandDescriptor descriptor = SQFSyntaxHelper.getInstance().getDescriptor(operator.getText());
		if (descriptor == null) {
			return false;
		}
		for (String s : descriptor.getAllLiterals()) {
			result.addElement(
					PrioritizedLookupElement.withPriority(LookupElementBuilder.create(trimQuotes ? s.substring(1, s.length() - 1) : s)
							.bold()
							.withTailText(" (" + SQFStatic.getSQFBundle().getString("CompletionContributors.literal") + ")")
							, LITERAL_PRIORITY
					)
			);
		}

		return false;
	});
}
 

static Collection<LookupElement> createFromPsiItems(Collection<? extends PsiNamedElement> elements, @Nullable Icon icon, @Nullable Integer groupId) {
    return elements.stream().map(psi -> {
        LookupElementBuilder element = LookupElementBuilder.create(psi).withCaseSensitivity(true);
        if (icon != null) {
            element = element.withIcon(icon);
        }
        if (groupId != null) {
            return PrioritizedLookupElement.withGrouping(element, groupId);
        }
        return element;
    }).collect(Collectors.toList());
}
 

static Collection<LookupElement> createPathItems(List<String> osPathes) {
    return osPathes.stream()
            .map(path ->
                    //fix the windows file and directory pathes to be cygwin compatible
                    SystemInfoRt.isWindows ? OSUtil.toBashCompatible(path) : path
            )
            .map(path -> {
                int groupId = path.startsWith("/") ? CompletionGrouping.AbsoluteFilePath.ordinal() : CompletionGrouping.RelativeFilePath.ordinal();
                return PrioritizedLookupElement.withGrouping(createPathLookupElement(path, !path.endsWith("/")), groupId);
            }).collect(Collectors.toList());
}
 

@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
    final Collection<LookupElement> lookupElements = new ArrayList<>();

    ControllerCollector.visitControllerActions(getProject(), (phpClass, method, name) ->
        namespaceCutter.cut(name, (processedClassName, prioritised) -> {
            LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(processedClassName)
                    .withIcon(LaravelIcons.ROUTE)
                    .withTypeText(phpClass.getPresentableFQN(), true);

            Parameter[] parameters = method.getParameters();
            if (parameters.length > 0) {
                lookupElementBuilder = lookupElementBuilder.withTailText(PhpPresentationUtil.formatParameters(null, parameters).toString());
            }

            LookupElement lookupElement = lookupElementBuilder;
            if (prioritised) {
                lookupElement = PrioritizedLookupElement.withPriority(lookupElementBuilder, 10);
            }

            lookupElements.add(lookupElement);
        })
    );

    return lookupElements;
}
 
源代码20 项目: litho   文件: RequiredPropLookupElement.java

static RequiredPropLookupElement create(LookupElement delegate, boolean shouldPrioritize) {
  if (shouldPrioritize) {
    delegate = PrioritizedLookupElement.withPriority(delegate, Integer.MAX_VALUE);
  }
  return new RequiredPropLookupElement(delegate);
}
 

private static List<LookupElement> addSmartCompletionContextPathEnumSuggestions(final String val,
                                                                                final ComponentModel component,
                                                                                final Map<String, String> existing) {
    final List<LookupElement> answer = new ArrayList<>();

    double priority = 100.0d;

    // lets help the suggestion list if we are editing the context-path and only have 1 enum type option
    // and the option has not been in use yet, then we can populate the list with the enum values.

    final long enums = component
            .getEndpointOptions()
            .stream()
            .filter(o -> "path".equals(o.getKind()) && !o
                    .getEnums()
                    .isEmpty())
            .count();
    if (enums == 1) {
        for (final EndpointOptionModel option : component.getEndpointOptions()) {

            // only add support for enum in the context-path smart completion
            if ("path".equals(option.getKind()) && !option
                    .getEnums()
                    .isEmpty()) {
                final String name = option.getName();
                // only add if not already used
                final String old = existing != null ? existing.get(name) : "";
                if (existing == null || old == null || old.isEmpty()) {

                    // add all enum as choices
                    for (final String choice : option
                            .getEnums()
                            .split(",")) {

                        final String key = choice;
                        final String lookup = val + key;

                        LookupElementBuilder builder = LookupElementBuilder.create(lookup);
                        // only show the option in the UI
                        builder = builder.withPresentableText(choice);
                        // lets use the option name as the type so its visible
                        builder = builder.withTypeText(name, true);
                        builder = builder.withIcon(AllIcons.Nodes.Enum);

                        if ("true".equals(option.getDeprecated())) {
                            // mark as deprecated
                            builder = builder.withStrikeoutness(true);
                        }

                        // its an enum so always auto complete the choices
                        LookupElement element = builder.withAutoCompletionPolicy(AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE);

                        // they should be in the exact order
                        element = PrioritizedLookupElement.withPriority(element, priority);

                        priority -= 1.0d;

                        answer.add(element);
                    }
                }
            }
        }
    }

    return answer;
}
 

public static LookupElement prioritized(LookupElement lookupElement, int priority) {
    return PrioritizedLookupElement.withPriority(lookupElement, priority);
}
 

public TemplateExpressionLookupElement(final TemplateState state, LookupElement element, int index) {
  super(PrioritizedLookupElement.withPriority(element, Integer.MAX_VALUE - 10 - index));
  myState = state;
}