@Nullable
    private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings)
        throws IncorrectOperationException {
      myDocument.insertString(myOffset, buffer);

      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      CodeStyleManager.getInstance(getProject())
          .adjustLineIndent(myFile, myOffset + buffer.length() - 2);

      PsiComment comment =
          PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);

      comment = createJavaDocStub(settings, comment, getProject());
      if (comment == null) {
        return null;
      }

      CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
      CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject());
      boolean old = codeStyleSettings.ENABLE_JAVADOC_FORMATTING;
      codeStyleSettings.ENABLE_JAVADOC_FORMATTING = false;

      try {
        comment = (PsiComment) codeStyleManager.reformat(comment);
      } finally {
        codeStyleSettings.ENABLE_JAVADOC_FORMATTING = old;
      }
      PsiElement next = comment.getNextSibling();
      if (next == null && comment.getParent().getClass() == comment.getClass()) {
        next =
            comment
                .getParent()
                .getNextSibling(); // expanding chameleon comment produces comment under comment
      }
      if (next != null) {
        next =
            myFile.findElementAt(
                next.getTextRange().getStartOffset()); // maybe switch to another tree
      }
      if (next != null
          && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode())
              || !next.getText().contains(LINE_SEPARATOR))) {
        int lineBreakOffset = comment.getTextRange().getEndOffset();
        myDocument.insertString(lineBreakOffset, LINE_SEPARATOR);
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1);
        comment =
            PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
      }
      return comment;
    }
