com.intellij.codeInsight.completion.CompletionParameters Java Examples

The following examples show how to use com.intellij.codeInsight.completion.CompletionParameters. 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: SQFVariableCompletionProvider.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
	PsiElement cursor = parameters.getOriginalPosition(); //cursor is on a word
	Project project = parameters.getOriginalFile().getProject();

	boolean originalPositionNull = cursor == null;
	if (originalPositionNull) {
		cursor = parameters.getPosition(); //cursor is after a word
	}
	if (forLocalVars) {
		if (cursor.getText().startsWith("_fnc")) {
			CompletionAdders.addFunctions(parameters, result);
		}
		CompletionAdders.addVariables(parameters, context, result, cursor, true);
	} else {
		if (cursor.getText().startsWith("BIS_")) {
			CompletionAdders.addBISFunctions(project, result);
		} else {
			CompletionAdders.addLiterals(cursor, result, false);
			CompletionAdders.addVariables(parameters, context, result, cursor, false);
			CompletionAdders.addCommands(project, result);
		}
	}
}
 
Example #2
Source File: AssetCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull final CompletionResultSet resultSet) {
    Project project = parameters.getPosition().getProject();

    if(!Symfony2ProjectComponent.isEnabled(parameters.getPosition())) {
        return;
    }

    for (AssetFile assetFile : assetParser.getAssetFiles(project)) {
        resultSet.addElement(new AssetLookupElement(assetFile, project));
    }

    if(includeCustom) {
        TwigNamedAssetsServiceParser twigPathServiceParser = ServiceXmlParserFactory.getInstance(project, TwigNamedAssetsServiceParser.class);
        for (String s : twigPathServiceParser.getNamedAssets().keySet()) {
            resultSet.addElement(LookupElementBuilder.create("@" + s).withIcon(PlatformIcons.FOLDER_ICON).withTypeText("Custom Assets", true));
        }
    }
}
 
Example #3
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 #4
Source File: FluidUtil.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
public static void completeViewHelperArguments(CompletionParameters parameters, CompletionResultSet result) {
    PsiElement psiElement = parameters.getPosition();

    FluidViewHelperExpr viewHelperExpr = (FluidViewHelperExpr) PsiTreeUtil.findFirstParent(psiElement, p -> p instanceof FluidViewHelperExpr);
    if (viewHelperExpr == null) {
        if (psiElement.getParent().getPrevSibling() instanceof FluidViewHelperExpr) {
            viewHelperExpr = (FluidViewHelperExpr) psiElement.getParent().getPrevSibling();
        } else if (psiElement.getParent() instanceof FluidInlineChain && psiElement.getParent().getFirstChild() instanceof FluidViewHelperExpr) {
            viewHelperExpr = (FluidViewHelperExpr) psiElement.getParent().getFirstChild();
        } else {
            return;
        }
    }

    Map<String, ViewHelper> allViewHelpersInContextByName = ViewHelperUtil.findAllViewHelpersInContextByName(psiElement.getProject(), psiElement);
    String viewHelperExprPresentableName = viewHelperExpr.getPresentableName();
    if (!allViewHelpersInContextByName.containsKey(viewHelperExprPresentableName)) {
        return;
    }

    allViewHelpersInContextByName.get(viewHelperExprPresentableName).arguments.forEach((name, argument) -> {
        result.addElement(FluidUtil.viewHelperArgumentLookupElement(psiElement, name, argument));
    });
}
 
Example #5
Source File: LSContentAssistProcessor.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
    Document document = parameters.getEditor().getDocument();
    Editor editor = parameters.getEditor();
    Project project = parameters.getOriginalFile().getProject();
    int offset = parameters.getOffset();
    initiateLanguageServers(project, document);
    CompletionParams param;
    try {
        param = LSPIJUtils.toCompletionParams(LSPIJUtils.toUri(document), offset, document);
        List<LookupElement> proposals = Collections.synchronizedList(new ArrayList<>());
        this.completionLanguageServersFuture
                .thenComposeAsync(languageServers -> CompletableFuture.allOf(languageServers.stream()
                        .map(languageServer -> languageServer.getTextDocumentService().completion(param)
                                .thenAcceptAsync(completion -> proposals
                                        .addAll(toProposals(project, editor, document, offset, completion, languageServer))))
                        .toArray(CompletableFuture[]::new)))
                .get();
        result.addAllElements(proposals);
    } catch (RuntimeException | InterruptedException | ExecutionException e) {
        LOGGER.warn(e.getLocalizedMessage(), e);
        result.addElement(createErrorProposal(offset, e));
    }
    super.fillCompletionVariants(parameters, result);
}
 
