Java Code Examples for com.intellij.codeInsight.completion.CompletionParameters#getPosition()

The following examples show how to use com.intellij.codeInsight.completion.CompletionParameters#getPosition() . 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: LayoutSpecMethodParameterAnnotationsContributor.java    From litho with Apache License 2.0 6 votes vote down vote up
@Override
protected void addCompletions(
    CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
  PsiElement element = parameters.getPosition();
  Optional.ofNullable(PsiTreeUtil.findFirstParent(element, PsiMethod.class::isInstance))
      .flatMap(method -> getParameterAnnotations((PsiMethod) method))
      .map(
          annotations ->
              new ReplacingConsumer(
                  annotations,
                  result,
                  (insertionContext, item) -> {
                    final Map<String, String> data = new HashMap<>();
                    data.put(
                        EventLogger.KEY_TARGET, EventLogger.VALUE_COMPLETION_TARGET_PARAMETER);
                    data.put(EventLogger.KEY_CLASS, item.getLookupString());
                    LithoLoggerProvider.getEventLogger()
                        .log(EventLogger.EVENT_COMPLETION, data);
                  }))
      .ifPresent(
          replacingConsumer -> {
            // We want our suggestions at the top, that's why adding them first
            replacingConsumer.addRemainingCompletions(parameters.getPosition().getProject());
            result.runRemainingContributors(parameters, replacingConsumer);
          });
}
 
Example 2
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 3
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 4
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 5
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 6
Source File: ElmMainCompletionProvider.java    From elm-plugin with MIT License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
    PsiElement position = parameters.getPosition();
    PsiElement parent = position.getParent();
    PsiElement grandParent = Optional.ofNullable(parent)
            .map(PsiElement::getParent)
            .orElse(null);
    if (parent instanceof ElmFile || parent instanceof GeneratedParserUtilBase.DummyBlock) {
        addCompletionsInInvalidExpression(position, resultSet);
    } else if (grandParent instanceof ElmLowerCasePath) {
        this.addValueOrFieldCompletions((ElmLowerCaseId) parent, resultSet);
    } else if (grandParent instanceof ElmMixedCasePath
            || grandParent instanceof ElmUpperCasePath) {
        addTypeOrModuleCompletions(parent, resultSet);
    } else if (grandParent instanceof ElmExposingClause) {
        this.addExposedValuesCompletion((ElmExposingClause)grandParent, resultSet);
    } else if (parent instanceof ElmUpperCaseId) {
        this.addExposedValuesCompletion((ElmUpperCaseId)parent, resultSet);
    } else if (parent instanceof ElmLowerCaseId && grandParent instanceof ElmModuleDeclaration) {
        this.singleModuleValueProvider.addCompletions((ElmFile)grandParent.getContainingFile(), resultSet);
    }
}
 
Example 7
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);
}
 
Example 8
Source File: CSharpCompletionUtil.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
public static boolean isClassNamePossible(CompletionParameters parameters)
{
	PsiElement position = parameters.getPosition();
	if(position.getNode().getElementType() == CSharpTokens.IDENTIFIER)
	{
		PsiElement parent = position.getParent();
		if(parent instanceof CSharpReferenceExpression)
		{
			if(((CSharpReferenceExpression) parent).getQualifier() != null)
			{
				return false;
			}

			if(parent.getParent() instanceof CSharpConstructorSuperCallImpl)
			{
				return false;
			}

			CSharpReferenceExpression.ResolveToKind kind = ((CSharpReferenceExpression) parent).kind();
			if(kind == CSharpReferenceExpression.ResolveToKind.TYPE_LIKE || kind == CSharpReferenceExpression.ResolveToKind.CONSTRUCTOR || kind == CSharpReferenceExpression.ResolveToKind
					.EXPRESSION_OR_TYPE_LIKE || kind == CSharpReferenceExpression.ResolveToKind.ANY_MEMBER)
			{
				return true;
			}
		}
	}
	return false;
}
 
