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

The following are top voted examples for showing how to use com.intellij.codeInsight.lookup.LookupElement. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: intellij-spring-assistant   File: YamlValueInsertHandler.java   Source Code and 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 2
Project: TS-IJ   File: TSGlobalVariableReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    Collection<TSVarExpr> globals = TSUtil.getGlobalList(project);
    List<LookupElement> variants = new ArrayList<>();

    for (final TSVarExpr global : globals) {
        if (global.getName() != null && global.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(global)
                    .withIcon(TSIcons.FILE)
                    .withTypeText(global.getContainingFile().getName())
                    .withCaseSensitivity(false)

            );
        }
    }

    return variants.toArray();
}
 
Example 3
Project: TS-IJ   File: TSFunctionCallReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    Collection<TSFnDeclStmt> functions = TSUtil.getFunctionList(project);
    List<LookupElement> variants = new ArrayList<>();

    for (final TSFnDeclStmt function : functions) {
        if (function.getFunctionName() != null && function.getFunctionName().length() > 0) {
            variants.add(LookupElementBuilder.create(function)
                    .withIcon(TSIcons.FILE)
                    .withTypeText(function.getContainingFile().getName())
                    .withCaseSensitivity(false)

            );
        }
    }

    return variants.toArray();
}
 
Example 4
Project: TS-IJ   File: TSLiteralReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    Collection<TSObjectExpr> globals = TSUtil.getObjectList(project);
    List<LookupElement> variants = new ArrayList<>();

    for (final TSObjectExpr global : globals) {
        if (global.getName() != null && global.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(global)
                    .withIcon(TSIcons.FILE)
                    .withTypeText(global.getContainingFile().getName())
                    .withCaseSensitivity(false)

            );
        }
    }

    return variants.toArray();
}
 
Example 5
Project: AppleScript-IDEA   File: AppleScriptReferenceElementImpl.java   Source Code and License 6 votes vote down vote up
private void addLookupElement(List<LookupElement> lookupElements, PsiElement el) {
  if (!el.isValid()) return;
  LookupElementBuilder builder;
  if (el instanceof DictionaryComponent) {
    DictionaryComponent dc = (DictionaryComponent) el;
    String dName = dc.getDictionary().getName();
    builder = LookupElementBuilder.createWithIcon(dc).appendTailText("   " + dName, true);
  } else if (el instanceof AppleScriptComponent) {
    builder = LookupElementBuilder.createWithIcon((AppleScriptComponent) el);
    if (el instanceof AppleScriptHandlerPositionalParametersDefinition) {
      AppleScriptHandlerPositionalParametersDefinition handlerCall = (AppleScriptHandlerPositionalParametersDefinition) el;
      builder = builder.withInsertHandler(handlerCall.getFormalParameterList() != null ?
          ParenthesesInsertHandler.WITH_PARAMETERS : ParenthesesInsertHandler.NO_PARAMETERS);
    }
  } else {
    builder = LookupElementBuilder.create(el);
  }
  AppleScriptComponentType componentType = AppleScriptComponentType.typeOf(el);
  String typeText = componentType != null ? componentType.toString().toLowerCase() : null;
  builder = builder.withTypeText(typeText, null, true);
  lookupElements.add(builder);
}
 
Example 6
Project: idea-php-typo3-plugin   File: TranslationReferenceTest.java   Source Code and License 6 votes vote down vote up
public void testReferenceCanResolveVariants() {
    PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
            "\"LLL:EXT:foo/sample.xlf:sys_<caret>language.language_isocode.ab\";");

    PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent();
    PsiReference[] references = elementAtCaret.getReferences();
    for (PsiReference reference : references) {
        if (reference instanceof TranslationReference) {
            Object[] variants = reference.getVariants();
            for (Object variant : variants) {
                if (variant instanceof LookupElement) {
                    String lookupString = ((LookupElement) variant).getLookupString();
                    assertEquals("LLL:EXT:foo/sample.xlf:sys_language.language_isocode.ab", lookupString);
                    return;
                }
            }

        }
    }

    fail("No TranslationReference found");
}
 
Example 7
Project: greycat-idea-plugin   File: GCMReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    List<GCMTypeDeclaration> properties = GCMUtil.findProperties(project);
    List<LookupElement> variants = new ArrayList<LookupElement>();
    for (final GCMTypeDeclaration property : properties) {
        if (property != null && property.getName() != null && property.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(property).
                    withIcon(GCMIcons.GCM_ICON_16x16).
                    withTypeText(property.getContainingFile().getName())
            );
        }
    }
    return variants.toArray();
}
 
Example 8
Project: roc-completion   File: RocSettingsProvider.java   Source Code and License 6 votes vote down vote up
private List<LookupElement> getSubCompletions(PsiElement psiElement)
{
    JSProperty property = PsiTreeUtil.getParentOfType(psiElement, JSProperty.class);

    if (property == null)
    {
        return Collections.emptyList();
    }

    String name = property.getQualifiedName();

    if (name == null)
    {
        return Collections.emptyList();
    }

    Setting setting = CompletionPreloader
        .getCompletions()
        .getSetting(name);

    return setting != null ? setting.getSubCompletionVariants() : Collections.emptyList();
}
 
