private static void commit(@NotNull PsiFile file) {
   PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
   Document document = manager.getDocument(file);
   if (document != null) {
     manager.commitDocument(document);
   }
 }
Esempio n. 2
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);
    }
  }
  private static void replaceByTagContent(Project project, XmlTag tagToReplace, XmlTag tagToInline)
      throws AndroidRefactoringErrorException {
    final ASTNode node = tagToInline.getNode();

    if (node == null) {
      throw new AndroidRefactoringErrorException();
    }
    final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(node);
    final ASTNode closingTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(node);

    if (startTagEnd == null || closingTagStart == null) {
      throw new AndroidRefactoringErrorException();
    }
    final int contentStart = startTagEnd.getTextRange().getEndOffset();
    final int contentEnd = closingTagStart.getTextRange().getStartOffset();

    if (contentStart < 0 || contentEnd < 0 || contentStart >= contentEnd) {
      throw new AndroidRefactoringErrorException();
    }
    final PsiFile file = tagToInline.getContainingFile();

    if (file == null) {
      throw new AndroidRefactoringErrorException();
    }
    final String textToInline = file.getText().substring(contentStart, contentEnd).trim();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = documentManager.getDocument(tagToReplace.getContainingFile());

    if (document == null) {
      throw new AndroidRefactoringErrorException();
    }
    final TextRange range = tagToReplace.getTextRange();
    document.replaceString(range.getStartOffset(), range.getEndOffset(), textToInline);
    documentManager.commitDocument(document);
  }
  @Override
  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor)
      throws IncorrectOperationException {
    final GrMethodCallExpression expression = (GrMethodCallExpression) element;
    final GrClosableBlock block = expression.getClosureArguments()[0];
    final GrParameterList parameterList = block.getParameterList();
    final GrParameter[] parameters = parameterList.getParameters();

    String var;
    if (parameters.length == 1) {
      var = parameters[0].getText();
      var = StringUtil.replace(var, GrModifier.DEF, "");
    } else {
      var = "it";
    }

    final GrExpression invokedExpression = expression.getInvokedExpression();
    GrExpression qualifier = ((GrReferenceExpression) invokedExpression).getQualifierExpression();
    final GroovyPsiElementFactory elementFactory =
        GroovyPsiElementFactory.getInstance(element.getProject());
    if (qualifier == null) {
      qualifier = elementFactory.createExpressionFromText("this");
    }

    StringBuilder builder = new StringBuilder();
    builder.append("for (").append(var).append(" in ").append(qualifier.getText()).append(") {\n");
    String text = block.getText();
    final PsiElement blockArrow = block.getArrow();
    int index;
    if (blockArrow != null) {
      index = blockArrow.getStartOffsetInParent() + blockArrow.getTextLength();
    } else {
      index = 1;
    }
    while (index < text.length() && Character.isWhitespace(text.charAt(index))) index++;
    text = text.substring(index, text.length() - 1);
    builder.append(text);
    builder.append("}");

    final GrStatement statement = elementFactory.createStatementFromText(builder.toString());
    GrForStatement forStatement = (GrForStatement) expression.replaceWithStatement(statement);
    final GrForClause clause = forStatement.getClause();
    GrVariable variable = clause.getDeclaredVariable();

    forStatement = updateReturnStatements(forStatement);

    if (variable == null) return;

    if (ApplicationManager.getApplication().isUnitTestMode()) return;

    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document doc = documentManager.getDocument(element.getContainingFile());
    if (doc == null) return;

    documentManager.doPostponedOperationsAndUnblockDocument(doc);
    editor.getCaretModel().moveToOffset(variable.getTextOffset());
    new VariableInplaceRenamer(variable, editor).performInplaceRename();
  }
 public void formatEveryoneAndCheckIfResultEqual(@NotNull final String... before) {
   assert before.length > 1;
   final PsiFile file = createFile("A.java", "");
   final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
   final Document document = manager.getDocument(file);
   String afterFirst = replaceAndProcessDocument(Action.REFORMAT, before[0], file, document);
   for (String nextBefore : before) {
     assertEquals(
         afterFirst, replaceAndProcessDocument(Action.REFORMAT, nextBefore, file, document));
   }
 }
 public void doTextTest(
     @NotNull final Action action, @NotNull String text, @NotNull String textAfter)
     throws IncorrectOperationException {
   final PsiFile file = createFile("A.java", text);
   final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject());
   final Document document = manager.getDocument(file);
   if (document == null) {
     fail("Document is null");
     return;
   }
   replaceAndProcessDocument(action, text, file, document);
   assertEquals(textAfter, document.getText());
   manager.commitDocument(document);
   assertEquals(textAfter, file.getText());
 }
  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();
  }
  // need to shorten references in type argument list
  public static void shortenReference(final PsiFile file, final int offset)
      throws IncorrectOperationException {
    Project project = file.getProject();
    final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
    Document document = manager.getDocument(file);
    if (document == null) {
      PsiUtilCore.ensureValid(file);
      LOG.error("No document for " + file);
      return;
    }

    manager.commitDocument(document);
    final PsiReference ref = file.findReferenceAt(offset);
    if (ref != null) {
      PsiElement element = ref.getElement();
      if (element != null) {
        JavaCodeStyleManager.getInstance(project).shortenClassReferences(element);
        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
      }
    }
  }
  @NotNull
  protected String doExtract(
      final PsiDirectory targetDirectory,
      final String targetfileName,
      final T first,
      final T last,
      final Language includingLanguage)
      throws IncorrectOperationException {
    final PsiFile file = targetDirectory.createFile(targetfileName);
    Project project = targetDirectory.getProject();
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    final Document document = documentManager.getDocument(file);
    document.replaceString(0, document.getTextLength(), first.getText().trim());
    documentManager.commitDocument(document);
    CodeStyleManager.getInstance(PsiManager.getInstance(project).getProject())
        .reformat(file); // TODO: adjustLineIndent

    final String relativePath =
        PsiFileSystemItemUtil.getRelativePath(first.getContainingFile(), file);
    if (relativePath == null) throw new IncorrectOperationException("Cannot extract!");
    return relativePath;
  }
  private boolean reportProblems(
      CompileContext context, Map<ProblemDescriptor, HighlightDisplayLevel> problemsMap) {
    if (problemsMap.isEmpty()) {
      return false;
    }

    boolean errorsReported = false;
    for (Map.Entry<ProblemDescriptor, HighlightDisplayLevel> entry : problemsMap.entrySet()) {
      ProblemDescriptor problemDescriptor = entry.getKey();
      final PsiElement element = problemDescriptor.getPsiElement();
      final PsiFile psiFile = element.getContainingFile();
      if (psiFile == null) continue;

      final VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;

      final CompilerMessageCategory category =
          myValidator.getCategoryByHighlightDisplayLevel(entry.getValue(), virtualFile, context);
      final Document document = myPsiDocumentManager.getDocument(psiFile);

      final int offset = problemDescriptor.getStartElement().getTextOffset();
      assert document != null;
      final int line = document.getLineNumber(offset);
      final int column = offset - document.getLineStartOffset(line);
      context.addMessage(
          category,
          problemDescriptor.getDescriptionTemplate(),
          virtualFile.getUrl(),
          line + 1,
          column + 1);
      if (CompilerMessageCategory.ERROR == category) {
        errorsReported = true;
      }
    }
    return errorsReported;
  }
  @Override
  @NotNull
  public List<TextEditorHighlightingPass> instantiatePasses(
      @NotNull final PsiFile psiFile,
      @NotNull final Editor editor,
      @NotNull final int[] passesToIgnore) {
    synchronized (this) {
      if (!checkedForCycles) {
        checkedForCycles = true;
        checkForCycles();
      }
    }
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    final Document document = editor.getDocument();
    PsiFile fileFromDoc = documentManager.getPsiFile(document);
    if (!(fileFromDoc instanceof PsiCompiledElement)) {
      assert fileFromDoc == psiFile : "Files are different: " + psiFile + ";" + fileFromDoc;
      Document documentFromFile = documentManager.getDocument(psiFile);
      assert documentFromFile == document
          : "Documents are different. Doc: "
              + document
              + "; Doc from file: "
              + documentFromFile
              + "; File: "
              + psiFile
              + "; Virtual file: "
              + PsiUtilCore.getVirtualFile(psiFile);
    }
    final TIntObjectHashMap<TextEditorHighlightingPass> id2Pass =
        new TIntObjectHashMap<TextEditorHighlightingPass>();
    final TIntArrayList passesRefusedToCreate = new TIntArrayList();
    myRegisteredPassFactories.forEachKey(
        new TIntProcedure() {
          @Override
          public boolean execute(int passId) {
            if (ArrayUtil.find(passesToIgnore, passId) != -1) {
              return true;
            }
            PassConfig passConfig = myRegisteredPassFactories.get(passId);
            TextEditorHighlightingPassFactory factory = passConfig.passFactory;
            final TextEditorHighlightingPass pass = factory.createHighlightingPass(psiFile, editor);

            if (pass == null) {
              passesRefusedToCreate.add(passId);
            } else {
              // init with editor's colors scheme
              pass.setColorsScheme(editor.getColorsScheme());

              TIntArrayList ids = new TIntArrayList(passConfig.completionPredecessorIds.length);
              for (int id : passConfig.completionPredecessorIds) {
                if (myRegisteredPassFactories.containsKey(id)) ids.add(id);
              }
              pass.setCompletionPredecessorIds(
                  ids.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : ids.toNativeArray());
              ids = new TIntArrayList(passConfig.startingPredecessorIds.length);
              for (int id : passConfig.startingPredecessorIds) {
                if (myRegisteredPassFactories.containsKey(id)) ids.add(id);
              }
              pass.setStartingPredecessorIds(
                  ids.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : ids.toNativeArray());
              pass.setId(passId);
              id2Pass.put(passId, pass);
            }
            return true;
          }
        });

    DaemonCodeAnalyzerEx daemonCodeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject);
    final FileStatusMap statusMap = daemonCodeAnalyzer.getFileStatusMap();
    passesRefusedToCreate.forEach(
        new TIntProcedure() {
          @Override
          public boolean execute(int passId) {
            statusMap.markFileUpToDate(document, passId);
            return true;
          }
        });

    return (List) Arrays.asList(id2Pass.getValues());
  }