Java Code Examples for com.intellij.codeInsight.lookup.LookupElementBuilder

The following are top voted examples for showing how to use com.intellij.codeInsight.lookup.LookupElementBuilder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: TS-IJ   File: TSMethodCallCompletionContributor.java   Source Code and License 7 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    PsiElement caller = parameters.getPosition().getPrevSibling().getPrevSibling();
    String ns = TSUtil.getElementNamespace(caller);

    //All global functions
    Project project = parameters.getOriginalFile().getProject();
    Collection<TSFnDeclStmt> functions = TSUtil.getFunctionList(project);
    for (TSFnDeclStmt function : functions) {
        if (function.getFunctionType() == TSFunctionType.GLOBAL)
            continue;

        result.addElement(
                LookupElementBuilder.create(function.getFunctionName())
                        .withCaseSensitivity(false)
                        .withPresentableText(function.getNamespace() + "." + function.getFunctionName())
                        .withBoldness(ns != null && function.getNamespace().equalsIgnoreCase(ns))
                        .withTailText(function.getArgList())
                        .withInsertHandler(TSCaseCorrectingInsertHandler.INSTANCE)
        );
    }
}
 
Example 2
Project: bamboo-soy   File: SoyCompletionContributor.java   Source Code and License 7 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 3
Project: yii2support   File: ValidationCompletionProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
private LookupElementBuilder buildLookup(PhpClassMember field, PhpExpression position, boolean autoValue) {
    String lookupString = field instanceof Method ? ClassUtils.getAsPropertyName((Method) field) : field.getName();
    LookupElementBuilder builder = LookupElementBuilder.create(field, lookupString).withIcon(field.getIcon());
    if (autoValue) {
        builder = builder.withInsertHandler((insertionContext, lookupElement) -> {

            Document document = insertionContext.getDocument();
            int insertPosition = insertionContext.getSelectionEndOffset();

            if (position.getParent().getParent() instanceof ArrayCreationExpression) {
                document.insertString(insertPosition + 1, " => ");
                insertPosition += 5;
                insertionContext.getEditor().getCaretModel().getCurrentCaret().moveToOffset(insertPosition);
            }
        });
    }
    if (field instanceof Field) {
        builder = builder.withTypeText(field.getType().toString());
    }
    return builder;
}
 
Example 4
Project: yii2support   File: FieldAttributesCompletionProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
private LookupElementBuilder buildLookup(PhpClassMember field, PhpExpression position) {
    String lookupString = field instanceof Method ? ClassUtils.getAsPropertyName((Method) field) : field.getName();
    LookupElementBuilder builder =  LookupElementBuilder.create(field, lookupString).withIcon(field.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {

                Document document = insertionContext.getDocument();
                int insertPosition = insertionContext.getSelectionEndOffset();

                if (position.getParent().getParent() instanceof ArrayCreationExpression) {
                    document.insertString(insertPosition + 1, " => ");
                    insertPosition += 5;
                    insertionContext.getEditor().getCaretModel().getCurrentCaret().moveToOffset(insertPosition);
                }
            });
    if (field instanceof Field) {
        builder = builder.withTypeText(field.getType().toString());
    }
    return builder;
}
 
Example 5
Project: yii2support   File: ObjectFactoryCompletionProvider.java   Source Code and License 6 votes vote down vote up
@NotNull
private LookupElementBuilder buildLookup(PhpClassMember field, PhpExpression position) {
    String lookupString = field instanceof Method ? ClassUtils.getAsPropertyName((Method) field) : field.getName();
    LookupElementBuilder builder =  LookupElementBuilder.create(field, lookupString).withIcon(field.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {

                Document document = insertionContext.getDocument();
                int insertPosition = insertionContext.getSelectionEndOffset();

                if (position.getParent().getParent() instanceof ArrayCreationExpression) {
                    document.insertString(insertPosition + 1, " => ");
                    insertPosition += 5;
                    insertionContext.getEditor().getCaretModel().getCurrentCaret().moveToOffset(insertPosition);
                }
            });
    if (field instanceof Field) {
        builder = builder.withTypeText(field.getType().toString());
    }
    return builder;
}
 
Example 6
Project: yii2support   File: DatabaseUtils.java   Source Code and License 6 votes vote down vote up
public static ArrayList<LookupElementBuilder> getLookupItemsTables(Project project, PhpExpression position) {
    DbPsiFacade facade = DbPsiFacade.getInstance(project);
    List<DbDataSource> dataSources = facade.getDataSources();

    // Code to test tests :)
    //dataSources.clear();
    //dataSources.add(new TestDataSource(project));

    ArrayList<LookupElementBuilder> list = new ArrayList<>();
    for (DbDataSource source : dataSources) {
        JBIterable<DasTable> filtered = source.getModel().traverser().filter(DasTable.class);
         for (Object item : filtered) {
            if (item instanceof DasTable) {
                list.add(DatabaseUtils.buildLookup(item, true, project));
            }
        }
    }
    return list;
}
 
Example 7
Project: intellij-spring-assistant   File: Suggestion.java   Source Code and License 6 votes vote down vote up
public LookupElementBuilder newLookupElement(ClassLoader classLoader) {
  LookupElementBuilder builder = LookupElementBuilder.create(this, suggestion);
  if (referringToValue) {
    if (description != null) {
      builder = builder.withTypeText(description, true);
    }
    if (representingDefaultValue) {
      builder = builder.bold();
    }
    if (yaml) {
      builder = builder.withInsertHandler(new YamlValueInsertHandler());
    }
  } else {
    builder = builder.withRenderer(CUSTOM_SUGGESTION_RENDERER).withInsertHandler(yaml ?
        new YamlKeyInsertHandler(ref, classLoader) :
        new YamlKeyInsertHandler(ref, classLoader));
  }
  return builder;
}
 
Example 8
Project: TS-IJ   File: TSLocalVariableCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    List<TSVarExpr> variables = new ArrayList<>();
    for (PsiElement current = parameters.getPosition().getPrevSibling(); current != null; current = current.getPrevSibling()) {
        if (current.getNode().getElementType().equals(TSTypes.FUNCTION))
            break;

        if (current.getNode().getElementType().equals(TSTypes.LOCALVAR)) {
            String prefixless = current.getText().substring(1);
            result.addElement(
                    LookupElementBuilder.create(prefixless)
                    .withPresentableText(current.getText())
                    .withCaseSensitivity(false)
            );
        }
    }
}
 
