com.intellij.codeInsight.intention.IntentionAction Java Examples

The following examples show how to use com.intellij.codeInsight.intention.IntentionAction. 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: SymfonyLightCodeInsightFixtureTestCase.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void assertIntentionIsAvailable(LanguageFileType languageFileType, String configureByText, String intentionText) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    Set<String> items = new HashSet<>();

    for (IntentionAction intentionAction : IntentionManager.getInstance().getIntentionActions()) {
        if(!intentionAction.isAvailable(getProject(), getEditor(), psiElement.getContainingFile())) {
            continue;
        }

        String text = intentionAction.getText();
        items.add(text);

        if(!text.equals(intentionText)) {
            continue;
        }

        return;
    }

    fail(String.format("Fail intention action '%s' is available in element '%s' with '%s'", intentionText, psiElement.getText(), items));
}
 
Example #2
Source File: ShowIntentionsPass.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean markActionInvoked(@Nonnull Project project, @Nonnull final Editor editor, @Nonnull IntentionAction action) {
  final int offset = ((EditorEx)editor).getExpectedCaretOffset();

  List<HighlightInfo> infos = new ArrayList<>();
  DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true, new CommonProcessors.CollectProcessor<>(infos));
  boolean removed = false;
  for (HighlightInfo info : infos) {
    if (info.quickFixActionMarkers != null) {
      for (Pair<HighlightInfo.IntentionActionDescriptor, RangeMarker> pair : info.quickFixActionMarkers) {
        HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first;
        if (actionInGroup.getAction() == action) {
          // no CME because the list is concurrent
          removed |= info.quickFixActionMarkers.remove(pair);
        }
      }
    }
  }
  return removed;
}
 
Example #3
Source File: AnnotatorUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
static void addError(
    AnnotationHolder holder, SpecModelValidationError error, List<IntentionAction> fixes) {
  PsiElement errorElement = (PsiElement) error.element;
  Annotation errorAnnotation =
      holder.createErrorAnnotation(
          Optional.of(errorElement)
              .filter(element -> element instanceof PsiClass || element instanceof PsiMethod)
              .map(PsiNameIdentifierOwner.class::cast)
              .map(PsiNameIdentifierOwner::getNameIdentifier)
              .orElse(errorElement),
          error.message);
  if (!fixes.isEmpty()) {
    for (IntentionAction fix : fixes) {
      errorAnnotation.registerFix(fix);
    }
  }
}
 
Example #4
Source File: AddArgumentFixTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void createAddMethodCallFix() {
  testHelper.getPsiClass(
      classes -> {
        // Setup test environment
        PsiClass cls = classes.get(0);
        PsiMethodCallExpression call =
            PsiTreeUtil.findChildOfType(cls, PsiMethodCallExpression.class);
        Project project = testHelper.getFixture().getProject();
        PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
        Editor editor = mock(Editor.class);
        when(editor.getCaretModel()).thenReturn(mock(CaretModel.class));

        IntentionAction fix =
            AddArgumentFix.createAddMethodCallFix(call, "ClassName", "methodName", factory);

        assertThat(call.getArgumentList().getExpressions()[0].getText())
            .isNotEqualTo("ClassName.methodName()");
        fix.invoke(project, editor, testHelper.getFixture().getFile());
        assertThat(call.getArgumentList().getExpressions()[0].getText())
            .isEqualTo("ClassName.methodName()");
        return true;
      },
      "RequiredPropAnnotatorTest.java");
}
 
Example #5
Source File: CachedIntentions.java    From consulo with Apache License 2.0 6 votes vote down vote up
private int getWeight(@Nonnull IntentionActionWithTextCaching action) {
  IntentionAction a = action.getAction();
  int group = getGroup(action).getPriority();
  while (a instanceof IntentionActionDelegate) {
    a = ((IntentionActionDelegate)a).getDelegate();
  }
  if (a instanceof PriorityAction) {
    return group + getPriorityWeight(((PriorityAction)a).getPriority());
  }
  if (a instanceof SuppressIntentionActionFromFix) {
    if (((SuppressIntentionActionFromFix)a).isShouldBeAppliedToInjectionHost() == ThreeState.NO) {
      return group - 1;
    }
  }
  return group;
}
 
