com.intellij.codeInsight.lookup.Lookup Java Examples

The following examples show how to use com.intellij.codeInsight.lookup.Lookup. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LiveTemplateCharFilter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Result acceptChar(char c, int prefixLength, Lookup lookup) {
  LookupElement item = lookup.getCurrentItem();
  if (item instanceof LiveTemplateLookupElement && lookup.isCompletion()) {
    if (Character.isJavaIdentifierPart(c)) return Result.ADD_TO_PREFIX;

    if (c == ((LiveTemplateLookupElement)item).getTemplateShortcut()) {
      return Result.SELECT_ITEM_AND_FINISH_LOOKUP;
    }
    return Result.HIDE_LOOKUP;
  }
  if (item instanceof TemplateExpressionLookupElement) {
    if (Character.isJavaIdentifierPart(c)) return Result.ADD_TO_PREFIX;
    if (CodeInsightSettings.getInstance().SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS) {
      return null;
    }
    return Result.HIDE_LOOKUP;
  }

  return null;
}
 
Example #2
Source File: BaseCodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void update(AnActionEvent event) {
  Presentation presentation = event.getPresentation();
  DataContext dataContext = event.getDataContext();
  Project project = dataContext.getData(CommonDataKeys.PROJECT);
  if (project == null){
    presentation.setEnabled(false);
    return;
  }

  final Lookup activeLookup = LookupManager.getInstance(project).getActiveLookup();
  if (activeLookup != null){
    presentation.setEnabled(isValidForLookup());
  }
  else {
    super.update(event);
  }
}
 
Example #3
Source File: CompletionCharFilter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Result acceptChar(char c, final int prefixLength, final Lookup lookup) {
  if (!lookup.isCompletion()) return null;

  if (Character.isJavaIdentifierPart(c)) return Result.ADD_TO_PREFIX;
  switch (c) {
    case '.':
    case ',':
    case ';':
    case '=':
    case ' ':
    case ':':
    case '(':
      return Result.SELECT_ITEM_AND_FINISH_LOOKUP;

    default:
      return Result.HIDE_LOOKUP;
  }
}
 
Example #4
Source File: StatisticsUpdate.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example #5
Source File: DocumentationManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public PsiElement getElementFromLookup(Editor editor, @Nullable PsiFile file) {
  Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup();

  if (activeLookup != null) {
    LookupElement item = activeLookup.getCurrentItem();
    if (item != null) {
      int offset = editor.getCaretModel().getOffset();
      if (offset > 0 && offset == editor.getDocument().getTextLength()) offset--;
      PsiReference ref = TargetElementUtil.findReference(editor, offset);
      PsiElement contextElement = file == null ? null : ObjectUtils.coalesce(file.findElementAt(offset), file);
      PsiElement targetElement = ref != null ? ref.getElement() : contextElement;
      if (targetElement != null) {
        PsiUtilCore.ensureValid(targetElement);
      }

      DocumentationProvider documentationProvider = getProviderFromElement(file);
      PsiManager psiManager = PsiManager.getInstance(myProject);
      PsiElement fromProvider = targetElement == null ? null : documentationProvider.getDocumentationElementForLookupItem(psiManager, item.getObject(), targetElement);
      return fromProvider != null ? fromProvider : CompletionUtil.getTargetElement(item);
    }
  }
  return null;
}
 
Example #6
Source File: CamelSmartCompletionEndpointOptions.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * We need special logic to determine when it should insert "=" at the end of the options
 */
