Java Code Examples for com.intellij.util.ProcessingContext

The following examples show how to use com.intellij.util.ProcessingContext. These examples are extracted from open source projects. 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 Project: consulo   Source File: LiftShorterItemsClassifier.java    License: 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 2
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
    RequirejsProjectComponent projectComponent = psiElement.getProject().getComponent(RequirejsProjectComponent.class);

    if (!projectComponent.isEnabled()) {
        return PsiReference.EMPTY_ARRAY;
    }

    String path = psiElement.getText();
    if (isRequireCall(psiElement) || isDefineFirstCollection(psiElement)) {
        PsiReference ref = new RequirejsReference(psiElement, new TextRange(1, path.length() - 1));
        return new PsiReference[] {ref};
    }

    return new PsiReference[0];
}
 
Example 3
Source Project: consulo   Source File: PsiElementPattern.java    License: Apache License 2.0 6 votes vote down vote up
public Self afterLeafSkipping(@Nonnull final ElementPattern skip, @Nonnull final ElementPattern pattern) {
  return with(new PatternCondition<T>("afterLeafSkipping") {
    @Override
    public boolean accepts(@Nonnull T t, final ProcessingContext context) {
      PsiElement element = t;
      while (true) {
        element = PsiTreeUtil.prevLeaf(element);
        if (element != null && element.getTextLength() == 0) {
          continue;
        }

        if (!skip.getCondition().accepts(element, context)) {
          return pattern.getCondition().accepts(element, context);
        }
      }
    }

  });
}
 
Example 4
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
    PhpClass phpClass = getValidAnnotationClass(psiElement);
    if(phpClass == null) {
        return new PsiReference[0];
    }

    PsiElement propertyName = PhpElementsUtil.getPrevSiblingOfPatternMatch(psiElement, PlatformPatterns.psiElement(PhpDocTokenTypes.DOC_IDENTIFIER));
    if(propertyName == null) {
        return new PsiReference[0];
    }

    AnnotationPropertyParameter annotationPropertyParameter = new AnnotationPropertyParameter(psiElement, phpClass, propertyName.getText(), AnnotationPropertyParameter.Type.PROPERTY_VALUE);
    return addPsiReferences(psiElement, processingContext, annotationPropertyParameter);

}
 
Example 5
public void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    if(!Symfony2ProjectComponent.isEnabled(parameters.getPosition())) {
        return;
    }

    // move this stuff to pattern fixed event stopping by phpstorm
    PsiElement currElement = parameters.getPosition().getOriginalElement();
    PsiElement prevElement = currElement.getPrevSibling();
    if ((prevElement != null) && ((prevElement instanceof PsiWhiteSpace))) prevElement = prevElement.getPrevSibling();

    if ((prevElement != null) && (prevElement.getNode().getElementType() == TwigTokenTypes.FILTER)) {
        for(Map.Entry<String, TwigExtension> entry : TwigExtensionParser.getFilters(parameters.getPosition().getProject()).entrySet()) {
            resultSet.addElement(new TwigExtensionLookupElement(currElement.getProject(), entry.getKey(), entry.getValue()));
        }
    }
}
 
Example 6
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 7
Source Project: idea-php-symfony2-plugin   Source File: XmlReferenceContributor.java    License: MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext context) {
    if(!Symfony2ProjectComponent.isEnabled(psiElement) || !(psiElement instanceof XmlAttributeValue)) {
        return new PsiReference[0];
    }

    String method = ((XmlAttributeValue) psiElement).getValue();
    if(StringUtils.isBlank(method)) {
        return new PsiReference[0];
    }

    PhpClass phpClass = XmlHelper.getPhpClassForServiceFactory((XmlAttributeValue) psiElement);
    if(phpClass == null) {
        return new PsiReference[0];
    }

    Method targetMethod = phpClass.findMethodByName(method);
    if(targetMethod == null) {
        return new PsiReference[0];
    }

    return new PsiReference[] {
        new ClassMethodStringPsiReference(psiElement, phpClass.getFQN(), targetMethod.getName()),
    };
}
 
Example 8
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 9
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(PlatformPatterns.psiElement(StringLiteralExpression.class), new PsiReferenceProvider() {
        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
            if (!(element instanceof StringLiteralExpression)) {
                return PsiReference.EMPTY_ARRAY;
            }

            StringLiteralExpression stringLiteralExpression = (StringLiteralExpression) element;
            if (!stringLiteralExpression.getContents().startsWith("LLL:")) {
                return PsiReference.EMPTY_ARRAY;
            }

            return new PsiReference[]{new TranslationReference(stringLiteralExpression)};
        }
    });
}
 
