下面列出了怎么用 com.intellij.codeInsight.completion.CompletionType 的API类实例代码及写法,或者点击链接到github查看源代码。
private void assertCompletion3rdInvocationContains(String configureByText, String... lookupStrings) {
myFixture.configureByText(YAMLFileType.YML, configureByText);
myFixture.complete(CompletionType.BASIC, 3);
if(lookupStrings.length == 0) {
fail("No lookup element given");
}
List<String> lookupElements = myFixture.getLookupElementStrings();
if(lookupElements == null || lookupElements.size() == 0) {
fail(String.format("failed that empty completion contains %s", Arrays.toString(lookupStrings)));
}
for (String s : lookupStrings) {
if(!lookupElements.contains(s)) {
fail(String.format("failed that completion contains %s in %s", s, lookupElements.toString()));
}
}
}
private void doTest(final int iterations) {
myFixture.configureByFile("functions_issue96.bash");
enableInspections();
long start = System.currentTimeMillis();
PlatformTestUtil.startPerformanceTest(getTestName(true), iterations * 2000, () -> {
for (int i = 0; i < iterations; i++) {
long innerStart = System.currentTimeMillis();
Editor editor = myFixture.getEditor();
editor.getCaretModel().moveToOffset(editor.getDocument().getTextLength());
myFixture.type("\n");
myFixture.type("echo \"hello world\"\n");
myFixture.type("pri");
myFixture.complete(CompletionType.BASIC);
System.out.println("Cycle duration: " + (System.currentTimeMillis() - innerStart));
}
}).usesAllCPUCores().attempts(1).assertTiming();
System.out.println("Complete duration: " + (System.currentTimeMillis() - start));
}
protected void doTestVariantsInner(CompletionType type, int count,
CheckType checkType,
String... variants) throws Throwable {
myFixture.complete(type, count);
List<String> stringList = myFixture.getLookupElementStrings();
assertNotNull("\nPossibly the single variant has been completed.\n" +
"File after:\n" +
myFixture.getFile().getText(),
stringList);
Collection<String> varList = new ArrayList<String>(Arrays.asList(variants));
if (checkType == CheckType.EQUALS) {
UsefulTestCase.assertSameElements(stringList, variants);
}
else if (checkType == CheckType.INCLUDES) {
varList.removeAll(stringList);
assertTrue("Missing variants: " + varList, varList.isEmpty());
}
else if (checkType == CheckType.EXCLUDES) {
varList.retainAll(stringList);
assertTrue("Unexpected variants: " + varList, varList.isEmpty());
}
}
@Override
public void scheduleAutoPopup(@Nonnull Editor editor, @Nonnull CompletionType completionType, @Nullable final Condition<? super PsiFile> condition) {
//if (ApplicationManager.getApplication().isUnitTestMode() && !TestModeFlags.is(CompletionAutoPopupHandler.ourTestingAutopopup)) {
// return;
//}
boolean alwaysAutoPopup = Boolean.TRUE.equals(editor.getUserData(ALWAYS_AUTO_POPUP));
if (!CodeInsightSettings.getInstance().AUTO_POPUP_COMPLETION_LOOKUP && !alwaysAutoPopup) {
return;
}
if (PowerSaveMode.isEnabled()) {
return;
}
if (!CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class, CompletionPhase.NoCompletion.getClass())) {
return;
}
final CompletionProgressIndicator currentCompletion = CompletionServiceImpl.getCurrentCompletionProgressIndicator();
if (currentCompletion != null) {
currentCompletion.closeAndFinish(true);
}
CompletionPhase.CommittingDocuments.scheduleAsyncCompletion(editor, completionType, condition, myProject, null);
}
@Override
public void testCompletionTyping(final String[] filesBefore, String toType, final String fileAfter) {
assertInitialized();
configureByFiles(filesBefore);
complete(CompletionType.BASIC);
for (int i = 0; i < toType.length(); i++) {
type(toType.charAt(i));
}
try {
checkResultByFile(fileAfter);
}
catch (RuntimeException e) {
System.out.println("LookupElementStrings = " + getLookupElementStrings());
throw e;
}
}
public AdditionalLanguagesCompletionContributor() {
extend(
CompletionType.BASIC,
psiElement()
.withLanguage(ProjectViewLanguage.INSTANCE)
.inside(
psiElement(ProjectViewPsiListSection.class)
.withText(
StandardPatterns.string()
.startsWith(AdditionalLanguagesSection.KEY.getName()))),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(
CompletionParameters parameters,
ProcessingContext context,
CompletionResultSet result) {
for (LanguageClass type :
availableAdditionalLanguages(parameters.getEditor().getProject())) {
result.addElement(LookupElementBuilder.create(type.getName()));
}
}
});
}
protected void doTestVariantsInner(String fileName) throws Throwable {
final VirtualFile virtualFile = myFixture.copyFileToProject(fileName);
final Scanner in = new Scanner(virtualFile.getInputStream());
final CompletionType type = CompletionType.valueOf(in.next());
final int count = in.nextInt();
final CheckType checkType = CheckType.valueOf(in.next());
final List<String> variants = new ArrayList<>();
while (in.hasNext()) {
final String variant = StringUtil.strip(in.next(), CharFilter.NOT_WHITESPACE_FILTER);
if (variant.length() > 0) {
variants.add(variant);
}
}
myFixture.complete(type, count);
checkCompletion(checkType, variants);
}
public void testCanCompleteRenderTypes() {
List<String> lookupElementStrings;
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $foo = ['renderType' => '<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete empty value", lookupElementStrings.contains("selectSingle"));
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $foo = ['renderType' => 's<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete partial value", lookupElementStrings.contains("selectSingle"));
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $GLOBALS['renderType'] = '<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete empty value", lookupElementStrings.contains("selectSingle"));
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $GLOBALS['renderType'] = 's<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete partial value", lookupElementStrings.contains("selectSingle"));
}
public void testCanCompleteTypes() {
List<String> lookupElementStrings;
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $foo = ['type' => '<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete empty value", lookupElementStrings.contains("text"));
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $foo = ['type' => 't<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete partial value", lookupElementStrings.contains("text"));
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $GLOBALS['type'] = '<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete empty value", lookupElementStrings.contains("text"));
myFixture.configureByText(PhpFileType.INSTANCE, "<?php $GLOBALS['type'] = 't<caret>'];");
myFixture.complete(CompletionType.BASIC);
lookupElementStrings = myFixture.getLookupElementStrings();
assertTrue("Can complete partial value", lookupElementStrings.contains("text"));
}
public BuiltInSymbolCompletionContributor() {
extend(
CompletionType.BASIC,
psiElement()
.withLanguage(BuildFileLanguage.INSTANCE)
.withParent(ReferenceExpression.class)
.andNot(psiComment())
.andNot(psiElement().afterLeaf(psiElement(BuildToken.fromKind(TokenKind.INT))))
.andNot(psiElement().inside(FuncallExpression.class))
.andNot(psiElement().afterLeaf(psiElement().withText(".")))
.andNot(psiElement().inFile(psiFile(BuildFileWithCustomCompletion.class))),
new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(
CompletionParameters parameters,
ProcessingContext context,
CompletionResultSet result) {
for (String symbol : BuiltInNamesProvider.GLOBALS) {
result.addElement(LookupElementBuilder.create(symbol));
}
}
});
}
protected void doTestVariantsInner(String fileName) throws Throwable {
final VirtualFile virtualFile = myFixture.copyFileToProject(fileName);
final Scanner in = new Scanner(virtualFile.getInputStream());
final CompletionType type = CompletionType.valueOf(in.next());
final int count = in.nextInt();
final CheckType checkType = CheckType.valueOf(in.next());
final List<String> variants = new ArrayList<String>();
while (in.hasNext()) {
final String variant = StringUtil.strip(in.next(), CharFilter.WHITESPACE_FILTER);
if (variant.length() > 0) {
variants.add(variant);
}
}
myFixture.complete(type, count);
checkCompletion(checkType, variants);
}
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);
}
}
}
});
}
public void testCompletion() {
myFixture.configureByFiles("CompleteTestData.java", "DefaultTestData.simple");
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertTrue(strings.containsAll(Arrays.asList("key with spaces", "language", "message", "tab", "website")));
assertEquals(5, strings.size());
}
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), () -> {
final CodeCompletionHandlerBase handler = new CodeCompletionHandlerBase(CompletionType.BASIC) {
@Override
protected void completionFinished(final CompletionProgressIndicator indicator, boolean hasModifiers) {
// find our lookup element
final LookupElement lookupElement = ContainerUtil.find(indicator.getLookup().getItems(), insert::match);
if(lookupElement == null) {
fail("No matching lookup element found");
}
// overwrite behavior and force completion + insertHandler
CommandProcessor.getInstance().executeCommand(indicator.getProject(), new Runnable() {
@Override
public void run() {
//indicator.setMergeCommand(); Currently method has package level access
indicator.getLookup().finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR, lookupElement);
}
}, "Autocompletion", null);
}
};
Editor editor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(getEditor(), getFile());
handler.invokeCompletion(getProject(), editor);
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
}, null, null);
}
public void testJavaInTheMiddleUnresolvedOptionsCompletion() {
myFixture.configureByText("JavaCaretInMiddleOptionsTestData.java", getJavaInTheMiddleUnresolvedOptionsTestData());
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertThat(strings, Matchers.not(Matchers.contains("timer:trigger?repeatCount=10")));
assertThat(strings, Matchers.contains("timer:trigger?repeatCount=10&exceptionHandler",
"timer:trigger?repeatCount=10&exchangePattern"));
assertTrue("There is less options", strings.size() == 2);
}
public void assertCompletion3rdInvocationNotContains(String filename, String configureByText, String... lookupStrings) {
myFixture.configureByText(filename, configureByText);
myFixture.complete(CompletionType.BASIC, 3);
List<String> lookupElementStrings = myFixture.getLookupElementStrings();
assertNotNull(lookupElementStrings);
assertFalse(lookupElementStrings.containsAll(Arrays.asList(lookupStrings)));
}
KeywordCompletionContributor(ORTypes types) {
extend(CompletionType.BASIC, psiElement(), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) {
PsiElement position = parameters.getPosition();
PsiElement originalPosition = parameters.getOriginalPosition();
PsiElement element = originalPosition == null ? position : originalPosition;
IElementType prevNodeType = CompletionUtils.getPrevNodeType(element);
PsiElement parent = element.getParent();
PsiElement grandParent = parent == null ? null : parent.getParent();
if (LOG.isTraceEnabled()) {
LOG.trace("»» Completion: position: " + position + ", " + position.getText());
LOG.trace(" original: " + originalPosition + ", " + (originalPosition == null ? null : originalPosition.getText()));
LOG.trace(" element: " + element);
LOG.trace(" parent: " + parent);
LOG.trace(" grand-parent: " + grandParent);
LOG.trace(" file: " + parameters.getOriginalFile());
}
if (originalPosition == null && parent instanceof FileBase) {
if (prevNodeType != types.DOT && prevNodeType != types.SHARPSHARP && prevNodeType != types.C_LOWER_SYMBOL) {
addFileKeywords(result);
}
}
}
});
}
public void testStepAutoCompletion() throws Exception {
myFixture.configureByFiles("SimpleSpec.spec", "SimpleSpec.txt");
Gauge.addModule(myFixture.getModule(), new GaugeService(mockProcess, mockGaugeConnection));
StepValue stepValue1 = new StepValue("This is a step", "This is a step");
StepValue stepValue2 = new StepValue("Hello", "Hello");
StepValue stepValue3 = new StepValue("The step", "The step");
when(mockGaugeConnection.fetchAllSteps()).thenReturn(asList(stepValue1, stepValue2, stepValue3));
myFixture.getEditor().getCaretModel().moveToOffset(49);
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertEquals(2, strings.size());
assertTrue(strings.containsAll(asList("This is a step", "The step")));
}
public void testShouldNotDisplayProperties() {
myFixture.configureByText("DialogHeader.re", "[@react.component] let make = () => { <div/> };");
myFixture.configureByText(RmlFileType.INSTANCE, "let _ = <<caret>Dialog");
myFixture.complete(CompletionType.BASIC, 1);
List<String> completions = myFixture.getLookupElementStrings();
assertEquals(1, completions.size());
assertEquals("DialogHeader", completions.get(0));
}
private void doTest(String... expectedSuggestions) {
final String fileName = getTestName(false).replace('$', '/') + ".java";
myFixture.copyFileToProject(getBasePath() + "/lombok.config", "lombok.config");
myFixture.configureByFile(getBasePath() + "/" + fileName);
myFixture.complete(CompletionType.BASIC, 1);
List<String> autoSuggestions = myFixture.getLookupElementStrings();
assertNotNull(autoSuggestions);
assertThat("Autocomplete doesn't contain right suggestions", autoSuggestions, CoreMatchers.hasItems(expectedSuggestions));
}
public void testEndOfFile() {
configureCode("A.re", "type x;");
configureCode("B.re", "A.<caret>");
myFixture.complete(CompletionType.BASIC, 1);
List<String> elements = myFixture.getLookupElementStrings();
assertSameElements(elements, "x");
}
protected void doTestInclude(String... extraFiles) throws Throwable {
final List<String> files = new ArrayList<String>();
files.add(getTestName(false) + ".hx");
Collections.addAll(files, extraFiles);
myFixture.configureByFiles(files.toArray(new String[0]));
final VirtualFile virtualFile = myFixture.copyFileToProject(getTestName(false) + ".txt");
String text = new String(virtualFile.contentsToByteArray());
List<String> includeLines = new ArrayList<String>();
List<String> excludeLines = new ArrayList<String>();
boolean include = true;
for (String line : text.split("\n")) {
line = line.trim();
if (line.equals(":INCLUDE")) {
include = true;
} else if (line.equals(":EXCLUDE")) {
include = false;
} else if (line.length() == 0) {
} else {
if (include) {
includeLines.add(line);
} else {
excludeLines.add(line);
}
}
//System.out.println(line);
}
//System.out.println(text);
myFixture.complete(CompletionType.BASIC, 1);
checkCompletion(CheckType.INCLUDES, includeLines);
checkCompletion(CheckType.EXCLUDES, excludeLines);
}
public void testSingleAlias() {
// like ReasonReact.Router
configureCode("ReasonReactRouter.rei", "type watcherID;");
configureCode("ReasonReact.rei", "module Router = ReasonReactRouter;");
configureCode("Dummy.re", "ReasonReact.Router.<caret>");
myFixture.complete(CompletionType.BASIC, 1);
List<String> elements = myFixture.getLookupElementStrings();
assertSize(1, elements);
assertEquals("watcherID", elements.get(0));
}
public void testRml_AliasInFile() {
// like ReasonReact.Router
configureCode("View.re", "module Detail = { let alias = \"a\"; };");
configureCode("Dummy.re", "module V = View.Detail; V.<caret>");
myFixture.complete(CompletionType.BASIC, 1);
List<String> elements = myFixture.getLookupElementStrings();
assertSize(1, elements);
assertEquals("alias", elements.get(0));
}
public void testRml_Uncurried() {
configureCode("A.re", "let x = 1;");
configureCode("B.re", "send(. <caret>)"); // should use free completion
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertSameElements(strings, "A");
}
public void testEnum() {
myFixture.configureByFiles("CompleteJavaEndpointSyntaxEnumTestData.java");
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertEquals(5, strings.size());
assertThat(strings, Matchers.contains("jms:", "jms:queue", "jms:topic", "jms:temp-queue", "jms:temp-topic"));
}
/**
* Test if code completion works with inside the bean dsl with an empty string.
*/
public void testJavaBeanTestDataCompletionWithEmptyBeanRef() {
myFixture.configureByFiles("CompleteJavaBeanRoute10TestData.java", "CompleteJavaSpringRepositoryBeanTestData.java");
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertEquals("There is many options", 2, strings.size());
}
public void testOcl_functorWithReturnType() {
configureCode("A.ml", "module type Intf = sig val x : bool end\n module MakeOcl(I:Intf) : Intf = struct let y = 1 end");
configureCode("B.ml", "open A\n module Instance = MakeOcl(struct let x = true end)");
configureCode("C.ml", "open B let _ = Instance.<caret>");
myFixture.complete(CompletionType.BASIC, 1);
List<String> elements = myFixture.getLookupElementStrings();
assertSameElements(elements, "x");
}
public void testJavaBeanWithClassHierarchy() {
myFixture.configureByFiles("CompleteJavaBeanRouteTestData.java", "CompleteJavaBeanTestData.java", "CompleteJavaBeanSuperClassTestData.java");
myFixture.complete(CompletionType.BASIC, 1);
List<String> strings = myFixture.getLookupElementStrings();
assertThat(strings, Matchers.not(Matchers.contains("thisIsVeryPrivate")));
assertThat(strings, Matchers.hasItems("letsDoThis", "anotherBeanMethod", "mySuperAbstractMethod", "mySuperMethod", "myOverLoadedBean", "myOverLoadedBean"));
assertEquals("There is many options", 6, strings.size());
}
@Test
public void testCompleteClassName() {
workspace.createPsiFile(
new WorkspacePath("java/com/google/bin/Main.java"),
"package com.google.bin;",
"public class Main {",
" public void main() {}",
"}");
BuildFile file =
createBuildFile(
new WorkspacePath("java/com/google/BUILD"),
"java_binary(",
" name = 'binary',",
" main_class = 'com.google.bin.M',",
")");
Editor editor = editorTest.openFileInEditor(file.getVirtualFile());
editorTest.setCaretPosition(editor, 2, " main_class = 'com.google.bin.M".length());
LookupElement[] completionItems = testFixture.complete(CompletionType.CLASS_NAME);
assertThat(completionItems).isNull();
assertFileContents(
file,
"java_binary(",
" name = 'binary',",
" main_class = 'com.google.bin.Main',",
")");
}