Example 9
Project: intellij-ce-playground   File: PyCustomType.java   Source Code and License 6 votes vote down vote up
@Override
public final boolean apply(@Nullable final Object input) {
  if (input == null) {
    return false;
  }
  if (myFilter == null) {
    return true; // No need to check
  }
  if (!(input instanceof LookupElement)) {
    return true; // Do not know how to check
  }
  final PyElement pyElement = PyUtil.as(((LookupElement)input).getPsiElement(), PyElement.class);
  if (pyElement == null) {
    return false;
  }
  return myFilter.process(pyElement);
}
 
Example 10
Project: intellij-ce-playground   File: JavaStaticMemberProcessor.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
protected LookupElement createLookupElement(@NotNull PsiMember member, @NotNull final PsiClass containingClass, boolean shouldImport) {
  shouldImport |= myOriginalPosition != null && PsiTreeUtil.isAncestor(containingClass, myOriginalPosition, false);

  if (member instanceof PsiMethod) {
    return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new GlobalMethodCallElement((PsiMethod)member, shouldImport, false));
  }
  return AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(new VariableLookupItem((PsiField)member, shouldImport) {
    @Override
    public void handleInsert(InsertionContext context) {
      FeatureUsageTracker.getInstance().triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME);

      super.handleInsert(context);
    }
  });
}
 
Example 11
Project: smcplugin   File: AbstractNamedLocalReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    List<LookupElement> variants = new ArrayList<>();

    Collection<ENCLOSED_TYPE> enclosedTypes = SmcPsiUtil.getElementsByTypeWithinParentType(myElement, enclosingTypeClass, enclosedTypeClass);
    for (final ENCLOSED_TYPE enclosed : enclosedTypes) {
        if (!StringUtil.isEmpty(enclosed.getName())) {
            variants.add(LookupElementBuilder.create(enclosed).
                    withIcon(getFile()).
                    withTypeText(enclosed.getContainingFile().getName())
            );
        }
    }
    return variants.toArray();
}
 
Example 12
Project: intellij-ce-playground   File: JavaMembersGetter.java   Source Code and License 6 votes vote down vote up
private void addConstantsFromReferencedClassesInSwitch(final Consumer<LookupElement> results) {
  final Set<PsiField> fields = ReferenceExpressionCompletionContributor.findConstantsUsedInSwitch(myPlace);
  final Set<PsiClass> classes = new HashSet<PsiClass>();
  for (PsiField field : fields) {
    ContainerUtil.addIfNotNull(classes, field.getContainingClass());
  }
  for (PsiClass aClass : classes) {
    processMembers(new Consumer<LookupElement>() {
      @Override
      public void consume(LookupElement element) {
        //noinspection SuspiciousMethodCalls
        if (!fields.contains(element.getObject())) {
          results.consume(TailTypeDecorator.withTail(element, TailType.CASE_COLON));
        }
      }
    }, aClass, true, false);
  }
}
 
Example 13
Project: intellij-ce-playground   File: GradleArgumentsCompletionProvider.java   Source Code and License 6 votes vote down vote up
protected List<LookupElement> getVariants(@NotNull final DataNode<ProjectData> projectDataNode, @NotNull final String modulePath) {
  final DataNode<ModuleData> moduleDataNode = findModuleDataNode(projectDataNode, modulePath);
  if (moduleDataNode == null) {
    return Collections.emptyList();
  }

  final ModuleData moduleData = moduleDataNode.getData();
  final boolean isRoot = projectDataNode.getData().getLinkedExternalProjectPath().equals(moduleData.getLinkedExternalProjectPath());
  final Collection<DataNode<TaskData>> tasks = ExternalSystemApiUtil.getChildren(moduleDataNode, ProjectKeys.TASK);
  List<LookupElement> elements = ContainerUtil.newArrayListWithCapacity(tasks.size());

  for (DataNode<TaskData> taskDataNode : tasks) {
    final TaskData taskData = taskDataNode.getData();
    elements.add(LookupElementBuilder.create(taskData.getName()).withIcon(ExternalSystemIcons.Task));
    if (!taskData.isInherited()) {
      elements.add(LookupElementBuilder.create((isRoot ? ':' : moduleData.getId() + ':') + taskData.getName())
                     .withIcon(ExternalSystemIcons.Task));
    }
  }
  return elements;
}
 
Example 14
Project: intellij-ce-playground   File: I18nReferenceContributor.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
  final Project project = myElement.getProject();
  PropertiesReferenceManager referenceManager = PropertiesReferenceManager.getInstance(project);
  final List<LookupElement> variants = new ArrayList<LookupElement>();
  referenceManager.processPropertiesFiles(GlobalSearchScopesCore.projectProductionScope(project), new PropertiesFileProcessor() {
    public boolean process(String baseName, PropertiesFile propertiesFile) {
      final Icon icon = propertiesFile.getContainingFile().getIcon(Iconable.ICON_FLAG_READ_STATUS);
      final String relativePath = ProjectUtil.calcRelativeToProjectPath(propertiesFile.getVirtualFile(), project);
      variants.add(LookupElementBuilder.create(propertiesFile, baseName)
                     .withIcon(icon)
                     .withTailText(" (" + relativePath + ")", true));
      return true;
    }
  }, this);
  return variants.toArray(new LookupElement[variants.size()]);
}
 