Example #6
Source File: PantsScalaHighlightVisitor.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private void tryToExtendInfo(@NotNull HighlightInfo info, @NotNull PsiFile containingFile) {
  List<Pair<HighlightInfo.IntentionActionDescriptor, TextRange>> actionRanges = info.quickFixActionRanges;
  if (actionRanges == null) {
    return;
  }
  for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> actionAndRange : actionRanges) {
    final TextRange textRange = actionAndRange.getSecond();
    final HighlightInfo.IntentionActionDescriptor actionDescriptor = actionAndRange.getFirst();
    final IntentionAction action = actionDescriptor.getAction();
    if (action instanceof CreateTypeDefinitionQuickFix) {
      final String className = textRange.substring(containingFile.getText());
      final List<PantsQuickFix> missingDependencyFixes =
        PantsUnresolvedReferenceFixFinder.findMissingDependencies(className, containingFile);
      for (PantsQuickFix fix : missingDependencyFixes) {
        info.registerFix(fix, null, fix.getName(), textRange, null);
      }
      if (!missingDependencyFixes.isEmpty()) {
        // we should add only one fix per info
        return;
      }
    }
  }
}
 
Example #7
Source File: DaemonTooltipActionProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static IntentionAction getFirstAvailableAction(PsiFile psiFile, Editor editor, ShowIntentionsPass.IntentionsInfo intentionsInfo) {
  Project project = psiFile.getProject();

  //sort the actions
  CachedIntentions cachedIntentions = CachedIntentions.createAndUpdateActions(project, psiFile, editor, intentionsInfo);

  List<IntentionActionWithTextCaching> allActions = cachedIntentions.getAllActions();

  if (allActions.isEmpty()) return null;

  for (IntentionActionWithTextCaching it : allActions) {
    IntentionAction action = IntentionActionDelegate.unwrap(it.getAction());

    if (!(action instanceof AbstractEmptyIntentionAction) && action.isAvailable(project, editor, psiFile)) {
      String text = it.getText();
      //we cannot properly render html inside the fix button fixes with html text
      if (!XmlStringUtil.isWrappedInHtml(text)) {
        return action;
      }
    }
  }
  return null;
}
 
Example #8
Source File: DrupalLightCodeInsightFixtureTestCase.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
public void assertIntentionIsAvailable(LanguageFileType languageFileType, String configureByText, String intentionText) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    for (IntentionAction intentionAction : IntentionManager.getInstance().getIntentionActions()) {
        if(intentionAction.isAvailable(getProject(), getEditor(), psiElement.getContainingFile()) && intentionAction.getText().equals(intentionText)) {
            return;
        }
    }

    fail(String.format("Fail intention action '%s' is available in element '%s'", intentionText, psiElement.getText()));
}
 
Example #9
Source File: RedundantModifiersQuickFixTest.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void findAccessModifierActions(String message) {
  myFixture.configureByFile(getBasePath() + '/' + getTestName(false) + ".java");

  final List<IntentionAction> availableActions = getAvailableActions();
  assertTrue(message,
    availableActions.stream().anyMatch(action -> action.getText().contains("Change access modifier")));
}
 
Example #10
Source File: HighlightInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
public IntentionActionDescriptor(@Nonnull IntentionAction action,
                                 @Nullable List<IntentionAction> options,
                                 @Nullable String displayName,
                                 @Nullable consulo.ui.image.Image icon,
                                 @Nullable HighlightDisplayKey key,
                                 @Nullable ProblemGroup problemGroup,
                                 @Nullable HighlightSeverity severity) {
  myAction = action;
  myOptions = options;
  myDisplayName = displayName;
  myIcon = icon;
  myKey = key;
  myProblemGroup = problemGroup;
  mySeverity = severity;
}
 
