com.intellij.codeInsight.completion.CompletionUtil Java Examples

The following examples show how to use com.intellij.codeInsight.completion.CompletionUtil. 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: CamelJavaBeanReferenceSmartCompletion.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
    final PsiElement element = completionParameters.getPosition();
    final PsiClass psiClass = getCamelIdeaUtils().getBean(element);

    if (psiClass != null) {
        Collection<PsiMethod> methods = getJavaMethodUtils().getMethods(psiClass);

        List<LookupElement> answer = getJavaMethodUtils().getBeanAccessibleMethods(methods)
            .stream()
            .map(method -> buildLookupElement(method, getJavaMethodUtils().getPresentableMethodWithParameters(method)))
            .collect(toList());

        // are there any results then add them
        if (!answer.isEmpty()) {
            String hackVal = element.getText();
            hackVal = hackVal.substring(1, hackVal.indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED));
            completionResultSet.withPrefixMatcher(hackVal).addAllElements(answer);
            completionResultSet.stopHere();
        }
    }
}
 
Example #2
Source File: DocumentationManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public PsiElement getElementFromLookup(Editor editor, @Nullable PsiFile file) {
  Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup();

  if (activeLookup != null) {
    LookupElement item = activeLookup.getCurrentItem();
    if (item != null) {
      int offset = editor.getCaretModel().getOffset();
      if (offset > 0 && offset == editor.getDocument().getTextLength()) offset--;
      PsiReference ref = TargetElementUtil.findReference(editor, offset);
      PsiElement contextElement = file == null ? null : ObjectUtils.coalesce(file.findElementAt(offset), file);
      PsiElement targetElement = ref != null ? ref.getElement() : contextElement;
      if (targetElement != null) {
        PsiUtilCore.ensureValid(targetElement);
      }

      DocumentationProvider documentationProvider = getProviderFromElement(file);
      PsiManager psiManager = PsiManager.getInstance(myProject);
      PsiElement fromProvider = targetElement == null ? null : documentationProvider.getDocumentationElementForLookupItem(psiManager, item.getObject(), targetElement);
      return fromProvider != null ? fromProvider : CompletionUtil.getTargetElement(item);
    }
  }
  return null;
}
 
Example #3
Source File: LiftShorterItemsClassifier.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void addElement(@Nonnull LookupElement added, @Nonnull ProcessingContext context) {
  myCount++;

  for (String string : CompletionUtil.iterateLookupStrings(added)) {
    if (string.length() == 0) continue;

    myElements.putValue(string, added);
    mySortedStrings.add(string);
    final NavigableSet<String> after = mySortedStrings.tailSet(string, false);
    for (String s : after) {
      if (!s.startsWith(string)) {
        break;
      }
      for (LookupElement longer : myElements.get(s)) {
        updateLongerItem(added, longer);
      }
    }
  }
  super.addElement(added, context);

  calculateToLift(added);
}
 