Example 15
Project: intellij-ce-playground   File: WordCompletionContributor.java   Source Code and License 6 votes vote down vote up
public static void addWordCompletionVariants(CompletionResultSet result, final CompletionParameters parameters, Set<String> excludes) {
  final Set<String> realExcludes = new HashSet<String>(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 16
Project: intellij-ce-playground   File: PyClassInsertHandler.java   Source Code and License 6 votes vote down vote up
public void handleInsert(InsertionContext context, LookupElement item) {
  final Editor editor = context.getEditor();
  final Document document = editor.getDocument();
  if (context.getCompletionChar() == '(') {
    context.setAddCompletionChar(false);
    final int offset = context.getTailOffset();
    document.insertString(offset, "()");

    PyClass pyClass = (PyClass) item.getObject();
    PyFunction init = pyClass.findInitOrNew(true, null);
    if (init != null && PyFunctionInsertHandler.hasParams(context, init)) {
      editor.getCaretModel().moveToOffset(offset+1);
      AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(context.getEditor(), init);
    }
    else {
      editor.getCaretModel().moveToOffset(offset+2);
    }
  }
}
 
Example 17
Project: intellij-ce-playground   File: PyModuleType.java   Source Code and License 6 votes vote down vote up
@NotNull
public static List<LookupElement> collectImportedSubmodulesAsLookupElements(@NotNull PsiFileSystemItem pyPackage,
                                                                            @NotNull PsiElement location,
                                                                            @Nullable final Set<String> existingNames) {

  final List<PsiElement> elements = collectImportedSubmodules(pyPackage, location);
  return elements != null ? ContainerUtil.mapNotNull(elements,
                                  new Function<PsiElement, LookupElement>() {
                                    @Override
                                    public LookupElement fun(PsiElement element) {
                                      if (element instanceof PsiFileSystemItem) {
                                        return buildFileLookupElement((PsiFileSystemItem)element, existingNames);
                                      }
                                      else if (element instanceof PsiNamedElement) {
                                        return LookupElementBuilder.createWithIcon((PsiNamedElement)element);
                                      }
                                      return null;
                                    }
                                  }) : Collections.<LookupElement>emptyList();
}
 
Example 18
Project: intellij-ce-playground   File: ActionOrGroupResolveConverter.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public LookupElement createLookupElement(ActionOrGroup actionOrGroup) {
  if (actionOrGroup instanceof Action) {
    Action action = (Action)actionOrGroup;
    final PsiElement element = getPsiElement(actionOrGroup);
    if (element == null) {
      throw new IllegalStateException(action.getId().getStringValue() + " in " + DomUtil.getFile(action) + " " + action.isValid() + " ");
    }

    LookupElementBuilder builder =
      LookupElementBuilder.create(ObjectUtils.assertNotNull(element),
                                  ObjectUtils.assertNotNull(getName(action)));

    final String text = action.getText().getStringValue();
    if (StringUtil.isNotEmpty(text)) {
      String withoutMnemonic = StringUtil.replace(text, "_", "");
      builder = builder.withTailText(" \"" + withoutMnemonic + "\"", true);
    }

    return builder;
  }

  return super.createLookupElement(actionOrGroup);
}
 
Example 19
Project: intellij-ce-playground   File: AndroidDslContributorTest.java   Source Code and License 6 votes vote down vote up
private void assertHasCompletions(String path, String... expectedCompletions) throws Exception {
  VirtualFile file = getProject().getBaseDir().findFileByRelativePath(path);
  assertNotNull(file);

  myFixture.configureFromExistingVirtualFile(file);

  LookupElement[] elements = myFixture.complete(CompletionType.BASIC);
  assertNotNull(elements);

  Set<String> suggestions = Sets.newHashSetWithExpectedSize(elements.length);
  for (LookupElement element : elements) {
    suggestions.add(element.getLookupString());
  }

  for (String expected : expectedCompletions) {
    String msg = String.format("%1$s not in available completions: {%2$s}", expected, Joiner.on(',').join(suggestions));
    assertTrue(msg, suggestions.contains(expected));
  }
}
 
Example 20
Project: intellij-ce-playground   File: DescendantClassesEnumMacro.java   Source Code and License 6 votes vote down vote up
@Override
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) {
  final List<PsiClass> classes = findDescendants(context, params);
  if (classes == null || classes.size() == 0) return null;

  Set<LookupElement> set = new LinkedHashSet<LookupElement>();
  boolean isShortName = params.length > 1 && !Boolean.valueOf(params[1].calculateResult(context).toString());

  for (PsiClass object : classes) {
    final String name = isShortName ? object.getName() : object.getQualifiedName();
    if (name != null && name.length() > 0) {
      set.add(LookupElementBuilder.create(name));
    }
  }

  return set.toArray(new LookupElement[set.size()]);
}
 
Example 21
Project: intellij-ce-playground   File: LookupTypedHandler.java   Source Code and License 6 votes vote down vote up
static CharFilter.Result getLookupAction(final char charTyped, final LookupImpl lookup) {
  final CharFilter.Result filtersDecision = getFiltersDecision(charTyped, lookup);

  final LookupElement currentItem = lookup.getCurrentItem();
  if (currentItem != null && charTyped != ' ') {
    String postfix = lookup.getAdditionalPrefix() + charTyped;
    final PrefixMatcher matcher = lookup.itemMatcher(currentItem);
    for (String lookupString : currentItem.getAllLookupStrings()) {
      if (lookupString.startsWith(matcher.getPrefix() + postfix)) {
        return CharFilter.Result.ADD_TO_PREFIX;
      }
    }
  }

  if (filtersDecision != null) {
    return filtersDecision;
  }
  throw new AssertionError("Typed char not handler by char filter: c=" + charTyped +
                           "; prefix=" + currentItem +
                           "; filters=" + Arrays.toString(getFilters()));
}
 
Example 22
Project: intellij-ce-playground   File: LegacyCompletionContributor.java   Source Code and License 6 votes vote down vote up
public static boolean completeReference(final CompletionParameters parameters, final CompletionResultSet result) {
  final CompletionData completionData = getCompletionData(parameters);
  if (completionData == null) {
    return false;
  }

  final Ref<Boolean> hasVariants = Ref.create(false);
  processReferences(parameters, result, new PairConsumer<PsiReference, CompletionResultSet>() {
    @Override
    public void consume(final PsiReference reference, final CompletionResultSet resultSet) {
      final Set<LookupElement> lookupSet = new LinkedHashSet<LookupElement>();
      completionData.completeReference(reference, lookupSet, parameters.getPosition(), parameters.getOriginalFile());
      for (final LookupElement item : lookupSet) {
        if (resultSet.getPrefixMatcher().prefixMatches(item)) {
          if (!item.isValid()) {
            LOG.error(completionData + " has returned an invalid lookup element " + item + " of " + item.getClass() +
                      " in " + parameters.getOriginalFile() + " of " + parameters.getOriginalFile().getClass());
          }
          hasVariants.set(true);
          resultSet.addElement(item);
        }
      }
    }
  });
  return hasVariants.get().booleanValue();
}
 
Example 23
Project: pysynthetic-intellij   File: SyntheticInitArgsCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext processingContext,
                              @NotNull CompletionResultSet result) {

    final PsiElement original = parameters.getOriginalPosition();
    if (original != null) {
        result = result.withPrefixMatcher(getPrefix(parameters.getOffset(), parameters.getOriginalFile()));
        SyntheticTypeInfo sti = processingContext.get(SYNTHETIC_TYPE_INFO_KEY);
        if (sti.hasSyntheticConstructor()) {
            for (SyntheticMemberInfo smi : sti.getMembers()) {
                LookupElement lookupElement =
                        LookupElementBuilder
                                .create(smi.getName() + "=")
                                .withIcon(PlatformIcons.PARAMETER_ICON);
                result.addElement(lookupElement);
            }
        }
    }
}
 