Example 9
Project: TS-IJ   File: TSGlobalNSCallCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    String namespace = parameters.getPosition().getPrevSibling().getPrevSibling().getText();

    Project project = parameters.getOriginalFile().getProject();
    Collection<TSFnDeclStmt> functions = TSUtil.getFunctionList(project);

    for (TSFnDeclStmt function : functions) {
        if (function.getFunctionType() == TSFunctionType.GLOBAL)
            continue;
        if (namespace != null && !function.getNamespace().equalsIgnoreCase(namespace))
            continue;

        result.addElement(
                LookupElementBuilder.create(function.getFunctionName())
                        .withCaseSensitivity(false)
                        .withPresentableText(function.getNamespace() + "::" + function.getFunctionName())
                        .withTailText(function.getArgList())
                        .withInsertHandler(TSCaseCorrectingInsertHandler.INSTANCE)
        );
    }
}
 
Example 10
Project: TS-IJ   File: TSGlobalCallCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    //All global functions
    Project project = parameters.getOriginalFile().getProject();
    Collection<TSFnDeclStmt> functions = TSUtil.getFunctionList(project);
    for (TSFnDeclStmt function : functions) {
        if (function.getFunctionType() != TSFunctionType.GLOBAL)
            continue;

        result.addElement(
                LookupElementBuilder.create(function)
                        .withCaseSensitivity(false)
                        .withTailText(function.getArgList())
                        .withInsertHandler(TSCaseCorrectingInsertHandler.INSTANCE)
        );
    }
}
 
Example 11
Project: TS-IJ   File: TSGlobalVariableReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    Collection<TSVarExpr> globals = TSUtil.getGlobalList(project);
    List<LookupElement> variants = new ArrayList<>();

    for (final TSVarExpr global : globals) {
        if (global.getName() != null && global.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(global)
                    .withIcon(TSIcons.FILE)
                    .withTypeText(global.getContainingFile().getName())
                    .withCaseSensitivity(false)

            );
        }
    }

    return variants.toArray();
}
 
Example 12
Project: TS-IJ   File: TSFunctionCallReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    Collection<TSFnDeclStmt> functions = TSUtil.getFunctionList(project);
    List<LookupElement> variants = new ArrayList<>();

    for (final TSFnDeclStmt function : functions) {
        if (function.getFunctionName() != null && function.getFunctionName().length() > 0) {
            variants.add(LookupElementBuilder.create(function)
                    .withIcon(TSIcons.FILE)
                    .withTypeText(function.getContainingFile().getName())
                    .withCaseSensitivity(false)

            );
        }
    }

    return variants.toArray();
}
 
Example 13
Project: TS-IJ   File: TSLiteralReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    Collection<TSObjectExpr> globals = TSUtil.getObjectList(project);
    List<LookupElement> variants = new ArrayList<>();

    for (final TSObjectExpr global : globals) {
        if (global.getName() != null && global.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(global)
                    .withIcon(TSIcons.FILE)
                    .withTypeText(global.getContainingFile().getName())
                    .withCaseSensitivity(false)

            );
        }
    }

    return variants.toArray();
}
 
Example 14
Project: AppleScript-IDEA   File: KeywordCompletionContributor.java   Source Code and License 6 votes vote down vote up
public KeywordCompletionContributor() {

    extend(CompletionType.BASIC, psiElement().inFile(StandardPatterns.instanceOf(AppleScriptFile.class)),
        new CompletionProvider<CompletionParameters>() {
          @Override
          protected void addCompletions(@NotNull CompletionParameters completionParameters,
                                        ProcessingContext processingContext,
                                        @NotNull CompletionResultSet completionResultSet) {
            PsiFile file = completionParameters.getOriginalFile();
            if (!(file instanceof AppleScriptFile)) return;
            PsiElement position = completionParameters.getPosition();
            if (position instanceof PsiComment) return;

            ASTNode node = position.getNode();
            if (node.getElementType() == AppleScriptTypes.STRING_LITERAL) return;

            for (IElementType kwElem : AppleScriptTokenTypesSets.KEYWORDS.getTypes()) {
              completionResultSet.addElement(LookupElementBuilder
                  .create(kwElem.toString().toLowerCase().replaceAll("_", " ")).bold()
                  .withTypeText("keyword", true));
            }
          }
        });
  }
 
Example 15
Project: AppleScript-IDEA   File: AppleScriptReferenceElementImpl.java   Source Code and License 6 votes vote down vote up
private void addLookupElement(List<LookupElement> lookupElements, PsiElement el) {
  if (!el.isValid()) return;
  LookupElementBuilder builder;
  if (el instanceof DictionaryComponent) {
    DictionaryComponent dc = (DictionaryComponent) el;
    String dName = dc.getDictionary().getName();
    builder = LookupElementBuilder.createWithIcon(dc).appendTailText("   " + dName, true);
  } else if (el instanceof AppleScriptComponent) {
    builder = LookupElementBuilder.createWithIcon((AppleScriptComponent) el);
    if (el instanceof AppleScriptHandlerPositionalParametersDefinition) {
      AppleScriptHandlerPositionalParametersDefinition handlerCall = (AppleScriptHandlerPositionalParametersDefinition) el;
      builder = builder.withInsertHandler(handlerCall.getFormalParameterList() != null ?
          ParenthesesInsertHandler.WITH_PARAMETERS : ParenthesesInsertHandler.NO_PARAMETERS);
    }
  } else {
    builder = LookupElementBuilder.create(el);
  }
  AppleScriptComponentType componentType = AppleScriptComponentType.typeOf(el);
  String typeText = componentType != null ? componentType.toString().toLowerCase() : null;
  builder = builder.withTypeText(typeText, null, true);
  lookupElements.add(builder);
}
 
