public static void doI18nSelectedString(
      final @NotNull Project project,
      final @NotNull Editor editor,
      final @NotNull PsiFile psiFile,
      final @NotNull I18nQuickFixHandler handler) {
    try {
      handler.checkApplicability(psiFile, editor);
    } catch (IncorrectOperationException ex) {
      CommonRefactoringUtil.showErrorHint(
          project, editor, ex.getMessage(), CodeInsightBundle.message("i18nize.error.title"), null);
      return;
    }

    final JavaI18nizeQuickFixDialog dialog = handler.createDialog(project, editor, psiFile);
    if (dialog == null) return;
    dialog.show();
    if (!dialog.isOK()) return;

    if (!CodeInsightUtilBase.prepareFileForWrite(psiFile)) return;
    final Collection<PropertiesFile> propertiesFiles = dialog.getAllPropertiesFiles();
    for (PropertiesFile file : propertiesFiles) {
      if (!CodeInsightUtilBase.prepareFileForWrite(file.getContainingFile())) return;
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                CommandProcessor.getInstance()
                    .executeCommand(
                        project,
                        new Runnable() {
                          public void run() {
                            try {
                              handler.performI18nization(
                                  psiFile,
                                  editor,
                                  dialog.getLiteralExpression(),
                                  propertiesFiles,
                                  dialog.getKey(),
                                  dialog.getValue(),
                                  dialog.getI18nizedText(),
                                  dialog.getParameters(),
                                  dialog.getPropertyCreationHandler());
                            } catch (IncorrectOperationException e) {
                              LOG.error(e);
                            }
                          }
                        },
                        CodeInsightBundle.message("quickfix.i18n.command.name"),
                        project);
              }
            });
  }
  protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myConstructorCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    try {
      PsiMethod constructor = (PsiMethod) targetClass.add(elementFactory.createConstructor());

      final PsiFile file = targetClass.getContainingFile();
      TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
      CreateFromUsageUtils.setupMethodParameters(
          constructor,
          templateBuilder,
          myConstructorCall.getArgumentList(),
          getTargetSubstitutor(myConstructorCall));
      final PsiMethod superConstructor =
          CreateClassFromNewFix.setupSuperCall(targetClass, constructor, templateBuilder);

      constructor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(constructor);
      Template template = templateBuilder.buildTemplate();
      if (targetClass == null) return;
      final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
      final TextRange textRange = constructor.getTextRange();
      editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
      editor.getCaretModel().moveToOffset(textRange.getStartOffset());

      startTemplate(
          editor,
          template,
          project,
          new TemplateEditingAdapter() {
            public void templateFinished(Template template, boolean brokenOff) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        public void run() {
                          try {
                            PsiDocumentManager.getInstance(project)
                                .commitDocument(editor.getDocument());
                            final int offset = editor.getCaretModel().getOffset();
                            PsiMethod constructor =
                                PsiTreeUtil.findElementOfClassAtOffset(
                                    file, offset, PsiMethod.class, false);
                            if (superConstructor == null) {
                              CreateFromUsageUtils.setupMethodBody(constructor);
                            } else {
                              OverrideImplementUtil.setupMethodBody(
                                  constructor, superConstructor, targetClass);
                            }
                            CreateFromUsageUtils.setupEditor(constructor, editor);
                          } catch (IncorrectOperationException e) {
                            LOG.error(e);
                          }
                        }
                      });
            }
          });
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!CodeInsightUtilBase.preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiMethod psiMethod =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class);
      if (psiMethod != null) {
        final ArrayList<PsiElement> psiParameters = new ArrayList<PsiElement>();
        final RefElement refMethod = myManager != null ? myManager.getReference(psiMethod) : null;
        if (refMethod != null) {
          for (final RefParameter refParameter : getUnusedParameters((RefMethod) refMethod)) {
            psiParameters.add(refParameter.getElement());
          }
        } else {
          final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
          for (PsiParameter parameter : parameters) {
            if (Comparing.strEqual(parameter.getName(), myHint)) {
              psiParameters.add(parameter);
              break;
            }
          }
        }
        final PsiModificationTracker tracker = psiMethod.getManager().getModificationTracker();
        final long startModificationCount = tracker.getModificationCount();

        removeUnusedParameterViaChangeSignature(psiMethod, psiParameters);
        if (refMethod != null && startModificationCount != tracker.getModificationCount()) {
          myProcessor.ignoreElement(refMethod);
        }
      }
    }
Beispiel #4
0
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement element = descriptor.getPsiElement();
    PsiStatement anchorStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class);
    LOG.assertTrue(anchorStatement != null);
    Editor editor = getEditor(project, element);
    if (editor == null) return;
    PsiFile file = element.getContainingFile();
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    Document document = documentManager.getDocument(file);
    if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
    PsiElement[] elements = {anchorStatement};
    PsiElement prev = PsiTreeUtil.skipSiblingsBackward(anchorStatement, PsiWhiteSpace.class);
    if (prev instanceof PsiComment
        && SuppressManager.getInstance().getSuppressedInspectionIdsIn(prev) != null) {
      elements = new PsiElement[] {prev, anchorStatement};
    }
    try {
      TextRange textRange = new JavaWithIfSurrounder().surroundElements(project, editor, elements);
      if (textRange == null) return;

      @NonNls String newText = myText + " != null";
      document.replaceString(textRange.getStartOffset(), textRange.getEndOffset(), newText);
      editor.getCaretModel().moveToOffset(textRange.getEndOffset() + newText.length());
      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);

    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