Example 24
Project: camel-idea-plugin   File: CamelSmartCompletionEndpointValue.java   Source Code and License 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 25
Project: intellij-ce-playground   File: AndroidCompletionContributor.java   Source Code and License 6 votes vote down vote up
private static CompletionResult customizeLayoutAttributeLookupElement(String localName,
                                                                      LookupElement lookupElement,
                                                                      CompletionResult result) {
  final String layoutPrefix = "layout_";

  if (!localName.startsWith(layoutPrefix)) {
    return result;
  }
  final String localSuffix = localName.substring(layoutPrefix.length());

  if (localSuffix.length() > 0) {
    final HashSet<String> lookupStrings = new HashSet<String>(lookupElement.getAllLookupStrings());
    lookupStrings.add(localSuffix);

    lookupElement = new LookupElementDecorator<LookupElement>(lookupElement) {
      @Override
      public Set<String> getAllLookupStrings() {
        return lookupStrings;
      }
    };
  }
  return result.withLookupElement(PrioritizedLookupElement.withPriority(lookupElement, 100.0));
}
 
Example 26
Project: intellij-ce-playground   File: InstanceofTypeProvider.java   Source Code and License 6 votes vote down vote up
private static LookupElement createInstanceofLookupElement(PsiClass psiClass, Set<PsiClass> toWildcardInheritors) {
  final PsiTypeParameter[] typeParameters = psiClass.getTypeParameters();
  if (typeParameters.length > 0) {
    for (final PsiClass parameterizedType : toWildcardInheritors) {
      if (psiClass.isInheritor(parameterizedType, true)) {
        PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
        final PsiWildcardType wildcard = PsiWildcardType.createUnbounded(psiClass.getManager());
        for (final PsiTypeParameter typeParameter : typeParameters) {
          substitutor = substitutor.put(typeParameter, wildcard);
        }
        final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());
        return PsiTypeLookupItem.createLookupItem(factory.createType(psiClass, substitutor), psiClass);
      }
    }
  }

  return new JavaPsiClassReferenceElement(psiClass);
}
 