Example #6
Source File: SoyCompletionContributor.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
@Override
public void fillCompletionVariants(
    @NotNull final CompletionParameters parameters,
    @NotNull final CompletionResultSet resultSet) {
  super.fillCompletionVariants(parameters, resultSet);

  // Discard _semantically_ invalid suggestions accepted by CamelHumpMatcher
  // (e.g. @state in @state/@param default initializer). We provide these ourselves.
  resultSet.runRemainingContributors(
      parameters,
      completionResult -> {
        if (completionResult.getLookupElement() != null) {
          if (completionResult.getLookupElement().getLookupString().startsWith("$")) {
            return;
          }
          resultSet.addElement(completionResult.getLookupElement());
        }
      });
}
 
Example #7
Source File: SoyCompletionContributor.java    From bamboo-soy with Apache License 2.0 6 votes vote down vote up
/**
 * Complete the "visibility" and "stricthtml" keywords in template definition open tags.
 */
private void extendWithTemplateDefinitionLevelKeywords() {
  extend(
      CompletionType.BASIC,
      psiElement().andOr(psiElement().inside(SoyBeginTemplate.class)),
      new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(
            @NotNull CompletionParameters completionParameters,
            ProcessingContext processingContext,
            @NotNull CompletionResultSet completionResultSet) {
          if (isPrecededBy(
              completionParameters.getPosition(),
              elt -> elt instanceof SoyTemplateDefinitionIdentifier)) {
            completionResultSet.addElement(LookupElementBuilder.create("visibility=\"private\""));
            completionResultSet.addElement(LookupElementBuilder.create("stricthtml=\"true\""));
          }
        }
      });
}
 
Example #8
Source File: LattePhpNamespaceCompletionProvider.java    From intellij-latte with MIT License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters params, ProcessingContext context, @NotNull CompletionResultSet result) {
	PsiElement curr = params.getPosition().getOriginalElement();
	if (PsiTreeUtil.getParentOfType(curr, LattePhpContent.class) == null) {
		return;
	}

	PhpIndex phpIndex = PhpIndex.getInstance(curr.getProject());
	String prefix = result.getPrefixMatcher().getPrefix();
	String namespace = "";
	if (prefix.contains("\\")) {
		int index = prefix.lastIndexOf("\\");
		namespace = prefix.substring(0, index) + "\\";
		prefix = prefix.substring(index + 1);
	}
	PhpCompletionUtil.addSubNamespaces(namespace, result.withPrefixMatcher(prefix), phpIndex, PhpNamespaceInsertHandler.getInstance());
}
 
Example #9
Source File: PhpEntityClassCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {

        if(!Symfony2ProjectComponent.isEnabled(parameters.getPosition())) {
            return;
        }

        PhpIndex phpIndex = PhpIndex.getInstance(parameters.getOriginalFile().getProject());
        Map<String, String> entityNamespaces = ServiceXmlParserFactory.getInstance(parameters.getOriginalFile().getProject(), EntityNamesServiceParser.class).getEntityNameMap();

        // copied from PhpCompletionUtil::addClassesInNamespace looks the official way to find classes in namespaces
        // its a really performance nightmare

        Collection<String> names = phpIndex.getAllClassNames(new CamelHumpMatcher(resultSet.getPrefixMatcher().getPrefix()));
        for (String name : names) {
            Collection<PhpClass> classes = phpIndex.getClassesByName(name);

            for(Map.Entry<String, String> entry: entityNamespaces.entrySet()) {
                String namespaceFqn = PhpLangUtil.toFQN(entry.getValue());
                Collection<PhpClass> filtered = PhpCompletionUtil.filterByNamespace(classes, namespaceFqn);
                for (PhpClass phpClass : filtered) {
                    resultSet.addElement(new PhpClassLookupElement(phpClass, true, PhpClassReferenceInsertHandler.getInstance()));
                }
            }
        }
    }
 