Example 9
Source File: CSharpCompletionSorting.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiredReadAction
private static LookupElementWeigher recursiveSorter(CompletionParameters completionParameters, CompletionResultSet result)
{
	PsiElement position = completionParameters.getPosition();


	Set<PsiElement> elements = new THashSet<>();

	PsiElement argumentListOwner = PsiTreeUtil.getContextOfType(position, CSharpCallArgumentListOwner.class, DotNetVariable.class);
	if(argumentListOwner instanceof CSharpMethodCallExpressionImpl)
	{
		ContainerUtil.addIfNotNull(elements, ((CSharpMethodCallExpressionImpl) argumentListOwner).resolveToCallable());
	}
	else if(argumentListOwner instanceof DotNetVariable)
	{
		elements.add(argumentListOwner);
	}

	List<CSharpForeachStatementImpl> foreachStatements = SyntaxTraverser.psiApi().parents(position).filter(CSharpForeachStatementImpl.class).addAllTo(new ArrayList<>());
	for(CSharpForeachStatementImpl foreachStatement : foreachStatements)
	{
		DotNetExpression iterableExpression = foreachStatement.getIterableExpression();
		if(iterableExpression instanceof CSharpReferenceExpression)
		{
			ContainerUtil.addIfNotNull(elements, ((CSharpReferenceExpression) iterableExpression).resolve());
		}
	}

	if(!elements.isEmpty())
	{
		return new CSharpRecursiveGuardWeigher(elements);
	}
	return null;
}
 
Example 10
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 11
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 12
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 13
Source File: LayoutSpecMethodAnnotationsProvider.java    From litho with Apache License 2.0 5 votes vote down vote up
@Override
protected void addCompletions(
    CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
  PsiElement position = parameters.getPosition();
  if (!CompletionUtils.findFirstParent(position, LithoPluginUtils::isLayoutSpec).isPresent())
    return;

  final Project project = position.getProject();
  for (String annotationFQN : ANNOTATION_QUALIFIED_NAMES) {
    LookupElement lookup =
        PrioritizedLookupElement.withPriority(
            createLookup(annotationFQN, project), Integer.MAX_VALUE);
    result.addElement(lookup);
  }
}
 
Example 14
Source File: PropertiesCompletionProvider.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void addCompletions(final CompletionParameters completionParameters,
        final ProcessingContext processingContext, final CompletionResultSet resultSet) {

    final PsiElement element = completionParameters.getPosition();
    if (!LeafPsiElement.class.isInstance(element)) {
        return; // ignore comment
    }

    final Project project = element.getProject();
    final Module module = findModule(element);
    final SuggestionService service = ServiceManager.getService(project, SuggestionService.class);
    if ((module == null || !service.isSupported(completionParameters))) { // limit suggestion to Messages
        return;
    }

    if (PropertyValueImpl.class.isInstance(element)) {
        ofNullable(PropertyValueImpl.class.cast(element).getPrevSibling())
                .map(PsiElement::getPrevSibling)
                .map(PsiElement::getText)
                .ifPresent(text -> resultSet.addAllElements(service.computeValueSuggestions(text)));
    } else if (PropertyKeyImpl.class.isInstance(element)) {
        final List<String> containerElements = PropertiesFileImpl.class
                .cast(element.getContainingFile())
                .getProperties()
                .stream()
                .filter(p -> !Objects.equals(p.getKey(), element.getText()))
                .map(IProperty::getKey)
                .collect(toList());
        resultSet
                .addAllElements(service
                        .computeKeySuggestions(project, module, getPropertiesPackage(module, completionParameters),
                                containerElements, truncateIdeaDummyIdentifier(element)));
    }
}
 