Example 16
Project: reasonml-idea-plugin   File: ModuleDotCompletionProvider.java   Source Code and License 6 votes vote down vote up
static void complete(Project project, PsiModuleName name, @NotNull CompletionResultSet resultSet) {
    // Get the correct module
    Collection<PsiModule> modules = StubIndex.getElements(IndexKeys.MODULES, name.getName(), project, GlobalSearchScope.allScope(project), PsiModule.class);

    if (!modules.isEmpty()) {
        for (PsiModule module : modules) {
            Collection<PsiNamedElement> expressions = module.getExpressions();

            for (PsiNamedElement expression : expressions) {
                resultSet.addElement(
                        LookupElementBuilder.create(expression).
                                withIcon(PsiIconUtil.getProvidersIcon(expression, 0)).
                                withTypeText(PsiInferredTypeUtil.getTypeInfo(expression))
                );
            }
        }
    }
}
 
Example 17
Project: reasonml-idea-plugin   File: MerlinCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
    MerlinService merlin = ApplicationManager.getApplication().getComponent(MerlinService.class);

    PsiFile originalFile = parameters.getOriginalFile();
    String text = originalFile.getText();
    LineNumbering lineNumbering = new LineNumbering(text);

    String suitablePrefix = findSuitablePrefix(parameters, text);

    MerlinPosition position = lineNumbering.offsetToPosition(parameters.getOffset());
    MerlinCompletion completion = merlin.completions(originalFile.getName(), text, position, suitablePrefix);

    for (MerlinCompletionEntry entry : completion.entries) {
        resultSet.addElement(LookupElementBuilder.
                create(entry.name).
                withIcon(getIcon(entry)).
                withTypeText(entry.desc));
    }
}
 
Example 18
Project: greycat-idea-plugin   File: GCMReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    List<GCMTypeDeclaration> properties = GCMUtil.findProperties(project);
    List<LookupElement> variants = new ArrayList<LookupElement>();
    for (final GCMTypeDeclaration property : properties) {
        if (property != null && property.getName() != null && property.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(property).
                    withIcon(GCMIcons.GCM_ICON_16x16).
                    withTypeText(property.getContainingFile().getName())
            );
        }
    }
    return variants.toArray();
}
 
Example 19
Project: magento2-phpstorm-plugin   File: PhpConstructorArgumentCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null || !(position instanceof XmlElement)) {
        return;
    }


    DiIndex diIndex = DiIndex.getInstance(position.getProject());
    PhpClass phpClass = diIndex.getPhpClassOfArgument((XmlElement) position);
    if (phpClass != null) {
        Method constructor = phpClass.getConstructor();
        if (constructor != null) {
            for (Parameter parameter : constructor.getParameters()) {
                result.addElement(
                        LookupElementBuilder
                                .create(parameter.getName())
                                .withIcon(parameter.getIcon())
                );
            }
        }
    }
}
 
Example 20
Project: magento2-phpstorm-plugin   File: LayoutContainerCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }

    Collection<String> keys = LayoutIndex.getAllKeys(ContainerNameIndex.KEY, position.getProject());
    for (String key: keys) {
        result.addElement(
            LookupElementBuilder.create(key).withIcon(PhpIcons.XML_TAG_ICON)
        );
    }
}
 
Example 21
Project: magento2-phpstorm-plugin   File: ModuleNameCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }
    String prefix = result.getPrefixMatcher().getPrefix();

    Collection<String> moduleNames
            = FileBasedIndex.getInstance().getAllKeys(ModuleNameIndex.KEY, position.getProject());


    moduleNames.removeIf(m -> !m.startsWith(prefix));
    for (String moduleName : moduleNames) {
        result.addElement(
                LookupElementBuilder
                        .create(moduleName)
                        .withIcon(AllIcons.Modules.ModulesNode)
        );
    }
}
 
Example 22
Project: magento2-phpstorm-plugin   File: LayoutBlockCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }

    Collection<String> keys = LayoutIndex.getAllKeys(BlockNameIndex.KEY, position.getProject());
    for (String key: keys) {
        result.addElement(
            LookupElementBuilder.create(key).withIcon(PhpIcons.XML_TAG_ICON)
        );
    }
}
 
Example 23
Project: magento2-phpstorm-plugin   File: VirtualTypeCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }

    String prefix = result.getPrefixMatcher().getPrefix();

    DiIndex index = DiIndex.getInstance(position.getProject());
    Collection<String> elements = index.getAllVirtualTypeElementNames(new PlainPrefixMatcher(prefix), position.getResolveScope());

    for (String elementName:elements) {
        result.addElement(
                LookupElementBuilder
                        .create(elementName)
                        .withIcon(PhpIcons.CLASS_ICON)
        );
    }
}
 
Example 24
Project: magento2-phpstorm-plugin   File: LayoutUpdateCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }

    List<XmlFile> targets = LayoutIndex.getLayoutFiles(position.getProject());
    if (targets.size() > 0) {
        for (XmlFile file : targets) {
            result.addElement(
                LookupElementBuilder
                        .create(file.getVirtualFile().getNameWithoutExtension())
                        .withIcon(PhpIcons.XML_TAG_ICON)
            );
        }
    }
}
 
Example 25
Project: magento2-phpstorm-plugin   File: PhpServiceMethodCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext context,
                              @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition().getOriginalElement();
    if (position == null) {
        return;
    }

    PhpClass phpClass = DiIndex.getPhpClassOfServiceMethod((XmlElement) position);
    if (phpClass != null) {
        for (Method method : phpClass.getMethods()) {
            result.addElement(
                    LookupElementBuilder
                            .create(method.getName())
                            .withIcon(method.getIcon())
            );
        }
    }
}
 
Example 26
Project: EmojiPrefix   File: EmojiResourceCompletionContributor.java   Source Code and License 6 votes vote down vote up
public EmojiResourceCompletionContributor() {
	extend(CompletionType.BASIC, PlatformPatterns.psiElement(PsiElement.class), new CompletionProvider<CompletionParameters>() {
		@Override
		protected void addCompletions(@NotNull CompletionParameters completionParameters,
									  ProcessingContext processingContext,
									  @NotNull CompletionResultSet completionResultSet) {
			Document document = completionParameters.getEditor().getDocument();
			int lineStart = document.getLineStartOffset(document.getLineNumber(completionParameters.getOffset()));
			String lineText = document.getText(new TextRange(lineStart, completionParameters.getOffset()));
			if (includeCount(lineText) == 1) {
				for (Map.Entry<String, Icon> iconEntry : EmojiUtil.getEmojiMap().entrySet()) {
					completionResultSet.addElement(LookupElementBuilder.create(iconEntry.getKey(), ":" + iconEntry.getKey() + ":")
							.withIcon(iconEntry.getValue())
							.withInsertHandler((insertionContext, lookupElement) -> {
								int startOffset = insertionContext.getStartOffset();
								Document insertDocument = insertionContext.getDocument();
								if (startOffset > 0 && insertDocument.getCharsSequence().charAt(startOffset - 1) == ':') {
									insertDocument.deleteString(startOffset - 1, startOffset);
								}
							}));
				}
			}
		}
	});
}
 