Example #11
Source File: HaxeSemanticAnnotatorTest.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void doTest(String... filters) throws Exception {
  doTestInternal(false, false, false);

  List<IntentionAction> intentions = myFixture.getAvailableIntentions();
  for (final IntentionAction action : intentions) {
    if (Arrays.asList(filters).contains(action.getText())) {
      System.out.println("Applying intent " + action.getText());
      myFixture.launchAction(action);
    } else {
      System.out.println("Ignoring intent " + action.getText() + ", not matching " + StringUtils.join(filters, ","));
    }
  }
  FileDocumentManager.getInstance().saveAllDocuments();
  myFixture.checkResultByFile(getTestName(false) + "_expected.hx");
}
 
Example #12
Source File: HaxeAnnotation.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public Annotation toAnnotation() {
  String tooltip = this.tooltip;
  if (null == tooltip && null != message && !message.isEmpty()) {
    tooltip = XmlStringUtil.wrapInHtml(XmlStringUtil.escapeString(message));
  }
  Annotation anno = new Annotation(range.getStartOffset(), range.getEndOffset(), severity, message, tooltip);

  for (IntentionAction action : intentions) {
    anno.registerFix(action);
  }
  return anno;
}
 
Example #13
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean availableFor(@Nonnull PsiFile psiFile, @Nonnull Editor editor, @Nonnull IntentionAction action) {
  if (!psiFile.isValid()) return false;

  try {
    Project project = psiFile.getProject();
    action = IntentionActionDelegate.unwrap(action);
    if (action instanceof SuppressIntentionActionFromFix) {
      final ThreeState shouldBeAppliedToInjectionHost = ((SuppressIntentionActionFromFix)action).isShouldBeAppliedToInjectionHost();
      if (editor instanceof EditorWindow && shouldBeAppliedToInjectionHost == ThreeState.YES) {
        return false;
      }
      if (!(editor instanceof EditorWindow) && shouldBeAppliedToInjectionHost == ThreeState.NO) {
        return false;
      }
    }

    if (action instanceof PsiElementBaseIntentionAction) {
      PsiElementBaseIntentionAction psiAction = (PsiElementBaseIntentionAction)action;
      if (!psiAction.checkFile(psiFile)) {
        return false;
      }
      PsiElement leaf = psiFile.findElementAt(editor.getCaretModel().getOffset());
      if (leaf == null || !psiAction.isAvailable(project, editor, leaf)) {
        return false;
      }
    }
    else if (!action.isAvailable(project, editor, psiFile)) {
      return false;
    }
  }
  catch (IndexNotReadyException e) {
    return false;
  }
  return true;
}
 
Example #14
Source File: CompilerCheck.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
public CompilerCheckBuilder addQuickFix(IntentionAction a)
{
	if(myQuickFixes.isEmpty())
	{
		myQuickFixes = new ArrayList<>(3);
	}
	myQuickFixes.add(a);
	return this;
}
 
Example #15
Source File: AnnotationIntentActionsFactory.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
public static Optional<IntentionAction> getFix(TextRange textRange, ErrorType errorType, PsiFile file) {
    if (errorType == ErrorType.IMPLICIT_TOKEN_DEFINITION){
        return Optional.of(new AddTokenDefinitionFix(textRange));
    } else if ( errorType==ErrorType.UNDEFINED_RULE_REF ) {
        return Optional.of(new CreateRuleFix(textRange, file));
    }
    return Optional.empty();
}
 
Example #16
Source File: QuickFixWrapper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAvailable(@Nonnull Project project, Editor editor, PsiFile file) {
  PsiElement psiElement = myDescriptor.getPsiElement();
  if (psiElement == null || !psiElement.isValid()) return false;
  final LocalQuickFix fix = getFix();
  return !(fix instanceof IntentionAction) || ((IntentionAction)fix).isAvailable(project, editor, file);
}
 
Example #17
Source File: GutterIntentionAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(@Nonnull IntentionAction o) {
  if (o instanceof GutterIntentionAction) {
    return myOrder - ((GutterIntentionAction)o).myOrder;
  }
  return 0;
}
 
