com.intellij.codeInsight.lookup.LookupElement Java Examples

The following examples show how to use com.intellij.codeInsight.lookup.LookupElement. 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: RuleTargetCompletionTest.java    From intellij with 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 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 #3
Source File: PhpEventDispatcherGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@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 #4
Source File: YamlInsertValueHandler.java    From intellij-swagger with 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 #5
Source File: LookupTypedHandler.java    From consulo with 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 #6
Source File: PhpIndexAbstractProviderAbstract.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
@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 #7
Source File: CSharpOverrideOrImplementCompletionContributor.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: BuiltInFunctionAttributeCompletionContributorTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: StepCompletionProvider.java    From Intellij-Plugin with 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 #10
Source File: RouterReference.java    From Thinkphp5-Plugin with 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 #11
Source File: RuleTargetCompletionTest.java    From intellij with 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 #12
Source File: StatisticsUpdate.java    From consulo with 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 #13
Source File: CSharpTypeLikeLookupElement.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: TagNameCompletionProviderTest.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void testThatTagsByFindTaggedServiceIdsOfPhpContainerBuilderIsCompleted() {
    Collection<LookupElement> lookupElements = TagNameCompletionProvider.getTagLookupElements(getProject());

    assertNotNull(ContainerUtil.find(lookupElements, lookupElement ->
        "my.acme_mailer.transport.tag".equals(lookupElement.getLookupString())
    ));
}
 
Example #15
Source File: TwigTemplateCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
    PsiElement psiElement = parameters.getOriginalPosition();
    if(psiElement == null || !Symfony2ProjectComponent.isEnabled(psiElement)) {
        return;
    }

    // "foobar".<caret>
    Collection<String> possibleTypes = TwigTypeResolveUtil.formatPsiTypeName(psiElement);
    if(possibleTypes.size() != 1) {
        return;
    }

    String rootElement = possibleTypes.iterator().next();

    resultSet.addAllElements(
        TwigUtil.getImportedMacrosNamespaces(psiElement.getContainingFile()).stream()
            .filter(twigMacro ->
                twigMacro.getName().startsWith(rootElement + ".")
            )
            .map((Function<TwigMacro, LookupElement>) twigMacro ->
                LookupElementBuilder.create(twigMacro.getName().substring(rootElement.length() + 1))
                    .withTypeText(twigMacro.getTemplate(), true)
                    .withTailText(twigMacro.getParameter(), true)
                    .withIcon(TwigIcons.TwigFileIcon).withInsertHandler(FunctionInsertHandler.getInstance())
            ).collect(Collectors.toList())
    );
}
 
Example #16
Source File: FormOptionGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
    Collection<LookupElement> elements = new ArrayList<>();

    for (String formType : DEFAULT_FORM) {
        FormOptionsUtil.visitFormOptions(
            getElement().getProject(), formType, new FormOptionLookupVisitor(elements)
        );
    }

    return elements;
}
 
Example #17
Source File: DebuggerCompletionContributor.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Override
public AutoCompletionDecision handleAutoCompletionPossibility(AutoCompletionContext context) {
  // auto-insert iff there's only one suggestion
  final LookupElement[] items = context.getItems();
  if (items.length == 1) {
    return AutoCompletionDecision.insertItem(items[0]);
  }
  return AutoCompletionDecision.SHOW_LOOKUP;
}
 
Example #18
Source File: HaxeClassNameCompletionContributor.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private MyProcessor(CompletionResultSet resultSet,
                    @Nullable String prefixPackage,
                    @Nullable InsertHandler<LookupElement> insertHandler) {
  myResultSet = resultSet;
  myPrefixPackage = prefixPackage;
  myInsertHandler = insertHandler;
}
 
Example #19
Source File: VariableCollector.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private List<LookupElement> convertToLookupElements(List<XQueryQName<XQueryVarName>> proposedReferences, int priority) {
    List<LookupElement> lookupElements = new ArrayList<LookupElement>(proposedReferences.size());
    for (int i = 0; i < proposedReferences.size(); i++) {
        lookupElements.add(convertToLookupElement(proposedReferences.get(i), priority));
    }
    return lookupElements;
}
 
