下面列出了com.intellij.psi.html.HtmlTag#com.intellij.codeInsight.lookup.LookupElement 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testLocalTarget() {
BuildFile file =
createBuildFile(
new WorkspacePath("java/com/google/BUILD"),
"java_library(name = 'lib')",
"java_library(",
" name = 'test',",
" deps = [':']");
Editor editor = editorTest.openFileInEditor(file);
editorTest.setCaretPosition(editor, 3, " deps = [':".length());
LookupElement[] completionItems = testFixture.completeBasic();
assertThat(completionItems).hasLength(1);
assertThat(completionItems[0].toString()).isEqualTo("':lib'");
}
public static void elementToLookup(@Nonnull CompletionResultSet resultSet,
@Nonnull IElementType elementType,
@Nullable NotNullPairFunction<LookupElementBuilder, IElementType, LookupElement> decorator,
@Nullable Condition<IElementType> condition)
{
if(condition != null && !condition.value(elementType))
{
return;
}
String keyword = ourCache.get(elementType);
LookupElementBuilder builder = LookupElementBuilder.create(elementType, keyword);
builder = builder.bold();
LookupElement item = builder;
if(decorator != null)
{
item = decorator.fun(builder, elementType);
}
item.putUserData(KEYWORD_ELEMENT_TYPE, elementType);
resultSet.addElement(item);
}
@Test
public void testNoCompletionInUnknownRule() {
ServiceHelper.unregisterLanguageExtensionPoint(
"com.intellij.completion.contributor",
BuiltInSymbolCompletionContributor.class,
getTestRootDisposable());
ServiceHelper.unregisterLanguageExtensionPoint(
"com.intellij.completion.contributor",
BuiltInFunctionCompletionContributor.class,
getTestRootDisposable());
setRuleAndAttributes("sh_binary", "name", "deps", "srcs", "data");
BuildFile file = createBuildFile(new WorkspacePath("BUILD"), "java_binary(");
Editor editor = editorTest.openFileInEditor(file.getVirtualFile());
editorTest.setCaretPosition(editor, 0, "java_binary(".length());
LookupElement[] completionItems = testFixture.completeBasic();
assertThat(completionItems).isEmpty();
}
@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);
}
}
/**
* 获取提示信息
*
* @return 返回提示集合
*/
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
final Collection<LookupElement> lookupElements = new ArrayList<>();
CollectProjectUniqueKeys ymlProjectProcessor = new CollectProjectUniqueKeys(getProject(), RouteValStubIndex.KEY);
//扫描文件获取key, 放入ymlProjectProcessor
FileBasedIndex.getInstance().processAllKeys(RouteValStubIndex.KEY, ymlProjectProcessor, getProject());
for (String key : ymlProjectProcessor.getResult()) { //从ymlProjectProcessor中获取结果
lookupElements.add(LookupElementBuilder.create(key).withIcon(LaravelIcons.ROUTE));
}
return lookupElements;
}
@Override
public void handleInsert(
final InsertionContext insertionContext, final LookupElement lookupElement) {
if (shouldUseQuotes(lookupElement)) {
final boolean hasDoubleQuotes =
hasStartingOrEndingQuoteOfType(insertionContext, lookupElement, DOUBLE_QUOTE);
if (hasDoubleQuotes) {
handleEndingQuote(insertionContext, DOUBLE_QUOTE);
handleStartingQuote(insertionContext, lookupElement, DOUBLE_QUOTE);
} else {
handleEndingQuote(insertionContext, SINGLE_QUOTE);
handleStartingQuote(insertionContext, lookupElement, SINGLE_QUOTE);
}
}
}
@Nonnull
public static CSharpTypeLikeLookupElement create(LookupElement delegate, DotNetGenericExtractor extractor, PsiElement expression)
{
CSharpNewExpression newExpression = null;
PsiElement parent = expression == null ? null : expression.getParent();
if(parent instanceof CSharpUserType)
{
PsiElement typeParent = parent.getParent();
if(typeParent instanceof CSharpNewExpression)
{
newExpression = (CSharpNewExpression) typeParent;
}
}
return new CSharpTypeLikeLookupElement(delegate, extractor, newExpression != null);
}
private static boolean completeTillTypedCharOccurrence(char charTyped, LookupImpl lookup, LookupElement item) {
PrefixMatcher matcher = lookup.itemMatcher(item);
final String oldPrefix = matcher.getPrefix() + lookup.getAdditionalPrefix();
PrefixMatcher expanded = matcher.cloneWithPrefix(oldPrefix + charTyped);
if (expanded.prefixMatches(item)) {
for (String s : item.getAllLookupStrings()) {
if (matcher.prefixMatches(s)) {
int i = -1;
while (true) {
i = s.indexOf(charTyped, i + 1);
if (i < 0) break;
final String newPrefix = s.substring(0, i + 1);
if (expanded.prefixMatches(newPrefix)) {
lookup.replacePrefix(oldPrefix, newPrefix);
return true;
}
}
}
}
}
return false;
}
@RequiredReadAction
@Override
public void processCompletion(@Nonnull CompletionParameters parameters,
@Nonnull ProcessingContext context,
@Nonnull final Consumer<LookupElement> result,
@Nonnull CSharpTypeDeclaration typeDeclaration)
{
Collection<DotNetModifierListOwner> overrideItems = getItemsImpl(typeDeclaration);
for(DotNetModifierListOwner overrideItem : overrideItems)
{
LookupElementBuilder builder = buildLookupItem(typeDeclaration, overrideItem, false);
result.consume(builder);
if(!typeDeclaration.isInterface() && overrideItem.hasModifier(CSharpModifier.INTERFACE_ABSTRACT))
{
builder = buildLookupItem(typeDeclaration, overrideItem, true);
result.consume(builder);
}
}
}
@Test
public void testCustomRuleCompletion() {
MockBuildLanguageSpecProvider specProvider = new MockBuildLanguageSpecProvider();
setBuildLanguageSpecRules(specProvider, "java_library");
registerApplicationService(BuildLanguageSpecProvider.class, specProvider);
BuildFile file =
createBuildFile(
new WorkspacePath("java/com/google/BUILD"),
"custom_rule(name = 'lib')",
"java_library(",
" name = 'test',",
" deps = [':']");
Editor editor = editorTest.openFileInEditor(file);
editorTest.setCaretPosition(editor, 3, " deps = [':".length());
LookupElement[] completionItems = testFixture.completeBasic();
assertThat(completionItems).hasLength(1);
assertThat(completionItems[0].toString()).isEqualTo("':lib'");
}
public void addSparedChars(Lookup lookup, LookupElement item, InsertionContext context) {
String textInserted;
if (context.getOffsetMap().containsOffset(CompletionInitializationContext.START_OFFSET) &&
context.getOffsetMap().containsOffset(InsertionContext.TAIL_OFFSET) &&
context.getTailOffset() >= context.getStartOffset()) {
textInserted = context.getDocument().getImmutableCharSequence().subSequence(context.getStartOffset(), context.getTailOffset()).toString();
}
else {
textInserted = item.getLookupString();
}
String withoutSpaces = StringUtil.replace(textInserted, new String[]{" ", "\t", "\n"}, new String[]{"", "", ""});
int spared = withoutSpaces.length() - lookup.itemPattern(item).length();
char completionChar = context.getCompletionChar();
if (!LookupEvent.isSpecialCompletionChar(completionChar) && withoutSpaces.contains(String.valueOf(completionChar))) {
spared--;
}
if (spared > 0) {
mySpared += spared;
}
}
@NotNull
public Collection<LookupElement> getLookupElements(@NotNull PhpToolboxCompletionContributorParameter parameter) {
PhpIndex instance = PhpIndex.getInstance(parameter.getProject());
Collection<LookupElement> lookupElements = new ArrayList<>();
for (String className : getClasses(parameter)) {
// strip double backslash
className = className.replaceAll("\\\\+", "\\\\");
for (PhpClass phpClass : getPhpClassesForLookup(instance, className)) {
lookupElements.add(
LookupElementBuilder.create(phpClass.getPresentableFQN()).withIcon(phpClass.getIcon())
);
}
}
return lookupElements;
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
Collection<LookupElement> elements = new ArrayList<>();
for(Method method: phpClass.getMethods()) {
if(method.getAccess().isPublic()) {
String name = method.getName();
if(!"getSubscribedEvents".equals(name) && !name.startsWith("__") && !name.startsWith("set")) {
elements.add(LookupElementBuilder.create(name).withIcon(method.getIcon()));
}
}
}
return elements;
}
@NotNull
private static LookupElement createParameterArrayTypeLookupElement(@NotNull ParameterArrayType type) {
LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(type.getKey())
.withIcon(PhpIcons.FIELD);
String types = StringUtils.join(type.getValues(), '|');
if (type.isOptional()) {
types = "(optional) " + types;
}
return lookupElementBuilder.withTypeText(types);
}
private List<LookupElement> getInitialNoStatElements(Iterable<LookupElement> source, ProcessingContext context) {
List<LookupElement> initialList = new ArrayList<>();
for (LookupElement next : myNext.classify(source, context)) {
if (myNoStats.contains(next)) {
initialList.add(next);
}
else {
break;
}
}
return initialList;
}
@Override
public boolean prefixMatches(@NotNull LookupElement element) {
if (element instanceof TabNineLookupElement) {
return true;
} else if (element instanceof LookupElementDecorator) {
LookupElementDecorator decorator = (LookupElementDecorator) element;
return prefixMatches(decorator.getDelegate());
}
return super.prefixMatches(element);
}
@Override
public boolean isStartMatch(LookupElement element) {
if (element instanceof TabNineLookupElement) {
return true;
}
return super.isStartMatch(element);
}
public static List<String> getLookupElementWeights(LookupImpl lookup, boolean hideSingleValued) {
final Map<LookupElement, List<Pair<String, Object>>> weights = lookup.getRelevanceObjects(lookup.getItems(), hideSingleValued);
return ContainerUtil.map(weights.entrySet(), new Function<Map.Entry<LookupElement, List<Pair<String, Object>>>, String>() {
@Override
public String fun(Map.Entry<LookupElement, List<Pair<String, Object>>> entry) {
return entry.getKey().getLookupString() + "\t" + StringUtil.join(entry.getValue(), new Function<Pair<String, Object>, String>() {
@Override
public String fun(Pair<String, Object> pair) {
return pair.first + "=" + pair.second;
}
}, ", ");
}
});
}
/** @return true if a LookupItem was inserted. */
public boolean completeIfUnique() {
LookupElement[] completionItems = testFixture.completeBasic();
if (completionItems == null) {
return true;
}
if (completionItems.length != 1) {
return false;
}
testFixture.getLookup().setCurrentItem(completionItems[0]);
testFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);
return true;
}
@Override
public AutoCompletionDecision handleAutoCompletionPossibility(AutoCompletionContext context) {
// auto-insert the obvious only case; else show other cases.
final LookupElement[] items = context.getItems();
if (items.length == 1) {
return AutoCompletionDecision.insertItem(items[0]);
}
return AutoCompletionDecision.SHOW_LOOKUP;
}
/**
* Collect block in virtual files via index
*/
@NotNull
public static Collection<LookupElement> getBlockLookupElements(@NotNull Project project, @NotNull Collection<VirtualFile> files) {
Collection<LookupElement> lookupElements = new ArrayList<>();
Map<VirtualFile, Collection<String>> templateNames = new HashMap<>();
for (Map.Entry<VirtualFile, Collection<String>> block : getBlockNamesForFiles(project, files).entrySet()) {
// performance optimize to not resolve too many elements
VirtualFile virtualFile = block.getKey();
if(!templateNames.containsKey(virtualFile)) {
templateNames.put(virtualFile, TwigUtil.getTemplateNamesForFile(project, virtualFile));
}
for (String blockName : block.getValue()) {
LookupElementBuilder lookupElementBuilder = LookupElementBuilder
.create(blockName)
.withIcon(TwigIcons.TwigFileIcon);
Collection<String> names = templateNames.getOrDefault(virtualFile, Collections.emptyList());
if(names.size() > 0) {
lookupElementBuilder = lookupElementBuilder.withTypeText(names.iterator().next(), true);
}
lookupElements.add(lookupElementBuilder);
}
}
return lookupElements;
}
@RequiredReadAction
@Nonnull
@Override
public Object[] getVariants()
{
ResolveKind kind = kind();
final List<LookupElement> values = new SmartList<>();
switch(kind)
{
case ATTRIBUTE:
for(ShaderMaterialAttribute attribute : ShaderMaterialAttribute.values())
{
LookupElementBuilder builder = LookupElementBuilder.create(attribute.name());
builder = builder.withIcon((Image) AllIcons.Nodes.Class);
builder = builder.withTypeText(attribute.getType(), true);
values.add(builder);
}
break;
case PROPERTY:
PsiFile containingFile = getContainingFile();
if(containingFile instanceof ShaderLabFile)
{
consumeProperties((ShaderLabFile) containingFile, values::add);
}
break;
}
return values.toArray();
}
@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);
}
}
private List<String> currentLookupStrings() {
LookupImpl lookup = completionTester.getLookup();
if (lookup == null) {
return ImmutableList.of();
}
return lookup
.getItems()
.stream()
.map(LookupElement::getLookupString)
.collect(Collectors.toList());
}
@Override
public List<String> getCompletionVariants(final String... filesBefore) {
assertInitialized();
configureByFiles(filesBefore);
final LookupElement[] items = complete(CompletionType.BASIC);
Assert.assertNotNull("No lookup was shown, probably there was only one lookup element that was inserted automatically", items);
return getLookupElementStrings();
}
@NotNull
public static Collection<LookupElement> getObjectRepositoryLookupElements(@NotNull Project project) {
PhpIndex index = PhpIndex.getInstance(project);
Collection<PhpClass> collection = index.getAllSubclasses("\\Doctrine\\Common\\Persistence\\ObjectRepository");
collection.addAll(index.getAllSubclasses("\\Doctrine\\Persistence\\ObjectRepository"));
return new ArrayList<>(DoctrineRepositoryLookupElement.create(collection));
}
@Nonnull
@Override
@RequiredReadAction
public Comparable weigh(@Nonnull LookupElement element)
{
final String name = getName(element);
if(name != null && getNameEndMatchingDegree(name, myExpectedTypes) != 0)
{
return NameUtil.nameToWords(name).length - 1000;
}
return 0;
}
@NotNull
@Override
public Collection<LookupElement> getLookupElements(@NotNull PhpToolboxCompletionContributorParameter parameter) {
return PhpIndex.getInstance(parameter.getProject())
.getAllFunctionNames(PrefixMatcher.ALWAYS_TRUE).stream().map(
s -> LookupElementBuilder.create(s).withIcon(PhpIcons.FUNCTION)
)
.collect(Collectors.toCollection(HashSet::new));
}
@Nonnull
@Override
@RequiredReadAction
public Comparable weigh(@Nonnull LookupElement element)
{
Boolean data = element.getUserData(CSharpNoVariantsDelegator.NOT_IMPORTED);
return data != Boolean.TRUE;
}
@Nonnull
@Override
public Iterable<LookupElement> classify(@Nonnull Iterable<LookupElement> source, @Nonnull final ProcessingContext context) {
List<LookupElement> initialList = getInitialNoStatElements(source, context);
Iterable<LookupElement> rest = withoutInitial(source, initialList);
Collection<List<LookupElement>> byWeight = buildMapByWeight(rest).descendingMap().values();
return JBIterable.from(initialList).append(JBIterable.from(byWeight).flatten(group -> myNext.classify(group, context)));
}