Example #10
Source File: CompletionAdders.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
public static void addVariables(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result,
								@NotNull PsiElement cursor, boolean forLocalVars) {
	HashSet<String> putVars = new HashSet<>();
	PsiUtil.traverseDepthFirstSearch(parameters.getOriginalFile().getNode(), astNode -> {
		PsiElement nodeAsElement = astNode.getPsi();
		if (nodeAsElement == cursor) {
			return false;
		}
		if (!(nodeAsElement instanceof SQFVariable)) {
			return false;
		}
		SQFVariable var = (SQFVariable) nodeAsElement;
		if (((var.isLocal() && forLocalVars) || (!var.isLocal() && !forLocalVars)) && !putVars.contains(var.getVarName().toLowerCase())) {
			putVars.add(var.getVarName().toLowerCase());
			result.addElement(PrioritizedLookupElement.withPriority(
					LookupElementBuilder.createWithSmartPointer(var.getVarName(), var)
							.withTailText(var.isMagicVar() ? " (Magic Var)" : (
											forLocalVars ? " (Local Variable)" : " (Global Variable)"
									)
							)
							.withIcon(var.isMagicVar() ? ArmaPluginIcons.ICON_SQF_MAGIC_VARIABLE : ArmaPluginIcons.ICON_SQF_VARIABLE), VAR_PRIORITY)
			);
		}
		return false;
	});
}
 
Example #11
Source File: SimpleCompletionExtension.java    From camel-idea-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context,
                    @NotNull CompletionResultSet resultSet, @NotNull String[] query) {
    PsiElement element = parameters.getPosition();
    Module module = ModuleUtilCore.findModuleForPsiElement(element);
    if (module == null) {
        return;
    }

    List<LookupElement> results = findResults(element, getQueryAtPosition(query));
    if (!results.isEmpty()) {
        resultSet
            .withRelevanceSorter(CompletionSorter.emptySorter())
            .addAllElements(results);
        resultSet.stopHere();
    }
}
 
Example #12
Source File: ShaderLabCGCompletionContributor.java    From consulo-unity3d with Apache License 2.0 6 votes vote down vote up
public ShaderLabCGCompletionContributor()
{
	extend(CompletionType.BASIC, StandardPatterns.psiElement().withLanguage(CGLanguage.INSTANCE), new CompletionProvider()
	{
		@RequiredReadAction
		@Override
		public void addCompletions(@Nonnull CompletionParameters parameters, ProcessingContext context, @Nonnull final CompletionResultSet result)
		{
			Place shreds = InjectedLanguageUtil.getShreds(parameters.getOriginalFile());

			for(PsiLanguageInjectionHost.Shred shred : shreds)
			{
				PsiLanguageInjectionHost host = shred.getHost();
				if(host instanceof ShaderCGScript)
				{
					ShaderLabFile containingFile = (ShaderLabFile) host.getContainingFile();
					ShaderReference.consumeProperties(containingFile, result::addElement);
				}
			}
		}
	});
}
 
Example #13
Source File: BuiltInSymbolCompletionContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
public BuiltInSymbolCompletionContributor() {
  extend(
      CompletionType.BASIC,
      psiElement()
          .withLanguage(BuildFileLanguage.INSTANCE)
          .withParent(ReferenceExpression.class)
          .andNot(psiComment())
          .andNot(psiElement().afterLeaf(psiElement(BuildToken.fromKind(TokenKind.INT))))
          .andNot(psiElement().inside(FuncallExpression.class))
          .andNot(psiElement().afterLeaf(psiElement().withText(".")))
          .andNot(psiElement().inFile(psiFile(BuildFileWithCustomCompletion.class))),
      new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(
            CompletionParameters parameters,
            ProcessingContext context,
            CompletionResultSet result) {
          for (String symbol : BuiltInNamesProvider.GLOBALS) {
            result.addElement(LookupElementBuilder.create(symbol));
          }
        }
      });
}
 
Example #14
Source File: AdditionalLanguagesCompletionContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
public AdditionalLanguagesCompletionContributor() {
  extend(
      CompletionType.BASIC,
      psiElement()
          .withLanguage(ProjectViewLanguage.INSTANCE)
          .inside(
              psiElement(ProjectViewPsiListSection.class)
                  .withText(
                      StandardPatterns.string()
                          .startsWith(AdditionalLanguagesSection.KEY.getName()))),
      new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(
            CompletionParameters parameters,
            ProcessingContext context,
            CompletionResultSet result) {
          for (LanguageClass type :
              availableAdditionalLanguages(parameters.getEditor().getProject())) {
            result.addElement(LookupElementBuilder.create(type.getName()));
          }
        }
      });
}
 