Example 27
Project: hybris-integration-intellij-idea-plugin   File: ItemTypeCodeCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
public void addCompletions(
    @NotNull final CompletionParameters parameters,
    final ProcessingContext context,
    @NotNull final CompletionResultSet result
) {
    Validate.notNull(parameters);
    Validate.notNull(result);

    final Project project = this.getProject(parameters);
    if (null == project) {
        return;
    }
    final TSMetaModel typeSystemMeta = TSMetaModelAccess.getInstance(project).getTypeSystemMeta();

    typeSystemMeta.getMetaClassesStream()
                  .map(meta -> LookupElementBuilder.create(meta.getName()).withIcon(HybrisIcons.TYPE_SYSTEM))
                  .forEach(result::addElement);
}
 
Example 28
Project: hybris-integration-intellij-idea-plugin   File: ExtensionsNameContributor.java   Source Code and License 6 votes vote down vote up
public ExtensionsNameContributor() {
    extend(
        CompletionType.BASIC,
        tagAttributePattern("extension", "name", null),
        new CompletionProvider<CompletionParameters>() {

            @Override
            protected void addCompletions(
                @NotNull final CompletionParameters parameters,
                final ProcessingContext context,
                @NotNull final CompletionResultSet result
            ) {
                final HybrisProjectSettings hybrisProjectSettings
                    = HybrisProjectSettingsComponent.getInstance(parameters.getOriginalFile().getProject())
                                                    .getState();
                final Set<String> extensions = hybrisProjectSettings.getCompleteSetOfAvailableExtensionsInHybris();

                extensions.forEach(name -> result.addElement(LookupElementBuilder.create(name)));
            }
        }
    );

}
 
Example 29
Project: hybris-integration-intellij-idea-plugin   File: ImpexMacrosCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(
    @NotNull final CompletionParameters parameters,
    final ProcessingContext context,
    @NotNull final CompletionResultSet result
) {
    final PsiFile originalFile = parameters.getOriginalFile();

    final Collection<ImpexMacroDeclaration> macroDeclarations = PsiTreeUtil.findChildrenOfType(
        originalFile, ImpexMacroDeclaration.class
    );

    if (macroDeclarations.isEmpty()) {
        return;
    }

    for (final ImpexMacroDeclaration macroDeclaration : macroDeclarations) {
        final PsiElement declaration = macroDeclaration.getFirstChild();
        result.addElement(LookupElementBuilder.create(declaration.getText())
                                              .withIcon(HybrisIcons.MACROS));
    }
}
 
Example 30
Project: intellij-plugin   File: ClassCompletionResolver.java   Source Code and License 6 votes vote down vote up
@Override
public Stream<LookupElementBuilder> resolveCompletions(String propertyName, PsiType psiType) {
    PsiType[] parameters = ((PsiClassReferenceType) psiType).getParameters();
    Stream<PsiClass> psiClassStream = null;
    if (parameters.length == 1 && parameters[0] instanceof PsiWildcardType) {
        PsiWildcardType psiWildcardType = ((PsiWildcardType) parameters[0]);
        if (psiWildcardType.isBounded()) {
            if (psiWildcardType.isExtends()) {
                psiClassStream = subClasses((PsiClassType) psiWildcardType.getExtendsBound()).stream();
            } else if (psiWildcardType.isSuper()) {
                psiClassStream = superClasses((PsiClassType) psiWildcardType.getSuperBound()).stream();
            }
        }
    }
    if (psiClassStream != null) {
        return psiClassStream.map(this::buildClassLookup).filter(Optional::isPresent).map(Optional::get);
    } else {
        return Stream.empty();
    }
}
 
Example 31
Project: intellij-plugin   File: KeyCompletionProvider.java   Source Code and License 6 votes vote down vote up
@Override
public Stream<LookupElementBuilder> resolve(String path, PsiElement position) {
    Project project = position.getProject();
    Stream<String> keys;
    if (path.isEmpty()) {
        keys = CoffigResolver.from(project)
                .onlyAtTopLevel()
                .classes()
                .map(CoffigResolver.Match::getName);
    } else {
        keys = CoffigResolver.from(project)
                .find(path)
                .filter(CoffigResolver.Match::isFullyResolved)
                .map(CoffigResolver.Match::allProperties)
                .orElse(Stream.empty());
    }
    return keys.map(key -> key.split("\\.")[0]).map(LookupElementBuilder::create);
}
 
Example 32
Project: intellij-ce-playground   File: AndroidAddStringResourceAction.java   Source Code and License 6 votes vote down vote up
@Override
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) {
  final PsiElement[] vars = getVariables(params, context);
  if (vars == null || vars.length == 0) {
    return null;
  }
  final Set<LookupElement> set = new LinkedHashSet<LookupElement>();
  for (PsiElement var : vars) {
    JavaTemplateUtil.addElementLookupItem(set, var);
  }
  LookupElement[] elements = set.toArray(new LookupElement[set.size()]);
  if (elements.length == 0) {
    return elements;
  }
  LookupElement lookupElementForDefValue = LookupElementBuilder.create(myDefaultValue);
  LookupElement[] result = new LookupElement[elements.length + 1];
  result[0] = lookupElementForDefValue;
  System.arraycopy(elements, 0, result, 1, elements.length);
  return result;
}
 
Example 33
Project: smcplugin   File: AbstractNamedLocalReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    List<LookupElement> variants = new ArrayList<>();

    Collection<ENCLOSED_TYPE> enclosedTypes = SmcPsiUtil.getElementsByTypeWithinParentType(myElement, enclosingTypeClass, enclosedTypeClass);
    for (final ENCLOSED_TYPE enclosed : enclosedTypes) {
        if (!StringUtil.isEmpty(enclosed.getName())) {
            variants.add(LookupElementBuilder.create(enclosed).
                    withIcon(getFile()).
                    withTypeText(enclosed.getContainingFile().getName())
            );
        }
    }
    return variants.toArray();
}
 