Example #4
Source File: MyPsiPolyVariantReference.java    From CppTools with Apache License 2.0 6 votes vote down vote up
public Object[] getVariants() {
  final PsiFile psiFile = psiElement.getContainingFile().getOriginalFile();
  int offset = psiElement.getText().indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
  CompletionCommand completion = new CompletionCommand(psiFile.getVirtualFile().getPath(), psiElement.getTextOffset() + offset);
  completion.post(psiFile.getProject());

  if (!completion.hasReadyResult()) return ArrayUtil.EMPTY_OBJECT_ARRAY;

  final List<String> list = completion.getVariants();
  if (list != null) {
    Object[] result = new Object[list.size()];
    int i = 0;

    EnvironmentFacade facade = EnvironmentFacade.getInstance();
    for (String s : list) {
      result[i++] = facade.createLookupElement(s);
    }
    return result;
  }
  return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
 
Example #5
Source File: CamelContributor.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the PSI text {@link CompletionUtil#DUMMY_IDENTIFIER} and " character and remove them.
 * <p/>
 * This implementation support Java literal expressions and XML attributes where you can define Camel endpoints.
 *
 * @param parameters - completion parameter to parse
 * @return new string stripped for any {@link CompletionUtil#DUMMY_IDENTIFIER} and " character
 */
@NotNull
private static String[] parsePsiElement(@NotNull CompletionParameters parameters) {
    PsiElement element = parameters.getPosition();

    String val = getIdeaUtils().extractTextFromElement(element, true, true, true);
    if (val == null || val.isEmpty()) {
        return new String[]{"", ""};
    }

    String valueAtPosition = getIdeaUtils().extractTextFromElement(element, true, false, true);

    String suffix = "";

    // okay IDEA folks its not nice, in groovy the dummy identifier is using lower case i in intellij
    // so we need to lower case it all
    String hackVal = valueAtPosition.toLowerCase();
    int len = CompletionUtil.DUMMY_IDENTIFIER.length();
    int hackIndex = hackVal.indexOf(CompletionUtil.DUMMY_IDENTIFIER.toLowerCase());
    //let's scrub the data for any Intellij stuff
    val = val.replace(CompletionUtil.DUMMY_IDENTIFIER, "");
    if (hackIndex == -1) {
        val = val.replace(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED, "");
        hackIndex = hackVal.indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED.toLowerCase());
        len = CompletionUtil.DUMMY_IDENTIFIER_TRIMMED.length();
    }

    if (hackIndex > -1) {
        suffix = valueAtPosition.substring(hackIndex + len);
        valueAtPosition = valueAtPosition.substring(0, hackIndex);
    }

    return new String[]{val, suffix, valueAtPosition};
}
 
Example #6
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
private int getCaretPositionInsidePsiElement(String stringLiteral) {
    String hackVal = stringLiteral.toLowerCase();

    int hackIndex = hackVal.indexOf(CompletionUtil.DUMMY_IDENTIFIER.toLowerCase());
    if (hackIndex == -1) {
        hackIndex = hackVal.indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED.toLowerCase());
    }
    return hackIndex;
}
 
Example #7
Source File: IdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
public boolean isCaretAtEndOfLine(PsiElement element) {
    String value = extractTextFromElement(element).trim();

    if (value != null) {
        value = value.toLowerCase();
        return value.endsWith(CompletionUtil.DUMMY_IDENTIFIER.toLowerCase())
            || value.endsWith(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED.toLowerCase());
    }

    return false;
}
 
Example #8
Source File: YamlKeywordsCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    PsiElement psiElement = parameters.getPosition();

    if (psiElement instanceof LeafPsiElement) {
        // Don't complete after tag (at end of line)
        // key: !my_tag <caret>\n
        if (YamlHelper.isElementAfterYamlTag(psiElement)) {
            return;
        }

        // Don't complete after End Of Line:
        // key: foo\n
        // <caret>
        if (YamlHelper.isElementAfterEol(psiElement)) {
            return;
        }

        String prefix = psiElement.getText();

        if (prefix.contains(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED)) {
            prefix = prefix.substring(0, prefix.indexOf(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED));
        }

        result = result.withPrefixMatcher(prefix);
    }

    for (Map.Entry<String, String> entry : YAML_KEYWORDS.entrySet()) {
        String yamlKeyword = entry.getKey();
        String yamlType = entry.getValue();

        LookupElementBuilder lookupElement = LookupElementBuilder.create(yamlKeyword)
                .withTypeText(yamlType);

        result.addElement(lookupElement);
    }
}
 
Example #9
Source File: TargetElementUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiElement getTargetElementFromLookup(Project project) {
  Lookup activeLookup = LookupManager.getInstance(project).getActiveLookup();
  if (activeLookup != null) {
    LookupElement item = activeLookup.getCurrentItem();
    final PsiElement psi = item == null ? null : CompletionUtil.getTargetElement(item);
    if (psi != null && psi.isValid()) {
      return psi;
    }
  }
  return null;
}
 