@NotNull
private static LookupElementBuilder addInsertHandler(final Editor editor, final LookupElementBuilder builder,
                                                     final String suffix) {
    return builder.withInsertHandler((context, item) -> {
        // enforce using replace select char as we want to replace any existing option
        if (context.getCompletionChar() == Lookup.NORMAL_SELECT_CHAR) {
            int endSelectOffBy = 0;
            if (context.getFile() instanceof PropertiesFileImpl) {
                //if it's a property file the PsiElement does not start and end with an quot
                endSelectOffBy = 1;
            }
            final char text = context
                    .getDocument()
                    .getCharsSequence()
                    .charAt(context.getSelectionEndOffset() - endSelectOffBy);
            if (text != '=') {
                EditorModificationUtil.insertStringAtCaret(editor, "=");
            }
        } else if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
            // we still want to keep the suffix because they are other options
            String value = suffix;
            final int pos = value.indexOf("&");
            if (pos > -1) {
                // strip out first part of suffix until next option
                value = value.substring(pos);
            }
            EditorModificationUtil.insertStringAtCaret(editor, "=" + value);
            // and move cursor back again
            final int offset = -1 * value.length();
            EditorModificationUtil.moveCaretRelatively(editor, offset);
        }

    });
}
 
Example #7
Source File: IdentifierCharFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Result acceptChar(char c, final int prefixLength, final Lookup lookup) {
  if (lookup.isCompletion()) return null;

  if (Character.isJavaIdentifierPart(c)) return Result.ADD_TO_PREFIX;
  return Result.SELECT_ITEM_AND_FINISH_LOOKUP;
}
 
Example #8
Source File: FileReferenceCharFilter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Result acceptChar(char c, int prefixLength, Lookup lookup) {
  final LookupElement item = lookup.getCurrentItem();
  if ('.' == c && item != null && item.getObject() instanceof PsiFileSystemItem) {
    PsiReference referenceAtCaret = lookup.getPsiFile().findReferenceAt(lookup.getLookupStart());
    if (referenceAtCaret != null && FileReference.findFileReference(referenceAtCaret) != null) {
      return Result.ADD_TO_PREFIX;
    }
  }

  return null;
}
 
Example #9
Source File: ConsoleExecuteAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public final void update(@Nonnull AnActionEvent e) {
  EditorEx editor = myConsoleView.getConsoleEditor();
  boolean enabled = !editor.isRendererMode() && isEnabled() &&
                    (myExecuteActionHandler.isEmptyCommandExecutionAllowed() || !StringUtil.isEmptyOrSpaces(editor.getDocument().getCharsSequence()));
  if (enabled) {
    Lookup lookup = LookupManager.getActiveLookup(editor);
    // we should check getCurrentItem() also - fast typing could produce outdated lookup, such lookup reports isCompletion() true
    enabled = lookup == null || !lookup.isCompletion() || lookup.getCurrentItem() == null ||
              (lookup instanceof LookupImpl && ((LookupImpl)lookup).getFocusDegree() == LookupImpl.FocusDegree.UNFOCUSED);
  }

  e.getPresentation().setEnabled(enabled);
}
 
Example #10
Source File: LookupActionsStep.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public PopupStep onChosen(LookupElementAction selectedValue, boolean finalChoice) {
  final LookupElementAction.Result result = selectedValue.performLookupAction();
  if (result == LookupElementAction.Result.HIDE_LOOKUP) {
    myLookup.hideLookup(true);
  } else if (result == LookupElementAction.Result.REFRESH_ITEM) {
    myLookup.updateLookupWidth(myLookupElement);
    myLookup.requestResize();
    myLookup.refreshUi(false, true);
  } else if (result instanceof LookupElementAction.Result.ChooseItem) {
    myLookup.setCurrentItem(((LookupElementAction.Result.ChooseItem)result).item);
    CommandProcessor.getInstance().executeCommand(myLookup.getProject(), () -> myLookup.finishLookup(Lookup.AUTO_INSERT_SELECT_CHAR), null, null);
  }
  return FINAL_CHOICE;
}
 
Example #11
Source File: ChooseItemAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEnabled(Editor editor, DataContext dataContext) {
  LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
  if (lookup == null) return false;
  if (!lookup.isAvailableToUser()) return false;
  if (focusedOnly && lookup.getFocusDegree() == LookupImpl.FocusDegree.UNFOCUSED) return false;
  if (finishingChar == Lookup.REPLACE_SELECT_CHAR) {
    return !lookup.getItems().isEmpty();
  }

  return true;
}
 