Example 27
Project: intellij-ce-playground   File: LookupWithIndentsBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * @return result lookup elements (to display in {@link PsiReference#getVariants()} for example)
 */
@NotNull
LookupElement[] getResult() {
  final List<LookupElement> result = new ArrayList<LookupElement>(myMap.size());
  for (final Entry<LookupElementBuilder, Pair<String, Integer>> entry : myMap.entrySet()) {
    LookupElementBuilder elementBuilder = entry.getKey();
    final Pair<String, Integer> helpAndPriority = entry.getValue();
    final String help = helpAndPriority.first;

    if (!StringUtil.isEmptyOrSpaces(help)) {
      final int padding = myMaxLength - elementBuilder.getLookupString().length();
      elementBuilder = elementBuilder.withTailText(String.format("%s : %s", StringUtil.repeat(" ", padding), help));
    }
    if (myHasPriority) {
      // If we have priority and it is not provided for certain element we believe it is 0
      final int priority = (helpAndPriority.second == null ? 0 : helpAndPriority.second);
      result.add(PrioritizedLookupElement.withPriority(elementBuilder, priority));
    }
    else {
      result.add(elementBuilder);
    }
  }
  return result.toArray(new LookupElement[result.size()]);
}
 
Example 28
Project: intellij-spring-assistant   File: YamlValueInsertHandler.java   Source Code and License 5 votes vote down vote up
private boolean hasStartingOrEndingQuoteOfType(final InsertionContext insertionContext,
    final LookupElement lookupElement, final char quoteType) {
  final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset();
  final int startOfLookupStringOffset = caretOffset - lookupElement.getLookupString().length();


  final boolean hasStartingQuote =
      hasStartingQuote(insertionContext, quoteType, startOfLookupStringOffset);
  final boolean hasEndingQuote = hasEndingQuote(insertionContext, caretOffset, quoteType);

  return hasStartingQuote || hasEndingQuote;
}
 
Example 29
Project: intellij-spring-assistant   File: YamlValueInsertHandler.java   Source Code and License 5 votes vote down vote up
private void handleStartingQuote(final InsertionContext insertionContext,
    final LookupElement lookupElement, final char quoteType) {
  final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset();
  final int startOfLookupStringOffset = caretOffset - lookupElement.getLookupString().length();

  final boolean hasStartingQuote =
      hasStartingQuote(insertionContext, quoteType, startOfLookupStringOffset);

  if (!hasStartingQuote) {
    insertionContext.getDocument()
        .insertString(startOfLookupStringOffset, String.valueOf(quoteType));
  }
}
 
Example 30
Project: intellij-spring-assistant   File: Suggestion.java   Source Code and License 5 votes vote down vote up
public void renderElement(LookupElement element, LookupElementPresentation presentation) {
  Suggestion suggestion = (Suggestion) element.getObject();
  if (suggestion.icon != null) {
    presentation.setIcon(suggestion.icon);
  }

  presentation.setStrikeout(suggestion.deprecationLevel != null);
  if (suggestion.deprecationLevel != null) {
    if (suggestion.deprecationLevel == SpringConfigurationMetadataDeprecationLevel.error) {
      presentation.setItemTextForeground(RED);
    } else {
      presentation.setItemTextForeground(YELLOW);
    }
  }

  String lookupString = element.getLookupString();
  presentation.setItemText(lookupString);
  if (!lookupString.equals(suggestion.suggestion)) {
    presentation.setItemTextBold(true);
  }

  String shortDescription;
  if (suggestion.defaultValue != null) {
    shortDescription = shortenTextWithEllipsis(suggestion.defaultValue, 60, 0, true);
    TextAttributes attrs =
        EditorColorsManager.getInstance().getGlobalScheme().getAttributes(SCALAR_TEXT);
    presentation.setTailText("=" + shortDescription, attrs.getForegroundColor());
  }

  if (suggestion.description != null) {
    presentation.appendTailText(
        " (" + Util.getFirstSentenceWithoutDot(suggestion.description) + ")", true);
  }

  if (suggestion.shortType != null) {
    presentation.setTypeText(suggestion.shortType);
  }
}
 
Example 31
Project: TS-IJ   File: TSCaseCorrectingInsertHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handleInsert(InsertionContext context1, LookupElement item) {
    Editor editor = context1.getEditor();

    //If they typed the element we should replace the thing they're typing with the correct case
    // Even though Torque is case-insensitive it looks bad if we don't
    PsiElement editing = context1.getFile().findElementAt(context1.getStartOffset());
    if (editing != null) {
        //Delete the element they were typing (note to only go to their carat position)
        editor.getDocument().deleteString(editing.getTextOffset(), editor.getCaretModel().getCurrentCaret().getOffset());
        //And insert the correctly cased version
        EditorModificationUtil.insertStringAtCaret(editor, item.getLookupString(), true);
    }
}
 
Example 32
Project: AppleScript-IDEA   File: AppleScriptCompletionWeigher.java   Source Code and License 5 votes vote down vote up
@Override
public Integer weigh(@NotNull final LookupElement element, @NotNull final CompletionLocation location) {
  final Object lookupObject = element.getObject();
  CommandParameter parameter = null;
  boolean opt = false;
  if (lookupObject instanceof CommandParameter) {
    parameter = (CommandParameter) lookupObject;
    opt = parameter.isOptional();
  }
  return parameter != null && opt ? -10 : 0;
}
 
Example 33
Project: idea-php-typo3-plugin   File: RouteHelper.java   Source Code and License 5 votes vote down vote up
@NotNull
public static Collection<LookupElement> getRoutesLookupElements(@NotNull Project project) {
    Collection<LookupElement> routeLookupElements = new ArrayList<>();

    Collection<String> routes = FileBasedIndex.getInstance().getAllKeys(RouteIndex.KEY, project);
    for (String routeName : routes) {
        List<RouteStub> values = FileBasedIndex.getInstance().getValues(RouteIndex.KEY, routeName, GlobalSearchScope.allScope(project));
        values.forEach(r -> routeLookupElements.add(new RouteLookupElement(r)));
    }

    return routeLookupElements;
}
 
Example 34
Project: idea-php-typo3-plugin   File: TableUtil.java   Source Code and License 5 votes vote down vote up
public static void completeAvailableTableNames(@NotNull Project project, @NotNull CompletionResultSet completionResultSet) {
    for (String name : TableUtil.getAvailableTableNames(project)) {
        completionResultSet.addElement(new LookupElement() {
            @NotNull
            @Override
            public String getLookupString() {

                return name;
            }
        });
    }
}
 
Example 35
Project: idea-php-typo3-plugin   File: TableUtil.java   Source Code and License 5 votes vote down vote up
@NotNull
public static LookupElement[] createAvailableTableNamesLookupElements(@NotNull Project project) {
    Collection<LookupElement> elements = new HashSet<>();
    for (String name : TableUtil.getAvailableTableNames(project)) {
        elements.add(new TableLookupElement(name));
    }

    return elements.toArray(new LookupElement[elements.size()]);
}
 
Example 36
Project: idea-php-typo3-plugin   File: ControllerActionReferenceTest.java   Source Code and 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 37
Project: laravel-insight   File: FixtureSuite.java   Source Code and License 5 votes vote down vote up
@NotNull
protected LookupElement[] getCompletionElements(
    final PsiElement reference,
    final int referenceDistance
) {
    myFixture.getEditor().getCaretModel().getPrimaryCaret().moveToOffset(reference.getTextOffset() + referenceDistance);
    myFixture.completeBasic();

    return valueOf(myFixture.getLookupElements());
}
 
Example 38
Project: laravel-insight   File: FixtureSuite.java   Source Code and License 5 votes vote down vote up
protected void coverageHandleInsert(
    final PsiFile fileSample,
    final LookupElement completionElement
) {
    runWriteAction(() -> {
        final InsertionContext insertionContext = getInsertionContext(fileSample, completionElement);
        completionElement.handleInsert(insertionContext);
    });
}
 
Example 39
Project: laravel-insight   File: FixtureSuite.java   Source Code and License 5 votes vote down vote up
@NotNull
private InsertionContext getInsertionContext(
    final PsiFile fileSample,
    final LookupElement completionElement
) {
    final Editor fixtureEditor = myFixture.getEditor();

    return new InsertionContext(new OffsetMap(fixtureEditor.getDocument()),
                                Lookup.NORMAL_SELECT_CHAR,
                                new LookupElement[] { completionElement },
                                fileSample,
                                fixtureEditor,
                                false);
}
 
Example 40
Project: bamboo-soy   File: PostfixInsertHandler.java   Source Code and License 5 votes vote down vote up
public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  Project project = editor.getProject();

  if (project != null) {
    EditorModificationUtil.insertStringAtCaret(
        editor, closingTagBeforeCaret + closingTagAfterCaret);
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    EditorModificationUtil.moveCaretRelatively(editor, -closingTagAfterCaret.length());
  }
}
 
Example 41
Project: intellij-postfix-templates   File: SuggestShortVariableNameMacro.java   Source Code and License 5 votes vote down vote up
@Override
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, final ExpressionContext context) {
  String[] names = getNames(context);
  if (names == null || names.length < 2) return null;
  LookupElement[] items = new LookupElement[names.length];
  for(int i = 0; i < names.length; i++) {
    items[i] = LookupElementBuilder.create(names[i]);
  }
  return items;
}
 
