Java Code Examples for com.intellij.codeInsight.lookup.LookupElement

The following examples show how to use com.intellij.codeInsight.lookup.LookupElement. 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   Source File: RuleTargetCompletionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLocalTarget() {
  BuildFile file =
      createBuildFile(
          new WorkspacePath("java/com/google/BUILD"),
          "java_library(name = 'lib')",
          "java_library(",
          "    name = 'test',",
          "    deps = [':']");

  Editor editor = editorTest.openFileInEditor(file);
  editorTest.setCaretPosition(editor, 3, "    deps = [':".length());

  LookupElement[] completionItems = testFixture.completeBasic();
  assertThat(completionItems).hasLength(1);
  assertThat(completionItems[0].toString()).isEqualTo("':lib'");
}
 
Example 2
Source Project: consulo-csharp   Source File: CSharpCompletionUtil.java    License: 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 3
@Test
public void testNoCompletionInUnknownRule() {
  ServiceHelper.unregisterLanguageExtensionPoint(
      "com.intellij.completion.contributor",
      BuiltInSymbolCompletionContributor.class,
      getTestRootDisposable());
  ServiceHelper.unregisterLanguageExtensionPoint(
      "com.intellij.completion.contributor",
      BuiltInFunctionCompletionContributor.class,
      getTestRootDisposable());

  setRuleAndAttributes("sh_binary", "name", "deps", "srcs", "data");

  BuildFile file = createBuildFile(new WorkspacePath("BUILD"), "java_binary(");

  Editor editor = editorTest.openFileInEditor(file.getVirtualFile());
  editorTest.setCaretPosition(editor, 0, "java_binary(".length());

  LookupElement[] completionItems = testFixture.completeBasic();
  assertThat(completionItems).isEmpty();
}
 
Example 4
Source Project: Intellij-Plugin   Source File: StepCompletionProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: Thinkphp5-Plugin   Source File: RouterReference.java    License: MIT License 6 votes vote down vote up
/**
 * 获取提示信息
 *
 * @return 返回提示集合
 */
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {

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

    CollectProjectUniqueKeys ymlProjectProcessor = new CollectProjectUniqueKeys(getProject(), RouteValStubIndex.KEY);
    //扫描文件获取key, 放入ymlProjectProcessor
    FileBasedIndex.getInstance().processAllKeys(RouteValStubIndex.KEY, ymlProjectProcessor, getProject());
    for (String key : ymlProjectProcessor.getResult()) {    //从ymlProjectProcessor中获取结果
        lookupElements.add(LookupElementBuilder.create(key).withIcon(LaravelIcons.ROUTE));
    }

    return lookupElements;
}
 
Example 6
Source Project: intellij-swagger   Source File: YamlInsertValueHandler.java    License: MIT License 6 votes vote down vote up
@Override
public void handleInsert(
    final InsertionContext insertionContext, final LookupElement lookupElement) {
  if (shouldUseQuotes(lookupElement)) {
    final boolean hasDoubleQuotes =
        hasStartingOrEndingQuoteOfType(insertionContext, lookupElement, DOUBLE_QUOTE);

    if (hasDoubleQuotes) {
      handleEndingQuote(insertionContext, DOUBLE_QUOTE);
      handleStartingQuote(insertionContext, lookupElement, DOUBLE_QUOTE);
    } else {
      handleEndingQuote(insertionContext, SINGLE_QUOTE);
      handleStartingQuote(insertionContext, lookupElement, SINGLE_QUOTE);
    }
  }
}
 
Example 7
@Nonnull
public static CSharpTypeLikeLookupElement create(LookupElement delegate, DotNetGenericExtractor extractor, PsiElement expression)
{
	CSharpNewExpression newExpression = null;
	PsiElement parent = expression == null ? null : expression.getParent();
	if(parent instanceof CSharpUserType)
	{
		PsiElement typeParent = parent.getParent();
		if(typeParent instanceof CSharpNewExpression)
		{
			newExpression = (CSharpNewExpression) typeParent;
		}
	}

	return new CSharpTypeLikeLookupElement(delegate, extractor, newExpression != null);
}
 
