private void replaceText(@NotNull Project project, boolean collectChanges) {
    ApplicationManager.getApplication().runWriteAction(() -> {
      try {
        Document beforeReformat = null;
        if (collectChanges && myEditor.getDocument().getTextLength() > 0) {
          beforeReformat = collectChangesBeforeCurrentSettingsAppliance(project);
        }

        //important not mark as generated not to get the classes before setting language level
        PsiFile psiFile = createFileFromText(project, myTextToReformat);
        prepareForReformat(psiFile);

        Document document = myEditor.getDocument();
        AbstractDocumentFormattingService.setDocument(psiFile, document);

        applySettingsToModel();
        final Ref<PsiFile> formatted = Ref.create();
        CodeStyle.runWithLocalSettings(
          project,
          mySettings,
          settings -> {
            settings.setRightMargin(getDefaultLanguage(), getAdjustedRightMargin());
            myEditor.getSettings().setTabSize(settings.getTabSize(getFileType()));
            formatted.set(doReformat(project, psiFile));
          });
        document.replaceString(0, document.getTextLength(), formatted.get().getText());
        DocumentReference docRef = DocumentReferenceManager.getInstance().create(document);
        UndoManager.getInstance(project).nonundoableActionPerformed(docRef, false);
        if (beforeReformat != null) {
          highlightChanges(beforeReformat);
        }
      }
      catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    });
  }
private void replaceText(@NotNull Project project, boolean collectChanges)