Example 42
Project: hybris-integration-intellij-idea-plugin   File: FSKeywordCompletionProvider.java   Source Code and License 5 votes vote down vote up
public FSKeywordCompletionProvider(
    @NotNull final Set<String> keywords,
    @NotNull final Function<String, LookupElement> func
) {
    this.keywords = keywords;
    this.func = func;
}
 
Example 43
Project: hybris-integration-intellij-idea-plugin   File: ImpexKeywordCompletionProvider.java   Source Code and License 5 votes vote down vote up
public ImpexKeywordCompletionProvider(
    @NotNull final Set<String> keywords,
    @NotNull final Function<String, LookupElement> func
) {
    this.keywords = keywords;
    this.func = func;
}
 
Example 44
Project: manifold-ij   File: JsonCompletionTest.java   Source Code and License 5 votes vote down vote up
public void testCompletionLevel1() throws Exception
{
  myFixture.copyFileToProject( "json/sample/Person.json" );
  myFixture.configureByFile( "json/completion/TestJsonCompletion_1.java" );

  LookupElement[] complete = myFixture.complete( CompletionType.BASIC );
  List<String> strings = myFixture.getLookupElementStrings();
  assertTrue( strings.containsAll( Arrays.asList( "getFirstName","setFirstName", "getLastName","setLastName", "getAge","setAge", "toJson", "toXml" ) ) );
}
 
Example 45
Project: manifold-ij   File: PropertiesCompletionTest.java   Source Code and License 5 votes vote down vote up
public void testCompletionLevel1() throws Exception
{
  myFixture.copyFileToProject( "properties/sample/MyProperties.properties" );
  myFixture.configureByFile( "properties/completion/TestPropertiesCompletion_Level1.java" );

  LookupElement[] complete = myFixture.complete( CompletionType.BASIC );
  List<String> strings = myFixture.getLookupElementStrings();
  assertTrue( strings.containsAll( Arrays.asList( "bye", "hello", "getValueByName" ) ) );
}
 
Example 46
Project: manifold-ij   File: PropertiesCompletionTest.java   Source Code and License 5 votes vote down vote up
public void testCompletionLevel2() throws Exception
{
  myFixture.copyFileToProject( "properties/sample/MyProperties.properties" );
  myFixture.configureByFile( "properties/completion/TestPropertiesCompletion_Level2.java" );

  LookupElement[] complete = myFixture.complete( CompletionType.BASIC );
  List<String> strings = myFixture.getLookupElementStrings();
  assertTrue( strings.containsAll( Arrays.asList( "good", "getValue", "getValueByName" ) ) );
}
 