Example 8
Source Project: consulo   Source File: LookupTypedHandler.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean completeTillTypedCharOccurrence(char charTyped, LookupImpl lookup, LookupElement item) {
  PrefixMatcher matcher = lookup.itemMatcher(item);
  final String oldPrefix = matcher.getPrefix() + lookup.getAdditionalPrefix();
  PrefixMatcher expanded = matcher.cloneWithPrefix(oldPrefix + charTyped);
  if (expanded.prefixMatches(item)) {
    for (String s : item.getAllLookupStrings()) {
      if (matcher.prefixMatches(s)) {
        int i = -1;
        while (true) {
          i = s.indexOf(charTyped, i + 1);
          if (i < 0) break;
          final String newPrefix = s.substring(0, i + 1);
          if (expanded.prefixMatches(newPrefix)) {
            lookup.replacePrefix(oldPrefix, newPrefix);
            return true;
          }
        }
      }
    }
  }
  return false;
}
 
Example 9
@RequiredReadAction
@Override
public void processCompletion(@Nonnull CompletionParameters parameters,
		@Nonnull ProcessingContext context,
		@Nonnull final Consumer<LookupElement> result,
		@Nonnull CSharpTypeDeclaration typeDeclaration)
{
	Collection<DotNetModifierListOwner> overrideItems = getItemsImpl(typeDeclaration);
	for(DotNetModifierListOwner overrideItem : overrideItems)
	{
		LookupElementBuilder builder = buildLookupItem(typeDeclaration, overrideItem, false);

		result.consume(builder);

		if(!typeDeclaration.isInterface() && overrideItem.hasModifier(CSharpModifier.INTERFACE_ABSTRACT))
		{
			builder = buildLookupItem(typeDeclaration, overrideItem, true);

			result.consume(builder);
		}
	}
}
 
Example 10
Source Project: intellij   Source File: RuleTargetCompletionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomRuleCompletion() {
  MockBuildLanguageSpecProvider specProvider = new MockBuildLanguageSpecProvider();
  setBuildLanguageSpecRules(specProvider, "java_library");
  registerApplicationService(BuildLanguageSpecProvider.class, specProvider);

  BuildFile file =
      createBuildFile(
          new WorkspacePath("java/com/google/BUILD"),
          "custom_rule(name = 'lib')",
          "java_library(",
          "    name = 'test',",
          "    deps = [':']");

  Editor editor = editorTest.openFileInEditor(file);
  editorTest.setCaretPosition(editor, 3, "    deps = [':".length());

  LookupElement[] completionItems = testFixture.completeBasic();
  assertThat(completionItems).hasLength(1);
  assertThat(completionItems[0].toString()).isEqualTo("':lib'");
}
 
Example 11
Source Project: consulo   Source File: StatisticsUpdate.java    License: Apache License 2.0 6 votes vote down vote up
public void addSparedChars(Lookup lookup, LookupElement item, InsertionContext context) {
  String textInserted;
  if (context.getOffsetMap().containsOffset(CompletionInitializationContext.START_OFFSET) &&
      context.getOffsetMap().containsOffset(InsertionContext.TAIL_OFFSET) &&
      context.getTailOffset() >= context.getStartOffset()) {
    textInserted = context.getDocument().getImmutableCharSequence().subSequence(context.getStartOffset(), context.getTailOffset()).toString();
  }
  else {
    textInserted = item.getLookupString();
  }
  String withoutSpaces = StringUtil.replace(textInserted, new String[]{" ", "\t", "\n"}, new String[]{"", "", ""});
  int spared = withoutSpaces.length() - lookup.itemPattern(item).length();
  char completionChar = context.getCompletionChar();

  if (!LookupEvent.isSpecialCompletionChar(completionChar) && withoutSpaces.contains(String.valueOf(completionChar))) {
    spared--;
  }
  if (spared > 0) {
    mySpared += spared;
  }
}
 
Example 12
@NotNull
public Collection<LookupElement> getLookupElements(@NotNull PhpToolboxCompletionContributorParameter parameter) {
    PhpIndex instance = PhpIndex.getInstance(parameter.getProject());

    Collection<LookupElement> lookupElements = new ArrayList<>();
    for (String className : getClasses(parameter)) {
        // strip double backslash
        className = className.replaceAll("\\\\+", "\\\\");

        for (PhpClass phpClass : getPhpClassesForLookup(instance, className)) {
            lookupElements.add(
                LookupElementBuilder.create(phpClass.getPresentableFQN()).withIcon(phpClass.getIcon())
            );
        }
    }

    return lookupElements;
}
 
Example 13
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {

    Collection<LookupElement> elements = new ArrayList<>();

    for(Method method: phpClass.getMethods()) {
        if(method.getAccess().isPublic()) {
            String name = method.getName();
            if(!"getSubscribedEvents".equals(name) && !name.startsWith("__") && !name.startsWith("set")) {
                elements.add(LookupElementBuilder.create(name).withIcon(method.getIcon()));
            }
        }
    }

    return elements;
}
 