Example #12
Source File: ChooseItemAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull final Editor editor, final DataContext dataContext) {
  final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
  if (lookup == null) {
    throw new AssertionError("The last lookup disposed at: " + LookupImpl.getLastLookupDisposeTrace() + "\n-----------------------\n");
  }

  if ((finishingChar == Lookup.NORMAL_SELECT_CHAR || finishingChar == Lookup.REPLACE_SELECT_CHAR) &&
      hasTemplatePrefix(lookup, finishingChar)) {
    lookup.hideLookup(true);

    ExpandLiveTemplateCustomAction.createExpandTemplateHandler(finishingChar).execute(editor, null, dataContext);

    return;
  }

  if (finishingChar == Lookup.NORMAL_SELECT_CHAR) {
    if (!lookup.isFocused()) {
      FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CONTROL_ENTER);
    }
  } else if (finishingChar == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_FINISH_BY_SMART_ENTER);
  } else if (finishingChar == Lookup.REPLACE_SELECT_CHAR) {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_REPLACE);
  } else if (finishingChar == '.')  {
    FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_FINISH_BY_CONTROL_DOT);
  }

  lookup.finishLookup(finishingChar);
}
 
Example #13
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void adjustPositionForLookup(@Nonnull Lookup lookup) {
  if (myEditor.isDisposed()) {
    Disposer.dispose(this);
    return;
  }

  if (!myHint.isVisible()) {
    if (!myKeepOnHintHidden) Disposer.dispose(this);
    return;
  }

  IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
  if (tooltip != null) {
    JRootPane root = myEditor.getComponent().getRootPane();
    if (root != null) {
      Point p = tooltip.getShowingPoint().getPoint(root.getLayeredPane());
      if (lookup.isPositionedAboveCaret()) {
        if (Position.above == tooltip.getPreferredPosition()) {
          myHint.pack();
          myHint.updatePosition(Position.below);
          myHint.updateLocation(p.x, p.y + tooltip.getPositionChangeY());
        }
      }
      else {
        if (Position.below == tooltip.getPreferredPosition()) {
          myHint.pack();
          myHint.updatePosition(Position.above);
          myHint.updateLocation(p.x, p.y - tooltip.getPositionChangeY());
        }
      }
    }
  }
}
 
Example #14
Source File: TargetElementUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiElement getTargetElementFromLookup(Project project) {
  Lookup activeLookup = LookupManager.getInstance(project).getActiveLookup();
  if (activeLookup != null) {
    LookupElement item = activeLookup.getCurrentItem();
    final PsiElement psi = item == null ? null : CompletionUtil.getTargetElement(item);
    if (psi != null && psi.isValid()) {
      return psi;
    }
  }
  return null;
}
 
Example #15
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
@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);
}
 
Example #16
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-generics-plugin with MIT License 5 votes vote down vote up
@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);
}
 
Example #17
Source File: LiveTemplateTest.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
public void expandTemplate(String lookupText, String... values) {
    new ListTemplatesAction().actionPerformedImpl(myFixture.getProject(), myFixture.getEditor());

    LookupElement[] elements = myFixture.getLookupElements();
    assertNotNull(elements);
    for (LookupElement element : elements) {
        if (lookupText.equals(element.getLookupString())) {
            myFixture.getLookup().setCurrentItem(element);
            myFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);
            substituteValues(values);
            myFixture.checkResultByFile(getTestName() + "_after.xq");
            return;
        }
    }
}
 
Example #18
Source File: LiveTemplateTest.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
private void substituteValues(String[] values) {
    int counter = 0;
    for (String value : values) {
        myFixture.type(value);
        boolean notLast = ++counter != values.length;
        if (notLast) {
            myFixture.type(Lookup.REPLACE_SELECT_CHAR);
        }
    }
}
 