Example #18
Source File: FunctionBracesIntentionTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testReactComponentFunction() {
    myFixture.configureByText(RmlFileType.INSTANCE, "let make = (children) => { ...component, render: self => <di<caret>v/>, };");
    IntentionAction bracesAction = myFixture.getAvailableIntention("Add braces to blockless function");
    myFixture.launchAction(bracesAction);

    myFixture.checkResult("let make = (children) => { ...component, render: self => { <div/>; }, };");
}
 
Example #19
Source File: UnusedImportsInspectionTest.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
public void testRemoveUnusedImportQuickFix() {
    final String testName = getTestName();

    Collection<Class<? extends LocalInspectionTool>> inspections = new ArrayList<Class<? extends LocalInspectionTool>>();
    inspections.add(UnusedImportsInspection.class);
    myFixture.enableInspections(inspections);
    myFixture.configureByFile(String.format("%s.xq", testName));

    List<IntentionAction> availableIntentions = myFixture.filterAvailableIntentions(UnusedImportsInspection.REMOVE_UNUSED_IMPORT_QUICKFIX_NAME);
    IntentionAction action = ContainerUtil.getFirstItem(availableIntentions);
    assertNotNull(action);
    myFixture.launchAction(action);

    myFixture.checkResultByFile(String.format("%s_after.xq", testName));
}
 
Example #20
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
public void assertIntentionIsAvailable(LanguageFileType languageFileType, String configureByText, String intentionText) {
    myFixture.configureByText(languageFileType, configureByText);
    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());

    for (IntentionAction intentionAction : IntentionManager.getInstance().getIntentionActions()) {
        if(intentionAction.isAvailable(getProject(), getEditor(), psiElement.getContainingFile()) && intentionAction.getText().equals(intentionText)) {
            return;
        }
    }

    fail(String.format("Fail intention action '%s' is available in element '%s'", intentionText, psiElement.getText()));
}
 
Example #21
Source File: IntentionManagerSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
public synchronized void unregisterMetaData(@Nonnull IntentionAction intentionAction) {
  for (Map.Entry<MetaDataKey, IntentionActionMetaData> entry : myMetaData.entrySet()) {
    if (entry.getValue().getAction() == intentionAction) {
      myMetaData.remove(entry.getKey());
      break;
    }
  }
}
 
Example #22
Source File: BuckAutoDepsQuickFixProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void registerFixes(
    @NotNull PsiJavaCodeReferenceElement referenceElement,
    @NotNull QuickFixActionRegistrar quickFixActionRegistrar) {
  List<IntentionAction> fixes = findFixesForReference(referenceElement);
  fixes.forEach(quickFixActionRegistrar::register);
  if (fixes.isEmpty() || Boolean.parseBoolean(System.getProperty(KEEP_DEFAULT_AUTODEPS))) {
    // Don't unregister the default if:
    //  1) We can't replace it with anything.
    //  2) The user has requested to keep it.
    return;
  }

  // If we think we can add both a Buck dependency and an IntelliJ module dependency,
  // unregister the default fix, which only adds an IntelliJ module dependency.
  quickFixActionRegistrar.unregister(
      new Condition<IntentionAction>() {
        private static final String ADD_MODULE_DEPENDENCY_FIX_CLASSNAME =
            "com.intellij.codeInsight.daemon.impl.quickfix.AddModuleDependencyFix";

        @Override
        public boolean value(IntentionAction intentionAction) {
          String className = intentionAction.getClass().getName();
          if (ADD_MODULE_DEPENDENCY_FIX_CLASSNAME.equals(className)) {
            return true;
          }
          return false;
        }
      });
}
 
Example #23
Source File: QuickFixAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void registerQuickFixAction(@Nullable HighlightInfo info,
                                          @Nullable TextRange fixRange,
                                          @Nullable IntentionAction action,
                                          @Nullable final HighlightDisplayKey key) {
  if (info == null) return;
  info.registerFix(action, null, HighlightDisplayKey.getDisplayNameByKey(key), fixRange, key);
}
 
Example #24
Source File: Annotation.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Register a quickfix which would be available onTheFly and in the batch mode. Should implement both IntentionAction and LocalQuickFix.
 */
