public static void wrapLongLinesIfNecessary(@NotNull PsiFile file,
                                       @NotNull Document document,
                                       int startOffset,
                                       int endOffset,
                                       List<? extends TextRange> enabledRanges,
                                       int rightMargin) {
    final VirtualFile vFile = FileDocumentManager.getInstance().getFile(document);
    if ((vFile == null || vFile instanceof LightVirtualFile) && !ApplicationManager.getApplication().isUnitTestMode()) {
      // we assume that control flow reaches this place when the document is backed by a "virtual" file so any changes made by
      // a formatter affect only PSI and it is out of sync with a document text
      return;
    }

    Editor editor = PsiEditorUtil.findEditor(file);
    EditorFactory editorFactory = null;
    if (editor == null) {
      if (!ApplicationManager.getApplication().isDispatchThread()) {
        return;
      }
      editorFactory = EditorFactory.getInstance();
      editor = editorFactory.createEditor(document, file.getProject(), file.getVirtualFile(), false);
    }
    try {
      final Editor editorToUse = editor;
      ApplicationManager.getApplication().runWriteAction(() -> {
        final CaretModel caretModel = editorToUse.getCaretModel();
        final int caretOffset = caretModel.getOffset();
        final RangeMarker caretMarker = editorToUse.getDocument().createRangeMarker(caretOffset, caretOffset);
        doWrapLongLinesIfNecessary(editorToUse, file.getProject(), editorToUse.getDocument(), startOffset, endOffset, enabledRanges,
                                   rightMargin);
        if (caretMarker.isValid() && caretModel.getOffset() != caretMarker.getStartOffset()) {
          caretModel.moveToOffset(caretMarker.getStartOffset());
        }
      });
    }
    finally {
      PsiDocumentManager documentManager = PsiDocumentManager.getInstance(file.getProject());
      if (documentManager.isUncommited(document)) documentManager.commitDocument(document);
      if (editorFactory != null) {
        editorFactory.releaseEditor(editor);
      }
    }
  }
public static void wrapLongLinesIfNecessary(@NotNull PsiFile file,
                                       @NotNull Document document,
                                       int startOffset,
                                       int endOffset,
                                       List<? extends TextRange> enabledRanges,
                                       int rightMargin)