示例#2
0
 protected static void replaceExpressionWithNegatedExpression(
     @NotNull PsiExpression newExpression, @NotNull PsiExpression expression) {
   final Project project = expression.getProject();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   PsiExpression expressionToReplace = expression;
   final String newExpressionText = newExpression.getText();
   final String expString;
   if (BoolUtils.isNegated(expression)) {
     expressionToReplace = BoolUtils.findNegation(expression);
     expString = newExpressionText;
   } else if (ComparisonUtils.isComparison(newExpression)) {
     final PsiBinaryExpression binaryExpression = (PsiBinaryExpression) newExpression;
     final String negatedComparison =
         ComparisonUtils.getNegatedComparison(binaryExpression.getOperationTokenType());
     final PsiExpression lhs = binaryExpression.getLOperand();
     final PsiExpression rhs = binaryExpression.getROperand();
     assert rhs != null;
     expString = lhs.getText() + negatedComparison + rhs.getText();
   } else {
     if (ParenthesesUtils.getPrecedence(newExpression) > ParenthesesUtils.PREFIX_PRECEDENCE) {
       expString = "!(" + newExpressionText + ')';
     } else {
       expString = '!' + newExpressionText;
     }
   }
   final PsiExpression newCall = factory.createExpressionFromText(expString, expression);
   assert expressionToReplace != null;
   final PsiElement insertedElement = expressionToReplace.replace(newCall);
   final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
   codeStyleManager.reformat(insertedElement);
 }
  private static boolean generateDelegate(GrChangeInfoImpl grInfo) {
    final GrMethod method = grInfo.getMethod();
    final PsiClass psiClass = method.getContainingClass();
    GrMethod newMethod = (GrMethod) method.copy();
    newMethod = (GrMethod) psiClass.addAfter(newMethod, method);
    StringBuilder buffer = new StringBuilder();
    buffer.append("\n");
    if (method.isConstructor()) {
      buffer.append("this");
    } else {
      if (!PsiType.VOID.equals(method.getReturnType())) {
        buffer.append("return ");
      }
      buffer.append(
          GrChangeSignatureUtil.getNameWithQuotesIfNeeded(
              grInfo.getNewName(), method.getProject()));
    }

    generateParametersForDelegateCall(grInfo, method, buffer);

    final GrCodeBlock codeBlock =
        GroovyPsiElementFactory.getInstance(method.getProject())
            .createMethodBodyFromText(buffer.toString());
    newMethod.setBlock(codeBlock);
    newMethod.getModifierList().setModifierProperty(PsiModifier.ABSTRACT, false);

    CodeStyleManager.getInstance(method.getProject()).reformat(newMethod);
    return processPrimaryMethodInner(grInfo, method, null);
  }
  public PsiElement createFromTemplate(
      final Project project,
      final PsiDirectory directory,
      String fileName,
      final FileTemplate template,
      final String templateText,
      final Properties props)
      throws IncorrectOperationException {
    fileName = checkAppendExtension(fileName, template);

    if (FileTypeManager.getInstance().isFileIgnored(fileName)) {
      throw new IncorrectOperationException(
          "This filename is ignored (Settings | File Types | Ignore files and folders)");
    }

    directory.checkCreateFile(fileName);
    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, templateText);

    if (template.isReformatCode()) {
      CodeStyleManager.getInstance(project).reformat(file);
    }

    file = (PsiFile) directory.add(file);
    return file;
  }
 private static void addDefaultConstructor(
     JavaChangeInfo changeInfo, PsiClass aClass, final UsageInfo[] usages)
     throws IncorrectOperationException {
   if (!(aClass instanceof PsiAnonymousClass)) {
     PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject());
     PsiMethod defaultConstructor =
         factory.createMethodFromText(aClass.getName() + "(){}", aClass);
     defaultConstructor =
         (PsiMethod)
             CodeStyleManager.getInstance(aClass.getProject()).reformat(defaultConstructor);
     defaultConstructor = (PsiMethod) aClass.add(defaultConstructor);
     PsiUtil.setModifierProperty(
         defaultConstructor, VisibilityUtil.getVisibilityModifier(aClass.getModifierList()), true);
     addSuperCall(changeInfo, defaultConstructor, null, usages);
   } else {
     final PsiElement parent = aClass.getParent();
     if (parent instanceof PsiNewExpression) {
       final PsiExpressionList argumentList = ((PsiNewExpression) parent).getArgumentList();
       final PsiClass baseClass = changeInfo.getMethod().getContainingClass();
       final PsiSubstitutor substitutor =
           TypeConversionUtil.getSuperClassSubstitutor(baseClass, aClass, PsiSubstitutor.EMPTY);
       fixActualArgumentsList(argumentList, changeInfo, true, substitutor);
     }
   }
 }
  @NotNull
  @Override
  public PsiField createField(@NotNull final String name, @NotNull final PsiType type)
      throws IncorrectOperationException {
    PsiUtil.checkIsIdentifier(myManager, name);
    if (PsiType.NULL.equals(type)) {
      throw new IncorrectOperationException("Cannot create field with type \"null\".");
    }

    @NonNls
    final String text = "class _Dummy_ { private " + type.getCanonicalText() + " " + name + "; }";
    final PsiJavaFile aFile = createDummyJavaFile(text);
    final PsiClass[] classes = aFile.getClasses();
    if (classes.length < 1) {
      throw new IncorrectOperationException("Class was not created " + text);
    }
    final PsiClass psiClass = classes[0];
    final PsiField[] fields = psiClass.getFields();
    if (fields.length < 1) {
      throw new IncorrectOperationException("Field was not created " + text);
    }
    PsiField field = fields[0];
    field =
        (PsiField)
            JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(field);
    return (PsiField) CodeStyleManager.getInstance(myManager.getProject()).reformat(field);
  }