Example 34
Project: smcplugin   File: SmcJavaMethodReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
    Project project = myElement.getProject();
    List<PsiMethod> properties = SmcPsiUtil.findJavaMethod(project);
    List<LookupElement> variants = new ArrayList<LookupElement>();
    for (final PsiMethod property : properties) {
        if (property.getName().length() > 0) {
            variants.add(LookupElementBuilder.create(property).
                    withIcon(AllIcons.Hierarchy.MethodDefined).
                    withTypeText(property.getContainingFile().getName())
            );
        }
    }
    return variants.toArray();
}
 
Example 35
Project: intellij-ce-playground   File: LookupWithIndentsBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * @return result lookup elements (to display in {@link PsiReference#getVariants()} for example)
 */
@NotNull
LookupElement[] getResult() {
  final List<LookupElement> result = new ArrayList<LookupElement>(myMap.size());
  for (final Entry<LookupElementBuilder, Pair<String, Integer>> entry : myMap.entrySet()) {
    LookupElementBuilder elementBuilder = entry.getKey();
    final Pair<String, Integer> helpAndPriority = entry.getValue();
    final String help = helpAndPriority.first;

    if (!StringUtil.isEmptyOrSpaces(help)) {
      final int padding = myMaxLength - elementBuilder.getLookupString().length();
      elementBuilder = elementBuilder.withTailText(String.format("%s : %s", StringUtil.repeat(" ", padding), help));
    }
    if (myHasPriority) {
      // If we have priority and it is not provided for certain element we believe it is 0
      final int priority = (helpAndPriority.second == null ? 0 : helpAndPriority.second);
      result.add(PrioritizedLookupElement.withPriority(elementBuilder, priority));
    }
    else {
      result.add(elementBuilder);
    }
  }
  return result.toArray(new LookupElement[result.size()]);
}
 
Example 36
Project: epigraph   File: SchemaCompletionContributor.java   Source Code and License 6 votes vote down vote up
private void completeWith(@NotNull PsiElement position, @NotNull final CompletionResultSet result) {
  PsiElement qid = position.getParent();
  if (!(qid instanceof SchemaQid)) return;

  if (PsiTreeUtil.getParentOfType(qid, SchemaSupplementDef.class) != null) {
    SchemaQnTypeRef qnTypeRef = PsiTreeUtil.getParentOfType(qid, SchemaQnTypeRef.class);
    if (qnTypeRef != null) {
      PsiElement prevSibling = SchemaPsiUtil.prevNonWhitespaceSibling(qnTypeRef);
      if (prevSibling != null
          && prevSibling.getNode().getElementType() != S_COMMA
          && prevSibling.getNode().getElementType() != S_SUPPLEMENT
          && !SchemaPsiUtil.hasPrevSibling(qnTypeRef, S_WITH)) {
        result.addElement(LookupElementBuilder.create("with "));
      }
    }
  }

}
 
Example 37
Project: intellij-ce-playground   File: ResourceBundleReference.java   Source Code and License 6 votes vote down vote up
@NotNull
public Object[] getVariants() {
  final ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(getElement().getProject());
  final PropertiesReferenceManager referenceManager = PropertiesReferenceManager.getInstance(getElement().getProject());

  final Set<String> bundleNames = new HashSet<String>();
  final List<LookupElement> variants = new SmartList<LookupElement>();
  PropertiesFileProcessor processor = new PropertiesFileProcessor() {
    @Override
    public boolean process(String baseName, PropertiesFile propertiesFile) {
      if (!bundleNames.add(baseName)) return true;

      final LookupElementBuilder builder =
        LookupElementBuilder.create(baseName)
          .withIcon(AllIcons.Nodes.ResourceBundle);
      boolean isInContent = projectFileIndex.isInContent(propertiesFile.getVirtualFile());
      variants.add(isInContent ? PrioritizedLookupElement.withPriority(builder, Double.MAX_VALUE) : builder);
      return true;
    }
  };

  referenceManager.processPropertiesFiles(myElement.getResolveScope(), processor, this);
  return variants.toArray(new LookupElement[variants.size()]);
}
 
Example 38
Project: intellij-ce-playground   File: GroovyCompletionUtil.java   Source Code and License 6 votes vote down vote up
private static LookupElementBuilder setTypeText(PsiElement element,
                                                LookupElementBuilder builder,
                                                PsiSubstitutor substitutor,
                                                @Nullable PsiElement position) {
  PsiType type = null;
  if (element instanceof GrVariable) {
    if (position != null && org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isLocalVariable(element)) {
      type = TypeInferenceHelper.getInferredType(position, ((GrVariable)element).getName());
    }
    else {
      type = ((GrVariable)element).getTypeGroovy();
    }
  }
  else if (element instanceof PsiVariable) {
    type = ((PsiVariable)element).getType();
  }
  else if (element instanceof PsiMethod) {
    type = substitutor.substitute(((PsiMethod)element).getReturnType());
  }
  return type != null ? builder.withTypeText(type.getPresentableText()) : builder;
}
 
Example 39
Project: intellij-ce-playground   File: PyModuleType.java   Source Code and License 6 votes vote down vote up
@NotNull
public static List<LookupElement> collectImportedSubmodulesAsLookupElements(@NotNull PsiFileSystemItem pyPackage,
                                                                            @NotNull PsiElement location,
                                                                            @Nullable final Set<String> existingNames) {

  final List<PsiElement> elements = collectImportedSubmodules(pyPackage, location);
  return elements != null ? ContainerUtil.mapNotNull(elements,
                                  new Function<PsiElement, LookupElement>() {
                                    @Override
                                    public LookupElement fun(PsiElement element) {
                                      if (element instanceof PsiFileSystemItem) {
                                        return buildFileLookupElement((PsiFileSystemItem)element, existingNames);
                                      }
                                      else if (element instanceof PsiNamedElement) {
                                        return LookupElementBuilder.createWithIcon((PsiNamedElement)element);
                                      }
                                      return null;
                                    }
                                  }) : Collections.<LookupElement>emptyList();
}
 
Example 40
Project: intellij-ce-playground   File: ActionOrGroupResolveConverter.java   Source Code and License 6 votes vote down vote up
@Nullable
@Override
public LookupElement createLookupElement(ActionOrGroup actionOrGroup) {
  if (actionOrGroup instanceof Action) {
    Action action = (Action)actionOrGroup;
    final PsiElement element = getPsiElement(actionOrGroup);
    if (element == null) {
      throw new IllegalStateException(action.getId().getStringValue() + " in " + DomUtil.getFile(action) + " " + action.isValid() + " ");
    }

    LookupElementBuilder builder =
      LookupElementBuilder.create(ObjectUtils.assertNotNull(element),
                                  ObjectUtils.assertNotNull(getName(action)));

    final String text = action.getText().getStringValue();
    if (StringUtil.isNotEmpty(text)) {
      String withoutMnemonic = StringUtil.replace(text, "_", "");
      builder = builder.withTailText(" \"" + withoutMnemonic + "\"", true);
    }

    return builder;
  }

  return super.createLookupElement(actionOrGroup);
}
 
Example 41
Project: pysynthetic-intellij   File: SyntheticInitArgsCompletionContributor.java   Source Code and License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
                              ProcessingContext processingContext,
                              @NotNull CompletionResultSet result) {

    final PsiElement original = parameters.getOriginalPosition();
    if (original != null) {
        result = result.withPrefixMatcher(getPrefix(parameters.getOffset(), parameters.getOriginalFile()));
        SyntheticTypeInfo sti = processingContext.get(SYNTHETIC_TYPE_INFO_KEY);
        if (sti.hasSyntheticConstructor()) {
            for (SyntheticMemberInfo smi : sti.getMembers()) {
                LookupElement lookupElement =
                        LookupElementBuilder
                                .create(smi.getName() + "=")
                                .withIcon(PlatformIcons.PARAMETER_ICON);
                result.addElement(lookupElement);
            }
        }
    }
}
 
Example 42
Project: intellij-ce-playground   File: MavenUtil.java   Source Code and License 6 votes vote down vote up
public static List<LookupElement> getPhaseVariants(MavenProjectsManager manager) {
  Set<String> goals = new HashSet<String>();
  goals.addAll(MavenConstants.PHASES);

  for (MavenProject mavenProject : manager.getProjects()) {
    for (MavenPlugin plugin : mavenProject.getPlugins()) {
      MavenPluginInfo pluginInfo = MavenArtifactUtil.readPluginInfo(manager.getLocalRepository(), plugin.getMavenId());
      if (pluginInfo != null) {
        for (MavenPluginInfo.Mojo mojo : pluginInfo.getMojos()) {
          goals.add(mojo.getDisplayName());
        }
      }
    }
  }

  List<LookupElement> res = new ArrayList<LookupElement>(goals.size());
  for (String goal : goals) {
    res.add(LookupElementBuilder.create(goal).withIcon(MavenIcons.Phase));
  }

  return res;
}
 
Example 43
Project: camel-idea-plugin   File: CamelSmartCompletionEndpointValue.java   Source Code and License 6 votes vote down vote up
private static void addEnumSuggestions(Editor editor, String val, String suffix, List<LookupElement> answer,
                                       String deprecated, String enums, String defaultValue, boolean xmlMode) {
    String[] parts = enums.split(",");
    for (String part : parts) {
        String lookup = val + part;
        LookupElementBuilder builder = LookupElementBuilder.create(lookup);
        builder = addInsertHandler(editor, suffix, builder, xmlMode);

        // only show the option in the UI
        builder = builder.withPresentableText(part);
        builder = builder.withBoldness(true);
        if ("true".equals(deprecated)) {
            // mark as deprecated
            builder = builder.withStrikeoutness(true);
        }
        boolean isDefaultValue = defaultValue != null && part.equals(defaultValue);
        if (isDefaultValue) {
            builder = builder.withTailText(" (default value)");
            // add default value first in the list
            answer.add(0, builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
        } else {
            answer.add(builder.withAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE));
        }
    }
}
 
Example 44
Project: intellij-ce-playground   File: CommandLineOptionReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
  final LookupWithIndentsBuilder builder = new LookupWithIndentsBuilder();

  final ValidationResult validationResult = getValidationResult();
  if (validationResult == null) {
    return EMPTY_ARRAY;
  }

  for (final Option option : validationResult.getUnusedOptions()) {
    // Suggest long options for -- and short for -
    final List<String> names = getElement().isLong() ? option.getLongNames() : option.getShortNames();
    for (final String optionName : names) {
      builder.addElement(LookupElementBuilder.create(optionName), option.getHelp().getHelpString());
    }
  }

  return builder.getResult();
}
 