Beispiel #5
0
  @Override
  public void execute(
      final Editor editor,
      final DataContext dataContext,
      @Nullable final Producer<Transferable> producer) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;

    final Document document = editor.getDocument();
    if (!FileDocumentManager.getInstance()
        .requestWriting(document, CommonDataKeys.PROJECT.getData(dataContext))) {
      return;
    }

    DataContext context = dataContext;
    if (producer != null) {
      context =
          new DataContext() {
            @Override
            public Object getData(@NonNls String dataId) {
              return PasteAction.TRANSFERABLE_PROVIDER.is(dataId)
                  ? producer
                  : dataContext.getData(dataId);
            }
          };
    }

    final Project project = editor.getProject();
    if (project == null
        || editor.isColumnMode()
        || editor.getSelectionModel().hasBlockSelection()
        || editor.getCaretModel().getCaretCount() > 1) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    document.startGuardedBlockChecking();
    try {
      for (PasteProvider provider : Extensions.getExtensions(EP_NAME)) {
        if (provider.isPasteEnabled(context)) {
          provider.performPaste(context);
          return;
        }
      }
      doPaste(editor, project, file, document, producer);
    } catch (ReadOnlyFragmentModificationException e) {
      EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e);
    } finally {
      document.stopGuardedBlockChecking();
    }
  }
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   final PsiDocTag myTag =
       PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiDocTag.class);
   if (myTag == null) return;
   if (!CodeInsightUtilBase.preparePsiElementForWrite(myTag)) return;
   myTag.delete();
 }
 @Override
 public void invoke(
     @NotNull Project project,
     @NotNull PsiFile file,
     @Nullable("is null when called from inspection") Editor editor,
     @NotNull PsiElement startElement,
     @NotNull PsiElement endElement) {
   if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
   addTypeCast(project, (PsiExpression) startElement, myType);
 }
 @Override
 public void invoke(@NotNull final Project project, final Editor editor, PsiFile file) {
   if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
   if (candidates.size() == 1) {
     final PsiMethod toImport = candidates.get(0);
     doImport(toImport);
   } else {
     chooseAndImport(editor, project);
   }
 }
  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
    if (!CodeInsightUtilBase.prepareFileForWrite(myMethod.getContainingFile())) return;

    try {
      PsiUtil.setModifierProperty(myMethod, PsiModifier.ABSTRACT, false);
      CreateFromUsageUtils.setupMethodBody(myMethod);
      CreateFromUsageUtils.setupEditor(myMethod, editor);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 public void applyFix(final Project project, final PsiFile file, final Editor editor) {
   if (!CodeInsightUtilBase.prepareFileForWrite(myClass.getContainingFile())) return;
   PsiCodeBlock body;
   if (myClass.isInterface() && (body = myMethod.getBody()) != null) body.delete();
   for (String exception : myExceptions) {
     PsiUtil.addException(myMethod, exception);
   }
   PsiMethod method = (PsiMethod) myClass.add(myMethod);
   method = (PsiMethod) method.replace(reformat(project, method));
   if (editor != null) {
     GenerateMembersUtil.positionCaret(editor, method, true);
   }
 }
 @Override
 public void invoke(
     @NotNull Project project,
     @NotNull PsiFile file,
     @Nullable("is null when called from inspection") Editor editor,
     @NotNull PsiElement startElement,
     @NotNull PsiElement endElement) {
   if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) {
     return;
   }
   PsiElement newPsi =
       GosuPsiParseUtil.parseIdentifierOrTokenOrRelativeType(_correctName, startElement);
   newPsi = findIdentifierOrToken(newPsi);
   PsiElement oldPsi = findIdentifierOrToken(startElement);
   oldPsi.replace(newPsi);
 }
  public void applyFix(
      @NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
    PsiElement element = descriptor.getPsiElement();
    if (element == null) return;
    final PsiFile myFile = element.getContainingFile();

    if (!CodeInsightUtilBase.prepareFileForWrite(myFile)) return;

    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              public void run() {
                chooseDirectoryAndMove(project, myFile);
              }
            });
  }
  private void surroundWithCodeBlock(@NotNull final MoveInfo info, final boolean down) {
    try {
      final Document document =
          PsiDocumentManager.getInstance(statementToSurroundWithCodeBlock.getProject())
              .getDocument(statementToSurroundWithCodeBlock.getContainingFile());
      int startOffset = document.getLineStartOffset(info.toMove.startLine);
      int endOffset = getLineStartSafeOffset(document, info.toMove.endLine);
      if (document.getText().charAt(endOffset - 1) == '\n') endOffset--;
      final RangeMarker lineRangeMarker = document.createRangeMarker(startOffset, endOffset);

      final PsiElementFactory factory =
          JavaPsiFacade.getInstance(statementToSurroundWithCodeBlock.getProject())
              .getElementFactory();
      PsiCodeBlock codeBlock = factory.createCodeBlock();
      codeBlock.add(statementToSurroundWithCodeBlock);
      final PsiBlockStatement blockStatement =
          (PsiBlockStatement)
              factory.createStatementFromText("{}", statementToSurroundWithCodeBlock);
      blockStatement.getCodeBlock().replace(codeBlock);
      PsiBlockStatement newStatement =
          (PsiBlockStatement) statementToSurroundWithCodeBlock.replace(blockStatement);
      newStatement = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(newStatement);
      info.toMove =
          new LineRange(
              document.getLineNumber(lineRangeMarker.getStartOffset()),
              document.getLineNumber(lineRangeMarker.getEndOffset()) + 1);
      PsiCodeBlock newCodeBlock = newStatement.getCodeBlock();
      if (down) {
        PsiElement blockChild = firstNonWhiteElement(newCodeBlock.getFirstBodyElement(), true);
        if (blockChild == null) blockChild = newCodeBlock.getRBrace();
        info.toMove2 =
            new LineRange(
                info.toMove2
                    .startLine, // document.getLineNumber(newCodeBlock.getParent().getTextRange().getStartOffset()),
                document.getLineNumber(blockChild.getTextRange().getStartOffset()));
      } else {
        int start =
            document.getLineNumber(newCodeBlock.getRBrace().getTextRange().getStartOffset());
        int end = info.toMove.startLine;
        if (start > end) end = start;
        info.toMove2 = new LineRange(start, end);
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  public static void renameNonCodeUsages(
      @NotNull Project project, @NotNull NonCodeUsageInfo[] usages) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    Map<Document, List<UsageOffset>> docsToOffsetsMap = new HashMap<Document, List<UsageOffset>>();
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    for (NonCodeUsageInfo usage : usages) {
      PsiElement element = usage.getElement();

      if (element == null) continue;
      element = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(element, true);
      if (element == null) continue;

      final ProperTextRange rangeInElement = usage.getRangeInElement();
      if (rangeInElement == null) continue;

      final PsiFile containingFile = element.getContainingFile();
      final Document document = psiDocumentManager.getDocument(containingFile);

      final Segment segment = usage.getSegment();
      LOG.assertTrue(segment != null);
      int fileOffset = segment.getStartOffset();

      List<UsageOffset> list = docsToOffsetsMap.get(document);
      if (list == null) {
        list = new ArrayList<UsageOffset>();
        docsToOffsetsMap.put(document, list);
      }

      list.add(new UsageOffset(fileOffset, fileOffset + rangeInElement.getLength(), usage.newText));
    }

    for (Document document : docsToOffsetsMap.keySet()) {
      List<UsageOffset> list = docsToOffsetsMap.get(document);
      LOG.assertTrue(list != null, document);
      UsageOffset[] offsets = list.toArray(new UsageOffset[list.size()]);
      Arrays.sort(offsets);

      for (int i = offsets.length - 1; i >= 0; i--) {
        UsageOffset usageOffset = offsets[i];
        document.replaceString(usageOffset.startOffset, usageOffset.endOffset, usageOffset.newText);
      }
      PsiDocumentManager.getInstance(project).commitDocument(document);
    }
    PsiDocumentManager.getInstance(project).commitAllDocuments();
  }
 @Override
 public void invoke(
     @NotNull final Project project, final Editor editor, @NotNull final PsiElement element)
     throws IncorrectOperationException {
   PsiDocCommentOwner container = getContainer(element);
   assert container != null;
   if (!CodeInsightUtilBase.preparePsiElementForWrite(container)) return;
   if (use15Suppressions(container)) {
     final PsiModifierList modifierList = container.getModifierList();
     if (modifierList != null) {
       addSuppressAnnotation(project, editor, container, container, getID(container));
     }
   } else {
     PsiDocComment docComment = container.getDocComment();
     PsiManager manager = PsiManager.getInstance(project);
     if (docComment == null) {
       String commentText =
           "/** @" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container) + "*/";
       docComment =
           JavaPsiFacade.getInstance(manager.getProject())
               .getElementFactory()
               .createDocCommentFromText(commentText);
       PsiElement firstChild = container.getFirstChild();
       container.addBefore(docComment, firstChild);
     } else {
       PsiDocTag noInspectionTag =
           docComment.findTagByName(SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME);
       if (noInspectionTag != null) {
         String tagText = noInspectionTag.getText() + ", " + getID(container);
         noInspectionTag.replace(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       } else {
         String tagText =
             "@" + SuppressionUtil.SUPPRESS_INSPECTIONS_TAG_NAME + " " + getID(container);
         docComment.add(
             JavaPsiFacade.getInstance(manager.getProject())
                 .getElementFactory()
                 .createDocTagFromText(tagText));
       }
     }
   }
   DaemonCodeAnalyzer.getInstance(project).restart();
 }
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      @Nullable("is null when called from inspection") Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiModifierListOwner myModifierListOwner = (PsiModifierListOwner) startElement;

    final ExternalAnnotationsManager annotationsManager =
        ExternalAnnotationsManager.getInstance(project);
    final PsiModifierList modifierList = myModifierListOwner.getModifierList();
    LOG.assertTrue(modifierList != null);
    if (modifierList.findAnnotation(myAnnotation) != null) return;
    final ExternalAnnotationsManager.AnnotationPlace annotationAnnotationPlace =
        annotationsManager.chooseAnnotationsPlace(myModifierListOwner);
    if (annotationAnnotationPlace == ExternalAnnotationsManager.AnnotationPlace.NOWHERE) return;
    if (annotationAnnotationPlace == ExternalAnnotationsManager.AnnotationPlace.EXTERNAL) {
      for (String fqn : myAnnotationsToRemove) {
        annotationsManager.deannotate(myModifierListOwner, fqn);
      }
      annotationsManager.annotateExternally(myModifierListOwner, myAnnotation, file, myPairs);
    } else {
      final PsiFile containingFile = myModifierListOwner.getContainingFile();
      if (!CodeInsightUtilBase.preparePsiElementForWrite(containingFile)) return;
      for (String fqn : myAnnotationsToRemove) {
        PsiAnnotation annotation = AnnotationUtil.findAnnotation(myModifierListOwner, fqn);
        if (annotation != null) {
          annotation.delete();
        }
      }

      PsiAnnotation inserted = modifierList.addAnnotation(myAnnotation);
      for (PsiNameValuePair pair : myPairs) {
        inserted.setDeclaredAttributeValue(pair.getName(), pair.getValue());
      }
      JavaCodeStyleManager.getInstance(project).shortenClassReferences(inserted);
      if (containingFile != file) {
        UndoUtil.markPsiFileForUndo(file);
      }
    }
  }
 @Override
 public void invoke(
     @NotNull Project project,
     @NotNull PsiFile file,
     @Nullable("is null when called from inspection") Editor editor,
     @NotNull PsiElement startElement,
     @NotNull PsiElement endElement) {
   final PsiClass myClass = (PsiClass) startElement;
   if (!CodeInsightUtilBase.prepareFileForWrite(myClass.getContainingFile())) return;
   PsiCodeBlock body;
   if (myClass.isInterface() && (body = myMethodPrototype.getBody()) != null) body.delete();
   for (String exception : myExceptions) {
     PsiUtil.addException(myMethodPrototype, exception);
   }
   PsiMethod method = (PsiMethod) myClass.add(myMethodPrototype);
   method = (PsiMethod) method.replace(reformat(project, method));
   if (editor != null) {
     GenerateMembersUtil.positionCaret(editor, method, true);
   }
 }
  @Nullable
  @Override
  protected TextRange surroundStatements(
      Project project, Editor editor, PsiElement container, PsiElement[] statements) {
    statements =
        MoveDeclarationsOutHelper.move(container, statements, isGenerateDefaultInitializers());

    if (statements.length == 0) {
      KotlinSurrounderUtils.showErrorHint(
          project, editor, KotlinSurrounderUtils.SURROUND_WITH_ERROR);
      return null;
    }

    KtIfExpression ifExpression =
        (KtIfExpression) KtPsiFactoryKt.KtPsiFactory(project).createExpression(getCodeTemplate());
    ifExpression =
        (KtIfExpression) container.addAfter(ifExpression, statements[statements.length - 1]);

    // TODO move a comment for first statement

    KtBlockExpression thenBranch = (KtBlockExpression) ifExpression.getThen();
    assert thenBranch != null
        : "Then branch should exist for created if expression: " + ifExpression.getText();
    // Add statements in then branch of created if
    KotlinSurrounderUtils.addStatementsInBlock(thenBranch, statements);

    // Delete statements from original code
    container.deleteChildRange(statements[0], statements[statements.length - 1]);

    ifExpression = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(ifExpression);

    KtExpression condition = ifExpression.getCondition();
    assert condition != null
        : "Condition should exists for created if expression: " + ifExpression.getText();
    // Delete condition from created if
    TextRange range = condition.getTextRange();
    TextRange textRange = new TextRange(range.getStartOffset(), range.getStartOffset());
    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    return textRange;
  }
  @Override
  public TextRange surroundExpression(Project project, Editor editor, PsiExpression expr)
      throws IncorrectOperationException {
    PsiManager manager = expr.getManager();
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);

    @NonNls String text = "if(a){\nst;\n}";
    PsiIfStatement ifStatement = (PsiIfStatement) factory.createStatementFromText(text, null);
    ifStatement = (PsiIfStatement) codeStyleManager.reformat(ifStatement);

    ifStatement.getCondition().replace(expr);

    PsiExpressionStatement statement = (PsiExpressionStatement) expr.getParent();
    ifStatement = (PsiIfStatement) statement.replace(ifStatement);

    PsiCodeBlock block = ((PsiBlockStatement) ifStatement.getThenBranch()).getCodeBlock();
    block = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(block);
    TextRange range = block.getStatements()[0].getTextRange();
    editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
    return new TextRange(range.getStartOffset(), range.getStartOffset());
  }
  public void invoke(
      @NotNull Project project, @NotNull final Editor editor, @NotNull PsiFile file) {
    if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;

    LookupManager.getInstance(project).hideActiveLookup();

    final CharSequence charsSequence = editor.getDocument().getCharsSequence();

    final CompletionData data = computeData(editor, charsSequence);
    String currentPrefix = data.myPrefix;

    final CompletionState completionState = getCompletionState(editor);

    String oldPrefix = completionState.oldPrefix;
    CompletionVariant lastProposedVariant = completionState.lastProposedVariant;

    if (lastProposedVariant == null
        || oldPrefix == null
        || !new CamelHumpMatcher(oldPrefix).prefixMatches(currentPrefix)
        || // oldPrefix.length() == 0 ||
        !currentPrefix.equals(lastProposedVariant.variant)) {
      // we are starting over
      oldPrefix = currentPrefix;
      completionState.oldPrefix = oldPrefix;
      lastProposedVariant = null;
    }

    CompletionVariant nextVariant =
        computeNextVariant(editor, oldPrefix, lastProposedVariant, data);
    if (nextVariant == null) return;

    int replacementEnd = data.startOffset + data.myWordUnderCursor.length();
    editor.getDocument().replaceString(data.startOffset, replacementEnd, nextVariant.variant);
    editor.getCaretModel().moveToOffset(data.startOffset + nextVariant.variant.length());
    completionState.lastProposedVariant = nextVariant;
    highlightWord(editor, nextVariant, project, data);
  }
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      @Nullable("is null when called from inspection") Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    if (!CodeInsightUtilBase.prepareFileForWrite(startElement.getContainingFile())) {
      return;
    }
    if (!(startElement instanceof GosuMethodImpl)) {
      return;
    }
    String src = startElement.getText();
    String property = isGetter ? "property get" : "property set";
    String newMethodName = methodName.substring(3);
    src = src.replace("function", property);
    src = src.replaceFirst(methodName, newMethodName);
    PsiElement stub = GosuPsiParseUtil.parseProgramm(src, startElement, file.getManager(), null);

    PsiElement newMethod =
        new PsiMatcherImpl(stub).descendant(hasClass(GosuMethodImpl.class)).getElement();
    startElement.replace(newMethod);
  }
    @Override
    protected void doFix(Project project, ProblemDescriptor descriptor)
        throws IncorrectOperationException {
      final PsiElement element = descriptor.getPsiElement();
      final PsiClass aClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
      if (aClass == null) {
        return;
      }
      final PsiElement parent = element.getParent();
      if (!(parent instanceof PsiReferenceExpression)) {
        return;
      }
      final PsiReferenceExpression methodExpression = (PsiReferenceExpression) parent;
      final PsiElement grandParent = methodExpression.getParent();
      if (!(grandParent instanceof PsiMethodCallExpression)) {
        return;
      }
      final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) grandParent;
      final PsiExpressionList list = methodCallExpression.getArgumentList();
      final PsiExpression[] expressions = list.getExpressions();
      final StringBuilder fieldText =
          new StringBuilder(
              "private static final java.util.regex.Pattern PATTERN = "
                  + "java.util.regex.Pattern.compile(");
      final int expressionsLength = expressions.length;
      if (expressionsLength > 0) {
        fieldText.append(expressions[0].getText());
      }
      fieldText.append(");");
      final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
      final PsiField newField = factory.createFieldFromText(fieldText.toString(), element);
      final PsiElement field = aClass.add(newField);

      final StringBuilder expressionText = new StringBuilder("PATTERN.");
      final String methodName = methodExpression.getReferenceName();
      final PsiExpression qualifier = methodExpression.getQualifierExpression();
      final String qualifierText;
      if (qualifier == null) {
        qualifierText = "this";
      } else {
        qualifierText = qualifier.getText();
      }
      if ("split".equals(methodName)) {
        expressionText.append(methodName);
        expressionText.append('(');
        expressionText.append(qualifierText);
        for (int i = 1; i < expressionsLength; i++) {
          expressionText.append(',');
          expressionText.append(expressions[i].getText());
        }
        expressionText.append(')');
      } else {
        expressionText.append("matcher(");
        expressionText.append(qualifierText);
        expressionText.append(").");
        expressionText.append(methodName);
        expressionText.append('(');
        if (expressionsLength > 1) {
          expressionText.append(expressions[1].getText());
          for (int i = 2; i < expressionsLength; i++) {
            expressionText.append(',');
            expressionText.append(expressions[i].getText());
          }
        }
        expressionText.append(')');
      }

      final PsiExpression newExpression =
          factory.createExpressionFromText(expressionText.toString(), element);
      PsiMethodCallExpression newMethodCallExpression =
          (PsiMethodCallExpression) methodCallExpression.replace(newExpression);
      newMethodCallExpression =
          CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(newMethodCallExpression);
      final PsiReferenceExpression reference = getReference(newMethodCallExpression);
      HighlightUtils.showRenameTemplate(aClass, (PsiNameIdentifierOwner) field, reference);
    }
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull Editor editor,
      @NotNull Caret caret,
      @NotNull PsiFile file) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
    myProject = project;
    myEditor = editor;
    myCaret = caret;
    myFile = file;

    myDocument = editor.getDocument();

    if (!FileDocumentManager.getInstance().requestWriting(myDocument, project)) {
      return;
    }
    FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.comment.block");
    final Commenter commenter = findCommenter(myFile, myEditor, caret);
    if (commenter == null) return;

    final String prefix;
    final String suffix;

    if (commenter instanceof SelfManagingCommenter) {
      final SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter) commenter;
      mySelfManagedCommenterData =
          selfManagingCommenter.createBlockCommentingState(
              caret.getSelectionStart(), caret.getSelectionEnd(), myDocument, myFile);

      if (mySelfManagedCommenterData == null) {
        mySelfManagedCommenterData = SelfManagingCommenter.EMPTY_STATE;
      }

      prefix =
          selfManagingCommenter.getBlockCommentPrefix(
              caret.getSelectionStart(), myDocument, mySelfManagedCommenterData);
      suffix =
          selfManagingCommenter.getBlockCommentSuffix(
              caret.getSelectionEnd(), myDocument, mySelfManagedCommenterData);
    } else {
      prefix = commenter.getBlockCommentPrefix();
      suffix = commenter.getBlockCommentSuffix();
    }

    if (prefix == null || suffix == null) return;

    TextRange commentedRange = findCommentedRange(commenter);
    if (commentedRange != null) {
      final int commentStart = commentedRange.getStartOffset();
      final int commentEnd = commentedRange.getEndOffset();
      int selectionStart = commentStart;
      int selectionEnd = commentEnd;
      if (myCaret.hasSelection()) {
        selectionStart = myCaret.getSelectionStart();
        selectionEnd = myCaret.getSelectionEnd();
      }
      if ((commentStart < selectionStart || commentStart >= selectionEnd)
          && (commentEnd <= selectionStart || commentEnd > selectionEnd)) {
        commentRange(selectionStart, selectionEnd, prefix, suffix, commenter);
      } else {
        uncommentRange(commentedRange, trim(prefix), trim(suffix), commenter);
      }
    } else {
      if (myCaret.hasSelection()) {
        int selectionStart = myCaret.getSelectionStart();
        int selectionEnd = myCaret.getSelectionEnd();
        if (commenter instanceof IndentedCommenter) {
          final Boolean value = ((IndentedCommenter) commenter).forceIndentedLineComment();
          if (value != null && value == Boolean.TRUE) {
            selectionStart =
                myDocument.getLineStartOffset(myDocument.getLineNumber(selectionStart));
            selectionEnd = myDocument.getLineEndOffset(myDocument.getLineNumber(selectionEnd));
          }
        }
        commentRange(selectionStart, selectionEnd, prefix, suffix, commenter);
      } else {
        EditorUtil.fillVirtualSpaceUntilCaret(editor);
        int caretOffset = myCaret.getOffset();
        if (commenter instanceof IndentedCommenter) {
          final Boolean value = ((IndentedCommenter) commenter).forceIndentedLineComment();
          if (value != null && value == Boolean.TRUE) {
            final int lineNumber = myDocument.getLineNumber(caretOffset);
            final int start = myDocument.getLineStartOffset(lineNumber);
            final int end = myDocument.getLineEndOffset(lineNumber);
            commentRange(start, end, prefix, suffix, commenter);
            return;
          }
        }
        myDocument.insertString(caretOffset, prefix + suffix);
        myCaret.moveToOffset(caretOffset + prefix.length());
      }
    }
  }