示例#7
0
 protected static void addStatementBefore(String newStatementText, PsiReturnStatement anchor) {
   final Project project = anchor.getProject();
   final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   final PsiStatement newStatement = factory.createStatementFromText(newStatementText, anchor);
   final PsiElement addedStatement = anchor.getParent().addBefore(newStatement, anchor);
   CodeStyleManager.getInstance(project).reformat(addedStatement);
 }
  @NotNull
  @Override
  public PsiCatchSection createCatchSection(
      @NotNull final PsiType exceptionType,
      @NotNull final String exceptionName,
      @Nullable final PsiElement context)
      throws IncorrectOperationException {
    if (!(exceptionType instanceof PsiClassType || exceptionType instanceof PsiDisjunctionType)) {
      throw new IncorrectOperationException("Unexpected type:" + exceptionType);
    }

    @NonNls
    final String text = "catch (" + exceptionType.getCanonicalText() + " " + exceptionName + ") {}";
    final DummyHolder holder =
        DummyHolderFactory.createHolder(
            myManager, new JavaDummyElement(text, CATCH_SECTION, level(context)), context);
    final PsiElement element =
        SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode());
    if (!(element instanceof PsiCatchSection)) {
      throw new IncorrectOperationException(
          "Incorrect catch section '" + text + "'. Parsed element: " + element);
    }

    final Project project = myManager.getProject();
    final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(project);
    helper.setupCatchBlock(exceptionName, exceptionType, context, (PsiCatchSection) element);
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    final PsiCatchSection catchSection = (PsiCatchSection) styleManager.reformat(element);

    GeneratedMarkerVisitor.markGenerated(catchSection);
    return catchSection;
  }
  @NotNull
  @Override
  public PsiMethod createMethod(@NotNull final String name, final PsiType returnType)
      throws IncorrectOperationException {
    PsiUtil.checkIsIdentifier(myManager, name);
    if (PsiType.NULL.equals(returnType)) {
      throw new IncorrectOperationException("Cannot create method with type \"null\".");
    }

    final String canonicalText = returnType.getCanonicalText();
    final PsiJavaFile aFile =
        createDummyJavaFile("class _Dummy_ { public " + canonicalText + " " + name + "() {} }");
    final PsiClass[] classes = aFile.getClasses();
    if (classes.length < 1) {
      throw new IncorrectOperationException(
          "Class was not created. Method name: " + name + "; return type: " + canonicalText);
    }
    final PsiMethod[] methods = classes[0].getMethods();
    if (methods.length < 1) {
      throw new IncorrectOperationException(
          "Method was not created. Method name: " + name + "; return type: " + canonicalText);
    }
    PsiMethod method = methods[0];
    method =
        (PsiMethod)
            JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(method);
    return (PsiMethod) CodeStyleManager.getInstance(myManager.getProject()).reformat(method);
  }
  @Override
  @NotNull
  protected FutureTask<Boolean> prepareTask(
      @NotNull final PsiFile file, final boolean processChangedTextOnly)
      throws IncorrectOperationException {
    return new FutureTask<>(
        () -> {
          FormattingProgressTask.FORMATTING_CANCELLED_FLAG.set(false);
          try {
            CharSequence before = null;
            Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
            if (getInfoCollector() != null) {
              LOG.assertTrue(document != null);
              before = document.getImmutableCharSequence();
            }

            CaretVisualPositionKeeper caretPositionKeeper = new CaretVisualPositionKeeper(document);

            if (processChangedTextOnly) {
              ChangedRangesInfo info =
                  FormatChangedTextUtil.getInstance().getChangedRangesInfo(file);
              if (info != null) {
                CodeStyleManager.getInstance(myProject).reformatTextWithContext(file, info);
              }
            } else {
              Collection<TextRange> ranges = getRangesToFormat(file);
              CodeStyleManager.getInstance(myProject).reformatText(file, ranges);
            }

            caretPositionKeeper.restoreOriginalLocation();

            if (before != null) {
              prepareUserNotificationMessage(document, before);
            }

            return !FormattingProgressTask.FORMATTING_CANCELLED_FLAG.get();
          } catch (FilesTooBigForDiffException e) {
            handleFileTooBigException(LOG, e, file);
            return false;
          } catch (IncorrectOperationException e) {
            LOG.error(e);
            return false;
          } finally {
            myRanges.clear();
          }
        });
  }
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
 @NotNull
 @Override
 public PsiClassInitializer createClassInitializer() throws IncorrectOperationException {
   final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { {} }");
   final PsiClassInitializer classInitializer = aFile.getClasses()[0].getInitializers()[0];
   return (PsiClassInitializer)
       CodeStyleManager.getInstance(myManager.getProject()).reformat(classInitializer);
 }
 @NotNull
 @Override
 public PsiMethod createConstructor(@NotNull @NonNls final String name) {
   final PsiJavaFile aFile =
       createDummyJavaFile("class " + name + " { public " + name + "() {} }");
   final PsiMethod method = aFile.getClasses()[0].getMethods()[0];
   return (PsiMethod) CodeStyleManager.getInstance(myManager.getProject()).reformat(method);
 }
  public void commentRange(
      int startOffset,
      int endOffset,
      String commentPrefix,
      String commentSuffix,
      Commenter commenter) {
    final CharSequence chars = myDocument.getCharsSequence();
    LogicalPosition caretPosition = myCaret.getLogicalPosition();

    if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
      if (endOffset == myDocument.getTextLength()
          || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        CommonCodeStyleSettings settings =
            CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
        String space;
        if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
          final FileType fileType = myFile.getFileType();
          int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
          int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
          Indent minIndent =
              CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
          if (minIndent == null) {
            minIndent = codeStyleManager.zeroIndent();
          }
          space = codeStyleManager.fillIndent(minIndent, fileType);
        } else {
          space = "";
        }
        final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
        if (!commentPrefix.endsWith("\n")) {
          nestingPrefix.append("\n");
        }
        final StringBuilder nestingSuffix = new StringBuilder(space);
        nestingSuffix.append(
            commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
        nestingSuffix.append("\n");
        TextRange range =
            insertNestedComments(
                startOffset,
                endOffset,
                nestingPrefix.toString(),
                nestingSuffix.toString(),
                commenter);
        myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
        LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
        myCaret.moveToLogicalPosition(pos);
        return;
      }
    }

    TextRange range =
        insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
    myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
    LogicalPosition pos =
        new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
    myCaret.moveToLogicalPosition(pos);
  }