Example #19
Source File: CSharpCompletionCharFilter.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public Result acceptChar(char c, final int prefixLength, final Lookup lookup)
{
	if(!lookup.isCompletion())
	{
		return null;
	}

	PsiFile psiFile = lookup.getPsiFile();
	if(psiFile.getFileType() != CSharpFileType.INSTANCE)
	{
		return null;
	}

	if(Character.isJavaIdentifierPart(c))
	{
		return Result.ADD_TO_PREFIX;
	}

	switch(c)
	{
		case '@':
			return Result.ADD_TO_PREFIX;
		case '{':
		case '<':
			return Result.SELECT_ITEM_AND_FINISH_LOOKUP;
		default:
			return null;
	}
}
 
Example #20
Source File: ProjectViewCompletionTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Test
public void testWhitespaceDividerInsertedAfterScalarSection() {
  setInput("impo<caret>");

  LookupElement[] completionItems = testFixture.completeBasic();
  assertThat(completionItems[0].getLookupString()).isEqualTo("import");

  testFixture.getLookup().setCurrentItem(completionItems[0]);
  testFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);

  assertResult("import <caret>");
}
 
Example #21
Source File: EditorTestHelper.java    From intellij with Apache License 2.0 5 votes vote down vote up
/** @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;
}
 
Example #22
Source File: ChooseItemAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public Replacing() {
  super(new Handler(false, Lookup.REPLACE_SELECT_CHAR));
}
 
Example #23
Source File: ChooseItemAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public FocusedOnly() {
  super(new Handler(true, Lookup.NORMAL_SELECT_CHAR));
}
 
Example #24
Source File: UserFunctionCompletionTest.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public void testCompletionCaretAtParentheses() throws Exception {
    myFixture.configureByText("test.cyp", "RETURN secondTestFuncti<caret>");
    myFixture.completeBasic();
    myFixture.finishLookup(Lookup.REPLACE_SELECT_CHAR);
    myFixture.checkResult("RETURN com.neueda.jetbrains.plugin.graphdb.test.database.neo4j_4_0.secondTestFunction(<caret>)");
}
 
Example #25
Source File: ChooseItemAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public CompletingStatement() {
  super(new Handler(true, Lookup.COMPLETE_STATEMENT_SELECT_CHAR));
}
 
Example #26
Source File: LiveTemplateLookupActionProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) {
  if (element instanceof LiveTemplateLookupElementImpl) {
    final TemplateImpl template = ((LiveTemplateLookupElementImpl)element).getTemplate();
    final TemplateImpl templateFromSettings = TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName());

    if (templateFromSettings != null) {
      consumer.consume(new LookupElementAction(IconUtil.getEditIcon(), "Edit live template settings") {
        @Override
        public Result performLookupAction() {
          final Project project = lookup.getEditor().getProject();
          assert project != null;
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              if (project.isDisposed()) return;

              final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
              ShowSettingsUtil.getInstance().editConfigurable(project, configurable, new Runnable() {
                @Override
                public void run() {
                  configurable.getTemplateListPanel().editTemplate(template);
                }
              });
            }
          });
          return Result.HIDE_LOOKUP;
        }
      });


      consumer.consume(new LookupElementAction(AllIcons.Actions.Delete, String.format("Disable '%s' template", template.getKey())) {
        @Override
        public Result performLookupAction() {
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              templateFromSettings.setDeactivated(true);
            }
          });
          return Result.HIDE_LOOKUP;
        }
      });
    }
  }
}
 
Example #27
Source File: UserFunctionCompletionTest.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public void testCompletionCaretAfterParentheses() throws Exception {
    myFixture.configureByText("test.cyp", "RETURN firstTestFuncti<caret>");
    myFixture.completeBasic();
    myFixture.finishLookup(Lookup.REPLACE_SELECT_CHAR);
    myFixture.checkResult("RETURN com.neueda.jetbrains.plugin.graphdb.test.database.neo4j_4_0.firstTestFunction()<caret>");
}
 
Example #28
Source File: PostfixTemplateLookupActionProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) {
  if (element instanceof PostfixTemplateLookupElement) {
    final PostfixTemplateLookupElement templateLookupElement = (PostfixTemplateLookupElement)element;
    final PostfixTemplate template = templateLookupElement.getPostfixTemplate();

    consumer.consume(new LookupElementAction(IconUtil.getEditIcon(), "Edit postfix templates settings") {
      @Override
      public Result performLookupAction() {
        final Project project = lookup.getEditor().getProject();
        assert project != null;
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            if (project.isDisposed()) return;

            PostfixTemplatesConfigurable configurable = new PostfixTemplatesConfigurable();
            PostfixTemplatesChildConfigurable childConfigurable = configurable.findConfigurable(templateLookupElement.getProvider());
            if(childConfigurable == null) {
              return;
            }
            ShowSettingsUtil.getInstance().editConfigurable(project, childConfigurable, new Runnable() {
              @Override
              public void run() {
                childConfigurable.focusTemplate(template);
              }
            });
          }
        });
        return Result.HIDE_LOOKUP;
      }
    });

    final PostfixTemplatesSettings settings = PostfixTemplatesSettings.getInstance();
    if (settings != null && settings.isTemplateEnabled(template, templateLookupElement.getProvider())) {
      consumer.consume(new LookupElementAction(AllIcons.Actions.Delete, String.format("Disable '%s' template", template.getKey())) {
        @Override
        public Result performLookupAction() {
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              settings.disableTemplate(template, templateLookupElement.getProvider());
            }
          });
          return Result.HIDE_LOOKUP;
        }
      });
    }
  }
}
 
Example #29
Source File: TargetFileCompletionIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
private void completionTest(String stringToComplete, String[] expected) {
  String fullStringToComplete = "\n\n" + stringToComplete;
  // should be only tested with pants versions above 1.24.0
  if (PantsUtil.isCompatibleProjectPantsVersion(myProjectRoot.getPath(), "1.24.0")) {
    invalidateCaches();

    String helloProjectPath = "examples/src/scala/org/pantsbuild/example/hello/";
    doImport(helloProjectPath);
    VirtualFile vfile = myProjectRoot.findFileByRelativePath(helloProjectPath + "BUILD");
    assertNotNull(vfile);

    Document doc = FileDocumentManager.getInstance().getDocument(vfile);

    String originalContent = doc.getText();

    int offset = doc.getText().length() + fullStringToComplete.indexOf(CURSOR);

    append(doc, fullStringToComplete.replace(CURSOR, ""));
    assertNotNull(doc.getText());

    Editor editor = EditorFactory.getInstance().createEditor(doc, myProject);
    editor.getCaretModel().moveToOffset(offset);

    new CodeCompletionHandlerBase(CompletionType.BASIC, false, false, true).invokeCompletion(myProject, editor);

    List<LookupElement> elements =
      Optional.ofNullable(
        LookupManager
          .getActiveLookup(editor)
      ).map(Lookup::getItems).orElse(new LinkedList<>());

    List<String> actual = elements.stream()
      .map(LookupElement::getLookupString)
      .collect(Collectors.toList());

    WriteAction.runAndWait(() -> doc.setText(originalContent));

    assertSameElements(actual, expected);
    EditorFactory.getInstance().releaseEditor(editor);
  }
}
 
Example #30
Source File: BuiltInFunctionsCompletionTest.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 4 votes vote down vote up
public void testCompletionLookupChar() throws Exception {
    myFixture.configureByText("test.cyp", "RETURN s<caret>");
    myFixture.completeBasic();
    myFixture.finishLookup(Lookup.REPLACE_SELECT_CHAR);
    myFixture.checkResult("RETURN shortestPath(<caret>)");
}