Example #15
Source File: WorkspaceTypeCompletionContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
public WorkspaceTypeCompletionContributor() {
  extend(
      CompletionType.BASIC,
      psiElement()
          .withLanguage(ProjectViewLanguage.INSTANCE)
          .inside(ProjectViewPsiScalarSection.class)
          .afterLeaf(psiElement().withText(":").afterLeaf(WorkspaceTypeSection.KEY.getName())),
      new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(
            CompletionParameters parameters,
            ProcessingContext context,
            CompletionResultSet result) {
          for (WorkspaceType type : WorkspaceType.values()) {
            result.addElement(LookupElementBuilder.create(type.getName()));
          }
        }
      });
}
 
Example #16
Source File: LatteVariableCompletionProvider.java    From intellij-latte with MIT License 6 votes vote down vote up
@Override
protected void addCompletions(
		@NotNull CompletionParameters parameters,
		ProcessingContext context,
		@NotNull CompletionResultSet result
) {
	PsiElement element = parameters.getPosition().getParent();
	if ((element instanceof LattePhpVariable) && ((LattePhpVariable) element).isDefinition()) {
		return;
	}

	List<LookupElement> elements = attachPhpVariableCompletions(element, parameters.getOriginalFile().getVirtualFile());
	result.addAllElements(elements);

	if (parameters.getOriginalFile() instanceof LatteFile) {
		attachTemplateTypeCompletions(result, element.getProject(), (LatteFile) parameters.getOriginalFile());
	}
}
 
Example #17
Source File: PhpClassAndParameterCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, final @NotNull CompletionResultSet resultSet) {

        PsiElement psiElement = parameters.getOriginalPosition();
        if(psiElement == null || !Symfony2ProjectComponent.isEnabled(psiElement)) {
            return;
        }

        PhpClassCompletionProvider.addClassCompletion(parameters, resultSet, psiElement, false);

        for( Map.Entry<String, ContainerParameter> entry: ContainerCollectionResolver.getParameters(psiElement.getProject()).entrySet()) {
            resultSet.addElement(
                new ParameterLookupElement(entry.getValue(), ParameterPercentWrapInsertHandler.getInstance(), psiElement.getText())
            );
        }

    }
 
Example #18
Source File: StepCompletionContributor.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
public static String getPrefix(CompletionParameters parameters) {
    PsiElement insertedElement = parameters.getPosition();
    int offsetInFile = parameters.getOffset();

    PsiReference ref = insertedElement.getContainingFile().findReferenceAt(offsetInFile);
    if (isStep(insertedElement) && ref != null) {
        List<TextRange> ranges = ReferenceRange.getRanges(ref);
        PsiElement element = ref.getElement();
        int startOffset = element.getTextRange().getStartOffset();
        for (TextRange range : ranges) {
            if (range.contains(offsetInFile - startOffset)) {
                int endIndex = offsetInFile - startOffset;
                int startIndex = range.getStartOffset();
                return StringUtil.trimStart(element.getText().substring(startIndex + 1, endIndex), " ");
            }
        }

    }
    return parameters.getPosition().getText().replace("IntellijIdeaRulezzz ", "").trim();
}
 
Example #19
Source File: CompletionAdders.java    From arma-intellij-plugin with MIT License 6 votes vote down vote up
public static void addVariables(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result,
								@NotNull PsiElement cursor, boolean forLocalVars) {
	HashSet<String> putVars = new HashSet<>();
	PsiUtil.traverseDepthFirstSearch(parameters.getOriginalFile().getNode(), astNode -> {
		PsiElement nodeAsElement = astNode.getPsi();
		if (nodeAsElement == cursor) {
			return false;
		}
		if (!(nodeAsElement instanceof SQFVariable)) {
			return false;
		}
		SQFVariable var = (SQFVariable) nodeAsElement;
		if (((var.isLocal() && forLocalVars) || (!var.isLocal() && !forLocalVars)) && !putVars.contains(var.getVarName().toLowerCase())) {
			putVars.add(var.getVarName().toLowerCase());
			result.addElement(PrioritizedLookupElement.withPriority(
					LookupElementBuilder.createWithSmartPointer(var.getVarName(), var)
							.withTailText(var.isMagicVar() ? " (Magic Var)" : (
											forLocalVars ? " (Local Variable)" : " (Global Variable)"
									)
							)
							.withIcon(var.isMagicVar() ? ArmaPluginIcons.ICON_SQF_MAGIC_VARIABLE : ArmaPluginIcons.ICON_SQF_VARIABLE), VAR_PRIORITY)
			);
		}
		return false;
	});
}
 