Example #10
Source File: LiftShorterItemsClassifier.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void calculateToLift(LookupElement element) {
  for (String string : CompletionUtil.iterateLookupStrings(element)) {
    for (int len = 1; len < string.length(); len++) {
      String prefix = string.substring(0, len);
      for (LookupElement shorterElement : myElements.get(prefix)) {
        if (myCondition.shouldLift(shorterElement, element)) {
          myToLift.putValue(element, shorterElement);
          myReversedToLift.putValue(shorterElement, element);
        }
      }
    }
  }
}
 
Example #11
Source File: LiftShorterItemsClassifier.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void removeElement(@Nonnull LookupElement element, @Nonnull ProcessingContext context) {
  for (String s : CompletionUtil.iterateLookupStrings(element)) {
    myElements.remove(s, element);
    if (myElements.get(s).isEmpty()) {
      mySortedStrings.remove(s);
    }
  }

  removeFromMap(element, myToLift, myReversedToLift);
  removeFromMap(element, myReversedToLift, myToLift);

  super.removeElement(element, context);
}
 
Example #12
Source File: CamelHumpMatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isStartMatch(LookupElement element) {
  for (String s : CompletionUtil.iterateLookupStrings(element)) {
    FList<TextRange> ranges = myCaseInsensitiveMatcher.matchingFragments(s);
    if (ranges == null) continue;
    if (ranges.isEmpty() || skipUnderscores(s) >= ranges.get(0).getStartOffset()) {
      return true;
    }
  }

  return false;
}
 
Example #13
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static List<TemplateImpl> filterApplicableCandidates(PsiFile file, int caretOffset, List<TemplateImpl> candidates) {
  if (candidates.isEmpty()) {
    return candidates;
  }

  PsiFile copy = insertDummyIdentifierWithCache(file, caretOffset, caretOffset, CompletionUtil.DUMMY_IDENTIFIER_TRIMMED).getFile();

  List<TemplateImpl> result = new ArrayList<>();
  for (TemplateImpl candidate : candidates) {
    if (isApplicable(copy, caretOffset - candidate.getKey().length(), candidate)) {
      result.add(candidate);
    }
  }
  return result;
}
 
Example #14
Source File: PopupUpdateProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeShown(final LightweightWindowEvent windowEvent) {
  final Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup();
  if (activeLookup != null) {
    activeLookup.addLookupListener(new LookupAdapter() {
      @Override
      public void currentItemChanged(LookupEvent event) {
        if (windowEvent.asPopup().isVisible()) { //was not canceled yet
          final LookupElement item = event.getItem();
          if (item != null) {
            PsiElement targetElement = CompletionUtil.getTargetElement(item);
            if (targetElement == null) {
              targetElement = DocumentationManager.getInstance(myProject).getElementFromLookup(activeLookup.getEditor(), activeLookup.getPsiFile());
            }

            updatePopup(targetElement); //open next
          }
        } else {
          activeLookup.removeLookupListener(this);
        }
      }
    });
  }
  else {
    final Component focusedComponent = WindowManagerEx.getInstanceEx().getFocusedComponent(myProject);
    boolean fromQuickSearch = focusedComponent != null && focusedComponent.getParent() instanceof ChooseByNameBase.JPanelProvider;
    if (fromQuickSearch) {
      ChooseByNameBase.JPanelProvider panelProvider = (ChooseByNameBase.JPanelProvider)focusedComponent.getParent();
      panelProvider.registerHint(windowEvent.asPopup());
    }
    else if (focusedComponent instanceof JComponent) {
      HintUpdateSupply supply = HintUpdateSupply.getSupply((JComponent)focusedComponent);
      if (supply != null) supply.registerHint(windowEvent.asPopup());
    }
  }
}
 
Example #15
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static List<TemplateImpl> listApplicableTemplateWithInsertingDummyIdentifier(Editor editor, PsiFile file, boolean selectionOnly) {
  int startOffset = editor.getSelectionModel().getSelectionStart();
  int endOffset = editor.getSelectionModel().getSelectionEnd();
  OffsetsInFile offsets = insertDummyIdentifierWithCache(file, startOffset, endOffset, CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
  return listApplicableTemplates(offsets.getFile(), getStartOffset(offsets), selectionOnly);
}