Example 47
Project: manifold-ij   File: ImageCompletionTest.java   Source Code and License 5 votes vote down vote up
public void testCompletion_Type() throws Exception
{
  myFixture.copyFileToProject( "image/sample/Logo.png" );
  myFixture.configureByFile( "image/completion/TestImageCompletion_Type.java" );

  LookupElement[] complete = myFixture.complete( CompletionType.BASIC );
  List<String> strings = myFixture.getLookupElementStrings();
  assertNotNull( strings );
  assertEquals( "Logo_png", strings.get( 0 ) );
  assertEquals( "image.sample.Logo_png", ((JavaPsiClassReferenceElement)complete[0]).getQualifiedName() );
}
 
Example 48
Project: manifold-ij   File: ExtCompletionTest.java   Source Code and License 5 votes vote down vote up
public void testCompletionLevel1() throws Exception
{
  myFixture.copyFileToProject( "extensions/java/lang/String/MyStringExt.java" );
  myFixture.configureByFile( "ext/completion/TestExtCompletion_1.java" );

  LookupElement[] complete = myFixture.completeBasic();
  List<String> strings = myFixture.getLookupElementStrings();
  assertTrue( strings.containsAll( Arrays.asList( "substringAfter", "substringBefore", "helloWorld" ) ) );
}
 
Example 49
Project: roc-completion   File: RocSettingsProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result)
{
    PsiElement position = parameters.getPosition();
    // Wrong file.
    if (!CompletionPreloader.isRocConfigFile(position.getContainingFile()))
    {
        return;
    }

    List<LookupElement> subCompletions = getSubCompletions(position);
    // Is this a request for sub-completons?
    if (subCompletions.size() > 0)
    {
        result.addAllElements(subCompletions);
        result.stopHere();

        return;
    }

    String prefix = result
        .getPrefixMatcher()
        .getPrefix();

    List<SettingLookupElement> completions = SettingCompletionBuilder.buildCompletions(parameters, prefix);

    Boolean foundCompletions = completions.size() > 0;
    Boolean isExtendedCompletion = parameters.isExtendedCompletion();

    // Add regular completions to the beginning of the list if user requested extended completions.
    if (!foundCompletions || isExtendedCompletion)
    {
        result.runRemainingContributors(parameters, true);
        return;
    }

    result.addAllElements(completions);
    // Don't display all the other junk.
    result.stopHere();
}
 
Example 50
Project: roc-completion   File: DefaultValue.java   Source Code and License 5 votes vote down vote up
List<LookupElement> getSubCompletionVariants()
{
    String enumerationSource = type;

    Boolean hasCorrectEnding = enumerationSource.endsWith("$/") || enumerationSource.endsWith("/i");

    if (!enumerationSource.startsWith("/^") || !hasCorrectEnding)
    {
        return Collections.emptyList();
    }

    enumerationSource = enumerationSource
        .replace("/^", "")
        .replace("$/i", "")
        .replace("/i", "")
        .replace("$/", "");

    List<LookupElement> subCompletions = new ArrayList<>();

    for (String subCompletion : enumerationSource.split("\\|"))
    {
        if (subCompletion.equals(this.toString()))
        {
            continue;
        }

        subCompletions.add(LookupElementBuilder.create(subCompletion));
    }

    return subCompletions;
}
 
Example 51
Project: mule-intellij-plugins   File: FlowRenameDialog.java   Source Code and License 5 votes vote down vote up
private void completeVariable(Editor editor) {
    String prefix = this.myNameSuggestionsField.getEnteredName();
    PsiReference reference = this.myTag.getReference();
    if(reference instanceof TagNameReference) {
        LookupElement[] lookupItems = TagNameReferenceCompletionProvider.getTagNameVariants(this.myTag, this.myTag.getNamespacePrefix());
        editor.getCaretModel().moveToOffset(prefix.length());
        editor.getSelectionModel().removeSelection();
        LookupManager.getInstance(this.getProject()).showLookup(editor, lookupItems, prefix);
    }

}
 
Example 52
Project: intellij-ce-playground   File: XmlCompletionContributor.java   Source Code and License 5 votes vote down vote up
static void completeTagName(CompletionParameters parameters, CompletionResultSet result) {
  PsiElement element = parameters.getPosition();
  if (!isXmlNameCompletion(parameters)) return;
  result.stopHere();
  PsiElement parent = element.getParent();
  if (!(parent instanceof XmlTag) ||
      !(parameters.getOriginalFile() instanceof XmlFile)) {
    return;
  }
  final XmlTag tag = (XmlTag)parent;
  final String namespace = tag.getNamespace();
  final String prefix = result.getPrefixMatcher().getPrefix();
  final int pos = prefix.indexOf(':');

  final PsiReference reference = tag.getReference();
  String namespacePrefix = tag.getNamespacePrefix();

  if (reference != null && !namespace.isEmpty() && !namespacePrefix.isEmpty()) {
    // fallback to simple completion
    result.runRemainingContributors(parameters, true);
  }
  else {

    final CompletionResultSet newResult = result.withPrefixMatcher(pos >= 0 ? prefix.substring(pos + 1) : prefix);

    final XmlFile file = (XmlFile)parameters.getOriginalFile();
    final List<XmlExtension.TagInfo> names = XmlExtension.getExtension(file).getAvailableTagNames(file, tag);
    for (XmlExtension.TagInfo info : names) {
      final LookupElement item = createLookupElement(info, info.namespace, namespacePrefix.isEmpty() ? null : namespacePrefix);
      newResult.addElement(item);
    }
  }
}
 