Example #20
Source File: LSPCompletionContributor.java    From lsp4intellij with Apache License 2.0 6 votes vote down vote up
public LSPCompletionContributor() {
    this.extend(CompletionType.BASIC, usePattern(), new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) {
            try {
                ApplicationUtil.runWithCheckCanceled(() -> {
                    Editor editor = parameters.getEditor();
                    int offset = parameters.getOffset();
                    Position serverPos = DocumentUtils.offsetToLSPPos(editor, offset);

                    EditorEventManager manager = EditorEventManagerBase.forEditor(editor);
                    if (manager != null) {
                        result.addAllElements(manager.completion(serverPos));
                    }
                    return null;
                }, ProgressIndicatorProvider.getGlobalProgressIndicator());
            } catch (ProcessCanceledException ignored) {
                // ProcessCanceledException can be ignored.
            } catch (Exception e) {
                LOG.warn("LSP Completions ended with an error", e);
            }
        }
    });
}
 
Example #21
Source File: BaseCompletionProvider.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
protected void withCypherMetadataProvider(CompletionParameters parameters, ProjectRunnable runnable) {
    Project project = parameters.getEditor().getProject();
    if (project != null) {
        CypherMetadataProviderService provider = ServiceManager.getService(project, CypherMetadataProviderService.class);
        runnable.run(provider);
    }
}
 
Example #22
Source File: PhpArrayCallbackGotoCompletion.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
@Override
public void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    PsiElement position = completionParameters.getPosition();

    PhpClass phpClass = findClassCallback(position);
    if(phpClass == null) {
        return;
    }

    for (Method method : phpClass.getMethods()) {
        String name = method.getName();

        // __construct
        if(name.startsWith("__")) {
            continue;
        }

        LookupElementBuilder lookupElement = LookupElementBuilder.create(name).withIcon(method.getIcon());

        PhpClass containingClass = method.getContainingClass();
        if(containingClass != null) {
            lookupElement = lookupElement.withTypeText(containingClass.getPresentableFQN(), true);
        }

        resultSet.addElement(lookupElement);
    }
}
 
Example #23
Source File: LattePhpCompletionProvider.java    From intellij-latte with MIT License 5 votes vote down vote up
@Override
protected void addCompletions(
		@NotNull CompletionParameters parameters,
		ProcessingContext context,
		@NotNull CompletionResultSet result
) {
	PsiElement element = parameters.getPosition().getParent();
	if (
			element instanceof LattePhpStaticVariable
					|| element instanceof LattePhpConstant
					|| (element instanceof LattePhpMethod && ((LattePhpMethod) element).isStatic())) {
		attachPhpCompletions(parameters, context, result, (BaseLattePhpElement) element, true);

	} else if (element instanceof LattePhpProperty || (element instanceof LattePhpMethod && !((LattePhpMethod) element).isStatic())) {
		attachPhpCompletions(parameters, context, result, (BaseLattePhpElement) element, false);

	} else if (!(element instanceof LatteMacroModifier) && !(element instanceof LattePhpString)) {
		classCompletionProvider.addCompletions(parameters, context, result);
		namespaceCompletionProvider.addCompletions(parameters, context, result);

		if (LatteUtil.matchParentMacroName(element, "varType") || LatteUtil.matchParentMacroName(element, "var")) {
			attachVarTypes(result);
		}

		variableCompletionProvider.addCompletions(parameters, context, result);
		functionCompletionProvider.addCompletions(parameters, context, result);
	}
}
 
Example #24
Source File: StatePropCompletionContributor.java    From litho with Apache License 2.0 5 votes vote down vote up
private static CompletionProvider<CompletionParameters> typeCompletionProvider() {
  return new CompletionProvider<CompletionParameters>() {
    @Override
    protected void addCompletions(
        @NotNull CompletionParameters completionParameters,
        ProcessingContext processingContext,
        @NotNull CompletionResultSet completionResultSet) {
      PsiElement element = completionParameters.getPosition();

      // Method parameter type in the Spec class
      // PsiIdentifier -> PsiJavaCodeReferenceElement -> PsiTypeElement -> PsiMethod -> PsiClass
      PsiElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class);
      if (typeElement == null) {
        return;
      }
      PsiMethod containingMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
      if (containingMethod == null) {
        return;
      }
      PsiClass cls = containingMethod.getContainingClass();
      if (!LithoPluginUtils.isLithoSpec(cls)) {
        return;
      }

      // @Prop or @State annotation
      PsiModifierList parameterModifiers =
          PsiTreeUtil.getPrevSiblingOfType(typeElement, PsiModifierList.class);
      if (parameterModifiers == null) {
        return;
      }
      if (parameterModifiers.findAnnotation(Prop.class.getName()) != null) {
        addCompletionResult(
            completionResultSet, containingMethod, cls.getMethods(), LithoPluginUtils::isProp);
      } else if (parameterModifiers.findAnnotation(State.class.getName()) != null) {
        addCompletionResult(
            completionResultSet, containingMethod, cls.getMethods(), LithoPluginUtils::isState);
      }
    }
  };
}
 