Example 45
Project: camel-idea-plugin   File: CamelSmartCompletionEndpointOptions.java   Source Code and License 6 votes vote down vote up
public static List<LookupElement> addSmartCompletionSuggestionsContextPath(String val, ComponentModel component,
                                                                           Map<String, String> existing, boolean xmlMode, PsiElement psiElement) {
    List<LookupElement> answer = new ArrayList<>();

    // show the syntax as the only choice for now
    LookupElementBuilder builder = LookupElementBuilder.create(val);
    builder = builder.withIcon(getCamelPreferenceService().getCamelIcon());
    builder = builder.withBoldness(true);
    builder = builder.withPresentableText(component.getSyntax());

    LookupElement element = builder.withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
    answer.add(element);
    val = removeUnknownEnum(val, psiElement);
    List<LookupElement> old = addSmartCompletionContextPathEnumSuggestions(val, component, existing);
    if (!old.isEmpty()) {
        answer.addAll(old);
    }

    return answer;
}
 
Example 46
Project: intellij-ce-playground   File: RegExpPropertyImpl.java   Source Code and License 6 votes vote down vote up
@NotNull
public Object[] getVariants() {
  final ASTNode categoryNode = getCategoryNode();
  if (categoryNode != null && categoryNode.getText().startsWith("In") && !categoryNode.getText().startsWith("Intelli")) {
    return UNICODE_BLOCKS;
  }
  else {
    boolean startsWithIs = categoryNode != null && categoryNode.getText().startsWith("Is");
    Collection<LookupElement> result = ContainerUtil.newArrayList();
    for (String[] properties : RegExpLanguageHosts.getInstance().getAllKnownProperties(getElement())) {
      String name = ArrayUtil.getFirstElement(properties);
      if (name != null) {
        String typeText = properties.length > 1 ? properties[1] : ("Character.is" + name.substring("java".length()) + "()");
        result.add(PrioritizedLookupElement.withPriority(LookupElementBuilder.create(name)
                                                           .withPresentableText(startsWithIs ? "Is" + name : name)
                                                           .withIcon(PlatformIcons.PROPERTY_ICON)
                                                           .withTypeText(typeText), getPriority(name)));
      }
    }
    return ArrayUtil.toObjectArray(result);
  }
}
 