Example 53
Project: intellij-ce-playground   File: XmlParameterInfoHandler.java   Source Code and License 5 votes vote down vote up
@Override
public Object[] getParametersForLookup(LookupElement item, ParameterInfoContext context) {
  if (!(item instanceof MutableLookupElement)) return null;
  final Object lookupItem = item.getObject();
  if (lookupItem instanceof XmlElementDescriptor) return new Object[]{lookupItem};
  return null;
}
 
Example 54
Project: intellij-ce-playground   File: CommandLineCompletionProvider.java   Source Code and License 5 votes vote down vote up
protected LookupElement createLookupElement(@NotNull Option option, @NotNull String text) {
  LookupElementBuilder res = LookupElementBuilder.create(text);

  if (option.getDescription() != null) {
    return TailTypeDecorator.withTail(res.withTypeText(option.getDescription(), true), TailType.INSERT_SPACE);
  }

  return res;
}
 
Example 55
Project: intellij-ce-playground   File: FunctionalExpressionCompletionProvider.java   Source Code and License 5 votes vote down vote up
private static void collectThisVariants(PsiType functionalInterfaceType,
                                        PsiParameter[] params,
                                        PsiElement originalPosition,
                                        PsiSubstitutor substitutor, PsiType expectedReturnType, List<LookupElement> result) {
  final PsiClass psiClass = PsiTreeUtil.getParentOfType(originalPosition, PsiClass.class);
  if (psiClass != null) {
    for (PsiMethod psiMethod : psiClass.getMethods()) {
      final PsiType returnType = psiMethod.getReturnType();
      if (isInstanceMethodWithAppropriateReturnType(expectedReturnType, psiMethod, returnType) &&
          areParameterTypesAppropriate(psiMethod, params, substitutor, 0)) {
        LookupElement methodRefLookupElement = LookupElementBuilder
          .create(psiMethod)
          .withPresentableText("this::" + psiMethod.getName())
          .withInsertHandler(new InsertHandler<LookupElement>() {
            @Override
            public void handleInsert(InsertionContext context, LookupElement item) {
              final int startOffset = context.getStartOffset();
              final Document document = context.getDocument();
              document.insertString(startOffset, "this::");
            }
          })
          .withTypeText(functionalInterfaceType.getPresentableText())
          .withIcon(AllIcons.Nodes.MethodReference)
          .withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
        result.add(methodRefLookupElement);
      }
    }
  }
}
 
Example 56
Project: intellij-ce-playground   File: XmlCompletionContributor.java   Source Code and License 5 votes vote down vote up
public static LookupElement createLookupElement(XmlExtension.TagInfo tagInfo,
                                                final String tailText, @Nullable String namespacePrefix) {
  LookupElementBuilder builder =
    LookupElementBuilder.create(tagInfo, tagInfo.name).withInsertHandler(
      new ExtendedTagInsertHandler(tagInfo.name, tagInfo.namespace, namespacePrefix));
  if (!StringUtil.isEmpty(tailText)) {
    builder = builder.withTypeText(tailText, true);
  }
  return builder;
}
 
Example 57
Project: intellij-ce-playground   File: PyIterableVariableMacro.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) {
  final List<LookupElement> results = new ArrayList<LookupElement>();
  final PsiElement element = context.getPsiElementAtStartOffset();
  if (element != null) {
    for (PsiNamedElement iterableElement : getIterableElements(element)) {
      results.add(LookupElementBuilder.create(iterableElement));
    }
  }
  return results.toArray(new LookupElement[results.size()]);
}
 
Example 58
Project: intellij-ce-playground   File: LanguageReference.java   Source Code and License 5 votes vote down vote up
@NotNull
public Object[] getVariants() {
  List<Injectable> list = InjectLanguageAction.getAllInjectables();
  return ContainerUtil.map2Array(list, LookupElement.class, new Function<Injectable, LookupElement>() {
    @Override
    public LookupElement fun(Injectable injectable) {
      return LookupElementBuilder.create(injectable.getId()).withIcon(injectable.getIcon()).withTailText(
        "(" + injectable.getDisplayName() + ")", true);
    }
  });
}
 
Example 59
Project: intellij-ce-playground   File: GroovyCompletionUtil.java   Source Code and License 5 votes vote down vote up
public static List<LookupElement> getCompletionVariants(GroovyResolveResult[] candidates,
                                                        boolean afterNew,
                                                        PrefixMatcher matcher,
                                                        PsiElement position) {
  List<LookupElement> result = ContainerUtil.newArrayList();
  for (GroovyResolveResult candidate : candidates) {
    result.addAll(createLookupElements(candidate, afterNew, matcher, position));
    ProgressManager.checkCanceled();
  }

  return result;
}
 
Example 60
Project: smcplugin   File: SmcJavaClassReference.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    List<PsiClass> classesForPackage = SmcPsiUtil.findClassesForPackage(packageName, myElement.getProject());
    List<LookupElement> variants = new ArrayList<LookupElement>();

    for (final PsiClass psiClass : classesForPackage) {
        if (!StringUtils.isEmpty(psiClass.getQualifiedName())) {
            variants.add(JavaLookupElementBuilder.forClass(psiClass));
        }
    }
    return variants.toArray();
}