Example 14
@NotNull
private static LookupElement createParameterArrayTypeLookupElement(@NotNull ParameterArrayType type) {
    LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(type.getKey())
        .withIcon(PhpIcons.FIELD);

    String types = StringUtils.join(type.getValues(), '|');
    if (type.isOptional()) {
        types = "(optional) " + types;
    }

    return lookupElementBuilder.withTypeText(types);
}
 
Example 15
Source Project: consulo   Source File: StatisticsWeigher.java    License: Apache License 2.0 5 votes vote down vote up
private List<LookupElement> getInitialNoStatElements(Iterable<LookupElement> source, ProcessingContext context) {
  List<LookupElement> initialList = new ArrayList<>();
  for (LookupElement next : myNext.classify(source, context)) {
    if (myNoStats.contains(next)) {
      initialList.add(next);
    }
    else {
      break;
    }
  }
  return initialList;
}
 
Example 16
Source Project: tabnine-intellij   Source File: TabNineCompletionContributor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean prefixMatches(@NotNull LookupElement element) {
    if (element instanceof TabNineLookupElement) {
        return true;
    } else if (element instanceof LookupElementDecorator) {
        LookupElementDecorator decorator = (LookupElementDecorator) element;
        return prefixMatches(decorator.getDelegate());
    }
    return super.prefixMatches(element);
}
 
Example 17
Source Project: tabnine-intellij   Source File: TabNineCompletionContributor.java    License: MIT License 5 votes vote down vote up
@Override
public boolean isStartMatch(LookupElement element) {
    if (element instanceof  TabNineLookupElement) {
        return true;
    }
    return super.isStartMatch(element);
}
 
Example 18
Source Project: consulo   Source File: DumpLookupElementWeights.java    License: Apache License 2.0 5 votes vote down vote up
public static List<String> getLookupElementWeights(LookupImpl lookup, boolean hideSingleValued) {
  final Map<LookupElement, List<Pair<String, Object>>> weights = lookup.getRelevanceObjects(lookup.getItems(), hideSingleValued);
  return ContainerUtil.map(weights.entrySet(), new Function<Map.Entry<LookupElement, List<Pair<String, Object>>>, String>() {
    @Override
    public String fun(Map.Entry<LookupElement, List<Pair<String, Object>>> entry) {
      return entry.getKey().getLookupString() + "\t" + StringUtil.join(entry.getValue(), new Function<Pair<String, Object>, String>() {
        @Override
        public String fun(Pair<String, Object> pair) {
          return pair.first + "=" + pair.second;
        }
      }, ", ");
    }
  });
}
 
Example 19
Source Project: intellij   Source File: EditorTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
/** @return true if a LookupItem was inserted. */
public boolean completeIfUnique() {
  LookupElement[] completionItems = testFixture.completeBasic();
  if (completionItems == null) {
    return true;
  }
  if (completionItems.length != 1) {
    return false;
  }
  testFixture.getLookup().setCurrentItem(completionItems[0]);
  testFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);
  return true;
}
 
Example 20
@Override
public AutoCompletionDecision handleAutoCompletionPossibility(AutoCompletionContext context) {
  // auto-insert the obvious only case; else show other cases.
  final LookupElement[] items = context.getItems();
  if (items.length == 1) {
    return AutoCompletionDecision.insertItem(items[0]);
  }
  return AutoCompletionDecision.SHOW_LOOKUP;
}
 
Example 21
Source Project: idea-php-symfony2-plugin   Source File: TwigUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Collect block in virtual files via index
 */
@NotNull
public static Collection<LookupElement> getBlockLookupElements(@NotNull Project project, @NotNull Collection<VirtualFile> files) {
    Collection<LookupElement> lookupElements = new ArrayList<>();

    Map<VirtualFile, Collection<String>> templateNames = new HashMap<>();

    for (Map.Entry<VirtualFile, Collection<String>> block : getBlockNamesForFiles(project, files).entrySet()) {
        // performance optimize to not resolve too many elements
        VirtualFile virtualFile = block.getKey();
        if(!templateNames.containsKey(virtualFile)) {
            templateNames.put(virtualFile, TwigUtil.getTemplateNamesForFile(project, virtualFile));
        }

        for (String blockName : block.getValue()) {
            LookupElementBuilder lookupElementBuilder = LookupElementBuilder
                .create(blockName)
                .withIcon(TwigIcons.TwigFileIcon);

            Collection<String> names = templateNames.getOrDefault(virtualFile, Collections.emptyList());
            if(names.size() > 0) {
                lookupElementBuilder = lookupElementBuilder.withTypeText(names.iterator().next(), true);
            }

            lookupElements.add(lookupElementBuilder);
        }
    }

    return lookupElements;
}
 