示例#15
0
  private static PsiMethod reformat(Project project, PsiMethod result)
      throws IncorrectOperationException {
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    result = (PsiMethod) codeStyleManager.reformat(result);

    JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    result = (PsiMethod) javaCodeStyleManager.shortenClassReferences(result);
    return result;
  }
示例#16
0
  public static PsiMethod generateSetterPrototype(
      PsiField field, final PsiClass containingClass, boolean returnSelf) {
    Project project = field.getProject();
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory();

    String name = field.getName();
    boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
    VariableKind kind = codeStyleManager.getVariableKind(field);
    String propertyName = codeStyleManager.variableNameToPropertyName(name, kind);
    String setName = suggestSetterName(project, field);
    try {
      PsiMethod setMethod =
          factory.createMethod(
              setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID);
      String parameterName =
          codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
      PsiParameter param = factory.createParameter(parameterName, field.getType());

      annotateWithNullableStuff(field, factory, param);

      setMethod.getParameterList().add(param);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true);
      PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic);

      @NonNls StringBuffer buffer = new StringBuffer();
      buffer.append("{\n");
      if (name.equals(parameterName)) {
        if (!isStatic) {
          buffer.append("this.");
        } else {
          String className = containingClass.getName();
          if (className != null) {
            buffer.append(className);
            buffer.append(".");
          }
        }
      }
      buffer.append(name);
      buffer.append("=");
      buffer.append(parameterName);
      buffer.append(";\n");
      if (returnSelf) {
        buffer.append("return this;\n");
      }
      buffer.append("}");
      PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null);
      setMethod.getBody().replace(body);
      setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod);
      return setMethod;
    } catch (IncorrectOperationException e) {
      LOG.error(e);
      return null;
    }
  }
  @Override
  public void handleInsert(InsertionContext context) {
    final Document document = context.getEditor().getDocument();
    document.replaceString(context.getStartOffset(), context.getTailOffset(), ";");
    final InsertionContext qualifierContext =
        CompletionUtil.emulateInsertion(context, context.getStartOffset(), myQualifier);
    OffsetKey oldStart = context.trackOffset(context.getStartOffset(), false);

    int start =
        CharArrayUtil.shiftForward(
            context.getDocument().getCharsSequence(), context.getStartOffset(), " \t\n");
    if (shouldParenthesizeQualifier(context.getFile(), start, qualifierContext.getTailOffset())) {
      final String space =
          CodeStyleSettingsManager.getSettings(qualifierContext.getProject())
                  .SPACE_WITHIN_PARENTHESES
              ? " "
              : "";
      document.insertString(start, "(" + space);
      document.insertString(qualifierContext.getTailOffset(), space + ")");
    }

    final char atTail = document.getCharsSequence().charAt(context.getTailOffset() - 1);
    if (atTail != ';') {
      LOG.error(
          LogMessageEx.createEvent(
              "Unexpected character",
              "atTail="
                  + atTail
                  + "\n"
                  + "offset="
                  + context.getTailOffset()
                  + "\n"
                  + "item="
                  + this
                  + "\n"
                  + "item.class="
                  + this.getClass()
                  + "\n"
                  + DebugUtil.currentStackTrace(),
              AttachmentFactory.createAttachment(context.getDocument())));
    }
    document.replaceString(context.getTailOffset() - 1, context.getTailOffset(), ".");

    CompletionUtil.emulateInsertion(getDelegate(), context.getTailOffset(), context);
    context.commitDocument();

    int formatStart = context.getOffset(oldStart);
    int formatEnd = context.getTailOffset();
    if (formatStart >= 0 && formatEnd >= 0) {
      CodeStyleManager.getInstance(context.getProject())
          .reformatText(context.getFile(), formatStart, formatEnd);
    }
  }
  private static void assertAfterCommit(
      Document document,
      final PsiFile file,
      String oldPsiText,
      FileElement myTreeElementBeingReparsedSoItWontBeCollected) {
    if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) {
      final String documentText = document.getText();
      if (ApplicationManagerEx.getApplicationEx().isInternal()) {
        String fileText = file.getText();
        LOG.error(
            "commitDocument left PSI inconsistent; file len="
                + myTreeElementBeingReparsedSoItWontBeCollected.getTextLength()
                + "; doc len="
                + document.getTextLength()
                + "; doc.getText() == file.getText(): "
                + Comparing.equal(fileText, documentText)
                + ";\n file psi text="
                + fileText
                + ";\n doc text="
                + documentText
                + ";\n old psi file text="
                + oldPsiText);
      } else {
        LOG.error("commitDocument left PSI inconsistent: " + file);
      }

      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
      try {
        BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
        final DiffLog diffLog =
            blockSupport.reparseRange(
                file, 0, documentText.length(), 0, documentText, new ProgressIndicatorBase());
        CodeStyleManager.getInstance(file.getProject())
            .performActionWithFormatterDisabled(
                new Runnable() {
                  @Override
                  public void run() {
                    synchronized (PsiLock.LOCK) {
                      doActualPsiChange(file, diffLog);
                    }
                  }
                });

        if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength()
            != document.getTextLength()) {
          LOG.error("PSI is broken beyond repair in: " + file);
        }
      } finally {
        file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
      }
    }
  }
 private static PsiStatement createAssignment(
     PsiLocalVariable local, String fieldname, PsiElementFactory factory) {
   try {
     PsiAssignmentExpression assignmentExpression =
         GosuPsiParseUtil.createAssignmentStatement(
             local.getProject(), fieldname, local.getInitializer());
     return (PsiStatement)
         CodeStyleManager.getInstance(local.getProject()).reformat(assignmentExpression);
   } catch (IncorrectOperationException e) {
     LOG.error(e);
     return null;
   }
 }
  private static void processMethod(
      @NotNull Project project,
      @NotNull PsiMethod targetMethod,
      @NotNull Set<PsiClassType> unhandledExceptions)
      throws IncorrectOperationException {
    for (PsiClassType unhandledException : unhandledExceptions) {
      PsiClass exceptionClass = unhandledException.resolve();
      if (exceptionClass != null) {
        PsiUtil.addException(targetMethod, exceptionClass);
      }
    }

    CodeStyleManager.getInstance(project).reformat(targetMethod.getThrowsList());
  }
 @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) {
   PsiReferenceExpression place = (PsiReferenceExpression) startElement;
   String qualifier = null;
   final PsiExpression qualifierExpression = place.getQualifierExpression();
   if (qualifierExpression != null) {
     qualifier = qualifierExpression.getText();
   }
   PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
   PsiMethodCallExpression callExpression;
   final String call = (qualifier != null ? qualifier + "." : "") + myMethodName;
   if (!myIsSetter) {
     callExpression =
         (PsiMethodCallExpression) elementFactory.createExpressionFromText(call + "()", null);
     callExpression =
         (PsiMethodCallExpression) CodeStyleManager.getInstance(project).reformat(callExpression);
     place.replace(callExpression);
   } else {
     PsiElement parent = PsiTreeUtil.skipParentsOfType(place, PsiParenthesizedExpression.class);
     if (parent instanceof PsiAssignmentExpression) {
       final PsiExpression rExpression = ((PsiAssignmentExpression) parent).getRExpression();
       final String argList = rExpression != null ? rExpression.getText() : "";
       callExpression =
           (PsiMethodCallExpression)
               elementFactory.createExpressionFromText(call + "(" + argList + ")", null);
       callExpression =
           (PsiMethodCallExpression)
               CodeStyleManager.getInstance(project).reformat(callExpression);
       parent.replace(callExpression);
     }
   }
 }
 public void run() {
   int lineStart = myDocument.getLineStartOffset(myLine);
   CommandProcessor.getInstance()
       .executeCommand(
           myProject,
           () ->
               ApplicationManager.getApplication()
                   .runWriteAction(
                       () -> {
                         CodeStyleManager.getInstance(myProject)
                             .adjustLineIndent(myDocument, lineStart);
                       }),
           ADJUST_INDENT_COMMAND_NAME,
           null);
 }
  @NotNull
  @Override
  public PsiImportStatement createImportStatement(@NotNull final PsiClass aClass)
      throws IncorrectOperationException {
    if (aClass instanceof PsiAnonymousClass) {
      throw new IncorrectOperationException("Cannot create import statement for anonymous class.");
    } else if (aClass.getParent() instanceof PsiDeclarationStatement) {
      throw new IncorrectOperationException("Cannot create import statement for local class.");
    }

    final PsiJavaFile aFile = createDummyJavaFile("import " + aClass.getQualifiedName() + ";");
    final PsiImportStatementBase statement = extractImport(aFile, false);
    return (PsiImportStatement)
        CodeStyleManager.getInstance(myManager.getProject()).reformat(statement);
  }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   PsiElement element = descriptor.getStartElement();
   if (!(element instanceof PsiLoopStatement)) return;
   PsiLoopStatement loop = (PsiLoopStatement) element;
   IteratorDeclaration declaration;
   declaration = IteratorDeclaration.fromLoop(loop);
   if (declaration == null) return;
   PsiStatement body = loop.getBody();
   if (!(body instanceof PsiBlockStatement)) return;
   PsiStatement[] statements = ((PsiBlockStatement) body).getCodeBlock().getStatements();
   PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
   String replacement = null;
   CommentTracker ct = new CommentTracker();
   if (statements.length == 2 && statements[1] instanceof PsiIfStatement) {
     PsiVariable variable = declaration.getNextElementVariable(statements[0]);
     if (variable == null) return;
     PsiExpression condition = ((PsiIfStatement) statements[1]).getCondition();
     if (condition == null) return;
     replacement = generateRemoveIf(declaration, ct, condition, variable.getName());
   } else if (statements.length == 1 && statements[0] instanceof PsiIfStatement) {
     PsiExpression condition = ((PsiIfStatement) statements[0]).getCondition();
     if (condition == null) return;
     PsiElement ref = declaration.findOnlyIteratorRef(condition);
     if (ref != null) {
       PsiElement call = ref.getParent().getParent();
       if (!declaration.isIteratorMethodCall(call, "next")) return;
       PsiType type = ((PsiExpression) call).getType();
       JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
       SuggestedNameInfo info =
           javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type);
       if (info.names.length == 0) {
         info =
             javaCodeStyleManager.suggestVariableName(
                 VariableKind.PARAMETER, "value", null, type);
       }
       String paramName =
           javaCodeStyleManager.suggestUniqueVariableName(info, condition, true).names[0];
       ct.replace(call, factory.createIdentifier(paramName));
       replacement = generateRemoveIf(declaration, ct, condition, paramName);
     }
   }
   if (replacement == null) return;
   ct.delete(declaration.getIterator());
   PsiElement result = ct.replaceAndRestoreComments(loop, replacement);
   LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result);
   CodeStyleManager.getInstance(project).reformat(result);
 }
  @NotNull
  @Override
  public PsiImportStatement createImportStatementOnDemand(@NotNull final String packageName)
      throws IncorrectOperationException {
    if (packageName.isEmpty()) {
      throw new IncorrectOperationException("Cannot create import statement for default package.");
    }
    if (!PsiNameHelper.getInstance(myManager.getProject()).isQualifiedName(packageName)) {
      throw new IncorrectOperationException("Incorrect package name: \"" + packageName + "\".");
    }

    final PsiJavaFile aFile = createDummyJavaFile("import " + packageName + ".*;");
    final PsiImportStatementBase statement = extractImport(aFile, false);
    return (PsiImportStatement)
        CodeStyleManager.getInstance(myManager.getProject()).reformat(statement);
  }
  @NotNull
  public static PsiElement createBundleFile(
      @NotNull PhpClass bundleClass,
      @NotNull String template,
      @NotNull String className,
      Map<String, String> vars)
      throws Exception {

    VirtualFile directory =
        bundleClass.getContainingFile().getContainingDirectory().getVirtualFile();
    if (fileExists(directory, new String[] {className})) {
      throw new Exception("File already exists");
    }

    String COMPILER_TEMPLATE = "/resources/fileTemplates/" + template + ".php";
    String fileTemplateContent = getFileTemplateContent(COMPILER_TEMPLATE);
    if (fileTemplateContent == null) {
      throw new Exception("Template content error");
    }

    String[] split = className.split("\\\\");

    String ns = bundleClass.getNamespaceName();
    String join = StringUtils.join(Arrays.copyOf(split, split.length - 1), "/");

    vars.put("ns", (ns.startsWith("\\") ? ns.substring(1) : ns) + join.replace("/", "\\"));
    vars.put("class", split[split.length - 1]);
    for (Map.Entry<String, String> entry : vars.entrySet()) {
      fileTemplateContent =
          fileTemplateContent.replace("{{ " + entry.getKey() + " }}", entry.getValue());
    }

    VirtualFile compilerDirectory = getAndCreateDirectory(directory, join);
    if (compilerDirectory == null) {
      throw new Exception("Directory creation failed");
    }

    Project project = bundleClass.getProject();
    PsiFile fileFromText =
        PsiFileFactory.getInstance(project)
            .createFileFromText(
                split[split.length - 1] + ".php", PhpFileType.INSTANCE, fileTemplateContent);
    CodeStyleManager.getInstance(project).reformat(fileFromText);
    return PsiDirectoryFactory.getInstance(project)
        .createDirectory(compilerDirectory)
        .add(fileFromText);
  }
  @Override
  public TextRange surroundStatements(
      Project project, Editor editor, PsiElement container, PsiElement[] statements)
      throws IncorrectOperationException {
    PsiManager manager = PsiManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);

    statements = SurroundWithUtil.moveDeclarationsOut(container, statements, false);
    if (statements.length == 0) {
      return null;
    }

    @NonNls String text = "try{\n}finally{\n\n}";
    PsiTryStatement tryStatement = (PsiTryStatement) factory.createStatementFromText(text, null);
    tryStatement = (PsiTryStatement) codeStyleManager.reformat(tryStatement);

    tryStatement =
        (PsiTryStatement) container.addAfter(tryStatement, statements[statements.length - 1]);

    PsiCodeBlock tryBlock = tryStatement.getTryBlock();
    if (tryBlock == null) {
      return null;
    }
    SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements);
    tryBlock.addRange(statements[0], statements[statements.length - 1]);
    container.deleteChildRange(statements[0], statements[statements.length - 1]);

    PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
    if (finallyBlock == null) {
      return null;
    }
    int offset = finallyBlock.getTextRange().getStartOffset() + 2;
    editor.getCaretModel().moveToOffset(offset);
    final Document document = editor.getDocument();
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
    editor.getSelectionModel().removeSelection();
    final PsiStatement firstTryStmt = tryBlock.getStatements()[0];
    final int indent =
        firstTryStmt.getTextOffset()
            - document.getLineStartOffset(document.getLineNumber(firstTryStmt.getTextOffset()));
    EditorModificationUtil.insertStringAtCaret(editor, StringUtil.repeat(" ", indent), false, true);
    return new TextRange(editor.getCaretModel().getOffset(), editor.getCaretModel().getOffset());
  }
  private void buildDelegate() {
    final PsiManager manager = sourceClass.getManager();
    final PsiElementFactory factory =
        JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    @NonNls final StringBuilder fieldBuffer = new StringBuilder();
    final String delegateVisibility = calculateDelegateVisibility();
    if (delegateVisibility.length() > 0) fieldBuffer.append(delegateVisibility).append(' ');
    fieldBuffer.append("final ");
    final String fullyQualifiedName = getQualifiedName();
    fieldBuffer.append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append(' ');
    fieldBuffer.append(delegateFieldName);
    fieldBuffer.append(" = new ").append(fullyQualifiedName);
    if (!typeParams.isEmpty()) {
      fieldBuffer.append('<');
      for (PsiTypeParameter typeParameter : typeParams) {
        fieldBuffer.append(typeParameter.getName());
      }
      fieldBuffer.append('>');
    }
    fieldBuffer.append('(');
    if (requiresBackpointer) {
      fieldBuffer.append("this");
    }

    fieldBuffer.append(");");
    try {
      final String fieldString = fieldBuffer.toString();
      final PsiField field = factory.createFieldFromText(fieldString, sourceClass);
      final PsiElement newField = sourceClass.add(field);
      codeStyleManager.reformat(
          JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(newField));
    } catch (IncorrectOperationException e) {
      logger.error(e);
    }
  }
  protected void changeInternalUsage(InternalUsageInfo usage, PsiElementFactory factory)
      throws IncorrectOperationException {
    if (!mySettings.isChangeSignature()) return;

    PsiElement element = usage.getElement();

    if (element instanceof PsiReferenceExpression) {
      PsiReferenceExpression newRef = null;

      if (mySettings.isMakeFieldParameters()) {
        PsiElement resolved = ((PsiReferenceExpression) element).resolve();
        if (resolved instanceof PsiField) {
          String name = mySettings.getNameForField((PsiField) resolved);
          if (name != null) {
            newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null);
          }
        }
      }

      if (newRef == null && mySettings.isMakeClassParameter()) {
        newRef =
            (PsiReferenceExpression)
                factory.createExpressionFromText(
                    mySettings.getClassParameterName() + "." + element.getText(), null);
      }

      if (newRef != null) {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        newRef = (PsiReferenceExpression) codeStyleManager.reformat(newRef);
        element.replace(newRef);
      }
    } else if (element instanceof PsiThisExpression && mySettings.isMakeClassParameter()) {
      element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null));
    } else if (element instanceof PsiSuperExpression && mySettings.isMakeClassParameter()) {
      element.replace(factory.createExpressionFromText(mySettings.getClassParameterName(), null));
    } else if (element instanceof PsiNewExpression && mySettings.isMakeClassParameter()) {
      final PsiNewExpression newExpression = ((PsiNewExpression) element);
      LOG.assertTrue(newExpression.getQualifier() == null);
      final String newText = mySettings.getClassParameterName() + "." + newExpression.getText();
      final PsiExpression expr = factory.createExpressionFromText(newText, null);
      element.replace(expr);
    }
  }
  private static void indentLinesIn(
      final Editor editor,
      final PsiFile file,
      final Document document,
      final Project project,
      RangeMarker range) {
    final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
    int line1 = editor.offsetToLogicalPosition(range.getStartOffset()).line;
    int line2 = editor.offsetToLogicalPosition(range.getEndOffset()).line;

    while (!lineContainsNonSpaces(document, line1) && line1 < line2) line1++;
    while (!lineContainsNonSpaces(document, line2) && line1 < line2) line2--;

    final FileViewProvider provider = file.getViewProvider();
    PsiFile rootToAdjustIndentIn = provider.getPsi(provider.getBaseLanguage());
    codeStyleManager.adjustLineIndent(
        rootToAdjustIndentIn,
        new TextRange(document.getLineStartOffset(line1), document.getLineStartOffset(line2)));
  }