Example 47
Project: intellij-ce-playground   File: JavaGenerateMemberCompletionContributor.java   Source Code and License 6 votes vote down vote up
private static LookupElementBuilder createOverridingLookupElement(boolean implemented,
                                                                  final PsiMethod baseMethod,
                                                                  PsiClass baseClass, PsiSubstitutor substitutor) {

  RowIcon icon = new RowIcon(baseMethod.getIcon(0), implemented ? AllIcons.Gutter.ImplementingMethod : AllIcons.Gutter.OverridingMethod);
  return createGenerateMethodElement(baseMethod, substitutor, icon, baseClass.getName(), new InsertHandler<LookupElement>() {
    @Override
    public void handleInsert(InsertionContext context, LookupElement item) {
      removeLookupString(context);

      final PsiClass parent = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getStartOffset(), PsiClass.class, false);
      if (parent == null) return;

      List<PsiMethod> prototypes = OverrideImplementUtil.overrideOrImplementMethod(parent, baseMethod, false);
      insertGenerationInfos(context, OverrideImplementUtil.convert2GenerationInfos(prototypes));
    }
  });
}
 
Example 48
Project: intellij-ce-playground   File: JavaLookupElementBuilder.java   Source Code and License 6 votes vote down vote up
public static LookupElementBuilder forMethod(@NotNull PsiMethod method,
                                             @NotNull String lookupString, final @NotNull PsiSubstitutor substitutor,
                                             @Nullable PsiClass qualifierClass) {
  LookupElementBuilder builder = LookupElementBuilder.create(method, lookupString)
    .withIcon(method.getIcon(Iconable.ICON_FLAG_VISIBILITY))
    .withPresentableText(method.getName())
    .withTailText(PsiFormatUtil.formatMethod(method, substitutor,
                                             PsiFormatUtilBase.SHOW_PARAMETERS,
                                             PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_TYPE));
  final PsiType returnType = method.getReturnType();
  if (returnType != null) {
    builder = builder.withTypeText(substitutor.substitute(returnType).getPresentableText());
  }
  builder = setBoldIfInClass(method, qualifierClass, builder);
  return builder;
}
 
Example 49
Project: intellij-ce-playground   File: CommandLineCommandReference.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
  final CommandLineFile file = getCommandLineFile();
  if (file == null) {
    return EMPTY_ARRAY;
  }
  final List<Command> commands = file.getCommands();
  if (commands == null) {
    return EMPTY_ARRAY;
  }

  final LookupWithIndentsBuilder result = new LookupWithIndentsBuilder();

  for (final Command command : commands) {
    final LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(command.getName());
    final Help help = command.getHelp(true);
    result.addElement(lookupElementBuilder, (help != null ? help.getHelpString() : null));
  }


  return result.getResult();
}
 
Example 50
Project: intellij-ce-playground   File: AnnotatedMacro.java   Source Code and License 6 votes vote down vote up
@Override
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) {
  final Query<PsiMember> query = findAnnotated(context, params);

  if (query != null) {
    Set<LookupElement> set = new LinkedHashSet<LookupElement>();
    final String secondParamValue = params.length > 1 ? params[1].calculateResult(context).toString() : null;
    final boolean isShortName = secondParamValue != null && !Boolean.valueOf(secondParamValue);
    final Project project = context.getProject();
    final PsiClass findInClass = secondParamValue != null
                                 ? JavaPsiFacade.getInstance(project).findClass(secondParamValue, GlobalSearchScope.allScope(project))
                                 : null;

    for (PsiMember object : query.findAll()) {
      if (findInClass != null && !object.getContainingClass().equals(findInClass)) continue;
      boolean isClazz = object instanceof PsiClass;
      final String name = isShortName || !isClazz ? object.getName() : ((PsiClass) object).getQualifiedName();
      set.add(LookupElementBuilder.create(name));
    }

    return set.toArray(new LookupElement[set.size()]);
  }
  return LookupElement.EMPTY_ARRAY;
}
 