Example 15
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 16
Source File: CamelEndpointSmartCompletionExtension.java    From camel-idea-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet resultSet, @NotNull String[] query) {
    boolean endsWithAmpQuestionMark = false;
    // it is a known Camel component
    String componentName = StringUtils.asComponentName(query[0]);

    // it is a known Camel component
    Project project = parameters.getOriginalFile().getManager().getProject();
    CamelCatalog camelCatalog = ServiceManager.getService(project, CamelCatalogService.class).get();

    String json = camelCatalog.componentJSonSchema(componentName);
    ComponentModel componentModel = ModelHelper.generateComponentModel(json, true);
    final PsiElement element = parameters.getPosition();

    // grab all existing parameters
    String concatQuery = query[0];
    String suffix = query[1];
    String queryAtPosition =  query[2];
    String prefixValue =  query[2];
    // camel catalog expects &amp; as & when it parses so replace all &amp; as &
    concatQuery = concatQuery.replaceAll("&amp;", "&");

    boolean editQueryParameters = concatQuery.contains("?");

    // strip up ending incomplete parameter
    if (queryAtPosition.endsWith("&") || queryAtPosition.endsWith("?")) {
        endsWithAmpQuestionMark = true;
        queryAtPosition = queryAtPosition.substring(0, queryAtPosition.length() - 1);
    }

    // strip up ending incomplete parameter
    if (concatQuery.endsWith("&") || concatQuery.endsWith("?")) {
        concatQuery = concatQuery.substring(0, concatQuery.length() - 1);
    }

    Map<String, String> existing = null;
    try {
        existing = camelCatalog.endpointProperties(concatQuery);
    } catch (Exception e) {
        LOG.warn("Error parsing Camel endpoint properties with url: " + queryAtPosition, e);
    }

    // are we editing an existing parameter value
    // or are we having a list of suggested parameters to choose among

    boolean caretAtEndOfLine = getIdeaUtils().isCaretAtEndOfLine(element);
    LOG.trace("Caret at end of line: " + caretAtEndOfLine);

    String[] queryParameter = getIdeaUtils().getQueryParameterAtCursorPosition(element);
    String optionValue = queryParameter[1];


    // a bit complex to figure out whether to edit the endpoint value or not
    boolean editOptionValue = false;
    if (endsWithAmpQuestionMark) {
        // should not edit value but suggest a new option instead
        editOptionValue = false;
    } else {
        if ("".equals(optionValue)) {
            // empty value so must edit
            editOptionValue = true;
        } else if (StringUtils.isNotEmpty(optionValue) && !caretAtEndOfLine) {
            // has value and cursor not at end of line so must edit
            editOptionValue = true;
        }
    }
    LOG.trace("Add new option: " + !editOptionValue);
    LOG.trace("Edit option value: " + editOptionValue);

    List<LookupElement> answer = null;
    if (editOptionValue) {
        EndpointOptionModel endpointOption = componentModel.getEndpointOption(queryParameter[0].substring(1));
        if (endpointOption != null) {
            answer = addSmartCompletionForEndpointValue(parameters.getEditor(), queryAtPosition, suffix, endpointOption, element, xmlMode);
        }
    }
    if (answer == null) {
        if (editQueryParameters) {
            // suggest a list of options for query parameters
            answer = addSmartCompletionSuggestionsQueryParameters(query, componentModel, existing, xmlMode, element, parameters.getEditor());
        } else {
            if (!resultSet.isStopped()) {
                // suggest a list of options for context-path
                answer = addSmartCompletionSuggestionsContextPath(queryAtPosition, componentModel, existing, xmlMode, element);
            }
        }
    }
    // are there any results then add them
    if (answer != null && !answer.isEmpty()) {
        resultSet.withPrefixMatcher(prefixValue).addAllElements(answer);
        resultSet.stopHere();
    }
}
 
Example 17
Source File: BuckTargetCompletionContributor.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public void fillCompletionVariants(
    @NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
  PsiFile psiFile = parameters.getOriginalFile();
  if (!BuckFileType.INSTANCE.equals(psiFile.getFileType())) {
    return;
  }
  PsiElement position = parameters.getPosition();
  String openingQuote;
  if (BuckPsiUtils.hasElementType(position, BuckTypes.APOSTROPHED_STRING)) {
    openingQuote = "'";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.APOSTROPHED_RAW_STRING)) {
    openingQuote = "r'";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.TRIPLE_APOSTROPHED_STRING)) {
    openingQuote = "'''";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.TRIPLE_APOSTROPHED_RAW_STRING)) {
    openingQuote = "r'''";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.QUOTED_STRING)) {
    openingQuote = "\"";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.QUOTED_RAW_STRING)) {
    openingQuote = "r\"";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.TRIPLE_QUOTED_STRING)) {
    openingQuote = "\"\"\"";
  } else if (BuckPsiUtils.hasElementType(position, BuckTypes.TRIPLE_QUOTED_RAW_STRING)) {
    openingQuote = "r\"\"\"";
  } else {
    return;
  }
  Project project = position.getProject();
  VirtualFile virtualFile = psiFile.getVirtualFile();
  String positionStringWithQuotes = position.getText();
  String prefix =
      positionStringWithQuotes.substring(
          openingQuote.length(), parameters.getOffset() - position.getTextOffset());
  if (BuckPsiUtils.findAncestorWithType(position, BuckTypes.LOAD_TARGET_ARGUMENT) != null) {
    // Inside a load target, extension files are "@this//syntax/points:to/files.bzl"
    if (prefix.startsWith("@")) {
      prefix = prefix.substring(1);
    }
    doCellNames(position, prefix, result);
    doTargetsForRelativeExtensionFile(virtualFile, prefix, result);
    doPathsForFullyQualifiedExtensionFile(virtualFile, project, prefix, result);
    doTargetsForFullyQualifiedExtensionFile(virtualFile, project, prefix, result);
  } else if (BuckPsiUtils.findAncestorWithType(position, BuckTypes.LOAD_ARGUMENT) != null) {
    doSymbolsFromExtensionFile(virtualFile, project, position, prefix, result);
  } else {
    if (prefix.startsWith("@")) {
      prefix = prefix.substring(1);
    }
    doCellNames(position, prefix, result);
    doTargetsForRelativeBuckTarget(psiFile, prefix, result);
    doPathsForFullyQualifiedBuckTarget(virtualFile, project, prefix, result);
    doTargetsForFullyQualifiedBuckTarget(virtualFile, project, prefix, result);
  }
}
 