Example #25
Source File: RequiredPropMethodContributor.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void addCompletions(
    CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
  result.runRemainingContributors(
      parameters,
      suggestedCompletion -> {
        LookupElement suggestedLookup = suggestedCompletion.getLookupElement();
        PsiElement suggestedElement = suggestedLookup.getPsiElement();
        CompletionResult replacingCompletion = null;

        if (suggestedElement instanceof PsiMethod) {
          PsiMethod suggestedMethod = (PsiMethod) suggestedElement;

          RequiredProp requiredPropAnnotation =
              PsiAnnotationProxyUtils.findAnnotationInHierarchy(
                  suggestedMethod, RequiredProp.class);
          if (requiredPropAnnotation != null) {
            RequiredPropLookupElement newLookupElement =
                RequiredPropLookupElement.create(
                    suggestedLookup,
                    isMainRequiredPropertySetter(
                        suggestedMethod.getName(), requiredPropAnnotation));
            replacingCompletion = CompletionUtils.wrap(suggestedCompletion, newLookupElement);

          } else if (isComponentCreateMethod(suggestedMethod)) {
            createMethodLookup(
                    suggestedMethod,
                    suggestedLookup,
                    parameters.getPosition().getPrevSibling(),
                    parameters.getEditor().getProject())
                .map(
                    newLookupElement ->
                        CompletionUtils.wrap(suggestedCompletion, newLookupElement))
                .ifPresent(result::passResult);
          }
        }
        result.passResult(
            replacingCompletion == null ? suggestedCompletion : replacingCompletion);
      });
}
 
Example #26
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 #27
Source File: EventCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, final @NotNull CompletionResultSet completionResultSet) {

    if(!Symfony2ProjectComponent.isEnabled(completionParameters.getPosition())) {
        return;
    }

    completionResultSet.addAllElements(
        EventDispatcherSubscriberUtil.getEventNameLookupElements(completionParameters.getPosition().getProject())
    );
}
 
Example #28
Source File: XQueryCompletionContributor.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private void extendForKeywords() {
    extend(CompletionType.BASIC, psiElement().inFile(instanceOf(XQueryFile.class)),
            new CompletionProvider<CompletionParameters>() {
                @Override
                protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context,
                                              @NotNull CompletionResultSet result) {
                    PsiElement position = parameters.getPosition();
                    if (isInsideOfUriLiteral(position)) return;
                    KeywordCollector keywordCollector = new KeywordCollector();
                    result.addAllElements(keywordCollector.getProposedLookUpItems(position));
                }
            });
}
 
Example #29
Source File: ConceptStaticArgCompletionProvider.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void addCompletions(CompletionParameters parameters, ProcessingContext processingContext, CompletionResultSet resultSet) {
    String prefix = getPrefix(parameters);
    resultSet = resultSet.withPrefixMatcher(new PlainPrefixMatcher(prefix));
    Collection<ConceptStaticArg> staticArgs = PsiTreeUtil.collectElementsOfType(parameters.getOriginalFile(), ConceptStaticArg.class);
    for (ConceptStaticArg arg : staticArgs) {
        if (arg != null) {
            String text = arg.getText().replaceFirst("\"", "");
            String textWithoutQuotes = text.substring(0, text.length() - 1);
            if (!textWithoutQuotes.equals(""))
                resultSet.addElement(LookupElementBuilder.create(textWithoutQuotes));
        }
    }
}
 
Example #30
Source File: CamelEndpointNameCompletionExtension.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull String query) {
    if (query.contains("?")) {
        //do not add completions when inside endpoint query params
        return false;
    }
    PsiElement element = parameters.getPosition();
    CamelIdeaUtils service = CamelIdeaUtils.getService();
    return service.isPlaceForEndpointUri(element)
        && service.isProducerEndpoint(element);
}