Example 10
@Override
public boolean accepts(@NotNull PsiFile psiFile, ProcessingContext processingContext) {
    if (psiFile.getFileType() != YAMLFileType.YML) {
        return false;
    }

    if (psiFile.getName().matches("(security|config).*\\.(yml|yaml)")) {
        return true;
    }

    // psiFile.virtualFile is empty; check via folder structure
    PsiDirectory containingDirectory = psiFile.getContainingDirectory();
    if (containingDirectory == null) {
        return false;
    }

    if ("packages".equals(containingDirectory.getName())) {
        return true;
    }

    VirtualFile virtualDirectoryFile = containingDirectory.getVirtualFile();

    String relativePath = VfsExUtil.getRelativeProjectPath(psiFile.getProject(), virtualDirectoryFile);
    return relativePath != null && relativePath.contains("config/packages/");
}
 
Example 11
Source Project: idea-latex   Source File: LatexReferenceContributor.java    License: MIT License 6 votes vote down vote up
/**
 * Returns references for given @{link PsiElement}.
 *
 * @param psiElement        current element
 * @param processingContext context
 * @return {@link PsiReference} list
 */
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
    if (psiElement instanceof LatexInstruction) {
        LatexInstructionExtImpl instruction = (LatexInstructionExtImpl) psiElement;
        String identifier = instruction.getIdentifier().getText();
        if (Arrays.asList(IDENTIFIERS).contains(identifier)) {
            LatexArgument arg = instruction.getArgument();
            if (arg != null && arg.getValue() != null) {
                return new FileReferenceSet(arg.getValue(), instruction, arg.getStartOffsetInParent() + 1, this, true).getAllReferences();
            }
        }
    }
    return PsiReference.EMPTY_ARRAY;
}
 
Example 12
Source Project: Intellij-Plugin   Source File: StepCompletionProvider.java    License: 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 13
Source Project: consulo   Source File: RenameInputValidatorRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static Function<String, String> getInputErrorValidator(final PsiElement element) {
  for(final RenameInputValidator validator: Extensions.getExtensions(RenameInputValidator.EP_NAME)) {
    if (!(validator instanceof RenameInputValidatorEx)) continue;
    final ProcessingContext context = new ProcessingContext();
    if (validator.getPattern().accepts(element, context)) {
      return new Function<String, String>() {
        @Override
        public String fun(String newName) {
          return ((RenameInputValidatorEx)validator).getErrorMessage(newName, element.getProject());
        }
      };
    }
  }
  return null;
}
 
Example 14
Source Project: buck   Source File: BuckIdentifierReferenceContributor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void registerReferenceProviders(@NotNull PsiReferenceRegistrar registrar) {

  registrar.registerReferenceProvider(
      PlatformPatterns.psiElement(BuckIdentifier.class),
      new PsiReferenceProvider() {
        @NotNull
        @Override
        public PsiReference[] getReferencesByElement(
            @NotNull PsiElement element, @NotNull ProcessingContext context) {
          if (element instanceof BuckIdentifier) {
            BuckIdentifier identifier = (BuckIdentifier) element;
            return new PsiReference[] {new BuckIdentifierReference(identifier)};
          } else {
            return new PsiReference[0];
          }
        }
      });
}
 
Example 15
Source Project: intellij-neos   Source File: EelProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    Project project = parameters.getPosition().getProject();
    Collection<String> contexts = FileBasedIndex.getInstance().getAllKeys(DefaultContextFileIndex.KEY, project);

    for (String eelHelper : contexts) {
        List<String> helpers = FileBasedIndex.getInstance().getValues(DefaultContextFileIndex.KEY, eelHelper, GlobalSearchScope.allScope(project));
        if (!helpers.isEmpty()) {
            for (String helper : helpers) {
                Collection<PhpClass> classes = PhpIndex.getInstance(project).getClassesByFQN(helper);
                for (PhpClass phpClass : classes) {
                    for (Method method : phpClass.getMethods()) {
                        if (!method.getAccess().isPublic()) {
                            continue;
                        }
                        if (method.getName().equals("allowsCallOfMethod")) {
                            continue;
                        }
                        String completionText = eelHelper + "." + method.getName() + "()";
                        result.addElement(LookupElementBuilder.create(completionText).withIcon(PhpIcons.METHOD_ICON));
                    }
                }
            }
        }
    }
}
 
Example 16
Source Project: idea-php-symfony2-plugin   Source File: AssetCompletionProvider.java    License: 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 17
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 18
Source Project: arma-intellij-plugin   Source File: SQFReferenceContributor.java    License: MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
	if (!(element instanceof SQFVariable)) {
		return PsiReference.EMPTY_ARRAY; //can't be referenced
	}
	SQFVariable var = (SQFVariable) element;

	if (var.isLocal()) {
		return PsiReference.EMPTY_ARRAY;
	}
	List<SQFVariable> vars = findGlobalVariables(element.getProject(), var);
	if (vars.isEmpty()) {
		return PsiReference.EMPTY_ARRAY;
	}
	return new PsiReference[]{new SQFVariableReference.IdentifierReference(var, vars)};
}
 