Example 18
Source File: VariableNameCompletionProvider.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
@Override
protected void addBashCompletions(String currentText, CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
    PsiElement element = parameters.getPosition();

    BashVar varElement = PsiTreeUtil.getContextOfType(element, BashVar.class, false);
    boolean dollarPrefix = currentText != null && currentText.startsWith("$");
    boolean insideExpansion = element.getParent() != null && element.getParent().getParent() instanceof BashParameterExpansion;
    if (varElement == null && !dollarPrefix && !insideExpansion) {
        return;
    }

    int invocationCount = parameters.getInvocationCount();
    int resultLength = 0;

    PsiElement original = parameters.getOriginalPosition();
    BashVar varElementOriginal = original != null ? PsiTreeUtil.getContextOfType(original, BashVar.class, false) : null;

    if (varElement != null) {
        // only keep vars of included files when starting in the original file
        PsiElement originalRef = varElementOriginal != null ? varElementOriginal : original;
        if (originalRef != null) {
            resultLength += addCollectedVariables(original, result, new BashVarVariantsProcessor(originalRef, false, true));
        }

        // only keep vars of the dummy file when starting in the dummy file
        resultLength += addCollectedVariables(element, result, new BashVarVariantsProcessor(varElement, true, false));
    } else {
        // not in a variable element, but collect all known variable names at this offset in the current file
        if (original != null) {
            resultLength += addCollectedVariables(original, result, new BashVarVariantsProcessor(original, false, true));
        }
        resultLength += addCollectedVariables(element, result, new BashVarVariantsProcessor(element, false, true));
    }

    if (currentText != null && (dollarPrefix || insideExpansion) && (invocationCount >= 2 || resultLength == 0)) {
        Project project = element.getProject();
        addBuiltInVariables(result, project);
        addGlobalVariables(result, project);
    } else {
        result.addLookupAdvertisement("Press twice for global variables");
    }
}
 
Example 19
Source File: InTemplateDeclarationVariableProvider.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
@Override
public void provide(@NotNull CompletionParameters parameters, ProcessingContext context, Map<String, FluidVariable> variableMap) {
    PsiElement psiElement = parameters.getPosition();

    getVariablesFromAroundElement(psiElement, variableMap);
}
 
Example 20
Source File: ConfigCompletionProvider.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {

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

    PsiElement yamlScalar = element.getParent();
    if(yamlScalar == null) {
        return;
    }

    PsiElement yamlCompount = yamlScalar.getParent();

    // yaml document root context
    if(yamlCompount.getParent() instanceof YAMLDocument) {
        attachRootConfig(completionResultSet, element);
        return;
    }

    // check inside yaml key value context
    if(!(yamlCompount instanceof YAMLCompoundValue || yamlCompount instanceof YAMLKeyValue)) {
        return;
    }

    // get all parent yaml keys
    List<String> items = YamlHelper.getParentArrayKeys(element);
    if(items.size() == 0) {
        return;
    }

    // normalize for xml
    items = ContainerUtil.map(items, s -> s.replace('_', '-'));

    // reverse to get top most item first
    Collections.reverse(items);

    Document document = getConfigTemplate(ProjectUtil.getProjectDir(element));
    if(document == null) {
        return;
    }

    Node configNode = getMatchingConfigNode(document, items);
    if(configNode == null) {
        return;
    }

    getConfigPathLookupElements(completionResultSet, configNode, false);

    // map shortcuts like eg <dbal default-connection="">
    if(configNode instanceof Element) {
        NamedNodeMap attributes = configNode.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            String attributeName = attributes.item(i).getNodeName();
            if(attributeName.startsWith("default-")) {
                Node defaultNode = getElementByTagNameWithUnPluralize((Element) configNode, attributeName.substring("default-".length()));
                if(defaultNode != null) {
                    getConfigPathLookupElements(completionResultSet, defaultNode, true);
                }
            }
        }
    }

}