Beispiel #24
0
  @Override
  public void invoke(
      @NotNull Project project,
      @NotNull PsiFile file,
      @Nullable("is null when called from inspection") Editor editor,
      @NotNull PsiElement startElement,
      @NotNull PsiElement endElement) {
    final PsiModifierList myModifierList = (PsiModifierList) startElement;
    final PsiVariable variable = myVariable == null ? null : myVariable.getElement();
    if (!CodeInsightUtilBase.preparePsiElementForWrite(myModifierList)) return;
    final List<PsiModifierList> modifierLists = new ArrayList<PsiModifierList>();
    final PsiFile containingFile = myModifierList.getContainingFile();
    final PsiModifierList modifierList;
    if (variable != null && variable.isValid()) {
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                public void run() {
                  try {
                    variable.normalizeDeclaration();
                  } catch (IncorrectOperationException e) {
                    LOG.error(e);
                  }
                }
              });
      modifierList = variable.getModifierList();
      assert modifierList != null;
    } else {
      modifierList = myModifierList;
    }
    PsiElement owner = modifierList.getParent();
    if (owner instanceof PsiMethod) {
      PsiModifierList copy = (PsiModifierList) myModifierList.copy();
      changeModifierList(copy);
      final int accessLevel = PsiUtil.getAccessLevel(copy);

      OverridingMethodsSearch.search((PsiMethod) owner, owner.getResolveScope(), true)
          .forEach(
              new PsiElementProcessorAdapter<PsiMethod>(
                  new PsiElementProcessor<PsiMethod>() {
                    public boolean execute(@NotNull PsiMethod inheritor) {
                      PsiModifierList list = inheritor.getModifierList();
                      if (inheritor.getManager().isInProject(inheritor)
                          && PsiUtil.getAccessLevel(list) < accessLevel) {
                        modifierLists.add(list);
                      }
                      return true;
                    }
                  }));
    }

    if (!CodeInsightUtilBase.prepareFileForWrite(containingFile)) return;

    if (!modifierLists.isEmpty()) {
      if (Messages.showYesNoDialog(
              project,
              QuickFixBundle.message("change.inheritors.visibility.warning.text"),
              QuickFixBundle.message("change.inheritors.visibility.warning.title"),
              Messages.getQuestionIcon())
          == DialogWrapper.OK_EXIT_CODE) {
        ApplicationManager.getApplication()
            .runWriteAction(
                new Runnable() {
                  public void run() {
                    if (!CodeInsightUtilBase.preparePsiElementsForWrite(modifierLists)) {
                      return;
                    }

                    for (final PsiModifierList modifierList : modifierLists) {
                      changeModifierList(modifierList);
                    }
                  }
                });
      }
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                changeModifierList(modifierList);
                UndoUtil.markPsiFileForUndo(containingFile);
              }
            });
  }
  @Override
  public void invoke(
      @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;
    try {
      final XmlTag contextTag = getContextTag(editor, file);
      if (contextTag == null) {
        throw new CommonRefactoringUtil.RefactoringErrorHintException(
            "Caret should be positioned inside a tag");
      }
      XmlElementDescriptor currentTagDescriptor = contextTag.getDescriptor();
      assert currentTagDescriptor != null;
      final XmlElementDescriptor[] descriptors =
          currentTagDescriptor.getElementsDescriptors(contextTag);
      Arrays.sort(
          descriptors,
          new Comparator<XmlElementDescriptor>() {
            @Override
            public int compare(XmlElementDescriptor o1, XmlElementDescriptor o2) {
              return o1.getName().compareTo(o2.getName());
            }
          });
      final JBList list = new JBList(descriptors);
      list.setCellRenderer(new MyListCellRenderer());
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              final XmlElementDescriptor selected = (XmlElementDescriptor) list.getSelectedValue();
              new WriteCommandAction.Simple(project, "Generate XML Tag", file) {
                @Override
                protected void run() {
                  if (selected == null) return;
                  XmlTag newTag = createTag(contextTag, selected);

                  PsiElement anchor = getAnchor(contextTag, editor, selected);
                  if (anchor == null) { // insert it in the cursor position
                    int offset = editor.getCaretModel().getOffset();
                    Document document = editor.getDocument();
                    document.insertString(offset, newTag.getText());
                    PsiDocumentManager.getInstance(project).commitDocument(document);
                    newTag =
                        PsiTreeUtil.getParentOfType(
                            file.findElementAt(offset + 1), XmlTag.class, false);
                  } else {
                    newTag = (XmlTag) contextTag.addAfter(newTag, anchor);
                  }
                  if (newTag != null) {
                    generateTag(newTag, editor);
                  }
                }
              }.execute();
            }
          };
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        XmlElementDescriptor descriptor =
            ContainerUtil.find(
                descriptors,
                new Condition<XmlElementDescriptor>() {
                  @Override
                  public boolean value(XmlElementDescriptor xmlElementDescriptor) {
                    return xmlElementDescriptor.getName().equals(TEST_THREAD_LOCAL.get());
                  }
                });
        list.setSelectedValue(descriptor, false);
        runnable.run();
      } else {
        JBPopupFactory.getInstance()
            .createListPopupBuilder(list)
            .setTitle("Choose Tag Name")
            .setItemChoosenCallback(runnable)
            .setFilteringEnabled(
                new Function<Object, String>() {
                  @Override
                  public String fun(Object o) {
                    return ((XmlElementDescriptor) o).getName();
                  }
                })
            .createPopup()
            .showInBestPositionFor(editor);
      }
    } catch (CommonRefactoringUtil.RefactoringErrorHintException e) {
      HintManager.getInstance().showErrorHint(editor, e.getMessage());
    }
  }
  @Override
  protected void invokeImpl(final PsiClass targetClass) {
    if (CreateFromUsageUtils.isValidReference(myReferenceExpression, true)) {
      return;
    }

    final Project project = myReferenceExpression.getProject();
    PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();

    final PsiFile targetFile = targetClass.getContainingFile();

    PsiType[] expectedTypes = CreateFromUsageUtils.guessType(myReferenceExpression, false);
    PsiType type = expectedTypes[0];

    String varName = myReferenceExpression.getReferenceName();
    PsiExpression initializer = null;
    boolean isInline = false;
    PsiExpression[] expressions =
        CreateFromUsageUtils.collectExpressions(
            myReferenceExpression, PsiMember.class, PsiFile.class);
    PsiStatement anchor = getAnchor(expressions);
    if (anchor instanceof PsiExpressionStatement
        && ((PsiExpressionStatement) anchor).getExpression() instanceof PsiAssignmentExpression) {
      PsiAssignmentExpression assignment =
          (PsiAssignmentExpression) ((PsiExpressionStatement) anchor).getExpression();
      if (assignment.getLExpression().textMatches(myReferenceExpression)) {
        initializer = assignment.getRExpression();
        isInline = true;
      }
    }

    PsiDeclarationStatement decl =
        factory.createVariableDeclarationStatement(varName, type, initializer);

    TypeExpression expression = new TypeExpression(project, expectedTypes);

    if (isInline) {
      final PsiExpression expr = ((PsiExpressionStatement) anchor).getExpression();
      final PsiElement semicolon = expr.getNextSibling();
      if (semicolon != null) {
        final PsiElement nextSibling = semicolon.getNextSibling();
        if (nextSibling != null) {
          decl.addRange(nextSibling, anchor.getLastChild());
        }
      }
      decl = (PsiDeclarationStatement) anchor.replace(decl);
    } else {
      decl = (PsiDeclarationStatement) anchor.getParent().addBefore(decl, anchor);
    }

    PsiVariable var = (PsiVariable) decl.getDeclaredElements()[0];
    boolean isFinal =
        CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS
            && !CreateFromUsageUtils.isAccessedForWriting(expressions);
    PsiUtil.setModifierProperty(var, PsiModifier.FINAL, isFinal);

    var = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(var);
    if (var == null) return;
    TemplateBuilderImpl builder = new TemplateBuilderImpl(var);
    builder.replaceElement(var.getTypeElement(), expression);
    builder.setEndVariableAfter(var.getNameIdentifier());
    Template template = builder.buildTemplate();

    final Editor newEditor = positionCursor(project, targetFile, var);
    TextRange range = var.getTextRange();
    newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());

    startTemplate(
        newEditor,
        template,
        project,
        new TemplateEditingAdapter() {
          @Override
          public void templateFinished(Template template, boolean brokenOff) {
            PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
            final int offset = newEditor.getCaretModel().getOffset();
            final PsiLocalVariable localVariable =
                PsiTreeUtil.findElementOfClassAtOffset(
                    targetFile, offset, PsiLocalVariable.class, false);
            if (localVariable != null) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        @Override
                        public void run() {
                          CodeStyleManager.getInstance(project).reformat(localVariable);
                        }
                      });
            }
          }
        });
  }
  public final void invokeCompletion(
      @NotNull final Project project,
      @NotNull final Editor editor,
      int time,
      boolean hasModifiers,
      boolean restarted,
      @NotNull final Caret caret) {
    markCaretAsProcessed(caret);

    if (invokedExplicitly) {
      CompletionLookupArranger.applyLastCompletionStatisticsUpdate();
    }

    checkNoWriteAccess();

    CompletionAssertions.checkEditorValid(editor);

    int offset = editor.getCaretModel().getOffset();
    if (editor.isViewer() || editor.getDocument().getRangeGuard(offset, offset) != null) {
      editor.getDocument().fireReadOnlyModificationAttempt();
      CodeInsightUtilBase.showReadOnlyViewWarning(editor);
      return;
    }

    if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
      return;
    }

    CompletionPhase phase = CompletionServiceImpl.getCompletionPhase();
    boolean repeated =
        phase.indicator != null && phase.indicator.isRepeatedInvocation(myCompletionType, editor);
    /*
    if (repeated && isAutocompleteCommonPrefixOnInvocation() && phase.fillInCommonPrefix()) {
      return;
    }
    */

    final int newTime = phase.newCompletionStarted(time, repeated);
    if (invokedExplicitly) {
      time = newTime;
    }
    final int invocationCount = time;
    if (CompletionServiceImpl.isPhase(CompletionPhase.InsertedSingleItem.class)) {
      CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
    }
    CompletionServiceImpl.assertPhase(
        CompletionPhase.NoCompletion.getClass(), CompletionPhase.CommittingDocuments.class);

    if (invocationCount > 1 && myCompletionType == CompletionType.BASIC) {
      FeatureUsageTracker.getInstance()
          .triggerFeatureUsed(CodeCompletionFeatures.SECOND_BASIC_COMPLETION);
    }

    final CompletionInitializationContext[] initializationContext = {null};

    Runnable initCmd =
        new Runnable() {
          @Override
          public void run() {
            Runnable runnable =
                new Runnable() {
                  @Override
                  public void run() {
                    EditorUtil.fillVirtualSpaceUntilCaret(editor);
                    PsiDocumentManager.getInstance(project).commitAllDocuments();
                    CompletionAssertions.checkEditorValid(editor);

                    final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(caret, project);
                    assert psiFile != null
                        : "no PSI file: "
                            + FileDocumentManager.getInstance().getFile(editor.getDocument());
                    psiFile.putUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING, Boolean.TRUE);
                    CompletionAssertions.assertCommitSuccessful(editor, psiFile);

                    initializationContext[0] =
                        runContributorsBeforeCompletion(editor, psiFile, invocationCount, caret);
                  }
                };
            ApplicationManager.getApplication().runWriteAction(runnable);
          }
        };
    if (autopopup) {
      CommandProcessor.getInstance().runUndoTransparentAction(initCmd);
      if (!restarted && shouldSkipAutoPopup(editor, initializationContext[0].getFile())) {
        CompletionServiceImpl.setCompletionPhase(CompletionPhase.NoCompletion);
        return;
      }
    } else {
      CommandProcessor.getInstance().executeCommand(project, initCmd, null, null);
    }

    insertDummyIdentifier(initializationContext[0], hasModifiers, invocationCount);
  }
  @Override
  protected void invokeImpl(PsiClass targetClass) {
    final PsiFile callSite = myMethodCall.getContainingFile();
    final Project project = myMethodCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();

    try {
      PsiMethod constructor = elementFactory.createConstructor();
      constructor = (PsiMethod) targetClass.add(constructor);

      final TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
      CreateFromUsageUtils.setupMethodParameters(
          constructor,
          templateBuilder,
          myMethodCall.getArgumentList(),
          getTargetSubstitutor(myMethodCall));

      final PsiFile psiFile = myMethodCall.getContainingFile();

      templateBuilder.setEndVariableAfter(constructor.getBody().getLBrace());
      final RangeMarker rangeMarker =
          psiFile.getViewProvider().getDocument().createRangeMarker(myMethodCall.getTextRange());

      constructor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(constructor);

      targetClass = constructor.getContainingClass();
      myMethodCall =
          CodeInsightUtil.findElementInRange(
              psiFile,
              rangeMarker.getStartOffset(),
              rangeMarker.getEndOffset(),
              myMethodCall.getClass());
      rangeMarker.dispose();

      Template template = templateBuilder.buildTemplate();
      final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
      if (editor == null) return;
      final TextRange textRange = constructor.getTextRange();
      final PsiFile file = targetClass.getContainingFile();
      editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
      editor.getCaretModel().moveToOffset(textRange.getStartOffset());

      startTemplate(
          editor,
          template,
          project,
          new TemplateEditingAdapter() {
            @Override
            public void templateFinished(Template template, boolean brokenOff) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        @Override
                        public void run() {
                          try {
                            PsiDocumentManager.getInstance(project)
                                .commitDocument(editor.getDocument());
                            final int offset = editor.getCaretModel().getOffset();
                            PsiMethod constructor =
                                PsiTreeUtil.findElementOfClassAtOffset(
                                    file, offset, PsiMethod.class, false);
                            CreateFromUsageUtils.setupMethodBody(constructor);
                            CreateFromUsageUtils.setupEditor(constructor, editor);

                            UndoUtil.markPsiFileForUndo(callSite);
                          } catch (IncorrectOperationException e) {
                            LOG.error(e);
                          }
                        }
                      });
            }
          });
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
 @Override
 public void invoke(@NotNull Project project, Editor editor, PsiFile file)
     throws IncorrectOperationException {
   if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
   changeNewOperatorType(myExpression, myType, editor);
 }