Example #20
Source File: ControllerActionReferenceTest.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
public void testReferenceCanResolveVariants() {
    PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
            "class ActionController {" +
            "public function action() {" +
            "  $this->forward('<caret>baz');" +
            "}" +
            "}"
    );

    PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent();
    PsiReference[] references = elementAtCaret.getReferences();
    for (PsiReference reference : references) {
        if (reference instanceof ControllerActionReference) {
            Object[] variants = reference.getVariants();
            for (Object variant : variants) {
                if (variant instanceof LookupElement) {
                    String lookupString = ((LookupElement) variant).getLookupString();
                    assertEquals("foo", lookupString);
                    return;
                }
            }

        }
    }

    fail("No ControllerActionReference found");
}
 
Example #21
Source File: DotEnvReference.java    From idea-php-dotenv-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    final PsiElement[] elements = EnvironmentVariablesApi.getKeyDeclarations(project, key);

    return Arrays.stream(elements)
            .filter(psiElement -> psiElement instanceof PsiNamedElement)
            .map(psiElement -> LookupElementBuilder.create(psiElement).
                    withTypeText(psiElement.getContainingFile().getName()))
            .toArray(LookupElement[]::new);
}
 
Example #22
Source File: CSharpCompletionSorting.java    From consulo-csharp with 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 #23
Source File: PhpVariableInsertHandler.java    From intellij-latte with MIT License 5 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE) {
		PsiElement parent = element.getParent();
		if (!(parent instanceof Variable) && !element.getText().startsWith("$")) {
			Editor editor = context.getEditor();
			CaretModel caretModel = editor.getCaretModel();
			int offset = caretModel.getOffset();
			caretModel.moveToOffset(element.getTextOffset() + (PhpPsiUtil.isOfType(parent, PhpElementTypes.CAST_EXPRESSION) ? 1 : 0));
			EditorModificationUtil.insertStringAtCaret(editor, "$");
			caretModel.moveToOffset(offset + 1);
			PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
		}
	}
}
 
Example #24
Source File: IndexUtil.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
@NotNull
public static Collection<LookupElement> getIndexedKeyLookup(@NotNull Project project, @NotNull ID<String, ?> var1) {
    Collection<LookupElement> lookupElements = new ArrayList<>();

    lookupElements.addAll(SymfonyProcessors.createResult(project, var1).stream().map(
        s -> LookupElementBuilder.create(s).withIcon(DrupalIcons.DRUPAL)).collect(Collectors.toList())
    );

    return lookupElements;
}
 
Example #25
Source File: QuotedInsertHandler.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
public void handleInsert(InsertionContext context, LookupElement lookupElement) {
    if(ResourceFileInsertHandler.isStringBeforeCaret(context.getEditor(), context, "'") ||
       ResourceFileInsertHandler.isStringBeforeCaret(context.getEditor(), context, "\""))
    {
        return;
    }

    int startOffset = context.getStartOffset();
    context.getDocument().insertString(startOffset, "\"");
    context.getDocument().insertString(startOffset + lookupElement.getLookupString().length() + 1, "\"");

    // move to end
    context.getEditor().getCaretModel().moveCaretRelatively(1, 0, false, false, true);
}
 
Example #26
Source File: PhpConstGotoCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void addAllClasses(Collection<LookupElement> elements, Collection<PhpClass> classes) {
    for (PhpClass phpClass : classes) {
        // Filter by classes only with constants (including inherited constants)
        if (PhpElementsUtil.hasClassConstantFields(phpClass)) {
            elements.add(wrapClassInsertHandler(new MyPhpLookupElement(phpClass)));
        }
    }
}
 
Example #27
Source File: StatisticsWeigher.java    From consulo with 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)));
}
 
Example #28
Source File: CSharpCompletionSorting.java    From consulo-csharp with 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 #29
Source File: FunctionProvider.java    From idea-php-toolbox with 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 #30
Source File: CompletionNavigationProvider.java    From idea-php-generics-plugin with MIT License 5 votes vote down vote up
@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);
}