com.intellij.psi.util.PsiElementFilter#com.intellij.codeInsight.completion.CompletionUtil源码实例Demo

下面列出了com.intellij.psi.util.PsiElementFilter#com.intellij.codeInsight.completion.CompletionUtil 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。


@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();
        }
    }
}
 
源代码2 项目: consulo   文件: DocumentationManager.java

@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;
}
 

@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);
}
 

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;
}
 

/**
 * 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};
}
 
源代码6 项目: camel-idea-plugin   文件: IdeaUtils.java

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;
}
 
源代码7 项目: camel-idea-plugin   文件: IdeaUtils.java

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;
}
 

@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);
    }
}
 
源代码9 项目: consulo   文件: TargetElementUtil.java

@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;
}
 

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);
        }
      }
    }
  }
}
 

@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);
}
 
源代码12 项目: consulo   文件: CamelHumpMatcher.java

@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;
}
 
源代码13 项目: consulo   文件: TemplateManagerImpl.java

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;
}
 
源代码14 项目: consulo   文件: PopupUpdateProcessor.java

@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());
    }
  }
}
 
源代码15 项目: consulo   文件: TemplateManagerImpl.java

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);
}