Example 22
Source Project: consulo-unity3d   Source File: ShaderReference.java    License: Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nonnull
@Override
public Object[] getVariants()
{
	ResolveKind kind = kind();
	final List<LookupElement> values = new SmartList<>();
	switch(kind)
	{
		case ATTRIBUTE:
			for(ShaderMaterialAttribute attribute : ShaderMaterialAttribute.values())
			{
				LookupElementBuilder builder = LookupElementBuilder.create(attribute.name());
				builder = builder.withIcon((Image) AllIcons.Nodes.Class);
				builder = builder.withTypeText(attribute.getType(), true);
				values.add(builder);
			}
			break;
		case PROPERTY:
			PsiFile containingFile = getContainingFile();
			if(containingFile instanceof ShaderLabFile)
			{
				consumeProperties((ShaderLabFile) containingFile, values::add);
			}
			break;
	}
	return values.toArray();
}
 
Example 23
Source Project: litho   Source File: LayoutSpecMethodAnnotationsProvider.java    License: Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 24
Source Project: intellij   Source File: BuildFileAutoCompletionTest.java    License: Apache License 2.0 5 votes vote down vote up
private List<String> currentLookupStrings() {
  LookupImpl lookup = completionTester.getLookup();
  if (lookup == null) {
    return ImmutableList.of();
  }
  return lookup
      .getItems()
      .stream()
      .map(LookupElement::getLookupString)
      .collect(Collectors.toList());
}
 
Example 25
Source Project: consulo   Source File: CodeInsightTestFixtureImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getCompletionVariants(final String... filesBefore) {
  assertInitialized();
  configureByFiles(filesBefore);
  final LookupElement[] items = complete(CompletionType.BASIC);
  Assert.assertNotNull("No lookup was shown, probably there was only one lookup element that was inserted automatically", items);
  return getLookupElementStrings();
}
 
Example 26
Source Project: idea-php-symfony2-plugin   Source File: DoctrineMetadataUtil.java    License: MIT License 5 votes vote down vote up
@NotNull
public static Collection<LookupElement> getObjectRepositoryLookupElements(@NotNull Project project) {
    PhpIndex index = PhpIndex.getInstance(project);
    Collection<PhpClass> collection = index.getAllSubclasses("\\Doctrine\\Common\\Persistence\\ObjectRepository");
    collection.addAll(index.getAllSubclasses("\\Doctrine\\Persistence\\ObjectRepository"));

    return new ArrayList<>(DoctrineRepositoryLookupElement.create(collection));
}
 
Example 27
Source Project: consulo-csharp   Source File: CSharpCompletionSorting.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@RequiredReadAction
public Comparable weigh(@Nonnull LookupElement element)
{
	final String name = getName(element);

	if(name != null && getNameEndMatchingDegree(name, myExpectedTypes) != 0)
	{
		return NameUtil.nameToWords(name).length - 1000;
	}
	return 0;
}
 
Example 28
Source Project: idea-php-toolbox   Source File: FunctionProvider.java    License: MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<LookupElement> getLookupElements(@NotNull PhpToolboxCompletionContributorParameter parameter) {
    return PhpIndex.getInstance(parameter.getProject())
        .getAllFunctionNames(PrefixMatcher.ALWAYS_TRUE).stream().map(
            s -> LookupElementBuilder.create(s).withIcon(PhpIcons.FUNCTION)
        )
        .collect(Collectors.toCollection(HashSet::new));
}
 
Example 29
Source Project: consulo-csharp   Source File: CSharpCompletionSorting.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
@RequiredReadAction
public Comparable weigh(@Nonnull LookupElement element)
{
	Boolean data = element.getUserData(CSharpNoVariantsDelegator.NOT_IMPORTED);
	return data != Boolean.TRUE;
}
 
Example 30
Source Project: consulo   Source File: StatisticsWeigher.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Iterable<LookupElement> classify(@Nonnull Iterable<LookupElement> source, @Nonnull final ProcessingContext context) {
  List<LookupElement> initialList = getInitialNoStatElements(source, context);
  Iterable<LookupElement> rest = withoutInitial(source, initialList);
  Collection<List<LookupElement>> byWeight = buildMapByWeight(rest).descendingMap().values();

  return JBIterable.from(initialList).append(JBIterable.from(byWeight).flatten(group -> myNext.classify(group, context)));
}