public <T extends IntentionAction & LocalQuickFix> void registerUniversalFix(@Nonnull T fix,
                                                                             @javax.annotation.Nullable TextRange range,
                                                                             @javax.annotation.Nullable final HighlightDisplayKey key) {
  registerBatchFix(fix, range, key);
  registerFix(fix, range, key);
}
 
Example #25
Source File: CodeInsightTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
public static IntentionAction findIntentionByText(List<IntentionAction> actions, @NonNls String text) {
  for (IntentionAction action : actions) {
    final String s = action.getText();
    if (s.equals(text)) {
      return action;
    }
  }
  return null;
}
 
Example #26
Source File: IntentionListStep.java    From consulo with Apache License 2.0 5 votes vote down vote up
@TestOnly
public Map<IntentionAction, List<IntentionAction>> getActionsWithSubActions() {
  Map<IntentionAction, List<IntentionAction>> result = new LinkedHashMap<>();

  for (IntentionActionWithTextCaching cached : getValues()) {
    IntentionAction action = cached.getAction();
    if (ShowIntentionActionsHandler.chooseFileForAction(myFile, myEditor, action) == null) continue;

    List<IntentionActionWithTextCaching> subActions = getSubStep(cached, cached.getToolName()).getValues();
    List<IntentionAction> options =
            subActions.stream().map(IntentionActionWithTextCaching::getAction).filter(option -> ShowIntentionActionsHandler.chooseFileForAction(myFile, myEditor, option) != null).collect(Collectors.toList());
    result.put(action, options);
  }
  return result;
}
 
Example #27
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public List<IntentionAction> getAvailableIntentions(final String... filePaths) {
  if (filePaths.length > 0) {
    configureByFilesInner(filePaths);
  }
  return getAvailableIntentions();
}
 
Example #28
Source File: IntentionManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<IntentionAction> getCleanupIntentionOptions() {
  ArrayList<IntentionAction> options = new ArrayList<>();
  options.add(EditCleanupProfileIntentionAction.INSTANCE);
  options.add(CleanupOnScopeIntention.INSTANCE);
  return options;
}
 
Example #29
Source File: ShowAutoImportPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static List<HintAction> extractHints(@Nonnull HighlightInfo info) {
  List<Pair<HighlightInfo.IntentionActionDescriptor, TextRange>> list = info.quickFixActionRanges;
  if (list == null) return Collections.emptyList();

  List<HintAction> hintActions = new SmartList<>();
  for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : list) {
    IntentionAction action = pair.getFirst().getAction();
    if (action instanceof HintAction) {
      hintActions.add((HintAction)action);
    }
  }
  return hintActions;
}
 
Example #30
Source File: CodeInsightTestFixtureImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static List<IntentionAction> doGetAvailableIntentions(@Nonnull Editor editor, @Nonnull PsiFile file) {
  ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo();
  ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1);
  List<HighlightInfo.IntentionActionDescriptor> descriptors = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
  descriptors.addAll(intentions.intentionsToShow);
  descriptors.addAll(intentions.errorFixesToShow);
  descriptors.addAll(intentions.inspectionFixesToShow);
  descriptors.addAll(intentions.guttersToShow);

  PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
  List<IntentionAction> result = new ArrayList<IntentionAction>();

  List<HighlightInfo> infos = DaemonCodeAnalyzerEx.getInstanceEx(file.getProject()).getFileLevelHighlights(file.getProject(), file);
  for (HighlightInfo info : infos) {
    for (Pair<HighlightInfo.IntentionActionDescriptor, TextRange> pair : info.quickFixActionRanges) {
      HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first;
      if (actionInGroup.getAction().isAvailable(file.getProject(), editor, file)) {
        descriptors.add(actionInGroup);
      }
    }
  }

  // add all intention options for simplicity
  for (HighlightInfo.IntentionActionDescriptor descriptor : descriptors) {
    result.add(descriptor.getAction());
    List<IntentionAction> options = descriptor.getOptions(element, editor);
    if (options != null) {
      for (IntentionAction option : options) {
        if (option.isAvailable(file.getProject(), editor, file)) {
          result.add(option);
        }
      }
    }
  }
  return result;
}