Example 19
@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 20
private void completeFieldArgumentTypeName() {
    CompletionProvider<CompletionParameters> provider = new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(@NotNull final CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {

            final PsiElement completionElement = parameters.getPosition();
            final TypeDefinitionRegistry registry = GraphQLTypeDefinitionRegistryServiceImpl.getService(completionElement.getProject()).getRegistry(parameters.getOriginalFile());
            addInputTypeCompletions(result, registry);
        }
    };
    extend(CompletionType.BASIC,
            psiElement(GraphQLElementTypes.NAME).afterLeafSkipping(
                    // skip
                    PlatformPatterns.or(psiComment(), psiElement(TokenType.WHITE_SPACE), psiElement().withText("[")),
                    // until argument type colon occurs
                    psiElement().withText(":")
            ).inside(GraphQLInputValueDefinition.class), provider);
}
 
Example 21
@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 22
@Override
public void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet resultSet, @NotNull String[] query) {
    Project project = parameters.getOriginalFile().getManager().getProject();

    List<VirtualFile> resourceRoots = ProjectRootManager.getInstance(project).getModuleSourceRoots(JavaModuleSourceRootTypes.PRODUCTION);
    resourceRoots.addAll(ProjectRootManager.getInstance(project).getModuleSourceRoots(JavaModuleSourceRootTypes.TESTS));
    ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    for (final VirtualFile sourceRoot : resourceRoots) {
        if (sourceRoot.isValid() && sourceRoot.getCanonicalFile() != null) {
            VfsUtil.processFilesRecursively(sourceRoot.getCanonicalFile(), virtualFile -> {
                propertyCompletionProviders.stream()
                    .filter(p -> p.isValidExtension(virtualFile.getCanonicalPath()) && !projectFileIndex.isExcluded(sourceRoot))
                    .forEach(p -> p.buildResultSet(resultSet, virtualFile));
                return true;
            });
        }
    }
}
 
Example 23
public void addCompletions(@NotNull CompletionParameters parameters,
    ProcessingContext context,
    @NotNull CompletionResultSet resultSet) {

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

    resultSet.addAllElements(TwigUtil.getTwigLookupElements(parameters.getPosition().getProject()));
}
 
Example 24
Source Project: litho   Source File: LayoutSpecMethodAnnotationsProvider.java    License: 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 25
Source Project: consulo   Source File: LiftShorterItemsClassifier.java    License: 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 26
Source Project: consulo   Source File: RenameInputValidatorRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public static Condition<String> getInputValidator(final PsiElement element) {
  for(final RenameInputValidator validator: Extensions.getExtensions(RenameInputValidator.EP_NAME)) {
    final ProcessingContext context = new ProcessingContext();
    if (validator.getPattern().accepts(element, context)) {
      return new Condition<String>() {
        @Override
        public boolean value(final String s) {
          return validator.isInputValid(s, element, context);
        }
      };
    }
  }
  return null;
}
 
Example 27
Source Project: consulo   Source File: PsiElementPattern.java    License: Apache License 2.0 5 votes vote down vote up
public Self withMetaData(final ElementPattern<? extends PsiMetaData> metaDataPattern) {
  return with(new PatternCondition<T>("withMetaData") {
    @Override
    public boolean accepts(@Nonnull final T t, final ProcessingContext context) {
      return t instanceof PsiMetaOwner && metaDataPattern.accepts(((PsiMetaOwner)t).getMetaData(), context);
    }
  });
}
 
Example 28
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 Project: consulo   Source File: NamedObjectProviderBinding.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addAcceptableReferenceProviders(@Nonnull PsiElement position, @Nonnull List<ProviderInfo<Provider, ProcessingContext>> list, @Nonnull PsiReferenceService.Hints hints) {
  String name = getName(position);
  if (name != null) {
    addMatchingProviders(position, myNamesToProvidersMap.get(name), list, hints);
    addMatchingProviders(position, myNamesToProvidersMapInsensitive.get(name.toLowerCase()), list, hints);
  }
}
 
Example 30
Source Project: BashSupport   Source File: DynamicPathCompletionProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void addBashCompletions(String currentText, CompletionParameters parameters, ProcessingContext context, CompletionResultSet result) {
    //if we are in a combined word, get it
    PsiElement parentElement = parameters.getPosition().getParent();
    if (parentElement instanceof BashWord) {
        currentText = findCurrentText(parameters, parentElement);
    }

    result = result.withPrefixMatcher(currentText);

    String usedPrefix = findUsedPrefix(currentText);
    if (usedPrefix == null) {
        return;
    }

    //fixme shouldn't be needed
    String baseDir = findBaseDir(parameters, usedPrefix);
    if (baseDir == null) {
        return;
    }

    String relativePath = currentText.substring(usedPrefix.length());
    if (relativePath.startsWith("/")) {
        relativePath = relativePath.substring(1);
    }

    List<String> completions = CompletionUtil.completeRelativePath(baseDir, usedPrefix, relativePath);
    result.addAllElements(CompletionProviderUtils.createPathItems(completions));
}