Example 51
Project: intellij-ce-playground   File: SPIClassProviderReferenceElement.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public Object[] getVariants() {
  final String name = getContainingFile().getName();
  final PsiClass superProvider = JavaPsiFacade.getInstance(getProject()).findClass(name, getResolveScope());
  if (superProvider != null) {
    final List<Object> result = new ArrayList<Object>();
    ClassInheritorsSearch.search(superProvider).forEach(new Processor<PsiClass>() {
      @Override
      public boolean process(PsiClass psiClass) {
        if (!psiClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
          final String jvmClassName = ClassUtil.getJVMClassName(psiClass);
          if (jvmClassName != null) {
            result.add(LookupElementBuilder.create(psiClass, jvmClassName));
          }
        }
        return true;
      }
    });
    return ArrayUtil.toObjectArray(result);
  }
  return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
 
Example 52
Project: intellij   File: BuiltInSymbolCompletionContributor.java   Source Code and License 6 votes vote down vote up
public BuiltInSymbolCompletionContributor() {
  extend(
      CompletionType.BASIC,
      psiElement()
          .withLanguage(BuildFileLanguage.INSTANCE)
          .andNot(psiComment())
          .withParent(ReferenceExpression.class)
          .andNot(psiElement().inside(FuncallExpression.class))
          .andNot(psiElement().afterLeaf(psiElement().withText("."))),
      new CompletionProvider<CompletionParameters>() {
        @Override
        protected void addCompletions(
            CompletionParameters parameters,
            ProcessingContext context,
            CompletionResultSet result) {
          for (String symbol : BuiltInNamesProvider.GLOBALS) {
            result.addElement(LookupElementBuilder.create(symbol));
          }
        }
      });
}
 
Example 53
Project: intellij-ce-playground   File: MavenModulePsiReference.java   Source Code and License 6 votes vote down vote up
@NotNull
public Object[] getVariants() {
  List<DomFileElement<MavenDomProjectModel>> files = MavenDomUtil.collectProjectModels(getProject());

  List<Object> result = new ArrayList<Object>();

  for (DomFileElement<MavenDomProjectModel> eachDomFile : files) {
    VirtualFile eachVFile = eachDomFile.getOriginalFile().getVirtualFile();
    if (Comparing.equal(eachVFile, myVirtualFile)) continue;

    PsiFile psiFile = eachDomFile.getFile();
    String modulePath = calcRelativeModulePath(myVirtualFile, eachVFile);

    result.add(LookupElementBuilder.create(psiFile, modulePath).withPresentableText(modulePath));
  }

  return result.toArray();
}
 
Example 54
Project: intellij-ce-playground   File: WordCompletionContributor.java   Source Code and License 6 votes vote down vote up
public static void addWordCompletionVariants(CompletionResultSet result, final CompletionParameters parameters, Set<String> excludes) {
  final Set<String> realExcludes = new HashSet<String>(excludes);
  for (String exclude : excludes) {
    String[] words = exclude.split("[ \\.-]");
    if (words.length > 0 && StringUtil.isNotEmpty(words[0])) {
      realExcludes.add(words[0]);
    }
  }
  
  int startOffset = parameters.getOffset();
  final PsiElement position = parameters.getPosition();
  final CompletionResultSet javaResultSet = result.withPrefixMatcher(CompletionUtil.findJavaIdentifierPrefix(parameters));
  final CompletionResultSet plainResultSet = result.withPrefixMatcher(CompletionUtil.findAlphanumericPrefix(parameters));
  for (final String word : getAllWords(position, startOffset)) {
    if (!realExcludes.contains(word)) {
      final LookupElement item = LookupElementBuilder.create(word);
      javaResultSet.addElement(item);
      plainResultSet.addElement(item);
    }
  }

  addValuesFromOtherStringLiterals(result, parameters, realExcludes, position);
}
 
Example 55
Project: intellij-ce-playground   File: TextFieldWithAutoCompletionListProvider.java   Source Code and License 6 votes vote down vote up
public LookupElementBuilder createLookupBuilder(@NotNull final T item) {
  LookupElementBuilder builder = LookupElementBuilder.create(item, getLookupString(item))
    .withIcon(getIcon(item));

  final InsertHandler<LookupElement> handler = createInsertHandler(item);
  if (handler != null) {
    builder = builder.withInsertHandler(handler);
  }

  final String tailText = getTailText(item);
  if (tailText != null) {
    builder = builder.withTailText(tailText, true);
  }

  final String typeText = getTypeText(item);
  if (typeText != null) {
    builder = builder.withTypeText(typeText);
  }
  return builder;
}
 
Example 56
Project: intellij-ce-playground   File: PySuperClassAttributesCompletionContributor.java   Source Code and License 6 votes vote down vote up
public PySuperClassAttributesCompletionContributor() {
  extend(CompletionType.BASIC,
         PlatformPatterns.psiElement()
           .withParents(PyReferenceExpression.class, PyExpressionStatement.class, PyStatementList.class, PyClass.class),
         new CompletionProvider<CompletionParameters>() {
           @Override
           protected void addCompletions(@NotNull CompletionParameters parameters,
                                         ProcessingContext context,
                                         @NotNull CompletionResultSet result) {
             PsiElement position = parameters.getOriginalPosition();
             PyClass containingClass = PsiTreeUtil.getParentOfType(position, PyClass.class);

             if (containingClass == null) {
               return;
             }
             for (PyTargetExpression expr : getSuperClassAttributes(containingClass)) {
               result.addElement(LookupElementBuilder.create(expr, expr.getName() + " = "));
             }
           }
         }
  );
}
 
Example 57
Project: intellij-ce-playground   File: CollectionElementNameMacro.java   Source Code and License 6 votes vote down vote up
public LookupElement[] calculateLookupItems(@NotNull Expression[] params, ExpressionContext context) {
  Result result = calculateResult(params, context);
  if (result == null) {
    return null;
  }
  final String[] words = result.toString().split("_");
  if (words.length > 1) {
    List<LookupElement> lookup = new ArrayList<LookupElement>();
    for(int i=0; i<words.length; i++) {
      String element = StringUtil.join(words, i, words.length, "_");
      lookup.add(LookupElementBuilder.create(element));
    }
    return lookup.toArray(new LookupElement[lookup.size()]);
  }
  return null;
}
 
Example 58
Project: yii2support   File: ValidationCompletionProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
private LookupElementBuilder buildLookup(Method method, PhpExpression position) {
    String lookupString = method.getName();
    LookupElementBuilder builder = LookupElementBuilder.create(method, lookupString).withIcon(method.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {
            });

    builder = builder.withTypeText(method.getFQN());


    return builder;
}
 
Example 59
Project: yii2support   File: ValidationCompletionProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
private LookupElementBuilder buildLookup(PhpClass phpClass, PhpExpression position) {
    String lookupString = phpClass.getFQN();
    lookupString = lookupString.replaceAll("^\\\\", "");
    LookupElementBuilder builder = LookupElementBuilder.create(phpClass, lookupString).withIcon(phpClass.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {
            })
            .withTypeText(phpClass.getNamespaceName().replaceAll("^\\\\", "").replaceAll("\\\\$", ""), true)
            .withPresentableText(phpClass.getName());

    return builder;
}
 
Example 60
Project: yii2support   File: ValidationCompletionProvider.java   Source Code and License 5 votes vote down vote up
@NotNull
private LookupElementBuilder buildLookup(String lookupString, PhpClass phpClass, PhpExpression position) {
    LookupElementBuilder builder = LookupElementBuilder.create(phpClass, lookupString).withIcon(phpClass.getIcon())
            .withInsertHandler((insertionContext, lookupElement) -> {
            });

    builder = builder.withTypeText(phpClass.getFQN(), true);

    return builder;
}